content stringlengths 42 6.51k |
|---|
def fowlkes_mallows_index_pair_counts(a, b, c):
"""
Compute the Fowlkes-Mallows index from pair counts; helper function.
Arguments:
a: number of pairs of elements that are clustered in both partitions
b: number of pairs of elements that are clustered in first but not second partition
c: number ... |
def readPhraseIndexFromFiles (filenames):
"""Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines
and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of."""
phraseIndex = dict()
for filename in filenames:
... |
def release_vcf_path(data_type: str, version: str, contig: str) -> str:
"""
Publically released VCF. Provide specific contig, i.e. "chr20", to retrieve contig
specific VCF
:param data_type: One of "exomes" or "genomes"
:param version: One of the release versions of gnomAD on GRCh37
:param conti... |
def auto_downsample_ratio(h, w):
"""
Automatically find a downsample ratio so that the largest side of the resolution be 512px.
"""
return min(512 / max(h, w), 1) |
def int_to_bytes(value: int) -> bytes:
"""Convert a given number to its representation in bytes.
Args:
value (int):
The value to convert.
Returns:
bytes:
The representation of the given number in bytes.
"""
return bytes(str(value), "utf-8") |
def align_username(user_name: str):
""" Align the username regarding to template """
if len(user_name) <= 5:
return str(user_name) + "@github.com"
elif len(user_name) <= 7:
return str(user_name) + "@github"
elif len(user_name) <= 10:
return str(user_name) + "@git"
elif len(u... |
def sql_tuple(L):
""" Make the given list into a SQL-formatted tuple """
result = ""
result += "("
result += ",".join(L)
result += ")"
return result |
def step(x):
"""Step function with threhold 0.5. Can take scalars and matrices."""
return 1 * (x >= 0.5) |
def probability(alpha, beta, t):
"""Probability function P"""
if t == 0:
return alpha / (alpha + beta)
return (beta + t - 1) / (alpha + beta + t) * probability(alpha, beta, t - 1) |
def _verify_limits(limits):
"""
Helper function to verify that the row/column limits are sensible.
Parameters
----------
limits : None|tuple|list
Returns
-------
None|tuple
"""
if limits is None:
return limits
temp_limits = [int(entry) for entry in limits]
if ... |
def ansible_stdout_to_str(ansible_stdout):
"""
@Summary: The stdout of Ansible host is essentially a list of unicode characters. This function converts it to a string.
@param ansible_stdout: stdout of Ansible
@return: Return a string
"""
result = ""
for x in ansible_stdout:
result... |
def lerp(x, x0, x1, y0, y1):
"""Linear interpolation of value y given min and max y values (y0 and y1),
min and max x values (x0 and x1), and x value.
"""
return y0 + (y1 - y0)*((x - x0)/(x1 - x0)) |
def _fixops(x):
"""Rewrite raw parsed tree to resolve ambiguous syntax which cannot be
handled well by our simple top-down parser"""
if not isinstance(x, tuple):
return x
op = x[0]
if op == 'parent':
# x^:y means (x^) : y, not x ^ (:y)
# x^: means (x^) :, not x ^ (:)
... |
def check_url(url):
"""
Checks whether the supplied URL is valid
:return: Boolean - True if valid
"""
return 'products.json' in url |
def decode_bin(num, n):
"""
Decode an integer into a pair of length-n binary tuples.
"""
ret = []
for _ in range(2*n):
ret.append(num%2)
num = num // 2
return tuple(ret[:n]), tuple(ret[n:]) |
def extract_titles(row):
"""Creates a list of dictionaries with the titles data and alternatives if exists
Args:
list: row[1:5].values
Return:
list of dictionaries with title and title type
"""
data = [
{"title":row[0], "type": "OriginalTitle"}
]
for item in... |
def combine_three_lists(list1, list2, list3):
"""The obvious solution to combining a known number of lists"""
output = []
for i in range(0, len(list1)):
for j in range(0, len(list2)):
for k in range(0, len(list3)):
string = list1[i] + list2[j] + list3[k]
print(string)
output.appe... |
def get_group_data_value(data_list, field, value_list=False):
"""to find the field value in group api call
return whole list of values if value_list is True
"""
for entity in data_list:
if entity["name"] == field:
entity_value = entity["values"]
if not entity_value:
... |
def factorial(n=1, show=False):
"""
=> Calcula factorial de um numero.
:param n: O numero a ser calculado
:param show: (opcional) Mostrar ou nao a conta
:return: O valor do factorial de um numero n.
"""
f = 1
for i in range(n, 0, -1):
f = f * i
if show:
... |
def valid_port(port):
"""
Returns whether the specified string is a valid port,
including port 0 (random port).
"""
try:
return 0 <= int(port) <= 65535
except:
return False |
def split_digits_at_end(seq : str):
"""
Splits strings like "A0201" into ("A", "0201")
"""
prefix = seq
suffix = ""
while prefix and prefix[-1].isdigit():
suffix = prefix[-1] + suffix
prefix = prefix[:-1]
return prefix, suffix |
def get_contact_name(contact: dict) -> str:
"""Determine contact name from available first name, last naame, and email."""
contact_name = ""
if contact["first_name"]:
contact_name = f"{contact['first_name']} "
if contact["last_name"]:
contact_name += f"{contact['last_name']} "
if co... |
def percent_to_float(s: str) -> float:
"""Parse a percentage string into a float."""
s = s.strip()
if s.endswith('%'):
s = s[:-1]
return float(s) / 100.0 |
def gen_reads(seq, k):
"""
gen_reads generates list of k bp "reads" sliding across transcripts (k-mers).
"""
k2 = k - 1
reads = [""] * (len(seq) - k2)
for i in range(len(seq) - k2):
reads[i] = seq[i : i + k]
return reads |
def comremcon4float(n: str) -> float:
""""Substitui a virgula por ponto e converte em float"""
return float(str(n).replace(',', '.')) |
def is_palindrome(n: int, base: int = 10) -> bool:
"""Checks if a non-negative integer is a palindrome in a given base.
Args:
n: A non-negative integer value.
base: The base in which ``n`` will be represented. Must be at least 2.
Returns:
``True`` if ``n`` is a palindrome (its digi... |
def gen_namespace(dbname, collname):
""" Generate namespace.
"""
return '%s.%s' % (dbname, collname) |
def find_bolded(s):
"""Returns a list with all bolded(signified by <b> and </b>) subtrings in given string
Also purges of italics
"""
assert s.count("<p>") == 1, "if you see this i messed up my extract method"
bbeg = -1
bend = -1
bolded = []
while True:
bbeg = s.find("<b>", bbeg+1)
if bbeg ==... |
def sign3w(x):
""" Decode signed 3-byte integer from unsigned int """
if x >= 8388608: # 2**23
x ^= 16777215 # 2**24 -1
x += 1
x *=-1
return x |
def calculate_percentages(amount: int, attributes_count: dict) -> dict:
""" Based on the calculated counts, creates a frequency table this time with the
percentage a trait occurs - rounded to three decimal places.
"""
attribute_percentages = dict()
# lambda func to calculate percentage
def pe... |
def _get_table_symmetric(table, val1, val2):
"""
Gets an operator from a table according to the given types. This
gives the illusion of a symmetric matrix, e.g. if tbl[a][b] doesn't exist,
tbl[b][a] is automatically tried. That means you only have to fill out
half of the given table. (The "table"... |
def Track(artist, title, **kwargs):
"""
Returns a dictionary Track
"""
d = {"artist": artist, "title": title}
for k in kwargs:
d[k] = kwargs[k]
return d |
def generate_trace(dx=0):
"""Generates parabolas offset along x by dx."""
xarr = range(-10, 10)
yarr = [(x+dx)**2 for x in xarr]
return {'x': xarr, 'y': yarr} |
def delete_deplicates(tweets):
"""
INPUT list of tweets like pos_train or neg_train
"""
tweets_no_duplicate = list(dict.fromkeys(tweets))
return tweets_no_duplicate |
def image_name(image_index, lighting_index):
""" Returns the name of the dtu image. image_index goes from 0-48
and lighting_index goes from 0 to 6 """
image_index += 1
if image_index < 10:
return 'rect_00{}_{}_r5000.png'.format(image_index, lighting_index)
else:
return 'rect_0{}_{}_r... |
def cert_time_to_seconds(cert_time):
"""Return the time in seconds since the Epoch, given the timestring
representing the "notBefore" or "notAfter" date from a certificate
in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
"notBefore" or "notAfter" dates must use UTC (RFC 5280).
Month is on... |
def remove_invalid_attributes(obj, data):
""" remove the attributes of a dictionary that do not belong in an object """
_data = {}
for name, value in data.items():
if hasattr(obj, name):
_data[name] = value
return _data |
def month_length(month: int, leap_year: bool = False):
"""
Calculate length of given month
"""
if month == 1:
# handle February
return 28 + int(leap_year)
elif month in [3, 5, 8, 10]:
return 30
else:
return 31 |
def wrapIngestRequest(
metadata: dict,
assets: list,
manifest: dict,
space_default: str,
action_default: str = "upsert",
) -> dict:
"""Creates an ingest request to be sent to the LTS MPS ingest API"""
req = {
"globalSettings": {
"actionDefault": action_default,
... |
def outermost_scope_from_subgraph(graph, subgraph, scope_dict=None):
"""
Returns the outermost scope of a subgraph.
If the subgraph is not connected, there might be several
scopes that are locally outermost. In this case, it
throws an Exception.
"""
if scope_dict is None:
scope_dict... |
def build_offline_user_data_job_operations(client, customer_data):
"""Builds the schema of user data as defined in the API.
Args:
client: The Google Ads client.
customer_data: Processed customer data to be uploaded.
Returns:
A list containing the operations.
"""
customer_data_operations = []
... |
def b32e(numbera):
#encode number. I struggled to find the right alphabet that frhd used for their encoding
"""Encode number in freerider base32."""
alphabet = '0123456789abcdefghijklmnopqrstuv' #DO NOT CHANGE
number = abs(numbera)
base32 = ''
while number:
number, i = divmod(number, 32... |
def find_first_nonzero(response):
"""
Parameters
----------
response : iterable
Every item is a dictionary which must contain at least keys:
'open','close', 'high', 'low'.
Returns
-------
int
First index where the entry is not zero. If none found,... |
def lt(x, y):
"""Creates an SMTLIB less than statement formatted string
Parameters
----------
x, y: float
First and second numerical arguments to include in the expression
"""
return "(< " + x + " " + y + ")" |
def formatsDirectorsField(directors_list):
""" Formats Directors field for Web app template. """
film_directors=""
if directors_list != None:
for director in directors_list:
if len(directors_list) == 1 or director == directors_list[-2]:
film_directors = director
... |
def calculate_corrected_normalised_rotation(norm_rot, bhr):
"""
Corrected normalised rotation according to Millen (2015)
Correction is for shear force
Normalisation is against pseudo uplift angle
:param norm_rot: Normalised rotation angle
:param bhr: Ratio of Foundation width to Effective height... |
def reciprocal_overlap(astart, aend, bstart, bend):
"""
Calculates reciprocal overlap of two ranges
:param `astart`: First range's start position
:type `astart`: int
:param `aend`: First range's end position
:type `aend`: int
:param `bstart`: Second range's start position
:type `bstart`... |
def identity_adjacency(info_dict):
"""
Each node points to itself.
"""
refs = []
acc_list = info_dict["accuracy"]
for i in range(0, len(acc_list)):
refs.append([i])
return refs |
def fqcn(cls):
"""Return the fully qualified class name of a class."""
return '%s.%s' % (cls.__module__, cls.__name__) |
def hex_colour(color: int) -> str:
"""Converts an integer representation of a colour to the RGB hex value."""
return f"#{color:0>6X}" |
def is_data_word(word):
"""Is data word bit set?"""
return (word & 0x1) == 0 |
def percentage(part, whole, resolution=2):
"""Calculates the percentage of a number, given a part and a whole
ie: 10 is what percent of 25 --> 40%
Args:
part (float): The part of a number
whole (float): The whole of a number
resolution (int): Number of decimal places (Default is 2)
... |
def lower_equals(string, match):
"""
This function returns if ``string`` lowercase is equal to ``match``.
Args:
string(str): The string to check.
match(str): The match to check against.
Returns:
bool: Whether ``string`` lowercase is equal to ``match``.
"""
return string.lower... |
def invert_bits(n: int) -> int:
"""
>>> bin(0b1100101100101 ^ invert_bits(0b1100101100101))
'0b1111111111111'
"""
return n ^ ((1 << n.bit_length()) - 1) |
def get_percentage(value, max_val):
"""Returns value in dictionary from the key_id.
Used when you want to get a value from a dictionary key using a variable
:param dictionary: dict
:param key_id: string
:return: value in the dictionary[key_id]
How to use:
{{ myval|get_perce... |
def encompasses_broadcastable(b1, b2):
"""
Parameters
----------
b1
The broadcastable attribute of a tensor type.
b2
The broadcastable attribute of a tensor type.
Returns
-------
bool
True if the broadcastable patterns b1 and b2 are such that b2 is
broad... |
def pg_capital(s : str) -> str:
"""
If string contains a capital letter, wrap it in double quotes
returns: string
"""
if '"' in s:
return s
needs_quotes = False
for c in str(s):
if ord(c) < ord('a') or ord(c) > ord('z'):
if not c.isdigit():
needs_... |
def sort_words_case_insensitively(words):
"""Sort the provided word list ignoring case,
one twist: numbers have to appear after letters!"""
char = [c for c in words if not c[0].isnumeric()]
num = [n for n in words if n[0].isnumeric()]
sorted_words = sorted(char, key = lambda word: word.lower()) +... |
def x_within_y_percent_of_z(x_to_compare, y_percent, z_base):
""" Return true if the input values are within a given y percent range. """
z_lower = (100 - y_percent) * z_base / 100.0
z_upper = (100 + y_percent) * z_base / 100.0
return bool(z_lower <= x_to_compare <= z_upper) |
def retreive_filename(path):
"""
Truncates absolute file directory and returns file name.
Parameters
----------
path : 1-dimensional string containing absolute directory of a file,
in /<dir>/<filename>.<foramt> format.
Returns
-------
filename : <filename> portion of the given file... |
def source_type_normalize(source_type):
"""
Make it easier to ignore small inconsistencies in these key word arguments.
>>> source_type_normalize("journals")
'journal'
>>> source_type_normalize("Journal")
'journal'
"""
ret_val = None
normal = {"journals": "journal",
"... |
def calc_coverage_color(coverage: float) -> str:
"""
Return color based on coverage result.
"""
if (coverage < 0) or (coverage > 100):
raise ValueError("Invalid coverage input should be between 0 - 100 %")
if coverage == 100:
return "Green"
elif coverage > 90:
return "Go... |
def mod11(list, max_weight=7):
"""Implements Modulus 11 check digit algorithm.
It's a variation of the HP's Modulus 11 algorithm.
Requires the sequence to be calculated in a list of
integers.
The HP's Modulus 11 algorithm can be accessed through
the following link:
http://docs.hp.c... |
def get_string_pattern(lst, pattern):
"""
Returns the string of the list based on the pattern
:param pattern:
:return:
"""
for i in lst:
if pattern in i:
return i
return False |
def prop(dic, prop_name):
""" Gets name property and set-ifies it. """
if prop_name in dic:
prop = dic[prop_name]
if isinstance(prop, str):
return set([prop])
else:
return set([i.lower() for i in prop])
return set() |
def _remove_calibration_note(raw_data):
""" adjusts the raw data string if a calibration note is present
According to the manual, this should not happen in SBI mode of the
scale. This is included to prevent hiccups but probably not handled
the right way....
The data with a calibration node on in p... |
def ra_in_decimal_hours(ra):
"""ra_in_decimal_hours.
Args:
ra:
"""
return(ra/15.0) |
def check_date(date):
"""check if date string has correct format.
Args:
date as a string mmddyyyy
Returns:
a boolean indicating if valid (True) or not (False)
"""
if len(date) != 8:
return False
if not date.isdigit():
return False
# months are between '01' ~... |
def _regex_to_postfix(regex):
"""
Convert infix regular expression into postfix w/ implicit concatenation.
Parameters
----------
regex : str
Regular expression -- accepts only ( | ) * + ?
Returns
-------
str
Notes
-----
Translated from Russ Cox's C implementation o... |
def sort_by_value(D,reverse=False):
"""
There are many ways to sort a dictionary by value and return lists/tuples/etc.
This is recommended for python 3 on StackOverflow.
"""
return [(k,D[k]) for k in sorted(D,key=D.get,reverse=reverse)] |
def prior_knolwedge_normalized(intuition, name="CREDIT"):
"""
function of prior knowledge for normalized price
:param intuition: input intuition var
:return: expected prob.
"""
if name == "CREDIT":
winning_prob = intuition
else:
print("# data mame error!")
exit()
... |
def rc_expanded(seq):
"""
get the reverse complemnt of seq
this one works for the expanded alphabet;
R=[AG], Y=[CT], K=[GT], M=[AC], S=[GC], W=[AT], and the four-fold
[ACT] = h, [ACG] = v, [AGT] = d, [CGT] = b
degenerate character N=[ATCG]
"""
compdict = {'a': 't',
'c': '... |
def global_color_table(color_depth, palette):
"""
Return a valid global color table.
The global color table of a GIF image is a 1-d bytearray of the form
[r1, g1, b1, r2, g2, b2, ...] with length equals to 2**n where n is
the color depth of the image.
----------
Parameters
color_depth:... |
def X_y_split(data: list):
""" Split data in X and y for ML models. """
X = [row[0] for row in data]
y = [row[1] for row in data]
return X, y |
def compare_dictionaries(d1, d2):
"""
Compare two dictionaries
:param d1:
:param d2:
:return: (bool) True if equal, False if different
"""
res = True
try:
for key in d1:
res &= (d1[key] == d2[key])
for key in d2:
res &= (d1[key] == d2[key])
exc... |
def customer_name(toml_data):
"""Return the customer name from the toml data file"""
return toml_data["customer"]["customer_name"] |
def time500mtovavg(minutes,secs):
""" Calculates velocity from pace in minutes, seconds)
"""
seconds = 60.*minutes+secs
vavg = 500./seconds
return vavg |
def empty_data(data):
"""Check to see if data is an empty list or None."""
if data is None:
return True
elif type(data) == list:
if len(data) == 0:
return True
return False |
def maximum_percentage_sum(ingredients):
"""
Computes the maximum sum of ingredients percentages for ingredients given in decreasing percentage order, even if
some ingredients does not have a percentage.
Notes:
This is useful to estimate if subingredients percentages are defined in percentage o... |
def concat(l):
"""concat(l) -> list
Concats a list of lists into a list.
Example:
>>> concat([[1, 2], [3]])
[1, 2, 3]
"""
res = []
for k in l:
res.extend(k)
return res |
def regenerated_pyconfig_h_in(file_paths):
"""Check if pyconfig.h.in has been regenerated."""
if 'configure.ac' in file_paths:
return "yes" if 'pyconfig.h.in' in file_paths else "no"
else:
return "not needed" |
def type_to_str(type_object) -> str:
"""
convert a type object to class path in str format
:param type_object: type
:return: class path
"""
cls_name = str(type_object)
assert cls_name.startswith("<class '"), 'illegal input'
cls_name = cls_name[len("<class '"):]
assert cls_name.endswi... |
def ensurelist(v):
"""Coerce NoneType to empty list, wrap non-list in list."""
if isinstance(v, list):
return v
elif v is None:
return []
else:
raise ValueError("Unexpected form of list: {}".format(v)) |
def listrun(pattern, values):
"""Find runs in a pattern containing elements from given values"""
runs = list()
run = list()
for i in pattern:
if i in values:
run.append(i)
else:
if len(run) > 1:
runs.append(run)
run = list()
... |
def vec_psd_dim(dim):
"""Compute vectorized dimension of dim x dim matrix."""
return int(dim * (dim + 1) / 2) |
def show_math_result(a, b, show_lower=True):
"""perform math operation, by default addition"""
op_display = "plus" if show_lower else "PLUS"
print("{} {} {} = {}".format(a, op_display, b, a + b))
return a + b |
def lomuto_partition(sorting: list, left: int, right: int) -> int:
"""
Example:
>>> lomuto_partition([1,5,7,6], 0, 3)
2
"""
pivot = sorting[right]
store_index = left
for i in range(left, right):
if sorting[i] < pivot:
sorting[store_index], sorting[i] = sorti... |
def intersection_by_key(s1, s2, key):
"""Returns the intersection of two sets, but the comparison is done by the function key applied to each element"""
dicts = [dict([(key(elem), elem) for elem in s]) for s in (s1, s2)]
dicts_key_sets = [set(d.keys()) for d in dicts]
return set([dicts[0][k] for k in di... |
def remove_whitespace(text):
"""Remove unnecessary whitespace while keeping logical structure
Keyword arguments:
text -- text to remove whitespace from (list)
Retain paragraph structure but remove other whitespace,
such as between words on a line and at the start and end of the text.... |
def is_leap(year: int) -> bool:
"""Returns boolean if year is a leap year.
Args:
year (int): year
Returns:
bool: is leap year
"""
if year % 4: # every 4 years
return False
if not year % 100 and year % 400:
return False
return True |
def replace__from___to__from(d: dict):
"""Replace recursive keys in the object from_ to from."""
res = {}
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [replace__from___to__from(v) for v in d]
for key, value in d.items():
if key == 'from_':
... |
def get_hparameters(hparams: dict = {}) -> dict:
"""Returns the most frequent behaviour in a window of window_size frames
Parameters:
- hparams (dict): dictionary containing hyperparameters to overwrite
Returns:
- defaults (dict): dictionary with overwritten parameters. Those not
s... |
def sec_to_timestring(seconds):
"""
Converts seconds to time string (MM:SS).
"""
# Prevent numbers less than zero.
if seconds < 0:
seconds = 0
minutes = int(seconds/60)
seconds -= (minutes*60)
return str(minutes).zfill(2) + ":" + str(seconds).zfill(2) |
def baseref_to_github(base_url, baseref):
""" Convert the url to github """
if baseref is None:
return None
replacement_url = "https://github.com/corda/docs-site/tree/staging/content/en"
return baseref.replace(base_url, replacement_url).replace(".html", ".md") |
def title_case_to_initials(text):
"""Converts "Column Title" to CT
"""
return ''.join([word[0].upper() for word in text.split()]) |
def makePath(path):
"""
Make path element of URI from a supplied list of segments.
The leadfing '/' is not included.
"""
return "/".join(path) |
def _decode_boolean(data):
"""Decode boolean"""
return data == "1" |
def remove_empty_fields(obj):
"""
Removes empty fields from NetBox objects.
This ensures NetBox objects do not return invalid None values in fields.
:param obj: A NetBox formatted object
:type obj: dict
"""
return {k: v for k, v in obj.items() if v is not None} |
def cross(A, B):
"""
Cross product of elements in A and elements in B.
:param A:
:param B:
:return:
"""
return [s + t for s in A for t in B] |
def valid_ap(ap, aps_per_axis):
"""
Helper to validate ap
"""
ap_x, ap_y = ap
return (ap_x in aps_per_axis and ap_y in aps_per_axis) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.