content stringlengths 42 6.51k |
|---|
def adj_dists_fast(clusts1, clusts2):
"""computes distance between adjacency matrices implied by partions without instantiating them.
This is faster than first computing adjacency matrices and then using
adj_dists when the number of clusters is small.
"""
# sum of square set sizes
dist = sum(len... |
def error(p:float, p_star:float) -> tuple:
"""
From 1.2.py.
"""
absolute_error = abs(p - p_star)
relative_error = absolute_error / p
return (absolute_error, relative_error) |
def crc_ccitt(data):
"""Calculate the CRC-16-CCITT with LifeScan's common seed.
Args:
data: (bytes) the data to calculate the checksum of
Returns:
(int) The 16-bit integer value of the CRC-CCITT calculated.
This function uses the non-default 0xFFFF seed as used by multiple
LifeScan meters.
"""
... |
def decode_comment(comment, psep=";", ssep="="):
"""Decode the comment."""
retval = {}
for token in comment.split(psep):
parts = token.split(ssep)
if len(parts) < 2:
retval[parts[0]] = ""
else:
retval[parts[0]] = "=".join(parts[1:])
return retval |
def calc_piping_thermal_losses_cooling(Total_load_per_hour_W):
"""
This function estimates the average thermal losses of a distribution for an hour of the year
:param Tnet_K: current temperature of the pipe
:param m_max_kgpers: maximum mass flow rate in the pipe
:param m_min_kgpers: minimum mass flo... |
def type_of_value(text):
"""
If given string is an int, return the original str
:param text:
:return:
"""
try:
int(text)
return int(text)
except ValueError:
pass
return str |
def check_bool(x):
"""check_bool checks if input 'x' either a bool or
one of the following strings: ["true", "false"]
It returns value as Bool type.
"""
if isinstance(x, bool):
return x
if not x.lower() in ["true", "false"]:
raise RuntimeError("{} is not a boolean value.".... |
def find_words(words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboards = ['qwertyuiop',
'asdfghjkl',
'zxcvbnm',]
out = []
for word in words:
for row in keyboards:
in_row = False
not_in_row = False
for c ... |
def searchnameinbases(name, bases):
"""
>>> class A(object):
... foo = 1
>>> class B(A):
... pass
>>> searchnameinbases('foo', (B,))
True
>>> searchnameinbases('bar', (B,))
False
"""
for base in bases:
if name in base.__dict__... |
def format_as_pct(value, decimal=2):
"""
Formats any value as a percentage.
Parameters
----------
value : int or float
The value you want to format as a percentage.
decimal : int, optional
The number of decimal places the output should have. The default
value is 2.
... |
def search_params_for_link(link):
"""
Parameters to pass to the search API
"""
return {
'filter_link': link,
'debug': 'include_withdrawn',
'fields[]': [
'indexable_content',
'title',
'description',
'expanded_organisations',
... |
def convert_scan_dict_to_string(scan_dict):
"""
converts parsed ImageScanStatus dictionary to string.
:param scan_dict: {'HIGH': 64, 'MEDIUM': 269, 'INFORMATIONAL': 157, 'LOW': 127, 'CRITICAL': 17, 'UNDEFINED': 6}
:return: HIGH 64, MEDIUM 269, INFORMATIONAL 157, LOW 127, CRITICAL 17, UNDEFINED 6
""... |
def tupsum(*addends, strAsOne=True):
"""
Performs a tuple addition on an indefinite number of tuples. Arguments must be tuple-coercibles (they must be
iterables or iterators), or scalars (i.e. tuple([arg]) succeeds).
Returns:
A tuple of the tuple sum of the addends.
DEVELOPER'S CORNER:
Tuples suppor... |
def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
word = word.lower()
pos = list(
filter(lambda v: v >= 0,
map(lambda c: word.index(c) if c in word else -1, 'aeiou')))
if pos:
first = min(pos)
return (word[:first], word[first:])
e... |
def is_callable(obj, name):
"""
A version of callable() that doesn't execute properties when doing the test for callability.
"""
return callable(getattr(obj.__class__, name, None)) |
def count_threads(processes: list) -> int:
"""
Returns the number of threads under given processes.
:param processes: A list of processes to sum up all the individual threads
:return: The sum of all the threads for all the passed processes
"""
return sum(process.num_threads() for process in pro... |
def csv_root(docs_path, config):
"""Set the root path for the CSV samples to the tests/test_docs dir, and return the
dir.
"""
config['CSV_ROOT_DIR'] = docs_path
return config['CSV_ROOT_DIR'] |
def kgtk_lqstring(x):
"""Return True if 'x' is a KGTK language-qualified string literal.
"""
return isinstance(x, str) and x.startswith("'") |
def tabescape(unescaped):
""" Escape a string using the specific Dovecot tabescape
See: https://github.com/dovecot/core/blob/master/src/lib/strescape.c
"""
return unescaped.replace(b"\x01", b"\x011")\
.replace(b"\x00", b"\x010")\
.replace(b"\t", b"\x01t")\
... |
def _cache_run_stop(run_stop, run_stop_cache):
"""Cache a RunStop document
Parameters
----------
run_stop : dict
raw pymongo dictionary. This is expected to have
an entry `_id` with the ObjectId used by mongo.
run_stop_cache : dict
Dict[str, Document]
Returns
----... |
def args_to_argline(prm, filters=[], underscore_to_dash=True,
bool_argparse=True):
"""Naive transformation of dictionary into argument line
Parameters
----------
prm : dict
desired pair of key-val. Keys must corresponds to argument line options
filters : list, optional
... |
def special_division(n1, n2):
"""This function returns 0 in case of 0/0. If non-zero divided by zero case is found, an Exception is raised
"""
if n2 == 0:
if n1 == 0:
n2 = 1
else:
raise ValueError("Invalid Input: a non-zero value can't be divided by zero")
return ... |
def prepare_function_parameters(input_parameters, training_parameters):
"""Prepare function parameters using input and training parameters"""
function_parameters = {}
function_parameters = input_parameters.copy()
function_parameters.update(training_parameters)
return function_parameters |
def _make_divisible(channel_size, divisor=None, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.... |
def calc_focal_length(distance, width, pixels):
"""
Calculates the focal length based off the input
Parameters:
distance(int): distance from camera to the object
width(int): actual width of the object
pixels(int): width in pixels of the object
return: focal length of the ca... |
def num_digits(n: int) -> int:
"""
Find the number of digits in a number.
>>> num_digits(12345)
5
>>> num_digits(123)
3
>>> num_digits(0)
1
>>> num_digits(-1)
1
>>> num_digits(-123456)
6
"""
digits = 0
n = abs(n)
while True:
n = ... |
def convert_time(timestamp):
""" Convert time stamp to total hours, minutes and seconds """
hrs = int(timestamp // 3600)
if hrs < 10:
hrs = "{0:02d}".format(hrs)
mins = "{0:02d}".format((int(timestamp % 3600) // 60))
secs = "{0:02d}".format((int(timestamp % 3600) % 60))
return hrs, mins,... |
def is_number(s):
"""The function determines if a string is a number or a text. Returns True if it's a number. """
try:
int(s)
return True
except ValueError:
return False |
def stack_push_pop_order(push_ord, pop_ord):
"""
:param push_ord:push sequence
:param pop_ord: pop sequence
:return: bool
"""
stack = []
while pop_ord:
while not stack or stack[-1] != pop_ord[0]:
if not push_ord:
return False
stack.append(push_... |
def square_loss(a, b):
"""
Returns the value of L(a,b)=(1/2)*|a-b|^2
"""
return 0.5 * (a - b)**2 |
def new_files(new, old):
"""The paths of all new and updated files.
new and old are folder hashes representing the new state (i.e. the local copy)
and old state (i.e. what is currently on the web config.server)"""
return [f for (f, h) in new.items() if h != old.get(f)] |
def get_identifier(target_path):
"""
Get the basename of a specific structure
:param target_path: complete path of the structure
:return: identifier name
"""
import os
basename = os.path.basename(target_path)
target_identifier, extension = os.path.splitext(basename)
extension = exte... |
def code_point_order(cp):
"""Ordering function for code points."""
return cp if isinstance(cp, int) else cp[0] |
def map_label_with_marker(labels):
"""
Map label with marker
:param labels:
:return:
"""
markers = ('o', '*', '^', '<', '>', '8', 's', 'p', 'v', 'h', 'H', 'D', 'd', 'P', 'X',
'.', ',', '1', '2', '3', '4', '+', 'x', '|', '_', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
return dict(z... |
def strip_list(the_list, *args):
"""
Strip emtpy items from end of list.
Args:
the_list(list): the list.
*args: any number of values to strip from the end of the list.
"""
targets = ''
if args:
targets = args
while True:
if len(the_list) == 0:
b... |
def PrettyTime(remaining_time):
"""Creates a standard version for a given remaining time in seconds.
Created over using strftime because strftime seems to be
more suitable for a datetime object, rather than just a number of
seconds remaining.
Args:
remaining_time: The number of seconds remaining as a... |
def binary_tail(n: int) -> int:
""" The last 1 digit and the following 0s of a binary representation, as a number """
return ((n ^ (n - 1)) + 1) >> 1 |
def _calc_ta(eff, n_gre, tr_gre, tr_seq, ti1, ti2, a1, a2):
"""Calculate TA for MP2RAGE sequence."""
return (2.0 * ti1 - n_gre * tr_gre) / 2.0 |
def create_empty_node(code, depth):
"""Returns a sitemap node with no children"""
return {"code": code, "depth": depth, "children": []} |
def is_family(guests):
""" If all last names are the same"""
lasts = set()
for guest in guests:
lasts.add(guest.last)
return len(lasts) == 1 |
def verbal_memory(premises, question):
"""checks if the question can be answered by only knowing all premises. Iterates
through a given list of premises and checks if both elements from the question
are contained in each premise. If such a premise can be found, an answer can be
returned based on the... |
def alphabeticalToDecimal(alpha):
"""
Converts str to an int index. e.g.: 'a' -> 0, 'b' -> 1, 'c' -> 2, 440414 -> 'yama'
:param alpha: str
:return: int
"""
assert isinstance(alpha, str) and alpha
from string import ascii_lowercase
index = -1
steps = [(x, y) for x, y in enumerate(alph... |
def condense_into_single_line(text):
"""
Remove all the newlines from a block of text, compressing multiple
lines of HTML onto a single line. Used as a Jinja2 filter.
"""
lines = [line.lstrip() for line in text.split('\n')]
return ''.join(lines) |
def parse_requirements(fname='requirements.txt', with_version=True):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version spec... |
def mirror_search_terms(terms):
"""
Interchange the sidedness of a query
:param terms: List of strings matching (H|L)[0-9]+(l|r)?
<has/lacks><ringid>[<left/right>]
:return: The same terms with occurrences of 'left' and 'right' interchanged
"""
terms = [term.replace('l', 'Q').r... |
def uint2int64(value):
"""
Convert an unsigned 64 bits integer into a signed 64 bits integer.
>>> print(uint2int64(1))
1
>>> print(uint2int64(2**64 + 1)) # ignore bits larger than 64 bits
1
>>> print(uint2int64(18446744073709551615))
-1
>>> print(uint2int64(18446744073709551614))
... |
def extract_datapoint(program_output):
"""
Extract the 6 numbers from the program's output string.
"""
program_output = program_output.split()
ix = program_output.index("Found") + 1
pathsFound = float(program_output[ix])
ix = program_output.index("length:", ix) + 1
shortest = float(... |
def convert_mip_type_to_python_type(mip_type: str):
"""
Converts MIP's types to the relative python class.
The "MIP" type that this method is expecting is related to
the "sql_type" enumerations contained in the CDEsMetadata.
"""
type_mapping = {
"int": int,
"real": float,
... |
def last_non_space(s,i):
"""
:param s: string
:param i: index
:return: A pair of (the last character before s[i] that is not a space, its index)
"""
i -= 1
while i >= 0 and (s[i] == ' ' or s[i] == '\n'):
i -= 1
if i >= 0:
return (s[i],i)
else:
return (None,-1... |
def list_differences(list1, list2):
"""Returns two lists containing the unique elements of each input list"""
outlist1 = []
outlist2 = []
outlist1[:] = [elem for elem in list1 if elem not in list2]
outlist2[:] = [elem for elem in list2 if elem not in list1]
return outlist1, outlist2 |
def _listify(string_or_list):
"""
return a list if the input is a string, if not: returns the input as it was
Args:
string_or_list (str or any):
Returns:
A list if the input is a string, if not: returns the input as it was
Note:
- allows user to use a string as an argument... |
def canSum(numbers, target, memo=None):
"""
Given a array of positive whole numbers, finds if there is a subarray whose sum equals the given target
"""
if memo == None:
memo = dict()
if target in memo:
return memo[target]
if target == 0:
return True
if target < 0:
... |
def encode_output(value):
"""Takes value and converts to an integer byte string"""
return bytes([int(value)]) |
def subpaths_from_list(page_list):
"""
Build node pairs (edges) from a list of page hits
:param page_list: list of page hits
:return: list of all possible node pairs
"""
return [[page, page_list[i + 1]] for i, page in enumerate(page_list) if i < len(page_list) - 1] |
def FileFixPath(fileSpec):
""" Tweaks slashes """
return fileSpec.replace("\\", "/") |
def fromStr(valstr):
"""Try to parse as int, float or bool (and fallback to a string as last resort)
Returns: an int, bool, float, str or byte array (for strings of hex digits)
Args:
valstr (string): A user provided string
"""
if len(valstr) == 0: # Treat an emptystring as an empty bytes
... |
def call_function_from_varnames(fn_name, input_names, output_names):
"""
Build c++ code to call a function using the given paramerers
"""
lines = ''
outputs_avail = output_names is not None and len(output_names) != 0
inputs_avail = input_names is not None and len(input_names) != 0
li... |
def idx_to_words(ls, words):
"""Given a list generated from cluster_idx, return a list that contains
sub-list (the first element being the idx, and the second element being the
words corresponding to the idx)"""
output = []
for cluster in ls:
word = words[cluster[0]]
for idx in clus... |
def eliminateExistingImages(conn, candidate, detections, detectionsWithImages):
"""eliminateExistingImages.
Args:
conn:
candidate:
detections:
detectionsWithImages:
"""
imagesToRequest = []
for row in detections:
if '%d_%s_%s_%d' % (candidate, row.tdate, row.expname,... |
def check(value, condition, string = ""):
"""
Verify that the condition is true and return the value.
Useful for conditional assignments, eg:
xs = [x]*n_elements if not isinstance(x, (list, tuple)) else check(x, len(x)==n_elements)
:param value:
:param condition:
:param string:
:re... |
def fromiter(result, obj):
"""If `obj` is scalar, return first element of result list"""
try:
iter(obj)
return result
except TypeError:
return result[0] |
def fromStr(valstr):
"""try to parse as int, float or bool (and fallback to a string as last resort)
Returns: an int, bool, float, str or byte array (for strings of hex digits)
Args:
valstr (string): A user provided string
"""
if(len(valstr) == 0): # Treat an emptystring as an empty bytes
... |
def get_size_from_dict(data):
"""
parse the dict for a width and height
"""
for prefix, ismax in [('', False), ('max-', True)]:
size = data.get(prefix+'size', '').strip() or None
if size:
width, height = size.split('x')
else:
width = data.get(prefix+'width... |
def check_value(contours, length):
"""
Funcao que verifica a existencia de um valor de resistor encontrado.
Inverte o sentido de contours se a distancia do menor x ate o inicio
da imagem for maior que a distancia do maior x ao fim (o que implica
que o resistor esta invertido).
Entrada: contours - Val... |
def flipcoords(xcoord, ycoord, axis):
"""
Flip the coordinates over a specific axis, to a different quadrant
xcoord:
The x coordinate to flip
ycoord:
The y coordinate to flip
axis:
The axis to flip across. Could be 'x' or 'y'
"""
axis = axis.lower()
if axis == 'y':
... |
def reverse_words(input_str: str) -> str:
"""
Reverses words in a given string
>>> sentence = "I love Python"
>>> reverse_words(sentence) == " ".join(sentence.split()[::-1])
True
>>> reverse_words(sentence)
'Python love I'
"""
return " ".join(reversed(input_str.split(" "))) |
def mad_quote(value):
"""Add quotes to a string value."""
quoted = repr(value)
return quoted[1:] if quoted[0] == 'u' else quoted |
def s_to_r(x):
"""score to result"""
if x == 0: return 0.5
elif x > 0: return 1
return 0 |
def indeed_url(job, location, posting_offset):
"""Returns Indeed.com API url for job query
Args:
job (str): Title of job
location (str): Location of job
posting_offset (str): Index of first posting
Return (str): Indeed url
"""
url = (f"https://www.indeed.com/jobs"
... |
def make_signable(object):
"""
<Purpose>
Return the role metadata 'object' in 'SIGNABLE_SCHEMA' format.
'object' is added to the 'signed' key, and an empty list
initialized to the 'signatures' key. The caller adds signatures
to this second field.
Note: check_signable_object_format() should be c... |
def get_data_card_summary(summary: dict) -> str:
"""
Prepare data card summary
:param summary: data card summary response
:return: human readable string
"""
data_card_summary = ""
for key, value in summary.items():
if value.get("count") == 0:
data_card_summary += "{}: {},... |
def get_nth_bit(block, n, blocksize=4) -> int:
"""Returns n-th bit in a `blocksize` bit block counting from left,
bit indexes start at 1.
"""
return block >> (blocksize-n) & 0b1 |
def elliptic_paraboloid(x, y, x0, y0, a, b):
""" x,y -> f(x) in the shape of a 'bowl'
:param x - x value in the plane
:param y - y value in the plane
:param x0 - amount to shift the bottom of the bowl by in x
:param y0 - amount to shift the bottom of the bowl by in y
:param a - scale the bowl's ... |
def neighbour_coordinates(grid, point_coords):
"""Returns list of coordinates for neighbours of the given point,
within the bounds of the grid"""
grid_width = len(grid[0])
grid_height = len(grid)
point_row, point_col = point_coords
neighbour_coords = [
(point_row, point_col - 1),
... |
def get_sig(row,labels):
""" get the highest significance value """
i = row.index(max(row))
return(labels[i]) |
def calc_overlap(list1, list2):
"""
Calculate how much two lists overlap percentage wise
"""
if len(list1) > 0 and len(list2) > 0:
return \
(1.0 - len(set(list1).difference(set(list2))) / len(list1)) * 100, \
(1.0 - len(set(list2).difference(set(list1))) / len(list2)) * 1... |
def count_bits(number, n_bits):
""" Optimization function for creating all possible combinations"""
ret = 0
bit_pos = []
for i in range(0, n_bits):
if (1 << i) & number != 0:
ret += 1
bit_pos.append(i)
return (ret, bit_pos) |
def get_color(val, cat):
"""get color fpr category and val"""
if cat == 't':
if val > 0:
return 'r'
return 'b'
if val > 0:
return 'b'
return 'r' |
def phi2 (n, p=2):
""" Euler phi function. Second version.
We use the fact that phi has a formula in terms of the prime
decomposition of n. We assume n is a positive integer. The
default initial value for prime p is 2. Thus calls such as
phi2 (52961) will succeed, though given n is odd we could... |
def multiple_returns(sentence):
"""
Returns a tuple with the length of a string and its first
character
"""
s_len = len(sentence)
if s_len == 0:
f_char = None
else:
f_char = sentence[0]
return ((s_len, f_char)) |
def reverse(x):
"""
:type x: int
:rtype: int
"""
if (x<0):
x = abs(x)
neg = -1
else:
neg = 1
rev_x = int(str(x)[::-1])
if abs(rev_x) < 2147483648:
return rev_x*neg
else:
... |
def gnomad_link(variant_obj):
"""Compose link to gnomAD website."""
url_template = ("http://gnomad.broadinstitute.org/variant/{this[chromosome]}-"
"{this[position]}-{this[reference]}-{this[alternative]}")
return url_template.format(this=variant_obj) |
def clean_elements(orig_list):
"""Strip each element in list and return a new list.
[Params]
orig_list: Elements in original list is not clean, may have blanks or
newlines.
[Return]
clean_list: Elements in clean list is striped and clean.
[Example]
>>> clean_e... |
def call(func, *args, exception=Exception, ret=False, **kwargs):
"""one liner method that handles all errors in a single line which returns None, or Error instance depending on ret
value.
"""
try:
return func(*args, **kwargs)
except exception as e:
return (None, e)[ret] |
def un_camel(text):
""" Converts a CamelCase name into an under_score name.
>>> un_camel('CamelCase')
'camel_case'
>>> un_camel('getHTTPResponseCode')
'get_http_response_code'
"""
result = []
pos = 0
while pos < len(text):
if text[pos].isupper():
... |
def to_mb(val, update_interval=None):
"""Converts bytes to MB"""
tmp = 1
if update_interval:
tmp = 1/update_interval
return (val / 1024 / 1024) * tmp |
def titlesplit(src=u'', linelen=24):
"""Split a string on word boundaries to try and fit into 3 fixed lines."""
ret = [u'', u'', u'']
words = src.split()
wlen = len(words)
if wlen > 0:
line = 0
ret[line] = words.pop(0)
for word in words:
pos = len(ret[line])
... |
def merge_dicts(dictionaries):
"""Merges multiple separate dictionaries into a single dictionary.
Parameters
----------
dictionaries : An iterable container of Python dictionaries.
Returns
-------
merged : A single dictionary that represents the result of merging the all the
... |
def printNamespaces(params: dict = {}) -> str:
"""
Get string of list of namespaces
Args:
params: dict of params containing the namespaces
Returns:
str: string of namespaces
"""
namespaces = params["namespaces"]
res: str = ""
for uri in namespaces:
res += "@pre... |
def normalize(cubes, refvalues, relative):
"""Normalize a single cube to its reference value
If the value is a relative value, i.e., a percentual change, set
the 'relative' parameter to `True`.
"""
for cube, refvalue in zip(cubes, refvalues):
cube.data -= refvalue
if relative:
... |
def validate_date_format(date_format):
"""
This function validates the date format specified
and returns it as a result.
"""
if date_format not in ['timestamp', 'datetime', 'isoformat']:
raise ValueError("date_format must be 'timestamp', 'datetime', or 'isoformat'")
date_format =... |
def _find_name_from_blame(blame_line):
"""
Finds the name of the committer of code given a blame line from git
Args:
blame_line: A string from the git output of the blame for a file.
Returns:
The username as a string of the user to blame
"""
blame_info = blame_line[blame_line.fi... |
def generate_relating_lines(input_field, output_field, function_name, field_prefix=""):
"""
Generates lua lines that checks other fields related to input_field for feature engineering
:param input_field: original censys field
:param output_field: flattened version of censys field
:param function_na... |
def redirect_output(commandstr, filename):
"""Redirect output of command"""
return '{} > {}'.format(commandstr, filename) |
def generate_state(start, diff, state_size, state_name):
"""Generates a dict that contains a state_name and a list of values."""
values = []
increment = float(1) / state_size
for iteration in range(int(state_size)):
# Get a value between start + diff
sample = start + diff * increme... |
def did_you_mean(unknown_command, entry_points):
"""
Return the command with the name most similar to what the user typed. This
is used to suggest a correct command when the user types an illegal
command.
"""
from difflib import SequenceMatcher
similarity = lambda x: SequenceMatcher(None,... |
def INVERSE(n):
"""
Returns control codes to set or unset inverse video text.
Use this in a ``PRINT`` or ``SET`` command. Example:
``PRINT("normal",INVERSE(1),"inverse",INVERSE(0),"normal")``
Args:
- n - integer - inverse or not (0-1)
"""
return "".join((chr(20),chr(int(n)))) |
def count_bits(num):
"""Function to count the number of 1's in binary of given value for n"""
count = ''
return len([count for bit in bin(num)[2:] if int(bit) == 1]) |
def _EXAMPLE(s):
"""Helper to provide uniform appearance for examples in cmdline options"""
return ", e.g. %r" % s |
def count_reinforcements(n_territories):
"""How many territory-generated reinforcements would be awarded, with this many territories?
Note that your total number of reinforcements will also include armies from redeemed sets
and from any fully owned continents.
`n_territories` -- `int` -- number of ter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.