content
stringlengths 42
6.51k
|
---|
def _buildGetterOrSetter( prefix, varName ):
"""Utility function used by getterName and setterName."""
if varName[0] == '_' :
varName = varName[1:]
return prefix + varName[0].upper() + varName[1:]
|
def plugins_filter(plugins, function_name):
""" Usage inside of generate_context:
from plugins import plugins_filter
for plugin in plugins_filter(plugins, "cookies"):
context = plugin(context)
"""
return [x for x in plugins if x.cookiecutter_function == function_name]
|
def segment_times(timeseries, max_gap):
"""
Returns an N-D array where each row represents a separate segmentation of continuous data with no gaps
greater than the max gap.
"""
time_segments = []
is_contiguous = False
arr_n = -1
for i, t in enumerate(timeseries):
if not is_contiguous:
time_segments.append([t])
arr_n += 1
else:
time_segments[arr_n].append(t)
if i + 1 < len(timeseries):
is_contiguous = (timeseries[i + 1] - t) < max_gap
return time_segments
|
def get_point(inputs, x, y):
"""return point[x][y] if in the boundary, return None if not"""
if x < 0 or y < 0 or x >= len(inputs) or y >= len(inputs[0]):
return None
return inputs[x][y]
|
def get_name(fname):
"""Get the elements of the file name we need
Params:
fname -- String: The file name
c9_c8_c176_IC12_s4_l_t
Returns:
The image's component number, scan number, and hemisphere
12, 4, L
"""
if fname.endswith('.nii.gz'):
fname = fname.replace('.nii.gz', '')
name_stuff = {}
tmp = fname.split('_') # tmp is just a placeholder
elems = tmp[-4:-1] # The elements of the file name in a list
name_stuff['IC'] = elems[0][2:] # 18
name_stuff['Scan'] = elems[1][1:] # 3
name_stuff['Hemi'] = elems[2].upper()
return name_stuff
|
def getNumChannel(name):
"""retourne l'id du salon"""
index = name.find("_")
numRaid = int(name[:index])
#assert(numRaid > 0)
return numRaid
|
def get_captcha_challenge(http_body,
captcha_base_url='http://www.google.com/accounts/'):
"""Returns the URL and token for a CAPTCHA challenge issued by the server.
Args:
http_body: str The body of the HTTP response from the server which
contains the CAPTCHA challenge.
captcha_base_url: str This function returns a full URL for viewing the
challenge image which is built from the server's response. This
base_url is used as the beginning of the URL because the server
only provides the end of the URL. For example the server provides
'Captcha?ctoken=Hi...N' and the URL for the image is
'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
Returns:
A dictionary containing the information needed to repond to the CAPTCHA
challenge, the image URL and the ID token of the challenge. The
dictionary is in the form:
{'token': string identifying the CAPTCHA image,
'url': string containing the URL of the image}
Returns None if there was no CAPTCHA challenge in the response.
"""
contains_captcha_challenge = False
captcha_parameters = {}
for response_line in http_body.splitlines():
if response_line.startswith('Error=CaptchaRequired'):
contains_captcha_challenge = True
elif response_line.startswith('CaptchaToken='):
# Strip off the leading CaptchaToken=
captcha_parameters['token'] = response_line[13:]
elif response_line.startswith('CaptchaUrl='):
captcha_parameters['url'] = '%s%s' % (captcha_base_url,
response_line[11:])
if contains_captcha_challenge:
return captcha_parameters
else:
return None
|
def is_almost_subset(set1, set2, min_set_diff = 2):
"""
Return True, if no more than min_set_diff members of set2
are contained in set1.
i.e, set2 is almost a subset of set1. See example for clarity:
Example
-------
>>> is_almost_subset(set(["A","B","C","D"]), set(["A", "K"]), 2)
True
>>> is_almost_subset(set(["A","B","C","D"]), set(["A", "K"]), 1)
False
"""
return len(set(set2)-set(set1)) < min_set_diff
|
def _P_2bc(h):
"""Define the boundary between Region 2b and 2c, P=f(h)
>>> "%.3f" % _P_2bc(3516.004323)
'100.000'
"""
return 905.84278514723-0.67955786399241*h+1.2809002730136e-4*h**2
|
def sn(ok):
"""converts boolean value to +1 or -1
"""
if ok: return 1
else: return -1
|
def popcount(n: int) -> int:
"""Popcount.
Args:
n (int): an 64-bit signed or unsigned integer.
Returns:
int: popcount := count of active binary bits.
Complexity:
time: O(1)
space: O(1)
Examples:
>>> popcount(0b1010)
2
>>> popcount(0b1100100)
3
>>> popcount(-1)
64
"""
n -= (n >> 1) & 0x5555555555555555
n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333)
n = (n + (n >> 4)) & 0x0F0F0F0F0F0F0F0F
n = n + (n >> 8)
n = n + (n >> 16)
n = n + (n >> 32)
return n & 0x0000007F
|
def circular_between(start, bet, end):
"""Finds if bet is in between start and end
Arguments:
start {Integer}
bet {Integer}
end {Integer}
Returns:
Boolean -- True if it is in between, else False
"""
if end > start:
return (bet > start and bet < end)
elif end < start:
return (bet > start or bet < end)
|
def nameAndVersion(aString):
"""Splits a string into the name and version number.
Name and version must be seperated with a hyphen ('-')
or double hyphen ('--').
'TextWrangler-2.3b1' becomes ('TextWrangler', '2.3b1')
'AdobePhotoshopCS3--11.2.1' becomes ('AdobePhotoshopCS3', '11.2.1')
'MicrosoftOffice2008-12.2.1' becomes ('MicrosoftOffice2008', '12.2.1')
"""
for delim in ('--', '-'):
if aString.count(delim) > 0:
chunks = aString.split(delim)
vers = chunks.pop()
name = delim.join(chunks)
if vers[0] in '0123456789':
return (name, vers)
return (aString, '')
|
def list2cmdline_patch(seq):
"""
# windows compatible
Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
contained within. A quoted string can be embedded in an
argument.
3) A double quotation mark preceded by a backslash is
interpreted as a literal double quotation mark.
4) Backslashes are interpreted literally, unless they
immediately precede a double quotation mark.
5) If backslashes immediately precede a double quotation mark,
every pair of backslashes is interpreted as a literal
backslash. If the number of backslashes is odd, the last
backslash escapes the next double quotation mark as
described in rule 3.
"""
# See
# http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
# or search http://msdn.microsoft.com for
# "Parsing C++ Command-Line Arguments"
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to separate this argument from the others
if result:
result.append(' ')
#
if type(arg) == bytes:
try:
arg = arg.decode()
except(UnicodeDecodeError):
print('debug:')
print(arg)
arg = arg.replace(b'\xa0', b'\xc2\xa0')
arg = arg.decode()
pass
needquote = (" " in arg) or ("\t" in arg) or not arg
if needquote:
result.append('"')
for c in arg:
if c == '\\':
# Don't know if we need to double yet.
bs_buf.append(c)
elif c == '"':
# Double backslashes.
result.append('\\' * len(bs_buf) * 2)
bs_buf = []
result.append('\\"')
else:
# Normal char
if bs_buf:
result.extend(bs_buf)
bs_buf = []
result.append(c)
# Add remaining backslashes, if any.
if bs_buf:
result.extend(bs_buf)
if needquote:
result.extend(bs_buf)
result.append('"')
return ''.join(result)
|
def create_futures_regex(input_symbol: str) -> str:
"""Creates a regular expression pattern to match the standard futures symbology.
To create the regular expression pattern, the function uses the fact that within the
ICE consolidated feed all the standard futures contracts are identified by the root
symbol (a unique mnemonic based on the exchange ticker or the ISIN, where no exchange
ticker is available), prefixed with the type and the optional session indicator, a
backslash, and a delivery date (formatted as MYYdd, where M is the month code, YY
are the last two digits of the year, and dd is 2-digit day of the month that is used
only for those futures where the day of the month is required to identify the security).
The function logic allows the user to pass a complete futures name, or to pass the
root symbol prefixed by the type and optional session indicator, followed by a
backslash and the * wildcard flag. In the former case, the resulting regex expression
will be such that it will match only the specific security that is passed as an input
(for example, by passing F:FDAX\\H21, the resulting regular expression will only
match the DAX futures contract with expiration in March 2021). If only the symbol
root (with all the necessary prefixes) followed by a backslash and the * wildcard
flag, is passed as an input, the resulting regex will be such to allow matching all
the possible combinations of month year (and optionally day) of expiration.
Parameters
----------
input_symbol: str
A standard futures symbol consisting of the root symbol prefixed with the type
identifier (F) and optional session indicator. If the user wants the function to
produce a regular expression that can match all the possible combinations of
month, year (and optionally day) expirations, then the root symbol will be followed
by a backslash and the * wildcard flag (for example F:FDAX\\* will result in a
regular expression that will match all the possible combinations of root symbol,
month code, year and eventually day codes). Alternatively, if the user is only
interested in creating a regular expression that matches literally only a
specific contract, the passed instrument symbol (prefixed with the type
identifier and optional session indicator) will be followed by a backslash and a
specific maturity, identified by the month code followed by the 2-digit year code
and the 2-digit day code for those contracts that are identified also by the day
of the month.
Returns
-------
str
Depending on the input symbol, the function returns a regular expression pattern
that either matches literally a specific security symbol or one that matches all
the possible maturities of the root symbol passed as an input.
"""
if not input_symbol.endswith('*'):
symbol_components = input_symbol.split("\\")
return rf"{symbol_components[0]}\\{symbol_components[1]}"
else:
symbol_root = input_symbol.split("\\")[0]
return rf"{symbol_root}\\[A-Z][0-9]{{2,4}}"
|
def commonLeader(data, i, j):
"""Get the number of common leading elements beginning at data[i] and data[j]."""
l = 0
try:
while l < 255+9 and data[i+l] == data[j+l]:
l += 1
except IndexError:
pass # terminates
return l
|
def squares(num):
"""Squares
Arguments:
num {int} -- Upper bound for the list of squares to generate
Returns:
dict -- The squares dictionary
"""
squares = {}
if num <= 0:
return squares
for n in range(1, num + 1):
squares[n] = n * n
return squares
|
def guess_species(known_species, frame_id):
"""Returns a guess at a species based frames of known species and the
frame with a detection having unknown species.
# Arguments
known_species: Dict mapping frame to species names.
frame_id: Frame number of unknown species.
# Returns
Name of species.
"""
known_frames = sorted(known_species.keys())
if not known_frames:
return None
for i, frame in enumerate(known_frames):
if frame == frame_id:
return known_species[frame]
if frame > frame_id:
if i == 0:
return known_species[frame]
if known_species[frame] == known_species[known_frames[i - 1]]:
return known_species[frame]
return None
return known_species[known_frames[-1]]
|
def glsl_type(socket_type: str):
"""Socket to glsl type."""
if socket_type in ('RGB', 'RGBA', 'VECTOR'):
return 'vec3'
else:
return 'float'
|
def factorization(fib):
""" Numeric factorization for a fibonacci number """
print(f"initializing factorization for {fib}")
divisor = 2
values = []
# save unfactorizable values
if fib <= 5:
values.append(str(fib))
else:
while fib != 1:
# finding divisors
if fib % divisor == 0:
values.append(str(divisor))
fib = fib/divisor
else:
divisor += 1
return values
|
def hex_to_rgb(value):
"""
Return (red, green, blue) values
Input is hexadecimal color code: #rrggbb.
"""
lv = len(value)
out = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
out = tuple([x/256.0 for x in out])
return out
|
def op_signum(x):
"""Returns the sign of this mathematical object."""
if isinstance(x, list):
return [op_signum(a) for a in x]
else:
m = abs(x)
if m:
x /= m
return x
|
def _round_up_time(time, period):
"""
Rounds up time to the higher multiple of period
For example, if period=5, then time=16s will be rounded to 20s
if time=15, then time will remain 15
"""
# If time is an exact multiple of period, don't round up
if time % period == 0:
return time
time = round(time)
return time + period - (time % period)
|
def enumerate_keyed_param(param, values):
"""
Given a param string and a dict of values, returns a flat dict of keyed, enumerated params.
Each dict in the values list must pertain to a single item and its data points.
Example:
param = "InboundShipmentPlanRequestItems.member"
values = [
{'SellerSKU': 'Football2415',
'Quantity': 3},
{'SellerSKU': 'TeeballBall3251',
'Quantity': 5},
...
]
Returns:
{
'InboundShipmentPlanRequestItems.member.1.SellerSKU': 'Football2415',
'InboundShipmentPlanRequestItems.member.1.Quantity': 3,
'InboundShipmentPlanRequestItems.member.2.SellerSKU': 'TeeballBall3251',
'InboundShipmentPlanRequestItems.member.2.Quantity': 5,
...
}
"""
if not values:
# Shortcut for empty values
return {}
if not param.endswith('.'):
# Ensure the enumerated param ends in '.'
param += '.'
if not isinstance(values, (list, tuple, set)):
# If it's a single value, convert it to a list first
values = [values, ]
for val in values:
# Every value in the list must be a dict.
if not isinstance(val, dict):
# Value is not a dict: can't work on it here.
raise ValueError((
"Non-dict value detected. "
"`values` must be a list, tuple, or set; containing only dicts."
))
params = {}
for idx, val_dict in enumerate(values):
# Build the final output.
params.update({
'{param}{idx}.{key}'.format(param=param, idx=idx+1, key=k): v
for k, v in val_dict.items()
})
return params
|
def hr_min_sec_to_secs(hour: int, mins: int, second: int):
"""
Converts hours, mins and seconds and returns consolidated seconds.
Used with datetime.now() object, and its hour, minutes and seconds attributes
:param hour: int
:param mins: int
:param second: int
:return: int
"""
hour_to_seconds = hour*60*60
mins_to_seconds = mins*60
return hour_to_seconds+mins_to_seconds+second
|
def elm2ind(el, m):
"""Same as pyssht.elm2ind, but will broadcast numpy arrays"""
return el * el + el + m
|
def etag(obj):
"""Return the ETag of an object. It is a known bug that the S3 API returns ETags wrapped in quotes
see https://github.com/aws/aws-sdk-net/issue/815"""
etag = obj['ETag']
if etag[0]=='"':
return etag[1:-1]
return etag
|
def _get_name_py_version(typed):
"""Gets the name of the type depending on the python version
Args:
typed: the type of the parameter
Returns:
name of the type
"""
return typed._name if hasattr(typed, "_name") else typed.__name__
|
def get_chunked_dim_size(dim_size, split_size, idx):
"""
Computes the dim size of the chunk for provided ``idx`` given ``dim_size``
and ``split_size``.
Args:
dim_size(int): Size of the dimension being chunked.
split_size(int): The chunk size for each chunk of ``dim_size``.
idx(int): The index of chunk whose dim size is being requested.
Returns:
An int indicating the dim size of the chunk.
"""
return min(dim_size, split_size * (idx + 1)) - split_size * idx
|
def calculateDifferenceBetweenTimePeriod(time1: str, time2: str) -> str:
"""
Calculates difference between two times given in input and returns
difference
>>> calculateDifferenceBetweenTimePeriod("00:00:00","23:59:59")
'23:59:59'
"""
# Change below this
l1 = time1.split(':')
l2 = time2.split(":")
# for time1
sec1 = int(l1[2])
min1 = int(l1[1])
hr1 = int(l1[0])
# for time 2
sec2 = int(l2[2])
min2 = int(l2[1])
hr2 = int(l2[0])
if sec1 > sec2:
sec = sec1-sec2
else:
sec = sec2-sec1
if min1 > min2:
min3 = min1-min2
else:
min3 = min2-min1
if hr1 > hr2:
hr = hr1-hr2
else:
hr = hr2-hr1
hr = str(hr)
min3 = str(min3)
sec = str(sec)
string = hr+':'+min3+':'+sec
return string
|
def build_experiment_url(base_url: str) -> str:
"""
Build the URL for an experiment to be published to.
"""
return '/'.join([base_url, 'experiment'])
|
def wordcount(text):
""" Return the number of words in the given text. """
if type(text) == str:
return len(text.split(" "))
elif type(text) == list:
return len(text)
else:
raise ValueError("Text to count words for must be of type str or of type list.")
|
def divisors(integer):
"""
Create a function that takes an integer n > 1 and returns an array
with all of the integer's divisors(except for 1 and the number itself),
from smallest to largest. If the number is prime return the
string '(integer) is prime'.
"""
if type(integer) is not int:
raise TypeError
arr = list(range(2, integer))
out = []
for i in arr:
if integer % i == 0:
out.append(i)
if out == []:
return "{} is prime".format(integer)
else:
return out
|
def get_stage_list(n_stages, stage_ratios):
"""Get stage label."""
if n_stages == 3:
return [0, 1, 2]
stage_values = []
stage = 0
threshold = stage_ratios[stage] * n_stages
for x in range(n_stages):
if x >= threshold:
stage += 1
threshold += stage_ratios[stage] * n_stages
stage_values.append(stage)
return stage_values
|
def _channel_name(row, prefix="", suffix=""):
"""Formats a usable name for the repeater."""
length = 16 - len(prefix)
name = prefix + " ".join((row["CALL"], row["CITY"]))[:length]
if suffix:
length = 16 - len(suffix)
name = ("{:%d.%d}" % (length, length)).format(name) + suffix
return name
|
def getopts(argv):
"""Parse arguments passed and add them to dictionary
:param argv: arguments must be url and threads
:return: dictionary of arguments
"""
opts = {} # Empty dictionary to store key-value pairs.
while argv: # While there are arguments left to parse...
if argv[0][0] == '-': # Found a "-name value" pair.
opts[argv[0]] = argv[1] # Add key and value to the dictionary.
argv = argv[1:] # Reduce the argument list by copying it starting from index 1.
return opts
|
def compare(context, object_field, raw_data, raw_field):
"""
Compare an object field value against the raw field value it should have come from.
Args:
context (str): The context of the comparison, used for printing error messages.
object_field (Any): The value of the object field being compared.
raw_data (dict): Raw data structure we're comparing a field from.
raw_field (str): Name of the raw field we're doing the comparison on.
Returns:
bool: True if comparison was successful, False if not.
"""
if raw_field in raw_data:
result = (object_field == raw_data[raw_field])
else:
result = (object_field is None)
if not result:
print(f"field value {raw_field} did not match in {context} - object value {object_field}, "
f"raw value {raw_data.get(raw_field, None)}")
return result
|
def xtype_from_derivation(derivation):
"""Returns the script type to be used for this derivation."""
if derivation.startswith("m/84'"):
return 'p2wpkh'
elif derivation.startswith("m/49'"):
return 'p2wpkh-p2sh'
else:
return 'standard'
|
def format_punctuation(txt: str) -> str:
"""Remove or add spaces around the punctuation signs.
Args:
txt (str): stores the original text
Returns:
str: returns formatted text
"""
punctuation = (",", ".", "!", "?")
for i in range(len(txt)-1):
if txt[i] in punctuation:
# del before symbols
if txt[i-1] == " ":
txt = txt[:i-1] + txt[i:]
return format_punctuation(txt)
# add after symbols
if txt[i+1] != " " and txt[i+1] != "\n":
txt = txt[:i+1] + " " + txt[i+1:]
return format_punctuation(txt)
return txt
|
def not_found(error):
"""Error to catch page not found"""
return {"status": 404, "error": "Resource not found!"}, 404
|
def fahrenheit(celsius):
""" Convert tempature celsius into farenheit """
return ((9 * celsius) / 5) + 32
|
def default_range(start, stop):
"""[start, start + 1, ..., stop -1]"""
return range(start, stop)
|
def any_of(possibilities, to_add=''):
"""
Helper function for regex manipulation:
Construct a regex representing "any of" the given possibilities
:param possibilities: list of strings representing different word possibilities
:param to_add: string to add at the beginning of each possibility (optional)
:return: string corresponding to regex which represents any of the given possibilities
"""
assert len(possibilities) > 0
s = '(?:'
if len(to_add) > 0:
s += possibilities[0] + to_add + ' '
else:
s += possibilities[0]
for i in range(len(possibilities) - 1):
if len(to_add) > 0:
s += '|' + possibilities[i + 1] + to_add + ' '
else:
s += '|' + possibilities[i + 1]
return s + ')'
|
def interp(x, in_min, in_max, out_min, out_max):
"""Linear interpolation"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
|
def email_address_stix_pattern_producer(data):
"""Convert an email address from TC to a STIX pattern."""
return f"[email-addr:value = '{data.get('summary')}']"
|
def parse_args(args):
"""Splits comma separated argument into size and rel attribute."""
parts = args.split(",")
arg = parts[0]
rel = len(parts) > 1 and parts[1] or None
if rel:
rel_attr = ' rel="%s"' % rel
else:
rel_attr = ''
return (arg, rel_attr)
|
def sliding_window(image_width,image_height, patch_w,patch_h,adj_overlay_x=0,adj_overlay_y=0):
"""get the subset windows of each patch
Args:
image_width: width of input image
image_height: height of input image
patch_w: the width of the expected patch
patch_h: the height of the expected patch
adj_overlay_x: the extended distance (in pixel of x direction) to adjacent patch,
make each patch has overlay with adjacent patch
adj_overlay_y: the extended distance (in pixel of y direction) to adjacent patch,
make each patch has overlay with adjacent patch
Returns: The list of boundary of each patch
"""
# output split information
f_obj = open('split_image_info.txt','w')
f_obj.writelines('### This file is created by split_image.py. mosaic_patches.py need it. Do not edit it\n')
f_obj.writelines('image_width: %d\n' % image_width)
f_obj.writelines('image_height: %d\n' % image_height)
f_obj.writelines('expected patch_w: %d\n' % patch_w)
f_obj.writelines('expected patch_h: %d\n' % patch_h)
f_obj.writelines('adj_overlay_x: %d\n' % adj_overlay_x)
f_obj.writelines('adj_overlay_y: %d\n' % adj_overlay_y)
count_x = (image_width - 2*adj_overlay_x) // patch_w
count_y = (image_height - 2*adj_overlay_y) // patch_h
patch_boundary = []
for i in range(0, count_x):
f_obj.write('column %d:' % i)
for j in range(0, count_y):
f_obj.write(' %d' % (i*count_y + j))
# extend the patch
xoff = i * patch_w + (image_width - count_x*patch_w - 2*adj_overlay_x)//2
yoff = j * patch_h + (image_height - count_y*patch_h - 2*adj_overlay_y)//2
xsize = patch_w + 2*adj_overlay_x
ysize = patch_h + 2*adj_overlay_y
new_patch = (xoff, yoff, xsize, ysize)
patch_boundary.append(new_patch)
f_obj.write('\n')
f_obj.close()
return patch_boundary
|
def poly_to_box(poly):
"""Convert a list of polygons into an array of tight bounding boxes."""
x0 = min(min(p[::2]) for p in poly)
x1 = max(max(p[::2]) for p in poly)
y0 = min(min(p[1::2]) for p in poly)
y1 = max(max(p[1::2]) for p in poly)
boxes_from_polys = [x0, y0, x1, y1]
return boxes_from_polys
|
def _parse_tfnone(dic):
""" Replace dictionary values of 'none', 'true' and 'false' by their
python types. """
formatter = {'none':None, 'true':True, 'false':False}
out = {}
for k,v in dic.items():
try:
v=formatter[v.lower()]
except KeyError:
pass
out[k] = v
return out
|
def getIso639LangCode(android_lang_code):
"""Convert language code to google api supported language code
See https://cloud.google.com/translate/docs/languages
"""
if android_lang_code == 'zh-rTW':
return 'zh-TW'
elif android_lang_code == 'zh-rCN':
return 'zh-CN'
elif android_lang_code == 'pt-rPT':
return 'pt'
else:
return android_lang_code
|
def shift_leftward(n, nbits):
"""Shift positive left, or negative right. Same as n * 2**nbits"""
if nbits < 0:
return n >> -nbits
else:
return n << nbits
|
def radix_sort(vals):
"""Return sorted list as copy."""
if len(vals) <= 1:
return vals[:]
digits = len(str(max(vals)))
for power in range(digits):
buckets = [[] for _ in range(10)]
for val in vals:
trunc_val = val % (10 ** (power + 1))
idx = trunc_val // (10 ** power)
buckets[idx].append(val)
res = []
for bucket in buckets:
for val in bucket:
res.append(val)
vals = res
return vals
|
def drop_placeholders_parallel(peaks, otherpeaks):
"""Given two parallel iterables of Peak objects, `peaks` and `otherpeaks`,
for each position that is not a placeholder in `peaks`, include that Peak object
and its counterpart in `otherpeaks` in a pair of output lists.
Parameters
----------
peaks : Iterable of FittedPeak
Peak collection to filter against
otherpeaks : Iterable
Collection of objects (Peak-like) to include based upon
contents of `peaks`
Returns
-------
list
Filtered form of `peaks`
list
Filtered form of `otherpeaks`
"""
new_peaks = []
new_otherpeaks = []
for i, peak in enumerate(peaks):
peak = peaks[i]
if peak.intensity > 1:
new_peaks.append(peak)
new_otherpeaks.append(otherpeaks[i])
return new_peaks, new_otherpeaks
|
def hexKeyToBin(counts, n_qubits):
"""Generates binary representation of a hex based counts
Derived from https://sarangzambare.github.io/jekyll/update/2020/06/13/quantum-frequencies.html
Args:
counts (dict): dictionary with hex keys
n_qubits (int): number of qubits
Returns:
dict: dictionary with bin keys
n_qubits (int): number of qubits
"""
out = dict()
for key, value in counts.items():
out[format(int(key,16), f'0{int(n_qubits)}b')] = value
return out, n_qubits
|
def compute_gcd(x, y):
"""Compute gcd of two positive integers x and y"""
if x < y:
return compute_gcd(y, x)
residual = x % y
if residual == 0:
return y
if residual == 1:
return 1
return compute_gcd(y, residual)
|
def non_zero_mean_difference(own_team_scores, enemy_team_scores, neutral_scores, assassin_scores, weights=(1, 1, 1, 1)):
""" Calculates the difference between the mean of own_team_scores and the mean of the combination of enemy_team_scores, neutral_scores and assassin_scores. """
own_team_scores, enemy_team_scores, neutral_scores, assassin_scores = \
(list(map(lambda x: x * weight, scores)) for weight, scores in zip(weights, [own_team_scores, enemy_team_scores, neutral_scores, assassin_scores]))
good_scores = [score for score in own_team_scores if score != 0]
bad_scores = [score for score in enemy_team_scores + neutral_scores + assassin_scores if score != 0] # FUTURE: it's possible to weight these beforehand, either by dividing by or multiplying by certain weights. (i.e. weight >1 or <1 makes a big difference)
mean_good_scores = sum(good_scores) / len(good_scores) if len(good_scores) > 0 else 0
mean_bad_scores = sum(bad_scores) / len(bad_scores) if len(bad_scores) > 0 else 0
mean_difference = mean_good_scores - mean_bad_scores
return mean_difference
|
def getMonth(month):
"""
returns the number of the month if given a string
and returns the name of the month if given and int
"""
# months = ['January', 'February', 'March', 'April', 'May', 'June',
# 'July', 'August', 'September', 'October' 'November',
# 'December']
mons = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']
if type(month) == str:
month = month[0].upper() + month[1:3].lower()
try:
return mons.index(month) + 1
except ValueError as err:
print('Shall we list the months: {}'.format(err))
if type(month) == int:
try:
return mons[month - 1]
except IndexError as err:
print('How many months are there in the year: {}'.format(err))
|
def checkInt(n):
""" To check if the string can be converted to int type """
try:
int(n)
return True
except ValueError:
return False
|
def get_barcode(item_scanned):
"""
(str) -> str
Returns the type of item that has been scanned based on the UPC of the item that has been scanned i.e. the "item_scanned" parameter
>>>get_barcode('111111')
'SINGLES'
>>>get_barcode('666666')
'SMALL'
>>>get_barcode('242424')
'LARGE'
"""
if item_scanned == '111111':
return 'SINGLES'
elif item_scanned == '666666':
return 'SMALL'
elif item_scanned == '242424':
return 'LARGE'
elif item_scanned == '0':
return 'done'
else: print ("Oops! You entered an unrecognized Universal Price Code (UPC). Please enter an appropriate UPC for your item")
|
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided,
returning a list of the values.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
fields_found.append(another_result)
return fields_found
|
def chunk_script_section(sd, n):
"""
Split simply on period.
Problematic for string like 'Dr.' and abbreviations like 'D.M.Z.'
Params:
sd (dict) -- {'title': section title (str),
'level': level (int),
'text': section text (str)}
n (int) -- chunk size
Returns:
chunks (list) -- list of sentence strings
"""
original_sentences = [sd['title']] + sd['text'].split('.')
chunks = []
for sent in original_sentences:
sent = sent.strip()
if not sent:
continue
if len(sent) > n:
split_on = sent[:n].rfind(" ")
tmp_split = [sent[:split_on], sent[split_on:]]
while len(tmp_split[-1]) > n:
last = tmp_split.pop()
split_on = last[:n].rfind(" ")
tmp_split += [last[:split_on], last[split_on:]]
chunks.extend(tmp_split)
else:
chunks.append(sent)
return chunks
|
def concat_imports(values, sep='.'):
"""Combine import statements.
Parameters
----------
values : list-like
The values to be concatenated
sep : string
The value between the statements
Returns
-------
str
The concatenated string
"""
if len(values) >= 1:
store = []
for v in values:
if isinstance(v, (list, tuple)):
store.extend(v)
else:
store.append(v)
return sep.join(store)
else:
return ''
|
def linspace(start, stop, num):
"""Custom version of numpy's linspace to avoid numpy depenency."""
if num == 1:
return stop
h = (stop - start) / float(num)
values = [start + h * i for i in range(num+1)]
return values
|
def ddpg(loss):
""" paper : https://arxiv.org/abs/1509.02971
+ effective to use with replay buffer
- using grads from critic not from actual pollicy ( harder to conv )
"""
grads = loss
return loss
|
def isnum(a):
"""True if a is an integer or floating-point number."""
if isinstance(a, (int, float)):
return 1
else:
return 0
|
def relative(p1, p2, r):
"""pass"""
x = p1[0] + r*(p2[0] - p1[0])
y = p1[1] + r*(p2[1] - p1[1])
return x, y
|
def _permutation_worker(k: int, items: list) -> list:
"""The kth Johnson-Trotter permutation of all items."""
n = len(items)
if n <= 1:
return items
else:
group = k // n
item = k % n
position = n - item - 1 if group % 2 == 0 else item
dummy = _permutation_worker(group, items[0 : (n - 1)])
dummy.insert(position, items[n - 1])
return dummy
|
def filter_credit_score(credit_score, bank_list):
"""Filters the bank list by the mininim allowed credit score set by the bank.
Args:
credit_score (int): The applicant's credit score.
bank_list (list of lists): The available bank loans.
Returns:
A list of qualifying bank loans.
"""
credit_score_approval_list = []
for bank in bank_list:
if credit_score >= int(bank[4]):
credit_score_approval_list.append(bank)
return credit_score_approval_list
|
def sigma(alpha, n):
"""
Clauset et al 2007 equation 3.2:
sigma = (alpha-1)/sqrt(n)
"""
return (alpha-1.) / n**0.5
|
def convert_inds_to_text(inds, ind2word, preprocess=False):
""" convert the given indexes back to text """
words = [ind2word[word] for word in inds]
return words
|
def get_adjacent_seat_positions(row, column, max_row, max_column):
"""Get positions of the seats adjacent to the seat with row and column."""
positions = []
for cur_row in range(row - 1, row + 2):
for cur_column in range(column - 1, column + 2):
if cur_row == row and cur_column == column:
continue
if 0 <= cur_row <= max_row and 0 <= cur_column <= max_column:
positions.append((cur_row, cur_column))
return positions
|
def build_mask(items, predicate, d=None, c=None):
"""
Applies the predicate to each item, taking the disjunction of the results.
Will add d as a disjunct, and then finally will take that in
conjunction with c. Returns the value.
"""
q = None
for i in items:
if q is None:
q = predicate(i)
else:
q |= predicate(i)
if d is not None:
q = d | q
if c is not None:
q = c & q
return q
|
def prob_downsample(local_d: int,
target_d: int,
outlier_d: int):
"""
Given local, target and outlier density (as estimated by KNN) calculate
the probability of retaining the event. If local density is less than or
equal to the outlier density, returns a probability of 0 (event will be
discarded). If the local density is greater than the outlier density
but less than the target density, return a value of 1 (absolutely keep this
event). If the local density is greater than the target density, then
the probability of retention is the ratio between the target and local
density.
Parameters
----------
local_d: int
target_d: int
outlier_d: int
Returns
-------
float
Value between 0 and 1
"""
if local_d <= outlier_d:
return 0
if outlier_d < local_d <= target_d:
return 1
if local_d > target_d:
return target_d / local_d
|
def bin2hex(x):
"""
Convert binary string to hexadecimal string.
For instance: '11010' -> '1a'
"""
return hex(int(x, 2))[2:]
|
def _remove_dups(elems, txids_seen):
"""API data has duplicate transaction data. Clean it."""
out = []
for elem in elems:
txid = elem["txhash"]
if txid in txids_seen:
continue
out.append(elem)
txids_seen.add(txid)
return out
|
def is_valid_file(ext, argument):
""" Checks if file format is compatible """
formats = {
'input_ligand_path': ['pdb'],
'output_ligand_path': ['pdbqt'],
'input_receptor_path': ['pdb'],
'output_receptor_path': ['pdbqt'],
'input_ligand_pdbqt_path': ['pdbqt'],
'input_receptor_pdbqt_path': ['pdbqt'],
'input_box_path': ['pdb'],
'output_pdbqt_path': ['pdbqt'],
'output_log_path': ['log']
}
return ext in formats[argument]
|
def construct_none_displayer(entries, placeholder='-'):
"""Return a string to be used as a placeholder for an empty option.
The length of the placeholder is based on the length of the longest
option in a list of entries.
"""
# Convert to string as a precaution to figure out length.
entries = [str(e) for e in entries]
# Get length of longest string from list
max_len = len(max(entries, key=len))
# Insert display option for choosing None
if max_len > 4:
none_dislplayer = placeholder * (max_len+1)
else:
none_dislplayer = placeholder * 5
return none_dislplayer
|
def str_to_bool(boolstr, default=False):
"""Convert a string to a boolean."""
boolstr = boolstr.lower()
if boolstr in ("true", "yes", "on", "1"):
return True
elif boolstr in ("false", "no", "off", "0"):
return False
else:
return default
|
def get_biggest_value_less_or_equal_to(iter: list or range, value):
"""Returns the biggest element from the list that is less or equal to the value. Return None if not found
"""
if type(iter) == list:
i = [x for x in iter if x <= value]
return max(i) if i else None
elif type(iter) == range:
if value in range(iter.start, iter.stop): # Value lies within this range, return step-aware value
return value - ((value - iter.start) % iter.step)
elif value > iter.stop-1: # value is greater than range, return last element of range
return iter.stop-1
else: # value is less than range, return None
return None
else:
raise ValueError("iter must be of type list or range")
|
def replace_month(json_str):
"""Replace month number by its name."""
json_str = json_str.replace('-01"', '-Ene"')
json_str = json_str.replace('-02"', '-Feb"')
json_str = json_str.replace('-03"', '-Mar"')
json_str = json_str.replace('-04"', '-Abr"')
json_str = json_str.replace('-05"', '-May"')
json_str = json_str.replace('-06"', '-Jun"')
json_str = json_str.replace('-07"', '-Jul"')
json_str = json_str.replace('-08"', '-Ago"')
json_str = json_str.replace('-09"', '-Sep"')
json_str = json_str.replace('-10"', '-Oct"')
json_str = json_str.replace('-11"', '-Nov"')
json_str = json_str.replace('-12"', '-Dic"')
return json_str
|
def max_length(x, y):
"""
This function can be passed to a reduce to determine the maximum length of
a list within a list of lists.
"""
if type(x) == list and type(y) == list:
return max(len(x), len(y))
elif type(x) == list and type(y) == int:
return max(len(x), y)
elif type(x) == int and type(y) == list:
return max(x, len(y))
elif type(x) == int and type(y) == int:
return max(x, y)
if type(x) != int or type(x) != list:
raise TypeError("Invalid type: " + str(type(x)))
if type(y) != int or type(y) != list:
raise TypeError("Invalid type: " + str(type(x)))
|
def find_contiguous_ids(job_ids):
"""Return the contiguous job ids in the given list.
Returns
-------
contiguous_job_ids : str
The job ids organized in contiguous sets.
"""
import operator
import itertools
contiguous_job_ids = []
for k, g in itertools.groupby(enumerate(job_ids), lambda x: x[0]-x[1]):
group = list(map(operator.itemgetter(1), g))
if len(group) == 1:
contiguous_job_ids.append(str(group[0]))
else:
contiguous_job_ids.append('{}-{}'.format(group[0], group[-1]))
return ','.join(contiguous_job_ids)
|
def parse_attributes(attribute_string):
"""Returns region of attribute string between first pair of double quotes"""
attribute_string = attribute_string[attribute_string.find('"')+1:]
if '"' in attribute_string:
attribute_string = attribute_string[:attribute_string.find('"')]
return attribute_string
|
def get_object_instances(predictions, target, confidence):
"""
Return the number of instances of a target class.
"""
targets_identified = [
pred for pred in predictions if pred['label'] == target and float(pred['confidence']) >= confidence]
return len(targets_identified)
|
def getSquareSegmentDistance(p, p1, p2):
"""
Square distance between point and a segment
"""
x = p1[0]
y = p1[1]
dx = p2[0] - x
dy = p2[1] - y
if dx != 0 or dy != 0:
t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy)
if t > 1:
x = p2[0]
y = p2[1]
elif t > 0:
x += dx * t
y += dy * t
dx = p[0] - x
dy = p[1] - y
return dx * dx + dy * dy
|
def millis_to_srt(millis):
"""Convert milliseconds time to the SRT subtitles format time string."""
result = ''
# milliseconds
milliseconds = millis % 1000
result = ('%03d' % milliseconds) + result
millis = (millis - milliseconds) / 1000
# seconds
seconds = millis % 60
result = ('%02d,' % seconds) + result
millis = (millis - seconds) / 60
# minutes
minutes = millis % 60
result = ('%02d:' % minutes) + result
millis = (millis - minutes) / 60
# hours
result = ('%02d:' % millis) + result
# ready
return result
|
def progress_report(current, previous):
"""Display the change in progress from previous to current."""
context = {
'current': current,
'previous': previous,
'scope_change': None,
'complete_change': None,
}
if current and previous:
if current.total < previous.total:
context['scope_change'] = 'down'
elif current.total > previous.total:
context['scope_change'] = 'up'
if current.pct_complete < previous.pct_complete:
context['complete_change'] = 'down'
elif current.pct_complete > previous.pct_complete:
context['complete_change'] = 'up'
return context
|
def generate_storage_options(args):
"""
Generate stoage options from args
:param args:
:return:
"""
if (not args.azure_tenant_id or
not args.azure_storage_account_name or
not args.azure_client_id or
not args.azure_client_secret):
return {}
else:
return {'tenant_id': args.azure_tenant_id,
'client_id': args.azure_client_id,
'client_secret': args.azure_client_secret,
'account_name': args.azure_storage_account_name}
|
def splitIndex(index):
"""Normalize a casual index like "one, two, 3,four" to canonical form like ["one", "two", 3, "four"]."""
out = [x.strip() for x in index.split(",")]
for i in range(len(out)):
try:
out[i] = int(out[i])
except ValueError:
pass
return out
|
def parse_results_for_matching_tag(output, image_tag):
"""This function is extremely reliant on the output format of
resnet_18/classify_images.py"""
match = False
if image_tag in output:
top_match = output.split("\n")[1]
if image_tag in top_match:
match = True
return match
|
def split_ver_str(ver_str):
"""Split version string into numeric components.
Return list of components as numbers additionally checking
that all components are correct (i.e. can be converted to numbers).
"""
ver_list = []
for c in ver_str.split('.')[0:3]:
if not c.isdecimal():
raise RuntimeError("Malformed version string '{}'. "
"Component '{}' is not an integer."
.format(ver_str, c))
ver_list.append(int(c))
return ver_list
|
def applyAprioriPrinciple(itemSets, selectedItemSets):
"""
Apply apriori principle
'if an item set is frequent,
then all of its subsets must also be frequent.'
"""
if len(selectedItemSets) == 0:
return []
returnItemSets = []
subsetLen = None
for s in itemSets:
allSubsetPresent = True
if not subsetLen:
subsetLen = len(s) - 1
l = s + s[0 : subsetLen - 1]
for i in range(len(s)):
subset = tuple(sorted(l[i : i + subsetLen]))
if subset not in selectedItemSets:
print('Subset', subset, 'not present, ignoring itemset', s ,'as per apriori principle')
allSubsetPresent = False
break
if allSubsetPresent:
returnItemSets.append(s)
return returnItemSets
|
def hex_to_rgb(hex_str):
""" translate tkinter hex color code #ffffff to rgb tuple of integers
https://stackoverflow.com/a/29643643/6929343
"""
h = hex_str.lstrip('#')
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
|
def is_prime_slow(n):
""" Slow trial division primality testing algorithm
(Always correct)
"""
if n <= 1:
return False
x = 2
while x * x <= n:
if n % x == 0:
return False
x += 1
return True
|
def checkanswer(possible, guess):
""" Case insensitive check of answer.
Assume inputs are in the correct format, since takeQuiz() accounts
for
Args:
possible (list): List of possible answers for question.
guess (string): User's guess for question.
Returns:
bool: True if guess is in possible, False otherwise.
"""
#In order to be user friendly, check for strings that are lowercased
for answer in possible:
if guess.lower() == answer.lower():
return True
return False
|
def _get_received_date(received_header):
"""
Helper function to grab the date part of a Received email header.
"""
received_header = received_header.replace('\r', '').replace('\n', '')
date = received_header.split(';')
try:
return date[-1]
except:
''
|
def has_any_letters(text):
""" Check if the text has any letters in it """
# result = re.search("[A-Za-z]", text) # works only with english letters
result = any(
c.isalpha() for c in text
) # works with any letters - english or non-english
return result
|
def time_to_string(seconds):
"""Return a readable time format"""
if seconds == 0:
return '0 seconds'
h, s = divmod(seconds, 3600)
m, s = divmod(s, 60)
if h != 1:
h_s = 'hours'
else:
h_s = 'hour'
if m != 1:
m_s = 'minutes'
else:
m_s = 'minute'
if s != 1:
s_s = 'seconds'
else:
s_s = 'second'
time_string = ''
if h:
time_string = f'{int(h)} {h_s}, {int(m)} {m_s} and {int(s)} {s_s}'
elif m:
time_string = f'{int(m)} {m_s} and {int(s)} {s_s}'
else:
time_string = f'{int(s)} {s_s}'
return time_string
|
def bit(b):
"""Internal use only"""
# return bit b on
return 2**b
|
def to_float(string):
""" Convert string to float
>>> to_float("42.0")
42.0
"""
try:
number = float(string)
except:
number = 0.0
return number
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.