content stringlengths 42 6.51k |
|---|
def product_sum(record: list) -> list:
"""Return a list that contains the sum of each prodcut sales."""
return [sum(i) for i in record] |
def server_error(e: Exception) -> str:
"""Handle server error, especially for the previewer."""
from traceback import format_exc
return f"<pre>{format_exc()}\n{e}</pre>" |
def P_controller(state):
"""
Use only the temperature desired - actual to generate hvac ON or OFF requests
"""
Kp = 0.2
output = Kp * (state["Tset"] - state["Tin"])
if output < 0:
control = 1
else:
control = 0
action = {"hvacON": control}
return action |
def _bump(version='0.0.0'):
"""
>>> _bump()
'0.0.1'
>>> _bump('0.0.3')
'0.0.4'
>>> _bump('1.0.5')
'1.0.6'
"""
major, minor, patch = version.split('.')
patch = str(int(patch) + 1)
return '.'.join([major, minor, patch]) |
def match(l_s, s_s):
"""
TO compare the long and short sequence one by one and find the most accurate one.
:param l_s: str, long sequence where short sequence find the most similar one
:param s_s: str, short sequence. As a standard to search
:return: b_s
"""
b_s = '' # best sequence
b_c_a = 0 # best correct alpha. Use it to compare the highest accuracy with other
for i in range(0, len(l_s)-len(s_s)+1): # len(l_s)-len(s_s)+1 is total number of combination
t_s = l_s[i:len(s_s)+i]
c_n = 0
for j in range(len(s_s)):
if s_s[j] == t_s[j]:
c_n += 1
if c_n > b_c_a:
b_s = t_s
b_c_a = c_n
return b_s |
def extract_dates(qd):
"""Extract a date range from a query dict, return as a (start,end) tuple of strings"""
start = end = None
# attempt to extract "start", or
# fall back to the None
try:
start = "%4d-%02d-%02d" % (
int(qd["start-year"]),
int(qd["start-month"]),
int(qd["start-day"]))
except: pass
# as above, for END
try:
end = "%4d-%02d-%02d" % (
int(qd["end-year"]),
int(qd["end-month"]),
int(qd["end-day"]))
except: pass
return (start, end) |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except ValueError:
nums.append(target)
nums.sort()
return nums.index(target) |
def fix_text(txt):
"""
Fixes text so it is csv friendly
"""
return " ".join(txt.replace('"', "'").split()) |
def safe_string_equals(a, b):
""" Near-constant time string comparison.
Used in order to avoid timing attacks on sensitive information such
as secret keys during request verification (`rootLabs`_).
.. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/
"""
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 |
def dashed(n):
"""Return an identifier with dashes embedded for readability."""
s = str(n)
pos = 0
res = []
s_len = len(s)
while pos < s_len:
res.append(s[pos:pos + 4])
pos += 4
return '-'.join(res) |
def reporthook(t):
"""https://github.com/tqdm/tqdm"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b: int, optional
Number of blocks just transferred [default: 1].
bsize: int, optional
Size of each block (in tqdm units) [default: 1].
tsize: int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner |
def _FormatHumanReadable(number):
"""Formats a float into three significant figures, using metric suffixes.
Only m, k, and M prefixes (for 1/1000, 1000, and 1,000,000) are used.
Examples:
0.0387 => 38.7m
1.1234 => 1.12
10866 => 10.8k
682851200 => 683M
"""
metric_prefixes = {-3: 'm', 0: '', 3: 'k', 6: 'M'}
scientific = '%.2e' % float(number) # 6.83e+005
e_idx = scientific.find('e') # 4, or 5 if negative
digits = float(scientific[:e_idx]) # 6.83
exponent = int(scientific[e_idx + 1:]) # int('+005') = 5
while exponent % 3:
digits *= 10
exponent -= 1
while exponent > 6:
digits *= 10
exponent -= 1
while exponent < -3:
digits /= 10
exponent += 1
if digits >= 100:
# Don't append a meaningless '.0' to an integer number.
digits = int(digits) # pylint: disable=redefined-variable-type
# Exponent is now divisible by 3, between -3 and 6 inclusive: (-3, 0, 3, 6).
return '%s%s' % (digits, metric_prefixes[exponent]) |
def create_annotation_choice_from_int(value):
"""
Creates an annotation choice form an int.
Parameters
-------
value : `int`
The validated annotation choice.
Returns
-------
choice : `tuple` (`str`, (`str`, `int`, `float`))
The validated annotation choice.
"""
return (str(value), value) |
def diagonal_stretch(magnitude, x, y):
"""Stretches the coordinates in both axes
Args:
magnitude (float): The magnitude of the amount to scale by
x (int): The x coordinate
y (int): The y coordinate
Returns:
tuple: The new x, y pair
"""
return int(x * magnitude), int(y * magnitude) |
def remove_node(node_var, breakline=True):
"""Query for removal of a node (with side-effects)."""
return "DETACH DELETE {}\n".format(node_var) |
def _total_size(shape_values):
"""Given list of tensor shape values, returns total size.
If shape_values contains tensor values (which are results of
array_ops.shape), then it returns a scalar tensor.
If not, it returns an integer."""
result = 1
for val in shape_values:
result *= val
return result |
def alltypes_callback(conn, object_name, methodname, **params):
# pylint: disable=attribute-defined-outside-init, unused-argument
# pylint: disable=invalid-name
"""
InvokeMethod callback defined in accord with pywbem
method_callback_interface which defines the input parameters and returns
all parameters received.
"""
return_params = [params[p] for p in params]
return_value = 0
return (return_value, return_params) |
def match(first, second):
"""
Tell if two strings match, regardless of letter capitalization
input
-----
first : string
first string
second : string
second string
output
-----
flag : bool
if the two strings are approximately the same
"""
if len(first) != len(second):
return False
for s in range(len(first)):
fir = first[s]
sec = second[s]
if fir.lower() != sec and fir.upper() != sec:
return False
return True |
def which(program):
"""
Check if executable exists in PATH
:param program: executable name or path to executable
:return: full path if found, None if not
"""
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None |
def listtostring(listin):
"""
Converts a simple list into a space separated sentence, effectively reversing str.split(" ")
:param listin: the list to convert
:return: the readable string
"""
ans = ""
for l in listin:
ans = ans + str(l) + " "
return ans.strip() |
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)]) |
def predict(model, data):
"""
Predicts and prepares the answer for the API-caller
:param model: Loaded object from load_model function
:param data: Data from process function
:return: Response to API-caller
:rtype: dict
"""
# return a dictionary that will be parsed to JSON and sent back to API-caller
return {} |
def loaded_token_vault(token_vault, team_multisig, token_vault_balances):
"""Token vault with investor balances set."""
for address, balance in token_vault_balances:
token_vault.functions.setInvestor(address, balance, 0).transact({"from": team_multisig})
return token_vault |
def extract_param(episode):
""" Given a list of parameter values, get the underlying parameters
Parameters
----------
episode: list
parameter values, such as ['a1', 'b2']
Returns
-------
param: list
parameter vector, e.g. ['A', 'B']
"""
if type(episode) is not list:
episode = [episode]
if len(episode) == 0:
return None
# collect the parameters
params_list = [episode[i][0] for i in range(len(episode))]
params = ''.join(params_list).upper()
# params = set(params_list)
return params |
def splitBytes(data,n=8):
"""Split BytesArray into chunks of n (=8 by default) bytes."""
return [data[i:i+n] for i in range(0, len(data), n)] |
def simp(f, a, b):
"""Simpson's Rule for function f on [a,b]"""
return (b-a)*(f(a) + 4*f((a+b)/2.0) + f(b))/6.0 |
def wrap(x, m, M):
"""
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
"""
diff = M - m
while x > M:
x = x - diff
while x < m:
x = x + diff
return x |
def energy(density, coefficient=1):
""" Energy associated with the diffusion model
:Parameters:
density: array of positive integers
Number of particles at each position i in the array/geometry
"""
from numpy import array, any, sum
# Make sure input is an array
density = array(density)
# of the right kind (integer). Unless it is zero length, in which case type does not matter.
if density.dtype.kind != 'i' and len(density) > 0:
raise TypeError("Density should be an array of *integers*.")
# and the right values (positive or null)
if any(density < 0):
raise ValueError("Density should be an array of *positive* integers.")
if density.ndim != 1:
raise ValueError("Density should be an a *1-dimensional* array of positive integers.")
return coefficient * 0.5 * sum(density * (density - 1)) |
def find_adjacent(overlapping_information: list, existing_nodes: list):
"""
Gets a list of directly connected subgraphs and creates the indirect connections.
:param overlapping_information: a list of lists each containing direct connections betweeen some subgraphs.
:param existing_nodes: a list containing each existing node once.
:return: a list of lists each containing all reachable subgraphs with other connected subgraphs in between.
"""
result_connections = []
for node in existing_nodes:
already_checked = False
for c in result_connections:
if node in c:
already_checked = True
break
if already_checked is True:
continue
connection_list = []
connection_list.append(node)
has_changed = True
while has_changed is True:
has_changed = False
for direct_connection in overlapping_information:
will_be_checked = False
for n in connection_list:
if n in direct_connection:
will_be_checked = True
break
if will_be_checked is True:
for new_node in direct_connection:
if new_node not in connection_list:
connection_list.append(new_node)
has_changed = True
result_connections.append(connection_list)
return result_connections |
def convert_set_to_ranges(charset):
"""Converts a set of characters to a list of ranges."""
working_set = set(charset)
output_list = []
while working_set:
start = min(working_set)
end = start + 1
while end in working_set:
end += 1
output_list.append((start, end - 1))
working_set.difference_update(range(start, end))
return output_list |
def seconds_to_HMS_str(total_seconds):
"""
Converts number of seconds to human readable string format.
Args:
(int) total_seconds - number of seconds to convert
Returns:
(str) day_hour_str - number of weeks, days, hours, minutes, and seconds
"""
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
day_hour_str = ''
if weeks > 0:
day_hour_str += '{} weeks, '.format(weeks)
if days > 0:
day_hour_str += '{} days, '.format(days)
if hours > 0:
day_hour_str += '{} hours, '.format(hours)
if minutes > 0:
day_hour_str += '{} minutes, '.format(minutes)
# always show the seconds, even 0 secs when total > 1 minute
if total_seconds > 59:
day_hour_str += '{} seconds'.format(seconds)
return day_hour_str |
def load_grid(input_grid):
"""
Convert the text form of the grid into an array form. For now this input is
always the same. If this changes then this code would need to be replaced.
"""
grid = [
[".#./..#/###"]
]
return grid |
def arrow(my_char, max_length):
"""
:param my_char:
:param max_length:
:return:Creates string in shape of arrow, made of the char and the tip will be in length of the max_length
"""
arrow_string = ""
for i in range(1, max_length * 2):
if i < max_length:
arrow_string = arrow_string + (my_char * i + '\n')
elif i >= max_length:
arrow_string = arrow_string + (my_char * (max_length * 2 - i) + '\n')
return arrow_string |
def difflist(list1: list, list2: list) -> list:
"""Showing difference between two lists
Args:
list1 (list): First list to check difference
list2 (list): Second list to check difference
Returns:
list: Difference between list1 and list2
"""
return list(set(list1).symmetric_difference(set(list2))) |
def RGBtoHSB( nRed, nGreen, nBlue ):
"""RGB to HSB color space conversion routine.
nRed, nGreen and nBlue are all numbers from 0 to 255.
This routine returns three floating point numbers, nHue, nSaturation, nBrightness.
nHue, nSaturation and nBrightness are all from 0.0 to 1.0.
"""
nMin = min( nRed, nGreen, nBlue )
nMax = max( nRed, nGreen, nBlue )
if nMin == nMax:
# Grayscale
nHue = 0.0
nSaturation = 0.0
nBrightness = nMax
else:
if nRed == nMin:
d = nGreen = nBlue
h = 3.0
elif nGreen == nMin:
d = nBlue - nRed
h = 5.0
else:
d = nRed - nGreen
h = 1.0
nHue = ( h - ( float( d ) / (nMax - nMin) ) ) / 6.0
nSaturation = (nMax - nMin) / float( nMax )
nBrightness = nMax / 255.0
return nHue, nSaturation, nBrightness |
def _build_re_custom_tokens(ner_labels):
"""
For RE tasks we employ the strategy below to create custom-tokens for our vocab:
Per each ner_label, create two tokens SUBJ-NER_LABEL, OBJ-NER_LABEL
These tokens make up the custom vocab
Arguments:
ner_labels (arr) : array of ner label names
"""
tokens = []
for label in ner_labels:
tokens.append("SUBJ-{}".format(label))
tokens.append("OBJ-{}".format(label))
return tokens |
def empty_to_none(raw):
"""
Return an empty string to None otherwise return the string.
"""
if not raw:
return None
return raw |
def make_feat_paths(feat_path):
"""
Make a feature path into a list.
Args:
feat_path (str): feature path
Returns:
paths (list): list of paths
"""
if feat_path is not None:
paths = [feat_path]
else:
paths = None
return paths |
def count_by_activity(contract_json):
"""
Given a full JSON contracts dictionary, return a new dictionary of counts
by activity.
"""
by_activity = contract_json['contracts']
activities = by_activity.keys()
return dict(zip(activities, [len(by_activity[a]) for a in activities])) |
def create_agent_params(name, dim_state, actions, mean, std, layer_sizes, discount_rate, learning_rate, batch_size, memory_cap, update_step, decay_mode, decay_period, decay_rate, init_eps, final_eps):
"""
Create agent parameters dict based on args
"""
agent_params = {}
agent_params['name'] = name
agent_params["dim_state"] = dim_state
agent_params["actions"] = actions
agent_params["mean"] = mean
agent_params["std"] = std
agent_params["layer_sizes"] = layer_sizes
agent_params["discount_rate"] = discount_rate
agent_params["learning_rate"] = learning_rate
agent_params["batch_size"] = batch_size
agent_params["memory_cap"] = memory_cap
agent_params["update_step"] = update_step
agent_params["decay_mode"] = decay_mode
agent_params["decay_period"] = decay_period
agent_params["decay_rate"] = decay_rate
agent_params['init_eps'] = init_eps
agent_params['final_eps'] = final_eps
return agent_params |
def _str_2_tuple(x):
"""Ensure `x` is at least a 1-tuple of str.
"""
return (x,) if isinstance(x, str) else tuple(x) |
def normal_percentile_to_label(percentile):
"""
Assigns a descriptive term to the MMSE percentile score.
"""
if percentile >= 98:
return 'Exceptionally High'
elif 91 <= percentile <= 97:
return 'Above Average'
elif 75 <= percentile <= 90:
return 'High Average'
elif 25 <= percentile <= 74:
return 'Average'
elif 9 <= percentile <= 24:
return 'Low Average'
elif 2 <= percentile <= 8:
return 'Below Average'
elif percentile < 2:
return 'Exceptionally Low' |
def no_add_printer(on=0):
"""Desabilitar a Adicao de Impressoras
DESCRIPTION
Qualquer usuario pode adicionar uma nova impressora no seu sistema.
Esta opcao, quando habilitada, desabilita a adicao de novas impressoras no
computador.
COMPATIBILITY
Todos.
MODIFIED VALUES
NoAddPrinter : dword : 00000000 = Desabilitado;
00000001 = Habilitada restricao.
"""
if on:
return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\
CurrentVersion\\Policies\\Explorer]
"NoAddPrinter"=dword:00000001'''
else:
return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\
CurrentVersion\\Policies\\Explorer]
"NoAddPrinter"=dword:00000000''' |
def findclosest(list, value):
"""Return (index, value) of the closest value in `list` to `value`."""
a = min((abs(x - value), x, i) for i, x in enumerate(list))
return a[2], a[1] |
def murnaghan(V, E0, B0, B1, V0):
"""From PRB 28,5480 (1983)"""
E = E0 + B0*V/B1*(((V0/V)**B1)/(B1-1)+1) - V0*B0/(B1-1)
return E |
def _neighbors(point):
"""
Get left, right, upper, lower neighbors of this point.
"""
i, j = point
return {(i-1, j), (i+1, j), (i, j-1), (i, j+1)} |
def addText(text, endIndex, namedStyleType, requests):
"""Adds requests to add text at endIndex with the desired nameStyleType.
Returns new endIndex.
Args:
text (String): text to add
endIndex (int): Current endIndex of document. Location to add text to
namedStyleType (String): desired namedStyleType of text
requests (list): list of requests to append requests to
Returns:
int: new endIndex after adding text
"""
# Finds new end index by incrementing endIndex by the length of the text
# plus 1 for the automatically appended '\n'
newEndIndex = endIndex + len(text) + 1
# Appends requests to add text, and then request to change namedStyleType
# as desired
requests.extend([
# Add text, including a '\n' at the previous line to create a new paragraph
# Note that a '\n' will automatically be appended to the end of the text
{
'insertText': {
'location': {
'index': endIndex - 1
},
'text': '\n' + text
}
},
{
'updateParagraphStyle': {
'range': {
'startIndex': endIndex,
'endIndex': newEndIndex
},
'paragraphStyle': {
'namedStyleType': namedStyleType
},
'fields': 'namedStyleType'
}
}
])
return newEndIndex |
def sqrlenv3(a):
"""compute squared length of 3-vector"""
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2] |
def is_dunder_method(obj) -> bool:
"""Is the method a dunder (double underscore), i.e. __add__(self, other)?"""
assert hasattr(obj, "__name__")
obj_name = obj.__name__
return obj_name.endswith("__") and obj_name.startswith("__") |
def power(num1, num2):
"""
POWER num1 num2
outputs ``num1`` to the ``num2`` power. If num1 is negative, then
num2 must be an integer.
"""
## @@: integer not required with negative num1...?
return num1**num2 |
def calc_image_weighted_average_iou(dict):
"""Calculate SOA-I-IoU"""
iou = 0
total_images = 0
for label in dict.keys():
num_images = dict[label]["images_total"]
if dict[label]["iou"] is not None and dict[label]["iou"] >= 0:
iou += num_images * dict[label]["iou"]
total_images += num_images
overall_iou = iou / total_images
return overall_iou |
def to_requests_format(ip, port):
""" Returns the proxy format for requests package """
return {'http': 'http://{}:{}'.format(ip, port),
'https': 'http://{}:{}'.format(ip, port)} |
def calculate_mean(some_list):
"""
Function to calculate the mean of a dataset.
Takes the list as an input and outputs the mean.
"""
return (1.0 * sum(some_list) / len(some_list)) |
def _get_wf_name(filename):
"""
Derive the workflow name for supplied DWI file.
Examples
--------
>>> _get_wf_name('/completely/made/up/path/sub-01_dir-AP_acq-64grad_dwi.nii.gz')
'dwi_preproc_dir_AP_acq_64grad_wf'
>>> _get_wf_name('/completely/made/up/path/sub-01_dir-RL_run-01_echo-1_dwi.nii.gz')
'dwi_preproc_dir_RL_run_01_echo_1_wf'
"""
from pathlib import Path
fname = Path(filename).name.rpartition(".nii")[0].replace("_dwi", "_wf")
fname_nosub = "_".join(fname.split("_")[1:])
return f"dwi_preproc_{fname_nosub.replace('.', '_').replace(' ', '').replace('-', '_')}" |
def label(arg):
"""
Returns the full name of the model based on the abbreviation
"""
switcher = {
'dcltr_base': "DeCLUTR Base",
'dcltr_sm': "DeCLUTR Small",
'distil': "DistilBERT",
'if_FT': "InferSent FastText",
'if_glove': "InferSent GloVe",
'roberta': "RoBERTa",
'use': "USE",
'new_lex': 'Lexical Vectors',
'old_lex': 'Lexical Weights',
'lexical_wt': 'Lexical Weights',
'lexical_wt_ssm': 'Lexical Weights',
'lex_vect': 'Lexical Vectors',
'lex_vect_corr_ts': 'Lexical Vectors (Corr)'
}
return switcher.get(arg) |
def nullvalue(test):
"""
Returns a null value for each of various kinds of test values.
"""
return False if isinstance(test,bool) else 0 if isinstance(test,int) else 0.0 if isinstance(test,float) else '' |
def filter_composite_from_subgroups(s):
"""
Given a sorted list of subgroups, return a string appropriate to provide as
the a composite track's `filterComposite` argument
>>> import trackhub
>>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown'])
'dimA dimB'
Parameters
----------
s : list
A list representing the ordered subgroups, ideally the same list
provided to `dimensions_from_subgroups`. The values are not actually
used, just the number of items.
"""
dims = []
for letter, sg in zip('ABCDEFGHIJKLMNOPQRSTUVWZ', s[2:]):
dims.append('dim{0}'.format(letter))
if dims:
return ' '.join(dims) |
def _FindTag(template, open_marker, close_marker):
"""Finds a single tag.
Args:
template: the template to search.
open_marker: the start of the tag (e.g., '{{').
close_marker: the end of the tag (e.g., '}}').
Returns:
(tag, pos1, pos2) where the tag has the open and close markers
stripped off and pos1 is the start of the tag and pos2 is the end of
the tag. Returns (None, None, None) if there is no tag found.
"""
open_pos = template.find(open_marker)
close_pos = template.find(close_marker, open_pos)
if open_pos < 0 or close_pos < 0 or open_pos > close_pos:
return (None, None, None)
return (template[open_pos + len(open_marker):close_pos],
open_pos,
close_pos + len(close_marker)) |
def uncamel(string):
""" CamelCase -> camel_case
"""
out = ''
before = ''
for char in string:
if char.isupper() and before.isalnum() and not before.isupper():
out += '_'
out += char.lower()
before = char
return out |
def same_status(q1, D1, q2, D2):
"""Helper for h_langeq_dfa
Check if q1,q2 are both accepting
or both non-accepting wrt D1,D2 resply.
"""
return (q1 in D1["F"]) == (q2 in D2["F"]) |
def get(mapping, key):
"""Retrive values based on keys"""
return mapping.get(key, 'N/A') |
def account_info(remote, resp):
"""Retrieve remote account information used to find local user.
It returns a dictionary with the following structure:
.. code-block:: python
{
'user': {
'profile': {
'full_name': 'Full Name',
},
},
'external_id': 'github-unique-identifier',
'external_method': 'github',
}
:param remote: The remote application.
:param resp: The response.
:returns: A dictionary with the user information.
"""
orcid = resp.get('orcid')
return {
'external_id': orcid,
'external_method': 'orcid',
'user': {
'profile': {
'full_name': resp.get('name'),
},
},
} |
def is_alive(lives, current):
"""see if the cell will be alive in the next world"""
if lives == 3:
return 1
if lives > 3 or lives < 2:
return 0
return current |
def cutting_rope_greed(l_rope):
"""
greed algorithm
:param l_rope: length of rope
:return: max of mul
"""
if l_rope < 2:
return 'Invalid Input'
# ans = 1
# while l_rope >= 5:
# ans *= 3
# l_rope -= 3
# ans *= l_rope
# return ans
ans = pow(3, l_rope // 3)
if l_rope % 3 == 1:
ans = ans // 3 * 4
elif l_rope % 3 == 2:
ans *= 2
return ans |
def cube_event_key(cube):
"""Returns key used for cube"""
return "cube:%s" % cube |
def _get_mc_dims(mc):
"""
Maximum data of all the bins
Parameters
----------
mc : dict
Molecular cloud dimensions
----------
"""
# Binned molecular cloud
if 'B0' in mc.keys():
mc_binned = True
nbins = len(mc.keys())
# Find the binned dimensions
xmax, ymax = 0, 0
for b in range(nbins):
bin_name = 'B'+str(b)
i, j = mc[bin_name]['pos']
if i >= xmax:
xmax = i
if j >= ymax:
ymax = j
dims = [xmax+1, ymax+1]
# Full molecular cloud
else:
mc_binned = False
nbins = 1
dims = [1, 1]
return dims, nbins, mc_binned |
def save_frontmatter(data: dict) -> str:
"""
Saves the given dictionary as markdown frontmatter.
Args:
data (dict): Dictionary containing all the frontmatter key-value pairs
Returns:
str: A string containing the frontmatter in the correct plaintext format
"""
lines = []
for key, value in data.items():
if isinstance(value, list):
lines.append(str(key) + ": " + "[" + ",".join([f"'{x}'" for x in value]) + "]")
else:
lines.append(str(key) + ": " + str(value))
return "\n".join(lines) |
def _diff_count(string1, string2):
"""
Count the number of characters by which two strings differ.
"""
assert isinstance(string1, str)
assert isinstance(string2, str)
if string1 == string2:
return 0
minlen = min(len(string1), len(string2))
diffcount = abs(len(string1) - len(string2))
for ii in range(0,minlen):
if string1[ii] != string2[ii]:
diffcount += 1
return diffcount |
def timecode_to_milliseconds(code):
""" Takes a time code and converts it into an integer of milliseconds.
"""
elements = code.replace(",", ".").split(":")
assert(len(elements) < 4)
milliseconds = 0
if len(elements) >= 1:
milliseconds += int(float(elements[-1]) * 1000)
if len(elements) >= 2:
milliseconds += int(elements[-2]) * 60000
if len(elements) >= 3:
milliseconds += int(elements[-3]) * 3600000
return milliseconds |
def TRIM(text):
"""Strips leading/trailing whitespace from string(s).
Parameters
----------
text : list or string
string(s) to have whitespace trimmed
Returns
-------
list or string
A list of trimmed strings or trimmed string with whitespace removed.
"""
if type(text) == str:
return(text.strip())
elif type(text) == list:
try:
text_return = [i.strip() for i in text]
return(text_return)
except:
print('Invalid list: please enter a list of strings.')
else:
print('Invalid type: please enter a string or list of strings.') |
def update_copy(d, _new=None, **kw):
"""Copy the given dict and update with the given values."""
d = d.copy()
if _new:
d.update(_new)
d.update(**kw)
return d |
def remove_length10_word(review_str:str)->str:
"""remove any words have length more than 10 on str
"""
final_list =[]
for word in review_str.split():
if len(word)<10:
final_list.append(word)
return " ".join(final_list) |
def make_error_message(e):
"""
Get error message
"""
if hasattr(e, 'traceback'):
return str(e.traceback)
else:
return repr(e) |
def max_slice(array):
"""
Returns the maximal sum of a slice of array (empty slices are also considered).
"""
max_ending = max_slice = 0
for a in array:
max_ending = max(0, max_ending + a)
max_slice = max(max_slice, max_ending)
return max_slice |
def return_value_args(arg1, arg2, kwarg1=None, kwarg2=None):
""" Test function for return values with live args | str --> None
Copy paste following to test:
foo, bar, kwarg1 = foobar, kwarg2 = barfoo
"""
return [arg1, arg2, kwarg1, kwarg2] |
def make_button(text, actions, content_texts=None):
"""
create button message content
reference
- https://developers.worksmobile.com/jp/document/100500804?lang=en
"""
if content_texts is not None:
return {"type": "button_template", "contentText": text,
"i18nContentTexts": content_texts, "actions": actions}
return {"type": "button_template", "contentText": text, "actions": actions} |
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy.
Taken from https://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression"""
z = x.copy()
z.update(y)
return z |
def join_comments(record: dict):
"""
Combine comments from "Concise Notes" and "Notes" fields.
Both will be stored in `comments` column of output dataset.
Parameters
----------
record : dict
Input record.
Returns
-------
type
Record with merged comments.
"""
if type(record['Concise Notes']) != str:
record['Concise Notes'] = ''
if type(record['Notes']) != str:
record['Notes'] = ''
comments = record['Concise Notes'] + '. ' + record['Notes']
return(comments) |
def make_date_iso(d):
"""Expects a date like 2019-1-4 and preprocesses it for ISO parsing.
"""
return '-'.join('{:02d}'.format(int(p)) for p in d.split('-')) |
def parseStr(x):
"""
function to parse a string
Parameters
----------
x : str
input string
Returns
-------
int or float or str
parsed string
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x |
def combine_host_port(host, port, default_port):
"""Return a string with the parameters host and port.
:return: String host:port.
"""
if host:
if host == "127.0.0.1":
host_info = "localhost"
else:
host_info = host
else:
host_info = "unknown host"
if port:
port_info = port
else:
port_info = default_port
return "%s:%s" % (host_info, port_info) |
def is_amazon(source_code):
"""
Method checks whether a given book is a physical book or a ebook giveaway for a linked Amazon account.
:param source_code:
:return:
"""
for line in source_code:
if "Your Amazon Account" in line:
return True
return False |
def identify_technique(target, obstype, slit, grating, wavmode, roi):
"""Identify whether is Imaging or Spectroscopic data
Args:
target (str): Target name as in the keyword `OBJECT` this is useful in
Automated aquisition mode, such as AEON.
obstype (str): Observation type as in `OBSTYPE`
slit (str): Value of `SLIT` keyword.
grating (str): Value of `GRATING` keyword.
wavmode (str): Value of `WAVMODE` keyword.
roi (str): Value of `ROI` keyword.
Returns:
Observing technique as a string. Either `Imaging` or `Spectroscopy`.
"""
if 'Spectroscopic' in roi or \
obstype in ['ARC', 'SPECTRUM', 'COMP'] or \
slit not in ['NO_MASK', '<NO MASK>'] or \
grating not in ['NO_GRATING', '<NO GRATING>'] or \
'_SP_' in target:
technique = 'Spectroscopy'
elif 'Imaging' in roi or \
obstype in ['EXPOSE'] or\
wavmode == 'IMAGING' or '_IM_' in target:
technique = 'Imaging'
else:
technique = 'Unknown'
return technique |
def identify_lens(path):
"""
Function to identify the optics of Insta360 ONE (close or far).
:param path:
:return:
"""
if "lensclose" in path:
which_lens = "close"
elif "lensfar" in path:
which_lens = "far"
else:
raise ValueError("Could not identify lens.")
return which_lens |
def extCheck( extention: str ) -> str:
"""
Ensures a file extention includes the leading '.'
This is just used to error trap the lazy programmer who wrote it.
:param extention: file extention
:type extention: str
:return: Properly formatted file extention
:rtype: str
"""
if extention[ 0 ] != '.':
extention = '.' + extention
return extention |
def parse_int(word):
""" Parse into int, on failure return 0 """
try:
return int(word)
except ValueError:
try:
return int(word.replace(',', ''))
except ValueError:
return 0 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'samskip' and password == 'owns' |
def list_insert_list(l, to_insert, index):
""" This function inserts items from one list into another list at the
specified index. This function returns a copy; it does not alter the
original list.
This function is adapted from: http://stackoverflow.com/questions/7376019/
Example:
a_list = [ "I", "rad", "list" ]
b_list = [ "am", "a" ]
c_list = list_insert_list(a_list, b_list, 1)
print( c_list ) # outputs: ['I', 'am', 'a', 'rad', 'list']
"""
ret = list(l)
ret[index:index] = list(to_insert)
return ret |
def needs_reversal(chain):
"""
Determine if the chain needs to be reversed.
This is to set the chains such that they are in a canonical ordering
Parameters
----------
chain : tuple
A tuple of elements to treat as a chain
Returns
-------
needs_flip : bool
Whether or not the chain needs to be reversed
"""
x = len(chain)
if x == 1:
first = 0
second = 0
else:
q, r = divmod(x, 2)
first = q - 1
second = q + r
while first >= 0 and second < len(chain):
if chain[first] > chain[second]:
# Case where order reversal is needed
return True
elif chain[first] == chain[second]:
# Indeterminate case
first -= 1
second += 1
else:
# Case already in the correct order
return False
return False |
def verify_tutor(dictionary):
"""
Checks if the tutors' names start with an uppercase letter.
Returns true if they all do. Otherwise returns the name that doesn't.
"""
days = list(dictionary.values())
# didnt want to write a lot of nested for loops, so here it goes
tutor_names = {lesson["tutor"] for day in days if day for lesson in day}
# this is roughly equivalent to:
# tutor_names = set()
# for day in days:
# if day:
# for lesson in day:
# tutor_names.add(lesson["tutor"])
for tutor in tutor_names:
# couldnt use the simple .istitle() method here since some tutors have
# weird middle names (e.g. AKM)
names = tutor.split()
upper_names = [name[0].isupper() for name in names]
if not all(upper_names):
return tutor
return True |
def _check_option_arb(df):#grib, write in other file?
""""checks option arbitrage conditions
"""
#butterflys negative
def _make_butterflys(g):
"takes groupby object by Is Call and expiry date"
return [(g[ix-1], g[ix], g[ix], g[ix+1]) for ix in range(1, len(g)-1)]
#iron butterflys negative
#no iron butterfly, regular butterly arb
#boxes positive |
def _aggregate_score_dicts(scores , name = None):
""" Aggregate a list of dict to a dict of lists.
Parameters
----------
scores : list of dictionaries
Contains a dictionary of scores for each fold.
name : str, optional
Prefix for the keys. The default is None.
Returns
-------
dict of lists
Example
-------
scores = [{'roc_auc' : 0.78 , 'accuracy' : 0.8} , {'roc_auc' : 0.675 , 'accuracy' : 0.56} , {'roc_auc' : 0.8 , 'accuracy' : 0.72 }]
_aggregate_score_dicts(scores) = {'roc_auc' : [0.78 , 0.675 , 0.8] , 'accuracy' : [0.8 , 0.56 , 0.72]}
"""
if name is None :
return {key: [score[key] for score in scores] for key in scores[0]}
else :
return {name + str('_') + key: [score[key] for score in scores] for key in scores[0]} |
def is_iterable(x):
"""Checks if x is iterable"""
try:
iter(x)
return True
except TypeError as te:
return False |
def getid(obj):
"""
Abstracts the common pattern of allowing both an object or an object's ID
(integer) as a parameter when dealing with relationships.
"""
try:
return obj.id
except AttributeError:
return int(obj) |
def need_search_path_refresh(sql):
"""Determines if the search_path should be refreshed by checking if the
sql has 'set search_path'."""
return 'set search_path' in sql.lower() |
def pytest_ignore_collect(path, config):
"""Skip App Engine tests when --gae-sdk is not specified."""
return (
'contrib/appengine' in str(path) and
config.getoption('gae_sdk') is None) |
def safe_unicode(arg, *args, **kwargs):
""" Coerce argument to Unicode if it's not already. """
return arg if isinstance(arg, str) else str(arg, *args, **kwargs) |
def join_path(*subpath: str, sep: str = "/") -> str:
"""Join elements from specific separator
Parameters
----------
*subpath: str
sep: str, optional
separator
Returns
-------
str
"""
return sep.join(subpath) |
def firesim_description_to_tags(description):
""" Deserialize the tags we want to read from the AGFI description string.
Return dictionary of keys/vals [buildtriplet, deploytriplet, commit]. """
returndict = dict()
desc_split = description.split(",")
for keypair in desc_split:
splitpair = keypair.split(":")
returndict[splitpair[0]] = splitpair[1]
return returndict |
def get_new_filename(filename: str) -> str:
"""[summary]
Args:
filename (str): [description]
Returns:
str: [description]
"""
base, ext = filename.split('.')
return base + '_copy.' + ext |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.