content stringlengths 42 6.51k |
|---|
def _len_stats(sequences):
"""
Return the minimum, mean and maximum sequence length.
>>> _len_stats(['A', 'AA', 'AAA'])
(1, 2.0, 3)
>>> _len_stats([])
(0, 0.0, 0)
"""
if not sequences:
return 0, 0.0, 0
lengths = [len(seq) for seq in sequences]
return min(lengths), sum(le... |
def obtain_ATC_levels(ATCs):
"""
Obtain the 5 levels of ATCs from an ATC list
"""
level_to_ATCs = {'level1':[], 'level2':[], 'level3':[], 'level4':[], 'level5':[]}
for ATC in ATCs:
level_to_ATCs['level1'].append(ATC[0]) # e.g. A
level_to_ATCs['level2'].append(ATC[0:3]) # e.g. A10
... |
def human_to_real(iops):
"""Given a human-readable IOPs string (e.g. 2K, 30M),
return the real number. Will return 0 if the argument has
unexpected form.
"""
digit = iops[:-1]
unit = iops[-1].upper()
if unit.isdigit():
digit = iops
elif digit.isdigit():
digit = int... |
def get_variable_name(fname):
"""
This function takes a file path and returns
the name of a variable.
"""
variables = ['demand', 'solarfarm', 'railsplitter']
split_str = fname.split('/')
file_name = split_str[-1]
pieces = file_name.split('_')
for p in pieces:
if any(p in va... |
def default(languages: dict, attr: str, **kwargs) -> dict:
"""
:param languages:
:param attr:
:param kwargs:
:return:
"""
return {
language: translate[attr](**kwargs)
for language, translate in languages.items()
} |
def gammapoisson_var(a, b):
"""Variance of a gamma-Poisson compound r.v. in shape-rate parameterization.
This is equivalent to the negative binomial distribution, which models the
number of trials k required to achieve a successes with probability p.
f(k; a, b) = \int_0^\infty Poisson(k; L) * Gamma... |
def replace_database_in_url(url, database_name):
"""
Substitute the database part of url for database_name.
Example: replace_database_in_url('foo/db1', 'db2') returns 'foo/db2'
This will not work for unix domain connections.
"""
i = url.rfind("/")
return f"{url[:i]}/{database_name}" |
def clash(flower1, flower2):
""" Test if two flowers will class at any point of their life [bloom, wilt]
(A classic test for interval interception, with start: x[1] and end x[2)
"""
return flower1[1] <= flower2[2] and flower2[1] <= flower1[2] |
def safe_equals(left: object, right: object) -> bool:
"""Safely check whether two objects are equal."""
try:
return bool(left == right)
except Exception:
return False |
def string_of_spaces(n):
"""
Creates a string of html spaces
:param n {int}: number of spaces
"""
return " " * n |
def getDict(symbolDictList):
"""Returns postprocessed output from solveEQ as dict
Parameters
----------
symbolDictList
list of solutions from solveEQ
Returns
-------
A dict containing all values of the generated variables.
"""
stringDict = {}
for i in range(len(symbo... |
def decode_args(args, stdin_encoding):
"""
Convert all bytes ags to str
by decoding them using stdin encoding.
"""
return [
arg.decode(stdin_encoding)
if type(arg) == bytes else arg
for arg in args
] |
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() in ("on"... |
def list_check_equal(input_list):
"""
Check equality of the input list items.
:param input_list: input list
:type input_list: list
:return: result as bool
"""
return input_list[1:] == input_list[:-1] |
def eksponen(a: int, n: int) -> int:
"""
Fungsi ini mengevaluasi a ^ n dengan
kompleksitas waktu (O(n)) sebesar O(log n)
Fungsi ini mengevaluasi a ^ n dengan memecah (divide)
komponen pemangkatan dan menyelesaikan hingga pangkat
dari komponen tersebut sama dengan 0 (conquer)
Rumus umum :
... |
def _region(region):
"""
Return the region argument.
"""
return " --region {r}".format(r=region) |
def pick_term(xp: int, yp: int, zp: int, option: str) -> int:
"""For parm tuple of (x, y, z) and option string like 'x" or '-z'. Return the number for the option term."""
options_map = {'x': xp, 'y': yp, 'z': zp, '-x': -xp, '-y': -yp, '-z': -zp}
return options_map[option] |
def validate_page(page):
"""Validate a page number"""
try:
rv = int(page)
except (ValueError, TypeError):
rv = 1
return rv |
def parseVersion(strversion):
"""Parse version strings of the form Protocol '/' Major '.' Minor. E.g. 'HTTP/1.1'.
Returns (protocol, major, minor).
Will raise ValueError on bad syntax."""
proto, strversion = strversion.split('/')
major, minor = strversion.split('.')
major, minor = int(major), i... |
def total_rain(rain_hours: list) -> int:
"""
Sum up the rain mm from list of rain hours
"""
if len(rain_hours) > 0:
return round(sum([list(x.values())[0]['1h'] for x in rain_hours]), 2)
else:
return 0 |
def update_shape(obs_shape, act_shape, rew_shape, wrapper_names):
"""
Overview:
Get new shape of observation, acton, and reward given the wrapper.
Arguments:
obs_shape (:obj:`Any`), act_shape (:obj:`Any`), rew_shape (:obj:`Any`), wrapper_names (:obj:`Any`)
Returns:
obs_shape (:ob... |
def jacobi_radius(r, M_host, M_sat):
"""
The Jacobi Radius for a satellite on a circular orbit about an extended host,
where the host is assumed to be well modeled as an isothermal sphere halo:
R_j = r * (M_sat / 2 M_host(<r))}^(1/3)
For MW/LMC, the Isothermal Sphere approximation is not a bad on... |
def first_word(text: str) -> str:
"""
returns the first word in a given text.
"""
text = text.replace('.', ' ').replace(',', ' ').strip()
word_list = list(text.split())
return word_list[0]
# another pattern
import re
return re.search("([\w']+)", text).group() |
def _clean(telegram_text):
"""Remove markdown characters to prevent
Telegram parser to fail ('_' & '*' chars)."""
return telegram_text.replace('_', '\_').replace('*', '') |
def from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
r, g, b = rgb
return f'#{r:02x}{g:02x}{b:02x}' |
def GetTechJobsAds(adList):
"""Filter out all tech jobs (Data/IT) from the list of all jobs"""
techAdList = filter(lambda ad: ad['occupation_field']['label'] == 'Data/IT', adList)
return list(techAdList) |
def filter_current_symbol(view, point, symbol, locations):
"""
Filter the point specified from the list of symbol locations. This
results in a nicer user experience so the current symbol doesn't pop up
when hovering over a class definition. We don't just skip all class and
function definitions for t... |
def get_new_field_item(field_update):
"""
Get the new key-value for a field_update.
"""
return (field_update[0], field_update[1][1]) |
def _create_fieldname_to_type_map(flat_dict_list):
"""
This method will create a map of file names to the respective data types
this is used so we can put type hints in the resultant CSV
For now this will only populate integer fields
Parameters:
flat_dict_list(in) -- This is a list of diction... |
def _capitalize(s):
"""Capitalize first letter.
Can't use built-in capitalize function because it lowercases any chars after the first one.
In this case, we want to leave the case of the rest of the chars the same.
"""
return s[0].upper() + s[1:] |
def PDFObjHasType(o, ty):
"""Return True if o, a PDF Object, has type ty."""
if o is None:
return False
return o[0] == ty |
def build_dot_value(key, value):
"""Build new dictionaries based off of the dot notation key.
For example, if a key were 'x.y.z' and the value was 'foo',
we would expect a return value of: ('x', {'y': {'z': 'foo'}})
Args:
key (str): The key to build a dictionary off of.
value: The valu... |
def fill_list_to_length(x,l,v):
"""
Add the value v to list x until
it reaches length l
"""
add_n = l - len(x)
if add_n > 0:
add = [v] * add_n
x.extend(add)
return x |
def null_data_cleaner(original_data: dict, data: dict) -> dict:
""" this is to remove all null parameters from data that are added during option flow """
for key in data.keys():
if data[key] == "null":
original_data[key] = ""
else:
original_data[key]=data[key]
return ... |
def ascii_to_hex(exception):
""" On unicode decode error (bytes -> unicode error), tries to replace
invalid unknown bytes by their hex notation.
"""
if isinstance(exception, UnicodeDecodeError):
obj = exception.object
start = exception.start
end = exception.end
invalid_p... |
def xround(x, divisor=1):
"""Round to multiple of given number.
Parameters
----------
x : float
Number to round.
divisor : float
Number the result shall be a multiple of.
Returns
-------
float
`x` rounded to the closest multiple of `divisor`.
"""
return ... |
def problem_has_boolean_output(tables):
"""
The problem only has True or False outputs.
:param tables: all truth tables.
:return: boolean indicating whether the problem is boolean or not.
"""
return all([isinstance(k, bool) or k in (0, 1) for k in tables.keys()]) |
def swapWordCount(wordToFreq):
"""
wordToFreq: the dict linking word to count
return freqToWord: the dict linking count to word
"""
freqToWord = {}
for wdKey in wordToFreq:
if wordToFreq[wdKey] in freqToWord:
freqToWord[wordToFreq[wdKey]].append(wdKey)
else:
... |
def _derived_class(cls, base_class):
"""
Only matches subclasses that are not equal to the base class.
"""
return cls is not base_class and issubclass(cls, base_class) |
def split_lines(s):
"""Split s into a list of lines, each of which has a trailing newline
If the lines are later concatenated, the result is s, possibly
with a single appended newline.
"""
return [l + '\n' for l in s.split('\n')] |
def company_alias_generator(string: str) -> str:
"""The alias_generator function for Company class.
Generates the aliases for the classes variables.
Aliases are given by: "company" + `variable_name` except for
`validate_account_information`
Args:
string (str): The variable name/ dictionary... |
def getattr_(entity, attribute):
"""Either unpack the attribute from every item in the entity
if the entity is a list, otherwise just return the attribute
from the entity. Returns None if the entity is either None
or empty."""
if entity in (None, []):
return None
if isinstance(entity, li... |
def convert_to_list(obj):
""" receives an object and if type tuple or list, return list. Else
return a list containing the one object
"""
if type(obj) is None: return [] # None implies empty list...
if type(obj) is list: return obj
if type(obj) is tuple:
return [x for x in obj]
... |
def rgb2hex(rgbl):
"""
Return hexidecial XML form of RGB colour tuple. Note that the xml parsing
of the tuple reads bgr rather than standard rgb, so the rgb tuple is reversed
in order on output to represent the true colour
"""
return "ff{0:02x}{1:02x}{2:02x}".format(int(rgbl[2]), int(rgbl[1]), i... |
def unit_coordinates_to_image_coordinates(y_current, x_current, center, height, width):
""" y, x order
"""
y_current = [[y0 * height, y1 * height] for y0, y1 in y_current]
x_current = [[x0 * width, x1 * width] for x0, x1 in x_current]
center[0] = center[0] * height
center[1] = center[1] * height... |
def bool_value(value):
"""
Converts the given object to a bool if it is possible.
Parameters
----------
value : object
Object to be converted to bool.
Returns
-------
value : bool
Bool value.
Raises
------
ValueError
If the object cannot be converte... |
def reorder_circle(circle):
"""Reorder the circle elements so that it starts from the lowest element
and goes to the direction of the smallest of two possible second elements.
For example, the circle "4736201" becomes "0147362". The circle
"32187654" becomes "12345678"."""
length = len(c... |
def skip_add(n):
""" Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
>>> # Do not use while/for loops!
>>> from construct_check import check
>>> # ban iteration
>>> check(this_file, 'skip_add... |
def get_scaled_size(bytes, suffix="B"):
"""
Credit to PythonCode for this function.\n
> https://www.thepythoncode.com/article/get-hardware-system-information-python\n
Scale bytes to its proper format\n
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
(> string)
"""
factor ... |
def convert_to_abmag(value, name):
"""
Convert magnitude to AB magnitude
Parameters
----------
value : float
Value of the band
name : str
Name of the band as stated in the GSC column name.
Options are: 2MASS: tmassJMag, tmassHMag, tmassKsMag
SDSS: SDSSgMag, SDSSi... |
def sort_by_dependency(names, images):
"""
Make sure images that have dependencies are last
"""
dependencies = []
while len(names):
name = names.pop(0) # get the first image name
if name in images:
definition = images[name]
# check if it has a dependency
... |
def get_strip_strings_array(strings):
""" takes a comma separated string and returns a list of strings
using the comma as the delimiter
example:
'HMC, V7000 ' -> ['HMC','V7000']
args:
strings: comma separated string list
returns:
string[] list of strings
"... |
def lam2f(l):
"""
Computes the photon frequency in Hz
Parameters
----------
l : float
Photon wavelength in m
Returns
-------
f : float
Frequency in Hz
"""
f = 299792458/l
return f |
def evaluate_distinct(seed_set_cascades):
"""
Measure the number of distinct nodes in the test cascades started from the seed set
"""
combined = set()
for i in seed_set_cascades.keys():
for j in seed_set_cascades[i]:
combined = combined.union(j)
return len(combined) |
def has_spdx_text_in_scancode_output(scancode_output_data_file_licenses):
"""Returns true if at least one license in the scancode output has the spdx identifier."""
return any(
'spdx' in scancode_output_data_file_license['matched_rule']['identifier']
for scancode_output_data_file_license in scan... |
def unshared_copy(inList):
"""perform a proper deepcopy of a multi-dimensional list (function from http://stackoverflow.com/a/1601774)"""
if isinstance(inList, list):
return list( map(unshared_copy, inList) )
return inList |
def convert_tvars_to_dict(tvars, name2nparr=None):
"""
convert the input training variables to a dictionary
:param tvars: the tensorflow trainable variables
:param name2nparr: a dictionary in same format with output, if given, the converted tvars will be added to this
:return: the dictionary in the... |
def df_if_two_one(value):
""" Final Data Cleaning Function
- This is run against station, latitude, longitude, and elevation for indidividual records
- Many of these records have usable data, so don't want to just throw them out.
- Example issues:
- Instead of a station of '000248532' a valu... |
def num_to_activation(num):
"""
Converts num to respective activation function
:param num: activation function num
:return: activation function string
"""
d = {
0: 'LeakyReLU',
1: 'relu',
2: 'tanh',
3: 'sigmoid',
}
return d[num] |
def bitstring2expr(bitstrings, variable_list):
"""Converts List of Bitstrings to Boolean expressions"""
string = ''
ret_list = []
for bitstring in bitstrings:
tmp_list = []
var = 0
for character in reversed(bitstring):
if character != '-':
if character... |
def changeColor(r, g, b, dataset, oldColors):
"""Callback to set new color values.
Positional arguments:
r -- Red value.
g -- Green value.
b -- Blue value.
dataset -- Currently selected dataset.
oldColors -- Previous colors in case none values are provided for r/g/b.
"""
if r == Non... |
def _succ(p,l):
"""
retrieve the successor of p in list l
"""
pos = l.index(p)
if pos+1 >= len(l):
return l[0]
else:
return l[pos+1] |
def color_str(color, raw_str):
"""Format a string with color.
:param color: a color name, can be r, g, b or y
:param raw_str: the string to be formatted
:returns: a colorful string
"""
if color == 'r':
fore = 31
elif color == 'g':
fore = 32
elif color == 'b':
for... |
def sliced_by_n(images, n=500):
"""Slice the images by sequences of n elements."""
return [images[i : i + n] for i in range(0, len(images), n)] |
def _compose_export_url(
fhir_url: str,
export_scope: str = "",
since: str = "",
resource_type: str = "",
container: str = "",
) -> str:
"""Generate a query string for the export request. Details in the FHIR spec:
https://hl7.org/fhir/uv/bulkdata/export/index.html#query-parameters"""
ex... |
def HFSS3DLayout_AdaptiveFrequencyData(freq):
"""Update HFSS 3D adaptive frequency data.
Parameters
----------
freq : float
Adaptive frequency value.
Returns
-------
list
List of frequency data.
"""
value = [("AdaptiveFrequency", freq), ("MaxDelta", "0.02"), ("Max... |
def filterYif(item):
""" filters an ASSET CONTROL generated csv list to find items that belong to Yifei Li """
return 'Yifei' in item['Custodian'] or item['Location']=='DION-320' |
def get_colab_github_url(relative_path: str, repository: str, branch: str) -> str:
"""Get the URL that a file will have on Google Colab when hosted on GitHub."""
return f"https://colab.research.google.com/github/{repository}/blob/{branch}/{relative_path}" |
def get_access(ioctl_code):
"""Returns the correct access type name for a 32 bit IOCTL code"""
access_names = [
'FILE_ANY_ACCESS',
'FILE_READ_ACCESS',
'FILE_WRITE_ACCESS',
'FILE_READ_ACCESS | FILE_WRITE_ACCESS',
]
access = (ioctl_code >> 14) & 3
return access_nam... |
def tagNameString( name ):
"""Return "" if name is None, otherwise return name surrounded by parentheses and double quotes."""
return "" if name is None else "(\"{}\")".format( name ) |
def _bcd2bin(value):
"""Convert binary coded decimal to Binary
:param value: the BCD value to convert to binary (required, no default)
"""
return value - 6 * (value >> 4) |
def magic_index(a):
"""
The obvious solution.
"""
return any(i == x for i, x in enumerate(a)) |
def quad2list2_receipt_v1(quad):
"""
convert to list of list
"""
return [
[quad["x1"], quad["y1"]],
[quad["x2"], quad["y2"]],
[quad["x3"], quad["y3"]],
[quad["x4"], quad["y4"]],
] |
def get_reference_data(p):
"""Summarise the bibliographic data of an article from an ADS query
Returns dict of 'author' (list of strings), 'title' (string), and
'ref' (string giving journal, first page, and year).
"""
data = {}
try:
data['author'] = p.author
except:
data['author'] =... |
def mean_labels(input_dict):
"""
Function to calculate the macro-F1 score from labels
Args:
input_dict (dict): classification report dictionary
Returns:
(float): macro-F1 score
"""
sum_f1 = (float(input_dict["3"]["f1-score"]) +
float(input_dict["4"]["f1-score"]) +... |
def comp_list_of_dicts(list1, list2):
"""
Compare list of dictionaries.
:param list1: First list of dictionaries to compare
:type list1: list of dictionaries
:param list2: Second list of dictionaries to compare
:type list2: list of dictionaries
:rtype: boolean
"""
for item in li... |
def _to_var_name(s):
"""
Remove,hyphens,slashes,whitespace in string so that it can be
used as an OrientDB variable name.
"""
r = s.replace("'",'prime')
table = str.maketrans(dict.fromkeys('.,!?_ -/<>{}[]()+-=*&^%$#@!`~.\|;:"'))
chars_to_remove = ['.', '!', '?', '_', '-', '/', '>', '<', '(',... |
def dl_ia_utils_memory_usage(df):
""" Calculate and print the memory usage and shape by the dataframe
:param df:
:return:
"""
error = 0
try:
print('{} Data Frame Memory usage: {:2.2f} GB'.format('-' * 20, df.memory_usage(deep=True).sum() / 1000000000))
print('{} Data Frame Sha... |
def _merge(dict1, dict2):
"""Merge two dicts, dict2 takes precedence."""
return {**dict1, **dict2} |
def find_max_str(smiles: str) -> str:
"""
General functionality to choose a multi-smiles string, containing the
longest string
"""
smiles = max(smiles.split("."), key=len)
return smiles |
def create_agent_params(dim_state, actions, ep_returns, ep_losses, mean, std, layer_sizes, discount_rate, learning_rate, batch_size, memory_cap, update_step, decay_period, init_eps, final_eps):
"""
Create agent parameters dict based on args
"""
agent_params = {}
agent_params["dim_state"] = dim_state... |
def in_box(coords, box):
"""Return true if coordinates are in box."""
if box[0][0] < coords[0] < box[1][0] and box[1][1] < coords[1] < box[0][1]:
return True
return False |
def transpose(pcl_file, outfile):
""" Transpose the merged pcl and metadata file
:param pcl_file: String; file that is the merge of the otu and metadata
:param outfile: String; file that is the transpose of the pcl_file
External dependencies
- Maaslin: https://bitbucket.org/biobakery/ma... |
def group_by(l, column, comp_margin=None):
"""
Groups list entities by column values.
"""
sorted_values = []
result_list = []
current_value = None
for i in range(0, len(l)):
x = l[i]
if x[column][0:comp_margin] in sorted_values or x[column][0:comp_margin] == current_value:
... |
def str_to_bool(text):
"""
Parses a boolean value from the given text
"""
return text and text.lower() in ['true', 'y', 'yes', '1'] |
def to_set(labels_list):
"""given a list of labels from annotations, return the set of (unique) labels
Parameters
----------
labels_list : list
of lists, i.e. labels from annotations
Returns
-------
labelset
Examples
--------
>>> labels_list = [voc.annot.labels for vo... |
def char_lookup(c: str, table: dict, default=None):
"""
Translate a char into a value by looking up from a dict.
Args:
c: char to translate
table: a dict to translate the char by looking up
default: If not None, this is the value to return in case the char does not exist in the tabl... |
def filename(select: str) -> str:
"""
Return the filename portion of a colon-separated selection.
"""
return select.split(":")[0] |
def to_nested_dict(d, delim='.', copy=True):
"""TLDR;
flat: {"a.b.c":0}
# pop 'a.b.c' and value 0 and break key into parts
parts: ['a','b','c']:
# process 'a'
flat <- {'a':dict()}
# process 'b'
flat <- {'a': {'b': dict()}}
# process 'c' @ tmp[parts[-1]] = val
flat <- {'a': {'b... |
def token_at_cursor( code, pos=0 ):
"""
Find the token present at the passed position in the code buffer
"""
l = len(code)
end = start = pos
# Go forwards while we get alphanumeric chars
while end<l and code[end].isalpha():
end+=1
# Go backwards while we get alphanumeric chars
... |
def validate_stdout(stdout):
"""
:param stdout:
:return: true if stdout does not indicate test failure
"""
# Todo: support should_panic tests (Implementation on hermit side with custom panic handler)
if "!!!PANIC!!!" in stdout:
return False
return True |
def get_yes_no(value):
""" coercing boolean value to 'yes' or 'no' """
return 'yes' if value else 'no' |
def _repeatlast(numfields,listin):
"""repeat last item in listin, until len(listin) = numfields"""
if len(listin) < numfields:
last = listin[-1]
for n in range(len(listin),numfields):
listin.append(last)
return listin |
def format_bucket(bucket):
"""Formats the bucket to a string.
:params ``int`` bucket:
Bucket number
:returns:
``str`` - Formatted (0 padded) bucket number.
"""
return '{:06d}'.format(bucket) |
def rgb_to_brg(rgb_colour):
"""Reorders RGB colour value to that used by DAWN's LED strip"""
return (
rgb_colour[2],
rgb_colour[0],
rgb_colour[1]
) |
def create_session_string(prefix, fmat, orb, rootsift, ratio, session):
"""Create an identifier string from the most common parameter options.
Keyword arguments:
prefix -- custom string appended at the beginning of the session string
fmat -- bool indicating whether fundamental matrices or essential matrices are es... |
def init(i):
"""
Not to be called directly. Sets the path to the vqe_plugin.
"""
return {'return':0} |
def stringify_klasses_data(klasses_by_module):
"""
Convert all the objects (modules and klasses) to their string names.
"""
klasses_data = {}
for module, klasses in klasses_by_module.items():
module_name = module.__name__
klasses_data[module_name] = []
for klass in klasses:
... |
def parse_tle_float(s):
"""Parse a floating point with implicit dot and exponential notation.
>>> parse_tle_float(' 12345-3')
0.00012345
>>> parse_tle_float('+12345-3')
0.00012345
>>> parse_tle_float('-12345-3')
-0.00012345
"""
return float(s[0] + '.' + s[1:6] + 'e' + s[6:8]) |
def structure(object,hashable=True):
"""Returns an object describing the hierarchical structure of the given
object (eliminating the values). Structures can be then compared via
equality testing. This can be used to more quickly compare
two structures than structureMatch, particularly when hashable=Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.