content stringlengths 42 6.51k |
|---|
def lmParamToPoint(a, c):
""" Return the coordinates of a landmark from its line parameters.
Wall landmarks are characterized by the point corresponding to the
intersection of the wall line and its perpendicular passing through the
origin (0, 0). The wall line is characterized by a vector (a, c) such as
its equation is given by y = ax + c.
"""
xp = float(-c*a / (1+a**2))
yp = float(c / (1+a**2))
return [xp, yp] |
def _extension(platform):
"""Get the init extension for a platform."""
if platform == 'windows':
return '.ps1'
return '.bash' |
def create_sequence_labels(labels):
""" Transforms input 'labels' into BIO format
"""
ret = []
ret.extend('B-{}'.format(label) for label in sorted(labels) if label != 'None')
ret.extend('I-{}'.format(label) for label in sorted(labels) if label != 'None')
ret.append('O')
return ret |
def calc_transport(shifts_amount: int, daily_transport: float) -> float:
"""Returns total monthly transportation refund.
Args:
shifts_amount (int): Total of number of monthly shifts.
daily_transport (float): Refund amount per shift.
Returns:
float: Total monthly transportation refund.
Raises:
None
"""
return round(daily_transport * shifts_amount, 2) |
def extend_flight_distance(distance: float) -> float:
"""Add factor to shortest flight distance to account for indirect flight paths
Following https://www.icao.int/environmental-protection/CarbonOffset/Documents/Methodology%20ICAO%20Carbon%20Calculator_v11-2018.pdf
section 4.2 we add a correction factor to represent deviations from the shortest
path flown between points due to stacking, traffic and weather-driven corrections.
Args:
distance: Shortest distance - geodesic or Great Circle - between points in km
Returns: Distance with additional correction factor
"""
if distance < 550:
return distance + 50
elif distance < 5500:
return distance + 100
return distance + 125 |
def flatten_tree(test, enumerator, exp):
"""test is function(exp) >> bool.
mapper is function(expression) >> list of subexpressions.
returns [subexpression, ...].
"""
return sum((flatten_tree(test, enumerator, subx) for subx in enumerator(exp)), []) if test(exp) else [exp] |
def interval_cover(I):
"""Minimum interval cover
:param I: list of closed intervals
:returns: minimum list of points covering all intervals
:complexity: O(n log n)
"""
S = []
for start, end in sorted(I, key=lambda v: (v[1], v[0])):
if not S or S[-1] < start:
S.append(end)
return S |
def get_conjunctive_grams(text1, text2, token_dict):
"""
Generate conjunctive 2-grams for continuous spans
:param text1:
:param text2:
:param token_dict:
:return:
"""
n1 = len(text1)
n2 = len(text2)
grams = set()
if n1 > 0 and n2 > 0:
grams.add(f'Conjunctive-Word-{token_dict[text1[0]].lemma.lower()}+{token_dict[text2[0]].lemma.lower()}')
grams.add(f'Conjunctive-Pos-{token_dict[text1[0]].pos.lower()}+{token_dict[text2[0]].pos.lower()}')
# if n1 > 1 and n2 > 0:
# grams.add(token_dict[text1[-1]].lemma.lower() + ' ' + token_dict[text2[0]].lemma.lower())
return grams |
def get_amount_episodes(episodes: str) -> int:
"""
Takes in the animethemes syntax of episodes and returns it's amoutn
"""
a = 0
for ep in episodes.split(', '):
if '-' in ep:
index = ep.index('-')
a += int(ep[:index])-int(ep[index+1:])
else:
a += int(ep)
return a |
def _create_certificate_subject(external_tls_config):
"""
Map parameters to custom resource subject
"""
organization = external_tls_config.get("organization")
organization_unit = external_tls_config.get("organizational_unit")
country = external_tls_config.get("country")
location = external_tls_config.get("location")
state = external_tls_config.get("state")
subject = {
"organizations": [organization],
"countries": [country],
"localities": [location],
"provinces": [state],
"organizationalUnits": [organization_unit]
}
return subject |
def update_device_state(data, d_dict):
"""Helper-function for _device_state_updater()."""
_cooling_state = False
_dhw_state = False
_heating_state = False
result = "idle"
if "binary_sensors" in d_dict:
for item, state in d_dict["binary_sensors"].items():
if item == "dhw_state" and state:
result = "dhw-heating"
_dhw_state = True
if "heating_state" in data and data["heating_state"]:
result = "heating"
_heating_state = True
if _heating_state and _dhw_state:
result = "dhw and heating"
if "cooling_state" in data and data["cooling_state"]:
result = "cooling"
_cooling_state = True
if _cooling_state and _dhw_state:
result = "dhw and cooling"
return result |
def contains(sequence, value):
"""A recursive version of the 'in' operator.
"""
for i in sequence:
if i == value or (hasattr(i, '__iter__') and contains(i, value)):
return True
return False |
def current_function_2(t):
"""
This function returns the value of a square wave current at a given simulation
time t. 0 <= j <= 1.
"""
t1 = t*1e9%2.0
if t1<1.0:
return 0
else:
return 1.0 |
def arrays_to_strings(measure_json):
"""To facilitate readability via newlines, we express some JSON
strings as arrays, but store them as strings.
Returns the json with such fields converted to strings.
"""
converted = {}
fields_to_convert = [
'title', 'description', 'why_it_matters', 'numerator_columns',
'numerator_where', 'denominator_columns', 'denominator_where']
for k, v in measure_json.items():
if k in fields_to_convert and isinstance(v, list):
converted[k] = ' '.join(v)
else:
converted[k] = v
return converted |
def bsd_checksum(data):
"""Implementation of the bsd 16-bit checksum algorithm.
"""
if not isinstance(data, bytearray):
data = bytearray(data) # pragma: no cover
r = 0
for ch in data:
if r & 1:
r |= 0x10000
r = ((r >> 1) + ch) & 0xffff
return r |
def play(start, rounds):
"""
>>> play((0, 3, 6), 4)
0
>>> play((0, 3, 6), 5)
3
>>> play((0, 3, 6), 6)
3
>>> play((0, 3, 6), 10)
0
>>> play((0, 3, 6), 2020)
436
"""
numbers = {}
round = len(start)
for i, j in enumerate(start[:-1]):
numbers[j] = i + 1
last = start[-1]
while round < rounds:
index = numbers.get(last)
numbers[last] = round
last = 0 if index is None else round - index
round += 1
return last |
def GetExpectationPath(expectation, file_name=''):
"""Get the path to a test file in the given test run and expectation.
Args:
expectation: name of the expectation.
file_name: name of the file.
Returns:
the path as a string relative to the bucket.
"""
return 'expectations/%s/%s' % (expectation, file_name) |
def compute_intersection(line1, line2):
"""
compute intersection of line1 and line2. If line1 and line2 don't have intersection, we return (-1, -1).
:params: line1: (x1, y1, x2, y2)
:params: line2: (x1, y1, x2, y2)
:return: ptx, pty: the intersection (ptx, pty)
"""
x1, y1, x2, y2 = line1[0], line1[1], line1[2], line1[3]
x3, y3, x4, y4 = line2[0], line2[1], line2[2], line2[3]
d = ((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4))
if d == 0:
return -1, -1
tmp1 = x1 * y2 - y1 * x2
tmp2 = x3 * y4 - y3 * x4
ptx = (tmp1 * (x3 - x4) - (x1 - x2) * tmp2) / d;
pty = (tmp1 * (y3 - y4) - (y1 - y2) * tmp2) / d;
return ptx, pty |
def search_dico(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
mn = 0
mx = len(a) - 1
i = 0
while mx - mn > 1:
i = (mn + mx) // 2
if a[i] == x:
return i
elif x > a[i]:
mn = i
else:
mx = i
if a[mn] == x:
return mn
elif a[mx] == x:
return mx
else:
return None |
def get_exclusive_key(s3_index_row):
"""
returns the exclusive key needed to make further queries of the s3Index dynamo table.
Args:
s3_index_row(dict): dynamo table row for the s3Index
Returns:
(dict): exclusive key
"""
exclusive = {"ingest-job-hash": s3_index_row["ingest-job-hash"],
"ingest-job-range": s3_index_row["ingest-job-range"]}
return exclusive |
def bubble_sort(data):
"""Bubble Sort implementation"""
n = len(data)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if data[j] > data[j+1]:
data[j], data[j + 1] = data[j + 1], data[j]
swapped = True
if not swapped:
break
return data |
def ends_in_6(year):
"""
Does the year end in '6'?
"""
return year % 10 == 6 |
def drop_homonyms(data):
"""Drop some CFs which have the correct name, but not the correct CAS number, to avoid duplicate matches based on the name alone."""
NOT_USED = {
("fenpropathrin", 64257847),
("mecoprop", 7085190),
# Slightly cheating here for fenoxycarb - ecoinvent doesn't specify
# the correct CAS number, so we take the higher value
("fenoxycarb", 72490018),
}
for ds in data:
ds["exchanges"] = [
cf
for cf in ds["exchanges"]
if (cf["name"].lower(), cf["CAS number"]) not in NOT_USED
]
return data |
def apply_threshold(votes, threshold):
"""Sets vote counts to 0 if threshold is not met."""
if threshold is not None:
v = []
combined_votes = sum(votes)
min_votes = combined_votes * threshold
for vote in votes:
if vote < min_votes:
v.append(0)
else:
v.append(vote)
return v
else:
return votes |
def get_string(string):
"""
Takes in either a str or an object that has the str inside of an index ["#text"]. This helps parsing of almost
all different records.
:param string:
:return:
"""
if isinstance(string, str):
return string
return string["#text"] |
def bfs_connected_component(graph, start):
"""Visits all the nodes of a search space (connected component) using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
Returns:
explored (list): List of the explored nodes
"""
# list to keep track of all visited nodes
explored = [ ]
# keep track of nodes to be checked
queue = [start]
# keep looping until there are nodes still to be checked
while queue:
# pop shallowest node (first node) from queue
node = queue.pop(0)
if node not in explored:
# add node to list of checked nodes
explored.append(node)
# get neighbours if node is present, otherwise default to empty
# list
neighbours = graph.get(node, [ ])
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
return explored |
def my_join(x):
"""
:param x: -> the list desired to join
:return:
"""
return ''.join(x) |
def plusOne(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits=[str(i) for i in digits]
number="".join(digits)
number=int(number)
number+=1
number=str(number)
digits=[int(i) for i in number]
return digits |
def A000120(n: int) -> int:
"""1's-counting sequence.
number of 1's in binary expansion of n (or the binary weight of
n).
"""
return f"{n:b}".count("1") |
def get_phrase(context, words, span):
"""Reimplementation of bidaf_no_answer.squad.utils.get_phrase."""
start, stop = span
char_idx = 0
char_start, char_stop = None, None
for word_idx, word in enumerate(words):
char_idx = context.find(word, char_idx)
if word_idx == start:
char_start = char_idx
char_idx += len(word)
if word_idx == stop - 1:
char_stop = char_idx
return context[char_start:char_stop] |
def pdf_field_type_str(field):
"""Gets a human readable string from a PDF field code, like '/Btn'"""
if not isinstance(field, tuple) or len(field) < 4 or not isinstance(field[4], str):
return ''
else:
if field[4] == '/Sig':
return 'Signature'
elif field[4] == '/Btn':
return 'Checkbox'
elif field[4] == '/Tx':
return 'Text'
else:
return ':skull-crossbones:' |
def system(_printer, ast):
"""Prints the instance system initialization."""
process_names_str = ' < '.join(map(lambda proc_block: ', '.join(proc_block), ast["processNames"]))
return f'system {process_names_str};' |
def prep_difflines(content):
""" difflib takes input in this "readlines" compatible format """
return [ x+"\n" for x in content.split("\n") ] |
def grow(arr: list) -> int:
"""This function returns the result of multiplying the values."""
if len(arr) is None:
return 0
res = 1
for item in arr:
res *= item
return res |
def determine_page_content_type(content):
""" Attempt to determine if content is ReST or HTML """
tags = ['<p>', '<ul>', '<h1>', '<h2>', '<h3>', '<pre>', '<br', '<table>']
content_type = 'restructuredtext'
content = content.lower()
for t in tags:
if t in content:
content_type = 'html'
return content_type |
def make_ordinal(n: int) -> str:
"""
LICENSE NOTICE
I found this function on https://stackoverflow.com/a/50992575/2065017.
As a result, it is licensed under the CC BY-SA 4.0 license.
I have added type hints in the function definition.
Convert an integer into its ordinal representation::
make_ordinal(0) => '0th'
make_ordinal(3) => '3rd'
make_ordinal(122) => '122nd'
make_ordinal(213) => '213th'
"""
if 11 <= (n % 100) <= 13:
suffix = "th"
else:
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
return str(n) + suffix |
def d_bernoulli_kullback_leibler_dq(p: float, q: float) -> float:
"""
Compute the partial derivative of the Kullback-Leibler divergence of two Bernoulli distributions.
With respect to the parameter q of the second distribution.
:param p: parameter of the first Bernoulli distribution
:param q: parameter of the second Bernoulli distribution
:return: dKL/dq(B(p) || B(q))
"""
return (1 - p) / (1 - q) - p/q |
def add_two_numbers(first_number, second_number):
""" Add two numbers together. """
total = first_number + second_number
return total |
def step_input(CurrTime, Amp, StartTime = 0.0):
"""
Function to create a step input
Arguments:
CurrTime : The current timestep (will also take an array)
Amp : The size of the step input
StartTime : The time that the step should occur
Returns:
The step input for the CurrTime timestep or an array representing the
step input over the times pass
"""
return Amp * (CurrTime > StartTime) |
def ListToDict(args):
"""
change a list to dict
:param args: a list
:type args: list
:return: dict
.. code-block:: python
>>> a = [1,2,3,4]
>>> print(ListToDict(a))
{1: {2: {3: 4}}}
"""
if not isinstance(args, list):
return None
if len(args) == 1:
return args[0]
else:
return {
args[0]:ListToDict(args[1:])
} |
def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if key not in js:
return default
if js[key] is None and not take_none:
return default
return js[key] |
def v2s(val):
"""Turn possibly missing value into string"""
return val if val is not None else '-' |
def parse_version(value: str) -> int:
"""Support version `0.0.0_0017`."""
try:
if "_" in value:
_, value = value.split("_")
return int(value)
except:
return 0 |
def parse_breaks(s):
"""
parser for text with line breaks but that should not be parsed into p tags
:s: the input string to parse
:returns: the string with \n\n replace with <br/> and \n with space
NOTE: to parse text into p tags simply parse as markdown.
"""
return s.strip().replace("\n\n", "\n<br/>\n").replace("\n", " ") |
def get_obj_name_from_title(tableTitle):
"""
Returns the String pertaining to the type of the table. Used only
when editing a default dashboard table since they do not have types saved,
it gets it from the hard-coded title.
"""
if tableTitle == "Recent Emails":
return "Email"
elif tableTitle == "Recent Indicators":
return "Indicator"
elif tableTitle == "Recent Samples":
return "Sample"
elif tableTitle == "Top Backdoors":
return "Backdoor"
elif tableTitle == "Top Campaigns":
return "Campaign"
elif tableTitle == "Counts":
return "Count" |
def mapping_inverse(mapping):
"""Inverses mapping if it is bijective or raises error if not."""
if len(set(mapping.keys())) != len(set(mapping.values())):
raise ValueError(f"Mapping {mapping} cannot be reversed, it is not bijective.")
return dict(zip(mapping.values(), mapping.keys())) |
def first_or_default(iterable, default=False, pred=None):
"""
Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_or_default([a, b, c], x) --> a or b or c or x
# first_or_default([a, b], x, f) --> a if f(a) else b if f(b) else x
iterable_internal = iter(filter(pred, iterable))
return next(iterable_internal, default) |
def format_percentile(q):
"""Format percentile as a string."""
if 0 <= q <= 1.0:
q = 100.0 * q
return '{:3.1f}%'.format(q) |
def getInt(target, pos):
"""
Get an integer from a list/whatever.
Returns the integer if in-range, False if out of range.
"""
try:
result=int(target[pos])
return result
except IndexError:
return False
except ValueError:
return False |
def is_a_b(variant, variant_dict):
"""
Is the value of the variant either 'A' or 'B'? Filters out junk data
:param variant:
:return: True or False
"""
return any([variant == x for x in list(variant_dict.values())]) |
def get_stolen_bits(num, bits_required):
"""
Returns binary representation of given number in given length
:param num: Number to be converted
:param bits_required: Length of Number of bits required
:return: Binary string of given number
"""
binary = "{0:b}".format(int(num))
prefix = bits_required - len(binary)
prefix_str = ""
if prefix > 0:
prefix_str = "0" * prefix
return prefix_str + binary |
def is_number(value):
"""Indicates whether a given value is a number; a decimal, float, or integer.
:param value: The value to be tested.
:rtype: bool
"""
try:
value + 1
except TypeError:
return False
else:
return True |
def port_int(p):
"""Pass through a port number (as a number or a string) provided it is valid and in range, otherwise raise an exception"""
try:
port=int(p)
except:
raise ValueError("Invalid port number")
if port>=0 and port<=65535:
return port
else:
raise ValueError("Port number out of range") |
def escape_split(string_to_split: str, seperator: str = ".") -> tuple:
"""Splits a string based on the provided seperator.
escape_split supports escaping the seperator by prepending a backslash.
:param string_to_split: String to split
:param seperator: Seperator to use for splitting (Default: ".")
"""
i, res, buffer = 0, [], ""
while True:
j, e = string_to_split.find(seperator, i), 0
if j < 0:
return tuple(res + [buffer + string_to_split[i:]])
while j - e and string_to_split[j - e - 1] == "\\":
e += 1
d = e // 2
if e != d * 2:
buffer += string_to_split[i : j - d - 1] + string_to_split[j]
i = j + 1
continue
res.append(buffer + string_to_split[i : j - d])
i = j + len(seperator)
buffer = "" |
def is_device_memory(obj):
"""All HSA dGPU memory object is recognized as an instance with the
attribute "__hsa_memory__" defined and its value evaluated to True.
All HSA memory object should also define an attribute named
"device_pointer" which value is an int(or long) object carrying the pointer
value of the device memory address. This is not tested in this method.
"""
return getattr(obj, '__hsa_memory__', False) |
def compare_data(data1, data2, ignore=None, expected=True):
"""
todo: Update Documentation
:param data1:
:type data1:
:param data2:
:type data2:
:param ignore:
:type ignore:
:param expected:
:type expected:
:return:
:rtype:
"""
print(data1)
print(data2)
return expected |
def clean_args(args: list, kwargs: dict, exclusive: bool = False) -> dict:
"""
Removes keys to prevent errors.
"""
kargs = list(kwargs.keys())
if exclusive:
for arg in kargs:
if arg not in args:
del kwargs[arg]
else:
for arg in args:
try:
del kwargs[arg]
except KeyError:
pass
return kwargs |
def is_sqlitedb_url(db_url):
"""Returns True if the url refers to a sqlite database"""
return db_url.startswith("sqlite:///") |
def is_a(x, n=None):
"""
Check whether a list is a non-decreasing parking function.
If a size `n` is specified, checks if a list is a non-decreasing
parking function of size `n`.
TESTS::
sage: from sage.combinat.non_decreasing_parking_function import is_a
sage: is_a([1,1,2])
True
sage: is_a([1,1,4])
False
sage: is_a([1,1,3], 3)
True
"""
if not isinstance(x, (list, tuple)):
return False
prev = 1
for i, elt in enumerate(x):
if prev > elt or elt > i + 1:
return False
prev = elt
if n is not None and n != len(x):
return False
return True |
def dashify(s):
"""Called from substitutions
"""
clean = ''.join([c for c in s.lower() if c == ' ' or 'a' <= c <= 'z'])
return clean.replace(' ', '-').strip('-').replace('--', '-') |
def _item_by_predicate(list_obj, predicate):
"""
Iterate through list_obj and return the object that matches the predicate.
|list_obj| list
|predicate| f(x) -> bool
|return| object otherwise None if not found
"""
for x in list_obj:
if predicate(x):
return x
return None |
def first_word_matcher(subject, general):
""" Determine whether first word in `subject` == `general`.
Args:
subject ::: (str) thread subject
general ::: (str) general name
"""
return True if subject.split('-')[0].strip() == general else False |
def check_valid(input_password):
"""
Checks to see if the input password is valid for this training program
Invalid in this case means you don't want to train on them
Additionaly grammar checks may be run later to futher exclude passwords#
This just features that will likely be universal rejections
Returns
TRUE if the password is valid
FALSE if invalid
"""
# Don't accept blank passwords for training.
if len(input_password) == 0:
return False
# Remove tabs from the training data
# This is important since when the grammar is saved to disk tabs are used
# as seperators. There certainly are other approaches but putting this
# placeholder here for now since tabs are unlikely to be used in passwords
if "\t" in input_password:
return False
# Below are other values that cause problems that we are going to remove.
# These values include things like LineFeed LF
#Invalid characters at the begining of the ASCII table
for invalid_hex in range (0x0,0x20):
if chr(invalid_hex) in input_password:
return False
# UTF-8 Line Seperator
if u"\u2028" in input_password:
return False
return True |
def padded_bin(k, n):
"""
Converts a number to binary form, left-padded to a given length.
This function might not work correctly with negative integers.
Parameters
----------
k : integer
The number to be converted to binary.
n : integer
The target length of the binary string. The returned string
will be at least of this length.
Returns
-------
s : string
The binary string, which is at least `n` characters long.
"""
s = bin(k)
return '0' * (n - len(bin(k)) + 2) + s[2:] |
def make_complete_graph(num_nodes):
"""
Returns a complete graph given n num_nodes
n*(n-1)/2 edges will be generated
"""
_digraph = {}
# creates a set with all nodes
_full_set = set(range(num_nodes))
# simply remove own node for each node set
for node in range(num_nodes):
_digraph[node] = _full_set.difference(set([node]))
return _digraph |
def stringify_parsed_email(parsed):
"""
Convert a parsed email tuple into a single email string
"""
if len(parsed) == 2:
return f"{parsed[0]} <{parsed[1]}>"
return parsed[0] |
def xy_to_cell_id(x: int, y: int, Ngrid: int):
""" Convert a position (x,y) to the grid cell
index (where upper left hand column is indexed
0 & indexing is done rowwise)
"""
return x + y*Ngrid |
def get_repository_and_tag_from_image_uri(image_uri):
"""
Return the name of the repository holding the image
:param image_uri: URI of the image
:return: <str> repository name
"""
repository_uri, tag = image_uri.split(":")
_, repository_name = repository_uri.split("/")
return repository_name, tag |
def prepare_dict(obj):
"""
Removes any keys from a dictionary that are only specific to our use in the module. FortiAnalyzer will reject
requests with these empty/None keys in it.
:param obj: Dictionary object to be processed.
:type obj: dict
:return: Processed dictionary.
:rtype: dict
"""
list_of_elems = ["mode", "adom", "host", "username", "password"]
if isinstance(obj, dict):
obj = dict((key, prepare_dict(value)) for (key, value) in obj.items() if key not in list_of_elems)
return obj |
def take_transcript_id_without_version(full_id):
"""Returns transcript id without version and everything which is after version separating comma.
Example:
Input: ESNT_0001.4
Output: ESNT_0001
Input: ESNT_0002.2.some_annotation
Output: ESNT_0002
"""
return full_id.split('.')[0] |
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
if day1 < day2:
return True
else:
return False
else:
return False
else:
return False |
def clean_line(line):
""" Decode bytestrings and string newlines. """
return line.decode().strip("\n") |
def find_median_depth(mask_area, num_median, histg):
"""
Iterate through all histogram bins and stop at the median value. This is the
median depth of the mask.
"""
median_counter = 0
centre_depth = 0.0
for x in range(0, len(histg)):
median_counter += histg[x][0]
if median_counter >= num_median:
# Half of histogram is iterated through,
# Therefore this bin contains the median
centre_depth = x / 50
break
return centre_depth |
def extended_gcd(a, b):
"""
We know:
ax + by = gcd(a, b)
This function returns gcd(a,b), x , y
"""
if a == 0:
return b, 0, 1
gcd, x_, y_ = extended_gcd(b % a, a)
x = y_ - (b // a) * x_
y = x_
return gcd, x, y |
def multv(A, V):
""" produit matrice/vecteur: A * V """
a00, a10, a01, a11 = A
b0, b1 = V
return [a00 * b0 + a10 * b1,
a01 * b0 + a11 * b1] |
def correct_geometry(v):
"""
If needed, identifies expanded angles with a corresponding one in the range (-180,180)
Parameters
----------
v : list
torsion or rotamer angle list that needs to be corrected to the range (-180,180)
Returns
-------
list
corrected list of rotamer angles
"""
for v_comp in v:
if v_comp > 180.0:
v_comp = v_comp - 360.0
if v_comp < -180.0:
v_comp = v_comp + 360.0
return v |
def chunks(l, n):
"""Yield successive n-sized chunks from l"""
result = []
for i in range(0, len(l), n):
# yield l[i:i+n]
result.append(l[i:i + n])
return result |
def _hg19_to_GRCh37(chrom):
"""Cheap and ugly conversion from hg19 to GRCh37 contigs.
"""
if chrom == "chrM":
return "MT"
else:
return chrom.replace("chr", "") |
def vertical_products(grid, n):
"""Get the products of N vertical items each."""
result = []
for x in range(0, len(grid[0])):
for i in range(0, len(grid) - (n - 1)):
product = 1
for j in range(n):
product *= grid[i + j][x]
result.append(product)
return result |
def remove_elements(list_iter, list_check):
"""
Removes any elements which can disrupt link from working
:param list_iter: original list to be checked and where elements will be removed from
:param list_check: list containing elements to remove
:return: cleaned version of list_iter
"""
# list to store any values which should be removed from list_check
remove = []
# iterates through list_iter and removes any elements in list_check from list_iter
for num, i in enumerate(list_iter):
for j in list_check:
if i in j:
remove.append(num)
for i in sorted(remove, reverse=True):
del list_iter[i]
# returns cleaned version of list_iter
return list_iter |
def makeCycleSortable(cycle):
"""Lets cycle number be easily sorted lexicographically
>>> makeCycleSortable(2)
'003'
>>> makeCycleSortable(43)
'044'
>>> makeCycleSortable(152)
'153'
"""
cycle += 1
if cycle < 10:
return '00' + str(cycle)
elif cycle < 100:
return '0' + str(cycle)
else:
return str(cycle) |
def pad_sequences(sequences, pad_token, tail=True):
"""
Pads the sentences, so that all the sentences in a batch have the same length
"""
max_length = max(len(x) for x in sequences)
sequence_padded, sequence_length = [], []
for seq in sequences:
seq = list(seq)
if tail:
seq_ = seq[:max_length] + [pad_token] * \
max(max_length - len(seq), 0)
else:
seq_ = [pad_token] * \
max(max_length - len(seq), 0) + seq[:max_length]
sequence_padded += [seq_]
sequence_length += [min(len(seq), max_length)]
return sequence_padded, sequence_length |
def base32_decode(base32_value: str) -> int:
"""
Convert base32 string to integer
Example 'A' -> 10
"""
return int(base32_value, 32) |
def cp_or_mdj(docket_number):
""" Is `docket_number` a CP docket, or a MDJ docket? """
if len(docket_number) == 21:
return "CP"
if len(docket_number) == 24:
return "MDJ"
return None |
def get_one_arg(args, argv):
"""
Hacked together parser to get just one value
:param args: Name of arg to retrieve. If multiple specified, return first found.
:type args: ```Tuple[str]```
:param argv: Argument list
:type argv: ```List[str]```
:return: First matching arg value
:rtype: ```Optional[str]```
"""
assert isinstance(args, (tuple, list)), "Expected tuple|list got {!r}".format(
type(args)
)
next_is_sym = None
for e in argv:
for eng in args:
if e.startswith(eng):
if e == eng:
next_is_sym = eng
else:
return e[len(eng) + 1 :]
elif next_is_sym == eng:
return e |
def create_headers(conf_payload):
"""Create header.
:param conf_payload: config payload
:return: headers
"""
partition_id = conf_payload["data-partition-id"]
app_key = conf_payload["AppKey"]
headers = {
'Content-type': 'application/json',
'data-partition-id': partition_id,
'AppKey': app_key
}
return headers |
def _format_warning(message, category, filename, lineno, line=None):
"""Simple format for warnings issued by ProPlot. See the
`internal warning call signature \
<https://docs.python.org/3/library/warnings.html#warnings.showwarning>`__
and the `default warning source code \
<https://github.com/python/cpython/blob/master/Lib/warnings.py>`__."""
return f'{filename}:{lineno}: ProPlotWarning: {message}\n' |
def get_identifiers(reporter, reportee, **kw):
"""Return "identifiers" part. For now, the `envelope_to` field always
corresponds to the `reporter`, i.e. mail receiver and the `header_from` to
the `reportee`, i.e. purported mail sender. """
return {
"envelope_to": reporter,
"header_from": reportee
} |
def debias_randomized_response_bool(release, p):
"""Adjust the mean release to remove bias."""
assert 0 <= release <= 1
assert 0 <= p <= 1
return (1 - p - 2 * release) / (2 * (p - 1)) |
def get_counts_and_averages(ID_and_ratings_tuple):
"""Given a tuple (movieID, ratings_iterable)
returns (movieID, (ratings_count, ratings_avg))
"""
nratings = len(ID_and_ratings_tuple[1])
return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings) |
def hand_total(hand):
"""Helper function to calculate the total points of a blackjack hand.
"""
total = 0
# Count the number of aces and deal with how to apply them at the end.
aces = 0
for card in hand:
if card in ['J', 'Q', 'K']:
total += 10
elif card == 'A':
aces += 1
else:
# Convert number cards (e.g. '7') to ints
total += int(card)
# At this point, total is the sum of this hand's cards *not counting aces*.
# Add aces, counting them as 1 for now. This is the smallest total we can make from this hand
total += aces
# "Upgrade" aces from 1 to 11 as long as it helps us get closer to 21
# without busting
while total + 10 <= 21 and aces > 0:
# Upgrade an ace from 1 to 11
total += 10
aces -= 1
return total |
def get_case_id_from_file(file_name: str, remove_modality: bool = True) -> str:
"""
Cut of ".nii.gz" from file name
Args:
file_name (str): name of file with .nii.gz ending
remove_modality (bool): remove the modality string from the filename
Returns:
str: name of file without ending
"""
file_name = file_name.split('.')[0]
if remove_modality:
file_name = file_name[:-5]
return file_name |
def flatten_json(payload_dict):
"""
Flatten a multi-hierarchy Python dictionary to a single-hierachy dict.
Parameters:
payload_dict (dict): The Python multi-hierarchy dictionary which is to be flatten to one hierarchy.
Returns:
out (dict): The flatten Python dict as a single-hierarchy Python dict.
"""
out = {}
def flatten(x, name=""):
# If the Nested key-value
# pair is of dict type
if type(x) is dict:
for a in x:
flatten(x[a], name + a + "/")
# If the Nested key-value
# pair is of list type
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + "/")
i += 1
else:
out[name[:-1]] = x
flatten(payload_dict)
return out |
def get_mapping_list(unit_mappings_list):
"""
Filters out name columns from unit_mappings.csv file and returns list of mappings suitable for BQ
:param unit_mappings_list:
:return: formatted list suitable for insert in BQ:
(measurement_concept_id, unit_concept_id, set_unit_concept_id, transform_value_as_number)
"""
pair_exprs = []
for route_mapping_dict in unit_mappings_list:
pair_expr = '({measurement_concept_id}, {unit_concept_id}, {set_unit_concept_id}, ' \
'\"{transform_value_as_number}\")'.format(**route_mapping_dict)
pair_exprs.append(pair_expr)
formatted_mapping_list = ', '.join(pair_exprs)
return formatted_mapping_list |
def segment_point_distance_sq(x1, y1, x2, y2, px, py):
""" Return the distance from segment (x1, y1, x2, y2) to point (px, py) """
pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
if pd2 == 0:
# Points are coincident.
x = x1
y = y2
else:
# parameter of closest point on the line
u = ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1)) / pd2
if u < 0: # off the end
x = x1
y = y1
elif u > 1.0: # off the end
x = x2
y = y2
else: # interpolate
x = x1 + u * (x2 - x1)
y = y1 + u * (y2 - y1)
return (x - px) * (x - px) + (y - py) * (y - py) |
def add_space(a):
"""For a given unicode string @notation
Add some spaces according to the ICONCLASS rules as commonly used in DE
See tests for examples
"""
if len(a) < 3:
return a
if a[1:3] == "(+":
tip = a[0]
start = 1
elif (a[2:4] == "(+") or (a[2] == "(" and a[3] != "+"):
tip = a[:2]
start = 2
else:
tip = "%s %s" % (a[:2], a[2])
if len(a) == 3:
return tip.strip()
if len(a) == 4 and a[2] == a[3]:
return "%s %s" % (a[:2], a[2:4])
start = 3
if a[2] == a[3]:
start = 4
tip = "%s %s" % (a[:2], a[2:4])
inbracket, inkey, parts, s = False, False, [tip], ""
for idx, x in enumerate(a[start:]):
if x == " " and not inbracket:
continue
if x == "(":
inbracket = True
parts.append(s)
s = ""
s += x
if x == "+" and inbracket:
inkey = True
inbracket = False
if x == ")":
inbracket = False
inkey = False
parts.append(s)
s = ""
if len(s) >= 2 and not inbracket:
parts.append(s)
s = ""
parts.append(s)
tmp = []
for idx, x in enumerate(parts):
if not x or x == " ":
continue
if idx < (len(parts) - 1) and parts[idx + 1] == ")":
tmp.append(x)
else:
tmp.append("%s " % x if x != "(+" else x)
return "".join(tmp).strip() |
def _remove_default_boundary(
lower_trim_indices, upper_trim_indices,
has_default_lower_boundary, has_default_upper_boundary,
batch_rank, dims, n_dims):
"""Creates trim indices that correspond to an inner grid with Robin BC."""
# For a sequence of `dims` we shift lower trims by one upward, if that lower
# bound is default; and upper trims by one downward, if that upper bound is
# default. For each dimension we compute paddings
# `[[lower_i, upper_i] for i in range(n_dims)]`
# with `lower_i` and `upper_i` being 0 or 1 to indicate whether the lower
# or upper indices were updated.
# For example, _remove_default_boundary(
# [0, 1], [-1, 0],
# [True, False], [False, True], 0, (1, ), 2)
# returns a tuple ([0, 1], [-1, -1], [[0, 0], [0, 1]]) so that only the
# upper index of the second dimension was changed.
trimmed_lower_indices = []
trimmed_upper_indices = []
paddings = batch_rank * [[0, 0]]
for dim in range(n_dims):
update_lower = has_default_lower_boundary[dim] and dim in dims
update_upper = has_default_upper_boundary[dim] and dim in dims
trim_lower = 1 if update_lower else 0
trimmed_lower_indices.append(lower_trim_indices[dim] + trim_lower)
trim_upper = 1 if update_upper else 0
trimmed_upper_indices.append(upper_trim_indices[dim] - trim_upper)
paddings.append([trim_lower, trim_upper])
return trimmed_lower_indices, trimmed_upper_indices, paddings |
def load_present_tracks(track_list):
"""Extract the ID's from the playlist object it is passed. Also returns a dictionary of ID's and song titles."""
present_track_id = set()
lookup_id = {}
for i in track_list:
present_track_id.add(i['track']['id'])
lookup_id[i['track']['id']] = i['track']['name']
return present_track_id, lookup_id |
def factorial(num):
"""Finds the factorial of the input integer.
Args:
num (int): The integer to find the factorial of.
Returns:
fact (int): The factorial of num.
"""
#If the number provided is zero then the factorial is 1
if num == 0:
fact = 1
#Otherwise set fact to 1 and begin finding the factorial r is
#used to find each num-n for n=0 to n=num each value in r is
#then used to compute the factorial
else:
fact = 1
r = list(range(1,num+1))
for i in r:
fact *= i
return fact |
def get_metadata_url(illust_id: int) -> str:
"""Get illust Metadata URL from ``illust_id``.
:param illust_id: Pixiv illust_id
:type illust_id: :class:`int`
:return: Pixiv Metadata URL
:rtype: :class:`str`
"""
return (
'https://www.pixiv.net/ajax/illust/'
'{}/ugoira_meta'.format(illust_id)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.