content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
from pathlib import Path
def get_cache_dir() -> Path:
"""
Returns a cache dir that can be used as a local buffer.
Example use cases are intermediate results and downloaded files.
At the moment this will be a folder that lies in the root of this package.
Reason for this location and against `~/.cache/paderbox` are:
- This repo may lie on an faster filesystem.
- The user has limited space in the home directory.
- You may install paderbox multiple times and do not want to get side
effects.
- When you delete this repo, also the cache is deleted.
Returns:
Path to a cache dir
>>> get_cache_dir() # doctest: +SKIP
PosixPath('.../paderbox/cache')
"""
dirname = Path(__file__).resolve().absolute().parents[2]
path = dirname / "cache"
if not path.exists():
path.mkdir()
return path
|
6f8655b9d8a145e7c018293456ac88546c78a34d
| 41,747 |
def represents_int(string: str):
"""Checks if a `string can be turned into an integer
Args:
string (str): String to test
Returns:
bool
"""
try:
int(string)
return True
except ValueError:
return False
|
bc5cfb39e3b89309a7d29608d9bafb28ae67cd18
| 41,754 |
def parse_brackets(line: str) -> tuple[int, str]:
"""
Returns the index at which closing brackets don't align anymore,
or if all closing ones do match, the string needed to complete it.
"""
stack: list[str] = []
opening_map = {
")": "(",
"]": "[",
"}": "{",
">": "<",
}
for index, bracket in enumerate(line):
if bracket in "([{<":
stack.append(bracket)
continue
opening_bracket = opening_map[bracket]
if stack.pop() != opening_bracket:
return index, ""
# Now, there's stuff left on the stack. Which means, we need more
# closing brackets here, for part 2. Disregard the integer.
closing_map = {value: key for key, value in opening_map.items()}
autocomplete = ""
while len(stack) > 0:
bracket = stack.pop()
autocomplete += closing_map[bracket]
return -1, autocomplete
|
3df3bc7bf6d1513b3d387023485949645b19e81c
| 41,755 |
def client_error(message, http_status_code=400):
"""
Simple util function to return an error in a consistent format to the calling
system (API Gateway in this case.
:param message:
:param http_status_code:
:return:
"""
return "ERROR::CLIENT::{}::{}".format(http_status_code, message)
|
ea6f1a3073b856eb2f08b84b62cf9c95d9a62de4
| 41,759 |
def get_zamid_s(zamid):
"""Gets the state of a nuclide from a its z-a-m id. 1 = first excited state, 0 = ground state.
Parameters
----------
zamid: str
z-a-m id of a nuclide
"""
s = int(zamid[-1])
return s
|
750108113619f5176bf75e479b52989f9546f876
| 41,763 |
def ceil(a, b):
"""
Returns the ceiling of a on b
"""
c = float(a) / float(b)
if c == int(c):
return int(c)
return int(c) + 1
|
f6c7d46f05512d0766d4f9b39cdff224ed7d9bb7
| 41,777 |
def market_cap(df, min_cap=200):
"""filters out stocks that don't meet the min_cap minimum capitalization
criteria.
:df: dataframe
:min_cap: minimum market_cap number (*1 million) for stocks to include in
stock universe (default = 200)
:returns: Dataframe with stocks that have market capitalization>min_cap
"""
df_allstocks = df[df.Market_Cap_Q1>200]
return df_allstocks
|
01f716510f3d172e262fcd220ce6affab1e22e19
| 41,778 |
def attach(item, action):
"""Attaches a parse action to an item."""
return item.copy().addParseAction(action)
|
7cbfbcee8316a009168ce577a6a178aa9d8384f1
| 41,780 |
from typing import List
def arraysum(array: List[int]) -> int:
""" Get the sum of all the elements in the array.
arraysum
========
The `arraysum` function takes an array and returns the sum of all of its
elements using divide and concuer method.
Parameters
----------
array: List[int]
An array/list of integers
Returns
-------
sum: int
Sum of all the elements in the array
"""
if len(array) == 0: # The base case: if the length of the
return 0 # array is 0 then stop
return array.pop() + arraysum(array) # Divide and conquer: divide the array
# into first element and rest of the
# elements and call itself with them
|
8a2ea3bd6391f7ed402f07b381d561c816a7c68d
| 41,783 |
import torch
def save_model(network, path):
"""
Save (trained) neural network to a file.
Intended to save trained models, but can save untrained ones as well.
Parameters
----------
network: pytorch object
Pytorch object or custom pytorch object containing model information.
path: str
Location for saving the file, including file name.
Returns
-------
None
"""
PATH = path
torch.save(network.state_dict(), PATH)
return None
|
173c123b00f18635d3aa271f4b5d1789ee9a81f8
| 41,784 |
def ReadPairs(filename):
"""Read pairs and match labels from the given file.
"""
pairs = []
labels = []
with open(filename) as f:
for line in f:
parts = [p.strip() for p in line.split()]
pairs.append((parts[0], parts[3]))
labels.append(1 if parts[1] == parts[4] else 0)
return pairs, labels
|
ab1c0a34f94c61b2d999a10a2fabab57790280b7
| 41,786 |
from typing import List
from typing import Tuple
from typing import Dict
def edf_annotations(triggers: List[Tuple[str, str, float]],
durations: Dict[str, float] = {}
) -> List[Tuple[float, float, str]]:
"""Convert bcipy triggers to the format expected by pyedflib for writing annotations.
Parameters
----------
triggers - trigger data in the format (symbol, targetness, stamp),
where stamp has been converted to acquisition clock units.
durations - optional map defining the duration (seconds) of each
trigger type. The default is to assign 0.0 seconds.
Returns
-------
List[Tuple(onset_in_seconds, duration_in_seconds, description)]
"""
return [(timestamp, durations.get(targetness, 0.0), label)
for (label, targetness, timestamp) in triggers]
|
8c26f7e7bd874bc2a996e251f02513135e8e9e49
| 41,788 |
def get_N(longN):
"""
Extract coefficients fro the 32bits integer,
Extract Ncoef and Nbase from 32 bit integer
return (longN >> 16), longN & 0xffff
:param int longN: input 32 bits integer
:return: Ncoef, Nbase both 16 bits integer
"""
return (longN >> 16), (longN & (2 ** 16 - 1))
|
bb8a0c041d8821958901681d925d278fb7083ba5
| 41,792 |
def join_list_mixed(x, sep=', '):
"""
Given a mixed list with str and list element join into a single str
:param x: list to be joined
:param sep: str to be used as separator between elements
:return: str
"""
return sep.join([sep.join(y) if isinstance(y, list) else y for y in x])
|
5faa80d7a451ceeff658938976f291337a6ee8d0
| 41,797 |
import re
def trim(string: str) -> str:
"""Takes in a string argument and trims every extra whitespace from in between as well as the ends."""
return re.sub(" +", " ", string.strip())
|
5c7b428d742a7255b0036d4eeb75a5fab2817e36
| 41,800 |
def _proc_lines(in_str):
""" Decode `in_string` to str, split lines, strip whitespace
Remove any empty lines.
Parameters
----------
in_str : bytes
Input bytes for splitting, stripping
Returns
-------
out_lines : list
List of line ``str`` where each line has been stripped of leading and
trailing whitespace and empty lines have been removed.
"""
lines = in_str.decode('latin1').splitlines()
return [line.strip() for line in lines if line.strip() != '']
|
66cd12550503ffd421bab32084a0c23897f90588
| 41,801 |
import itertools
def decode_years_to_min_max(summarized_year_string):
"""
decode a summarized string of years into minimum & max. year values
>>> decode_years_to_min_max('2000-2002, 2004')
(2000, 2004)
>>> decode_years_to_min_max('1992, 1994-1995')
(1992, 1995)
>>> decode_years_to_min_max('1750, 1752')
(1750, 1752)
>>> decode_years_to_min_max('1750-1751')
(1750, 1751)
>>> decode_years_to_min_max('1901')
(1901, 1901)
"""
tokens = []
# split summary into groups of sequential digits or sequental non-digits
for match, group_iterator in itertools.groupby(summarized_year_string
,key=str.isdigit):
group_string = ''.join(group_iterator)
tokens.append(group_string)
# pick off the first & last groups
min_string = tokens[0]
max_string = tokens[-1]
return int(min_string), int(max_string)
|
078b74432fc762c4ba39accec90a72a6cec00dc9
| 41,802 |
def font_style(
custom_font, font):
"""
Changes font family
:param custom_font: font used by Message in Tkinter GUI
:param font: font the user selects
:return: font used by GUI
"""
custom_font.config(family=font)
return custom_font
|
d2bf35924abd32b6232039c6284dbb35891a4df8
| 41,803 |
def y_in_process(coord2d: list, y_coord: int, ly: int, processes_in_y: int) -> bool:
"""
Checks whether a global y coordinate is in a given process or not.
Args:
coord2d: process coordinates given the cartesian topology
x_coord: global y coordinate
lx: size of the lattice grid in y direction
processes_in_x: number of processes in y direction
Returns:
boolean whether global y coordinate is in given process or not
"""
lower = coord2d[1] * (ly // processes_in_y)
upper = (coord2d[1] + 1) * (ly // processes_in_y) - 1 if not coord2d[1] == processes_in_y - 1 else ly - 1
return lower <= y_coord <= upper
|
0d67c92426f44fff405e7f50f4219ad2d2c76361
| 41,804 |
import requests
def fetch_coordinates(apikey, address):
"""
Get the coordinates of address.
Returns:
return: longitude and latitude of address.
Args:
apikey: token for Yandex service.
address: name of specific place.
"""
base_url = "https://geocode-maps.yandex.ru/1.x"
response = requests.get(base_url, params={
"geocode": address,
"apikey": apikey,
"format": "json",
})
response.raise_for_status()
found_places = response.json()['response']['GeoObjectCollection']['featureMember']
if not found_places:
return None
most_relevant = found_places[0]
lon, lat = most_relevant['GeoObject']['Point']['pos'].split(" ")
return lon, lat
|
027a73130526522019cadf1982c22039873c732b
| 41,809 |
import torch
def compute_iou(pred_mask, gt_mask):
"""
Computes IoU between predicted instance mask and
ground-truth instance mask
"""
pred_mask = pred_mask.byte().squeeze()
gt_mask = gt_mask.byte().squeeze()
# print('pred_masks', pred_mask.shape, 'gt_masks', gt_mask.shape)
intersection = torch.bitwise_and(pred_mask, gt_mask).sum().float()
union = torch.bitwise_or(pred_mask, gt_mask).sum().float()
return intersection / union
|
fbfbfaa92954d950dd18e5bf9e21bf303676a28d
| 41,812 |
def document_path(doc_id, options):
"""Return relative path to document from base output directory."""
if options.dir_prefix is None:
return ''
else:
return doc_id[:options.dir_prefix]
|
91ef1244839580d9d218639676d0f6979008cf67
| 41,813 |
import re
def pip_to_requirements(s):
"""
Change a PIP-style requirements.txt string into one suitable for setup.py
"""
if s.startswith('#'):
return ''
m = re.match('(.*)([>=]=[.0-9]*).*', s)
if m:
return '%s (%s)' % (m.group(1), m.group(2))
return s.strip()
|
dcfceacfab4c47429bd7aff7bc6795ab7f3f7b5f
| 41,816 |
def range_check(value, min_value, max_value, inc_value=0):
"""
:brief Determine if the input parameter is within range
:param value: input value
:param min_value: max value
:param max_value: min value
:param inc_value: step size, default=0
:return: True/False
"""
if value < min_value:
return False
elif value > max_value:
return False
elif (inc_value != 0) and (value != int(value / inc_value) * inc_value):
return False
return True
|
bf21759371706144e9d25f0692c60d3246e66159
| 41,819 |
import json
def destructure(env):
"""Decodes Nix 2.0 __structuredAttrs."""
return json.loads(env['__json'])
|
93b7fbee7262358c75d8f7d9343e51fef2662f6a
| 41,820 |
def passAuth(password):
""" Returns true if the password matches with the user's password, else returns false."""
if password == 9241:
return True
else:
return False
|
63f60643f999de198b237d3b4f0d2e4c9046157e
| 41,825 |
def _dict_printable_fields(dict_object, skip_fields):
"""Returns a list of strings for the interesting fields of a dict."""
return ['%s=%r' % (name, value)
for name, value in dict_object.items()
# want to output value 0 but not None nor []
if (value or value == 0)
and name not in skip_fields]
|
776663a70a7f76879722e9ae55feef7ab50d5880
| 41,827 |
def _get_host(self, request, prefix_path = None):
"""
Retrieves the host for the current request prepended
with the given prefix path.
:type request: Request
:param request: The request to be used.
:type prefix_path: String
:param prefix_path: The prefix path to be prepended to the
host value.
:rtype: String
:return: The current host (name) for the given request.
"""
# retrieves the host value from the request headers
host = request.request.get_header("Host")
# in case there is a prefix path defined
if prefix_path:
# prepends the prefix path to the host
host = prefix_path + host
# returns the host
return host
|
9b3c205734820ac03ba8e1e3441e7ea6540fc6c3
| 41,829 |
def create_labels_lookup(labels):
"""
Create a dictionary where the key is the row number and the value is the
actual label.
In this case, labels is an array where the position corresponds to the row
number and the value is an integer indicating the label.
"""
labels_lookup = {}
for idx, label in enumerate(labels):
labels_lookup[idx] = int(label[0][:])
return labels_lookup
|
b80bab4792d4bd403a903c18907d16b2bcb79418
| 41,834 |
from typing import Optional
from typing import List
def str2list(x: str) -> Optional[List]:
"""Convert string to list base on , delimiter."""
if x:
return x.split(",")
|
62cd7f087f72981e22f2f8fdc1871a394e00501b
| 41,836 |
def mag2Jy(info_dict, Mag):
"""Converts a magnitude into flux density in Jy
Parameters
-----------
info_dict: dictionary
Mag: array or float
AB or vega magnitude
Returns
-------
fluxJy: array or float
flux density in Jy
"""
fluxJy = info_dict["Flux_zero_Jy"] * 10 ** (-0.4 * Mag)
return fluxJy
|
b81d3b8abd10e30e12c33d2a91b42981d2c0d522
| 41,837 |
def buildProcessArgs(*args, **kwargs):
"""Build |CLI| arguments from Python-like arguments.
:param prefix: Prefix for named options.
:type prefix: :class:`basestring`
:param args: Positional arguments.
:type args: :class:`~collections.Sequence`
:param kwargs: Named options.
:type kwargs: :class:`dict`
:return: Converted argument list.
:rtype: :class:`list` of :class:`basestring`
This function converts Python-style arguments, including named arguments, to
a |CLI|-style argument list:
.. code-block:: python
>>> buildProcessArgs('p1', u'p2', None, 12, a=5, b=True, long_name=u'hello')
['-a', '5', '--long-name', u'hello', '-b', 'p1', u'p2', '12']
Named arguments are converted to named options by adding ``'-'`` (if the name
is one letter) or ``'--'`` (otherwise), and converting any underscores
(``'_'``) to hyphens (``'-'``). If the value is ``True``, the option is
considered a flag that does not take a value. If the value is ``False`` or
``None``, the option is skipped. Otherwise the stringified value is added
following the option argument. Positional arguments --- except for ``None``,
which is skipped --- are similarly stringified and added to the argument list
following named options.
"""
result = []
for k, v in kwargs.items():
if v is None or v is False:
continue
result += ["%s%s" % ("-" if len(k) == 1 else "--", k.replace("_", "-"))]
if v is not True:
result += ["%s" % v]
return result + ["%s" % a for a in args if a is not None]
|
e802e8b35a7b0e6f9bd06e62f29e4dce49580dea
| 41,838 |
def strip_suffix(string, suffix):
"""Remove a suffix from a string if it exists."""
if string.endswith(suffix):
return string[:-(len(suffix))]
return string
|
0ca354328ce8579fcce4f16f4f0dfdeac4708391
| 41,843 |
def create_url(config):
"""Create github api url."""
return '{base_url}/repos/{repo_owner}/{repo_name}/issues'.format(**config)
|
3e3068f7a02ca65d8f2d5a1b987378e3b50d8dba
| 41,846 |
def minmax_scale(array, ranges=(0., 1.)):
"""
normalize to [min, max], default is [0., 1.]
:param array: ndarray
:param ranges: tuple, (min, max)
:return:
"""
_min = ranges[0]
_max = ranges[1]
return (_max - _min) * (array - array.min()) / (array.max() - array.min()) + _min
|
105dcecb40ac982dcf0973e15b9f2cc80e9a8469
| 41,850 |
def update_zones(
self,
zones: dict,
delete_dependencies: bool,
) -> bool:
"""Configure zones on Orchestrator.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - zones
- POST
- /zones
.. warning::
This will overwrite the zones so use the :func:`~get_zones`
function to get existing zones and append if you don't want to
remove existing zones
:param zones: Dictionary of zones to configure in the format \n
``{"ZONE_ID" : {"name" : "ZONE_NAME"}, ... }`` \n
e.g. {"1" : {"name" : "MPLS"}, ...}
:type zones: dict
:param delete_dependencies: If True, Zones deleted here will be
removed from overlays, policies, interfaces and deployment
profiles currently using those zones.
:type delete_dependencies: bool
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._post(
"/zones",
data=zones,
expected_status=[204],
return_type="bool",
)
|
e4c1470411b75e23df02c3b14398b311d0ca59e1
| 41,855 |
def IsVector(paramType):
""" Check if a param type translates to a vector of values """
pType = paramType.lower()
if pType == 'integer' or pType == 'float':
return False
elif pType == 'color' or pType.startswith('float'):
return True
return False
|
58a14693ffabc2230eea0b3f6702aa56ffc514ca
| 41,857 |
def secondsToMinutes(times):
"""
Converts splits in seconds to minutes.
"""
return times / 60.0
|
04a97bbadce9ef982fab72fc7dced25aea16c3de
| 41,860 |
def calc_frequencies(rolls):
"""
1) Create a list of length 11 named totals with all zeros in it
2) Go through the rolls[][] list with a nested loop;
add the number in rolls[row][col] to the appropriate entry in the
totals list.
"""
# Initialize a list of length 11 named totals
totals = [0 for _ in range(11)]
# Add the number in rolls[row][col] to the corresponding number
for row in range(6):
for col in range(6):
totals[row + col] += rolls[row][col]
return totals
|
6735e0ab5111fcf51f86f7f9b1d1dcba569652ed
| 41,862 |
def getRelativeFreePlaceIndexForCoordinate(freePlaceMap, x, y):
"""
Returns the Index in the FreePlaceValueArray in witch the given Coordinate is in
:param freePlaceMap: The FreePlaceMap to check on
:param x: The X Coordinate to Check for
:param y: The Y Coordinate to Check for
:return: The found Index or None if not Found
"""
if freePlaceMap is None or len(freePlaceMap) < y or len(freePlaceMap[0]) < x or x < 0 or y < 0:
return None
# Check current Cell
if freePlaceMap[y][x] != -1:
return freePlaceMap[y][x] - 1
# Check Left Cell
elif x > 0 and freePlaceMap[y][x - 1] != -1:
return freePlaceMap[y][x - 1] - 1
# Check Right Cell
elif x < len(freePlaceMap[0]) - 1 and freePlaceMap[y][x + 1] != -1:
return freePlaceMap[y][x + 1] - 1
# Check Cell Underneath
elif y > 0 and freePlaceMap[y - 1][x] != -1:
return freePlaceMap[y - 1][x] - 1
# Check Upper Cell
elif y < len(freePlaceMap) - 1 and freePlaceMap[y + 1][x] != -1:
return freePlaceMap[y + 1][x] - 1
return None
|
855b5c6e4e225bb5f25b941d84d71756822ec152
| 41,868 |
def rating_class(rating):
"""
Outputs the Bootstrap CSS class for the review rating based on the range.
"""
try:
rating = float(rating)
except ValueError:
return ""
if rating >= 80:
return "success"
if rating >= 50:
return "info"
if rating >= 20:
return "warning"
return "danger"
|
46bb43032a7193ffe63e91bc261a36eca84da0a6
| 41,870 |
def create_info(type, client_public_key, server_public_key):
"""
Create info structure for use in encryption.
The start index for each element within the buffer is:
value | length | start |
-----------------------------------------
'Content-Encoding: '| 18 | 0 |
type | len | 18 |
nul byte | 1 | 18 + len |
'P-256' | 5 | 19 + len |
nul byte | 1 | 24 + len |
client key length | 2 | 25 + len |
client key | 65 | 27 + len |
server key length | 2 | 92 + len |
server key | 65 | 94 + len |
For the purposes of push encryption the length of the keys will
always be 65 bytes.
:param type: HTTP Content Encryption Specification (must be "aesgcm")
:param client_public_key: Client's public key in bytes
:param server_public_key: Server's public key in bytes
:return: generated info
"""
if not isinstance(type, bytes):
raise TypeError('type must be bytes')
# The string 'Content-Encoding: ' in utf-8 encoding
info = b'Content-Encoding: '
# Tye 'type' of the record, encoded in utf-8
info += type
# null + 'P-256' (representing the EC being used) + null
info += b'\x00P-256\x00'
# The length of the client's public key as a 16-bit integer
info += len(client_public_key).to_bytes(2, byteorder='big')
# Actual client's public key
info += client_public_key
# The length of our public key
info += len(server_public_key).to_bytes(2, byteorder='big')
# Actual public key
info += server_public_key
return info
|
0e2dae46522d89c8b099721d05bac6ae0058e64a
| 41,879 |
def get_total(alist, digits=1):
"""
get total sum
param alist: list
param digits: integer [how many digits to round off result)
return: float
"""
return round(sum(alist), digits)
|
27a26f21e74036a56796f1cc05fcfb88efa41a45
| 41,883 |
import json
def to_json(obj):
"""Object to JSON."""
return json.dumps(obj)
|
2029d7507b029ea1d9c11c99a3a9735d0094a3c6
| 41,886 |
import re
def replaceall(replace_dict, string):
"""
replaceall will take the keys in replace_dict and replace string with their corresponding values. Keys can be regular expressions.
"""
replace_dict = dict((re.escape(k), v) for k, v in list(replace_dict.items()))
pattern = re.compile("|".join(list(replace_dict.keys())))
return pattern.sub(lambda m: replace_dict[re.escape(m.group(0))], string)
|
66c6ec299476986011de21a5f28a613c44435d33
| 41,894 |
def roll_rating(flight_phase, aircraft_class, roll_timecst):
""" Give a rating of the Roll mode : Level1 Level2 or Level 3 according to MILF-8785C
Args:
flight_phase : string : 'A', 'B' or 'C'
aircraft_class : int : 1, 2, 3 or 4
roll_timecst (float): Roll Mode time constante [s]
Returns:
1 one 2 or 3 corresponding to the flight level
"""
if flight_phase == 'A' or flight_phase == 'C':
if aircraft_class ==1 or aircraft_class == 4:
if 0<= roll_timecst <=1:
roll_rate = 1
elif roll_timecst <=1.4:
roll_rate = 2
elif roll_timecst <= 10:
roll_rate = 3
else:
roll_rate = None
else: # aircraft_class == 2 or aircraft_class == 3:
if 0<= roll_timecst <=1.4:
roll_rate = 1
elif roll_timecst <=3:
roll_rate = 2
elif roll_timecst <= 10:
roll_rate = 3
else:
roll_rate = None
else: # flight_phase == 'B':
if 0<= roll_timecst <=1.4:
roll_rate = 1
elif roll_timecst <=3:
roll_rate = 2
elif roll_timecst <= 10:
roll_rate = 3
else:
roll_rate = None
return roll_rate
|
7e24ad1cf3c2433ed7b3e5fe7dab8a53b35a6d8d
| 41,898 |
def correct_invalid_value(value, args):
"""This cleanup function replaces null indicators with None."""
try:
if value in [item for item in args["nulls"]]:
return None
if float(value) in [float(item) for item in args["nulls"]]:
return None
return value
except:
return value
|
e7c575d45237dce82491e53afeccb953b21e1b33
| 41,906 |
from typing import Dict
def generate_wiki_template_text(name: str, parameters: Dict[str, str]) -> str:
"""
Generate wikitext for template call with name and parameters.
Parameters should not contain unescaped '{', '}' or '|' characters,
otherwsie generated text can be incorrect.
"""
result = '{{' + name
if len(parameters):
result += '\n'
for key, value in parameters.items():
result += f'| {key} = {value}\n'
result += '}}'
return result
|
2c785431fed529cafa45a22a824033d284dffd44
| 41,907 |
import importlib
def my_model(opts):
"""Creates model object according to settings in parsed options.
Calls function with name opts.opts2model in module opts.model_module to
create model instance.
Args:
opts (obj): Namespace object with options. Required attributes are
opts.model_module and opts.opts2model.
Returns:
my_model (obj): Instantiated model object construtcted by function
opts.opts2model in module opts.model_module.
Raises:
NotImplementedError: When model wrapper opts.opts2model does not exist
in model module opts.model_module.
"""
model_import = 'models.' + opts.model_module
model_lib = importlib.import_module(model_import)
my_model = None
for name, fct in model_lib.__dict__.items():
if name==opts.opts2model:
my_model = fct(opts)
if my_model==None:
raise NotImplementedError(
"""Model wrapper function {opts2model} is not implemented in
model module {model_module}""".format(
opts2model=opts.opts2model,
model_module=opts.model_module
)
)
print("""Model was constructed by calling model function
{opts2model} in model module {model_module}.""".format(
opts2model=opts.opts2model,
model_module=opts.model_module
)
)
return my_model
|
9c31d2ba15c157cf5f7b15a7cf6fba88ce16a981
| 41,908 |
def group_cpu_metrics(metrics):
"""Group together each instances metrics per app/space"""
grouped_metrics = {}
for metric in metrics:
grouped_metrics.setdefault(metric['space'], {}).setdefault(metric['app'], []).append(metric['value'])
return [(app, space, metric_values,)
for space, apps in grouped_metrics.items() for app, metric_values in apps.items()]
|
91b91601c359e2b80c31b80fcb80bd5915d5972d
| 41,915 |
def time2secs(timestr):
"""Converts time in format hh:mm:ss to number of seconds."""
h, m, s = timestr.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
|
e06432cd56db691574e8400a23a57982e9177531
| 41,916 |
def convert_arabic_to_roman(arabic):
"""
Convert an arabic literal to a roman one. Limits to 39, which is a rough
estimate for a maximum for using roman notations in daily life.
..note::
Based on https://gist.github.com/riverrun/ac91218bb1678b857c12.
:param arabic: An arabic number, as string.
:returns: The corresponding roman one, as string.
"""
if int(arabic) > 39:
return arabic
to_roman = {
1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII',
8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX'
}
roman_chars_list = []
count = 1
for digit in arabic[::-1]:
digit = int(digit)
if digit != 0:
roman_chars_list.append(to_roman[digit * count])
count *= 10
return ''.join(roman_chars_list[::-1])
|
6f786c75250fe4da7e7c540acc82a8fc100254a7
| 41,917 |
def compare(a, b):
"""Sort an array of persons with comparator.
Comparator:
- If scores are equal, compare names.
- If a.score is higher than b.score, a should appear first.
- Vice versa.
"""
if a.score == b.score:
return a.name < b.name
return b.score - a.score < 0
|
5f58377a5d783c88cb214230d2823ce319860652
| 41,921 |
def delete_com_line(line : str) -> str:
"""Deletes comments from line"""
comm_start = line.find("//")
if comm_start != -1:
line = line[:comm_start]
return line
|
e75d74f68222d35e1231a3725d4a34c1d3e768ad
| 41,924 |
def flatten_image(img):
"""
takes in an (m, n) numpy array and flattens it
into an array of shape (1, m * n)
"""
s = img.shape[0] * img.shape[1]
img_wide = img.reshape(1, s)
return img_wide[0]
|
d97d070d9f827f57c79a6714e10d7b4cb8e06a46
| 41,929 |
def non_step(func):
"""A decorator which prevents a method from automatically being wrapped as
a infer_composite_step by RecipeApiMeta.
This is needed for utility methods which don't run any steps, but which are
invoked within the context of a defer_results().
@see infer_composite_step, defer_results, RecipeApiMeta
"""
assert not hasattr(func, "_skip_inference"), \
"Double-wrapped method %r?" % func
func._skip_inference = True # pylint: disable=protected-access
return func
|
f257a882fd5cf9b92e786153ba2a524ead75745e
| 41,933 |
def count_calls(results):
"""count number of "call" nodeid's in results"""
return len(list(r for r in results.keys() if r[1]=='call'))
|
e3ad7fa2fb8577fff615e55514afbcbe1af0ac9d
| 41,937 |
import typing
def exclude_header(
headers: typing.Sequence[str], exclude: typing.Set[str]
) -> typing.Sequence[typing.Optional[str]]:
"""
Exclude header.
Exclude columns from header by changing the entry to None.
:param headers: headers
:param exclude: columns to be excluded
:returns: header with columns excluded
"""
excluded_headers = [None if current in exclude else current for current in headers]
return excluded_headers
|
29d432abcae17848c42b6d238b744157a51ba133
| 41,940 |
def get_locus_blocks(glstring):
"""
Take a GL String, and return a list of locus blocks
"""
# return re.split(r'[\^]', glstring)
return glstring.split('^')
|
8981ca07549544f26139c11c21394979658abe2a
| 41,944 |
import re
def is_instance_type_format(candidate):
"""Return a boolean describing whether or not candidate is of the format of an instance type."""
return re.search(r"^([a-z0-9\-]+)\.", candidate) is not None
|
53568168301800776b5c7f1b39bbeddc8dc0ca0f
| 41,946 |
def enforce_file_extension(file, extension):
"""
Returns the given string (file name or full path) with the given extension.
string had no file extension .extension will be appended. If it had another
extension it is changed to the given extension. If it had the given
extension already the unchanged string is returned.
Parameters
----------
file: File name or full path. Can include a file extension .*
extension: File extension the given file name will be returned with.
Returns
-------
The given file with the given extension.
"""
if not extension.startswith('.'):
extension = '.' + extension
split_str = file.split('.', 1)
if (len(split_str) != 2) or (split_str[-1] != extension[1:]):
file = split_str[0] + extension
return file
|
021d69bcc1d4cf3f3fc500e9c8418c60b8c99d9f
| 41,947 |
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in either list1 and list2.
This function can be iterative.
"""
merged = []
idx1 = 0
idx2 = 0
while idx1 < len(list1) and idx2 < len(list2):
if list1[idx1] <= list2[idx2]:
merged.append(list1[idx1])
idx1 += 1
else:
merged.append(list2[idx2])
idx2 += 1
if idx1 == len(list1):
merged.extend(list2[idx2: ])
else:
merged.extend(list1[idx1: ])
return merged
|
57d2bf358d6d0d3353e4b3953e2ddce3c2d28050
| 41,953 |
def read_key_words(file):
"""Reads list of words in file, one keyword per line"""
return [line.rstrip('\n') for line in open(file)]
|
337bac4b6c2eac8a36ec372ea90c8bcab8218ed9
| 41,956 |
def bk_nearest_neighbor_search(search_string, tree):
"""
Search tree for nearest matches to supplied string.
Parameters
----------
search_string : str
search string
tree : BKTree
tree to search
Return values
-------------
matches : list
list of strings containing nearest matches from tree, where first item
is distance from search_string to nearest matches
"""
threshold = tree.root.distance_metric[tree.metric](search_string,
tree.root.string)
matches_dictionary = {}
matches_dictionary[threshold] = []
tree.root.recursive_nn_search(search_string, threshold,
matches_dictionary, tree.metric)
matches = [sorted(matches_dictionary.keys())[0]]
for value in matches_dictionary[matches[0]]:
matches.append(value)
return matches
|
b86f0663f711aea29abbb79e203ee74452d34207
| 41,959 |
def month_id(dte):
"""
Return an integer in the format YYYYMM.
Argument:
dte - the dte to use in making the month id.
"""
result = dte.year * 100 + dte.month
return result
|
ab5fcab351e7884b05803d0077d0eec473d08fa5
| 41,961 |
def delete_snapshot(connection, snapshot_id=None):
"""Deletes a snapshot.
* connection: An ec2 connection instance.
* volume_id: ID of snapshot to delete.
Returns True if deletion is successful.
"""
return connection.delete_snapshot(snapshot_id)
|
702bfffaa7d69453613e42aefcb019963191b152
| 41,964 |
import threading
def _get_internal_name(name):
"""Returns the internal thread-local name of an attribute based on its id.
For each specified attribute, we create an attribute whose name depends on
the current thread's id to store thread-local value for that attribute. This
method provides the name of this thread-specific attribute.
Args:
name: str, name of the exposed attribute.
Returns:
str, name of the internal attribute storing thread local value.
"""
return '__' + name + '_' + str(threading.current_thread().ident)
|
522a686ab7aaca18dfa8e2ac667881b15a75fd32
| 41,967 |
def gcd_step(a, b):
"""
Performs a single step of the gcd algorithm.
Example: gcd_step(1071, 462) == (2, 147) because 1071 == 2 * 462 + 147.
"""
if a < b:
return (0, b)
res = 0
while a >= b:
a -= b
res += 1
return (res, a)
|
02eedde8652a285c1b7af999d439c9fe77349d3f
| 41,970 |
def generate_Q_data(Q):
"""
問題のテキストデータを生成する。改行コードはCR+LFとする。
Parameters
==========
Q : tuple
read_Q()の返り値
Returns
=======
txt : str
問題のテキストデータ
"""
crlf = '\r\n' # DOSの改行コード
size, block_num, block_size, block_data, block_type, num_lines = Q
txt = 'SIZE %dX%d%s' % (size[0], size[1], crlf)
txt += 'BLOCK_NUM %d%s' % (block_num, crlf)
for i in range(1, block_num+1):
txt += crlf
txt += 'BLOCK#%d %dX%d%s' % (i, block_size[i][0], block_size[i][1], crlf)
for row in block_data[i]:
txt += ','.join(['+' if n == -1 else str(n) for n in row]) + crlf
return txt
|
70c3c1c0b2550a6805b1b2abedf0e5b115377e05
| 41,977 |
def get_feature_names(factors_path):
"""
Get feature names by reading header of factors csv
Args:
factors_path: path to factors csv with names of features as header
Returns:
list(str): list of column names read from file
"""
with open(factors_path) as f:
col_names = f.readline().split(',')
col_names[-1] = col_names[-1].strip('\n')
# Skip first field if empty (result of to_csv(save_index=True))
if not col_names[0]:
return col_names[1:]
else:
return col_names
|
0e224a610d9b4f072d76562b6efb0fb675eab5e0
| 41,978 |
def _transitive_parenthood(key,
term_dict):
"""Finds all parents, transitively, of `key` in `term_dict`.
Does not include itself in the set of parents, regardless of the type of
relation. This is left to the caller to decide.
Args:
key: Go Term, e.g. GO:0000001
term_dict: Go term to set of parent go terms.
Returns:
Set of transitive parent go terms of `key`.
"""
running_total = set()
to_examine = set(term_dict[key]) # Make a copy so we can pop from it.
while len(to_examine) > 0: # pylint: disable=g-explicit-length-test
cur_element = to_examine.pop()
running_total.add(cur_element)
for potential in term_dict[cur_element]:
if potential not in running_total:
to_examine.add(potential)
return running_total
|
9c3aa32ad90d02965aad67ffa436b0d02af65ba4
| 41,984 |
def organize(iterable, key):
"""Put all of the elements in `iterable` into
a dictionary which maps possible return values
of key onto lists of items of iterable
iterable - any iterable object (e.g. a list, or tuple)
key - a function that takes items in interable as inputs
Example:
organize([1,2,3],lambda x: x==2)
{True:[1,3],False:[2]}
"""
out = {}
for item in iterable:
k = key(item)
if not k in out:
out[k] = []
out[k].append(item)
return out
|
19edcc50738a0247e57c0b7c4d1812e63000b7ef
| 41,985 |
def __getWindow(window_config:str): #Called in genImgPatches()
"""Parses window_config to get height and width as integers
Args:
window_config (str): string of window height and width. Example: '5000,5000'
Outputs:
window (dict): dictionary containing ax:dim pairs
"""
dims = window_config.split(',',1)
axis = ('width','height')
window = {ax:int(dim) for (ax,dim) in zip(axis,dims)}
return window
|
8f9a9858f9f96c5f2698f922b63f2e7d328138a9
| 41,986 |
def get_slot(datetime_sec, band):
"""
Return IBP schedule time slot (0 ... 17) from given datetime_sec (second
from UNIX time epoch) and band (14, 18, ..., 28) MHz value
"""
time_xmit = 10 # sec (transmitting time length)
n_slots = 18 # number of slots
period_sched = n_slots * time_xmit
slot_offset = {
14: 0,
18: 1,
21: 2,
24: 3,
28: 4
}
timeslot_in_sched = int(datetime_sec % period_sched) / time_xmit
return (timeslot_in_sched - slot_offset[band]) % n_slots
|
0566887707e280b5c31f1ae87a3b443757421ce7
| 41,990 |
from unittest.mock import call
def fsl_cluster(finput, findex, thresh=0.9, fosize=None, fothresh=None, **kwargs):
"""
Run FSL Cluster command (https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/Cluster)
:param str finput: Input filename, image to be thresholded
:param float thresh: Chosen threshold; default = 0.9
:param str findex: Output file with each cluster assigned an integer from 1 to N
:param str fosize: Output file with each cluster voxel assigned an integer equivalent to its cluster size
:param str fothresh: Output file with clusters assigned the original values (only > threshold remain)
:return:
"""
# First try to run standard spherical project
osize = "--osize={}".format(fosize) if fosize is not None else ""
othresh = "--othresh={}".format(fothresh) if fothresh is not None else ""
fsl = "cluster --in={} --thresh={} --oindex={} {} {}".format(finput, thresh, findex, osize, othresh)
print("Running command: {}".format(fsl))
code_1 = call(fsl, **kwargs)
return code_1
|
cf314748daaeb9880ebc9c914f880eaa091fa0f9
| 41,993 |
def form_for_field(config, field):
"""
Gets the form name which contains the field that is passed in
"""
for form in config['forms']:
if field in form['csv_fields'].values():
return form['form_name']
|
d960154bbf473a2e8a730fd74fd70c3896620df0
| 41,994 |
def evaluate_chi2(chi2: float, gt_chi2: float, tol: float = 1e-3):
"""Evaluate whether chi square values match."""
if chi2 is None:
return False
return abs(chi2 - gt_chi2) < tol
|
2277365b1eb87d6591634ee92abe7380eec4e77f
| 41,995 |
import ast
def copy_location(new_node, old_node):
"""An ast.copy_location extension.
This function behaves identically to the standard ast.copy_location except
that it also copies parent and sibling references.
"""
new_node = ast.copy_location(new_node, old_node)
new_node.parent = old_node.parent
new_node.previous, new_node.next = old_node.previous, old_node.next
return new_node
|
ac827c9edf2a8de6c7abb1f6fd23eca8480c8cc4
| 41,996 |
def get_latitude(dataset):
"""Get latitude dimension from XArray dataset object."""
for dim_name in ['lat', 'latitude']:
if dim_name in dataset.coords:
return dataset[dim_name]
raise RuntimeError('Could not find latitude dimension in dataset.')
|
6a0eb8cbe27c0a802133ec80f7feb7f11afe8b15
| 42,000 |
async def get_indexed_tags(redis):
"""Get all tags monitored for indexing.
Args:
redis (aioredis.Redis): a Redis interface.
Returns:
A list of monitored tags as `str` objects.
"""
return await redis.lrange('indexed_tags', 0, -1, encoding='utf-8')
|
5f9c7cd1c2eb89e04013ddfd6fdb81d24b4d5685
| 42,003 |
def linear_search(l, item):
"""
Liner Search Implementation.
Time O(n) run.
O(1) space complexity, finds in place.
:param l: A List
:param item: Item from the List or N/a (-1).
:return:the founded index of the wanted item.
"""
for i in range(len(l)):
if item == l[i]:
return i
return -1
|
18369cdf07bd4784e21bb01b8a3545c5d742e5cf
| 42,004 |
import functools
def dec_check_lines(func):
"""
Decorator to check the currently displayed lines on the LCD to prevent rewriting on the screen.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
str_args = str(args) + str(kwargs)
if self.lines != str_args:
self.lines = str_args
func(self, *args, **kwargs)
return wrapper
|
104be359535ed3ac11b40dc2a578eea73915ad15
| 42,008 |
def circumcircle(u, v, w):
"""find the center/radius of circumcircle of triangle uvw"""
vu, wv, uw = (u - v), (v - w), (w - u)
d = 2 * ((u - v).crs(v - w)).dot((u - v).crs(v - w))
a = (v - w).dot(v - w) * (u - v).dot(u - w) / d
b = (u - w).dot(u - w) * (v - u).dot(v - w) / d
c = (u - v).dot(u - v) * (w - u).dot(w - v) / d
o = u * a + v * b + w * c
r = (u - o).mag()
return o, r
|
ee824a1ccc96663d1e347057938b1a6fc4da80ac
| 42,010 |
def convert_ms(ms):
"""
Converts milliseconds into h:m:s
:param ms: int
:return: str
"""
seconds = (ms / 1000) % 60
seconds = int(seconds)
if seconds < 10:
seconds = "0" + str(seconds)
else:
seconds = str(seconds)
minutes = (ms / (1000 * 60)) % 60
minutes = int(minutes)
if minutes < 10:
minutes = "0" + str(minutes)
else:
minutes = str(minutes)
hours = (ms / (1000 * 60 * 60)) % 24
hours = int(hours)
if hours < 10:
hours = "0" + str(hours)
else:
hours = str(hours)
return hours + ":" + minutes + ":" + seconds
|
1b39e0ac151fbdf6a3e7a6a15e83c36ff40e0810
| 42,011 |
def GetASTSummary(ast):
""" Summarizes an AST field
Flags:
P - AST_PREEMPT
Q - AST_QUANTUM
U - AST_URGENT
H - AST_HANDOFF
Y - AST_YIELD
A - AST_APC
L - AST_LEDGER
B - AST_BSD
K - AST_KPERF
M - AST_MACF
C - AST_CHUD
C - AST_CHUD_URGENT
G - AST_GUARD
T - AST_TELEMETRY_USER
T - AST_TELEMETRY_KERNEL
T - AST_TELEMETRY_WINDOWED
S - AST_SFI
"""
out_string = ""
state = int(ast)
thread_state_chars = {0x0:'', 0x1:'P', 0x2:'Q', 0x4:'U', 0x8:'H', 0x10:'Y', 0x20:'A',
0x40:'L', 0x80:'B', 0x100:'K', 0x200:'M', 0x400:'C', 0x800:'C',
0x1000:'G', 0x2000:'T', 0x4000:'T', 0x8000:'T', 0x10000:'S'}
state_str = ''
mask = 0x1
while mask <= 0x10000:
state_str += thread_state_chars[int(state & mask)]
mask = mask << 1
return state_str
|
af6bd56509666162501dee0e3077a6470b9a6c0a
| 42,016 |
def is_number_tryexcept(s):
"""
Returns True if string `s` is a number.
Taken from: https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float
"""
try:
float(s)
return True
except ValueError:
return False
|
569f73b4be50e1ddb4157ec98e59c2310d874412
| 42,019 |
import six
def split_ver(v):
"""Split v into a list of integers.
Args:
v (:obj:`str` or :obj:`list` of :obj:`int` or :obj:`int`):
Version string to split using periods.
Returns:
:obj:`list` of :obj:`int` or :obj:`str`
"""
v = v.split(".") if isinstance(v, six.string_types) else v
return [
int(x) if isinstance(x, six.string_types) and x.isdigit() else x
for x in v
if x not in ["", None]
]
|
c3bebb064c229c65c306f0cf40697337e2884a3b
| 42,031 |
def overlap(x):
"""Function to define the overlap between two lists contained in a pandas dataframe
1) return the length of the drug shared list
Parameters
----------
x : Dataframe
Dataframe containing the drug list related to the side effect and the drug list related to the target
"""
return len(x['se_drug'].intersection(x['tg_drug']))
|
fb3fe3a74583b5c719d8a32d0c93d56d5d70dc9b
| 42,035 |
def distance2(x1, y1, z1, x2, y2, z2):
"""Calculates the distance^2 between point 1 and point 2."""
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)
|
ff2740fe1ce3e52e336a18dca9c4f7bb504cacf4
| 42,038 |
from textwrap import dedent
def dedent_nodetext_formatter(nodetext, has_options, caller=None):
"""
Just dedent text.
"""
return dedent(nodetext)
|
7a4a06a68470f75eba26aa311b99f85a2859367a
| 42,039 |
def get_grid(size):
"""Create grid with size."""
return [[[] for _ in range(size)]
for _ in range(size)]
|
53db2ac06d8ada944575d022685bbf2f21929b09
| 42,040 |
def format_datetime(value, format="%B %d, %Y"):
"""Format a date time to (Default): Month Day, LongYear"""
if value is None:
return ""
return value.strftime(format).lstrip("0").replace(" 0", " ")
|
747a31ff83a2497d7d3257d7311e7e18071b5848
| 42,041 |
def noop_walk(_data, _arg):
"""
No-op walker.
"""
return 0
|
4f60f855d7d3671ca61bd64b19f47524dc560ebe
| 42,043 |
def work_dir(tmpdir):
"""Return temporary directory for output/input files."""
return tmpdir.mkdir('work_dir')
|
952bf3fbe1a81a43a37d35e255a6ddc97a1a18ee
| 42,044 |
import six
def _IsUrl(resource_handle):
"""Returns true if the passed resource_handle is a url."""
parsed = six.moves.urllib.parse.urlparse(resource_handle)
return parsed.scheme and parsed.netloc
|
8ebd20a55c168cbefd243cbc01c87ea051a35c52
| 42,046 |
def run(state, initial):
"""
Run the stateful action ``state`` given initial state ``initial``.
Equivalent to ``state.run(initial)``.
:return: A tuple of ``(a, s)``, where ``a`` is the value of the action,
and ``s`` is the new state.
"""
return state.run(initial)
|
6204133fe147ff3ab6fd68cb69e697391ffa65f6
| 42,054 |
def author() -> str:
"""
It gets the authors string.
:return: See description.
:rtype str.
"""
return '(c) 2020 Giovanni Lombardo mailto://g.lombardo@protonmail.com'
|
8275d724299012f8bac866db512e695b97a87b2a
| 42,056 |
def _matches_to_sets(matches):
"""
Helper function to facilitate comparing collections of dictionaries in
which order does not matter.
"""
return set(map(lambda m: frozenset(m.items()), matches))
|
4e8b38131130275c1ced0c960c0f6ef6d59c4790
| 42,057 |
def eval_precisions(scores, targets, topk=(1,)):
"""Computes the precision@k for the specified values of k
Args:
scores: FloatTensor, (num_examples, num_classes)
targets: LongTensor, (num_examples, )
"""
maxk = max(topk)
num_examples = targets.size(0)
_, preds = scores.topk(maxk, 1, largest=True, sorted=True)
preds = preds.t() # (maxk, num_exmples)
correct = preds.eq(targets.unsqueeze(0).expand_as(preds))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / num_examples).data.item())
return res
|
42e76d0b036b39a7531cdcbde6c7ebc3fa6ff13f
| 42,058 |
def escape(query):
"""Escape a value to be used in a query"""
query = query.replace("\\", "\\\\")
query = query.replace("|", "\\|")
query = query.replace("*", "\\*")
return query
|
8eb162fc3eae6bc9c54257f33273ac8fee19637c
| 42,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.