content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def xor(b1, b2):
"""Expects two bytes objects of equal length, returns their XOR"""
assert len(b1) == len(b2)
return bytes([x ^ y for x, y in zip(b1, b2)]) | 3376df85b52cea276417e29ae81c80208dc28b86 | 13,921 |
import random
import string
def random_string(length=1, unicode=False):
"""
Returns random ascii or unicode string.
"""
if unicode:
def random_fun():
return chr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))
else:
def random_fun():
return random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits)
return ''.join(random_fun() for _ in range(length)) | 45760b3e3c42e484d51abf76f9eb2ae0c8132fd1 | 13,928 |
import math
def probability(ec, en, t):
"""
Probability function
:param ec: current energy
:param en: next energy
:param t: temperature ratio
:return: probability value
"""
return math.exp((ec - en) / t) | c055081cd93473ecf4abeab1c8b5cc36fb38f0a4 | 13,930 |
def add_ext(name, ext, seq=-1):
"""add_ext constructs file names with a name, sequence number, and
extension.
Args:
name (string) - the filename
ext (string) - the file extension
seq (int) - the number in a sequence with other files
(Default -1) means that it is a standalone
file
"""
#add period if not
if '.' not in ext[0]:
ext = '.' + ext
if seq != -1:
ext = str(seq) + ext
return name + ext | 650eee088ae58d182c49f35f37e5b8deac57fa1d | 13,933 |
def get_coding_annotation_fasta(seq_record):
"""
When passed a sequence record object returns an array of FASTA strings for each annotation.
:param seq_record: A Biopython sequence record object.
:return: A FASTA file string containing all sequences record object CDS sequence features.
"""
fasta = []
features = seq_record.features # Each sequence has a list (called features) that stores seqFeature objects.
for feature in features: # For each feature on the sequence
if feature.type == "CDS": # CDS means coding sequence (These are the only feature we're interested in)
feat_qualifiers = feature.qualifiers # Each feature contains a dictionary called qualifiers which contains
# data about the sequence feature (for example the translation)
start = int(feature.location.start) # Type-casting to int strips fuzzy < > characters.
end = int(feature.location.end)
strand = feature.location.strand
if strand is None:
strand = "?"
elif int(strand) < 0:
strand = "-"
elif int(strand) > 0:
strand = "+"
else:
strand = "?"
location = "[" + str(start) + ":" + str(end) + "](" + strand + ")"
# Gets the required qualifiers. Uses featQualifiers.get to return the qualifiers or a default value if the qualifiers
# is not found. Calls strip to remove unwanted brackets and ' from qualifiers before storing it as a string.
protein_id = str(feat_qualifiers.get('protein_id', 'no_protein_id')).strip('\'[]')
if protein_id == 'no_protein_id':
continue # Skips the iteration if protein has no id.
protein_locus = str(feat_qualifiers.get('locus_tag', 'no_locus_tag')).strip('\'[]')
gene = str(feat_qualifiers.get('gene', 'no_gene_name')).strip('\'[]')
product = str(feat_qualifiers.get('product', 'no_product_name')).strip('\'[]')
translated_protein = str(feat_qualifiers.get('translation', 'no_translation')).strip('\'[]')
fasta_part_one = ">" + protein_id + " " + gene + "-" + product + " (Locus: " + protein_locus + ")"
fasta_part_two = " (Location: " + location + ")" + "\n" + translated_protein + "\n"
fasta.append(fasta_part_one + fasta_part_two)
fasta_string = "".join(fasta)
return fasta_string | 4fa24279ebb89ea7c61eeae6614c1fa309ffad87 | 13,936 |
from typing import Union
def bars_to_atmospheres(bar: float, unit: str) -> Union[float, str]:
"""
This function converts bar to atm
Wikipedia reference: https://en.wikipedia.org/wiki/Standard_atmosphere_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
>>> bars_to_atmospheres(36, "bar")
35.529237601776465
>>> bars_to_atmospheres("57.6", "bar")
56.84678016284234
>>> bars_to_atmospheres(0, "bar")
0.0
>>> bars_to_atmospheres(35, "Pa")
'Invalid unit'
>>> bars_to_atmospheres("barrs", "bar")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'barrs'
"""
if unit == "bar":
atm = float(bar) / 1.01325
return atm
else:
return "Invalid unit" | d460021395af77acda01296710f145e9b52d8594 | 13,937 |
def series(expr, x, point=0, n=6, dir="+"):
"""Series expansion of expr around point `x=point`.
See the doctring of Basic.series() for complete details of this wrapper.
"""
return expr.series(x, point, n, dir) | fee3fff7a29136813c7d6bf5d1cf7c576651368d | 13,940 |
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None):
"""Process input of the apply_transform_funcs function.
:param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple
:param dict func_args: function positional arguments, specified as (function, arguments tuple) pairs
:param dict func_kwargs: function keyword arguments, specified as (function, kwargs dict) pairs
:returns: transformation functions for apply_transform_funcs function
:rtype: list
"""
# copy function arguments and make sure they are in dictionaries
func_args = dict(func_args) if func_args else {}
func_kwargs = dict(func_kwargs) if func_kwargs else {}
# loop over specified functions
proc_funcs = []
for func_spec in trans_funcs:
# expand (func, args, kwargs) combinations
try:
func, args, kwargs = (func_spec, None, None) if isinstance(func_spec, str) else func_spec
except TypeError:
func, args, kwargs = func_spec, None, None
except ValueError:
raise ValueError('expected (func, args, kwargs) combination (got {!s})'.format(func_spec))
# get positional arguments
args_ = func_args.pop(func, None)
if args is not None and args_ is not None:
raise RuntimeError('arguments for "{!s}" in both "trans_funcs" and "func_args"'.format(func))
args = tuple(args) if args is not None else tuple(args_) if args_ is not None else ()
# get keyword arguments
kwargs_ = func_kwargs.pop(func, None)
if kwargs is not None and kwargs_ is not None:
raise RuntimeError('keyword arguments for "{!s}" in both "trans_funcs" and "func_kwargs"'.format(func))
kwargs = dict(kwargs) if kwargs is not None else dict(kwargs_) if kwargs_ is not None else {}
# check if function is callable
if not (isinstance(func, str) or callable(func)):
raise TypeError('function "{!s}" is not callable'.format(func))
# append function specification
proc_funcs.append((func, args, kwargs))
# check if all specified arguments were used
if func_args:
raise ValueError('unused function arguments specified: {!s}'.format(func_args))
if func_kwargs:
raise ValueError('unused function keyword arguments specified: {!s}'.format(func_kwargs))
return proc_funcs | 2e9fe4bec55f0a13a0644cfe27ba887f00e85c55 | 13,942 |
import math
def _get_fov(pillow_image) -> float:
"""Get the horizontal FOV of an image in radians."""
exif_data = pillow_image.getexif()
# 41989 is for 'FocalLengthIn35mmFilm'.
focal_length = exif_data[41989]
# FOV calculation, note 36 is the horizontal frame size for 35mm
# film.
return 2 * math.atan2(36, 2 * focal_length) | 9b8101010a980079d950b6151a3d5280d5eedb73 | 13,944 |
def pieChartInfoPlus(trips):
"""
Calculates the total distance per activity mode
Parameters
----------
trips : dict - Semantic information (nested)
Returns
-------
list(data): list - labels of the activity modes
list(data.values()): list - distance per activity mode
"""
labels = ["IN_PASSENGER_VEHICLE","STILL","WALKING","IN_BUS","CYCLING","FLYING","RUNNING","IN_FERRY","IN_TRAIN","SKIING","SAILING","IN_SUBWAY","IN_TRAM","IN_VEHICLE"]
data = {}
for year in trips:
for month in trips[year]:
for event in trips[year][month]:
if list(event)[0] == 'activitySegment':
try:
dist = event['activitySegment']['distance']
for label in labels:
if label == event['activitySegment']['activityType']:
data[label] = data.get(label,0) + dist
except:
print('There is no distance!')
return list(data), list(data.values()) | ad0306b2561b01a33c509b2c454f464e9c6ff8a3 | 13,946 |
def findCharacter(stringList, patternCharacter):
"""
Find the specific character from the list and return their indices
"""
return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter]) | 32cc8fb5970c6cd3cefd161b9e13e340f1645d13 | 13,949 |
def cell_trap_getter_generator(priv_attr):
""" Generates a getter function for the cell_trap property.
"""
def getter(self):
if getattr(self, priv_attr) is None:
data =\
(
self.gfpffc_bulb_1 - self.gfpffc_bulb_bg
)/self.gfpffc_bulb_bg
setattr(self, priv_attr, data)
return getattr(self, priv_attr)
return getter | 15217adbd96ce44b361444867e5d9c6d202440f4 | 13,951 |
def bg_trim(im):
"""
Function to programmatically crop card to edge.
`im` is a PIL Image Object.
"""
# This initial crop is hacky and stupid (should just be able to set device
# options) but scanner isn't 'hearing' those settings.
# w,h = im.size
im = im.crop((443, 0, 1242, 1200))
# bg = Image.new(im.mode, im.size, im.getpixel((2, 2)))
# diff = ImageChops.difference(im, bg)
# diff = ImageChops.add(diff, diff, 2.0, -100)
# bbox = diff.getbbox()
return im
# if bbox:
# return im
# else:
# print("There's been a problem.") | b5b59059aa9823cd2be385ead5cc21b135a4e24b | 13,954 |
def get_filtered_query(must_list=None, must_not_list=None):
"""Get the correct query string for a boolean filter. Accept must and
must_not lists. Use MatchList for generating the appropriate lists.
"""
bool_filter = {}
if must_list:
bool_filter['must'] = must_list
if must_not_list:
bool_filter['must_not'] = must_not_list
result = {
'query': {
'filtered': {
'filter': {
'bool': bool_filter
}
}
}
}
return result | 2190456ad7e91239bb623f7ec3d2c460e521e36f | 13,955 |
def convert_to_letter(grade):
"""Convert a decimal number to letter grade"""
grade = round(grade, 1)
if grade >= 82.5:
return 'A'
elif grade >= 65:
return 'B'
elif grade >= 55:
return 'C'
elif grade >= 50:
return 'D'
else:
return 'F' | 13ce25275750e7a27e0699078a15ba551674a941 | 13,956 |
def time_coord(cube):
"""
Return the variable attached to time axis.
Examples
--------
>>> import iris
>>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/'
... 'fmrc/us_east/US_East_Forecast_Model_Run_Collection_best.ncd')
>>> cube = iris.load_cube(url, 'sea_water_potential_temperature')
>>> timevar = time_coord(cube)
>>> timevar.name() # What is the time coordinate named?
'time'
>>> cube.coord_dims(timevar) # Is it the zeroth coordinate?
(0,)
"""
timevars = cube.coords(axis="T", dim_coords=True)
if not timevars:
timevars = [
coord for coord in cube.dim_coords if "time" in coord.name()
] # noqa
if not timevars:
ValueError(f'Could not find "time" in {repr(cube.dim_coords)}')
if len(timevars) != 1:
raise ValueError("Found more than one time coordinates!")
timevar = timevars[0]
return timevar | 12a706f956846e8471d0d7f044367c77210c4486 | 13,957 |
import re
def oneliner(s) -> str:
"""Collapse any whitespace in stringified `s` into a single space. """
return re.sub(r"[\n ]+", " ", str(s).strip()) | ed1d419b4fab8cb2deccdbc2944996ef7be28cc5 | 13,958 |
from typing import Counter
def diff_counts(values : list[int]) -> dict[int, int]:
"""Count the gaps between ordered elements in a list, by size."""
ordered = [0] + sorted(values) + [max(values) + 3]
return Counter(j - i for i, j in zip(ordered, ordered[1:])) | 897cb7fdfed85b37bd8bd7031290e34199c57574 | 13,960 |
def convert_netdict_to_pydict(dict_in):
"""Convert a net dictionary to a Python dictionary.
Parameters
----------
dict_in : dict
Net dictionary to convert.
Returns
-------
dict
Dictionary converted to Python.
"""
pydict = {}
for key in dict_in.Keys:
pydict[key] = dict_in[key]
return pydict | 6aa9bb5ac00ff92d23ff5a449d096caad0d01c9c | 13,963 |
from typing import List
def binary_search(input_array: List[int], target: int):
"""
Given a sorted input array of integers, the function looks for a target or returns None
Returns:
Target index or None
"""
if not input_array or not target:
return None
left_pointer = 0
right_pointer = len(input_array) - 1
while left_pointer <= right_pointer:
mid_pointer = (left_pointer + right_pointer) // 2
mid_value = input_array[mid_pointer]
if target > mid_value:
left_pointer = mid_pointer + 1
elif target < mid_value:
right_pointer = mid_pointer - 1
else:
return mid_pointer
return None | b9f389d1b31e5b95bb885bd638549f7775db207e | 13,964 |
def is_superuser(view):
"""Allow access to the view if the requesting user is a superuser."""
return view.request.user.is_superuser | 5a15433200634ca326c36bdc17acbc1ada4e6426 | 13,966 |
from typing import Any
import torch
import numbers
def python_scalar_to_tensor(data: Any, device: torch.device = torch.device("cpu")) -> Any:
""" Converts a Python scalar number to a torch tensor and places it on the given device. """
if isinstance(data, numbers.Number):
data = torch.tensor([data], device=device)
return data | 83e4ac093a40225f9c5fe121d9b67424f258e039 | 13,969 |
def LIGHTNING(conf):
"""Get Lightning Color code from config"""
return conf.get_color("colors", "color_lghtn") | 08781e469c7262228904e883594e475be634816b | 13,971 |
from typing import Tuple
def InterpolateValue(x: float, xy0: Tuple[float, float], xy1: Tuple[float, float]) -> float:
"""Get the position of x on the line between xy0 and xy1.
:type x: float
:type xy0: Tuple[float, float]
:type xy1: Tuple[float, float]
:return: y
:rtype: float
"""
if xy0[0] < xy1[0]:
min_xy = xy0
max_xy = xy1
else:
min_xy = xy1
max_xy = xy0
a = (max_xy[1] - max_xy[1]) / (max_xy[0] - min_xy[0])
b = min_xy[1] - a * min_xy[0]
return a * x + b | 9de4372b593fae65f772c19a8ac369315a8489d0 | 13,975 |
def boolean(prompt=None, yes='y', no='n', default=None, sensitive=False,
partial=True):
"""Prompt for a yes/no response.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
yes : str, optional
Response corresponding to 'yes'.
no : str, optional
Response correspnding to 'no'.
default : bool, optional
The return value if user inputs empty response.
sensitive : bool, optional
If True, input is case sensitive.
partial : bool, optional
Can user type 'y' or 'ye' for 'yes' and 'n' for 'no'?
Returns
-------
bool
Either True (if user selects 'yes') or False (if user selects 'no')
"""
def norm(x):
return x if sensitive else str(x).lower()
def to_bool(c):
"""Business logic for converting input to boolean."""
if partial and len(c):
if norm(yes).startswith(norm(c)):
return True
elif norm(no).startswith(norm(c)):
return False
else:
if norm(yes) == norm(c):
return True
elif norm(no) == norm(c):
return False
raise ValueError
if prompt is None:
y = '[{}]'.format(yes) if default is True else yes
n = '[{}]'.format(no) if default is False else no
prompt = '{y}/{n}? '.format(y=y, n=n)
s = input(prompt)
if (default is not None) and not s:
return default
try:
return to_bool(s)
except ValueError:
return boolean(prompt=prompt, yes=yes, no=no, default=default,
sensitive=sensitive, partial=partial) | 159c8be6004e4e9f2c5a271e36facd3610561b61 | 13,978 |
import torch
def compute_local_cost(pi, a, dx, b, dy, eps, rho, rho2, complete_cost=True):
"""Compute the local cost by averaging the distortion with the current
transport plan.
Parameters
----------
pi: torch.Tensor of size [Batch, size_X, size_Y]
transport plan used to compute local cost
a: torch.Tensor of size [Batch, size_X]
Input measure of the first mm-space.
dx: torch.Tensor of size [Batch, size_X, size_X]
Input metric of the first mm-space.
b: torch.Tensor of size [Batch, size_Y]
Input measure of the second mm-space.
dy: torch.Tensor of size [Batch, size_Y, size_Y]
Input metric of the second mm-space.
eps: float
Strength of entropic regularization.
rho: float
Strength of penalty on the first marginal of pi.
rho2: float
Strength of penalty on the first marginal of pi. If set to None it is
equal to rho.
complete_cost: bool
If set to True, computes the full local cost, otherwise it computes the
cross-part on (X,Y) to reduce computational complexity.
Returns
----------
lcost: torch.Tensor of size [Batch, size_X, size_Y]
local cost depending on the current transport plan.
"""
distxy = torch.einsum(
"ij,kj->ik", dx, torch.einsum("kl,jl->kj", dy, pi)
)
kl_pi = torch.sum(
pi * (pi / (a[:, None] * b[None, :]) + 1e-10).log()
)
if not complete_cost:
return - 2 * distxy + eps * kl_pi
mu, nu = torch.sum(pi, dim=1), torch.sum(pi, dim=0)
distxx = torch.einsum("ij,j->i", dx ** 2, mu)
distyy = torch.einsum("kl,l->k", dy ** 2, nu)
lcost = (distxx[:, None] + distyy[None, :] - 2 * distxy) + eps * kl_pi
if rho < float("Inf"):
lcost = (
lcost
+ rho
* torch.sum(mu * (mu / a + 1e-10).log())
)
if rho2 < float("Inf"):
lcost = (
lcost
+ rho2
* torch.sum(nu * (nu / b + 1e-10).log())
)
return lcost | 3d29e8ae5ef14ab30cd676eebeb6507e9cbfafca | 13,981 |
def electron_binding_energy(charge_number):
"""Return the electron binding energy for a given number of protons (unit
is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C.,
2003, Rev. Mod. Phys.,75, 1021]."""
return 1.44381e-5 * charge_number ** 2.39\
+ 1.55468e-12 * charge_number ** 5.35 | 6d5a845b1b11720b44b62500f979f0a621faca0a | 13,985 |
def parse_generic(data, key):
"""
Returns a list of (potentially disabled) choices from a dictionary.
"""
choices = []
for k, v in sorted(data[key].iteritems(), key=lambda item: item[1]):
choices.append([v, k])
return choices | 90d2f2188d5cca7adb53eebca80a80f2c46b04a7 | 13,986 |
def attrs_to_dict(attrs):
"""
Convert a list of tuples of (name, value) attributes to a single dict of attributes [name] -> value
:param attrs: List of attribute tuples
:return: Dict of attributes
"""
out = {}
for attr in attrs:
if out.get(attr[0]) is None:
out[attr[0]] = attr[1]
else:
if not isinstance(out[attr[0]], list):
out[attr[0]] = [out[attr[0]]]
out[attr[0]].append(attr[1])
return out | ccf9440d29de2f8556e694f4ab87e95f0bfd9e8a | 13,987 |
def count(i):
"""List or text. Returns the length as an integer."""
return len(i) | d8daf7cd325ce1acfb382723759ff190becd785f | 13,989 |
def find_body(view):
"""
Find first package body declaration.
"""
return view.find(r'(?im)create\s+(or\s+replace\s+)?package\s+body\s+', 0) | b592199e4ef09d079645fc82ade8efbe3c92a895 | 13,994 |
def get_num_objects(tree):
""" Get number of objects in an image.
Args:
tree: Tree element of xml file.
Returns: Number of objects.
"""
num_obj = 0
for e in tree.iter():
if e.tag == 'object':
num_obj = num_obj + 1
return num_obj | 92f937cbbf2eabdc909ef6bc1f06ccb87e0148b7 | 13,999 |
from typing import Union
def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float:
"""
Return the tolerance equivalent to the deprecated `check_less_precise`
parameter.
Parameters
----------
check_less_precise : bool or int
Returns
-------
float
Tolerance to be used as relative/absolute tolerance.
Examples
--------
>>> # Using check_less_precise as a bool:
>>> _get_tol_from_less_precise(False)
0.5e-5
>>> _get_tol_from_less_precise(True)
0.5e-3
>>> # Using check_less_precise as an int representing the decimal
>>> # tolerance intended:
>>> _get_tol_from_less_precise(2)
0.5e-2
>>> _get_tol_from_less_precise(8)
0.5e-8
"""
if isinstance(check_less_precise, bool):
if check_less_precise:
# 3-digit tolerance
return 0.5e-3
else:
# 5-digit tolerance
return 0.5e-5
else:
# Equivalent to setting checking_less_precise=<decimals>
return 0.5 * 10 ** -check_less_precise | 375f7918a04fafb4a79f77abd3f0282cdc74e992 | 14,001 |
def get_arg(cmds):
"""Accepts a split string command and validates its size.
Args:
cmds: A split command line as a list of strings.
Returns:
The string argument to the command.
Raises:
ValueError: If there is no argument.
"""
if len(cmds) != 2:
raise ValueError('%s needs an argument.' % cmds[0])
return cmds[1] | a12b9402cb824748127c9a925850a10f6a9fe022 | 14,003 |
def _magnitude_to_marker_size(v_mag):
"""Calculate the size of a matplotlib plot marker representing an object with
a given visual megnitude.
A third-degree polynomial was fit to a few hand-curated examples of
marker sizes for magnitudes, as follows:
>>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., 4., 5.])
>>> y = np.array([120., 90., 60., 30., 15., 11., 6., 1.])
>>> coeffs = np.polyfit(x, y, 3)
This function is valid over the range -2.0 < v <= 6.0; v < -2.0 returns
size = 160. and v > 6.0 returns size = 1.
Args:
v_mag: A float representing the visual magnitude of a sky object.
Returns:
A float to be used as the size of a marker depicting the sky object in a
matplotlib.plt scatterplot.
"""
if v_mag < -2.0:
size = 160.0
elif v_mag > 6.0:
size = 1.0
else:
coeffs = [-0.39439046, 6.21313285, -33.09853387, 62.07732768]
size = coeffs[0] * v_mag**3. + coeffs[1] * v_mag**2. + coeffs[2] * v_mag + coeffs[3]
return size | cb030993c5799da9f84e9bbadb9fe30680d74944 | 14,009 |
def upto(limit: str, text: str) -> str:
""" return all the text up to the limit string """
return text[0 : text.find(limit)] | 0fbe1732954c225fe8d8714badb9126c8ab72a4d | 14,010 |
def check_occuring_variables(formula,variables_to_consider,allowed_variables) :
"""
Checks if the intersection of the variables in <formula> with the variables
in <variables_to_consider> is contained in <allowed_variables>
Parameters
----------
formula : list of list of integers
The formula to consider.
variables_to_consider : list of integers
Those variables in <formula> that shall be considered.
allowed_variables : list of integers
Must be contained in <variables_to_consider>.
Gives the subset of <variables_to_consider> that may occur in <formula>
Returns
-------
True if the intersection of the variables in <formula> with <variables_to_consider>
is contained in <allowed_variables>
"""
variable_set=set(allowed_variables)
for clause in formula :
variables_in_clause = {abs(l) for l in clause if abs(l) in variables_to_consider}
if not variables_in_clause <= variable_set:
return False, [v for v in variables_in_clause if not v in variable_set]
return True, [] | 16faf544cc6f4993afb1cad356037820d54225ba | 14,012 |
def _merge_config_dicts(dct1, dct2):
"""
Return new dict created by merging two dicts, giving dct1 priority over
dct2, but giving truthy values in dct2 priority over falsey values in dct1.
"""
return {str(key): dct1.get(key) or dct2.get(key)
for key in set(dct1) | set(dct2)} | 9d66c10438027254fbac7d8cc91185a07dd9da65 | 14,015 |
def from_list(*args):
"""
Input:
args - variable number of integers represented as lists, e.g. from_list([1,0,2], [5])
Output:
new_lst - a Python array of integers represented as strings, e.g. ['102','5']
"""
new_lst = []
for lst in args:
new_string = ''
for digit in lst:
new_string += str(digit)
new_lst.append(new_string)
return new_lst | c3c0a2224433104a00ffabdadf612127d1b0ed3c | 14,017 |
def perpetuity_present_value(
continuous_cash_payment: float,
interest_rate: float,
):
"""Returns the Present Value of Perpetuity Formula.
Parameters
----------
continuous_cash_payment : float
Amount of continuous cash payment.
interest_rate : float
Interest rate, yield or discount rate.
Returns
-------
float:
Present value of perpetuity
Example
-------
>>> pv = perpetuity_present_value(5, 0.15)
>>> round(pv, 2)
33.33
"""
return continuous_cash_payment / interest_rate | 26eb398776ce4f74348b23920b99b0390c462ff9 | 14,018 |
def __avg__(list_):
"""Return average of all elements in the list."""
return sum(list_) / len(list_) | 3204d823e83bd43efccf9886acd3ae8b01e1d7a0 | 14,022 |
import requests
def check_hash(h):
"""
Do the heavy lifting. Take the hash, poll the haveibeenpwned API, and check results.
:param h: The sha1 hash to check
:return: The number of times the password has been found (0 is good!)
"""
if len(h) != 40:
raise ValueError("A sha1 hash should be 30 characters.")
h = h.upper()
chk = h[:5]
r = requests.get("https://api.pwnedpasswords.com/range/%s" % chk)
if r.status_code != 200:
raise EnvironmentError("Unable to retrieve password hashes from server.")
matches = {m: int(v) for (m, v) in [ln.split(':') for ln in r.content.decode('utf-8').split("\r\n")]}
#print("Prefix search returned %d potential matches." % len(matches))
for m in matches.keys():
if m == h[5:]:
return matches[m]
return 0 | 965dd75b5da095bc24ce6a6d733b271d9ec7aa80 | 14,028 |
def get_field_hint(config, field):
"""Get the hint given by __field_hint__ or the field name if not defined."""
return getattr(config, '__{field}_hint__'.format(field=field), field) | 0d374daf93646caf55fe436c8eb2913d22151bbc | 14,030 |
def btc(value):
"""Format value as BTC."""
return f"{value:,.8f}" | 1d883384a6052788e8fa2bedcddd723b8765f44f | 14,032 |
import time
def nagios_from_file(results_file):
"""Returns a nagios-appropriate string and return code obtained by
parsing the desired file on disk. The file on disk should be of format
%s|%s % (timestamp, nagios_string)
This file is created by various nagios checking cron jobs such as
check-rabbitmq-queues and check-rabbitmq-consumers"""
data = open(results_file).read().strip()
pieces = data.split('|')
if not len(pieces) == 4:
state = 'UNKNOWN'
ret = 3
data = "Results file malformed"
else:
timestamp = int(pieces[0])
time_diff = time.time() - timestamp
if time_diff > 60 * 2:
ret = 3
state = 'UNKNOWN'
data = "Results file is stale"
else:
ret = int(pieces[1])
state = pieces[2]
data = pieces[3]
return (ret, "%s: %s" % (state, data)) | 02697105ad5e9d01dd0eb504e232314f4d15a6a9 | 14,035 |
import math
def _width2wing(width, x, min_wing=3):
"""Convert a fractional or absolute width to integer half-width ("wing").
"""
if 0 < width < 1:
wing = int(math.ceil(len(x) * width * 0.5))
elif width >= 2 and int(width) == width:
# Ensure window width <= len(x) to avoid TypeError
width = min(width, len(x) - 1)
wing = int(width // 2)
else:
raise ValueError("width must be either a fraction between 0 and 1 "
"or an integer greater than 1 (got %s)" % width)
wing = max(wing, min_wing)
wing = min(wing, len(x) - 1)
assert wing >= 1, "Wing must be at least 1 (got %s)" % wing
return wing | 38bdb809167b19b0ef5c7fad6858d2f7016ec310 | 14,036 |
def mb_bl_ind(tr1, tr2):
"""Returns the baseline index for given track indices.
By convention, tr1 < tr2. Otherwise, a warning is printed,
and same baseline returned.
"""
if tr1 == tr2:
print("ERROR: no baseline between same tracks")
return None
if tr1 > tr2:
print("WARNING: tr1 exepcted < than tr2")
mx = max(tr1, tr2)
bl = mx*(mx-1)/2 + min(tr1, tr2)
return bl.astype(int) | 7d1bc958ca9928f54e51935510d62c45f7fc927f | 14,037 |
def datetime_format_to_js_datetime_format(format):
"""
Convert a Python datetime format to a time format suitable for use with
the datetime picker we use, http://www.malot.fr/bootstrap-datetimepicker/.
"""
converted = format
replacements = {
'%Y': 'yyyy',
'%y': 'yy',
'%m': 'mm',
'%d': 'dd',
'%H': 'hh',
'%I': 'HH',
'%M': 'ii',
'%S': 'ss',
}
for search, replace in replacements.items():
converted = converted.replace(search, replace)
return converted.strip() | a037146b17aae21831bc4c76d4500b12bc34feba | 14,040 |
def make_data(current_data):
""" Formats the given data into the required form """
x = []
n = len(current_data)
for i in range(n - 1):
x.append(current_data[i])
x.append(1)
return x, current_data[n - 1] | 04ff4ba93445895451c4c710e7aae59b9787a07d | 14,042 |
def average_over_dictionary(mydict):
"""
Average over dictionary values.
"""
ave = sum([x for x in mydict.values()])/len(mydict)
return ave | 584e8cb073c298b3790a96e2649dbacfd5716987 | 14,043 |
def treat_category(category: str) -> str:
""" Treats a list of string
Args:
category (str): the category of an url
Returns:
str: the category treated
"""
return category.lower().strip() | a4c08383bdfb40e5e64bbf576df53a7f46fc07da | 14,047 |
def _get_fully_qualified_class_name(obj):
"""
Obtains the fully qualified class name of the given object.
"""
return obj.__class__.__module__ + "." + obj.__class__.__name__ | e427991067254c2ac1963c5ae59468ec2c0835e2 | 14,049 |
import decimal
def new_decimal(value):
"""Builds a Decimal using the cleaner float `repr`"""
if isinstance(value, float):
value = repr(value)
return decimal.Decimal(value) | 023809d3db3e863f66559913f125e61236520a6a | 14,051 |
import unicodedata
def unidecode(s: str) -> str:
"""
Return ``s`` with unicode diacritics removed.
"""
combining = unicodedata.combining
return "".join(
c for c in unicodedata.normalize("NFD", s) if not combining(c)
) | 589dc0403c95e29f340070e3a9e81a6f14950c8e | 14,061 |
def AutoUpdateUpgradeRepairMessage(value, flag_name):
"""Messaging for when auto-upgrades or node auto-repairs.
Args:
value: bool, value that the flag takes.
flag_name: str, the name of the flag. Must be either autoupgrade or
autorepair
Returns:
the formatted message string.
"""
action = 'enable' if value else 'disable'
plural = flag_name + 's'
link = 'node-auto-upgrades' if flag_name == 'autoupgrade' else 'node-auto-repair'
return ('This will {0} the {1} feature for nodes. Please see '
'https://cloud.google.com/kubernetes-engine/docs/'
'{2} for more '
'information on node {3}.').format(action, flag_name, link, plural) | 7153b7aa44d6d798aa58d9328ac49097016c0879 | 14,062 |
import ast
import collections
import logging
def _get_ground_truth_detections(instances_file,
allowlist_file=None,
num_images=None):
"""Processes the annotations JSON file and returns ground truth data corresponding to allowlisted image IDs.
Args:
instances_file: COCO instances JSON file, usually named as
instances_val20xx.json.
allowlist_file: File containing COCO minival image IDs to allowlist for
evaluation, one per line.
num_images: Number of allowlisted images to pre-process. First num_images
are chosen based on sorted list of filenames. If None, all allowlisted
files are preprocessed.
Returns:
A dict mapping image id (int) to a per-image dict that contains:
'filename', 'image' & 'height' mapped to filename & image dimensions
respectively
AND
'detections' to a list of detection dicts, with each mapping:
'category_id' to COCO category id (starting with 1) &
'bbox' to a list of dimension-normalized [top, left, bottom, right]
bounding-box values.
"""
# Read JSON data into a dict.
with open(instances_file, 'r') as annotation_dump:
data_dict = ast.literal_eval(annotation_dump.readline())
image_data = collections.OrderedDict()
# Read allowlist.
if allowlist_file is not None:
with open(allowlist_file, 'r') as allowlist:
image_id_allowlist = set([int(x) for x in allowlist.readlines()])
else:
image_id_allowlist = [image['id'] for image in data_dict['images']]
# Get image names and dimensions.
for image_dict in data_dict['images']:
image_id = image_dict['id']
if image_id not in image_id_allowlist:
continue
image_data_dict = {}
image_data_dict['id'] = image_dict['id']
image_data_dict['file_name'] = image_dict['file_name']
image_data_dict['height'] = image_dict['height']
image_data_dict['width'] = image_dict['width']
image_data_dict['detections'] = []
image_data[image_id] = image_data_dict
shared_image_ids = set()
for annotation_dict in data_dict['annotations']:
image_id = annotation_dict['image_id']
if image_id in image_data:
shared_image_ids.add(image_id)
output_image_ids = sorted(shared_image_ids)
if num_images:
if num_images <= 0:
logging.warning(
'--num_images is %d, hence outputing all annotated images.',
num_images)
elif num_images > len(shared_image_ids):
logging.warning(
'--num_images (%d) is larger than the number of annotated images.',
num_images)
else:
output_image_ids = output_image_ids[:num_images]
for image_id in list(image_data):
if image_id not in output_image_ids:
del image_data[image_id]
# Get detected object annotations per image.
for annotation_dict in data_dict['annotations']:
image_id = annotation_dict['image_id']
if image_id not in output_image_ids:
continue
image_data_dict = image_data[image_id]
bbox = annotation_dict['bbox']
# bbox format is [x, y, width, height]
# Refer: http://cocodataset.org/#format-data
top = bbox[1]
left = bbox[0]
bottom = top + bbox[3]
right = left + bbox[2]
if (top > image_data_dict['height'] or left > image_data_dict['width'] or
bottom > image_data_dict['height'] or right > image_data_dict['width']):
continue
object_d = {}
object_d['bbox'] = [
top / image_data_dict['height'], left / image_data_dict['width'],
bottom / image_data_dict['height'], right / image_data_dict['width']
]
object_d['category_id'] = annotation_dict['category_id']
image_data_dict['detections'].append(object_d)
return image_data | 2650ff4ffeb13d0a7874164474fa47a82880d45d | 14,063 |
def decomp(n):
""" Retorna a decomposição em fatores primos de um inteiro em forma de dicionário onde as chaves são
as bases e o valores os expoentes.
Ex:
>>> decomp(12)
{2: 2, 3: 1}
>>> decomp(72)
{2: 3, 3: 2}
:param n: number
:return: dictionary
"""
expoente = 0
base = 2
decomposicao = {}
while n > 1:
while n % base == 0:
expoente += 1
n = n/base
if expoente > 0:
decomposicao[base] = expoente
expoente = 0
base += 1
return decomposicao | 999d8be04ffd197ebdd14c88b525eb8ca4379bb9 | 14,075 |
import requests
def sendRequest(url, type="POST", params=None, headers=None):
"""
Send a request to a URL
### Input:
- `url` (str) | the url to send the request to
- `type` (str) | the type of request (GET or POST)
- `params` (dict) | parameters to be sent with the request
- `headers` (dict) | headers to be sent with the request
### Output:
- `response` (dict) | the JSON response of the request
"""
## Perform a GET request
if type == "GET":
rawResponse = requests.get(url, params=params, headers=headers)
## Perform a POST request
else:
rawResponse = requests.post(url, params=params, headers=headers)
## Convert the response to a json object, if possible
if hasattr(rawResponse, "json"):
response = rawResponse.json()
## Otherwise, get the text response
else:
response = rawResponse.text
return response | 7f450b8eedf6405b237730b9f7d6da5277c41e7b | 14,080 |
def get_span_row_count(span):
"""
Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
Consider this table::
+--------+-----+
| foo | bar |
+--------+ |
| spam | |
+--------+ |
| goblet | |
+--------+-----+
::
>>> span = [[0, 1], [1, 1], [2, 1]]
>>> print(get_span_row_count(span))
3
"""
rows = 1
first_row = span[0][0]
for i in range(len(span)):
if span[i][0] > first_row:
rows += 1
first_row = span[i][0]
return rows | e226e0f78bd6711a7ddbe9c749ed43d1d2bc476c | 14,083 |
def get_logbook_by_name(logbook_name, conn):
"""
Get a logbook by name from a persistence backend connection
:param str logbook_name: The name of the logbook to get
:param obj conn: A persistence backend connection
:return obj logbook: The logbook with the specified name
"""
return next(
iter([i for i in conn.get_logbooks() if i.name == logbook_name])
) | 7ed83cfca3d7f0313046b39032c2b906c4bff410 | 14,085 |
from typing import List
def get_label_list(labels: List[List[int]]) -> List[int]:
"""Gets a sorted list of all the unique labels from `labels`.
Args:
labels: A list of lists, each corresponding to the label-sequence of a text.
Returns:
All the unique labels the ever appear in `labels`, given in a sorted list.
Example:
Given `labels=[[0, 0, 3, 2, 5], [4, 0], [5, 2, 3]]`, returns `[0, 2, 3, 4, 5]`.
"""
unique_labels = set()
for label in labels:
unique_labels = unique_labels | set(label)
label_list = list(unique_labels)
label_list.sort()
return label_list | be795ff63c1eaccd221289708551a8ddd02b2cc5 | 14,088 |
def format_message(date_str, node, msg):
"""Format log message"""
message = f"{date_str}: {node.site_name}: {node.location or node.model} ({node.serial}) {msg}"
return message | 53dc7e2716f935a083c36e40ad4887cfe23c0aad | 14,089 |
def _world2fig(ff, x, y):
"""
Helper function to convert world to figure coordinates.
Parameters
----------
ff : `~aplpy.FITSFigure`
`~aplpy.FITSFigure` instance.
x : ndarray
Array of x coordinates.
y : ndarray
Array of y coordinates.
Returns
-------
coordsf : tuple
Figure coordinates as tuple (xfig, yfig) of arrays.
"""
# Convert world to pixel coordinates
xp, yp = ff.world2pixel(x, y)
# Pixel to Axes coordinates
coordsa = ff._ax1.transData.transform(zip(xp, yp))
# Axes to figure coordinates
coordsf = ff._figure.transFigure.inverted().transform(coordsa)
return coordsf[:, 0], coordsf[:, 1] | 99df767d948bc1c0807b676e2178de1478a1ac71 | 14,098 |
def is_palindrome(number):
""" Returns True if `number` is a palindrome, False otherwise.
"""
num_str = str(number)
num_comparisons = len(num_str) // 2
for idx in range(num_comparisons):
if num_str[idx] != num_str[-1-idx]:
return False
return True | 391aec57bba8366d7e7ef2c8187fda377f5a786d | 14,099 |
from typing import Iterable
def flatten_list(li: Iterable):
"""Flattens a list of lists."""
if isinstance(li, Iterable):
return [a for i in li for a in flatten_list(i)]
else:
return [li] | 306536fdadf231b0a0f752bb63d7e01317819674 | 14,100 |
import re
def remove_unwanted_chars(x: str, *chars: str, to_replace: str = "") -> str:
"""Remove unwanted characters from a string."""
return re.sub(f"[{''.join(chars)}]", to_replace, x) | 4a1e25b1ad12f47f835d4f6cdbac4a6e08413077 | 14,106 |
def write_the_species_tree(annotated_species_tree, output_file):
"""
this function writes the species tree to file
args:
annotated_species_tree : a string of annotated species tree in .newick format
output_file : a file name to write to
output:
a file containing the annotated species tree
"""
with open(output_file, "w") as out:
out.write(annotated_species_tree)
print("wrote the annotated species besttree to "+output_file)
return output_file | 7db9d5fc10cd27b1e7a5e51427e7de6991a1157a | 14,107 |
import functools
def compose(*functions):
"""
A functional helper for dealing with function compositions. It ignores any None functions, and if all are None,
it returns None.
Parameters
----------
*functions
function arguments to compose
Returns
-------
function or None
The composition f(g(...)) functions.
"""
# help from here: https://mathieularose.com/function-composition-in-python/
def f_of_g(f, g):
if f is not None and g is not None:
return lambda x: f(g(x))
elif f is not None:
return f
elif g is not None:
return g
else:
return lambda x: x
if any(functions):
return functools.reduce(f_of_g, functions, lambda x: x)
else:
return None | 8a18b1e0beef43c0cfac4439fa158675a486b560 | 14,108 |
def pretty_print_list(lst, name = 'features', repr_format=True):
""" Pretty print a list to be readable.
"""
if not lst or len(lst) < 8:
if repr_format:
return lst.__repr__()
else:
return ', '.join(map(str, lst))
else:
topk = ', '.join(map(str, lst[:3]))
if repr_format:
lst_separator = "["
lst_end_separator = "]"
else:
lst_separator = ""
lst_end_separator = ""
return "{start}{topk}, ... {last}{end} (total {size} {name})".format(\
topk = topk, last = lst[-1], name = name, size = len(lst),
start = lst_separator, end = lst_end_separator) | d199261e6b9fd226256a151601d0bd86e7458fe1 | 14,109 |
def _partition(entity, sep):
"""Python2.4 doesn't have a partition method so we provide
our own that mimics str.partition from later releases.
Split the string at the first occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the separator. If the separator is not
found, return a 3-tuple containing the string itself, followed
by two empty strings.
"""
parts = entity.split(sep, 1)
if len(parts) == 2:
return parts[0], sep, parts[1]
else:
return entity, '', '' | 0172ce09bd0451eb538122bd9566a3e70d0dcc15 | 14,117 |
import json
def load_dict_from_json(filename: str) -> dict:
"""
Load the given file as a python `dict`
Parameters
----------
filename: `str` an absolute path to the json file to be loaded.
Returns
-------
`dict` The loaded json file as a python dictionary.
"""
with open(filename, 'r') as file:
return json.loads(file.read()) | 1d55e5dbcf33e7f1d21063be7b722a5ed5bc6bb3 | 14,125 |
def get_n_neighborhood_start_stop_indices_3D(volume_shape, point, n):
"""
Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the point within the 3D volume.
Note that this returns an index range where the end is *non-inclusive*! So for a point at x,y,z with 0-neighborhood (only the point itself), you will get x,x+1,y,y+1,z,z+1 as return values.
Parameters
----------
volume_shape: 3-tuple of int
The shape of the volume (e.g., whole 3D image)
point: 1D array of length 3
The x, y, and z coordinates of the query point. Must lie within the volume. This is the point around which the neighborhood will be computed.
n: int >= 0
The neighborhood size (in every direction, the neighborhood is always square). For 0, only the index of the point itself will be returned. For 1, the 26 neighbors in distance 1 plus the index of the point itself (so 27 indices) will be returned. If the point is close to the border of the volume, only the valid subset will be returned of course. For n=2 you get (up to) 125 indices.
Returns
-------
xstart: int
The x start index, inclusive.
xend: int
The x end index, exclusive.
ystart: int
The y start index, inclusive.
yend: int
The y end index, exclusive.
zstart: int
The z start index, inclusive.
zend: int
The z end index, exclusive.
Examples
--------
>>> volume = np.zeros((3, 3, 3))
>>> point = [2, 2, 2]
>>> xstart, xend, ystart, yend, zstart, zend = st.get_n_neighborhood_start_stop_indices_3D(volume.shape, point, 1) # 1-neighborhood
"""
vx = volume_shape[0]
vy = volume_shape[1]
vz = volume_shape[2]
# now set valid ones to 1
xstart = max(0, point[0]-n)
xend = min(point[0]+1+n, vx)
ystart = max(0, point[1]-n)
yend = min(point[1]+1+n, vy)
zstart= max(0, point[2]-n)
zend = min(point[2]+1+n, vz)
return xstart, xend, ystart, yend, zstart, zend | 6eb1c6f0b4ff537b3d0eb1b647b019a2d61480b7 | 14,128 |
from typing import Dict
from typing import Any
def add_to_dict_with_swapped_keys(old_dict: Dict[Any, Dict],
new_dict: Dict[Any, Dict]) -> Dict[Any, Dict]:
"""
Swap the keys of two nested dictionaries in a new dictionary.
{'Key1': {'Key2': 42}} -> {'Key2': {'Key1': 42}}
Args:
old_dict: a nested dictionary whose keys are to be swapped
new_dict: an initiated dictionary, does not have to be empty
Returns:
the new_dict with the addition of swapped keys of the old_dict
"""
for key1, nested_dict in old_dict.items():
for key2, value in nested_dict.items():
new_dict.setdefault(key2, {})[key1] = value
return new_dict | 2b4d0a0d8bd2734d8c0bc7abde1fa659454f1464 | 14,129 |
import typing
import functools
def build_simple_validator(func: typing.Callable, *args, **kwargs) -> typing.Callable[[typing.Any], typing.Any]:
"""Build a ready-to-use simple validator out of a function.
Args:
- func: callable, the function to be called to validate an input
- args: list, args to partially apply to func
- kwargs: dict, kwargs to partially apply to func
Returns:
validator: functools.partial, a partial function based on ``func``, with ``args`` and ``kwargs`` partially
applied and run through functools.update_wrapper
"""
validator = functools.partial(func, *args, **kwargs)
return functools.update_wrapper(validator, func) | cc8227cce228579e51aa05ceb25d9020d51eb199 | 14,131 |
import torch
def quat_conjugate(a: torch.Tensor) -> torch.Tensor:
"""Computes the conjugate of a quaternion.
Args:
a: quaternion to compute conjugate of, shape (N, 4)
Returns:
Conjugated `a`, shape (N, 4)
"""
shape = a.shape
a = a.reshape(-1, 4)
return torch.cat((-a[:, :3], a[:, -1:]), dim=-1).view(shape) | 530eb2a8d8b9b87de2bfcaeb48729704908131cc | 14,132 |
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
"""
if line_number == 1:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
return # Don't expect blank lines after function decorator
if (logical_line.startswith('def ') or
logical_line.startswith('class ') or
logical_line.startswith('@')):
if indent_level > 0 and blank_lines != 1:
return 0, "E301 expected 1 blank line, found %d" % blank_lines
if indent_level == 0 and blank_lines != 2:
return 0, "E302 expected 2 blank lines, found %d" % blank_lines
if blank_lines > 2:
return 0, "E303 too many blank lines (%d)" % blank_lines | 0f2d89ae662ffd39170e83f8788cf2946f7cd045 | 14,136 |
def shiny_gold_in(bag: str, rules: dict) -> bool:
"""Recursively check for shiny gold bags."""
if "shiny gold" in rules[bag].keys():
return True
elif not rules[bag]: # bag holds no others
return False
else:
for inner in rules[bag]:
if shiny_gold_in(inner, rules):
return True
return False | 1859f499b72a938a58a78af5ca1a78e9f7221731 | 14,148 |
def get_position_type(salary_plan):
"""
Given a salary plan code, map to one of the VIVO position types
"""
position_dict = {
'CPFI': 'postdoc',
'CTSY': 'courtesy-faculty',
'FA09': 'faculty',
'FA9M': 'clinical-faculty',
'FA10': 'faculty',
'FA12': 'faculty',
'FACM': 'clinical-faculty',
'FAPD': 'postdoc',
'FASU': 'faculty',
'FELL': None, # Fellowship, lump sum payment only
'FWSP': None, # student-assistant
'GA09': None, # graduate-assistant
'GA12': None, # graduate-assistant
'GASU': None, # graduate-assistant
'HOUS': 'housestaff',
'ISCR': None, # Scholarship, lump sum payment only
'OF09': 'temp-faculty',
'OF12': 'temp-faculty',
'OFSU': 'temp-faculty',
'OPSE': None, # OPS
'OPSN': None, # OPS
'STAS': None, # student-assistant
'STBW': None, # student-assistant
'TA09': 'non-academic',
'TA10': 'non-academic',
'TA12': 'non-academic',
'TASU': 'non-academic',
'TU1E': 'non-academic',
'TU2E': 'non-academic',
'TU9E': 'non-academic',
'TUSE': 'non-academic',
'TU1N': None, # TEAMS Hourly
'TU2N': None, # TEAMS Hourly
'TU9N': None, # TEAMS Hourly
'TUSN': None, # TEAMS Hourly
'US1N': None, # USPS
'US2N': None, # USPS
'US9N': None, # USPS
'USSN': None, # USPS
'US2E': 'non-academic', # USPS Exempt
}
position_type = position_dict.get(salary_plan, None)
return position_type | eaaa64bfe35d27476eb9218d6401e0565126392d | 14,149 |
def str2ms(s):
"""
Convert the time strings from an SRT file to milliseconds.
Arguments:
s: A time value in the format HH:MM:SS,mmm where H, M, S and m are
digits.
Returns:
The time string converted to an integer value in milliseconds.
"""
s = s.strip()
time, ms = s.split(",")
h, m, s = time.split(":")
return int(ms) + 1000 * (int(s) + 60 * (int(m) + 60 * int(h))) | 552f9ffbd557cc0729c035901dc1a1a1bfae66d8 | 14,153 |
import torch
def get_device(inputs):
""" Get used device of a tensor or list of tensors. """
if isinstance(inputs, torch.Tensor):
device = inputs.device
elif isinstance(inputs, (tuple, list)):
device = inputs[0].device
else:
raise TypeError(f'Inputs can be a tensor or list of tensors, got {type(inputs)} instead!')
return device | eb67cb3a5ae226c4136bc172d37225ba6a64b45f | 14,157 |
def quick_sort(sequence: list) -> list:
"""Simple implementation of the quick sort algorithm in Python
:param sequence: some mutable ordered collection with heterogeneous comparable items inside
:return: the same collection ordered by ascending
"""
if len(sequence) < 2:
return sequence
_sequence = sequence[:]
pivot = _sequence.pop()
lesser = []
greater = []
for element in _sequence:
(greater if element > pivot else lesser).append(element)
return quick_sort(lesser) + [pivot] + quick_sort(greater) | 73470224b8f149568b84c7b723097fc0c2ef353f | 14,161 |
def score_tup(t):
"""
Score an ngram tuple returned from a database ngram table. A higher scoring
term is more deserving of inclusion in the resulting acrostic
:param t: (Term string, initials string, Corpus count, Used count)
:return: Fitness score for this term
"""
term = t[0]
inits = t[1]
pop = t[2]
used = t[3]
raw = (len(term)*pop/(10*used*used*used))**(len(inits))
if "#" in term:
score = 2*raw
else:
score = raw
return max(score, 1) | eea34dbf2d6a7dec37dc95cde289560a77c72f7e | 14,163 |
import torch
def get_optimizer(parameters, lr, weight_decay):
"""
Initiate Adam optimizer with fixed parameters
Args:
parameters: filter, parameters to optimize
lr: float, initial learning rate
weight_decay: float, between 0.0 and 1.0
Return:
a torch.optim.Adam optimizer
"""
return torch.optim.Adam(parameters, lr=lr, weight_decay=weight_decay) | 54b4c6a4cd02672ebfc8ff9c850f0d601fc6510f | 14,165 |
import requests
def get_gist(url):
""" Get gist contents from gist url.
Note the gist url display the raw gist instead of usual gist page.
Args:
url (str) : url containing the raw gist instead of usual gist page.
Returns:
(str): output gist str.
"""
r = requests.get(url)
assert r.status_code==200, "Failed Page query code {}".format(r.status_code)
return r.text | 853623c31af246dc07e22ac8a7dd0b515a74a080 | 14,171 |
import re
def is_email(addr):
"""
判断是否是合法邮箱
:param addr: 邮箱地址
:return: True or False
"""
re_is_email = re.compile("^[a-z0-9]+([._-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z]+$")
if re_is_email.search(addr):
return True
else:
return False | c48d931af7f57420d4b5829da02aa72203275f0f | 14,173 |
def merge_unique(a: list, b: list) -> set:
"""
merges all of the unique values of each list into a new set
>>> merge_unique([1, 2, 3], [3, 4, 5])
{1, 2, 3, 4, 5}
"""
ret = set()
a.extend(b)
for element in a:
ret.add(element)
return ret | 6a969c6beaee46e5618d25c5714cec223ebf1686 | 14,174 |
def get_wanted_parameter(season_data, names, index_para):
""" Take in a list of players' names, a wanted parameter and return
:param season_data: a dictionary of players' statistics
:param names: a list of players' names
:param index_para: index of the wanted parameter depending on the file
:return:
a_list_of_wanted_para: a list of wanted parameter for each player
"""
a_list_of_wanted_para = []
for name in names:
stat_for_player = season_data[name]
para = stat_for_player[index_para]
a_list_of_wanted_para.append(para)
return a_list_of_wanted_para | 0d278abd79f28c922dfcacf4984af7efe14a9070 | 14,175 |
def DL_ignore(answers):
"""Return False if any dictionary-learning method was selected.
Arguments
---------
answers: dict
Previous questions answers.
Returns
-------
bool
True if DL verbosity question should be ignored.
"""
expected = ['ITKrMM', 'wKSVD', 'BPFA']
flag = [meth in answers['method'] for meth in expected]
return True not in flag | fda853fc0f959dd5302a90bc9d56f012a1d7da8f | 14,183 |
def wait(status, timeout=None, *, poll_rate="DEPRECATED"):
"""(Blocking) wait for the status object to complete
Parameters
----------
status: StatusBase
A Status object
timeout: Union[Number, None], optional
Amount of time in seconds to wait. None disables, such that wait() will
only return when either the status completes or if interrupted by the
user.
poll_rate: "DEPRECATED"
DEPRECATED. Has no effect because this does not poll.
Raises
------
WaitTimeoutError
If the status has not completed within ``timeout`` (starting from
when this method was called, not from the beginning of the action).
Exception
This is ``status.exception()``, raised if the status has finished
with an error. This may include ``TimeoutError``, which
indicates that the action itself raised ``TimeoutError``, distinct
from ``WaitTimeoutError`` above.
"""
return status.wait(timeout) | 3311714c7aee5cbbecf658bfa563826c363752e2 | 14,186 |
import re
def find_md_links(md):
"""Returns dict of links in markdown:
'regular': [foo](some.url)
'footnotes': [foo][3]
[3]: some.url
"""
# https://stackoverflow.com/a/30738268/2755116
INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)')
FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[([^\]]+)\]\[(\d+)\]')
FOOTNOTE_LINK_URL_RE = re.compile(r'\[(\d+)\]:\s+(\S+)')
links = list(INLINE_LINK_RE.findall(md))
footnote_links = dict(FOOTNOTE_LINK_TEXT_RE.findall(md))
footnote_urls = dict(FOOTNOTE_LINK_URL_RE.findall(md))
footnotes_linking = []
for key in footnote_links.keys():
footnotes_linking.append((footnote_links[key], footnote_urls[footnote_links[key]]))
return links | d630d22d571e774312516fc4005444087d23392f | 14,187 |
def epoch_time(start_time, end_time):
"""
Computes the time for each epoch in minutes and seconds.
:param start_time: start of the epoch
:param end_time: end of the epoch
:return: time in minutes and seconds
"""
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs | 8265cb78c26a96a83a1035c09a7dccb0edf8c4d0 | 14,189 |
def base_prob(phred_score):
""" Returns the probabilty that a base is incorrect, given its
Phred score.
"""
prob = 10.0**(-float(phred_score)/10)
return prob | 8231019213204e65d577ea86d1e2e0e7352a3f70 | 14,193 |
import re
def need_format(line: str) -> bool:
"""
Return true if line as a title declaration followed by content
"""
return (
(
re.search("\t+e_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+e_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("\t+e_\w*[-'\w]*\W*=\W*{\W*#", line) is None
)
or (
re.search("\t+k_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+k_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("\t+k_\w*[-'\w]*\W*=\W*{\W*#", line) is None
)
or (
re.search("\t+d_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+d_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("\t+d_\w*[-'\w]*\W*=\W*{\W*#", line) is None
)
or (
re.search("\t+c_\w*[-'\w]*\W*=", line) is not None
and re.search("\t+c_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None
and re.search("\t+c_\w*[-'\w]*\W*=\W*{\W*#", line) is None
)
) | 61576aa02a745db8b0ce0c9c4c9a4d4589e8d842 | 14,195 |
def builderFor(action, hypervisor=None, template=None, service=None):
"""
This decorator is used to supply metadata for functions which is then used to find suitable methods
during building just by these properties.
:param action: Name of the generic step/action (see planner) that this function implements
:type action: str
:param hypervisor: Name of the hypervisor that this function can be used for
:type action: str
:param template: A list of template properties this function is suitable for (e.g. OS, certain software)
:type action: [str]
:param service: Production or type of the service that this function can be used for
:type action: str
:returns: The deocorated input function with the given attribute values
:rtype: function
"""
def decorate(f):
f.action = action
f.hypervisor = hypervisor
f.template = template
f.service = service
return f
return decorate | 1dddfd8dc5dbc87e5a018fc4fb144bef8a8f98e3 | 14,197 |
def undeployed_value_only_calculator(repository, undeployed_value_tuple, deployed_value_tuple):
"""
Just return the undeployed value as the value.
This calculator can be used when there will be no deployed value.
"""
return undeployed_value_tuple[2] | 58294274d37b4c7bb9cad21bb01260986cb0d6ae | 14,198 |
import re
def _remove_inner_punctuation(string):
"""
If two strings are separated by & or -, remove
the symbol and join the strings.
Example
-------
>>> _remove_inner_punctuation("This is AT&T here")
'This is ATT here'
>>> _remove_inner_punctuation("A T & T")
'A T T'
"""
string = re.sub('[\&\-]', '', string)
return string | 4ca3e7f91e35dba2e0a34f1dfd935e004623875e | 14,199 |
import random
def random_string(length, charset):
"""
Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str
"""
n = len(charset)
return ''.join(charset[random.randrange(n)] for _ in range(length)) | 1370f86a2e696ba6030b719ec8e32631f1865e01 | 14,206 |
def reverse_spline(tck):
"""Reverse the direction of a spline (parametric or nonparametric),
without changing the range of the t (parametric) or x (nonparametric) values."""
t, c, k = tck
rt = t[-1] - t[::-1]
rc = c[::-1]
return rt, rc, k | 77c239fa8360657ed4ad4c1eb8d18493c97a84a1 | 14,209 |
import importlib
import pkgutil
def list_submodules(package, recursive=True):
"""
Recursively (optional) find the submodules from a module or directory
Args:
package (str or module): Root module or directory to load submodules from
recursive (bool, optional): Recursively find. Defaults to True.
Returns:
array: array containing module paths that can be imported
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = []
for _loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + '.' + name
results.append(full_name)
if recursive and is_pkg:
results.extend(list_submodules(full_name))
return results | a5d69affc4cd19bd3e7c67c2d006c224bbafe80d | 14,210 |
def trainee_already_marked_training_date(trainee, training_date):
"""Check whether trainee already marked the given training date.
If trainee already has training day info it means he/she answered marked the given date.
Args:
trainee(models.Trainee): trainee instance to check whether already marked the given date.
training_date(datetime.date): training date to check.
Returns:
bool. True if trainee already marked the given date, otherwise False.
"""
return bool(trainee.get_training_info(training_date=training_date)) | 138006be069201923017e0277ffec6a7c06080b4 | 14,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.