content stringlengths 42 6.51k |
|---|
def first_order_func(x, a, b):
"""For linear Approximation.
x: List or array, independence variable
a: Float, coefficient of first order x
b: Float, intercept of linear approximation
"""
return a*x + b |
def term_rankings_size( term_rankings ):
"""
Return the number of terms covered by a list of multiple term rankings.
"""
m = 0
for ranking in term_rankings:
if m == 0:
m = len(ranking)
else:
m = min( len(ranking), m )
return m |
def shift(c, k):
"""shifts and returns char c by offset determined by char k"""
c_upper = c.isupper()
k_upper = k.isupper()
# find numeric value of c (offset so a == 0).
c = ord(c) - 65 if c_upper else ord(c) - 97
k = ord(k) - 65 if k_upper else ord(k) - 97
# shift according to (k)ey char ... |
def _clean_token(s):
"""If the token is digit, then round the actual value into the nearest 10 times value.
Args:
s: original digit, 65 -> 60
"""
if len(s) > 1:
if s.isdigit():
l = len(s)
s = str(int(s)//(10**(l-1)) * 10**(l-1))
return s.lower() |
def dry_malt_to_grain_weight(malt):
"""
DME to Grain Weight
:param float malt: Weight of DME
:return: Grain Weight
:rtype: float
"""
return malt * 5.0 / 3.0 |
def ext_language(ext, exts=None, simple=True):
"""Language of the extension in those extensions
If exts is supplied, then restrict recognition to those exts only
If exts is not supplied, then use all known extensions
>>> ext_language('.py') == 'python'
True
"""
languages = {
".py":... |
def add(b1, b2):
"""
Return bbox containing two bboxes.
"""
return (min(b1[0], b2[0]), min(b1[1], b2[1]), max(b1[2], b2[2]), max(b1[3], b2[3])) |
def tag_morphology(tag):
"""
>>> tag_morphology("NOUN__Animacy=Inan|Case=Nom|Gender=Neut|Number=Sing")
{'POS': 'NOUN', 'Animacy': 'Inan', 'Case': 'Nom', 'Gender': 'Neut', 'Number': 'Sing'}
>>> tag_morphology("SYM___")
{'POS': 'SYM'}
"""
pos, parts = tag.split("__", 1)
info = {"POS": pos}... |
def read_file(f_in):
"""
Read a file, return an array of strings (lines).
"""
fd_in = open(f_in)
lines = fd_in.readlines()
fd_in.close()
return lines |
def lookup(unit_str):
"""look up the input keyword in the dictionary and return the standard synonym"""
unit_dict = {"T": ["T", "T_b", "T_cmb", "T_CMB", "K", "K_CMB"],
"T_RJ": ["T_rj", "T_RJ", "s_nu", "K_RJ", "K_rj"],
"I": ["I", "I_nu", "MJy/sr"]
}
try:
... |
def hrbool2bool(s):
"""Convert a string that a user might input to indicate a boolean value of
either True or False and convert to the appropriate Python bool.
* Note first that the case used in the string is ignored
* 't', 'true', '1', 'yes', and 'one' all map to True
* 'f', 'false', '0', 'no', an... |
def get_data_type(datum):
"""Determines the data type to set for the PostgreSQL database"""
if datum.isdigit():
return "integer"
elif datum.replace(".", "", 1).isdigit():
return "decimal"
return "text" |
def get_metal_num(metal):
"""
Get mental layer number from a string, such as "metal1" or "metal10"
:param metal: string that describes the metal layer
:return: metal number
"""
len_metal = len("metal")
parse_num = ""
for idx in range(len_metal, len(metal)):
parse_num += metal[idx... |
def thaw(snowflake):
"""
Tiny function to return the unix timestamp of a snowflake
:param snowflake: a discord snowflake (It's unique, just like you! ha.)
:type snowflake: int
:return: unix timestamp of the message
:rtype: int
"""
return ((snowflake >> 22)+1420070400000)/1000 |
def _format_status_msg(messages, lang):
"""
The status messages are actually a list of dictionary objects that are not suitable for direct Solr export.
This function simplifies the JSON format into a simple text string.
:param messages: a list of dictionary objects
:return: a simple string
"""
... |
def _combine_counts(count1, count2):
""" Sum two counts, but check that if one is 'unknown',
both are 'unknown'. In those cases, return a single
value of 'unknown'. """
if count1 == 'unknown' or count2 == 'unknown':
assert(count1 == 'unknown' and count2 == 'unknown')
return 'unkn... |
def class_from_name(kls):
"""
Returns a class object from a class name.
:param kls: Context qualified name of the class.
:return: A class instance representing the given class.
"""
try:
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
... |
def is_true(input_string):
"""
Return True if the input is a boolean True, or a string that
matches 'true' or 'yes' (case-insensitive).
Return False for all other string inputs.
Raise ValueError otherwise.
"""
if isinstance(input_string, bool):
return input_string # Return as-is
... |
def getminmax_pair_compare(arr):
""" Compare in pairs
If n is odd then initialize min and max as first element.
If n is even then initialize min and max as minimum and maximum of the first two elements respectively.
For rest of the elements, pick them in pairs and compare their maximum and minimum
w... |
def get_default_cve_data(severity):
"""
Return some default CVE metadata for the given severity
:param severity: Severity
:return: score, vectorString
"""
vectorString = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
score = 9.0
severity = severity.upper()
attackComplexity = severity... |
def schomate(T):
"""
Shchomate equation to calculate specific heat of water vapor for a given temperature T.
:param T: Temperature [K]
:return: Heat Capacity [J/mol*K]
"""
t = T / 1000
if 500 <= T < 1700:
a, b, c, d, e = [30.092, 6.832514, 6.793425, -2.53448, 0.082139]
elif T == 1700:
return 2.7175
elif 17... |
def modifiyItems(dic, keyFunction, valueFunction):
"""Applies *funkction(key,value) to each key or value in dic"""
return {keyFunction(key, value): valueFunction(key, value) for key, value in dic.items()} |
def id_for_base(val):
"""Return an id for a param set."""
if val is None:
return "No base params"
if "editor-command" in val:
return "Long base params"
if "ecmd" in val:
return "Short base params"
return "Unknown base params" |
def catalan_base(n):
"""
base case
H(n) = sum (i = 1 to n H(i - 1) * H(n - i))
"""
if n < 2:
return 1
res = 0
for i in range(n):
res += catalan_base(i) * catalan_base(n - i - 1)
return res |
def forward_step(x, parameters):
"""get prediction"""
y_hat = parameters['w'] * x + parameters['b']
return y_hat |
def is_int(value):
"""Checks if the input is a valid integer."""
try:
int(value)
return True
except ValueError and TypeError:
return False |
def filter_checkpoint_dict(model_state_dict, checkpoint_state_dict, dismissed_w):
"""
Filtering checkpoint state dict based on the available modules in model
:return:
"""
updated_state_dict = {}
for name, weight in model_state_dict.items():
if name in checkpoint_state_dict:
u... |
def _get_csv_file_content(csv_file):
"""
returns appropriate csv file content based on input and output is
compatible with python versions
"""
if not isinstance(csv_file, str):
content = csv_file.read()
else:
content = csv_file
if isinstance(content, bytes):
csv_cont... |
def rewrite(path: str, content: str, encoding: str = "utf-8") -> int:
"""
rewrite(path: str, content: str, encoding: str = "utf-8") -> int ---- Clears file and write content into it.
Return amount of written symbols. If file doesn't exist, create it.
"""
with open(path, "w", encoding = encoding) as... |
def is_included_type(type_name):
"""
Those are types for which we already have a class file implemented.
"""
return type_name in [
"AABB",
"Basis",
"Color",
"ObjectID",
"Plane",
"Quaternion",
"Rect2",
"Rect2i",
"Transform2D",
... |
def unorderable_list_difference(expected, actual):
"""Same behavior as sorted_list_difference but
for lists of unorderable items (like dicts).
As it does a linear search per item (remove) it
has O(n*n) performance."""
missing = []
while expected:
item = expected.pop()
try:
... |
def process_div_get_ut_test(div_string):
"""
:param div_string:
:return:
"""
ut_test_res = 0
string_token_list = div_string.split("\n")
for token in string_token_list:
if "tests" in token:
tmp_list = token.split(" ")
if tmp_list[-1] == 'tests':
... |
def _format_hours(values: list) -> list:
"""Return a list of xx:00 formated time strings.
Returns a list xx:00 formated time strings from a list of input hours.
Invalid iput hours (e.g. outside of 0-23) will raise an exception.
Parameters
----------
values: list(int)
List of month numb... |
def coef(name, value, idx=0):
"""
Return a dict that represents a new coefficient.
:param name : int or sequence of int, optional, default: 1
Shape of the new notation, e.g., ``(2, 3)`` or ``2``.
:param value : number, vector with the same shape as `shape`, optional, default: None
... |
def get_departuresMock(_stop_id, route, api_key):
"""Mock TransportNSW departures loading."""
data = {
'stop_id': '209516',
'route': '199',
'due': 16,
'delay': 6,
'real_time': 'y'
}
return data |
def parse_substitution_misc(consequence):
"""
Return fields for syn, non-syn or correlated
"""
elem = consequence.strip().split(' ')
#Default: ['gene', 'G=>A', 'GBS222_0094', 'base', '33']
correlated = False
locus_tag = elem[2]
# Handle: ['gene', 'C=>G', 'GBS222_t08', 'base', '64,... |
def ucsc_link(variant_obj, build=None):
"""Compose link to UCSC."""
build = build or 37
url_template = ("http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg19&"
"position=chr{this[chromosome]}:{this[position]}"
"-{this[position]}&dgv=pack&knownGene=pack&omimGene=pac... |
def files(path="", file_type="", include_path=True, recurse=False):
"""
A flexible function to return files from a given directory.
"""
import os, fnmatch
if '.' not in file_type and file_type != "" and file_type != "/":
file_type = '.' + file_type
if path.strip() == "":
path = os.getcwd()
result = []
d... |
def gcd(a,b):
"""gcd(a,b) returns the greatest common divisor of the integers a and b."""
if a == 0:
return abs(b)
return abs(gcd(b % a, a)) |
def getSquareDistance(p1, p2):
"""
Square distance between two points
"""
dx = p1['x'] - p2['x']
dy = p1['y'] - p2['y']
return dx * dx + dy * dy |
def applied_to_degree(record, degree):
"""(str, str) -> bool
Return True iff student represented by record applied to the degree
>>>applied_to_degree('Jacqueline Smith,Fort McMurray Composite High,2016,MAT,90,94,ENG,92,88,CHM,80,85,BArts', 'BArts')
True
>>>applied_to_degree('Jacqueline Smi... |
def commaList(inputList, fieldToUse):
""" Given an input list and a fieldname of which field to use, return a string that contains all those field items, separated by a comma and a space. """
outstr = ""
for thisItem in inputList:
if outstr != "": outstr += ", "
outstr += thisItem[fieldToUse]
return outstr |
def html_post_line(mark_value, post_filename, title, post_url_done=False, class_name=None):
""" Build post reference line
See: https://jekyllrb.com/docs/liquid/tags/#link
Called by gen_posts_by_vote() directly
Called indirectly by gen_posts_by_tag() via html_posts()
"""
opt_tag = ""... |
def parts_sums(ls):
"""
Loops through and sums the list removing one element each phase.
:param ls: a list of integers.
:return: a new list containing the sum of the old in parts.
"""
result = [sum(ls)]
for x in range(len(ls)):
result.append(result[-1] - ls[x])
return result |
def cmp_expected(real, exp):
"""Compares a value from a trace with an expected value.
If expected is -1, the result doesn't matter
"""
for real_val, exp_val in zip(real, exp):
if exp_val is not None and real_val != exp_val:
return False
return True |
def matrix_mult(a, b):
"""
Performs matrix multiplication on two given matrices.
:param a: lists of lists containing integers.
:param b: lists of lists containing integers.
:return: the right hand side of the equation.
"""
table = [[0 for x in range(len(b))] for x in range(len(a))]
for i... |
def get_publication(context, pub):
""" Get a single publication."""
return {'publication': pub} |
def join_kv(obj, listjoin=", ", tmpl="{k}: {v!r}"):
"""Pass."""
items = []
for k, v in obj.items():
if isinstance(v, list):
v = listjoin.join([str(i) for i in v])
items.append(tmpl.format(k=k, v=v))
return items |
def split_words (sentence):
"""
Returns the words of the recieved sentence
"""
tokens =[]
token = []
for i in range(len(sentence)):
c = sentence[i]
if c == "," or c == ":":
# case: "Today, allright?"
if i+1 == len(sentence):
if tok... |
def convertToNumber (tpl, m):
"""Encode the tuple of an objective pair to an integer, as follows
Given tpl = (v1, v2)
Coded tpl = v1*m + v2
"""
(v1, v2) = tpl
v1 = eval(v1)
v2 = eval(v2)
return v1*m + v2 |
def textColor(colorNumber):
"""Return character changing console text colour."""
return '\033[%dm' % (30 + colorNumber) |
def build_data_strings(data_sources, data_components):
"""
Build source->component strings for layer generation
:param data_sources: List of Data Sources (dicts)
:param data_components: List of Data Components (dicts)
:return: dict mapping of Data Component IDs to generated source->component strings... |
def increment_dictionary_with_dictionary(dict_a, dict_b):
"""
Function to add the values from one dictionary to the values from the same keys in another.
Args:
dict_a: First dictionary to be added
dict_b: Second dictionary to be added
Return:
The combined dictionary
"""
... |
def simple_pixel_mapping(pixel_indices: list, len_pixels: int, sort=True):
"""
Returns a dictionary assigning an integer to identify each pixel index in
pixel_indices. If sort is enabled, it sorts the indices by row, then by column
:param pixel_indices: a list containing the pixel indices
:param le... |
def get_center_point(geom):
"""Returns a center point for the given geometry object.
:param geom: The geometry
:type geom: GEOSGeometry
:rtype: Point
:returns: the center point
"""
if geom:
center = geom.centroid
return center |
def match_module(names):
"""
line is a stripped Fortran statement. (no comment or
white space at beginning or end.) if it contains the beginning of
a module definition, return the module name in upper case
"""
if len(names) < 2: return ""
if names[0] == "MODULE" and names[1] != "PROCEDURE":... |
def getAuthorFromRssEntry(val):
"""
Get the author(s) string for the given RSS-entry
Parameters
----------
val : dict and RSS-entry
DESCRIPTION.
Returns
-------
str just the name or names of the authors or empty string if none
DESCRIPTION.
"""
authors=[]
nwit... |
def bitrange_string(s):
"""parse a string of the form [%d:%d]"""
s = s.lstrip('[')
s = s.rstrip(']')
x = s.split(':')
try:
msb = int(x[0], 10)
lsb = int(x[1], 10)
except:
return None
return (msb, lsb) |
def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
... |
def cm2nm(E_cm):
"""Converts photon energy from absolute cm-1 to wavelength
Parameters
----------
E_cm: float
photon energy in cm-1
Returns
-------
float
Photon energy in nm
Examples
... |
def reverse_hex(hex_str):
"""Reverse a hex foreground string into its background version."""
hex_str = "".join([hex_str[i : i + 2] for i in range(0, len(hex_str), 2)][::-1])
return hex_str |
def entity_delete_by_id(entityId: str):
"""List one entity.
"""
return {"message": "Not yet implemented"} |
def print_point_jitter_info(jitter_x_list, jitter_y_list, boundary_index_list):
"""
print jitter info
"""
max_edge_x = 0.0
max_edge_y = 0.0
max_center_x = 0.0
max_center_y = 0.0
for i in range(len(jitter_x_list)):
if i in boundary_index_list:
if jitter_x_list[i] > ... |
def distance2(a, b):
"""The square of the distance between two (x, y) points."""
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 |
def indent_xml(xml_as_string):
"""
Indents a string of XML-like objects.
This works only for units with no text or tail members, and only for
strings whose leaves are written as <tag /> and not <tag></tag>.
:param xml_as_string: XML string to indent
:return: indented XML string
"""
tabs... |
def repeatedSubstringPatternB(s):
"""
:type s: str
:rtype: bool
"""
return s in (s + s)[1:-1] |
def millify(n, precision=0, drop_nulls=True, prefixes=[]):
"""Humanize number."""
millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
if prefixes:
millnames = ['']
millnames.extend(prefixes)
n = float(n)
millidx = 0
while abs(n) >= 1000:
millidx += 1
n = roun... |
def ensure_object_is_string(item, title):
"""
Checks that the item is a string. If not, raises ValueError.
"""
assert isinstance(title, str)
if not isinstance(item, str):
msg = "{} must be a string. {} passed instead."
raise TypeError(msg.format(title, type(item)))
return None |
def extend(key, term):
""" extend a key with a another element in a tuple
Works if they key is a string or a tuple
>>> extend('x', '.dtype')
('x', '.dtype')
>>> extend(('a', 'b', 'c'), '.dtype')
('a', 'b', 'c', '.dtype')
"""
if isinstance(term, tuple):
pass
elif isinstance(... |
def listify(item):
"""
Check if an item is enclosed in a list and make it a list if not
:param item: item to convert to a list
:return: list containing the original item
"""
if not isinstance(item, list) and item is not None:
return [item]
else:
return item |
def dscp_to_tos(dscp):
"""Convert dscp value to tos."""
tos = int(bin(dscp * 4), 2)
return tos |
def init_params(parameter, numFrames):
"""Auxiliary function to set the parameter dictionary
Parameters
----------
parameter: dict
See the above function visualizeComponentsKAM for further information
Returns
-------
parameter: dict
"""
parameter['startSec'] = 1 * parameter... |
def is_breakpoint(breakpoints: list, pc: int) -> bool:
"""
Determine if the current programme counter is at a breakpoint.
Parameters
----------
breakpoints : list, mandatory
A list of the predetermined breakpoints
pc: int, mandatory
The current value of the program counter
... |
def intersect(a, b):
"""Returns a new list of the intersection of a and b"""
return set(a) & set(b) |
def PRA2HMS (ra):
""" Convert a right ascension in degrees to hours, min, seconds
ra = Right ascension in deg.
"""
################################################################
p = ra / 15.0
h = int(p)
p = (p - h) * 60.0
m = int(p)
s = (p - m) * 60.0
out = " %2d %2d %8.5f"... |
def mrr(ground_truth, prediction):
"""Compute Mean Reciprocal Rank metric. Reciprocal Rank is set 0 if no predicted item is in contained the ground truth.
Args:
ground_truth (List): the ground truth set or sequence
prediction (List): the predicted set or sequence
Returns:
rr (float... |
def _is_dictionary(arg):
"""Check if argument is an dictionary (or 'object' in JS)."""
return isinstance(arg, dict) |
def reverse24(x, k=24):
"""reverses order of bits 0,...,k-1 of an integer. Default is k=24.
If any bits apart form bit 0,...,k-1 are set, an execption is raised.
"""
if x & -(1 << k):
raise ValueError("Too high bits are set for bit reversal")
return sum( ((x >> (k-i-1)) & 1) << i for i in... |
def centerxywh_to_xyxy(boxes):
"""
args:
boxes:list of center_x,center_y,width,height,
return:
boxes:list of x,y,x,y,cooresponding to top left and bottom right
"""
x_top_left = boxes[0] - boxes[2] / 2
y_top_left = boxes[1] - boxes[3] / 2
x_bottom_right = boxes[0] + boxes[2] /... |
def get_percent_crowd_agreement(crowd_selection, selection_counts, total_responses, map_selection_field,
error_val=None):
"""
Figure out how well the crowd agreed and if two answers tied, figure out the agreement for both
:param crowd_selection: the winning selection for a ... |
def link(href, text):
"""Generate a link"""
return '<a href="%s">%s</a>' % (href, text) |
def filter_chroot(chroot, paths):
"""
Takes a sequence of paths, and returns only those that match a given chroot.
Removes the chroot from the prefix of the path.
Filter for, and remove chroots from a set of given paths.
:param chroot: Your zk connections chroot
"""
if not chroot:
... |
def is_upper_case(message) -> bool:
"""This function test if string in uppercase."""
return message.upper() == message |
def prunecomments(blocks):
"""Remove comments."""
i = 0
while i < len(blocks):
b = blocks[i]
if b['type'] == 'paragraph' and (b['lines'][0].startswith('.. ') or
b['lines'] == ['..']):
del blocks[i]
if i < len(blocks) and blocks... |
def __compute_triangle_number(prior_number):
"""
Determine the next triangle number from the given number or the given number
if it is a triangle number.
"""
number = -1
n = 1
while number < prior_number:
number = n * (n + 1) /2
n += 1
return int(number) |
def get_value_of(value, unit_groups):
"""Get value from individual units in unit groups."""
values = {}
for group in unit_groups:
for unit_no, unit in group.items():
values[unit_no] = (unit[value], unit['type'])
return values |
def count_words(text):
"""
Count the number of times each word occurs in text (str). Return dictionary
where keys are unique words and values are word counts. Skip punctuation.
"""
text = text.lower()
skips = [".", ",", ";", ":", "'", '"']
for ch in skips:
text = text.replace(ch, "")... |
def _create_dmaap_key(config_key):
"""Create dmaap key from config key
Assumes config_key is well-formed"""
return "{:}:dmaap".format(config_key) |
def is_nds_service(network_data_source):
"""Determine if the network data source points to a service.
Args:
network_data_source (network data source): Network data source to check.
Returns:
bool: True if the network data source is a service URL. False otherwise.
"""
return... |
def get_pure_payment_type_and_info(payment_type):
""" <payment_type>$<info>
"""
res = payment_type.split('$', 1)
if len(res) == 2:
return res
return res[0], None |
def check_dependencies(details):
"""you can feed this function with the output of
'(requirements|recommends)_details_*'.
The result is True if all dependencies are met.
"""
failed = [key for (key, state) in details.items() if not state]
return len(failed) == 0 |
def run_cb(_func, *_args, **_kwds):
"""
run_cb(func, *args, **kwds) -> any or None
If func is not None, return the result of calling it with the given
arguments; otherwise, do nothing and return None.
"""
if _func is not None: return _func(*_args, **_kwds) |
def v7_multimax(iterable):
"""Return a list of all maximum values.
Or we could make a new list out of the given iterable and then find
the max and loop over it again just as we did before
"""
iterable = list(iterable)
max_item = max(iterable, default=None)
return [
item
for ... |
def _stringify_path(path):
"""
Convert *path* to a string or unicode path if possible.
"""
if isinstance(path, str):
return path
# checking whether path implements the filesystem protocol
try:
return path.__fspath__()
except AttributeError:
pass
raise TypeError(... |
def extract_face_colors(faces, material_colors):
"""Extract colors from materials and assign them to faces
"""
faceColors = []
for face in faces:
material_index = face['material']
faceColors.append(material_colors[material_index])
return faceColors |
def time_range(from_date, to_date):
"""Define the time range specified by the user."""
time_range_params = {}
if from_date:
time_range_params['from_'] = from_date or None
if to_date:
time_range_params['to'] = to_date or None
return time_range_params |
def format_minutes(minutes):
"""Take string format of min:sec and make it float for minutes played"""
# Return None if this player did not play
if 'DNP' in minutes:
return None
min, sec = minutes.split(':')
return float(min) + (float(sec) / 60) |
def process_subtitle(data):
"""get subtitle group name from links"""
result = {}
for s in data:
result[s["tag_id"]] = s["name"]
return result |
def deep_rbx_dict_to_list(data):
"""
Deeply converts "rbx dicts" (ie, dicts with ordered numeric keys) into proper lists.
May not maintain order.
"""
bad_dict: dict = data
for key, value in bad_dict.items():
if not isinstance(value, dict):
continue
bad_dict[key] = ... |
def humanize_filesize(num):
"""
Convert a file size to human-readable form.
eg: in = 2048, out = ('2', 'KB')
"""
if num < 1024.0:
return ('%3.0f' % num, 'B')
for x in ['B', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return ('%3.1f' % num, x)
num /= 1024.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.