content stringlengths 42 6.51k |
|---|
def _type_check(variable_name: str, variable_type: str) -> str:
"""
Return the type check Python instruction.
If variable_type == int:
type(variable_name) == int
else:
isinstance(variable_name, variable_type)
:param variable_name: the variable name.
:param variable_type: the... |
def _bool(val):
"""
Return ``True`` iff *val* is "1", "yes", or "true", otherwise ``False``.
>>> _bool('TRUE')
True
>>> _bool('nah')
False
"""
return val.lower() in ('1', 'yes', 'true') |
def format_value_for_munin(value, zero_allowed=False):
"""
Convert value into a format that will be understood by Munin
@param value: value to write
@param boolean zero_allowed: if True, 0 will be reported as 0, otherwise as unknown ('U')
@return value
"""
return value if value or (zero_allo... |
def get_inverse_transform(transform):
"""Generates a transform which is the inverse of the provided transform"""
inverse_transform = [0] * len(transform)
for i in range(len(transform)):
inverse_transform[transform[i]] = i
return inverse_transform |
def write_about(name, title, date, author):
"""
"""
return "* {} - {} * The {} is about {}. It has been writtent by {}, and published in {}.".format(name, title, name, title, author, date) |
def _calculate_texture_sim(ri, rj):
"""
Calculate texture similarity using histogram intersection
"""
return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])]) |
def val_to_dec(value, base=2):
""" base=2: [False, False, False, False, False, False, False, True] -> 128 """
res = 0
for idx, val in enumerate(value):
res += int(val) * base ** idx
return res |
def topo_sorted(depmap):
"""Return list of items topologically sorted.
depmap: { item: [required_item, ...], ... }
Raises ValueError if a required_item cannot be satisfied in any order.
The per-item required_item iterables must allow revisiting on
multiple iterations.
"""
ordered = [ ... |
def generate(message: str) -> str:
"""Generate a string with 'Hello message' format.
Args:
message: A string to be added.
Returns:
Generated String.
"""
return 'Hello {}'.format(message) |
def hello_guest(guest):
"""route for user privelege only"""
return 'Hello %s as Guest' % guest |
def is_list_of_int(value):
"""
Check if an object is a list of integers
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, int) for elem in value) |
def invert(d):
"""Given a dictionary `d`, produce a dictionary that inverts its key-value relationship.
Warning:
If a value appears multiple times in `d` the resulting inverse dictionary will contain
only the last key that was encountered while iterating over `d` (which is, by definition,
... |
def strtoken(st,pos,sep):
"""Splits string and returns splitted substring. Returns "" if None
Args:
st: String to split
pos: Position to return. Can be negative
sep: Separator
"""
out = ""
s = st.split(sep)
if len(s) >= abs(pos) and pos != 0:
if pos > 0:
out = s[pos-1]
else:
... |
def make_url_action(label, url, i18n_labels=None):
"""
make url action.
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/1005050?lang=en>`_
:param url: User behavior will trigger the client to request this URL.
:return: actions content
"""
i... |
def scale_loss(loss, loss_scale):
"""Scale loss by loss_scale."""
if callable(loss):
return lambda: loss() * loss_scale
return loss * loss_scale |
def get_tag_value(tag_list, key):
"""
Given a list of dictionaries representing tags, returns the value of the given key, or None if the key
cannot be found.
"""
for tag in tag_list:
if tag["Key"] == key:
return tag["Value"]
return None |
def dosta_Topt_volt_to_degC(T_optode_volt):
"""
Description:
Computes T_optode [degC], the DOSTA foil temperature as measured by its internal thermistor,
from the analog output of a DOSTA Aanderaa Optode connected to a SBE CTD's 0-5 volt analog
data channel.
Usage:
T_optode... |
def convert_LengthUnit(len_unit1,len_unit):
"""
convert unit from [len_unit] => [len_unit1]
"""
if len_unit1 =="" or len_unit1 == len_unit:
return len_unit,1
#
dictC = {"ft_km":0.0003048, "kt_km": 1.852 , "mi_km":1.609344, "m_km":0.001, \
"km_ft":3280.8399, "km_kt": 0.53996... |
def _all_slots(T):
""" Return a list of all slots for a type, or object.
Args:
T: the type, or object to determine the slots for.
Returns:
The list of slot names, including those in base classes.
"""
if not isinstance(T, type):
T = type(T)
slots = []
def inner(T, sl... |
def full_name_natural_split(full_name):
"""
This function splits a full name into a natural first name, last name
and middle initials.
"""
parts = full_name.strip().split(' ')
first_name = ""
if parts:
first_name = parts.pop(0)
if first_name.lower() == "el" and parts:
fir... |
def match_with_gaps(my_word, other_word):
"""
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special
s... |
def get_year_and_day_of_year(year_and_day_of_year):
"""
Extract the year and day of year as separate values from a single integer containing both
:param year_and_day_of_year: An integer with format 'YYYYDDD' where YYYY is the year and DDD is the day
:return: A list of the year and day of year
"""
... |
def reorder(mylist):
"""Reorder list from 0 degree -> 360 degree to -180 degree -> 180 degree.
Parameters
----------
mylist : list
old list
Returns
-------
list
new list
"""
old_mylist = mylist
mylist = old_mylist[180:]
mylist += old_mylist[:180]
return... |
def get_arguments_str(arguments: dict) -> str:
""" takes the arguments dictionary of a proc_init and turns it into a nicely formatted string
"""
return ", ".join(["{}:{}".format(k, arguments[k]) for k in arguments]) |
def skeletonModuleName(mname):
"""Convert a scoped name string into the corresponding skeleton
module name. e.g. M1.M2.I -> M1__POA.M2.I"""
l = mname.split(".")
l[0] = l[0] + "__POA"
return ".".join(l) |
def build_stats(history, eval_result, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
history: Results of the training step. Supports both categorical_accuracy
and sparse_categorical_accuracy.
eval_output: Output of the eval step. Assumes first value is eval_loss and
... |
def query_api_url(count, start):
"""
Queries the Alexa API for top sites with a global scope
:param count: Number of sites to return in a response
:param start: Index of site to start from according to the Alexa API
:return: json
"""
return f'https://ats.api.alexa.com/api?Action=Topsites&Co... |
def hours_minutes(raw_table, base_index):
""" Convert raw value to hours """
return "%02d:%02d" % (raw_table[base_index],
raw_table[base_index + 1]) |
def extract_email(commit_email):
"""
Helper function!
Takes as parameter a string that contains between "<" and ">" an email that needs to be extracted.
The function uses find to search for the beginning of the email (that starts with "<") and adds the lengths of the
"<" so that returned email doesn... |
def version_split(s, delimiters={"=", ">", "<", "~"}):
"""Split the string by the version:
mypacakge<=2.4,==2.4 -> (mypacakge, <=2.4,==2.4)
In [40]: version_split("asdsda>=2.4,==2")
Out[40]: ('asdsda', ['>=2.4', '==2'])
In [41]: version_split("asdsda>=2.4")
Out[41]: ('asdsda', ['>=2.4'])
... |
def is_scale_type(variable_type):
"""Utility method that checks to see if variable_type is a float"""
try:
float(variable_type)
return True
except ValueError:
return False |
def _make_post_url(row):
"""
create the facebook post URL from ID
"""
post_url = "http://facebook.com/{0}".format(row['facebook_id'])
return post_url |
def calc_price_exquisite_extract_of_nourishment(fine_price, masterwork_price, rare_price, exotic_price):
""" https://wiki.guildwars2.com/wiki/Exquisite_Extract_of_Nourishment """
return 5 * fine_price + 5 * masterwork_price + 5 * rare_price + 10 * exotic_price |
def dotPlot(seqA: str, seqB: str) -> list:
"""Compare two DNA sequences using DotPlot method.
**Keyword arguments:**
seqA -- first sequence
seqB -- second sequence
"""
la = len(seqA)
lb = len(seqB)
M = [[' ' for n in range(la)] for m in range(lb)]
for i in range(lb):
for j in range(l... |
def _all_elements_equal(list_to_check:list) -> bool:
"""Private function to check whether all elements of
list_to_check are equal."""
# set() is not used here as some times the list
# elements are not hashable, e.g., strings.
if len(list_to_check) == 1:
return True
return all([
... |
def process_path(module_path):
"""
Method to obtain module and class_name from a module path
Args:
module_path(String): path in the format module.class_name
Returns:
tuple containing class_name and module
"""
if module_path == 'numpy.ndarray':
return 'StorageNumpy', 'hec... |
def checksum(data):
"""
Calculate checksum on value string.
@retval checksum - base 10 integer representing last two hexadecimal digits of the checksum
"""
total = sum([ord(x) for x in data])
return total & 0xff |
def _adjust_component(value: int) -> int:
""" Returns the midpoint value of the quadrant a component lies.
By Maitreyi Patel 101120534
>>>_adjust_component(43)
31
>>>_adjust_component(115)
95
>>>_adjust_component(154)
159
>>>_adjust_component(210)
223
"""
mid... |
def simple(s):
"""Break str `s` into a list of str.
1. `s` has all of its peripheral whitespace removed.
1. `s` is downcased with `lower`.
2. `s` is split on whitespace.
3. For each token, any peripheral punctuation on it is stripped
off. Punctuation is here defined by `string.punctuation`.
... |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
maxSum = 0
currentS... |
def interfaces(data):
"""return a list of interfaces name"""
return [interface['nick'] for interface in data['interfaces']] |
def generate_col_names(d):
"""Utility function to generate column names for the synthetic dataset """
assert (d >= 6)
pC = 2 # number of confounders
pP = 2 # number of outcome predictors
pI = 2 # number of exposure predictors
pS = d - (pC + pI + pP) # number of spurious covariates
... |
def extract_features(row):
""" extract_features function
Taking one row, extracts all features deemed useful for logistic regression
and returns them as a list.
Args
----
row : dict
A single data point
Returns
-------
list
"""
pclass = float(row['Pclass']) if row['... |
def _get_project_sync_url(sg_field_value, logger):
"""
Return sync url from Shotgun File/Link field.
:param sg_field_value: Shotgun File/Link field value as a dict or ``None``.
:param logger: Logger instance.
:returns: URL for sync as a str or ``None``.
"""
# We expect a File/Link field... |
def to_lowercase(words):
"""Convert all characters to lowercase from list of tokenized words"""
new_words = []
for word in words:
new_word = word.lower()
new_words.append(new_word)
return new_words |
def xmltag_split(tag):
"""Return XML element bare tag name (without prefix)"""
try:
return tag.split('}')[1]
except:
return tag |
def utf(val):
"""Little helper function which turns strings to utf-8 encoded bytes"""
if isinstance(val, str):
return val.encode('utf-8')
else:
return val |
def is_instruction(func):
"""
Check the given function to see if it's an instruction.
A instruction is a function that is decorated with :func:`~ydf.instructions.instruction`.
:param func: Object to check
:return: `True` if object is an instruction function, `False` otherwise
"""
return ca... |
def mirror_action(act):
"""
Mirror an action, swapping left/right.
"""
direction = (act % 18) // 6
act -= direction * 6
if direction == 1:
direction = 2
elif direction == 2:
direction = 1
act += direction * 6
return act |
def _map_fn_to_mapcat_fn(fn, *args, **kwargs):
"""
takes in a function for mapping, and arguments to apply, and returns
a result for a mapcat
NOTE:
- this is a separate function for serializability
"""
res = fn(*args, **kwargs)
return [res] |
def minDistance(s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
len1 = len(s1)
len2 = len(s2)
dp = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 1):
if i > 0 and j == 0:
dp[i][j] =... |
def _split_short_opt_list(short_opt_list):
"""Split short options list used by getopt.
Returns a set of the options.
"""
res = set()
tmp = short_opt_list[:]
# split into logical elements: one-letter that could be followed by colon
while tmp:
if len(tmp) > 1 and tmp[1] is ':':
... |
def format_list(data, separator=', '):
"""Return a formatted strings
:param data: a list of strings
:param separator: the separator to use between strings (default: ', ')
:rtype: a string formatted based on separator
"""
if data is None:
return None
return separator.join(sorted(dat... |
def CharUnique(S: str) -> bool:
"""
>>> CharUnique('deacidified')
False
>>> CharUnique('keraunoscopia')
False
>>> CharUnique('layout')
True
>>> CharUnique('brand')
True
>>> CharUnique('texture')
False
>>> CharUnique('ovalness')
False
>>> CharUnique('unglove')
True
"""
#for i scan ahe... |
def _seconds_to_time(seconds):
"""
Convert seconds into a time-string with the format HH:MM:SS. Seconds should
be an integer or float (rounded to nearest second and then cast to int).
"""
# Represent as integer
try:
if not type(seconds) is int:
seconds = int(round(seconds,0... |
def _partition(array, low, high, pindex):
"""Sort values lower < pivot index < higher."""
# Place pivot in front
array[low], array[pindex] = array[pindex], array[low]
i = low + 1
for j in range(low + 1, high):
if array[j] < array[low]:
array[i], array[j] = array[j], array[i]
... |
def centroid(X):
"""
Calculate the centroid from a vectorset X
"""
C = sum(X)/len(X)
return C |
def move(text, i, j):
"""Move operation.
move position X to position Y means that the letter which is at
index X should be removed from the string, then inserted such that it
ends up at index Y.
"""
chars = [t for t in text]
letter = chars[i]
chars.pop(i)
chars.insert(j, letter)
... |
def is_vlan(v):
"""
Check value is valid VLAN ID
>>> is_vlan(1)
True
>>> is_vlan(-1)
False
>>> is_vlan(4095)
True
>>> is_vlan(4096)
False
>>> is_vlan("g")
False
"""
try:
v = int(v)
return 1 <= v <= 4095
except ValueError:
return False |
def listify(x):
"""Puts non-list objects into a list.
Parameters
----------
x: Object to ensure is list
Returns
----------
:obj:`list`
If ``x`` is already a list, this is returned. Otherwise, a list\
containing ``x`` is returned.
"""
if isinstance(x, list):
... |
def arg_keys(arg_name, keys):
"""Appends arg_name to the front of all values in keys.
Args:
arg_name: (string) String containing argument name.
keys: (list of strings) Possible inputs of argument.
Returns:
List of strings with arg_name append to front of keys.
"""
return ["... |
def inherit_docstrings(cls):
"""Inherit docstrings from parent class"""
from inspect import getmembers, isfunction
for name, func in getmembers(cls, isfunction):
if func.__doc__:
continue
for parent in cls.__mro__[1:]:
if hasattr(parent, name):
func._... |
def get_ids_from_list_of_dicts(lst):
"""Get all ids out of a list of objects and return a list of string ids."""
id_list = []
for item_dict in lst:
if "id" in item_dict:
id_list.append(item_dict["id"])
return id_list |
def points_allowed_score(points: float) -> int:
"""The points allowed score logic generator based on standard D/ST fantasy
football scoring.
Args:
points (float): number of points allowed
Returns:
score (int): the score got for that number of points allowed
"""
if points == 0:
... |
def rotate(data, n):
"""
Create a method named "rotate" that returns a given array with the elements
inside the array rotated n spaces.
with array [1, 2, 3, 4, 5]
n = 7 => [4, 5, 1, 2, 3]
n = 11 => [5, 1, 2, 3, 4]
n = -3 => [4, 5, 1, 2, 3]
"""
if data:
... |
def is_autosomal(chrom):
"""Keep chromosomes that are a digit 1-22, or chr prefixed digit chr1-chr22
"""
try:
int(chrom)
return True
except ValueError:
try:
int(str(chrom.lower().replace("chr", "").replace("_", "").replace("-", "")))
return True
ex... |
def clean_newline(line):
"""Delete newline characters at start and end of line
Params:
line (Unicode)
Returns:
line (Unicode)
"""
return_line = line.strip('\r\n')
if return_line != line:
return True, return_line
else:
return False, line |
def args_to_int(args: list) -> tuple:
""" Convert augs to int or return empty """
try:
return tuple([int(i) for i in args])
except ValueError:
return () |
def swap(record):
""" Swap (token, (ID, URL)) to ((ID, URL), token)
Args:
record: a pair, (token, (ID, URL))
Returns:
pair: ((ID, URL), token)
"""
token = record[0]
keys = record[1]
return (keys,token) |
def isplaceholder(sym):
"""
Checks whether a symbol in a structure is a placeholder for a representation
"""
if isinstance(sym, str):
return sym[0] == "#"
else:
return False |
def big_number(int_in):
"""Converts a potentially big number into a lisible string.
Example:
- big_number(10000000) returns '10 000 000'.
"""
s = str(int_in)
position = len(s)
counter = 0
out = ''
while position != 0:
counter += 1
position -= 1
out = s[posit... |
def get_values_language():
"""Provide expected values - database table language."""
return [
None,
True,
"xxx_code_iso_639_3",
"xxx_code_pandoc",
"xxx_code_spacy",
"xxx_code_tesseract",
"xxx_directory_name_inbox",
"xxx_iso_language_name",
] |
def init_feature(
chromosome_size: int,
organism: str,
mol_type: str = 'genomic DNA') -> str:
"""
Initialize a feature section of genbank file.
The feature section always start with the mandatory 'source' feature
"""
text = f'''\
FEATURES Location/Qualifi... |
def calc_met_equation_cdd(case, t_min, t_max, t_base):
"""Calculate cdd according to Meteorological
Office equations as outlined in Day (2006): Degree-days: theory and application
Arguments
---------
case : int
Case number
t_min : float
Minimum daily temperature
t_max : floa... |
def _get_column_val(column):
"""
Parameters
----------
column : float or tuple
gives the column or (column, unc) or (column, punc, munc)
Returns
-------
column: float
column value
"""
if isinstance(column, tuple):
return float(column[0])
else:
re... |
def get_md_link(text: str, link: str) -> str:
"""Get a link in Markdown format."""
return f"[{text}]({link})" |
def make_tax_group_dict(taxonomic_groups):
"""Convert string to dictionary. Then check if all values are, in fact,
integers"""
tg = eval(taxonomic_groups)
if type(tg) == dict:
pass
else:
raise TypeError("Taxonomic groups can not be coerced into a"
"dictionary!... |
def tarjans(complexes, products):
""" Tarjans algorithm to find strongly connected components.
Dirctly from the peppercornenumerator project.
"""
stack, SCCs = [], []
def strongconnect(at, index):
stack.append(at)
at.index = index
at.llink = index
index += 1
... |
def splitter(string, left=False, right=False):
"""Split 'domain\cn' or 'domain\computer' values and return left and/or right.
Can be used with tuple unpacking if left/right not set, but should be wrapped in
a try-except to catch ValueError in the case split returns 1 string.
"""
try:
split... |
def filter_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0):
"""
This is an example handler function which can filter entities. Multiple handler functions can be used to
process a entity. The response is an entity which will get passed to the next handler i... |
def contingency_table(ys, yhats, positive=True):
"""Computes a contingency table for given predictions.
:param ys: true labels
:type ys: iterable
:param yhats: predicted labels
:type yhats: iterable
:param positive: the positive label
:return: TP, FP, TN, FN
>>> ys = [True, True, T... |
def WORK(config, task):
"""
The work to be done for each task
Parameters
----------
config : dict
task : dict
Returns
-------
status : Boolean
"""
status = False
return(status) |
def endswith(string, target):
"""
Description
----------
Check to see if the target string is the end of the string.
Parameters
----------
string : str - string to check end of\n
target : str - string to search for
Returns
----------
bool - True if target is the end of stri... |
def prep_ingr(ingredients):
"""preprocess formatting of the list of ingredients
will remove string 'and' and '&' if present
Args:
ingredients (list of strings): list of ingredients
Returns:
list: list of formatted ingredients
"""
toreturn = []
for ingr in ingr... |
def validate_input(crop_size, crop_center): # validates the input of the ex4 function
"""
:param image_array: A numpy array containing the image data in an arbitrary datatype and shape (X, Y).
:param crop_size:A tuple containing 2 odd int values. These two values specify the size
of the rectangl... |
def doublecolon_tail(string):
"""return the last (rightmost) part of a namespace or namespace-qualified proc"""
last_colons = string.rfind("::")
if last_colons >= 0:
return string[last_colons + 2 :]
return string |
def same_keys(a, b):
"""Determine if the dicts a and b have the same keys in them"""
for ak in a.keys():
if ak not in b:
return False
for bk in b.keys():
if bk not in a:
return False
return True |
def gfrcalc_alt(guide, distneg_med, distpos_med):
"""
Determines guide field ratio, the ratio of the PIL-parallel component of
magnetic field to the PIL-perpendicular component, a proxy for the magnetic
shear.
Parameters
----------
guide_left : arr
Guide field strength, right-hand s... |
def is_executable(permission_int):
"""Takes a number containing a Unix file permission mode (as reported by RPM utility)
and returns True if the file has executable bit set.
NOTE: for some reason the modes returned by RPM utility are beyond 777 octal number...
so we throw away the... |
def is_odd(x: float):
"""Function checking if a number is odd.
Args:
x (float): Number to check.
Returns:
bool: True if the number is odd, False otherwise.
"""
return x % 2 == 1 |
def mod_inv(a, n):
"""Computes the multiplicative inverse of a modulo n using the extended Euclidean algorithm."""
t, r = 0, n
new_t, new_r = 1, a
while new_r != 0:
quotient = r // new_r
t, new_t = new_t, t - quotient * new_t
r, new_r = new_r, r - quotient * new_r
if r > 1:... |
def build_settings_dictionary(id_string, start_time, redis_connection_string, shared_memory_max_size,
ordered_ownership_stop_threshold, ordered_ownership_start_threshold):
"""
Builds the settings dictionary which peers use to pass settings information back and forth.
"""
... |
def is_anagram(word_1, word_2):
"""
Test if the parameters are anagram of themselves.
:param word_1: 1st word
:param word_2: 2nd word
:return: True if the parameters are anagram, False if not
"""
word_1.lower()
word_2.lower()
return sorted(word_1) == sorted(word_2) |
def func_g(a, n, p, x_i):
"""
a_(i+1) = func_g(a_i, x_i)
"""
if x_i % 3 == 2:
return a
elif x_i % 3 == 0:
return 2*a % n
elif x_i % 3 == 1:
return (a + 1) % n
else:
print("[-] Something's wrong!")
return -1 |
def v3_state_away_json():
"""Return a /v1/ss3/subscriptions/<SUBSCRIPTION_ID>/state/away."""
return {
"success": True,
"reason": None,
"state": "AWAY",
"lastUpdated": 1534725096,
"exitDelay": 120
} |
def sanitize_dest(path):
"""Ensure the destination does have a trailing /"""
return path if path.endswith('/') else path + '/' |
def list_difference(l1, l2, key1=None, key2=None):
"""Like set difference method, but list can have duplicates. If l1 has two
identical items, and l2 has one of that item, res will have 1 of that item
left. Sets would remove it"""
if not key1:
key1 = lambda x: x
if not key2:
key2 = l... |
def _cleanup_eval(body):
"""Removes code blocks from code."""
if body.startswith('```') and body.endswith('```'):
return '\n'.join(body.split('\n')[1:-1])
return body.strip('` \n') |
def parseDBXrefs(xrefs):
"""Parse a DB xref string like HGNC:5|MIM:138670 to a dictionary"""
#Split by |, split results by :. Create a dict (python 2.6 compatible way).
if xrefs == "-": return {}
return dict([(xrefParts[0], xrefParts[2])
for xrefParts in (xref.partition(":")
... |
def int_to_little_endian(n: int, length: int) -> bytes:
"""
Represents integer in little endian byteorder.
:param n: integer
:param length: byte length
:return: little endian
"""
return n.to_bytes(length, 'little') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.