content stringlengths 42 6.51k |
|---|
def add_integer(a, b=98):
"""
Adds two integers together
Args:
a (int): first value to add
b (int, default=98): second value to add
Returns:
the sum of a and b
"""
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
if type(a) is not ... |
def _is_problematic( # pylint: disable=too-many-arguments
starts, ends, block_index, first, max_res_block, min_gap_block):
"""
Return True is the sub-exon block is problematic.
In particular, a sub-exon block is problematic if it has <= max_res_block
and it is separeated from the rest of the s... |
def degree_to_note(root, mode, degree):
"""Convert a list of relative degrees to midi note numbers.
Parameters
----------
key - MIDI note number for the root note
mode - a number for the mode (0 - Ionian (major),
1 - Dorian, ..., 5 - Aeolian (minor), ...)
degree - a scale degree ... |
def humanize_time(secs):
"""
taken from http://testingreflections.com/node/6534
:param secs:
:return:
"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) |
def fitness(member):
"""Computes the fitness of a species member.
http://bit.ly/ui-lab5-dobrota-graf"""
if member < 0 or member >= 1024:
return -1
elif member >= 0 and member < 30:
return 60.0
elif member >= 30 and member < 90:
return member + 30.0
elif member >= 90 and member < 120:... |
def unique_list(l):
"""Remove duplicate term from a list
Parameters
----------
l : list
A list potentially contains duplicate terms
Returns
ulist : list
A list without unique terms
"""
ulist = []
for item in l:
if item not in ulist:
u... |
def is_int_even_v04(num):
"""
Use the modulo operator to evaluate whether an integer provided by
the caller is even or odd, returning either True or False. Wrap
return statements in try / except blocks to catch exceptions.
Parameters:
num (int): the integer to be evaluated.
Returns:
... |
def collisionBetweenTwoSurfaces(r1_ul, r1_lr, r2_ul, r2_lr):
"""
Check wheter two rectangles are colliding.
:param r1_ul: Point of the upper left corner of the first rectangle.
:param r1_lr: Point of the lower right corner of the first rectangle.
:param r2_ul: Point of the upper left corner of the second rectangle... |
def LevenshteinDistance(first, second):
"""Find the Levenshtein distance between two strings."""
if len(first) > len(second):
first, second = second, first
if len(second) == 0:
return len(first)
first_length = len(first) + 1
second_length = len(second) + 1
distance_matrix = [[0] ... |
def parse_season_day_period(time_id):
"""Returns the season, day and period value from an id
Argument
--------
time_id : int
An integer representing the interval count
Returns
-------
tuple
A tuple of ``(season, period)``
Notes
-----
time_id = (168 * (season - 1... |
def remove_crs(mystring):
"""Removes new lines"""
return mystring.replace('\n', ' ').replace('\r', '') |
def number_unit(disc):
"""
Return the number of units with the given discriminant.
"""
if disc < -4:
return 2
elif disc == -4:
return 4
elif disc == -3:
return 6
else:
raise ValueError |
def strip_whitespace(values):
"""Strip leading and trailing whitespace from each string in a list of
strings. If the string only contains whitespace, filter it out.
"""
return [v.strip() for v in values if v.strip()] |
def build_raw_query(table, where):
"""Build a raw SQL query with a user-defined `where` clause."""
return " ".join([
'SELECT', 'id', 'FROM', table,
'WHERE', where.replace('%', '%%'),
]) |
def format_bustime(bustime, round="millisecond"):
"""Convert bustime to a human-readable string (-)HH:MM:SS.fff, with the
ending cut off depending on the value of round:
"millisecond": (default) Round to the nearest millisecond.
"second": Round down to the current second.
"minute": Round down to the current min... |
def get_detname(det_id):
"""Return NRC[A-B][1-5] for valid detector/SCA IDs"""
det_dict = {481:'A1', 482:'A2', 483:'A3', 484:'A4', 485:'A5',
486:'B1', 487:'B2', 488:'B3', 489:'B4', 490:'B5'}
scaids = det_dict.keys()
detids = det_dict.values()
detnames = ['NRC' + idval for idval in d... |
def get_organism_list(population_dict):
"""
Constructs organism list from population dict data structure.
"""
organism_list = []
for species in population_dict:
organism_list.extend(population_dict[species]['organisms'])
return organism_list |
def convert_object_into_dict( result ):
"""The search script returns objects, converts into a dictionary so
that they can be serialized when we send them to ther server.
"""
if type( result ) is dict: return result # just in case...
return { k: getattr( result, k ) for k in result.__dict__ } |
def str_strip(text):
"""Strips whitespaces from the start and the end of the text."""
return text.strip() |
def calc_history_score(history):
"""
Calculate the history score given a list of pass/fail booleans.
Lower indices represent the most recent entries.
"""
if len(history) == 0:
return 0.0
score = 1.0
for index, good in enumerate(history):
if not good:
score -= 0.5 ... |
def argname(i):
"""Get a name for an unnamed positional argument, given its position."""
return "_" + str(i) |
def min(x, y):
"""
Return the minimum between x and y
>>> min(1,2)
1
>>> min(3,1)
1
>>> min(2,3)
2
>>> min(0, 67777)
0
>>> min(-1, -5)
-5
>>> min(-7, -1)
-7
>>> min(0, 0)
0
"""
if (x < y):
return x
else:
return y |
def matches(task, config):
"""Check if a task matches a configured filter."""
if "labels" in config["filter"].keys():
for label in config["filter"]["labels"]:
if label["id"] not in task["labels"]:
return False
if "project" in config["filter"].keys():
if config["fi... |
def int_to_float(value):
"""
Convert integer to float, if possible.
Parameters
----------
value
Name of the value we want to convert.
Returns
-------
value
Value converted to float, if possible
"""
return float(value) if type(value) == int else value |
def get_division(genome: dict):
"""Retrieve the division of a genome."""
division = genome["division"].lower().replace("ensembl", "")
if division == "bacteria":
raise NotImplementedError("Bacteria from Ensembl not supported.")
is_vertebrate = bool(division == "vertebrates")
return division,... |
def s_esc(s):
"""
equivalent to s.replace("/",r"\/")
:type s: str
:rtype: str
"""
return s.replace("/", r"\/") |
def parse_to_none(val):
"""
Convert value to None if match, pass otherwise.
"""
if val in ['Unknown', 'NA', '']:
return None
return val |
def count_elements(_polymer):
"""Return a list of the polymer elements with the tuples sorted by count descending"""
count_dicts = { c: _polymer.count(c) for c in _polymer }
return sorted(count_dicts.items(), key = lambda p: p[1], reverse=True) |
def isPhysicalQuantity(x):
"""
@param x: an object
@type x: any
@returns: C{True} if x is a L{PhysicalQuantity}
@rtype: C{bool}
"""
return hasattr(x, 'value') and hasattr(x, 'unit') |
def GetValue(text, valname):
"""Primitive routine to retrieve a value from a string of this form:
'Santa Clara Valley - AQI: 80, Pollutant: PM2.5'
AQI: 0..500 http://www.sparetheair.org/understanding-air-quality/reading-the-air-quality-index
101+ in any district triggers a spair the air.
"""
fi... |
def expand_case_matching(s):
"""Expands a string to a case insenstive globable string."""
t = []
openers = {'[', '{'}
closers = {']', '}'}
nesting = 0
for c in s:
if c in openers:
nesting += 1
elif c in closers:
nesting -= 1
elif nesting > 0:
... |
def rangeLimit(u, range):
"""
Returns a logical vector that is True where the
values of `u` are outside of `range`.
"""
return ~((range[0] < u) & (u < range[1])) |
def get_vpc_domain_id(n1, n2):
""" calculate INTEGER vpc_id for two nodes """
n1 = int(n1)
n2 = int(n2)
if n1>n2: vpc_node = (n1<<16) + n2
else: vpc_node = (n2<<16) + n1
return vpc_node |
def output_ext(key: int, ext: str):
"""
given a key and file ext, concats them both.
de, 6 --> de6
"""
new_ext = ext + str(key)
return new_ext |
def convert_from_ms_to_s(timestamp: int) -> int:
"""Converts from milliseconds to seconds"""
return round(timestamp / 1000) |
def ConvertClassExpressionToClassType(class_name):
""" Turn "final HashMap<String>" to HashMap.class. """
return '%s.class' % class_name.split()[-1].split('<')[0] |
def findEndBrace(s, lbchar='(', rbchar=')'):
"""Find position in string (or list of strings), s, at which final matching
brace occurs (if at all). If not found, returns None.
s[0] must be the left brace character. Default left and right braces are
'(' and ')'. Change them with the optional second and t... |
def escapeAttrJavaScriptStringDQ(sText):
""" Escapes a javascript string that is to be emitted between double quotes. """
if '"' not in sText:
chMin = min(sText);
if ord(chMin) >= 0x20:
return sText;
sRet = '';
for ch in sText:
if ch == '"':
sRet += '\\"'... |
def find_outliers(group, delta):
"""
given a list of values, find those that are apart from the rest by
`delta`. the indexes for the outliers is returned, if any.
examples:
values = [100, 6, 7, 8, 9, 10, 150]
find_outliers(values, 5) -> [0, 6]
values = [5, 6, 5, 4, 5]
find_outliers(va... |
def fromMel(x):
""" Converts x from mel-scale to Hz """
return 700*(10**(x/2595.0)-1) |
def response_plain_text(message, endsession):
""" create a simple json plain text response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': message
},
'shouldEndSession': endsession
} |
def instance_module_vhdl_style(module_name, entity_name, ports):
"""
Instance VHDL module
:param module_name:
:param entity_name:
:param ports:
:return:
"""
# Instance the module
disp_str = "\n{} : {} port map (\n".format(entity_name, module_name)
for port in ports:
disp... |
def sum_stats(stats_data):
"""
Summarize the bounces, complaints, delivery attempts and rejects from a
list of datapoints.
"""
t_bounces = 0
t_complaints = 0
t_delivery_attempts = 0
t_rejects = 0
for dp in stats_data:
t_bounces += int(dp['Bounces'])
t_complaints += in... |
def is_palindrome_2(n):
"""
Check for first and last value of int digit
:param n:
:return:
"""
number_as_list = list(str(n))
for n in number_as_list:
# check if current item is not equal to last itme in the list
if n != number_as_list.pop():
return False
retur... |
def single_number(nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in range(0, 32):
count = 0
for num in nums:
if ((num >> i) & 1):
count += 1
res |= ((count % 3) << i)
if res >= 2**31:
res -= 2**32
return res |
def zipdict(keys, vals):
"""Creates a dict with keys mapped to the corresponding vals."""
return dict(zip(keys, vals)) |
def _get_type_name(value):
"""return a string describing the type of value"""
try:
return value.__class__.__name__
except AttributeError:
pass
return repr(type(value)) |
def attributes_present(variables, attr_map):
"""Returns a list of the relevant attributes present
among the variables.
"""
return [attr for attr in attr_map if any(v.attributes[attr] for v
in variables)] |
def markdown_escaper(input_text):
"""Small function that escapes out special characters in Markdown
so they display as intended. Primarily intended for use in titles.
:param input_text: The text we want to work with.
:return: `input_text`, but with the characters escaped.
"""
characters_to... |
def _is_installed(package: str) -> bool:
"""Helper function to detect if some package is installed."""
try:
__import__(package) # noqa: WPS421
except ImportError:
return False
else:
return True |
def filter_words(word):
"""Applies some filtering and discard words based on certain rules"""
if (len(word) > 1):
return True
else:
return False |
def ec_from_reading(reading: float, T: float) -> float:
"""Temperature-compensate an ec reading."""
# todo
return reading
# if cal:
# a = cal.ec / cal.reading
# b = cal.ec - a * cal.reading
# return a * reading + b
# else:
# return reading |
def check(filename, *words):
""" Find if the words are present in the file """
content = open(filename).read().lower().split()
return all(word in content for word in words) |
def get_unique_items(x_pairs, y_pairs):
"""Return all item mentioned either by x_pairs
or y_pairs.
"""
x_pairs.extend(y_pairs)
res = []
for a, b in x_pairs:
if a not in res:
res.append(a)
if b not in res:
res.append(b)
return res |
def remove_invalid_req_args(credentials_dict, invalid_args):
"""
This function iterates through the invalid_args list and removes the
elements in that list from credentials_dict and adds those to a new
dictionary
Returns:
credentials_dict: Input dictionary after popping the elements in
... |
def __indent_text_block(text):
""" Indent a text block """
lines = text.splitlines()
if len(lines) > 1:
out = lines[0] + "\r\n"
for i in range(1, len(lines)-1):
out = out + " " + lines[i] + "\r\n"
out = out + " " + lines[-1]
return out
return tex... |
def find_columns(num: int) -> str:
"""Build the table headings for the assignment sections"""
return ' '.join([str(i) for i in range(1, num + 1)]) |
def isCoveredBy(poly, poly1):
"""isCoveredBy(poly, poly1) - returns 1 if poly is completely covered
by poly1, 0 if not"""
return not (poly-poly1) |
def verifyPassword(password):
"""
Check the length and complexity of the password
return true if a pass, false otherwise
"""
if len(password) < 7:
return False
return True |
def _get_comparisons_1(idx, a, b):
"""Collect comparisons of 1st type:
If A < B and B < C, do their vector reflect this linearity, i.e do sim(A,B) > sim(A,C) and
sim(B,C) > sim(A,C) hold?
"""
if len(a) == 0:
return []
if len(b) == 0:
return []
out = []
r1 = [int(x) ... |
def idx_self_reference(indices):
"""
Check Array for Existing: Array[IDX] == [IDX]
"""
for c, idx in enumerate(indices):
if c == idx:
return True
return False |
def convert_unit(value, src_unit, dest_unit):
"""Coverts the value in dest_unit from src_unit
Arguments:
value -- A positive number.
src_unit -- string ['kg', 'ounce', 'pound']
dest_unit -- string ['kg', 'ounce', 'pound']
>>> abs(convert_unit(10.23, 'kg', 'ounce')-360.85302) <= 1e-... |
def filter_fields(check_fields, container):
"""
Given a set of fields, this is a list of fields actually found in some containing
object.
Always includes keyfunc fields unless they set the magic _filter_key attribute
sorted_json_field above is a good example of doing this
"""
fields = []
... |
def power(raw_table, base_index):
""" Value of MWh, KWh, Wh or None if 65535 """
if (raw_table[base_index] == 0xFFFF
or raw_table[base_index+1] == 0xFFFF
or raw_table[base_index+2] == 0xFFFF):
return None
return (raw_table[base_index] * 1000 + raw_table[base_index+1]) * 1000 ... |
def unique_filename(filename, namespace, resource, resource_name):
"""Return a unique filename derived from the arguments provided, e.g.
"namespace_{namespace}.{configmap|secret}_{resource_name}.{filename}".
This is used where duplicate data keys may exist between ConfigMaps
and/or Secrets within the s... |
def gcd_recur(a, b):
"""Find the greatest common denominator with 2 arbitrary integers.
Parameters
----------
a : int
User provided integer
b : int
User provided integer
Returns
-------
gcd : int
"""
if b == 0:
return a
if b > a:
tmp = b
... |
def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
"""
if x is None:
return None
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(perm).contiguous()
out_size = list(x.size())
out_size[0] *= coun... |
def int_to_bits(int_str, qubit_count):
"""
Convert a number (possibly in string form) to a readable bit format.
For example, the result '11', which means both qubits were measured as 1, is returned by the API as "3".
This converts that output to the readable version.
Args:
int_str: A string... |
def _trim(docstring):
"""Remove block indentation from a docstring."""
if not docstring:
return ''
lines = docstring.splitlines()
# Determine minimum indentation (first line doesn't count):
indent = 999
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
... |
def Step_DeadBiomass(Xo,Hinf,Cinf,Ninf,Ginf,QH,QC,QN,QG,Nc,decay,mort,Qc,X,dt,Vc):
"""
Computes the increase in dead biomass between t and t+dt
"""
return(Xo + (-0.1*Xo + (decay+mort)*Nc*(Qc+X))*dt) |
def get_cv(word, vowels, sep=None):
"""
Calculate the consonant ("C") and vowel ("V") structure of the
given word. Returns a string of the characters "C" and "V"
corresponding to the characters in the word.
*vowels* -- A list of the characters representing vowels.
*sep* -- String used to separ... |
def unix_time_to_mjd(time_in_unix):
"""
Converts the time format from unix to MJD (Modified Julian Date)
86400 is the # of sec per 24 hours
40587 is the unix epoch in mjd
"""
time_in_mjd = time_in_unix / 86400 + 40587
return time_in_mjd |
def bl_calculate_deposit(amount: int, percentage: int, years: int) -> float:
"""
This function calculate amount of deposit
:param amount: Start amount
:param percentage: Bank percentage
:param years: Time of deposit
:return: Amount of deposit
"""
return amount * (1 + (percentage / 100) ... |
def lsb (target, data):
"""
Embeded data to LSB of target
ex: target='101010', data='111', return '101111'
:param target: string <binary>
:param data: string <binary>
:returns: string
"""
s1 = str(target)
s2 = str(data)
# check if data can't insert in target
if len(s2)>len(s... |
def makeConfiguration(line):
"""
returns configuration based on the line
"""
if line == None:
configuration = [0.0, 0.0, 0.0]
else:
x = float( line[30:38].strip() )
y = float( line[38:46].strip() )
z = float( line[46:54].strip() )
configuration = [x, y, z]
return c... |
def max_common_subphrase_length(a, b):
"""Return the length of the longest common subphrase of a and b; where a and b are
lists of tokens (form+tag)."""
longest = 0
for sp_a in range(len(a)):
for sp_b in range(len(b)):
pos_a = sp_a
pos_b = sp_b
# disregard tag... |
def stripASCII(contentData):
"""
Strips out non-printable ASCII chars from strings, leaves CR/LF/Tab.
Args:
contentData: b"\x01He\x05\xFFllo"
Returns:
strippedMessage: "Hello"
"""
strippedMessage = str()
if type(contentData) == bytes:
for entry in contentData:
... |
def make_stacker_cmd_string(args):
"""Generate stacker invocation script from command line arg list.
This is the standard stacker invocation script, with the following changes:
* Adding our explicit arguments to parse_args (instead of leaving it empty)
* Overriding sys.argv
"""
# This same cod... |
def unique_elements(list_):
"""
Functions to find unique elements from a list of given numbers.
Can also use 'list(set([list_]))'
"""
uniques = []
for number in list_:
if number not in uniques:
uniques.append(number)
return uniques |
def fix_id(id):
"""
fixes the id such that is it a resource identifier
:param id:
:return:
"""
import re
# convert strange characters to space
r = re.sub(r"""[!#$%&'\(\)\*\+,\./:;<=>\?@\[\\\]\^`\{\|}~_]+""", ' ', id)
# title case all words
r = r.title()
r = r[0].lower() + r[1:]
# remove white sp... |
def get_query_for_date_extract(
date_type: str,
target_column: str,
new_column: str,
) -> str:
"""
This method will get as input the date type and return a query with
the appropriate function of that date type on snowflake, it can be a simple function or a whole expression
"""
if date_... |
def has_all_machine_addresses(addresses, subnets):
"""
Check that list of (subnet_ID, machine_ID) tuples contains all addresses on network based
on subnets list
"""
for s_id, s_size in enumerate(subnets):
for m in range(s_size):
# +1 to s_id since first subnet is 1
if... |
def process_dupe_archive_entry(data, duplicates):
"""Take a dupe_archive_data entry and update photo_id if needed."""
clean_photo_ids = []
for photo_id in data.get('photo_ids'):
if photo_id in duplicates:
orig_photo_id = duplicates.get(photo_id).get('orig_photo_id')
clean_pho... |
def search_python(python_code, template_name):
"""
Searches Python code for a template name.
Returns a list of tuples, each one being:
(filename, line number)
"""
retval = []
for fn, content in python_code:
for ln, line in enumerate(content):
if ((u'"%s"' % template_name... |
def alpha_numeric_filter(string):
"""Takes a string and returns a filtered string with only alpha-numeric characters"""
filtered = ""
for char in string:
if char.isalnum() or char == ' ':
filtered += char
if char == '\n':
continue
return filtered |
def FilterRequests(requests):
"""Filters a list of requests.
Args:
requests: [RequestData, ...]
Returns:
A list of requests that are not data URL, have a Content-Type, and are
not served from the cache.
"""
return [r for r in requests if not r.IsDataUrl()
and 'Content-Type' in r.header... |
def stripper(name):
"""
Strip fluff from bar filename.
:param name: Bar filename, must contain '-nto+armle-v7+signed.bar'.
:type name: str
"""
return name.replace("-nto+armle-v7+signed.bar", "") |
def knapsack_max_value(max_weight, items):
"""
Get the maximum value of the knapsack.
"""
# Initialize a lookup table to store the maximum value
lookup_table = [0] * (max_weight + 1)
# Iterate down the given list
for item in items:
# The capacity represents amount of remaining capac... |
def hex_mat_to_string(data):
""" Return string from hex matrix. Inverse of string_to_hex_mat"""
return ''.join([''.join([chr(h) for h in block]) for block in data]).strip('\x00') |
def ensure_list(value):
"""Ensure that parameters are always a list.
Further replaces all None values by empty dictionaries.
"""
if isinstance(value, (dict, int, float, str)):
value = [value]
return value |
def same_last_tasks(plan, n, task=None):
"""
Given a partial 'plan', returns True if the 'n' last tasks of the partial plan are the same (and optionnaly equal to 'task')
"""
if len(plan) < n:
return False
last_tasks = [plan[-i].name for i in range(1, n + 1)]
#print("Last tasks:", last_ta... |
def toChunk(data):
"""
Convert string to a chunk.
@returns: a tuple of strings representing the chunked encoding of data
"""
return ("%x\r\n" % len(data), data, "\r\n") |
def change_dict_naming_convention(d, convert_function):
"""
Convert a nested dictionary from one convention to another.
Args:
d (dict): dictionary (nested or not) to be converted.
convert_function (func): function that takes the string in one convention and returns it in the other one.
R... |
def sizeof_fmt(num, suffix=''):
"""
Format the number to a humanized order of magnitude.
For example, ``11234`` become ``11.23K``.
:param num:
The positive integer.
:param suffix:
Additional suffix added to the resulting string.
:returns:
Formatted number as a string.
... |
def trim_url(url: str):
"""
Inclusively trims everything before the last / character
"""
index = url.rfind('/')
return url[index + 1:] |
def xfrm_ids(name):
"""
Coerce some text into something suitable for a fragment identifier.
"""
return ''.join(filter(lambda c: c.isalnum() or c in '_-',
name.lower().translate({ord(c): '-'
for c in '\N{EM DASH}'
... |
def is_current(ttval):
"""Return True if the `ttval` is now.
"""
print('is_current:', ttval, ttval == ttval.__class__())
return ttval == ttval.__class__() |
def grep_word(word, filenames):
""" Open the given files and look for a specific word.
Append lines containing word to a list and
return it """
lines, words = [], []
for filename in filenames:
print('Processing', filename)
lines += open(filename).readlines()
# Debugging steps
... |
def mongodb_safe(data, dotreplace, dollarreplace):
"""
Transform collected data to be MongoDB safe.
"""
def safe_key(key):
if key.startswith('$'):
key = key.replace('$', dollarreplace, 1)
return key.replace('.', dotreplace)
def safe_value(value):
if not isinsta... |
def split_pkgname(name):
"""
Split a package name in four fields:
(name, pkgver, pkgrel, epoch)
"""
base, sep, pkgrel = name.rpartition('-')
name, sep, pkgver = base.rpartition('-')
epoch, sep, pkgver = pkgver.partition(':')
if not sep:
epoch, pkgver = None, epoch
else:
epoch = int(epoch)
return name,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.