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 of pairs of elements that are clustered in second but not first partition
Example usage:
In [1]: a = 1
In [2]: b = 2
In [3]: c = 2
In [4]: d = 10
In [5]: fowlkes_mallows_index_pair_count(a, b, c)
Out[5]: 0.3333333333333333
"""
import math
if (a+b)*(a+c)!=0:
return float(a)/math.sqrt((a+b)*(a+c))
elif a+b==a+c==0:
return 1.0
else:
return 0.0 |
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:
with open(filename,"r") as instream:
for line in instream:
line = line.strip()
if (line != "" and not line.startswith("#")):
line = line.lower()
phrase = line.split()
firstWord = phrase[0]
phraseList = phraseIndex.get(firstWord)
if (phraseList == None):
phraseList = []
phraseIndex[firstWord] = phraseList
phraseList.append(phrase)
# Sort each list of phrases in decreasing order of phrase length
for phrases in phraseIndex.values():
phrases.sort(key=lambda p: len(p),reverse=True)
return phraseIndex |
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 contig: Single contig "chr1" to "chrY"
:return: Path to VCF
"""
contig = f".{contig}" if contig else ""
return f"gs://gnomad-public/release/{version}/vcf/{data_type}/gnomad.{data_type}.r{version}.sites{contig}.vcf.bgz" |
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(user_name) > 16:
return user_name[:17]
else:
return user_name |
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 len(temp_limits) != 2:
raise ValueError('Got unexpected limits `{}`'.format(limits))
if not (0 <= temp_limits[0] < temp_limits[1]):
raise ValueError('Got unexpected limits `{}`'.format(limits))
return temp_limits[0], temp_limits[1] |
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 += x.encode('UTF8')
return 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 ^ (:)
post = ('parentpost', x[1])
if x[2][0] == 'dagrangepre':
return _fixops(('dagrange', post, x[2][1]))
elif x[2][0] == 'rangepre':
return _fixops(('range', post, x[2][1]))
elif x[2][0] == 'rangeall':
return _fixops(('rangepost', post))
elif op == 'or':
# make number of arguments deterministic:
# x + y + z -> (or x y z) -> (or (list x y z))
return (op, _fixops(('list',) + x[1:]))
elif op == 'subscript' and x[1][0] == 'relation':
# x#y[z] ternary
return _fixops(('relsubscript', x[1][1], x[1][2], x[2]))
return (op,) + tuple(_fixops(y) for y in x[1:]) |
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 set(row[1:]):
if item and item != row[0]:
data.append(
{"title":item,"type":"AlternativeType"}
)
return data |
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.append(string)
print(output)
return output |
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:
return None
return (
entity_value[0]["values"]
if value_list
else entity_value[0]["values"][0]
)
return None |
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:
print(i, end = '')
if i > 1:
print(f' x ', end='')
else:
print(' =', end= ' ')
return f |
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 contact_name:
return f"{contact_name}({contact['email']})"
return contact["email"] |
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 digits read the same forward and
backward) in the given base, or ``False`` otherwise.
"""
# create a copy of n and number to hold its reversed value
n_copy = n
reverse_n = 0
# append each of the digits of n to reverse_n in reverse order
while n_copy != 0:
n_copy, digit = divmod(n_copy, base)
reverse_n = (reverse_n * base) + digit
# compare the original n to its reversed version
return n == reverse_n |
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 == -1:
break
bend = s.find("</b>", bbeg)
bolded.append(s[bbeg+3:bend]) #content bolded without tags
for n in range(len(bolded)):
bolded[n] = bolded[n].replace("<i>", "")
bolded[n] = bolded[n].replace("</i>", "")
return bolded |
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 percent(count): return (count / amount) * 100
for attribute in attributes_count:
freq_percent = percent(attributes_count[attribute])
freq_percent = round(freq_percent, 3)
attribute_percentages[attribute] = f'{freq_percent}%'
return attribute_percentages |
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" is a nested dict.)
"""
tmp = table.get(val1)
if tmp is None:
# table[val1] is missing; try table[val2]
tmp = table.get(val2)
if tmp is None:
return None
return tmp.get(val1)
else:
# table[val1] is there. But if table[val1][val2] is missing,
# we still gotta try it the other way.
tmp = tmp.get(val2)
if tmp is not None:
return tmp
# gotta try table[val2][val1] now.
tmp = table.get(val2)
if tmp is None:
return None
return tmp.get(val1) |
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{}_{}_r5000.png'.format(image_index, lighting_index) |
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 one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
UTC should be specified as GMT (see ASN1_TIME_print())
"""
from time import strptime
from calendar import timegm
months = (
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
)
time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
try:
month_number = months.index(cert_time[:3].title()) + 1
except ValueError:
raise ValueError('time data %r does not match '
'format "%%b%s"' % (cert_time, time_format))
else:
# found valid month
tt = strptime(cert_time[3:], time_format)
# return an integer, the previous mktime()-based implementation
# returned a float (fractional seconds are always zero here).
return timegm((tt[0], month_number) + tt[2:6]) |
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,
"spaceDefault": space_default,
},
"metadata": metadata,
"assets": {"audio": [], "video": [], "text": [], "image": assets},
"manifest": manifest,
}
return req |
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 = graph.scope_dict()
scopes = set()
for element in subgraph:
scopes.add(scope_dict[element])
# usual case: Root of scope tree is in subgraph,
# return None (toplevel scope)
if None in scopes:
return None
toplevel_candidates = set()
for scope in scopes:
# search the one whose parent is not in scopes
# that must be the top level one
current_scope = scope_dict[scope]
while current_scope and current_scope not in scopes:
current_scope = scope_dict[current_scope]
if current_scope is None:
toplevel_candidates.add(scope)
if len(toplevel_candidates) != 1:
raise TypeError("There are several locally top-level nodes. "
"Please check your subgraph and see to it "
"being connected.")
else:
return toplevel_candidates.pop() |
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 = []
for data_type in customer_data:
for item in customer_data[data_type]:
# Creates a first user data based on an email address.
user_data_operation = client.get_type('OfflineUserDataJobOperation')
user_data = user_data_operation.create
user_identifier = client.get_type('UserIdentifier')
if data_type == 'emails':
user_identifier.hashed_email = item['hashed_email']
elif data_type == 'phones':
user_identifier.hashed_phone_number = item['hashed_phone_number']
elif data_type == 'mobile_ids':
user_identifier.mobile_id = item['mobile_id']
elif data_type == 'user_ids':
user_identifier.third_party_user_id = item['third_party_user_id']
elif data_type == 'addresses':
user_identifier.address_info.hashed_first_name = item[
'hashed_first_name']
user_identifier.address_info.hashed_last_name = item['hashed_last_name']
user_identifier.address_info.country_code = item['country_code']
user_identifier.address_info.postal_code = item['postal_code']
user_data.user_identifiers.append(user_identifier)
customer_data_operations.append(user_data_operation)
return 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)
base32 = alphabet[i] + base32
if numbera < 0:
base32 = '-'+base32
return base32 or alphabet[0] |
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, return -1.
"""
first_nonzero = -1
for i, datapoint in enumerate(response):
if (
datapoint["open"] != 0
or datapoint["close"] != 0
or datapoint["high"] != 0
or datapoint["low"] != 0
):
first_nonzero = i
break # Find first nonzero point
return first_nonzero |
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
elif director != directors_list[-1] and director != directors_list[-2]:
film_directors += director + ", "
elif director == directors_list[-1]:
film_directors += " & " + director
else:
film_directors = "Unknown"
return film_directors |
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 of superstructure mass
:return:
"""
return norm_rot ** (1 - 0.2 * bhr) * 10 ** (.25 * bhr) |
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`: int
:param `bend`: Second range's end position
:type `bend`: int
:return: reciprocal overlap
:rtype: float
"""
ovl_start = max(astart, bstart)
ovl_end = min(aend, bend)
if ovl_start < ovl_end: # Otherwise, they're not overlapping
ovl_pct = float(ovl_end - ovl_start) / \
max(aend - astart, bend - bstart)
else:
ovl_pct = 0
return ovl_pct |
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)
Returns:
float: The percentage of a number
or
int: The percentage of a number (if resolution is zero or a negative number)
Example:
>>> percentage(10, 25)
40.0
>>> percentage(5, 19, 3)
26.316
"""
if whole == 0:
raise ZeroDivisionError
percent = 100 * float(part)/float(whole)
return round(percent, resolution) if resolution >=1 else int(percent) |
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() == match |
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_percentage:max_value }}
"""
value = int(value)
max_val = int(max_val)
if max_val == 0:
return '0'
return "{0:.0f}".format((value / max_val) * 100) |
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
broadcasted to b1's shape and not the opposite.
"""
if len(b1) < len(b2):
return False
b1 = b1[-len(b2) :]
return not any(v1 and not v2 for v1, v2 in zip(b1, b2)) |
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_quotes = True
break
if needs_quotes:
return '"' + s + '"'
return s |
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()) + sorted(num)
return sorted_words
# shorter solution
return sorted(words, key=lambda x: (x[0].isdigit(), str(x).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 directory.
"""
token = path.split('/')
filename = token[-1].split('.')[0]
return filename |
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",
"videostreams": "videostream",
"video": "videostream",
"videos": "videostream",
"books": "book"
}
if source_type is not None:
source_type = source_type.lower()
ret_val = normal.get(source_type, source_type)
return ret_val |
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 "Gold"
elif coverage > 80:
return "Orange"
elif coverage > 70:
return "OrangeRed"
else:
return "Red" |
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.com/en/32209-90024/apds02.html
Requires a list of integers with the values to be
calculated and the maximum value of weight variable.
"""
sum = 0
weight = 2
# Iterates through the list from right to left,
# +multiplying each value for it's weight. If
# +the weight reaches max_weight, then it is
# +restarted to 2.
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
# HP's Modulus 11 algorithm says that a 10
# +result is invalid and a 11 result is equal
# +to 0. So, both values are returned as 0.
if mod > 9:
return 0
else:
return mod |
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 put and output of this method
in: "+123.4567[8]g "
out: "+123.45678 g "
"""
if "[" in raw_data:
raw_data = raw_data.replace("[", "").replace("]", " ")
return raw_data |
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' ~ '12'
if (date[0] != '1' and date[0] != '0'):
return False
if date[0] == '1':
if (date[1] != '0') and (date[1] != '1') and (date[1] != '2'):
return False
# dates are between 0 ~ 31
if (date[2] != '0') and (date[2] != '1') \
and (date[2] != '2') and (date[2] != '3'):
return False
return True |
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 of
Ken Thompson's Regular Expression Search Algorithm:
https://swtch.com/~rsc/regexp/dfa0.c.txt (MIT License)
See also http://swtch.com/~rsc/regexp/ and
Thompson, Ken. Regular Expression Search Algorithm,
Communications of the ACM 11(6) (June 1968), pp. 419-422.
"""
nalt = 0
natom = 0
dst = []
paren = []
if not len(regex) > 0: # pragma: no cover
raise ValueError("Regular expression is empty.")
for _ in regex:
if _ == "(":
if natom > 1:
natom = natom - 1
dst.append(".")
paren.append((nalt, natom))
nalt = 0
natom = 0
elif _ == "|":
if natom == 0: # pragma: no cover
raise ValueError("Regex is missing an expression before |.")
natom -= 1
while natom > 0:
dst.append(".")
natom -= 1
nalt += 1
elif _ == ")":
if not paren:
raise ValueError("Regex parentheses do not match.")
if natom == 0: # pragma: no cover
raise ValueError("Regex parentheses are missing an expression.")
natom -= 1
while natom > 0:
dst.append(".")
natom -= 1
while nalt > 0:
dst.append("|")
nalt -= 1
(nalt, natom) = paren.pop()
natom += 1
elif _ in ("*", "+", "?"):
if natom == 0: # pragma: no cover
raise ValueError("Regex operator %s requires an expression." % _)
dst.append(_)
else:
if natom > 1:
natom -= 1
dst.append(".")
dst.append(_)
natom += 1
natom -= 1
while natom > 0:
dst.append(".")
natom -= 1
while nalt > 0:
dst.append("|" * nalt)
nalt -= 1
return "".join(dst) |
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()
return winning_prob |
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': 'g',
'g': 'c',
't': 'a',
'r': 'y',
'y': 'r',
'k': 'm',
'm': 'k',
's': 's', # palindromic
'w': 'w', # palindromic
'n': 'n', # all;
"h": "d", # threes
"v": "b",
"d": "h",
"b": "v"
}
tseq = [compdict[i] for i in seq] # new list
tseq.reverse()
return "".join(tseq) |
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: color depth of the GIF.
palette: a list of rgb colors of the format [r1, g1, b1, r2, g2, b2, ...].
The number of colors must be greater than or equal to 2**n where n is
the color depth. Redundant colors will be discarded.
"""
try:
palette = bytearray(palette)
except:
raise ValueError('Cannot convert palette to bytearray.')
valid_length = 3 * (1 << color_depth)
if len(palette) < valid_length:
raise ValueError('Invalid palette length.')
if len(palette) > valid_length:
palette = palette[:valid_length]
return palette |
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])
except KeyError:
return False
return res |
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 of their parent ingredient
or in percentage of the total product.
Args:
ingredients (list): List of dicts corresponding to the ingredients
Returns:
float: Maximum value of the sum of all ingredients percentages.
"""
maximum_sum = 0
maximum_percentage = 100
for ingredient in ingredients:
if 'percent' in ingredient:
maximum_percentage = float(ingredient['percent'])
maximum_sum += maximum_percentage
return maximum_sum |
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.endswith("'>"), 'illegal input'
cls_name = cls_name[:-len("'>")]
return cls_name |
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()
elif len(run) == 1:
run = list()
if len(run) > 1:
runs.append(run)
return runs |
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] = sorting[i], sorting[store_index]
store_index += 1
sorting[right], sorting[store_index] = sorting[store_index], sorting[right]
return store_index |
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 dicts_key_sets[0] & dicts_key_sets[1]]) |
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.
"""
clean_text = []
curr_line = ''
# Remove any newlines that follow two lines of whitespace consecutively
# Also remove whitespace at start and end of text
while text:
if not curr_line:
# Find the first line that is not whitespace and add it
curr_line = text.pop(0)
while not curr_line.strip() and text:
curr_line = text.pop(0)
if curr_line.strip():
clean_text.append(curr_line)
else:
# Filter the rest of the lines
curr_line = text.pop(0)
if text:
if curr_line.strip():
clean_text.append(curr_line)
else:
# If the current line is whitespace then make sure there is
# no more than one consecutive line of whitespace following
if not text[0].strip():
if len(text) > 1 and text[1].strip():
clean_text.append(curr_line)
else:
clean_text.append(curr_line)
else:
# Add the final line if it is not whitespace
if curr_line.strip():
clean_text.append(curr_line)
# Now filter each individual line for extraneous whitespace
cleaner_text = []
clean_line = ''
for line in clean_text:
clean_line = ' '.join(line.split())
if not clean_line.strip():
clean_line += '\n'
cleaner_text.append(clean_line)
return cleaner_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_':
res['from'] = replace__from___to__from(d['from_'])
else:
res[key] = replace__from___to__from(d[key])
return res |
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
specified in the input retain their default values"""
defaults = {
"speed_pause": 5,
"climb_tol": 10,
"close_contact_tol": 35,
"side_contact_tol": 80,
"follow_frames": 10,
"follow_tol": 5,
"huddle_forward": 15,
"huddle_speed": 2,
"nose_likelihood": 0.85,
"fps": 24,
}
for k, v in hparams.items():
defaults[k] = v
return defaults |
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.