content stringlengths 42 6.51k |
|---|
def buffer_to_bytes(buf):
"""Cast a buffer object to bytes"""
if not isinstance(buf, bytes):
buf = bytes(buf)
return buf |
def s2n_motorola(str):
"""Extract multibyte integer in Motorola format (little endian)."""
x = 0
for c in str:
x = (x << 8) | ord(c)
return x |
def split_multiple(value):
"""Used to split multiple terms separated by comma (e.g. keywords)."""
result = list()
for item in value.split(','):
item = item.strip()
if item:
result.append(item)
return result |
def is_object_ref(d):
"""
Checks if a dictionary is a reference object. The dictionary is considered to be a
reference object when it contains non-empty 'id' and 'type' fields.
:type d: dict
:return: True if passed dictionary is a reference object, otherwise False
"""
has_id = 'id' in d.keys() and d['id']
has_type = 'type' in d.keys() and d['type']
return has_id and has_type |
def validate_value(arg):
"""Function: validate_value
Description: Test function.
Arguments:
(input) arg
"""
return arg == "value" |
def _get_matching_stream(smap, itag):
""" Return the url and signature for a stream matching itag in smap. """
for x in smap:
if x['itag'] == itag and x.get("s"):
return x['url'], x['s']
raise IOError("Sorry this video is not currently supported by pafy") |
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{} week(s) and {} day(s).".format(weeks, remainder) |
def find_first_different_block(cipher_bytes1, cipher_bytes2, block_size):
"""
If there are differences in cipher_bytes (in a block), return index of 1st byte in that block.
If they are the same, return -1.
If they have different length, and everything is the same (except those longer blocks), return index
of 1st byte in longer block, which is len(shorter_byte) + 1
"""
# make sure byte2 is the shorter block
if len(cipher_bytes2) > len(cipher_bytes1):
cipher_bytes1, cipher_bytes2 = cipher_bytes2, cipher_bytes1
# compare
for start in range(0, len(cipher_bytes2), block_size):
end = start + block_size
if cipher_bytes1[start:end] != cipher_bytes2[start:end]:
return start
# everything is equal, check their length
if len(cipher_bytes2) == len(cipher_bytes1):
return -1
else:
return len(cipher_bytes2) + 1 |
def deltafmt(delta, decimals=None):
"""
Returns a human readable representation of a time with the format:
[[[Ih]Jm]K[.L]s
For example: 6h5m23s
If "decimals" is specified, the seconds will be output with that many decimal places.
If not, there will be two places for times less than 1 minute, one place for times
less than 10 minutes, and zero places otherwise
"""
try:
delta = float(delta)
except:
return '(bad delta: %s)' % delta
if delta < 60:
if decimals is None:
decimals = 2
return ("{0:." + str(decimals) + "f}s").format(delta)
mins = int(delta / 60)
secs = delta - mins * 60
if delta < 600:
if decimals is None:
decimals = 1
return ("{0:d}m{1:." + str(decimals) + "f}s").format(mins, secs)
if decimals is None:
decimals = 0
hours = int(mins / 60)
mins -= hours * 60
if delta < 3600:
return "{0:d}m{1:.0f}s".format(mins, secs)
else:
return ("{0:d}h{1:d}m{2:." + str(decimals) + "f}s").format(hours, mins, secs) |
def interp2(x, xdata, ydata): # --DC
"""LINEAR INTERPOLATION/EXTRAPOLATION GIVEN TWO DATA POINTS"""
m = (ydata[1] - ydata[0]) / (xdata[1] - xdata[0])
b = ydata[1] - m * xdata[1]
y = m * x + b
return y |
def flatten(obj, path=""):
"""Flatten nested dicts into hierarchical keys."""
result = {}
if isinstance(obj, dict):
for key, item in obj.items():
result.update(flatten(item, path=(path + "." if path else "") + key.lower()))
elif isinstance(obj, (str, int, float, bool)):
result[path] = obj
return result |
def shortest_path_from_list(file_name, name_list):
""" Determines the shortest path to a file in a list of candidates.
Args:
file_name: A string specifying the name of the matching candidates.
name_list: A list of strings specifying paths.
Returns:
A string specifying the candidate with the shortest path or None.
"""
candidates = [path for path in name_list if path.split('/')[-1] == file_name]
if not candidates:
return None
shortest_path = candidates[0]
for candidate in candidates:
if len(candidate.split('/')) < len(shortest_path.split('/')):
shortest_path = candidate
return shortest_path |
def cucdiv(real1, imag1, real2, imag2):
"""
Compute the quotient of the given complex numbers.
Assuming that `x` is the complex number composed of
the real part `real1` and imaginary part `imag1`,
while `y` consists of `real2` and `imag2`,
the result is computed by the equation `x / y`.
"""
divisor = real2 * real2 + imag2 * imag2
res_real = (real1 * real2 + imag1 * imag2) / divisor
res_imag = (imag1 * real2 - real1 * imag2) / divisor
return res_real, res_imag |
def is_valid_unknown_header(header):
"""Check whether characters of a header are all valid.
:type header: str
:rtype : bool
:param header: The header.
:return: True if so.
"""
# Construct valid characters.
valid_char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Check all characters.
for ch in header:
if valid_char.find(ch) == -1:
return False
return True |
def pad_string(string: str, length: int) -> str:
"""Pads a string to specified length.
Args:
string: the text string to be padded with spaces
length: the length of the returned string
Returns:
A string exactly length characters long.
This is a helper function to hide the messy ljust()[] syntax, which is
needed many places in pyfind because of the re-use of a single console
line for running status information about which folders are being searched.
"""
return string[:length].ljust(length) |
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
total = 0
for i in range(len(prices) - 1):
total += max(prices[i + 1] - prices[i], 0)
return total |
def link_parse(link, page_type):
"""Returns the owner and album ids for an album or the screen
name of either user or group page.
Parameters:
-----------
:link: str, e.g. https://vk.com/album11111_111111111
or https://vk.com/club1;
:page_type: str, one of {'album', 'user', 'group'};
:returns: str or tuple of ints, e.g. 'club1'
or (11111, 111111111)
"""
link_end = link.split('/')[-1]
if page_type == 'album':
ids = link_end.split('album')[1].split('_')
return int(ids[0]), int(ids[1])
else:
return link_end |
def list_dim(lst):
""" Function to return the dimension of a list (e.g. nested list).
"""
if not type(lst) == list:
return 0
return len(lst) + list_dim(lst[0]) |
def fix_thread_string(tstr):
"""
Takes a string with numbers separated by period and possibly with /
at end, and outputs a string with 3 digit numbers separated by periods.
"""
remove_slash = lambda s: s[:-1] if s[-1] == '/' else s
three_digits = lambda s: "%03d" % int(s)
return '.'.join( map(three_digits, map(remove_slash, tstr.split('.')))) |
def filter_today_probs(done, today_probs):
"""Filter today's problems from done."""
today_prob_id = set(x[0] for x in today_probs)
done = list(filter(lambda x: x[0] not in today_prob_id,
done))
return done |
def sim_avg(terms1, terms2, sem_sim):
"""Similarity between two term sets based on average
"""
sims = []
for t1 in terms1:
for t2 in terms2:
sim = sem_sim(t1, t2)
if sim is not None:
sims.append(sim)
if not sims:
return
return round(sum(sims) / len(sims), 3) |
def dir_filter(item):
"""
Accept each item which doesn't start with _
:type item: str
:param item: a string item to filter
:return: true if item doesn't start with _
"""
return not item.startswith("_") |
def HasCombine(r):
"""Whether structure involves Combine predicate."""
if isinstance(r, dict):
member_index = sorted(r.keys())
elif isinstance(r, list):
member_index = range(len(r))
else:
assert False, (
'HasCombine should be called on list or dict. Got: %s' % str(r))
if isinstance(r, dict):
if 'predicate_name' in r and r['predicate_name'] == 'Combine':
return True
for k in member_index:
if isinstance(r[k], dict) or isinstance(r[k], list):
if HasCombine(r[k]):
return True
return False |
def relative_index(list_, value):
"""
Returns on which the given `value` would be inserted into the given list.
Parameters
----------
list_ : `list` of `Any`
The list o which value would be inserted.
value : `Any`
The value what would be inserted.
Returns
-------
relative_index : `int`
"""
bot = 0
top = len(list_)
while True:
if bot < top:
half = (bot+top)>>1
if list_[half] < value:
bot = half+1
else:
top = half
continue
return bot |
def inverse(a, n, strict = True):
"""
Compute the inverse of a modulo n using the Extended Euclidean algorithm.
If strict is True (default), raises an error if a is not invertible.
Otherwise, a number b is output such that a*b % n == gcd(a, b).
"""
b, x, y = n, 0, 1
while a != 0:
k = int(b // a)
b, a, x, y = a, b - k*a, y, x - k*y
if strict and b not in [-1, 1]:
raise ValueError("input not invertible")
return (b*x) % n |
def compute_border_indices(J, i0, i1):
"""
Computes border indices at all scales which correspond to the original
signal boundaries after padding.
At the finest resolution,
original_signal = padded_signal[..., i0:i1].
This function finds the integers i0, i1 for all temporal subsamplings
by 2**J, being conservative on the indices.
Parameters
----------
J : int
maximal subsampling by 2**J
i0 : int
start index of the original signal at the finest resolution
i1 : int
end index (excluded) of the original signal at the finest resolution
Returns
-------
ind_start, ind_end: dictionaries with keys in [0, ..., J] such that the
original signal is in padded_signal[ind_start[j]:ind_end[j]]
after subsampling by 2**j
"""
ind_start = {0: i0}
ind_end = {0: i1}
for j in range(1, J + 1):
ind_start[j] = (ind_start[j - 1] // 2) + (ind_start[j - 1] % 2)
ind_end[j] = (ind_end[j - 1] // 2) + (ind_end[j - 1] % 2)
return ind_start, ind_end |
def ping_parser(line):
"""When Twitch pings, the server ,ust pong back or be dropped."""
if line == 'PING :tmi.twitch.tv':
return 'PONG :tmi.twitch.tv'
return None |
def create_unique(dic):
"""
create unique identifier from the dict
"""
return dict(zip(range(1, len(dic.keys()) + 1), dic.keys())) |
def type_name(cls):
"""Get the name of a class."""
if not cls:
return '(none)'
return '{}.{}'.format(cls.__module__, cls.__name__) |
def linear_range_transform(tensor, from_range, to_range):
"""
Linearly interpolate from the from_range into to_range.
For example, if from_range = (0,1), and to_range=(-2, 5), then 0 is mapped
to -2 and 1 is mapped to 5, and all the values in-between are linearly
interpolated.
* tensor: a numpy or Pytorch tensor, or a scalar.
"""
fmin, fmax = from_range
tmin, tmax = to_range
return (tensor - fmin) / float(fmax - fmin) * (tmax - tmin) + tmin |
def parse_rule(l, cats):
"""Parses a sound change rule or category.
Given a line l with the format 'a > b / c_d ! e_f', produces a dict of
the form
{
'from': 'a',
'to': 'b',
'before': 'c',
'after': 'd',
'unbefore': 'e',
'unafter': 'f'
}.
If l is of the form 'a > b / c_d ! e_f | g > h / i_j ! k_l', the output is
a list of the '|' delimited rules.
If l is of the form 'a = b c d', the output is a dict of the form
{
'cat_name': 'a',
'category': ['b', 'c', 'd']
}. Category names in curly brackets are expanded.
Args:
l: The line of text to parse.
cats: The dict of categories to use in the rule.
Returns:
A dict representing either a sound change rule or category, or a list
of several sound changes.
"""
word_start = r'(?<=^|\s)'
word_end = r'(?=$|\s)'
out = {}
if len(l.split(' = ')) == 2:
# If there is an equals sign, it's a category
out['cat_name'] = l.split(' = ')[0].strip()
category = l.split(' = ')[1]
# expand categories
for c in cats:
category = category.replace('{' + c + '}', ' '.join(cats[c]))
out['category'] = category.split()
else:
if len(l.split(' | ')) > 1:
# It's a list of sound changes
return [parse_rule(ll, cats) for ll in l.split(' | ')]
# Otherwise, it's a sound change rule
try:
# Attempt to set 'from' and 'to'. If there isn't a ' > ', it will
# raise an IndexError when trying to set 'to', so 'from' will be
# set, but 'to' will not. This could be used when parsing a rule to
# be used as a search pattern, and not as a sound change. Need to
# split on ' / ' and ' ! ' in case it is being used in this way.
out['from'] = l.split(' > ')[0].split(' / ')[0].split(' ! ')[0]
# Treat '0' like ''
if out['from'] == '0':
out['from'] = ''
out['to'] = l.split(' > ')[1].split(' / ')[0].split(' ! ')[0]
# Treat '0' like ''
if out['to'] == '0':
out['to'] = ''
except IndexError:
pass
try:
# Attempt to set 'before' and 'after'. If there isn't a ' / ', it
# will raise an IndexError, and neither will be set. If there isn't
# a '_', it will raise an IndexError when trying to set 'after', so
# 'before' will be set, but 'after' will not.
out['before'] = l.split(' / ')[1].split('_')[0].split(' ! ')[0]
out['before'] = out['before'].replace('#', word_start)
out['after'] = l.split(' / ')[1].split('_')[1].split(' ! ')[0]
out['after'] = out['after'].replace('#', word_end)
except IndexError:
pass
try:
# Attempt to set 'unbefore' and 'unafter'. Same comments apply as
# for 'before' and 'after'. Note that the negative conditions must
# come after the positive conditions, if both exist.
out['unbefore'] = l.split(' ! ')[1].split('_')[0]
out['unbefore'] = out['unbefore'].replace('#', word_start)
out['unafter'] = l.split(' ! ')[1].split('_')[1]
out['unafter'] = out['unafter'].replace('#', word_start)
except IndexError:
pass
return out |
def format_size(size_bytes):
"""
Format size in bytes approximately as B/kB/MB/GB/...
>>> format_size(2094521)
2.1 MB
"""
if size_bytes < 1e3:
return "{}B".format(size_bytes)
elif size_bytes < 1e6:
return "{:.1}kB".format(size_bytes / 1e3)
elif size_bytes < 1e9:
return "{:.1}MB".format(size_bytes / 1e6)
elif size_bytes < 1e12:
return "{:.1}GB".format(size_bytes / 1e9)
else:
return "{:.1}TB".format(size_bytes / 1e12) |
def FunList(List):
"""[Takes list and prints it vertically assigning each item its index number on CLI]
Args:
List ([string]): [The items to be displayed]
Returns:
[string]: [a string displaying entries vertically with its indexes]
"""
rtnList = "\n"
for i in range(len(List)):
rtnList += f"{i+1} - {List[i]}\n"
return rtnList |
def method_2(lst):
""" Using sum() function """
lst_sum = sum(lst)
print(f'method 2: {lst_sum}')
return lst_sum |
def serialize(expr):
"""
Return code to write expression to buffer.
:param expr str: string python expression that is evaluated for serialization
:returns str: python call to write value returned by expr to serialization buffer
"""
return 'buff.write(%s)' % expr |
def count_char(char, word):
"""Counts the characters in word"""
return word.count(char)
# If you want to do it manually try a for loop |
def full_term_match(text, full_term, case_sensitive):
"""Counts the match for full terms according to the case_sensitive option
"""
if not case_sensitive:
text = text.lower()
full_term = full_term.lower()
return 1 if text == full_term else 0 |
def dependency_mapping(dep):
"""
+-----------+-----------------------------------+
| EGrid Tag | Dependency Tag |
+===========+===================================+
| S | nsub, csubj, csubjpass, dsubjpass |
+-----------+-----------------------------------+
| O | iobj, obj, pobj, dobj |
+-----------+-----------------------------------+
| X | For any other dependency tag |
+-----------+-----------------------------------+
"""
S = ['nsubj', 'csubj', 'csubjpass', 'dsubjpass']
O = ['iobj', 'obj', 'pobj', 'dobj']
if S.count(dep) == 1:
return 'S'
if O.count(dep) == 1:
return 'O'
return 'X' |
def indexMultiple(x,value):
"""
Return indexes in x with multiple values.
"""
return [ i[0] for i in enumerate(x) if i[1] == value ] |
def dec_to_bin(number):
"""
Returns the string representation of a binary
number.
:param number: int, base 10
:return: str, string representation base 2
>>> assert(dec_to_bin(10) == '1010')
"""
return '{0:b}'.format(number) |
def opts_dd(lbl, value):
"""Format an individual item in a Dash dcc dropdown list.
Args:
lbl: Dropdown label
value: Dropdown value
Returns:
dict: keys `label` and `value` for dcc.dropdown()
"""
return {'label': str(lbl), 'value': value} |
def _merge_observation(accum_observation, observation):
"""
Old visual observation is discarded, because it is outdated frame.
Text observations are merged, because they are messages sent from the rewarder.
"""
if observation is None:
# We're currently masking. So accum_observation probably
# belongs to the previous episode. We may lose a "text"
# observation from the previous episode, but that's ok.
return None
elif accum_observation is None:
# Nothing to merge together
return observation
accum_observation['vision'] = observation.get('vision')
accum_observation['text'] = accum_observation.get('text', []) + observation.get('text', [])
return accum_observation |
def get_role_permission(role):
"""Common function for getting the permission froms arg
This format is 'openstack.roles.xxx' and 'xxx' is a real role name.
:returns:
String like "openstack.roles.admin"
If role is None, this will return None.
"""
return "openstack.roles.%s" % role.lower() |
def parseMemory(memAttribute):
"""
Returns EC2 'memory' string as a float.
Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB').
Amazon loves to put commas in their numbers, so we have to accommodate that.
If the syntax ever changes, this will raise.
:param memAttribute: EC2 JSON memory param string.
:return: A float representing memory in GiB.
"""
mem = memAttribute.replace(',', '').split()
if mem[1] == 'GiB':
return float(mem[0])
else:
raise RuntimeError('EC2 JSON format has likely changed. Error parsing memory.') |
def decode_lookup(key, dataset, description):
"""Convert a reference to a description to be used in data files"""
if key in dataset:
return dataset[key]
else:
decoded = input("Please enter {desc} for {key}: ".format(desc=description, key=key))
dataset[key] = decoded
return decoded |
def join_str_list(str_list):
"""Join a list of strings, handling spaces appropriately"""
return "".join(s[2:] if s.startswith("##") else " " + s for s in str_list) |
def imo_checksum(n):
"""
This function for IMO numbers that are designed as 7-digit integer number
:param n: String or Integer, Number to be subject to a IMO-checksum test
:return: Boolean, True for valid IMO number checksum, False for otherwise
"""
#
# Cross check type of input, and the range of number
# IMO number should be an integer with 7 digits
try:
n = int(n)
except (ValueError, TypeError):
return False
if not (n >= 1000000) & (n <= 9999999):
return False
else:
pass
#
# IMO checksum formula
if ((n // 1000000 % 10) * 7 +
(n // 100000 % 10) * 6 +
(n // 10000 % 10) * 5 +
(n // 1000 % 10) * 4 +
(n // 100 % 10) * 3 +
(n // 10 % 10) * 2) % 10 == (n % 10):
return True
else:
return False |
def underline(text):
"""Format a string in underline by overstriking."""
return ''.join(map(lambda ch: ch + "\b_", text)) |
def has_duplicates2(t):
"""Checks whether any element appears more than once in a sequence.
Faster version using a set.
t: sequence
"""
return len(set(t)) < len(t) |
def strip_zip_suffix(filename):
"""
Helper function to strip suffix from filename.
:param filename: This field is the name of file.
"""
if filename.endswith('.gz'):
return filename[:-3]
elif filename.endswith('.bz2'):
return filename[:-4]
else:
return filename |
def _calculate_checksum(bytestring):
"""Calculate the checksum used by OneTouch Ultra and Ultra2 devices
Args:
bytestring: the string of which the checksum has to be calculated.
Returns:
A string with the hexdecimal representation of the checksum for the input.
The checksum is a very stupid one: it just sums all the bytes,
modulo 16-bit, without any parity.
"""
checksum = 0
for byte in bytestring:
checksum = (checksum + byte) & 0xffff
return checksum |
def fmt_time(val, missing, _trace, tzinfo):
"""Format timestamp."""
if val is None:
return missing
return (val.astimezone(tzinfo)).strftime("%Y-%m-%d %H:%M") |
def basic_ttr(n_terms, n_words):
""" Type-token ratio (TTR) computed as t/w, where t is the number of unique
terms/vocab, and w is the total number of words.
(Chotlos 1944, Templin 1957)
"""
if n_words == 0:
return 0
return n_terms / n_words |
def linecount(doc: str, end: int, start: int = 0):
"""Returns the number of lines (by counting the
number of newline characters \\n, with the first line
being line number one) in the string *doc* between the
positions *start* and *end*.
"""
return doc.count("\n", start, end) + 1 |
def find_innermost_brackets(formula):
"""Return the indices of (one of) the innermost bracketed term.
Args:
formula (list of str): The formula split at whitespace.
Returns:
int: The first index of the first innermost bracketed term.
int: The last index +1 of the first innermost bracketed term.
"""
d = 0
d_max = 0
i_max = [0, len(formula)-1]
inside = False
for i, symb in enumerate(formula):
if symb == "(":
d += 1
if d > d_max:
d_max = d
i_max = []
inside = True
elif symb == ")":
d = max(d-1, 0)
inside = False
elif inside:
i_max.append(i)
return i_max[0], i_max[-1]+1 |
def get_user_credentials(username, env_config):
""" Return email and pswd of specified user, as a tuple. """
user_email = env_config.get(username).get('email')
user_pswd = env_config.get(username).get('pswd')
return (user_email, user_pswd) |
def update_schema_types(schema: dict, column_names: list, new_type: dict):
"""
Update entries within schema dictionary to reflect a common change across all rows in list (column_names)
Parameters
----------
schema
column_names
list of names of keys within schema to assign new type to
new_type
type dictionary to update the schame entry to
"""
schema = schema.copy()
for column_name in column_names:
schema[column_name] = new_type
return schema |
def _get_hdr_values(extns, key):
"""
Helper function to get the all header values from a list of extensions.
The return value is a dict keyed on the EXPID value.
Parameters
----------
extns : iterable of :any:`astrodata.Astrodata`
AstroData extensions to be examined
key : str
The FITS header key to find in the list of extensions
"""
return {x.hdr.get('EXPID'): x.hdr.get(key) for x in extns} |
def build_production_array(arr: list) -> list:
"""
Parameters
-----------
Returns
---------
Notes
------
"""
if not arr:
return arr
lenth = len(arr)
out = [1] * lenth
for i in range(1, lenth):
out[i] = out[i-1] * arr[i-1]
tmp = 1
for i in range(lenth-2, -1, -1):
tmp *= arr[i+1]
out[i] *= tmp
return out |
def parse_args(args):
"""
Takes the given args, parses them and return the arguments object
:param args:
:return:
"""
arguments = {}
if args is not None:
for argument in args:
if '=' in argument:
tmp = [a for a in argument.split('=', 1)]
try:
value = eval(tmp[1]) # todo: this seems dangerous
except (NameError, SyntaxError):
value = tmp[1]
arguments[tmp[0]] = value
else:
arguments = eval(argument)
return arguments |
def bead_sort(sequence: list) -> list:
"""
>>> bead_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> bead_sort([6, 11, 12, 4, 1, 5])
[1, 4, 5, 6, 11, 12]
>>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bead_sort([5, 0, 4, 3])
[0, 3, 4, 5]
"""
if any(not isinstance(x, int) or x < 0 for x in sequence):
raise TypeError("Sequence must be list of nonnegative integers")
for _ in range(len(sequence)):
for i, (rod_upper, rod_lower) in enumerate(
zip(sequence, sequence[1:])):
if rod_upper > rod_lower:
sequence[i] -= rod_upper - rod_lower
sequence[i + 1] += rod_upper - rod_lower
return sequence |
def normalize_api_params(params):
"""Normalize GitHub Issues API params to Search API.
conventions:
Issues API params | Search API converted values
-------------------------|---------------------------------------
state | into q as "state:open", "state:closed"
creator | into q as "author:username"
mentioned | into q as "mentions:username"
direction | order
"""
if 'direction' in params:
params['order'] = params['direction']
del params['direction']
# these params need to be added to the "q" param as substrings
if 'state' in params:
state_param = ' state:' + params['state']
params['q'] += state_param
del params['state']
if 'creator' in params:
creator_param = ' author:' + params['creator']
params['q'] += creator_param
del params['creator']
if 'mentioned' in params:
mentioned_param = ' mentions:' + params['mentioned']
params['q'] += mentioned_param
del params['mentioned']
return params |
def recurse_fact(n):
# n! can also be defined as n * (n-1)!
""" calculates n! recursively """
if n <= 1:
return 1
else:
return n * recurse_fact(n - 1) |
def get_label_buttons(label_buttons, endpoint, labels, collection, eid):
"""
Creates endpoints with the prefix 'endpoint' to assign qualitative
analysis codes to a given document 'eid' in a given 'collection'.
The codes are taken from 'labels' (typically part of the app config).
Appends the new endpoints to an existing dictionary 'label_buttons'.
"""
label_buttons.setdefault(eid, [])
for l in labels:
d = {'url':'/%s/%s/%s/%s' % (endpoint, collection, eid, l[1]),
'name':l[0]}
label_buttons[eid].append(d)
return label_buttons |
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g, b = x, c, 0
elif h<180:
r, g, b = 0, c, x
elif h<240:
r, g, b = 0, x, c
elif h<300:
r, g, b = x, 0, c
else:
r, g, b = c, 0, x
return (int((r+m)*255), int((g+m)*255), int((b+m)*255), int(a*255)) |
def moeda_brasileira(numero, with_marker=True):
"""
Retorna uma string no formato de moeda brasileira
"""
if numero == None or numero == '': return ''
try:
contador = 0
preco_str = ''
num = numero.__str__()
if '.' in num:
preco, centavos = num.split('.')
else:
preco = num
centavos = '00'
tamanho = len(preco)
while tamanho > 0:
preco_str = preco_str + preco[tamanho-1]
contador += 1
if contador == 3 and tamanho > 1:
preco_str = preco_str + '.'
contador = 0
tamanho -= 1
tamanho = len(preco_str)
str_preco = ''
while tamanho > 0:
str_preco = str_preco + preco_str[tamanho-1]
tamanho -= 1
if with_marker:
return "R$ %s,%s" % (str_preco, centavos)
else:
return "%s,%s" % (str_preco, centavos)
except:
return 'Erro. Nao foi possivel formatar.' |
def to_array(string):
"""Converts a string to an array relative to its spaces.
Args:
string (str): The string to convert into array
Returns:
str: New array
"""
try:
new_array = string.split(" ") # Convert the string into array
while "" in new_array: # Check if the array contains empty strings
new_array.remove("")
return new_array
except:
print("The parameter string is not a str")
return string |
def split_numerical_value(numeric_value, splitVal):
"""
split numeric value on splitVal
return sub ranges
"""
split_num = numeric_value.split(',')
if len(split_num) <= 1:
return split_num[0], split_num[0]
else:
low = split_num[0]
high = split_num[1]
# Fix 2,2 problem
if low == splitVal:
lvalue = low
else:
lvalue = low + ',' + splitVal
if high == splitVal:
rvalue = high
else:
rvalue = splitVal + ',' + high
return lvalue, rvalue |
def euclid_algorithm(area):
"""Return the largest square to subdivide area by."""
height = area[0]
width = area[1]
maxdim = max(height, width)
mindim = min(height, width)
remainder = maxdim % mindim
if remainder == 0:
return mindim
else:
return euclid_algorithm((mindim, remainder)) |
def gridify(n, f):
"""
e.g., (1.1243, 0.005) -> 1.120
"""
return round(n / f) * f |
def neuron_params(device_params, scale=1 << 6, p_scale=1 << 12):
"""Translates device parameters to neuron parameters.
Parameters
----------
device_params : dictionary
dictionary of device parameter specification.
scale : int
neuron scale value. Default value = 1 << 6.
p_scale : int
parameter scale value. Default value = 1 << 12
Returns
-------
dictionary
dictionary of neuron parameters that can be used to initialize neuron
class.
"""
return {
'threshold': device_params['vThMant'] / scale,
'current_decay': device_params['iDecay'] / p_scale,
'voltage_decay': device_params['vDecay'] / p_scale,
} |
def create_zero_matrix(rows: int, columns: int) -> list:
"""
Creates a matrix rows * columns where each element is zero
:param rows: a number of rows
:param columns: a number of columns
:return: a matrix with 0s
e.g. rows = 2, columns = 2
--> [[0, 0], [0, 0]]
"""
if not isinstance(rows, int) or not isinstance(columns, int) or \
isinstance(rows, bool) or isinstance(columns, bool):
return []
zero_matrix = []
num_columns = [0] * columns
if num_columns:
zero_matrix = [[0] * columns for _ in range(rows)]
return zero_matrix |
def configGet(cmap, tup):
"""
Answers the question, should we do this test, given this config file?
Following the values of the tuple through the map,
returning the first non-null value. If all values are null,
return True (handles tests that may have been added after the
config was generated).
"""
for name in tup:
if not name in cmap:
return True
run = cmap[name]["run"] if "run" in cmap[name] else None
if run != None:
return run
cmap = cmap[name]["sub"] if "sub" in cmap[name] else {}
return True |
def gen_marker(marker_id, marker_type, Point, Color, scale, text):
"""Place a marker of a given type and color at a given location"""
marker = """ -
header:
seq: 1482
stamp:
secs: 1556650754
nsecs: 179000000
frame_id: "world"
ns: "thick_traj"
id: %d
type: %d
action: 0
pose:
position:
x: %g
y: %g
z: %g
orientation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
scale:
x: %g
y: %g
z: %g
color:
r: %g
g: %g
b: %g
a: 1.0
lifetime:
secs: 0
nsecs: 0
frame_locked: False
text: "%s"
mesh_resource: ''
mesh_use_embedded_materials: False
""" % \
(marker_id, marker_type, Point[0], Point[1], Point[2],
scale, scale, scale, Color[0], Color[1], Color[2], text);
return marker; |
def get_array_info(subs, dictofsubs):
"""
Returns information needed to create and access members of the numpy array
based upon the string names given to them in the model file.
Parameters
----------
subs : Array of strings of subscripts
These should be all of the subscript names that are needed to create the array
dictofsubs : dictionary
returns
-------
A dictionary of the dimensions associating their names with their numpy indices
directory = {'dimension name 1':0, 'dimension name 2':1}
A list of the length of each dimension. Equivalently, the shape of the array:
shape = [5,4]
"""
# subscript references here are lists of array 'coordinate' names
if isinstance(subs,list):
element=subs[0]
else:
element=subs
# we collect the references used in each dimension as a set, so we can compare contents
position=[]
directory={}
dirpos=0
elements=element.replace('!','').replace(' ','').split(',')
for element in elements:
if element in dictofsubs.keys():
if isinstance(dictofsubs[element],list):
dir,pos = (get_array_info(dictofsubs[element][-1],dictofsubs))
position.append(pos[0])
directory[dictofsubs[element][-1]]=dirpos
dirpos+=1
else:
position.append(len(dictofsubs[element]))
directory[element]=dirpos
dirpos+=1
else:
for famname,value in dictofsubs.iteritems():
try:
(value[element])
except: pass
else:
position.append(len(value))
directory[famname]=dirpos
dirpos+=1
return directory, position |
def convert_f_to_k(temperature_f):
"""Convert Fahrenheit to Kelvin"""
temperature_k = (temperature_f - 32) * (5/9) + 273.15
return temperature_k |
def to_numbers(li_dig1, li_dig2, li_result):
"""
This function gets 3 lists of numbers which represent the operands' digits
It returns the operands as integers
"""
dig1 = li_dig1[0]
dig2 = li_dig2[0]
result = li_result[0]
for i in range(0, len(li_dig1) - 1):
dig1 = dig1 * 10 + li_dig1[i + 1]
dig2 = dig2 * 10 + li_dig2[i + 1]
result = result * 10 + li_result[i + 1]
return dig1, dig2, result |
def cz_u(cL, U, cL_u = 0):
""" This calculates the coefficient of force in the z direction
with respect to the change in the forward velocity
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. New York, 1991, (pg 23)
Inputs:
cL [dimensionless]
U [meters/second]
cL_u
Outputs:
cz_u [dimensionless]
Properties Used:
N/A
"""
# Generating Stability derivative
cz_u = -2. * cL - U * cL_u
return cz_u |
def next_available_id(v):
"""
Return smallest nonnegative integer not in v.
"""
i = 0
while i in v:
i += 1
return i |
def parse_schedule_json(schedules_json):
"""
The original design of metronome had an array of schedules defined but
limited it to 1. This limits to 1 and takes the array format or just
1 schedule format.
:param schedules_json: schedule or array of schedules in json
:type schedules_json: json [] or {}
:returns: schedule json
:rtype: json
"""
if type(schedules_json) is list:
return schedules_json[0]
else:
return schedules_json |
def epoch_time(start_time: float, end_time: float):
"""
Calculate the time spent during one epoch
Args:
start_time (float): training start time
end_time (float): training end time
Returns:
(int, int) elapsed_mins and elapsed_sec spent during one epoch
"""
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 |
def gray_code(N):
""" Generate a Gray code for traversing the N qubit states. """
if N <= 0 or type(N) is not int:
raise ValueError("Input for gray code construction must be a positive integer.")
if N == 1: # Base case
return ["0", "1"]
else:
sub_code = gray_code(N-1)
return ["0" + x for x in sub_code] + ["1" + x for x in sub_code[::-1]] |
def get_matching_items_from_dict(value, dict_name):
"""
Return all items in a dict for which the label matches the provided value.
@param value: the value to match
@param dict_name: the dict to look in
"""
matches = [dict_name[x]["items"]
for x in dict_name if x.lower() == value]
if len(matches) == 0:
return []
else:
return matches[0] |
def bern_choice(probabilities, random_function) -> int:
"""Draws a random value with random_function and returns
the index of a probability which the random value undercuts.
The list is theoretically expanded to include 1-p
"""
assert type(probabilities) is list
random_value = random_function()
for index in range(len(probabilities)):
if random_value <= probabilities[index]:
return index
return len(probabilities) |
def xor(a: bytes, b: bytes) -> bytes:
""" Xor byte a byte entre a e b """
return bytes(x^y for x, y in zip(a, b)) |
def generate_query_string(query_params):
"""Generate a query string given kwargs dictionary."""
query_frags = [
str(key) + "=" + str(value) for key, value in query_params.items()
]
query_str = "&".join(query_frags)
return query_str |
def fpi_bandpass_lims(d, n):
"""Bandpass filter limits for a single order of an FPI at given gap.
Parameters
----------
d : float
Gap length of the Fabry-Perot etalon.
n : int
The order of the FPI peak included in the limits
Returns
-------
(lmin, lmax) : tuple of float
Minimum and maximum wavelengths that include the three FPI orders.
"""
lmax = 2 * d * (1 / n + 1 / (2 * n * (n - 1)))
lmin = 2 * d * (1 / n - 1 / (2 * n * (n - 1)))
return (lmin, lmax) |
def joiner(list_of_strings):
"""Join all the stings in the list, excepting the first"""
if len(list_of_strings) > 1:
return ' '.join(list_of_strings[1:])
return '' |
def unpad_pkcs7(data):
"""
Strips PKCS#7 padding from data.
Raises ValueError if padding is invalid.
"""
if len(data) == 0:
raise ValueError("Error: Empty input.")
pad_value = data[-1]
if pad_value == 0 or pad_value > 16:
raise ValueError("Error: Invalid padding.")
for i in range(1, pad_value + 1):
if data[-i] != pad_value:
raise ValueError("Error: Invalid padding.")
unpadded = data[: (len(data) - pad_value)]
return unpadded |
def _parse_input(obj, arg):
"""
Returns obj[arg] if arg is string, otherwise returns arg.
"""
return obj[arg] if isinstance(arg, str) else arg |
def DNA_to_mRNA_List(DNA_string):
"""Takes in DNA sequence string and converts it to an mRNA list.
Parameters
----------
DNA_string : string
String that contains letters/characters of a DNA string, e.g., 'a,' t,' 'c,' and 'g.'
Returns
-------
mRNA_List : list
List that converts each and every value in input to corresponding mRNA values.
"""
# Creates an empty list to which values will be appended
mRNA_List = [];
# Loops through each character of DNA string input
for char in DNA_string:
if char == 'a' or char == 'A':
# Characters are appended to mRNA_List
mRNA_List.append('U')
elif char == 't' or char == 'T':
mRNA_List.append('A')
elif char == 'c' or char == 'C':
mRNA_List.append('G')
elif char == 'g' or char == 'G':
mRNA_List.append('C')
# Output mRNA_List is returned by function
return mRNA_List |
def l1_norm(lst):
"""
Calculates the l1 norm of a list of numbers
"""
return sum([abs(x) for x in lst]) |
def bisection_solve(x, eval_ans, epsilon, low, high):
"""x, epsilon, low, high are floats
epsilon > 0
eval_ans a function mapping a float to a float
low <= high and there is an ans below low and high s.t.
eval(ans) is within epsilon of x
returns ans s.t. eval(ans) within epsilon of x"""
ans = (high + low) // 2
counter = 1
while abs(eval_ans(ans) - x) >= epsilon:
if eval_ans(ans) < x:
low = ans
else:
high = ans
ans = (high + low) // 2
counter += 1
return ans, counter |
def choose(n: int, k: int) -> int:
"""Return binomial coefficient of n choose k."""
ans = 1
for i in range(min(k, n-k)):
ans *= n-i
ans //= i+1
return ans |
def check_if_only_decoys(sequences):
"""
Check if the sequences to consolidate are composed only of decoys
"""
only_decoys = True
for sequence in sequences:
if 'decoy' not in sequence.split()[2]:
only_decoys = False
break
return only_decoys |
def read_int_item(item_id: int) -> dict:
""" Example function """
return {
'foo': item_id
} |
def decode(what):
"""Decode a EDIComm string into its component parts (splitting lists as needed)"""
parts = what.split(' ')
new_parts = []
# First expansion: each separate parameter, keeping lists together.
this_part = ''
for part in parts:
this_part += part
merge = part.endswith('\\')
if merge:
this_part = this_part[:-1] + ' '
else:
new_parts.append(this_part)
this_part = ''
parts = new_parts
new_parts = []
# Second expansion: lists.
for part in parts:
if part.find(',') == -1:
new_parts.append(part)
continue
part_parts = part.split(',')
parsed_parts = []
parsed = ''
for p in part_parts:
parsed += p
merge = p.endswith('\\')
if merge:
parsed = parsed[:-1] + ','
else:
parsed_parts.append(parsed)
parsed = ''
if len(parsed_parts) == 1:
new_parts.append(parsed_parts[0])
else:
new_parts.append(parsed_parts)
return new_parts |
def add_lists(*lists):
"""Add two lists together without numpy
For example, given lists:
[1, 2] [3, 4]
The result is:
[4, 6]
Lists are sliced to prevent mutation.
"""
lists = (l[:] for l in lists)
return list(map(sum, zip(*lists))) |
def maybe_add_ellipses(s, maxlen=72, instead_of_ellipses_add_this_text=None):
"""
If string s is longer than maxlen, truncate it and add on ... to
the end.
If you want something else, use the instead_of_ellipses_add_this_text
>>> maybe_add_ellipses('abcdef')
'abcdef'
>>> maybe_add_ellipses('abcdef', 3)
'abc...'
"""
if len(s) <= maxlen:
return s
elif instead_of_ellipses_add_this_text:
return "{0}{1}".format(s[:maxlen],
instead_of_ellipses_add_this_text)
else:
return "%s..." % s[:maxlen] |
def best_score(a_dictionary):
"""Returns a key with the biggest integer value.
Checks if a thing is a dicrionary with the is instance method"""
if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0:
return None
ret = list(a_dictionary.keys())[0]
big = a_dictionary[ret]
for k, v in a_dictionary.items():
if v > big:
big = v
ret = k
return (ret) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.