content stringlengths 42 6.51k |
|---|
def parse_word(word, s):
"""Parses the word and counts the number of digits, lowercase letters,
uppercase letters, and symbols. Returns a dictionary with the results.
If any character in the word is not in the set of digits, lowercase
letters, uppercase letters, or symbols it is marked as a bad characte... |
def invmod(a,b):
"""
Return modular inverse using a version Euclid's Algorithm
Code by Andrew Kuchling in Python Journal:
http://www.pythonjournal.com/volume1/issue1/art-algorithms/
-- in turn also based on Knuth, vol 2.
"""
a1, a2, a3 = 1, 0, a
b1, b2, b3 = 0, 1, b
while b3 != 0:
... |
def get_bit_values(number, size=32):
"""
Get bit values as a list for a given number
>>> get_bit_values(1) == [0]*31 + [1]
True
>>> get_bit_values(0xDEADBEEF)
[1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, \
1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1]
You may override the... |
def get_array_prepare(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_prepare__) for i, x in enumerate(args)
... |
def re_escape(string: str) -> str:
"""
Escape literal backslashes for use with :mod:`re`.
.. seealso:: :func:`re.escape`, which escapes all characters treated specially be :mod:`re`.
:param string:
"""
return string.replace('\\', "\\\\") |
def _makeDefValues(keys):
"""Returns a dictionary containing None for all keys."""
return dict(( (k, None) for k in keys )) |
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" |
def get_subset_tasks(all_tasks, ratio):
"""Select a subset of tasks from all_tasks, keeping some % from each temp.
Args:
all_tasks: List of tasks like ['00001:001', ...]
ratio: A number between 0-1, specifying how many of the tasks to keep.
Returns:
tasks: An updated list, with the r... |
def extract_user_text(info):
"""
Extract known information from info['user_text'].
Current known info is
+ 'Calibration data for frame %d'
"""
user_text = info['user_text']
if b'Calibration data for' in user_text[:20]:
texts = user_text.split(b'\n')
for i in range(info['Numbe... |
def reverse_dict_partial(dict_obj):
"""Reverse a dict, so each value in it maps to one of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to the key that mapped to it.
Example
-------
>>> dicti... |
def generate_error(source: str, error: str):
"""Generate error message"""
return {
'source': source,
'error': error,
} |
def _read24(arr):
"""Parse an unsigned 24-bit value as a floating point and return it."""
ret = 0.0
for b in arr:
ret *= 256.0
ret += float(b & 0xFF)
return ret |
def validate_threshold(threshold, sim_measure_type):
"""Check if the threshold is valid for the sim_measure_type."""
if sim_measure_type == 'EDIT_DISTANCE':
if threshold < 0:
raise AssertionError('threshold for ' + sim_measure_type + \
' should be greater tha... |
def problem_2_try2(limit=4000000):
""" attempted optimize for not checking even,
but actually marginally slower? """
f_1 = 0
f_2 = 1
even_sum = 0
while f_1 < limit:
# at start of iter, f_1 should always be even
even_sum += f_1
for _ in range(3):
f_1, f_2... |
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55):
""" m*wavelength = neff * delta_length """
return m * wavelength / neff |
def get_dict_of_struct(connection, host):
"""
Transform SDK Host Struct type to Python dictionary.
"""
if host is None:
return dict()
hosts_service = connection.system_service().hosts_service()
host_service = hosts_service.host_service(host.id)
clusters_service = connection.system_s... |
def to_set(list):
"""Crappy implementation of creating a Set from a List. To cope with older Python versions"""
temp_dict = {}
for entry in list:
temp_dict[entry] = "dummy"
return temp_dict.keys() |
def generate_latex_error(error_msg):
""" generate_latex_error(error_msg: str) -> str
this generates a piece of latex code with an error message.
"""
error_msg = error_msg.replace("\n", "\\MessageBreak ")
s = """\\PackageError{vistrails}{ An error occurred when executing vistrails. \\MessageBreak... |
def maximum_difference_sort_value(contributions):
"""
Auxiliary function to sort the contributions for the compare_plot.
Returns the value of the maximum difference between values in contributions[0].
Parameters
----------
contributions: list
list containing 2 elements:
a Numpy.... |
def color565(r, g=0, b=0):
"""Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As
a convenience this is also available in the parent adafruit_rgb_display
package namespace."""
try:
r, g, b = r # see if the first var is a tuple/list
except TypeError:
pass
r... |
def find_match_brackets(search, opening='<', closing='>'):
"""Returns the index of the closing bracket that matches the first opening bracket.
Returns -1 if no last matching bracket is found, i.e. not a template.
Example:
'Foo<T>::iterator<U>''
returns 5
"""
index = ... |
def fib(n):
"""
a pure recursive fib
"""
if n < 2:
return 1
else:
return fib(n-1) + fib(n-2) |
def get_graph_element_name(elem):
"""Obtain the name or string representation of a graph element.
If the graph element has the attribute "name", return name. Otherwise, return
a __str__ representation of the graph element. Certain graph elements, such as
`SparseTensor`s, do not have the attribute "name... |
def check_for_lower_adj_height(arr, index_row, index_col) -> bool:
"""
Args:
arr: heightmap array
index_row: row index of location to check adjacent locations for lower or equally low height
index_col: column index of location to check adjacent locations for lower or equally low height
... |
def scalar_in_sequence(x, y):
"""Determine whether the scalar in the sequence."""
if x is None:
raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, "
"but the scalar is not.")
if y is None:
raise ValueError("Judge scalar in... |
def _inFilesystemNamespace(path):
"""
Determine whether the given unix socket path is in a filesystem namespace.
While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
above support PF_UNIX sockets in an "abstract namespace" that does not
correspond to any path. This function retur... |
def convertOrfToGenomic(start, end, strand, orfStart):
"""Convert domain coordinates in ORF to genomic.
@param start: Domain start coord
@param end: Domain end coord
@param strand: Strand
@param orfStart: ORF start coord
@return: (gStart, gEnd)
"""
if strand=='+':
gStart = o... |
def create_nc_dimension(nc_file, shape):
"""
Cria as dimensoes do arquivo (x, y, z, w)
time = UNLIMITED ;
level = UNLIMITED ;
latitude = shape[0] ;
longitude = shape[1] ;
Parameters
----------
nc_file : netCDF4.Dataset
Dataset file to create the dimensions.
... |
def sumofDigits(n):
"""calculate the sum of the digits of an input integer"""
assert n >= 0 and int(n) == n, 'The number has to be positive integers only'
if n == 0:
return 0
else:
return int(n%10) + sumofDigits(int(n/10)) |
def MID(text, start_num, num_chars):
"""
Returns a segment of a string, starting at start_num. The first character in text has
start_num 1.
>>> MID("Fluid Flow", 1, 5)
'Fluid'
>>> MID("Fluid Flow", 7, 20)
'Flow'
>>> MID("Fluid Flow", 20, 5)
''
>>> MID("Fluid Flow", 0, 5)
Traceback (most recent ca... |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
if num < 1024.0:
return "%3.0f bytes" % (num)
num /= 1024.0
for x in ['KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def chunks(seq, n) :
"""
Description
----------
Split list seq into n list
Parameters
----------
seq : input list
n : number of elements to split seq into
Returns
-------
list of n list
"""
return [seq[i::n] for i ... |
def toggle_popover(n, is_open):
"""
Shows/hides informance on toggle click
:param n: num clicks on toggle button
:param is_open: open state of class warnings
:return: negated open state if click, else open state
"""
if n:
return not is_open
return is_open |
def reference(api, line):
"""
day on day line
:param api: plugin api object, select is not implement during init.
:param line: tuple-like ((timestamp, value)), the timestamp and value is const
:return: (reference_name, [[timestamp, value]]), tuple is not recommended
"""
res = []
if len(... |
def bar(x, greeting='hello'):
"""bar greets its input"""
return f'{greeting} {x}' |
def badhash(x):
"""
Just a quick and dirty hash function for doing a deterministic shuffle based on image_id.
Source:
https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
"""
x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF
x = (((x ... |
def _mask_token(token: str) -> str:
"""Mask a PAT token for display."""
if len(token) <= 8:
# it's not valid anyway, just show the entire thing
return token
else:
return "%s%s%s" % (token[0:4], len(token[4:-4]) * "*", token[-4:]) |
def coupling_list2dict(couplinglist):
"""Convert coupling map list into dictionary.
Example list format: [[0, 1], [0, 2], [1, 2]]
Example dictionary format: {0: [1, 2], 1: [2]}
We do not do any checking of the input.
Return coupling map in dict format.
"""
if not couplinglist:
ret... |
def will_reciprocate(data_dict, index):
"""Searches the text of the request for phrases that suggest a promise to
give pizza to someone else. data_dict is a dictionary of lists,and any given
index in the lists corresponds to the same post for different keys.
"""
title = data_dict["title"][index... |
def setDefaultOptionIfMissing(options,defaultOptions):
"""
If options is none or empty, return defaultOptions directly;
Otherwise set option in options if option exist in defaultOptions but does not exist in options.
"""
if not defaultOptions:
return {} if options is None else options
i... |
def create_row(*fields):
""" generate aligned row """
row = ""
for field in fields:
value, width, padding, alignment = \
field[0], field[1], field[2], field[3]
value = value[:(width - padding)] + ".." \
if len(value) > width - padding else value
if alig... |
def convert_composition_string_to_dict( X ):
"""
Converts a composition string of style "CH4:0.02, N2:0.01, O2:0.45"
into a dict, a la composition['CH4'] = 0.02
"""
results = {}
for sp in X.split(","):
st = sp.strip()
try:
results[ st.split(":")[0].strip() ] = float( ... |
def is_ignored_file(f):
"""Check if this file has to be ignored.
Ignored files includes:
- .gitignore
- OS generated files
- text editor backup files
- XCF image files (Gimp)
"""
return f == '.gitignore' or f == '.DS_Store' or f == '.DS_Store?' or \
f == '.Spotlight-V100' or f =... |
def tick(price: float, tick_size: float = 0.05) -> float:
"""
round the given price to the nearest tick
>>> tick(100.03)
100.05
>>> tick(101.31, 0.5)
101.5
>>> tick(101.04, 0.1)
101.0
>>> tick(100.01,0.1)
100.0
"""
return round(round(price / tick_size) * tick_size, 2) |
def uint16_tag(name, value):
"""Create a DMAP tag with uint16 data."""
return name.encode('utf-8') + \
b'\x00\x00\x00\x02' + \
value.to_bytes(2, byteorder='big') |
def is_power_of_2(num):
"""
Check if the input number is a power of 2.
"""
return num != 0 and ((num & (num - 1)) == 0) |
def get_year_filename(file):
"""Get the year from the datestr part of a file."""
date_parts = [int(d) for d in file.split('.')[-2].split('-')]
return date_parts[0] |
def h5str(obj):
"""strings stored in an HDF5 from Python2 may look like
"b'xxx'", that is containg "b". strip these out here
"""
out = str(obj)
if out.startswith("b'") and out.endswith("'"):
out = out[2:-1]
return out |
def filename(tmpdir):
"""Use this filename for the tests."""
return f"{tmpdir}/test.mp4" |
def set_whole_node_entry(entry_information):
"""Set whole node entry
Args:
entry_information (dict): a dictionary of entry information from white list file
Returns:
dict: a dictionary of entry information from white list file with whole node settings
"""
if "submit_attrs" in entry_... |
def flip(board):
"""Returns horizontal mirror image of board with inverted colors."""
flipped_board = dict()
for square, piece in board.items():
flipped_board[(7 - square[0], square[1])] = piece.swapcase()
return flipped_board |
def unzip(l):
"""
Returns the inverse operation of `zip` on `list`.
Args:
l (list): the list to unzip
"""
return list(map(list, zip(*l))) |
def tanh_derivative(x):
"""
Actual derivative: tanh'(x) = 1 - (tanh(x))^2 but logic same as sigmoid
derivative
"""
return 1 - x ** 2 |
def _get_short_lang_code(lang: str) -> str:
"""Returns an alternative short lang code"""
return lang if "zh" in lang else lang.split("-")[0] |
def changed_keys(a, b):
"""Compares two dictionaries and returns list of keys where values are different"""
# Note! This function disregards keys that don't appear in both dictionaries
keys = []
if a is not None and b is not None:
for k, _ in b.items():
if k in a and a[k] != b[k]:
... |
def filter_duplicates(donors, acceptors):
"""
Filter out duplicate donor acceptor atom pairs
"""
pairs = sorted(list(set([(d, acceptors[idx]) for idx, d in enumerate(donors)])))
new_donors, new_acceptors = [], []
for d, a in pairs:
new_donors.append(d)
new_acceptors.append(a)
... |
def index_in_str(text, substring, starting=0):
"""
Gets index of text in string
:arg text: text to search through
:arg substring: text to search for
:arg starting: offset
:return position
"""
search_in = text[starting:]
if substring in search_in:
return search_in.index(subst... |
def getHeaderObj(relationname, attribute_conf):
"""Generate header of ARFF file in JSON format
Args:
relationname (string): relation name, can be understood as name of dataset
attribute_conf (dict): attribute configuration load from file
Returns:
dict: header JSON object of ARFF fo... |
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
This is not pythonic, but needed for certain situations.
"""
components = data.split("_")
capital_components = "".join(x.title() for x in components[1:])
return f"{components[0]}{capital_components}" |
def i2n(i):
"""ip to number """
ip = [int(x) for x in i.split('.')]
return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3] |
def heuristic_function_1(game_state, move):
"""Give a heuristic evaluation in form of a number
of how good it would be to make "move" to "game_state". The value is
higher the better the move, regardless of the player to make it.
This function give higher values to more central columns.
"""
retu... |
def hsv2rgb(c):
"""Convert an hsv color to rgb."""
h,s,v = c
h = h%360
h = 6*((h/360)%1)
i = int(h)
f = h-i
p = v*(1-s)
q = v*(1-s*f)
t = v*(1-s*(1-f))
if (i==6) or (i==0):
return (v,t,p)
elif i == 1:
return (q,v,p)
elif i == 2:
return (p,v,t)
elif i == 3:
... |
def has_more_results(response):
"""
Checks the `exceededTransferLimit` flag of the REST API response. If set, this
flag indicates that there are more rows after the page offset than could be
returned in the response, which means that we need to continue paging.
"""
return response.get('exceededTransferLimi... |
def calculate_posterior(bayes_factor, prior_prob):
"""
Calculate the posterior probability of association from the bayes factor
and prior probability of association.
"""
if bayes_factor == float('inf'):
return 1.0
posterior_odds = bayes_factor * prior_prob / (1.0 - prior_prob)
return... |
def Val(text):
"""Return the value of a string
This function finds the longest leftmost number in the string and
returns it. If there are no valid numbers then it returns 0.
The method chosen here is very poor - we just keep trying to convert the
string to a float and just use the last successful... |
def tuple_to_bool(value):
"""
Converts a value triplet to boolean2 values
From a triplet: concentration, decay, threshold
Truth value = conc > threshold/decay
"""
return value[0] > value[2] / value[1] |
def u8(x: int) -> bytes:
"""
Encode an 8-bit unsigned integer.
"""
assert 0 <= x < 256
return x.to_bytes(1, byteorder='little') |
def valfilter(predicate, d, factory=dict):
""" Filter items in dictionary by value
>>> iseven = lambda x: x % 2 == 0
>>> d = {1: 2, 2: 3, 3: 4, 4: 5}
>>> valfilter(iseven, d)
{1: 2, 3: 4}
See Also:
keyfilter
itemfilter
valmap
"""
rv = factory()
for k, v in d... |
def get_color_index(name_index, color_arr):
"""
examine color index due to the name index value
:param name_index: baby name index
:param color_arr: color array
:return: color index
"""
if name_index > len(color_arr):
color_index = name_index % len(color_arr)
else:
color... |
def concat_multi_expr(*expr_args):
"""Concatenates multiple expressions into a single expression by using the
barrier operator.
"""
me = None
for e in expr_args:
me = me | e if me else e
return me |
def _get_sub_dict(d, *names):
"""
get sub dictionary recursive.
"""
for name in names:
d = d.get(name, None)
if d is None:
return dict()
return d |
def DefficiencyBound(D, k, k2):
""" Calculate the D-efficiency bound of an array extension
Args:
D (float): D-efficiency of the design
k (int): numbers of columns
k2 (int): numbers of columns
Returns:
float: bound on the D-efficiency of extensions of a design with k columns... |
def residue_vs_water_hbonds(hbonds, solvent_resn):
"""
Split hbonds into those involving residues only and those mediated by water.
"""
residue_hbonds, water_hbonds = [], []
for hbond in hbonds:
frame_idx, atom1_label, atom2_label, itype = hbond
if solvent_resn in atom1_label or solv... |
def format_prio_list(prio_list):
"""Format a list of prios into a string of unique prios with count.
Args:
prio_list (list): a list of PrioEvent objects.
Returns:
The formatted string containing the unique priorities and
their count if they occurred more than once.
"""
prio... |
def otp(data, password, encodeFlag=True):
""" do one time pad encoding on a sequence of chars """
pwLen = len(password)
if pwLen < 1:
return data
out = []
for index, char in enumerate(data):
pwPart = ord(password[index % pwLen])
newChar = char + pwPart if encodeFlag else char - pwPart
newChar = newChar + 2... |
def list_of_strings_has_substring(list_of_strings, string):
"""Check if any of the strings in `list_of_strings` is a substrings of `string`"""
return any([elem.lower() in string.lower() for elem in list_of_strings]) |
def normalize_starting_slash(path_info):
"""Removes a trailing slash from the given path, if any."""
# Ensure the path at least contains a slash
if not path_info:
return '/'
# Ensure the path starts with a slash
elif path_info[0] != '/':
return '/' + path_info
# No need to chan... |
def get_namespace(namespace, view=None):
"""
Get the contents of the given 'namespace', returning a dictionary of
choices (appropriate for folders) and a list of items (appropriate for
messages).
"""
d = {}
l = []
# First try looking for folders. Then look for items. And so... |
def _get_keyed_rule_indices(rules):
"""returns {frozesent((par_name, edge1, edge2, ..)): index}"""
new = {}
for i, rule in enumerate(rules):
edges = rule.get("edges", rule.get("edge", None)) or []
edges = [edges] if type(edges) == str else edges
par_name = rule["par_name"]
ke... |
def has_prefix(x: list):
"""Returns "True" if some value in the list is a prefix for another value in this list."""
for val in x:
if len(list(filter(val.startswith, x))) > 1:
return True
return False |
def _field_post(field):
"""Add sqlalchemy conversion helper info
Convert aggregation -> _aggregation_fn,
as -> _cast_to_datatype and
default -> _coalesce_to_value"""
if "as" in field:
field["_cast_to_datatype"] = field.pop("as")
if "default" in field:
field["_coalesce_to_value"... |
def _check_validity_specie_tag_in_reaction_dict(k):
"""Validate key in database reaction entry"""
return not (
k == "type"
or k == "id_db"
or k == "log_K25"
or k == "log_K_coefs"
or k == "deltah"
or k == "phase_name"
or k == "Omega"
or k == "T_c"
... |
def format_properties(event):
"""Formats the user input for a password policy."""
event_properties = event["ResourceProperties"]
allowed_properties_bool = [
"RequireSymbols",
"RequireNumbers",
"RequireUppercaseCharacters",
"RequireLowercaseCharacters",... |
def multiply_with_positional_args(*args):
"""
:param args: a tuple with arbitrary number of positional arguments
:return:
"""
foo = args[0]
bar = args[1]
return foo * bar |
def rm(x, l):
"""List l without element x."""
return [y for y in l if x != y] |
def rsa_decrypt(c: int, d: int, n: int) -> int:
"""
Implements RSA Decryption via the mathematical formula.
The formula is m=(c**d) % N
Returns the plain "text" really integer representation of the value.
:param c: Ciphertext integer.
:param d: the private key exponent.
:param n: the modulus.
:return: the pla... |
def ConvertIregName(iregname):
"""
On Python 2.3 and higher, converts the given ireg-name component
of an IRI to a string suitable for use as a URI reg-name in pre-
rfc2396bis schemes and resolvers. Returns the ireg-name
unmodified on Python 2.2.
"""
try:
# I have not yet verified th... |
def spliter(line, _len=len):
"""
Credits to https://stackoverflow.com/users/1235039/aquavitae
Return a list of words and their indexes in a string.
"""
words = line.split(' ')
index = line.index
offsets = []
append = offsets.append
running_offset = 0
for word in words:
... |
def removeDuplicatesList(value):
"""
remove duplicates
"""
print(value)
return list(dict.fromkeys(value)) |
def q2p(q):
""" Convert MAPQ to Pr(incorrect). """
return 10**(q/-10) |
def calculateSensitivity(tn, fp, fn, tp):
"""
return the Sensitivity based on the confusion matrix values
:param tn: Quantity of True negative
:param fp: Quantity of False positive
:param fn: Quantity of False negative
:param tp: Quantity of True positive
:type tn: int - required
:type... |
def un_unicode(d):
""" transform unicode keys to normal """
return dict((str(k), v) for (k,v) in d.items()) |
def IsRefsTags(value):
"""Return True if the given value looks like a tag.
Currently this is identified via refs/tags/ prefixing."""
return value.startswith("refs/tags/") |
def calc_max_num_clones(walker_weight, min_weight, max_num_walkers):
"""
Parameters
----------
walker_weight :
min_weight :
max_num_walkers :
Returns
-------
"""
# initialize it to no more clones
max_n_clones = 0
# start with a two splittin... |
def _EdgeStyle(data):
"""Helper callback to set default edge styles."""
flow = data.get("flow")
if flow in {"backward_control", "backward_data", "backward_call"}:
return "dashed"
else:
return "solid" |
def percentage(fraction, total):
""" Calculate the percentage without risk of division by zero
Arguments:
fraction -- the size of the subset of samples
total -- the total size of samples
Returns:
fraction as a percentage of total
"""
p = 0 if total == 0 else 100.0 * fraction / total
return "%.2f... |
def _replica_results_dedup(queries):
"""This method deduplicates data object results within a query, so that ls displays data objects
one time, instead of once for every replica."""
deduplicated_queries = []
for query in queries:
new_query = query.copy()
if "results" in query:
... |
def is_fully_unmeth(methfreq, eps=1e-5):
"""
Check if the freq is unmethylated, means 0.0 (almost)
:param methfreq:
:param eps:
:return:
"""
if methfreq > 1.0 + eps or methfreq < 0:
raise Exception(f'detect error value for freq={methfreq}')
if methfreq < eps: # near 0
r... |
def split_accn(accn):
"""
Split accession into prefix and number, leaving suffix as text
and converting the type prefix to uppercase.
:param str accn: ordinary accession identifier.
:return str, str: prefix and integral suffix
"""
typename, number_text = accn[:3], accn[3:]
return typena... |
def get_lambda_path_from_event(event) -> str:
"""Builds the lambda function url based on event data"""
lambda_path = event["requestContext"]["path"]
lambda_domain = event["requestContext"]["domainName"]
return f"https://{lambda_domain}{lambda_path}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.