content stringlengths 42 6.51k |
|---|
def get_custom_field(task, field_name):
"""
Gets the value of a custom field
"""
for field in task["custom_fields"]:
if field["name"] == "Repo(s)" and field_name == "Repo(s)":
return field["text_value"]
elif field["name"] == field_name:
return field["enum_value"][... |
def ne(token):
"""
This just assumes that words in all caps or titles are
named entities.
:type token: str
"""
if token.istitle() or token.isupper():
return True
return False |
def sphere_to_plane_car(az0, el0, az, el):
"""Project sphere to plane using plate carree (CAR) projection.
The target point can be anywhere on the sphere. The output (x, y)
coordinates are likewise unrestricted.
Please read the module documentation for the interpretation of the input
parameters an... |
def fill_unk(lexicon, words_to_fill, pseudo="UNK"):
"""
Fill rare words with UNK
:param lexicon: vocabulary
:param words_to_fill: the words to fill in
:param pseudo: the pseudo token to substitute unknown words
:return:
"""
return [w if w in lexicon else pseudo for w in words_to_fill] |
def is_valid_requeue_limit(requeue_limit):
"""Checks if the given requeue limit is valid.
A valid requeue limit is always greater than
or equal to -1.
"""
if not isinstance(requeue_limit, int):
return False
if requeue_limit <= -2:
return False
return True |
def count_y_clusters(y):
"""
Count BGCs regions in a list of protein domain BGC states. Done by counting all consecutive 1 as one region.
:param y: List of BGC states (0 = non-BGC, 1 = BGC), one state for each protein domain
:return: Count of BGCs in given list of protein domain BGC states.
"""
... |
def calculate_plane_point(plane, point):
"""Calculates the point on the 3D plane for a point with one value missing
:param plane: Coefficients of the plane equation (a, b, c, d)
:param point: 3D point with one value missing (e.g. [None, 1.0, 1.0])
:return: Valid point on the plane
"""
a, b, c,... |
def _safe_str(obj):
"""Helper for assert_* ports"""
try:
return str(obj)
except Exception:
return object.__str__(obj) |
def get_parameter_list_from_parameter_dict(pd):
"""Takes a dictionary which contains key value pairs for model parameters and converts it into a list of
parameters that can be used as an input to an optimizer.
:param pd: parameter dictionary
:return: list of parameters
"""
pl = []
for key i... |
def safedivf(a, b):
"""A zero-safe division, returns 0.0 if b is 0, a / float(b) otherwise."""
return a / float(b) if b else 0.0 |
def print_time_cost(dtime, unit_max="hour"):
""" return string for delta_time """
if dtime <= 60 * 1.5:
dtime_str = "{:.3f} sec".format(dtime)
elif dtime <= 60 * 60 * 1.5:
dtime_str = "{:.3f} min".format(dtime / 60.)
elif dtime <= (60 * 60 * 24 * 3):
dtime_str = "{:.3f} hours".fo... |
def plot_relative_Bs(relative_Bs):
"""Make scatter plot of relative Bs for dose-decay"""
d = {
"dose_relative_Bs": {
"data": [
{
"x": list(range(0, len(relative_Bs))),
"y": relative_Bs,
"type": "scatter",
... |
def get_robot_definition(robot_geometry, solver_type):
"""
:return robot_definition: dictionary
"""
robot_definition = {}
if solver_type == 1:
robot_definition['a1'] = robot_geometry['d1']
robot_definition['a2'] = robot_geometry['d4']
robot_definition['b'] = robot_geometry['... |
def iroot(k, n):
"""Computes floor(n^(1/k)), that is, the k-th root of n, rounded down to the nearest integer."""
hi = 1
while pow(hi, k) < n:
hi *= 2
lo = hi // 2
while hi - lo > 1:
mid = (lo + hi) // 2
midToK = pow(mid, k)
if midToK < n:
lo = mid
... |
def format_station(station):
"""Format the station for a playlist description."""
return '' if not station else f'on {station}' |
def contains_failure(message):
"""
Check if a given pytest contained a failure.
Arguments
---------
message : str
The pytest output to check
Returns
-------
bool
True if the output contains failures; False otherwise
"""
return "= FAILURES =" in message |
def decode_json(data):
"""
The passbolt API returns legacy strings or JSON objects.
Try to decode JSON, and if invalid return string.
"""
import json
try:
data = json.loads(data)
except json.decoder.JSONDecodeError:
return data
return data["password"] |
def safe_in(x, ys):
"""
Test if x is present in ys even if x is unhashable.
"""
try:
return x in ys
except TypeError:
return False |
def int_if_youCan(x):
""" Return string without decimals if value has none"""
if x % 1.0 == 0:
strX = str(int(x))
else:
strX = "%.6f" % (x)
return strX |
def gamma_parameters(mean, var):
"""
Returns tuple with scale and shape of gamma distribution
based on a mean and variance.
Keyword arguments:
mean -- mean of the gamma dist
var -- variance of the gamma dist
"""
scale = var / mean
shape = var / (scale ** 2)
return scale, sha... |
def is_scalar(x):
"""True if x is a scalar (constant numeric value)
"""
return isinstance(x, (int, float)) |
def parsetimezone(s):
"""find a trailing timezone, if any, in string, and return a
(offset, remainder) pair"""
if s.endswith("GMT") or s.endswith("UTC"):
return 0, s[:-3].rstrip()
# Unix-style timezones [+-]hhmm
if len(s) >= 5 and s[-5] in "+-" and s[-4:].isdigit():
sign = (s[-5... |
def get_4x4_translation(x,y,z):
"""return a matrix 4x4 for translation"""
a= [1,0,0,0]
b= [0,1,0,0]
c= [0,0,1,0]
d= [x,y,z,1]
return [a,b,c,d] |
def knapsack(limit, values, weights):
"""Returns the maximum value that can be reached using given weights"""
n = len(weights)
dp = [0]*(limit+1)
for i in range(n):
for j in range(limit, weights[i]-1, -1):
dp[j] = max(dp[j], values[i] + dp[j - weights[i]])
return dp[-1] |
def get_provenance_record(attributes, ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
caption = ("Average {long_name} between {start_year} and {end_year} "
"according to {dataset}.".format(**attributes))
record = {
'caption': caption,
... |
def generate_trait(trait, component, inherit):
"""
This function generates a type trait label for C++
"""
return "template <>\nstruct {}<component::{}> : {} {};\n".format(
trait, component, inherit, "{}") |
def calc_default_colors(p_index):
"""List of default colors, lines, and markers to use if user does not
specify them in the input yaml file.
Parameters
----------
p_index : integer
Number of pairs in analysis class
Returns
-------
list
List of dictionaries cont... |
def sensible_jump(n, desired_rows=20):
"""
return a sensible jump size to output desired_rows given input of n
:param n:
:param desired_rows:
:return:
"""
if n < desired_rows:
return 1
j = int(n / desired_rows)
return round(j, -len(str(j)) + 1) |
def other_taxonomy_levels(level):
"""
return the name of all the taxonomic levels *not* specified by level.
Handy if you want to drop all the other columns.
:param level: string string string string
:return:
"""
levels = ['Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus']
levels... |
def _short_str(obj, l=30):
"""Return a shortened str of an object -- for logging"""
s = str(obj)
if len(s) > l:
return s[:l-3] + "..."
else:
return s |
def apply_spherical_spreading(signal, distance, inverse=False):#, nblock):
"""Apply spherical spreading.
:param signal. Signal. Iterable.
:param distance: Distance. Iterable.
:param nblock: Amount of samples in block.
"""
if inverse:
return signal * distance
else:
return si... |
def getMaxAmplitude(sampleWidth):
"""Gets the maximum possible amplitude for a given sample width"""
return 2 ** (sampleWidth * 8 - 1) - 1 |
def cut_line(str, line_len):
"""
Wrap output
"""
result = []
temp = []
for idx, item in enumerate(str.split()):
temp.append(item)
if (idx + 1) % line_len == 0:
result.append(' '.join(temp))
temp = []
if len(temp) != 0:
result.append(' '.join(te... |
def str_is_float(value: str) -> bool:
"""
:param value:
:return:
"""
if not value or isinstance(value, bool):
return False
if value[0] in ['-', '+']:
value = value[1:]
if value.lower() in ['nan', 'infinity', 'inf']:
return False
try:
float(value)
e... |
def ok(b):
"""
:returns: 'ok' if b is True, else, return 'error'.
"""
if b:
return "ok"
return "error" |
def set_lsb(number, bit):
"""Sets the Least Significant Bit of a number to the specified bit value.
Arguments:
number (int) -- the number to be modified
bit (int) -- the value to be set as the LSB of number
Returns:
int type
"""
binary = str(bin(number))[2:]
retString ... |
def try_map(m, value):
"""Maps/translates `value` if it is present in `m`. """
if value in m:
return m[value]
else:
return value |
def list_dims(l):
"""
"""
return [len(l)] + list_dims(l[0]) if l and isinstance(l, list) else [] |
def isTriangleNum(n):
"""Given a number, return True if it is a triangle number"""
n *= 2
v1 = 1
v2 = 2
while True:
if n == v1 * v2:
return True
elif n < v1 * v2:
return False
else:
v1 += 1
v2 += 1 |
def handle_pmid_26740625(*filenames):
"""Clement, ..., Santambrogio. J. Biol. Chem. 2016 [PMID 26740625]"""
# Mouse with transgenic DRB*01:01, collected about 3,000 peptides.
# Peptides are mouse-derived, MHC II is human.
return None |
def b_backward_recurrence(a, b, z, w0, w1, N):
"""Use recurrence relation (3.14) from _[pop] to compute hyp1f1(a, b -
N, z) given w0 = hyp1f1(a, b + 1, z) and w1 = hyp1f1(a, b, z).
The minimal solution is gamma(b - a)*hyp1f1(a, b, z)/gamma(b), so
it's safe to naively use the recurrence relation.
"... |
def _pprint_dict(seq, _nest_lvl=0):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u"{%s}"
pairs = []
pfmt = u"%s: %s"
for k, v in seq.items():
pairs.append(pfmt % (repr(k), repr(v)))
return fmt % ", ... |
def b2i(b):
"""Bytes to Integers (Big Endian)"""
n = 0
for bt in b:
n += bt
n = n << 8
return n >> 8 |
def split(data, count) :
""" Splits data into list of exactly count+1 items, some possibly empty strings """
out = data.split(None, count)
while len(out) < count + 1:
out.append("")
return out |
def factorial(n):
"""
Tells the value of n!
:param n: number to be factorial
:type n: int
:return: n!
:rtype: int
"""
if type(n) is not int:
raise TypeError('n must be type int.')
if n > 1:
return n * factorial(n-1)
else:
return 1 |
def process_terms(terms):
"""
Processes weighted lists
"""
weight_sum = sum(term[1] for term in terms)
if weight_sum <= 0:
return 0
return sum(float(val * weight) for weight, val in terms) / weight_sum |
def if_error(f, x, upon_error):
"""
Mimics Excel IFERROR functionality.
If you're using this, you're probably doing Python wrong.
(If you're using this with numpy/pandas, check the numpy WHERE argument
first.)
But sometimes it's useful.
Like maybe you'd like to ignore unicode errors for a wh... |
def object_kind(object_path):
"""
Parse the kind of object from an UDisks2 object path.
Example: /org/freedesktop/UDisks2/block_devices/sdb1 => device
"""
try:
return {
'block_devices': 'device',
'drives': 'drive',
'jobs': 'job',
}.get(object_path... |
def relativeSize(bbox1, bbox2):
"""
Calculate the relative size of bbox1 to bbox2.
:return: (sx, sy) where bbox1_width = sx * bbox2_width, etc.
"""
sx = (bbox1[2]-bbox1[0]) / (bbox2[2]-bbox2[0])
sy = (bbox1[3]-bbox1[1]) / (bbox2[3]-bbox2[1])
return (sx, sy) |
def radius_of_curvature(z, zt, C):
"""
Returns the radius of curvature of the flight path at any point.
Parameters
----------
z : float
Current depth below the reference horizontal line.
zt : float
Initial depth below the reference horizontal line.
C : float
... |
def split_in_parts(coords, to_remove):
"""splits the trajecotories by the stops that are within the centres (indicated in the to_remove vector)"""
parts = []
part = []
prev_truevalue = True
for coord, truevalue in zip(coords, to_remove):
if not truevalue:
part.append(coord)
... |
def convert_search(search):
""" Convert classic wildcard to SQL wildcard """
if not search:
# Default value
search = ""
else:
# Allow * for wildcard matching and space
search = search.replace("*", "%").replace(" ", "%")
# Allow ^ for start of string and $ for end of stri... |
def reduce_structure(reduce, accumulate, param_groups):
""" Applies an operation to the elements of a parameter group and accumulates
the result via specificed functions
:param reduce: The reducing operation
:param accumulate: The accumulating operation
:param param_groups: The
:return: The accu... |
def validate(action, n=None):
"""
Validate whether it is a valid non-block action
"""
if action is None:
return True
else:
return n not in action |
def hexd(n):
"""Return hex digits (strip '0x' at the beginning)."""
return hex(n)[2:] |
def is_string_with_space(check_input):
"""
This function checks if the string entered by user is alphabets with space included
:param check_input: string input by user
:return: bool
"""
check_input = check_input.lower()
if ' ' in check_input:
check_input.strip()
for char in check_input:
if char.isalpha() ... |
def sql_filtered_insert(table, set_columns, values):
"""
Generates dynamically a sql insert query by eliminating the columns that have value to None
WARNING: RESPECT columns AND values SORT ORDER IN THE LISTS!
If the values are positioned incorrectly with respect to the column names,
they will be sa... |
def generate_url(start_time: str, end_time: str) -> str:
"""Generates a CAISO OASIS url based on start and time.
Parameters
----------
start_time : str
start timestamp
end_time : str
end timestamp
Returns
-------
target_url: str
OASIS url for download
"""
... |
def search4letters(phrase: str, letters: str = 'aeiou') -> set:
"""Returns the set of 'letters' found in 'phrase'."""
return set(letters).intersection(set(phrase)) |
def SubstTemplate(contents, values):
"""
Returns the template with substituted values from the specified dictionary.
Keywords to be substituted are surrounded by '@': @KEYWORD@.
No attempt is made to avoid recursive substitution. The order
of evaluation is random based on the order of the keywords returne... |
def control_arg(var):
"""
:param var:
:return:
"""
if var.isdigit():
return int(var)
else:
return var |
def deleteSpace1(s1):
"""
delete space in String
sample: " abc x y z " => "abc x y z"
"""
sa = (s1.strip()).rsplit()
sres = ""
for i in range(len(sa)):
if i>0:
sres +=' '
sres += sa[i]
return sres |
def _is_debug_build(environment):
"""Checks whether a debug build has been requested
@param environment Environment whose settings will be checked for a debug build
@returns True if a debug build has been requested, otherwise False"""
if 'DEBUG' in environment:
return environment['DEBUG']
... |
def breadth_first(root: dict) -> list:
"""
Using a queue to do breadth-first traverse from tree root iteratively.
"""
if not root or not isinstance(root, dict):
return []
data = []
node = root
queue = []
queue.append(node) # enqueue the node - add the node at the end
while l... |
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if encoding is None:
return str(obj)
elif isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
else:
return str(obj, encoding) |
def is_negative(b):
"""Returns True if the given byte represents a negative number.
"""
return ((b >> 7) & 0x1) == 1 |
def makeChessboard(col, row):
"""
Creates a idealized coordinate array of a chessboard.
Args:
col (int): number of interior columns on the chessboard
row (int): number of interior rows on the chessboard
Returns:
Raw 2D (z=0) chessboard coordinate array.
"""
x = 0
y ... |
def hypersphere_params(n_samples):
"""Generate hypersphere benchmarking parameters.
Parameters
----------
n_samples : int
Number of samples to be used.
Returns
-------
_ : list.
List of params.
"""
manifold = "Hypersphere"
manifold_args = [(3,), (5,)]
module... |
def indian_word_currency(value):
"""
Converts a large integer number into a friendly text representation.
Denominations used are: Hundred, Thousand, Lakh, Crore
Examples:
1000 becomes 1 Thousand
15000 becomes 15 Thousands
15600 becomes 15.60 Thousands
100000 becomes 1 Lak... |
def instance_on_host(instance, host_name):
"""
Returns true if the instance is located on the host
"""
if host_name != instance['OS-EXT-SRV-ATTR:host']:
return False, "instance is not on host"
return True, "instance is on host" |
def type_mapping(name):
"""
Mapping between types name and type integer value.
.. runpython::
:showcode:
from mlprodict.onnxrt.doc.doc_helper import type_mapping
import pprint
pprint.pprint(type_mapping(None))
print(type_mapping("INT"))
print(type_mapping(2)... |
def Jolanta_3D_Coulomb(a, rc):
"""
computes int_rc^oo dr r**4 * exp(-a*r**2) * (-1/r)
this is for RAC radial p-GTO: u(r) = R(r)*r
u1*u2 = r**4 * exp(-(a1+a2)*r**2)
rc is ignored (needed for function uniformity)
returns -1/(2*a**2)
"""
return -1/(2*a**2) |
def midi2hz(midi):
"""
hz = midi2hz(midi)
Converts frequency in midi notation to Hertz.
"""
return 440*2**((midi-69)/12.0) |
def _rk12_step(func, y0, dt):
"""Improved Euler-Integration step to integrate dynamics.
Args:
func: Function handle to time derivative.
y0: Current state.
dt: Integration step.
Returns:
Next state.
"""
dy = func(y0)
y_ = y0 + dt * dy
return y0 + dt / 2. * (dy + func(y_)) |
def _extract_lemmas_from_sentences(sentences):
"""
extracts the first occurrence of a lemma from each sentence, using the markers
:param sentences: list or array of strings representing the DIRTY sentences, i.e. with markers for the lemmas
:return: a list of the lemmas that were found, corresponding in ... |
def checkUnique2(String):
"""
Time Complexity : O(n)
"""
if len(String)>128: #total ascii characters is 128, can use 256 for extended ascii
return False
checker = 0
for i in range(len(String)):
val = ord(String[i])
print(checker, val, 1<<val)
if ((checker & (1<<val)) > 0):
return False
checker = ch... |
def int2signed(num, nbits=32):
""" Given a Python integer, return its 2s complement
word representation.
"""
if num < 0:
return 2 ** nbits + num
else:
return num |
def _factorial(x: int) -> int:
"""Cached recursive factorial function in case someone wants to call
`power_basis` with a large order.
"""
if x < 0:
raise ValueError('_factorial() not defined for negative values')
if x < 2:
return 1
return _factorial(x - 1) * x |
def prefix_base_url(base_url, endpoint):
"""
Returns ``base_url`` + ``endpoint`` with the right forward slashes.
>>> prefix_base_url('https://play.dhis2.org/dev/',
... '/api/trackedEntityInstances')
'https://play.dhis2.org/dev/api/trackedEntityInstances'
>>> prefix_base_url('ht... |
def quote_stripped(value: str) -> str:
"""
Strip out a single level of single (') or double (") quotes.
"""
single, double = "'", '"'
if (value.startswith(single) and value.endswith(single)) or\
(value.startswith(double) and value.endswith(double)):
return value[1:-1]
return value |
def _device_category_to_string(category_id):
"""
:param category_id: Category ID to convert to a string
:return: Category description
"""
if category_id < 50:
return 'Reserved'
if category_id < 1000:
return 'Temporary'
if category_id < 2000:
return 'Administrative Too... |
def rgb(r, g, b, maximum=1.):
"""Create an SVG color string "#xxyyzz" from r, g, and b.
r,g,b = 0 is black and r,g,b = maximum is white.
"""
return "#%02x%02x%02x" % (max(0, min(r*255./maximum, 255)),
max(0, min(g*255./maximum, 255)),
max(0, m... |
def parse_addr(specified_address):
"""Parse the --liveserver argument into a host/IP address and port range"""
# This code is based on
# django.test.testcases.LiveServerTestCase.setUpClass
# The specified ports may be of the form '8000-8010,8080,9200-9300'
# i.e. a comma-separated list of ports or ... |
def parse_version(ver):
"""Split version into major and minor"""
vs = ver.split(".")
if len(vs) != 2:
return -1, -1
return int(vs[0]), int(vs[1]) |
def equal(seq):
"""Determine whether a sequence holds identical elements.
"""
return len(set(seq)) <= 1 |
def access_model_field(app_name, model_name, field_name, request=None, instance=None):
"""
Return true to allow access of a given field_name to model app_name.model_name given
a specific object of said model.
"""
# in django version 1.2 a new attribute is on all models: _state of type ModelState
... |
def collection_id(product: str, version: str) -> str:
"""Creates a collection id from a product and a version:
Args:
product (str): The MODIS product
version (str): The MODIS version
Returns:
str: The collection id, e.g. "modis-MCD12Q1-006"
"""
return f"modis-{product}-{ver... |
def add(a, b):
"""Add two numbers and return the sum"""
summation = round(a+b, 4)
print("The sum of " + str(a) + " and " + str(b) + " is " + str(summation) + ".")
return str(a) + " + " + str(b) + " = " + str(summation) |
def assignment_complete(assignments, inp):
"""
input:
assignment: a dict contains only the colored points with key (coordinate) values (colors) including the terminals
inp: 2d list of the input
return weather or not the assignments are complete
"""
# if len of assignments keys length of inp... |
def tile_validator(value):
"""
Supported tile values: 128, 256, 320, 448, 512
"""
if not value.isnumeric:
raise TypeError("Select a valid vlaue.")
elif value.isnumeric and int(value) in (128, 256, 320, 448, 512):
return int(value)
else:
raise TypeError("Select a valid vl... |
def convert_reminder_string(reminder):
"""Convert reminder string to minutes integer.
Keyword arguments:
reminder: String representation of time,
e.g. '10' for 10 minutes,
'1d' for one day,
'3h' for three hours, etc.
Returns:
Integer of reminder convert... |
def frameTestSegmented(frame):
"""Test for segmented messages.
Args:
frame (dict): Frame to test
Returns:
bool: ``True`` if this is a segmented message, else ``False``.
"""
# Ignore non-segmented messages
if frame['s_flag'] != 1:
return False
return True |
def _create_policies_key(config_key):
"""Create policies key from config key
Assumes config_key is well-formed"""
return "{:}:policies/".format(config_key) |
def get_backend_bucket_outputs(res_name, backend_name):
""" Creates outputs for the backend bucket. """
outputs = [
{
'name': 'name',
'value': backend_name
},
{
'name': 'selfLink',
'value': '$(ref.{0}.selfLink)'.format(res_name)
}
... |
def filter_short_trips(trip_list, unique_sensor_count=4, silent=True):
"""Removes trips too short to be identifiable as cruising.
trip_list [list]: a list of dicts in JSON format.
unique_sensor_count [int]: trips with fewer than this number of hits on
unique sensors will be filtered out.
silen... |
def numToLetter(n):
""" for 1 <= n <= 26 """
return chr(ord('a') + n - 1) |
def get_all_rows(table_name):
"""
Returns a string for a query statement to retrieve all rows in a table.
: param table_name : name of mySQL table
: return : string containing query statment to get all the rows
"""
return f"select * from {table_name}" |
def has_bad_member(hospital, matched_dict, capacities):
"""
We check if currently hospital has more residents than it's capacity, so we have to remove worst resident based on this criteria.
"""
if len(matched_dict[hospital]) > capacities[hospital]:
return True
elif len(matched_dict[hosp... |
def get_as_text(kw, field):
"""
Return ``kw[field]`` as a stripped string
"""
return kw.get(field, '').strip() |
def move_zeros(array: list):
"""
An algorithm that takes an array and moves all of the
zeros to the end, preserving the order of the other elements.
:param array:
:return:
"""
moving_zero = True
while moving_zero:
moving_zero = False
for i, a in enumerate(array):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.