content stringlengths 42 6.51k |
|---|
def has_async_fn(fn):
"""Returns true if fn can be called asynchronously."""
return hasattr(fn, "async") or hasattr(fn, "asynq") |
def str2list_row(row):
"""
convert str to list in a row.
"""
row = row.strip('\n') # delete '\n'.
row = row.strip('\r') # delete '\r'.
row = row.split(',')
return row |
def get_target_delta(data_size: int) -> float:
"""Generate target delta given the size of a dataset. Delta should be
less than the inverse of the datasize.
Parameters
----------
data_size : int
The size of the dataset.
Returns
-------
float
The target delta value.
"... |
def normalize_params(text:str) -> list:
"""
need to create standard function to normalize parametrs
But first need to understand what params there could be
"""
result = list()
# for default value list of one 0 will be returned
result.append('0')
if ' ' in text:
if '/' in text:
... |
def getCanonicalSvnPath(path):
"""Returns the supplied svn repo path *without* the trailing / character.
Some pysvn methods raise exceptions if svn directory URLs end with a
trailing / ("non-canonical form") and some do not. Go figure...
"""
if path and path.endswith('/'):
path = path[:-1]
return path |
def isfastq(f, verbose=False):
"""
Simple check for fastq file
"""
if 'fq' in f or 'fastq' in f:
return True
return False |
def _str_to_bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueError('Need bool; got %r' % s)
return {'true': True, 'false': False}[s.lower()] |
def create_INFO_dict(INFO):
"""return a dict of values from the INFO field of a VCF
"""
d = {}
for entry in INFO.split(";"):
if "=" in entry:
variable, value = entry.split("=", 1)
d[variable] = value
return d |
def first(obj):
"""
return first element from object
(also consumes it if obj is an iterator)
"""
return next(iter(obj)) |
def is_config_file(filename, extensions=[".yml", ".yaml", ".json"]):
"""
Return True if file has a valid config file type.
Parameters
----------
filename : str
filename to check (e.g. ``mysession.json``).
extensions : str or list
filetypes to check (e.g. ``['.yaml', '.json']``).... |
def pos2wn (pos):
"""Take PTB POS and return wordnet POS
a, v, n, r, x or None 'don't tag'
z becomes z
FIXME: add language as an attribute
"""
if pos in "CC EX IN MD POS RP VAX TO".split():
return None
elif pos in "PDT DT JJ JJR JJS PRP$ WDT WP$".split():
return 'a'
... |
def markupify(string):
""" replace _ with \_ [ not need for all markup ] """
return string.replace("_","\_") |
def combine_counts (counts, sample_names):
""" Combine a set of count dictionaries
counts is a dictorinary of count_data where key is sample name
"""
full_tag_list = []
num_of_samples = len(sample_names)
# Generate the complete tag list (some samples won't have some tags)
for sample in sample_names:
full_tag_... |
def u(s, encoding="utf-8"):
""" bytes/int/float to str """
if isinstance(s, (str, int, float)):
return str(s)
if isinstance(s, bytes):
return s.decode(encoding)
raise TypeError("unsupported type %s of %r" % (s.__class__.__name__, s)) |
def get_tags(line):
"""Get tags out of the given line.
:param str line: Feature file text line.
:return: List of tags.
"""
if not line or not line.strip().startswith("@"):
return set()
return set((tag.lstrip("@") for tag in line.strip().split(" @") if len(tag) > 1)) |
def effective_decimals(num):
""" find the first effective decimal
:param float num: number
:return int: number of the first effective decimals
"""
dec = 0
while 0. < num < 1.:
dec += 1
num *= 10
return dec |
def check_states(user_action, expected_action):
"""this function check the dialogue states of the json_object.
assume both expected action and user action went through
action standarlization, which means they must have a flight and name field.
"""
# first status needs to match
status_match = expected_action... |
def _contains_instance_of(seq, cl):
"""
:type seq: iterable
:type cl: type
:rtype: bool
"""
for e in seq:
if isinstance(e, cl):
return True
return False |
def block(name, content, converter):
"""
Create terraform block.
Args:
. name - block name.
. content - block dict.
. converter - schema converter function
"""
res =""
res += f'\n {name} ' + '{'
for key, val in content.items():
res += converter(key,... |
def get_group_size_and_start(total_items, total_groups, group_id):
"""
Calculate group size and start index.
"""
base_size = total_items // total_groups
rem = total_items % total_groups
start = base_size * (group_id - 1) + min(group_id - 1, rem)
size = base_size + 1 if group_id <= rem else ... |
def leading_indent(str):
"""Count the lead indent of a string"""
if not isinstance(str, list):
str = str.splitlines(True)
for line in str:
if line.strip():
return len(line) - len(line.lstrip())
return 0 |
def binary_xor(a, b):
""" xor the binary numbers passed in parameters as strings
Args:
a -- string
b -- string
return a ^ b in binary
"""
initial_len = len(a)
return bin(int(a, 2) ^ int(b, 2))[2:].zfill(initial_len) |
def extract_fields(json):
"""Extracts a JSON dict of fields.
REST and RPC protocols use different JSON keys for OpenSocial objects. This
abstracts that and handles both cases.
Args:
json: dict The JSON object.
Returns: A JSON dict of field/value pairs.
"""
return json.get('entry') or json |
def LJ(r):
"""Returns the LJ energy"""
return 4 * (((1 / r) ** 12) - ((1 / r) ** 6)) |
def _state_diff(state, previous_state):
"""A dict to show the new, changed and removed attributes between two states
Parameters
----------
state : dict
previous_state : dict
Returns
-------
dict
with keys 'new', 'changed' and 'removed' for each of those with content
"""
... |
def dns(addrs):
"""Formats the usage of DNS servers.
Very important to define this parameter when ever running a container as
Ubuntu resolves over the loopback network, and RHEL doesn't.
If you don't supply this in a docker run command, than users running RHEL
based Linux cannot run automation bui... |
def get_uv_3(x, y):
"""Get the velocity field for exercise 6.1.3."""
return x*(x-y), y*(2*x-y) |
def firstjulian(year):
"""Calculate the Julian date up until the first of the year."""
return ((146097*(year+4799))//400)-31738 |
def fix_kwargs(kwargs):
"""Return kwargs with reserved words suffixed with _."""
new_kwargs = {}
for k, v in kwargs.items():
if k in ('class', 'type'):
new_kwargs['{}_'.format(k)] = v
else:
new_kwargs[k] = v
return new_kwargs |
def square_of_sum(N):
"""Return the square of sum of natural numbers."""
return (N * (N + 1) // 2) ** 2 |
def box(keyword):
"""Validation for the ``<box>`` type used in ``background-clip``
and ``background-origin``."""
return keyword in ('border-box', 'padding-box', 'content-box') |
def sentitel_strict_acc(y_true, y_pred):
"""
Calculate "strict Acc" of aspect detection task of Sentitel.
"""
total_cases=int(len(y_true))
true_cases=0
for i in range(total_cases):
if y_true[i]!=y_pred[i]:continue
true_cases+=1
aspect_strict_Acc = true_cases/total_ca... |
def face_num_filter(ans):
"""
ans -list of (pic_url, face_num)
"""
return list(filter(lambda x: x[1] == 1, ans)) |
def less_than(val1, val2):
"""
Simple function that returns True if val1 <= val2 and False otherwise.
:param val1: first value of interest
:param val2: second value of interest
:return: bool: True if val1 <= val2 and False otherwise
"""
if round(val1, 3) <= round(val2, 3): # only care ... |
def jekyll_slugify(input: str, mode: str = "default") -> str:
"""Slugify a string
Note that non-ascii characters are always translated to ascii ones.
Args:
input: The input string
mode: How string is slugified
Returns:
The slugified string
"""
if input is None or mode ... |
def less_equal(dict1: dict, dict2: dict):
"""equal the same key to respect the key less dict"""
if len(dict1) > len(dict2):
dict1, dict2 = dict2, dict1
for key in dict1.keys():
if dict1[key] != dict2[key]:
return False
return True |
def default_dev_objective(metrics):
"""
Objective used for picking the best model on development sets
"""
if "eval_mnli/acc" in metrics:
return metrics["eval_mnli/acc"]
elif "eval_mnli-mm/acc" in metrics:
return metrics["eval_mnli-mm/acc"]
elif "eval_f1" in metrics:
retur... |
def list_comprehension(function, argument_list):
"""Apply a multivariate function to a list of arguments in a serial fashion.
Uses Python's built-in list comprehension.
Args:
function: A callable object that accepts more than one argument
argument_list: An iterable object of input argument... |
def listify(x):
"""
Example:
>>> listify('a b c')
['a', 'b', 'c']
>>> listify('a, b, c')
['a', 'b', 'c']
>>> listify(3)
[3]
"""
if isinstance(x, str):
if ',' in x:
return [x1.strip() for x1 in x.split(',')]
else:
r... |
def check_similar_cpds(cpds, moa_dict):
"""This function checks if two compounds are found in the same moa"""
for x in range(len(cpds)):
for y in range(x+1, len(cpds)):
for kys in moa_dict:
if all(i in moa_dict[kys] for i in [cpds[x], cpds[y]]):
retur... |
def strip_dot_git(url: str) -> str:
"""Strip trailing .git"""
return url[: -len(".git")] if url.endswith(".git") else url |
def reciprocal_overlap(astart, aend, bstart, bend):
"""
creates a reciprocal overlap rule for matching two entries. Returns a method that can be used as a match operator
"""
ovl_start = max(astart, bstart)
ovl_end = min(aend, bend)
if ovl_start < ovl_end: # Otherwise, they're not overlapping
... |
def get_parameter(kwargs, key, default=None):
""" Get a specified named value for this (calling) function
The parameter is searched for in kwargs
:param kwargs: Parameter dictionary
:param key: Key e.g. 'loop_gain'
:param default: Default value
:return: result
"""
if kwargs is None:
... |
def header_line(name, description, head_type=None, values=None):
"""
A helper function to generate one header line for the capabilities()
"""
ret = {'name': name, 'description': description}
if head_type is None:
ret['type'] = 'string'
else:
ret['type'] = head_type
if values ... |
def filter_by_lines(units, lines):
"""Filter units by line(s)."""
return [i for i in units if i.line in lines] |
def singleton(cls):
"""
This method is used for provide singleton object.
:param cls:
:return: type method
"""
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance() |
def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
set1 = set(str(num1))
set2 =... |
def divisors_to_string(divs):
"""
Convert a list of numbers (representing the orders of cyclic groups
in the factorization of a finite abelian group) to a string
according to the format shown in the examples.
INPUT:
- ``divs`` -- a (possibly empty) list of numbers
OUTPUT: a string represe... |
def average(iterable):
"""Return the average of the values in iterable.
iterable may not be empty.
"""
it = iterable.__iter__()
try:
sum = next(it)
count = 1
except StopIteration:
raise ValueError("empty average")
for value in it:
sum = sum + value
... |
def calculate_ratios(x1, y1, x2, y2, width, height):
"""
Calculate relative object ratios in the labeled image.
Args:
x1: Start x coordinate.
y1: Start y coordinate.
x2: End x coordinate.
y2: End y coordinate.
width: Bounding box width.
height: Bounding box he... |
def get_vocabs(datasets):
"""
Args:
datasets: a list of dataset objects
Return:
a set of all the words in the dataset
"""
print("Building vocab...")
vocab_words = set()
vocab_tags = set()
for dataset in datasets:
for words, tags in dataset:
vocab_words... |
def intdiv(p, q):
""" Integer divsions which rounds toward zero
Examples
--------
>>> intdiv(3, 2)
1
>>> intdiv(-3, 2)
-1
>>> -3 // 2
-2
"""
r = p // q
if r < 0 and q*r != p:
r += 1
return r |
def contains_filepath(filepath1, filepath2):
"""
contains_filepath checks if file1 is contained in filepath of file2
"""
return filepath2.startswith(filepath1) |
def shallow_compare_dict(source_dict, destination_dict, exclude=None):
"""
Return a new dictionary of the different keys. The values of `destination_dict` are returned. Only the equality of
the first layer of keys/values is checked. `exclude` is a list or tuple of keys to be ignored.
"""
difference ... |
def format_thousands(value):
"""Adds thousands separator to value."""
return "{:,}".format(int(value)) |
def _preprocess_path(path: str) -> str:
"""
Preprocesses the path, i.e.,
it makes sure there's no tailing '/' or '\'
:param path: The path as passed by the user
:return: The path of the folder on which the model will be stored
"""
if path.endswith("/") or path.endswith("\\"):
path = ... |
def get_bitfinex_candle_url(url: str, pagination_id: int):
"""Get Bitfinex candle URL."""
if pagination_id:
url += f"&end={pagination_id}"
return url |
def ucfirst(word):
""" Capitialize the first letter of the string given
:param word: String to capitalize
:type word: str
:return: Capitalized string
:rtype: str
"""
return word.upper() if len(word) == 1 else word[0].upper() + word[1:] if word else word |
def add_log(log, theta, logl, pseudo):
"""
function to append thata and ll value to the logs
"""
log['logl'].append(logl)
if pseudo:
log['pseudo_data'].append('#FF4949')
else:
log['pseudo_data'].append('#4970FF')
for parameters in theta:
log[parameters].append(theta[p... |
def binary_search(nums, key):
"""Returns the index of key in the list if found, -1 otherwise.
List must be sorted."""
left = 0
right = len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] == key:
return middle
elif nums[middle] > key:
... |
def string_to_ascii_html(string: str) -> str:
"""Convert unicode chars of str to HTML entities if chars are not ASCII."""
html = []
for c in string:
cord = ord(c)
if 31 < cord < 127:
html.append(c)
else:
html.append('&#{};'.format(cord))
return ''.join(htm... |
def phys2dig(signal, dmin, dmax, pmin, pmax):
"""
converts physical values to digital values
Parameters
----------
signal : np.ndarray or int
A numpy array with int values (digital values) or an int.
dmin : int
digital minimum value of the edf file (eg -2048).
dmax : int
... |
def get_overtime(hour_out, check_out):
"""menghitung lembur pegawai"""
if check_out > hour_out:
result = check_out - hour_out
else:
result = ' '
return result |
def get_length(input_data):
"""
Obtain the number of elements in each dataset
Parameters
----------
input_data : list
Parsed dataset of genes
Returns
-------
length : list
the length of each dataset
"""
length = []
for dat... |
def iff( a, b, c ):
"""
Ternary shortcut
"""
if a:
return b
else:
return c |
def list_elongation(lst, length, value=None):
"""Append value to lst as long as length is not reached, return lst."""
for i in range(len(lst), length):
lst.append(value)
return lst |
def fibList(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n mu... |
def cf_or(a, b):
"""The OR of two certainty factors."""
if a > 0 and b > 0:
return a + b - a * b
elif a < 0 and b < 0:
return a + b + a * b
else:
return (a + b) / (1 - min(abs(a), abs(b))) |
def _clean_html(html):
"""Returns the py3Dmol.view._make_html with 100% height and width"""
start = html.find("width:")
end = html.find('px">') + 2
size_str = html[start:end]
html = html.replace(size_str, "width: 100%; height: 100%")
return html |
def is_tandem_repeat(start, stop, unitlength, sequence):
"""
:param start: the start (inclusive) of a tandem repeat sequence
:param stop: the stop (exclusive) of a tandem repeat sequence
:param unitlength: the unit length of the repeat sequence
:param sequence: the sequence to which the coordinates... |
def get_axis_num_from_str(axes_string):
"""
u,v,w correspond to 0,1,2 in the trailing axis of adcpy velocity arrays.
This method returns a list of 0,1, and 2s corresponding to an input
string composed u,v, and ws.
Inputs:
axes_string = string composed of u v or w only [str]
Returns:
... |
def one_bounce(a1, x0, xp0, x1, z1, z2):
"""
Calculates the x position of the beam after bouncing off one flat mirror.
Parameters
----------
a1 : float
Pitch of first mirror in radians
x0 : float
x position of the source in meters
xp0 : float
Pitch of source in rad... |
def busquedaBinaria(numero, lista):
"""
Esta busqueda no me devuelve la posisicion en el array original
pero me devuelve un entero positivo si es que el valor se encuentra
y -1 caso contrario
"""
listaTemp = lista
medio = len(lista)
while medio >0:
n = len(listaTemp)
medi... |
def get_method_acronym(method):
"""Gets pretty acronym for specified ResponseGraphUCB method."""
if method == 'uniform-exhaustive':
return r'$\mathcal{S}$: UE'
elif method == 'uniform':
return r'$\mathcal{S}$: U'
elif method == 'valence-weighted':
return r'$\mathcal{S}$: VW'
elif method == 'count-... |
def coor_to_int(coor):
"""
Convert the latitude/longitute from float to integer by multiplying to 1e6,
then rounding off
"""
return round(coor * 1000000) |
def hex_to_rgb(rgb_string):
"""
Takes #112233 and returns the RGB values in decimal
"""
if rgb_string.startswith("#"):
rgb_string = rgb_string[1:]
red = int(rgb_string[0:2], 16)
green = int(rgb_string[2:4], 16)
blue = int(rgb_string[4:6], 16)
return (red, green, blue) |
def smart_repr(obj, object_list=None, depth=1):
"""Return a repr of the object, using the object's __repr__ method.
Be smart and pass the depth value if and only if it's accepted.
"""
# If this object's `__repr__` method has a `__code__` object *and*
# the function signature contains `object_list`... |
def get_p2p_ssqr_diff_over_var(model):
"""
Get sum of squared differences of consecutive values as a fraction of the
variance of the data.
"""
return model['ssqr_diff_over_var'] |
def con_str(strarr, k):
"""."""
n = len(strarr)
res = ""
if n == 0 or k > n or k <= 0:
return ""
for el in strarr:
if len(el) > len(res):
res = el
for idx, el in enumerate(strarr):
if el == res:
if len(strarr[idx:idx + k]) > len(strarr[:k - idx]):
... |
def divide(a,b):
"""THIS IS A DOC STRING THAT ONLY SHOWS WHEN USING HELP COMMAND"""
if type(a) is int and type(b) is int:
return a/b
return "A and B must be ints!" |
def derive_tenant(url):
"""Derive tenant ID from host
We consider the standard `subdomain.domain.com` structure to be the
`tenant_id`.
There might be multiple applications that are hosted for the subdomain,
and they may have additional application identifiers at the beginning,
like 'customers.... |
def validate_form(form, required):
"""funkcija ki sprejme formo in vsebine, ki ne smejo biti prazne (required)"""
messages = []
for vsebina in required:
value = form.get(vsebina)
if value is "" or value is None:
messages.append("%s" % vsebina)
return messages |
def answer_check(n:int, table_number:str, target_number:str, H:int, B:int) -> bool:
"""
answer check.
"""
check_H, check_B = 0, 0
for col in range(0, n):
if target_number[col] == table_number[col]:
check_H += 1
if check_H != H:
return False
for i in range(0,... |
def disease_related(row):
"""
Determine whether the cause of death was disease related or not from
the value for Last Known Vital Status
"""
last_vital = row.get("Last Known Vital Status", "Unknown") or "Unknown"
if "deceased by disease" in last_vital.lower():
ret = True
elif "unkno... |
def coverage(a1,b1,a2,b2):#{{{
"""
return the coverage of two intervals
a1, b1, a2, b2 are integers
when the return value <=0, it means there is no coverage
"""
return (min(b1,b2)-max(a1,a2)) |
def eh_peca(peca):
"""
Reconhece peca.
:param peca: universal
:return: bool
Recebe um argumento de qualquer tipo e devolve True se o seu argumento corresponde a uma peca
e False caso contrario.
"""
return peca in ("X", "O", " ") |
def _get_frames(d, cross = False, mask = None):
"""gets two frames (or one frame and NoneType) from dual (or single) frame data"""
if cross == True:
x1,x2 = d
if mask is not None:
x1,x2 = x1[mask],x2[mask]
else:
if len(d) == 1 and isinstance(d, tuple):
x1, = d... |
def parseLineForExpression(line):
"""Return parsed SPDX expression if tag found in line, or None otherwise."""
p = line.partition("SPDX-License-Identifier:")
if p[2] == "":
return None
# strip away trailing comment marks and whitespace, if any
expression = p[2].strip()
expression = expre... |
def in_circle(x, y, a=0, b=0, r=25):
"""Check if 2D coordinates are within a circle
Optional arguments offset the circle's centre and specify radius
returns True if x,y is in circle of position a,b and radius r
"""
return (x - a)*(x - a) + (y - b)*(y - b) < r**2 |
def convert_int_to_rgb_string(rgb_int):
""" This function converts a RGB-Int value to a Standard RGB-String
The Alpha Value is fixed.
:param rgb_int: the RGB-Value as Integer
:return: Standard RGB-Values as String
"""
red = rgb_int & 255
green = (rgb_int >> 8) & 255
blue = (rgb_int... |
def integers(sequence_of_sequences):
"""
Returns a new list that contains all the integers
in the subsequences of the given sequence, in the order that they
appear in the subsequences.
For example, if the argument is:
[(3, 1, 4),
(10, 'hi', 10),
[1, 2.5, 3, 4],
'he... |
def _swap_bytes(data):
"""swaps bytes for 16 bit, leaves remaining trailing bytes alone"""
a, b = data[1::2], data[::2]
data = bytearray().join(bytearray(x) for x in zip(a, b))
if len(b) > len(a):
data += b[-1:]
return bytes(data) |
def _parse_dimensions(metric_name):
""" Parse out existing dimensions from the metric name """
try:
metric_name, dims = metric_name.split("|", 1)
except ValueError:
dims = ""
return (
metric_name,
dict(dim_pair.split("=") for dim_pair in dims.split(",") if dim_pair),
... |
def quick_sort(alist):
"""Implement a sorted in order by value list."""
if len(alist) < 2:
return alist
if len(alist) == 2:
if alist[0] > alist[1]:
alist[0], alist[1] = alist[1], alist[0]
return alist
pivot = alist[0]
less = []
greater = []
for num in alis... |
def _create_name_mapping(all_nodes):
""" helper function to creates the name of the nodes within a GraphPipeline model
- if no ambiguities, name of node will be name of model
- otherwise, name of node will be '%s_%s' % (name_of_step,name_of_model)
Parameters
----------
all_nodes : list... |
def add_quotes_to_strings(strings):
"""
Add double quotes strings in a list then join with commas.
Args:
strings (list(str)): List of strings to add parentheses to.
Returns:
str: The strings with quotes added and joined with commas.
"""
quote_strings = []
for _string in stri... |
def get_metricx_list(type, features):
"""
Function:
get_metricx_list
Description:
Return an instance of a MetricX for each feature name on a list.
Input:
- type,class: The MetricX object to instance.
- features,list: List of feature names.
... |
def get_currency_from_checkout(currency):
"""Convert Checkout's currency format to Saleor's currency format.
Checkout's currency is using lowercase while Saleor is using uppercase.
"""
return currency.upper() |
def slice_to_range(sl: slice, n):
"""
Turn a slice into a range
:param sl: slice object
:param n: total number of items
:return: range object, if the slice is not supported an exception is raised
"""
if sl.start is None and sl.step is None and sl.start is None: # (:)
return range(n)... |
def overlap1(a0, a1, b0, b1):
"""Check if two 1-based intervals overlap."""
return int(a0) <= int(b1) and int(a1) >= int(b0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.