content stringlengths 42 6.51k |
|---|
def are_connected(n1, n2, rn1, a1, a2, bonds_intra, bonds_inter):
"""
Detect if a certain atom pair is bonded accordind to criteria.
Considers only to the self residue and next residue
Borrowed from IDP Conformer Generator package (https://github.com/julie-forman-kay-lab/IDPConformerGenerator) develop... |
def conjoin(functions, *args, **kwargs):
"""Returns True if all functions return True when applied to args."""
for f in functions:
if not f(*args, **kwargs):
return False
return True |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return value.strftime("%Y-%m-%d %H:%M:%S") |
def register_dictionary(nickname, email, password='default acceptable password', repeat_password='default acceptable password'):
"""creates the dictionary that can be used for registration"""
return dict(nickname=nickname, email=email, password=password, repeat_password=repeat_password) |
def comment(s: str) -> str:
"""Return an OCaml comment containing the given string s."""
return "(* " + s + " *)" |
def parse_network_info(net_bond, response_json):
"""
Build the network info
"""
out_dict = {}
ip_list = []
node_count = 0
# Build individual node information
for node_result in response_json['result']['nodes']:
for node in response_json['result']['nodes']:
if node['no... |
def update_params(base_param: dict, additional: dict):
"""overwrite base parameter dictionary
Parameters
----------
base_param : dict
base param dictionary
additional : dict
additional param dictionary
Returns
-------
dict
updated parameter dictionary
"""
... |
def clamp(n, minn, maxn):
"""Constrain a number n to the interval [minn, maxn]"""
return min(max(n, minn), maxn) |
def ParseSortByArg(sort_by=None):
"""Parses and creates the sort by object from parsed arguments.
Args:
sort_by: list of strings, passed in from the --sort-by flag.
Returns:
A parsed sort by string ending in asc or desc, conforming to
https://aip.dev/132#ordering
"""
if not sort_by:
return N... |
def get_catalog_record_preferred_identifier(cr):
"""Get preferred identifier for a catalog record.
Args:
cr (dict): A catalog record.
Returns:
str: The preferred identifier of e dataset. If not found then ''.
"""
return cr.get('research_dataset', {}).get('preferred_identifier', ''... |
def _all_dependencies(node, dg):
"""Gets all the dependencies for the passed in node.
:param str node: The node to lookup dependencies for.
:param dict dg: The graph to lookup.
:return: Tuple of a list of pairs from parent to child dependencies and
the list of direct_dependencies.
:rtype: ... |
def cross_product(u, v):
""" return the cross product of u and v """
return u[1] * v[2] - u[2] * v[1], -(u[0] * v[2] - u[2] * v[0]), u[0] * v[1] - u[1] * v[0]; |
def compare(numA, numB):
"""
compare(numA, numB):
Compares two numbers. Returns:
1, if the first number is greater than the second,
0, if they are equal,
-1, if the first number is smaller than the second.
Parameters
----------
numA: integer or float
numB: integer ... |
def _read_charval_file(handle):
"""Read sequence character frequencies/weights from file.
Args:
handle (file/list): input file
Returns:
dict : e.g. {'A': 0.0826, 'Q': 0.0393}
Sample input format:
# Multi-line information
# e.g. Frequencies obtained from SwissProt.
... |
def pretty_ti_txt(line):
"""Make given TI TXT line pretty by adding colors to it.
"""
if line.startswith('@'):
line = '\033[0;33m' + line + '\033[0m (segment address)'
elif line == 'q':
line = '\033[0;35m' + line + '\033[0m (end of file)'
else:
line += ' (data)'
return... |
def convert_to_int(bin_len):
""" convert base36 back to int
"""
return int(bin_len,36) |
def parse_num(source, start, charset):
"""Returns a first index>=start of chat not in charset"""
while start<len(source) and source[start] in charset:
start+=1
return start |
def _convert(text):
"""If text is numeric, convert to an integer. Otherwise, force lowercase."""
return int(text) if text.isdigit() else text.lower() |
def relabel(dictionary):
"""
Go through dictionary and rename all keys from 1 to N.
"""
count = 0
new_values = dict([])
ret = dictionary.copy()
for key in dictionary.keys():
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1:
... |
def _regularize_spaces(text: str) -> str:
""" Replaces spaces in a string with underscores. """
return text.replace(' ', '_') |
def component_similar ( same ) :
"""Should one use ``similar'' component?
"""
if same is Ellipsis : return True
elif same is NotImplemented : return True
elif isinstance ( same , str ) \
and same.strip().lower() in ( 'ditto' , 'similar' ) : return True
return False |
def getChanceAgreement(l1, l2):
"""
Returns p_e, the probability of chance agreement: (1/N^2) * sum(n_k1 * n_k2) for rater1, rater2, k categories (i.e. two in this case, 0 or 1), for two binary lists L1 and L2
"""
assert(len(l1) == len(l2))
summation = 0
for label in [0, 1]:
summation +=... |
def _identify_fs_from_path(path, mounts):
"""
Scan a list of mount points and try to identify the one that matches the
given path
"""
max_match = 0
matching_mount = None
for mount in mounts:
if path.startswith(mount) and len(mount) > max_match:
max_match = len(mount)
... |
def width(grid):
"""Gets the width of the grid (stored in row-major order)."""
try:
return len(grid[0])
except IndexError:
return 0 |
def get_range_downstream(pam_pos, guide_len):
"""
Get positions N bp downstream, i.e. for forward 5' PAMs or reverse 3' PAMs
:param pam_pos: position of PAM, int.
:return: sgRNA seed region positions, set of ints.
"""
sgrna = set(range(pam_pos + 1, pam_pos + (guide_len + 1)))
return sgrna |
def to_sql_format(title):
"""Convert a page title or username to 'canonical' SQL format.
SQL format uses underscores instead of spaces, and capitalizes the first
letter.
"""
title = title.replace(" ", "_")
if not title:
return ""
return title[0].upper() + title[1:] |
def abs_val(num):
"""
Find the absolute value of a number.
>>> abs_val(-5.1)
5.1
>>> abs_val(-5) == abs_val(5)
True
>>> abs_val(0)
0
"""
return -num if num < 0 else num |
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
... |
def binary_search(list, value):
"""This function takes a list as input and a value to find.Then it searches for that value using binary search"""
left, right = 0, len(list)-1
while left <= right:
mid = (left+right)//2
if list[mid] == value:
return mid #Returning the index
... |
def first_non_rest(line):
"""
find the first non-rest in an array of durations.
"""
found = False
non_rest = None
rest_list = []
counter = 0
for val in line:
if type(val) != type({}): #found a non-rest
found = True
non_rest = val
else:
rest_list.append(counter)
counter += 1... |
def debyte_dict(d, exceptions=('filedata', )):
"""convert keys and values from bytes into utf8 strings"""
res = {}
for _k, _v in d.items():
# convert all keys and non-exceptional values to unicode
k = str(_k, 'utf8')
if type(_v) == list:
if k in exceptions: # this is ra... |
def to_series(items, conjunction='and'):
"""
Formats the given items as a series string.
Example:
>>> to_series([1, 2, 3])
'1, 2 and 3'
:param items: the items to format in a series
:param conjunction: the series conjunction
:return: the items series
:rtype: str
""... |
def check_all(args_dict, predicate_func):
"""
Used to check if the predicate function returns true for all of the arguments.
"""
for arg in args_dict.values():
if not predicate_func(arg):
return False
return True |
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for ea... |
def normalize_commit_sha(sha_lst):
"""
The commit_sha section of the config file can hold commits in 2 ways:
* "<SHA>" - E.g. "428acae1b2ac15c3ad523e8d40755a9301220822".
* {"sha": "<SHA>", "msg": "<HELP>"} - E.g.
{"sha": "d9d622afe0ca8c7ab9d24c17f9fe59b54dcc61c9", "msg": "Fix ..."}.
:param sha_... |
def flatten(xs):
"""
flatten(xs):
expand_wildcard causes lists to become nested lists. Flatten() flattens them again.
"""
res = []
def loop(ys):
for i in ys:
if isinstance(i, list):
loop(i)
else:
res.append(i)
loop(xs)
retu... |
def merge_dicts(*dict_args):
"""Merge two dicts into a single dictionary
:param dict_args: The dicts to be merged
:return: The resulting dictionary from the merge
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def ConstructViceroyBuildDetailsURL(build_id):
"""Return the dashboard (viceroy) URL for this run.
Args:
build_id: CIDB id for the master build.
Returns:
The fully formed URL.
"""
_link = ('https://viceroy.corp.google.com/'
'chromeos/build_details?build_id=%(build_id)s')
return _link % ... |
def dict_raise_on_duplicates(ordered_pairs):
"""Reject duplicate keys."""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %s (value: %s)" % (k, v))
else:
d[k] = v
return d |
def bubble_sort(arr):
""" Time complexity O(n^2) Space complexity O(1) """
for i in range(len(arr) - 1):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[i], arr[j]
return arr |
def unpack_object_id(object_id):
"""Return ``(table_name, id)`` for ``object_id``::
>>> unpack_object_id(u'questions#1234')
(u'questions', 1234)
>>> unpack_object_id(u'questions#*')
(u'questions', None)
"""
parts = object_id.split('#')
try:
parts[1] = i... |
def strip_BOS_EOS_tokens(tokens, labels):
"""
Removes the BOS and EOS tokens and their corresponding O label.
strip_BOS_EOS_tokens('BOS text . . . text EOS', 'O X . . . X O')
> 'text . . . text', 'X . . . X'
"""
new_tokens = [' '.join(x.split(' ')[1:-1]).strip() for x in tokens]
new_labels... |
def merge_dictionaries(first, *others):
"""
Merge multiple dictionaries in one.
When multiple dictionaries have the same key, then the value of the latest (right most) will be selected.
:param Dict first: The first dictionary
:param List[Dict] others: The rest of dictionaries to be merged in one.
... |
def lambda_handler(event, _):
"""
Auto confirms attributes and users.
"""
# Confirm the user
event['response']['autoConfirmUser'] = True
# Set the email as verified if it is in the request
if 'email' in event['request']['userAttributes']:
event['response']['autoVerifyEmail'] = True
... |
def process_labels(labels:str):
"""
Takes a string of phonemes as input and outputs a list of lowercase phonemes
"""
return labels.lower().split() |
def get_top_bottom(lst, top, bottom):
"""
Returns a cropped list, keeping some of the list's top and bottom.
Edge conditions are handled gracefuly.
Input list should be ascending so that top is at the end.
"""
if len(lst) < top+bottom:
delta = top+bottom - len(lst)
bottom = botto... |
def sort_keyset(keyset):
"""Divides a set of keys into three groups
and returns a tuple=(ALL CAPS, Capitalized, no caps)"""
value1 = [k_temp for k_temp
in keyset
if k_temp.upper() == k_temp]
value2 = [k_temp for k_temp in keyset
if k_temp.upper() ... |
def _sign(val, length):
"""
Convert unsigned integer to signed integer
"""
if val & (1 << (length - 1)):
return val - (1 << length)
return val |
def mean(num_lst):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_list : list
List of numbers to calculate the average of
Returns
-------
The average/mean of num_lst
"""
Sum = sum(num_lst)
count = 0
for num in num_lst:
count += 1
return Sum / count |
def eratosthenes(n):
"""
this fxn is the Sieve of Eratosthenes.
this algorithm generates a list of positive integers up to a given input n,
then removes all multiples of 2, then 3,then 4, and so on until only the numbers
that are divisible by 1 and itself are left in the list. and therefore the lis... |
def manhattan_distance(point1, point2):
"""!
@brief Calculate Manhattan distance between between two vectors.
\f[
dist(a, b) = \sum_{i=0}^{N}\left | a_{i} - b_{i} \right |;
\f]
@param[in] point1 (array_like): The first vector.
@param[in] point2 (array_like): The second vector.
... |
def split_file_name_for_sort(f):
"""
Returns tuple of string and integer components for sorting
For example:
"cluster_10.txt" -> ("cluster_",10,".txt")
"""
components = []
current_component = ''
component_is_digits = False
# Loop over characters in the input string
for c in str... |
def decrease_english(raw_table, base_index):
""" Convert decrease flag to french """
if raw_table[base_index] == 0:
return "stop"
else:
return "decreasing" |
def int_validation(to_validate):
"""
Checks if given argument is type(int)
:param to_validate: Argument to check
:return: List of
"""
try:
if type(to_validate) != int:
raise ValueError(f'Wrong value type {type(to_validate)}')
except Exception as ex:
return [False,... |
def bytesto(bytes, to, bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
"""
a = {"k": 1, "m": 2, "g": 3, "t": 4, "p": 5, "e": 6}
r = float(bytes)
for i in range(a[to]):
... |
def _align_interval(interval):
"""
Flip inverted intervals so the lower number is first.
"""
(bound_one, bound_two) = interval
return (min(bound_one, bound_two), max(bound_one, bound_two)) |
def include_tags(tag_list, *args):
"""
- Filters a tag set by Inclusion
- variable tag keys given as parameters, tag keys corresponding to args
are excluded
RETURNS
TYPE: list
"""
targets = []
for tag in tag_list:
for arg in args:
if arg == tag... |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary representing an XML document.
"""
# No further processing
return proc_data |
def momentum(prices, shortMA, longMA, upper_threshold, lower_threshold):
"""
If momentum is positive, buy, if momentum is negative, sell, otherwise hold
:param prices: list of prices
:param shortMA: integer short moving average
:param longMA: integer long moving average
:param upper_threshold:
... |
def read_calibration_file(calib_filename):
"""
Given a calibration, return the calibration structure.
Parameters
----------
calib_filename: str
Fully specificied filename of the non-calibrated file (data level < 2)
Returns
-------
output_filename: str
Fully specificied ... |
def get_vector26():
"""
Return the vector with ID 26.
"""
return [
0.33861310,
0.33069345,
0.33069345,
] |
def none_if_empty(collection):
"""Return collection or None if it's empty."""
return collection if len(collection) > 0 else None |
def page_not_found(error):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL.', 404 |
def _separator(sep):
"""helper function to return the correct delimiter"""
if sep == 'Comma':
return ','
elif sep == 'Tab':
return '\t'
elif sep == 'Fixed':
return None
elif sep == 'Semicolon':
return ';'
else:
return ',' |
def coalesce(x, *replace):
"""Replace missing values
https://dplyr.tidyverse.org/reference/coalesce.html
Args:
x: The vector to replace
replace: The replacement
Returns:
A vector the same length as the first argument with missing values
replaced by the first non-missin... |
def get_lam1(membrane_geometry):
""" dimensionless geometry coefficient lambda1
The corresponding definition (of different separability factor) is provided in Table 1 in [2].
Note that the definition in [2] is slightly different due to the use of hydraulic radius of channel.
This means that the lam1 in ... |
def _parse_dims(dims):
"""Helper method to parse comma-separated NN layer dimension values.
Parameters
----------
dims: str
Comma-separated string values. Example `256,256`
Returns
-------
list[int]
A list containing the NN layer dimensions values.
"""
if isinstance... |
def first_existing(d, keys):
"""Returns the value of the first key in keys which exists in d."""
for key in keys:
if key in d:
return d[key]
return None |
def format_remove_duplicates(text, patterns):
"""Removes duplicated line-basis patterns.
Based on simple pattern matching, removes duplicated lines in a block
of lines. Lines that match with a same pattern are considered as
duplicates.
Designed to be used as a filter function for Jinja2.
Arg... |
def to_cert_dat(key):
"""
Convert input raw key to list
:param key: Input raw key
:return: Key as list format
"""
cert_data = list()
for i in key:
cert_data.append(ord(i))
return cert_data |
def length(text):
"""<string> -- Gets the length of <string>"""
return "The length of that string is {} characters.".format(len(text)) |
def get_tapis_abaco_image(base_url):
"""
Determine the docker image name for a tapis notebook associated with a base_url.
"""
# designsafe tenant:
if 'agave.designsafe-ci.org' in base_url:
return 'taccsciapps/jupyteruser-ds-abaco:1.2.14'
return None |
def _clean_dict(d):
"""
Removes all falsy elements from a nested dict
"""
if not isinstance(d, dict):
return d
return {k: _clean_dict(v) for k, v in d.items() if v} |
def compare2float_relative(x_base, y_check, relative_error):
"""Compare whether 2 geometries and their intersection is 'equal', measure with relative."""
value_x = float(x_base)
value_y = float(y_check)
return ((abs(value_x - value_y)) / (abs(value_x))) <= relative_error |
def percent(num,denom):
"""
Return values as percentage
Arguments:
num (float): number to express as percentage
denom (float): denominator
Returns:
Float: value expressed as a percentage.
"""
return float(num)/float(denom)*100.0 |
def validate_samplesheet_header(header: list) -> bool:
"""
Validates that column names match expected values.
Expected column names for both iSeq and MiSeq sequencers are hardcoded here.
:param header: List of column names
:return: True if header meets all expected values, else False
"""
hea... |
def format_list(my_list):
"""
:param my_list:
:type: list
:return: list separated with ', ' & before the last item add the word 'and '
:rtype: list
"""
new_list = ', '.join(my_list[0:len(my_list)-1:2]) + " and " + my_list[len(my_list)-1]
return new_list |
def if_homophone(a, b, p):
"""
Return True if words a and b have the same pronounciation.
"""
if (a in p) and (b in p):
if p[a] == p[b]:
return True |
def json_patch_headers(app):
"""JSON Patch headers."""
return [
('Content-Type', 'application/json-patch+json'),
('Accept', 'application/json'),
] |
def find_highest(tem, h):
"""
:param tem:int, the temperature that user entered.
:param h:int, the highest temperature so far.
This function finds the highest temperature.
"""
max = h
if tem > max:
return tem
return h |
def validateInputs(dict):
"""
Checks that all necessary inputs to post request are present
----------
Parameters
----------
dict: dictionary received from post request
Returns
-------
1 if there are missing keys
0 if all keys are present
"""
dict_keys = ['username... |
def nested_filter(path, filter_, *args, **kwargs):
"""
Creates a nested query for use with nested documents
Keyword arguments such as score_mode and others can be added.
"""
nested = {
"path": path,
"filter": filter_
}
nested.update(kwargs)
return {
"nested": nes... |
def where_not_None(item_list):
"""returns list of indexes of non None values
SeeAlso:
flag_None_items
"""
return [index for index, item in enumerate(item_list) if item is not None] |
def merge_schemas(a, b, path=None):
"""Recursively zip schemas together
"""
path = path if path is not None else []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_schemas(a[key], b[key], path + [str(key)])
elif ... |
def _ParseRepositoryTag(image_name):
"""Parses out the repository and tag from a Docker image name.
Args:
image_name: (str) The full name of an image, expected to be in a format of
"repository[:tag]"
Returns:
A (repository, tag) tuple representing the parsed result.
None repository means the i... |
def split_conn_PFI(connection):
"""Return PFI input number of a connection string such as 'PFI0' as an
integer, or raise ValueError if format is invalid"""
try:
return int(connection.split('PFI', 1)[1])
except (ValueError, IndexError):
msg = "PFI connection string %s does not match forma... |
def segment_video(fstart, fend):
"""
Given the duration [fstart, fend] of a video, segment the duration
into many 30-frame segments with overlapping of 15 frames
"""
segs = [(i, i+30) for i in range(fstart, fend-30+1, 15)]
return segs |
def compute_training_steps(
dataloader, num_epochs=1, max_steps=-1, gradient_accumulation_steps=1
):
"""Computes the max training steps given a dataloader.
Args:
dataloader (Dataloader): A PyTorch DataLoader.
num_epochs (int, optional): Number of training epochs. Defaults to 1.
max_s... |
def is_int(obj):
"""Returns True if this object can be represented as an integer and does
not contain a decimal point.
"""
try:
int(obj) # Truncates decimal portions of float...
if '.' in str(obj):
return False
return True
except ValueError:
return False |
def is_iterable(value):
"""Return True if the object is an iterable type."""
return hasattr(value, '__iter__') |
def filter_most_specific(types):
"""From a list of types, determine the most specific ones.
Args:
types (list[type]): List of types.
Returns:
list[type]: Most specific types in `types`.
"""
filtered_types = []
while len(types) > 0:
t, types = types[0], types[1:]
... |
def get_language(file_path):
"""Return the language a file is written in."""
if file_path.endswith(".py"):
return "python3"
elif file_path.endswith(".js"):
return "node"
elif file_path.endswith(".rb"):
return "ruby"
elif file_path.endswith(".go"):
return "go run"
elif file_path.endswith(".c") or file_... |
def get_key(row, columns, numeric_column):
"""Get sort key for this row
"""
if(numeric_column):
return [int(row[column]) for column in columns]
else:
return [row[column] for column in columns] |
def is_palindrome(p: str) -> bool:
"""
Determine if a string is a palindrome.
:param p: the string
:return: True if a palindrome, and false otherwise
>>> is_palindrome("can")
False
>>> is_palindrome("cac")
True
>>> is_palindrome('')
True
>>> is_palindrome('a')
True
"... |
def filter_irrelevant_matches(matches, requested_dimensions):
"""Only return dimensions the user configured"""
if requested_dimensions:
return [match
for match in matches
if match["dim"] in requested_dimensions]
else:
return matches |
def flatten_tree_structure(root_list):
"""Flatten a tree."""
elements = []
def generate(input_list, indent_levels_so_far):
"""Generate flat list of nodes."""
for index, element in enumerate(input_list):
# add to destination
elements.append(element)
# comp... |
def get_prefetcher_setup(job):
"""
Return the proper setup for the Prefetcher.
Prefetcher is a tool used with the Event Streaming Service.
:param job: job object.
:return: setup string for the Prefetcher command.
"""
# add code here ..
return '' |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""
Calculate the max prediction score of prediction against the given ground_truths.
:param metric_fn: A metric function to evaluate the prediction
against the ground_truths.
:param prediction: The predicti... |
def int_overflow(value: int) -> int:
"""
Simulates 32bit integer overflow.
"""
return ((value ^ 0x80000000) & 0xffffffff) - 0x80000000 |
def pad(sent, max_len):
"""
syntax "[0] * int" only works properly for Python 3.5+
Note that in testing time, the length of a sentence
might exceed the pre-defined max_len (of training data).
"""
length = len(sent)
return (sent + [0] * (max_len - length))[:max_len] if length < max_len else s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.