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 = '' ... |
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
... |
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 le... |
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, opti... |
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',... |
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.
"... |
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 *... |
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
retu... |
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 pa... |
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(firs... |
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(pro... |
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 bac... |
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:
... |
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 (... |
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(densit... |
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 contain... |
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, en... |
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_se... |
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 = arr... |
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).sy... |
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( n... |
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 (... |
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
... |
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... |
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.
MODIFI... |
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): desir... |
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... |
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.n... |
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': "R... |
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'
... |
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 of... |
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',
},
... |
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 // ... |
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 b... |
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 = []
fo... |
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) -... |
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(el... |
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(tex... |
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,
"i18nConte... |
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.
"""
... |
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:... |
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"
... |
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... |
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.")
r... |
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 extentio... |
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:... |
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... |
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["tu... |
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 butt... |
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.
... |
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 = ke... |
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.