content stringlengths 42 6.51k |
|---|
def encode_name(name):
"""
encode_name encodes special characters to be xml-compatible entities
"""
if name is None:
return name
return name.replace("&", "&") |
def _rev_auth_str(client_api_key, user_api_key):
"""Returns a Rev Auth string."""
return 'Rev %s:%s' % (client_api_key, user_api_key) |
def to_year_only(time):
"""Convert date from '2019-05-08T08:27:07.472Z' to '2019'"""
return time[:4] |
def Tn(n):
""" Triangular numbers."""
return n * (n + 1) // 2 |
def calculate_informedness(TPR, TNR):
"""
Calculates the informedness/Youden's J meassure of the supplied data, using the equation as per: https://en.wikipedia.org/wiki/Youden%27s_J_statistic
Informedness = TPR+TNR-1
Input:
TPR: True Positive Rate
TNR: True Negative Rate... |
def remove_long_short_sentences(sentences, s_th=3, l_th=25):
"""
remove too short and too long sentences
:param sentences: a list containing the orig sentences in formant of: [index, sentence indices as list]
:param s_th: the threshold for the short sentences, i.e. sentences with length below this n... |
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
list = []
for i in range(0, len(paragraphs)):
if select(para... |
def crc16_compute(data):
"""Straight port of the bank CRC used by DFU
data is a sequence or generator of integer in 0..255
"""
crc = 0xffff
for d in data:
crc = (crc >> 8 & 0xff) | (crc << 8 & 0xff00)
crc ^= d
crc ^= (crc & 0xff) >> 4 & 0xff
crc ^= crc << 12 & 0xffff... |
def getSubset(mali, identifiers, not_in_set=False):
"""return subset of mali which only contains identifiers."""
new_mali = {}
if not_in_set:
for k, v in mali.items():
if k not in identifiers:
new_mali[k] = v
else:
for k, v in mali.items():
if k ... |
def clean_string(string, remove_parenthesis=False, remove_brackets=False):
"""
Return given string that is strip, uppercase without multiple whitespaces. Optionally, remove parenthesis and brackets. Note that "\t\n\s" will be removed
Parameters
----------
string : str
String to clean
re... |
def find_edges(faces):
"""
Find all edges on a mesh
Parameters
----------
faces : list of lists of three integers
the integers for each face are indices to vertices, starting from zero
Returns
-------
edges : list of lists of integers
each element is a 2-tuple of vertex... |
def inbracket(strg):
""" extraction of bracket content
Parameters
----------
strg : a string with a bracket
Returns
-------
lbra : left part of the string
inbr : string inside the bracket
Examples
--------
>>> strg ='abcd{un texte}'
>>> lbra,inbr = inbracket(strg)
... |
def FirstChar(line):
"""Gets the first non-space character of the line."""
idx = 0
while line[idx] == ' ':
idx += 1
return line[idx] |
def compute_lifting_parameter(lamb, lambda_plane_idxs, lambda_offset_idxs, cutoff):
"""One way to compute a per-particle "4D" offset in terms of an adjustable lamb and
constant per-particle parameters.
Notes
-----
(ytz): this initializes the 4th dimension to a fixed plane adjust by an offset
fo... |
def dict2str(dic):
"""Build a str representation of a dict.
:param dic: The dict to build a str representation for.
:returns: The dict in str representation that is a k=v command list for
each item in dic.
"""
return ','.join("%s=%s" % (key, val)
for key, val in sorted(d... |
def write_time(time_in_secs):
"""Return time in 00h:00m:00s format."""
try:
time = round(float(time_in_secs))
except (TypeError, ValueError):
raise ValueError('Invalid time measure.')
if time < 0:
raise ValueError('Time must be positive.')
hours = time // 3600
minutes =... |
def get_id(page):
"""Extract the id from a page.
Args:
page: a string
Returns:
an integer
"""
start_pos = page.find("<id>")
end_pos = page.find("</id>")
assert start_pos != -1
assert end_pos != -1
start_pos += len("<id>")
return int(page[start_pos:end_pos]) |
def _bytes_to_string(value: bytes) -> str:
"""Decode bytes to a UTF-8 string.
Args:
value (bytes): The bytes to decode
Returns:
str: UTF-8 representation of bytes
Raises:
UnicodeDecodeError
"""
return value.decode(encoding="utf-8") |
def is_string_list(a_list):
"""
Checks that every element is a string
:param a_list: []
:return: True if list of strings and False otherwise
"""
for element in a_list:
if not isinstance(element, str):
return False
return True |
def fahrenheit_to_celsius(fahrenheit_temp):
"""Calculate celsius temperature from fahrenheit
PARAMETERS
----------
fahrenheit_temp : float
A temperature in degrees
RETURNS
-------
temperature : float
"""
# apply formula
return (fahrenheit_temp - 32)*(5/9) |
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin, it should be called when the configuration of the plugin is changed during the
operation of the device service.
The new configuration category should be passed.
Args:
handle: handle returned by the plugin initialis... |
def rejoin_parts_multiple_index(param_parts):
"""Join parameter name parts."""
return "_".join(param_parts[1:-2]) |
def radboud_cervix_concepts2labels(report_concepts):
"""
Convert the concepts extracted from cervix reports to the set of pre-defined labels used for classification
Params:
report_concepts (dict(list)): the dict containing for each cervix report the extracted concepts
Returns: a dict containing for each ... |
def process_groups(text, is_group_member, process_group, is_group_member_parameters={}, process_group_parameters={}):
"""Processes groups with a block of text.
Determining whether a line in the input text is a group member and processing said groups is delegated to the supplied functions.
"""
text = t... |
def zero_ten_to_value(scale_value):
"""
This method will transform a string value from the 0-10 scale to its
confidence integer representation.
The scale for this confidence representation is the following:
.. list-table:: 0-10 to STIX Confidence
:header-rows: 1
* - 0-10 Scale
... |
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower()+'_'+language[p+1:].lower()
... |
def guess_type(s):
""" attempt to convert string value into numeric type """
sc = s.replace(',', '') # remove comma from potential numbers
try:
return int(sc)
except ValueError:
pass
try:
return float(sc)
except ValueError:
pass
return s |
def multiplicacion_por_suma(n,m):
"""
int, int --> int
OBJ: crear una lista con m elementos (0,m-1), rellenar los elementos con n y sumar los elementos
"""
if m==0 or n==0:
return 0
elif m==1:
return n
elif n==1:
return m
elif n>0 and m>0: #n y m positivos
... |
def merge_metrics(dict_1: dict, dict_2: dict):
"""
Merge dicts with common keys as list
"""
dict_3 = {**dict_1, **dict_2}
for key, value in dict_3.items():
if key in dict_1 and key in dict_2:
dict_3[key] = dict_1[key] + value # since dict_1 val overwritten by above merge
ret... |
def _escape_presto(val: str) -> str:
"""ParamEscaper
https://github.com/dropbox/PyHive/blob/master/pyhive/common.py"""
return "'{0}'".format(val.replace("'", "''")) |
def _int_to_shot_id(shot_int):
"""
Returns: integer to shot id
"""
return str(shot_int).zfill(10) + ".jpg" |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False |
def _check_from_statement(current: int, following: int) -> bool:
""" """
return (current == 108 and following == 109) or (
current == 108 and following == 84
) |
def d1l(dx, fc, i):
""" first-order, left-sided derivative at index i """
D = (fc[i] - fc[i-1])/dx
return D |
def to_kelvin(value, unit):
"""
:param value: magnitude in float or int format
:param unit: units of the input one of C, F, R, or K
:return: a float value in Kelvin converted from the input unit
"""
kmap = {
'C': (lambda c: c + 273.15),
'F': (lambda f: (f + 459.67) / 1.8),
... |
def isTokenStepString(s):
"""Determine whether this is a placeholder string"""
if len(s) < 2:
return False
return s[0] == "~" and s[-1] == "~" |
def _val_to_byte_list(number, num_bytes, big_endian=True):
"""
Converts an integer into a big/little-endian multi-byte representation.
Similar to int.to_bytes() in the standard lib but returns a list of integers
between 0 and 255 (which allows for bitwise arithmetic) instead of a bytearray.
"""
... |
def gini_gain_quotient(
left_total,
right_total,
left_amount_classified_zero,
left_amount_classified_one,
right_amount_classified_zero,
right_amount_classified_one):
"""
Returns a pair of numbers that represent the Gini gain, given a split in
the dataset.
... |
def CodePagesToReachedSize(reached_symbol_names, page_to_symbols):
"""From page offset -> [all_symbols], return the reached portion per page.
Args:
reached_symbol_names: ([str]) List of reached symbol names.
page_to_symbols: (dict) As returned by CodePagesToMangledSymbols().
Returns:
{page offset (i... |
def modified_secant(f, x0, x1, x2, eps=5e-6, max_iterations=50):
"""
Function that finds a root using a modified Secant (or Inverse quadratic interpolation ) method for a given function
f(x). The function finds the root of f(x) with a predefined absolute accuracy epsilon. The function excepts three
star... |
def is_finite_ordinal(n):
"""
Return True if n is a finite ordinal (non-negative int).
"""
return isinstance(n, int) and n >= 0 |
def numToDigits(num, places):
"""Helper, for converting numbers to textual digits."""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s |
def numberOfPaths(nXm_matrix):
"""
Returns the total number of paths from the top left
to the bottom right by moving right and down in a 2D array
of size n x m. Where cells can only contain `1` or `0` while
real paths can only contain `1`.
"""
hight = len(nXm_matrix)
width = len(nXm_matr... |
def update_results(results, add):
"""Given a map of results for all ontologies and a map of results to add,
append the results to the lists in the map."""
results["error"] = results["error"] + add["error"]
results["warn"] = results["warn"] + add["warn"]
results["info"] = results["info"] + add["info"... |
def get_languages_and_names(ref_texts):
"""Obtain list of languages and names in our reference texts."""
found_names=[]
found_languages=[]
for ref_text in ref_texts:
found_languages.append(ref_text.language)
found_names.append(ref_text.name)
return found_languages, found_names |
def RotateRightWithCarry(cpu, unused, source):
""" From z80 Heaven:
8-bit rotation to the right. the bit leaving on the right is copied into the carry, and into bit 7.
"""
# Fairly similar to above, but note that bit 0 is copied both to bit 7 and 8 (carry set/reset)
return (source >> 1) | ((source &... |
def _read_genel_fields_until_char_blank(card_fields, istart):
"""somewhat loose parser helper function for GENEL"""
new_fields = []
i = 0
for i, field in enumerate(card_fields[istart:]):
if field is None:
break
if field.upper() in ['UD', 'K', 'S', 'Z']:
break
... |
def sort_tups(seq):
"""Nicely sorts a list of symbolic tuples, in a way we'll describe later."""
return sorted(seq,key=lambda k:(-len(k),k),reverse=True)[::-1] |
def _get_previous_month(month, year):
"""Returns previous month.
:param month: Month (integer from 1...12).
:param year: Year (integer).
:return: previous_month: Previous month (integer from 1...12).
:return: previous_year: Previous year (integer).
"""
previous_month = month - 1
if pr... |
def newton_sqrt1(x):
"""Return the square root of x using Newton's method"""
val = x
while True:
last = val
val = (val + x / val) * 0.5
if abs(val - last) < 1e-9:
break
return val |
def val_to_freq(word_value, scalar):
"""turn value to integer"""
return {k: abs(int(word_value[k] * scalar)) for k in word_value} |
def hash_code(data):
"""Generate hash code using builtin hash() function.
:param data: Data to generate hash code for
"""
# h = 0
# for c in data:
# h = (ord(c) + (31 * h)) % MAX_32_INT
# return h
return abs(hash(data)) |
def aic_hmm(log_likelihood, dof):
"""
Function to compute the Aikaike's information criterion for an HMM given
the log-likelihood of observations.
:param log_likelihood: logarithmised likelihood of the model
dof (int) - single numeric value representing the number of trainable
parameter... |
def getdetsize(ccdshape, xbin, ybin):
"""Set the detector size basec on the binning and shape of the ccd
ccdshape: tuple
Shape of the detector
xbin: int
x binning
ybin: int
y binning
"""
x1=1
y1=1
x2=xbin*ccdshape[1]
y2=xbin*ccdshape[0]
... |
def merge(arr1, arr2):
"""Merge two sorted arrays without duplicates
Args:
arr1: first sorted array
arr2: second sorted array
Returns:
sorted array comprises items from both input arrays
"""
i, j = 0, 0
total = []
try:
total_len = len(arr1) + len(arr2)
ex... |
def maptostr(target_list):
"""Casts a list of python types to a list of strings
Args:
target_list (list): list containing python types
Returns:
List containing strings
"""
return [str(each) for each in target_list] |
def has_double_chars(entry):
"""Return True if there are double chars (aa, bb,...) in the given string."""
for idx in range(1, len(entry)):
if entry[idx] == entry[idx - 1]:
return True
return False |
def _diff_cache_cluster(current, desired):
"""
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fidd... |
def guard_is_time_to_retry(guard, time):
"""Tests if enough time has passed to retry an unreachable
(i.e. hibernating) guard. Derived from entry_is_time_to_retry() in
entrynodes.c."""
if (guard['last_attempted'] < guard['unreachable_since']):
return True
diff = time - guard['unrea... |
def solution3(nums):
"""convert nums to set -> for each n, continue searching n - 1 and n + 1"""
s = set(nums)
counted = set()
max_size = 0
def countStep(x, step):
if x in s:
counted.add(x)
return countStep(x + step, step) + 1
else:
return 0
... |
def merge_or(base, to_merge, exclusive):
"""
Merge json schemas assuming a 'oneOf' or 'anyOf' command
The idea is to find out the differences between 'base' and 'to_merge'.
If a property is in 'base' and not in 'to_merge', it is added to all the alternative
properties except 'to_merge'.
If a pr... |
def calcCropSensorWidth(sensorWidth, nativeAspectRatio, mediaAspectRatio):
"""
Calculate effective/utilised width of camera sensor when image/video is
recorded at non-native aspect ratio.
"""
cropRatio = (nativeAspectRatio[1] / nativeAspectRatio[0]
) / (mediaAspectRatio[1] / mediaA... |
def update_schema(schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_ne... |
def rle(seq):
"""Create RLE"""
newstr = seq[0]
initial_val = 1
for index, char in enumerate(seq[1:]):
if char == newstr[-1]:
initial_val += 1
if index == len(seq) - 2:
newstr += str(initial_val)
elif char != newstr[-1]:
if initial_val... |
def _get_canonical_query_string(query):
"""Get canonical query string."""
query = query or ""
return "&".join(
[
"=".join(pair) for pair in sorted(
[params.split("=") for params in query.split("&")],
)
],
) |
def to_seconds(days):
"""convert days to seconds"""
return days*24*60*60 |
def fahr2cel(t):
"""Converts an input temperature in fahrenheit to degrees celsius
Inputs:
t: temperature, in degrees Fahrenheit
Returns:
Temperature, in C
"""
return (t - 32) * 5 / 9 |
def rpn2splitter(splitter_rpn):
"""
Convert from splitter_rpn to splitter.
Recurrent algorithm to perform the conversion.
Every time combines pairs of input in one input,
ends when the length is one.
Parameters
----------
splitter_rpn :
splitter in reverse polish notation
... |
def uniquify(l):
"""
Return the given list without duplicates, retaining order.
See Dave Kirby's order preserving uniqueifying list function
http://www.peterbe.com/plog/uniqifiers-benchmark
"""
seen = set()
seen_add = seen.add
uniques = [x for x in l if x not in seen and not seen_add(x... |
def getannotationstrings(cann):
"""
get a nice string summary of a curation
input:
cann : dict from /sequences/get_annotations (one from the list)
output:
cdesc : str
a short summary of each annotation
"""
cdesc = ''
if cann['description']:
cdesc += cann['description... |
def check_float(string):
"""
Helper function for checking if a string can be converted to a float.
:param string: string to be verified as a float
:returns: True if the string can be converted to a float, False otherwise
"""
try:
float(string)
return True
except ValueError:
... |
def padding(sent, sequence_len):
"""
convert sentence to index array
"""
if len(sent) > sequence_len:
sent = sent[:sequence_len]
padding = sequence_len - len(sent)
sent2idx = sent + [0]*padding
return sent2idx, len(sent) |
def path_from_canonical_parts(prefix, controller, action, args):
"""
Returns a route ('/admin/users/edit/3') from canonical parts
('admin', 'users', 'edit', [id])
"""
args_parts = ['<' + x + '>' for x in args]
route_parts = [prefix, controller, action] + args_parts
route_parts = [x for x in ... |
def _normpath(path):
"""
Globus Transfer-specific normalization, based on a careful reading of the stdlib
posixpath implementation:
https://github.com/python/cpython/blob/ea0f7aa47c5d2e58dc99314508172f0523e144c6/Lib/posixpath.py#L338
this must be done without using os.path.normpath to be compatib... |
def timedelta_nice_format(td_object):
"""Create string with nice formatted time duration"""
if td_object is None:
return "None"
seconds = int(td_object.total_seconds())
if seconds == 0:
return "0 seconds"
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
... |
def construct_nomscen(mdl):
"""
Creates a nominal scenario nomscen given a graph object g by setting all function modes to nominal.
Parameters
----------
mdl : Model
Returns
-------
nomscen : scen
"""
nomscen={'faults':{},'properties':{}}
nomscen['properties']['time']=0.0
... |
def rsqrt_hidden(hidden_size):
"""rsqrt of hidden size"""
return float(hidden_size) ** -0.5 |
def reverse_dict_old(dikt):
"""
takes a dict and return a new dict with old values as key and old keys as values (in a list)
example
_reverse_dict({'AB04a':'b', 'AB04b': 'b', 'AB04c':'b', 'CC04x': 'c'})
will return
{'b': ['AB04a', 'AB04b', 'AB04c'], 'c': 'CC04x'}
"""
new_dikt = {... |
def quicksort(items):
"""O(n * log n)."""
if len(items) < 2:
return items
else:
pivot_index = len(items) // 2
pivot = items[pivot_index]
left = [num for i, num in enumerate(items) if num <= pivot and i != pivot_index]
right = [num for i, num in enumerate(items) if num... |
def is_quote(code, idx=0):
"""Position in string is an unescaped quotation mark."""
return (0 <= idx < len(code) and
code[idx] == '"' and
(idx == 0 or code[idx-1] != '\\')) |
def update_in(coll, path, update, default=None):
"""Creates a copy of coll with a value updated at path."""
if not path:
return update(coll)
elif isinstance(coll, list):
copy = coll[:]
# NOTE: there is no auto-vivication for lists
copy[path[0]] = update_in(copy[path[0]], path... |
def other_elements(element):
"""
Function to work with str,int,float
"""
print(element)
return 111 |
def dydt(x, y, a):
"""Computes the equation for y prime"""
dy = x + a * y
return dy |
def calc_q_c1ncs(q_c1n, delta_q_c1n):
"""
q_c1ncs from CPT, Eq 2.10
"""
q_c1ncs = q_c1n + delta_q_c1n
return q_c1ncs |
def check_overlap(bbox1, bbox2):
"""
Checks if 2 boxes are overlapping. Also works for 2D tuples.
Args:
bbox1: [x1, y1, x2, y2] or [z1, z2]
bbox2: [x1, y1, x2, y2] or [z1, z2]
Returns:
bool
"""
if bbox1[0] > bbox2[2] or bbox2[0] > bbox1[2]:
return False
if l... |
def split_flat_pair_dict(the_dict):
"""Combine a pair of file dictionaries
Parameters
----------
the_dict : `dict`
A dictionary of data_ids or filenames keyed by raft, slot, filetype
Returns
-------
out_dict : `dict`
A dictionary of data_ids or filenames keyed by raft, slot... |
def sort_datasplit(split):
"""Sorts a single split of the SidechainNet data dict by ascending length."""
sorted_len_indices = [
a[0]
for a in sorted(enumerate(split['seq']), key=lambda x: len(x[1]), reverse=False)
]
for datatype in split.keys():
split[datatype] = [split[datatype... |
def findNextOpr(txt):
"""
>>> findNextOpr(' 3* 4 - 5')
3
>>> findNextOpr('8 4 - 5')
6
>>> findNextOpr('89 4 5')
-1
"""
# decide whether the data type is correct
if not isinstance(txt, str) or len(txt) <= 0:
return "error: findNextOpr"
# use for ... |
def update_loss_dict(old, new, weight=1, inplace=True):
"""Update a dictionary of losses/metrics with a new batch
Parameters
----------
old : dict
Previous (accumulated) dictionary of losses/metrics
new : dict
Dictionary of losses/metrics for the current batch
weight : float, de... |
def compare_pval_alpha_tf(p_val, alpha=.05):
""" this functions tests p values vs our chosen alpha returns bool"""
status = None
if p_val > alpha:
status = False
else:
status = True
return status |
def matrix_to_relations(matrix):
"""
Reads a boolean matrix and receives it as a list of tuples of relations
:param matrix: list of lists
:return: list of tuples
>>> matrix_to_relations([[1, 1, 0, 0],\
[1, 1, 0, 0],\
[0, 0, 1, 1],\
[0, 0, ... |
def parse_body(body_text):
"""
param: body_text :: string
"""
try:
split_text = body_text.rsplit(" ")
source_lang = split_text[0]
target_lang = split_text[1]
query_string = " ".join(split_text[2:])
except Exception:
query_string = """Message not well form... |
def translation(vertex, delta):
"""Move, or slide, a coordinate in 2d space."""
[vertex_x, vertex_y] = vertex
[delta_x, delta_y] = delta
return [vertex_x + delta_x, vertex_y + delta_y] |
def custom_MLP_lr_scheduler(epoch, lr):
"""Learning rate schedule for use with MLPs
Parameters
----------
epoch : int
The current epoch of training
lr : float
The current learning rate
Returns
-------
Float
The learning rate for the next epoch of training
""... |
def is_leap(year):
"""This function takes a year and returns if it is a leap year.
Param: year (positive integer)
Return: boolean
"""
return year % 400 == 0 or year % 4 == 0 and year % 100 != 0 |
def OOV_handeler(lemma, pos):
"""
Handles OOV words
:param lemma: str
:param pos: str
:return: lemma, pos
"""
if pos in [".", "?", ","]: lemma = "<PUNCT>"
elif pos == 'NUM': lemma = "<NUM>"
elif pos == 'SYM': lemma = "<SYM>"
return lemma, pos |
def _remove_missing_resource_ids(config_records, resource_ids):
"""
Remove resource_ids found in config_results and return any remaining resource_ids
:param config_records: config compliance records
:param resource_ids: list of resource ids
:returns: list of resource IDs found in compliance rec... |
def _add_new_line_if_none(s: str):
"""Since graphviz 0.18, need to have a newline in body lines.
This util is there to address that, adding newlines to body lines
when missing."""
if s and s[-1] != "\n":
return s + "\n"
return s |
def factors_of(number):
"""Get the factors of a given number.
:param number: The number for which the factors will be obtained.
:type number: int
:rtype: list[int]
:raise: TypeError
"""
if type(number) is not int:
raise TypeError("Factors may only be acquired for an integer.")
... |
def string(x, n):
"""Convert a float, x, to a string with n significant figures.
This function returns a decimal string representation of a float
to a specified number of significant figures.
>>> create_string(9.80665, 3)
'9.81'
>>> create_string(0.0120076, 3)
'0.0120'
>>> create_string(100000, 5)
'100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.