content stringlengths 42 6.51k |
|---|
def signature(rle):
"""
Return the sequence of characters in a run-length encoding
(i.e. the signature).
Also works with variable run-length encodings
"""
return ''.join(r[0] for r in rle) |
def make_rep(req, body=None):
"""Utility which creates a reply object based on the headers in the request
object."""
rep = { 'head': { 'seq': req['head']['seq'] +1,
'cmd': req['head']['cmd'],
'rSeq': req['head']['seq'] }}
if body:
rep['body'] = body
return rep |
def json_extract(obj, key):
"""Recursively fetch values from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, val_ue in obj.items():
if isinstance(val_ue, (dict, list)):
extract(val_ue, arr, key)
elif k == key:
arr.append(val_ue)
elif isinstance(obj, list):
for item in obj:
extract(item, arr, key)
return arr
values = extract(obj, arr, key)
return values |
def rule2string(lhs,rhs,isCopy=False):
"""
Makes a string from a rule. Used in printing and in making a dict of rules and probs.
Arguments:
lhs : string
rhs : string list
isCopy : boolean indicating a copy rule. Only used in cky_constituent_copy
"""
s = "%s->%s"%(lhs,".".join(rhs))
if isCopy:
s+=".copy"
return s |
def label_maker(benchmark_covariate, kd, ky, digits=2):
"""
Return a string created by appending the covariate name to the multiplier(s) ky and (if applicable) kd.
Parameters
----------
benchmark_covariates : string or list of strings
a string or list of strings with names of the variables to use for benchmark bounding.
kd : float or list of floats
a float or list of floats with each being a multiple of the strength of association between a
benchmark variable and the treatment variable to test with benchmark bounding (Default value = 1).
ky : float or list of floats
same as kd except measured in terms of strength of association with the outcome variable (Default value = None).
digits : int
rouding digit of ky/kd shown in the string (Default value = 2).
Returns
-------
"""
if benchmark_covariate is None:
return 'manual'
else:
variable_text = ' ' + str(benchmark_covariate)
if ky == kd:
multiplier_text = str(round(ky, digits))
else:
multiplier_text = str(round(kd, digits)) + '/' + str(round(ky, digits))
bound_label = multiplier_text + 'x' + variable_text
return bound_label |
def validate_gff_gtf_filename(f):
"""Ensure file extension is gff or gtf"""
if "gtf" in f.lower():
return True
elif "gff" in f.lower():
return True
else:
return False |
def compute_f(match_num, test_num, gold_num, significant, f_only):
"""
Compute the f-score based on the matching clause number,
clause number of DRS set 1,
clause number of DRS set 2
Args:
match_num: matching clause number
test_num: clause number of DRS 1 (test file)
gold_num: clause number of DRS 2 (gold file)
Returns:
precision: match_num/test_num
recall: match_num/gold_num
f_score: 2*precision*recall/(precision+recall)
"""
if test_num == 0 or gold_num == 0:
if f_only:
return 0.00
else:
return 0.00, 0.00, 0.00
precision = round(float(match_num) / float(test_num), significant)
recall = round(float(match_num) / float(gold_num), significant)
if precision < 0.0 or precision > 1.0 or recall < 0.0 or recall > 1.0:
raise ValueError("Precision and recall should never be outside (0.0-1.0), now {0} and {1}".format(precision, recall))
if (precision + recall) != 0:
f_score = round(2 * precision * recall / (precision + recall), significant)
if f_only:
return f_score
else:
return precision, recall, f_score
else:
if f_only:
return 0.00
else:
return precision, recall, 0.00 |
def _nt_colour(nt):
"""
Set default colours for 21, 22 and 24 nt sRNAs
:param nt: aligned read length (int)
:return: colour code (str)
"""
hex_dict = {18: '#669999', 19: '#33cccc', 20: '#33cccc', 21: '#00CC00',
22: '#FF3399', 23: '#d8d408', 24: '#3333FF', 25: '#cccc00',
26: '#660033', 27: '#996600', 28: '#336699', 29: '#ff6600',
30: '#ff99ff', 31: '#669900', 32: '#993333', "mir": '#ff7b00'}
if nt not in hex_dict:
return "black"
else:
return hex_dict[nt] |
def unescape_path_key(key):
"""Unescape path key."""
key = key.replace(r'\\', '\\')
key = key.replace(r'\.', r'.')
return key |
def reverse(x: int) -> int:
"""
Function to find reverse of any number
"""
rev = 0
while x > 0:
rev = (rev * 10) + x % 10
x = int(x / 10)
return rev |
def solution(array):
"""Returns the first ten digits of the sum of the array elements.
>>> import os
>>> sum = 0
>>> array = []
>>> with open(os.path.dirname(__file__) + "/num.txt","r") as f:
... for line in f:
... array.append(int(line))
...
>>> solution(array)
'5537376230'
"""
return str(sum(array))[:10] |
def notenum_to_freq(notenum):
"""Converts MIDI note number to frequency."""
f0 = 440.0
a = 2 ** (1.0 / 12.0)
return f0 * (a ** (notenum - 69)) |
def _mirrorpod_filter(pod):
"""Check if a pod contains the mirror K8s annotation.
Args:
- pod: kubernetes pod object
Returns: (False, "") if the pod has the mirror annotation,
(True, "") if not
"""
mirror_annotation = "kubernetes.io/config.mirror"
annotations = pod["metadata"].get("annotations")
if annotations and mirror_annotation in annotations:
return False, ""
return True, "" |
def handler(event, context):
"""
Handle bounds requests
"""
print(event, context)
return True |
def extractConfigParameter(configParameter, era, run):
"""
_extractConfigParameter_
Checks if configParameter is era or run dependent. If it is, use the
provided era and run information to extract the correct parameter.
"""
if isinstance(configParameter, dict):
if 'acqEra' in configParameter and era in configParameter['acqEra']:
return configParameter['acqEra'][era]
elif 'maxRun' in configParameter:
newConfigParameter = None
for maxRun in sorted(configParameter['maxRun'].keys()):
if run <= maxRun:
newConfigParameter = configParameter['maxRun'][maxRun]
break
if newConfigParameter:
return newConfigParameter
return configParameter['default']
else:
return configParameter |
def strToBytes(raw_str):
""" convert str to bytes after bytesToStr conversion to return
the original bytes content """
return bytes.fromhex(raw_str) |
def shell_escape(string):
"""
Escape double quotes, backticks and dollar signs in given ``string``.
For example::
>>> _shell_escape('abc$')
'abc\\\\$'
>>> _shell_escape('"')
'\\\\"'
"""
for char in ('"', '$', '`'):
string = string.replace(char, '\\{}'.format(char))
return string |
def gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor.
Currently, this uses the Euclidean algorithm.
Parameters
----------
a : int
Non-zero
b : int
Non-zero
Returns
-------
greatest_common_divisor : int
Examples
--------
>>> gcd(1, 7)
1
>>> gcd(-1, -1)
1
>>> gcd(1337, 42)
7
>>> gcd(-1337, -42)
7
>>> gcd(120, 364)
4
>>> gcd(273, 1870)
1
"""
if a == 0 or b == 0:
raise ValueError(f"gcd(a={a}, b={b}) is undefined")
while b != 0:
a, b = b, a % b
return abs(a) |
def chk_abbreviation(abbreviation):
"""Checks whether the abbreviation is composed only by letters."""
toret = False
for ch in abbreviation:
if not ch.isalpha():
break
else:
toret = True
return toret |
def installation_token_payload(passed_keywords: dict) -> dict:
"""Create a properly formatted payload for handling installation tokens.
{
"expires_timestamp": "2021-09-22T02:28:11.762Z",
"label": "string",
"type": "string", [CREATE only]
"revoked": boolean [UPDATE only]
}
"""
returned_payload = {}
if passed_keywords.get("expires_timestamp", None):
returned_payload["expires_timestamp"] = passed_keywords.get("expires_timestamp", None)
if passed_keywords.get("label", None):
returned_payload["label"] = passed_keywords.get("label", None)
return returned_payload |
def compile_route_to_regex(route):
"""Compiles a route to regex
Arguments:
route {masonite.routes.Route} -- The Masonite route object
Returns:
string -- Returns the regex of the route.
"""
# Split the route
split_given_route = route.split('/')
# compile the provided url into regex
url_list = []
regex = '^'
for regex_route in split_given_route:
if '*' in regex_route or '@' in regex_route:
if ':int' in regex_route:
regex += r'(\d+)'
elif ':string' in regex_route:
regex += r'([a-zA-Z]+)'
else:
# default
regex += r'([\w.-]+)'
regex += r'\/'
# append the variable name passed @(variable):int to a list
url_list.append(
regex_route.replace('@', '').replace(
':int', '').replace(':string', '')
)
else:
regex += regex_route + r'\/'
if regex.endswith('/') and not route.endswith('/'):
regex = regex[:-2]
regex += '$'
return regex |
def reverse_compliment(pattern):
"""returns reverse complement for the input pattern"""
compliment = {'C': 'G',
'G': 'C',
'A': 'T',
'T': 'A'}
output = []
for key in pattern:
output.append(compliment[key])
reverse_output = (output[::-1])
output_str1 = ''.join(reverse_output)
return output_str1 |
def hf_vs_hadr_energy(hadr_energy):
"""Hadronic factor as a function of a hadronic cascade's energy.
Parameters
----------
hadr_energy
Returns
-------
hadr_factor
Notes
-----
C++ function originally named "HadronicFactorHadEM"
"""
E0 = 0.18791678 # pylint: disable=invalid-name
m = 0.16267529
f0 = 0.30974123
e = 2.71828183
en = max(e, hadr_energy)
return 1 - pow(en / E0, -m) * (1 - f0) |
def test_middleware(components):
""" Test middleware function that returns a simple number """
for component in components:
component['quantity'] = component['quantity'] + 1
return components |
def clean_newick_id(name):
"""
Return a version of name suitable for placement in a newick file
:param name: The name to clean up
:return: a name with no colons, spaces, etc
"""
name = name.replace(' ', '_')
name = name.replace(':', '_')
name = name.replace('[', '_')
name = name.replace(']', '_')
return name |
def sum(a, b):
"""
>>> sum(2, 4)
6
>>> sum('a', 'b')
'ab'
"""
return a+b+b |
def add_two(a, b):
"""adds two numbers
Arguments:
a {int} -- num one
b {int} -- num two
Returns:
[int] -- [number added]
"""
if not a or not b:
return None
return a + b |
def is_leap_year(given_year):
"""
Checks if a given year denoted by 'given_year' is leap-year or not.
Returns True if 'given_year' is leap-year.
Returns False otherwise.
"""
if given_year % 100 == 0:
if given_year % 400 == 0:
return True
else:
return False
else:
if given_year % 4 == 0:
return True
else:
return False |
def lloyd_only_rref_p(et, p):
"""
Soil respiration of Lloyd & Taylor (1994) with fix E0
If E0 is know in Lloyd & Taylor (1994) then one can calc
the exponential term outside the routine and the fitting
becomes linear. One could also use functions.line0.
Parameters
----------
et : float or array_like of floats
exp-term in Lloyd & Taylor
p : iterable of floats
`p[0]` = Respiration at Tref=10 degC [umol(C) m-2 s-1]
Returns
-------
float
Respiration [umol(C) m-2 s-1]
"""
return p[0]*et |
def average(iterable):
"""Return the average of the values in iterable.
iterable may not be empty.
"""
it = iterable.__iter__()
try:
s = next(it)
count = 1
except StopIteration:
raise ValueError("empty average")
for value in it:
s = s + value
count += 1
return s/count |
def enc(s):
"""UTF-8 encode a string."""
return s.encode('utf-8') |
def join_lines(x):
"""Inverse of split_lines"""
if all(isinstance(i, str) for i in x):
return "\n".join(x)
elif all(isinstance(i, list) for i in x):
return [join_lines(i) for i in x]
else:
raise TypeError(f"{[type(i) for i in x]} {str(x)[:20]}") |
def profit(initial_capital, multiplier):
"""Calculate the profit based on multiplier factor.
:param initial_capital: Initial amount of capital
:type initial_capital: float
:param multiplier: Multiplying factor
:type multiplier: float
:return: Profit
:rtype: float
"""
return initial_capital * (multiplier + 1.0) - initial_capital |
def CorelatedGame(*args):
"""The more arguments are equal to the first argument,
the higher the return value."""
incr = 1.0/len(args)
r = 0.0
x = args[0]
for y in args:
if y == x: r += incr
return r |
def noise_removal_w_regex(input_text):
"""Removing noise from using using regular expression.
:param input_text: Noisy text.
:return: Clean text.
"""
import re
# pattern to remove hashtagged words eg. #this
r_pattern = "#[\w]*"
# matches iterator
matches = re.finditer(r_pattern, input_text)
for i in matches:
# removing each match from original input text
input_text = re.sub(i.group().strip(),'', input_text)
# removing inner extra spaces
return re.sub(' +',' ',input_text) |
def _get_subclass_entry(cls, clss, exc_msg="", exc=NotImplementedError):
"""In a list of tuples (cls, ...) return the entry for the first
occurrence of the class of which `cls` is a subclass of.
Otherwise raise `exc` with the given message"""
for clstuple in clss:
if issubclass(cls, clstuple[0]):
return clstuple
raise exc(exc_msg % locals()) |
def is_correct_type(item, expected_type):
"""Function for check if a given item has the excpected type.
returns True if the expected type matches the item, False if not
Parameters:
-item: the piece of data we are going to check.
-expected_type: the expected data type for item.
"""
if item != None: #if we are not in front of a missing value
if expected_type in {int, float, (int, float)}:
try:
if (float(item)*10%10) == 0: #if the number is not a float
if expected_type in {int, (int, float)}:
return True
elif expected_type == float:
return False
elif expected_type in {float, (int, float)}:
return True
except ValueError: #This means that the value was not an integer neither float
return False
elif expected_type == bool and item.strip().upper() in {'TRUE', 'FALSE'}:
return True
elif expected_type == str and item.strip().upper() not in {'TRUE', 'FALSE'}:
try:
float(item)
return False
except ValueError: #This means that we could not convert the item to float, wich means is not a numeric value.
return True
else:
return False |
def _is_comment(cells):
"""Returns True if it is a comment row, False otherwise."""
for cell in cells:
if cell.strip() == '':
continue
return cell.lstrip().startswith('#')
return False |
def unitDecoder(text):
"""changes css length unit to rough approximation in char cells"""
scale = 1
unit_to_char_dict = {
'em': 2,
'ex': 1,
'ch': 1,
'rem': 2,
'cm': 5,
'mm': 0.5,
'in': 12.7,
'px': 0.13,
'pt': 0.18,
'pc': 0.014
}
number = ""
unit = ""
nums = list([str(x) for x in range(0, 10)])
for char in text:
if char in nums + ["."]:
number += char
else:
unit += char
number = float(number)
try:
return int(number * scale * unit_to_char_dict[unit])
except KeyError:
if unit.strip() == "":
return number
return 1 |
def adjacent_nodes(graph, start):
"""Given a node `start` it returns a list which shows
which nodes are reachable from `start`. If the list
return by start looks like [True True False True], that means
that nodes 0, 1 and 3 are reachable from node K.
Time Complexity: # O(V + E), where V = number of vertices
and E the number of edges."""
nodes = len(graph)
visited = [False] * nodes
followers = [start]
# O(V + E)
while followers:
current_node = followers.pop()
if visited[current_node]:
continue
visited[current_node] = True
for i in range(nodes):
if graph[i][current_node] == 1:
followers.append(i)
return visited |
def rgb_to_int(rgb):
"""Given an rgb, return an int"""
return rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256) |
def filter_metadata(context, metadata: dict) -> dict:
"""
Remove metadata indicated by fixtures
:param context: Behave context
:param metadata: Metadata dictionary containing macro parameters
"""
if getattr(context, 'disable_payload', False):
metadata = {k: v for k, v in metadata.items() if k != "src_payload"}
return metadata |
def find_val_or_next_smaller(bst, x):
"""Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
if bst is None:
return None
elif bst.val == x:
return x
elif bst.val > x:
return find_val_or_next_smaller(bst.left, x)
else:
right_best = find_val_or_next_smaller(bst.right, x)
if right_best is None:
return bst.val
return right_best |
def get_web_url_from_stage(stage: str) -> str:
"""Return the full URL of given web environment.
:param stage: environment name. Can be 'production', 'dev' (aliases: 'local', 'development'), 'staging', 'preview',
or the name of any other environment
"""
if stage in ['local', 'dev', 'development']:
return 'http://localhost'
elif stage == "production":
return 'https://www.digitalmarketplace.service.gov.uk'
return f'https://www.{stage}.marketplace.team' |
def normalize_azimuth(azimuth):
"""Normalize azimuth to (-180, 180]."""
if azimuth <= -180:
return azimuth + 360
elif azimuth > 180:
return azimuth - 360
else:
return azimuth |
def activity_region(activity_arn):
"""
Return the region for an AWS activity_arn.
'arn:aws:states:us-east-2:123456789012:stateMachine:hello_world' => 'us-east-2'
"""
if activity_arn:
parts = activity_arn.split(':')
return parts[3] if len(parts) >= 4 else None
else:
return None |
def node_text_content(node) -> str:
"""
Get the text content of a node.
"""
if node is None:
return ""
if isinstance(node, str):
return node
if isinstance(node, list):
return " ".join(map(node_text_content, node))
if isinstance(node, dict):
if "text" in node:
return node_text_content(node["text"])
if "content" in node:
return node_text_content(node["content"])
if "items" in node:
return node_text_content(node["items"])
return str(node) |
def ireplace(old, new, string):
"""Returns a copy of `string` where all the occurrences of a
case-insensitive search after `old` is replaced with `new`.
:param old: the item in `string` to do a case insensitive search after.
:param new: new item to replace `old` with.
:param string: string to search-and-replace `old` with `new` in.
"""
idx = 0
while idx < len(string):
index = string.lower().find(old.lower(), idx)
if index == -1:
return string
string = string[:index] + new + string[index + len(old):]
idx = index + len(old)
return string |
def CountRect(a, b, c, d):
"""Counts number of small rectangles inside a big (incomplete) rectangle.
The input rectangle axb has 4 corners (two cxc/2, two dxd/2) cut."""
vertex = [[1 for i in range(b+1)] for j in range(a+1)] # a row, b col
for i in range(c): # cuts two c corners
for j in range(i+1):
vertex[j][i-j] = 0
vertex[a-j][b-i+j] = 0
for i in range(d): # cuts two d corners
for j in range(i+1):
vertex[j][b-i+j] = 0
vertex[a-j][i-j] = 0
# Begins to count.
count = 0
for i in range(a+1):
for j in range(b+1):
if vertex[i][j] == 0:
continue
for p in range(i+1, a+1):
if vertex[p][j] == 0:
break
for q in range (j+1, b+1):
if vertex[i][q] == 0 or vertex[p][q] == 0:
break;
count += 1
return count |
def bytes2human(n, format='%(value).1f %(symbol)sB'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> bytes2human(1)
'1.0 B'
>>> bytes2human(1024)
'1.0 KB'
>>> bytes2human(1048576)
'1.0 MB'
>>> bytes2human(1099511627776127398123789121)
'909.5 YB'
>>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
'9.8 K/sec'
>>> # precision can be adjusted by playing with %f operator
>>> bytes2human(10000, format="%(value).5f %(symbol)s")
'9.76562 K'
Taken from: http://goo.gl/kTQMs and subsequently simplified
Original Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
"""
n = int(n)
if n < 0:
raise ValueError("n < 0")
symbols = ('', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(symbols[1:]):
if n >= prefix[symbol]:
value = float(n) / prefix[symbol]
return format % locals()
return format % dict(symbol=symbols[0], value=n) |
def flatten_dictionary(json_data):
"""Return flat meta report dictionary from nested dictionary."""
meta = {}
meta["report"] = {}
for item in json_data:
if type(json_data[item]) is dict:
for values in json_data[item]:
if type(json_data[item][values]) is dict:
for second_values in json_data[item][values]:
if type(json_data[item][values][second_values]) is dict:
for third_values in json_data[item][values][second_values]:
if type(json_data[item][values][second_values][third_values])\
is not list or dict or None:
debug_test = json_data[item][values][second_values][third_values]
if debug_test:
meta["report"][str(item + "." + values + "." + second_values + "." +
third_values)] = \
str(json_data[item][values][second_values][third_values])
elif type(json_data[item][values][second_values]) is not list or None:
none_test = str(json_data[item][values][second_values])
if none_test:
meta["report"][str(item + "." + values + "." + second_values)] =\
str(json_data[item][values][second_values])
elif type(json_data[item][values]) is not list or None:
values_test = json_data[item][values]
if values_test and str(values_test) != "none":
meta["report"][str(item + "." + values)] = str(json_data[item][values])
elif type(json_data[item]) is list:
for list_items in json_data[item]:
test_dict = list_items
if type(test_dict) is str:
meta["report"][item] = test_dict
else:
meta[item] = json_data[item]
elif type(json_data[item]) is not list or None:
test_item = json_data[item]
if test_item and str(test_item) != '"':
meta["report"][item] = json_data[item]
return meta |
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None):
"""
:param lineColor: list
:param fillColor: list
:param imageData: str
:param imagePath: str
:return: dict""
"""
# return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": imageData,
# "imagePath": imagePath}
return {"imagePath": imagePath, "imageData": imageData, "shapes": shapes, "fillColor": fillColor, "lineColor": lineColor
} |
def sort_dict_desc(dictionary):
"""Sorts dictionary in descending order by values."""
return sorted(dictionary.items(), key=lambda item: item[1], reverse=True) |
def day_2_strategy(passphrase):
"""Return if passphrase is valid is no repeat words
and no anagrams."""
valid = True
words = set()
for word in passphrase.split():
sorted_word = ''.join(sorted(word))
if sorted_word not in words:
words.add(sorted_word)
else:
valid = False
break
return valid |
def _bytes_to_unicode(obj):
"""
Convert a non-`bytes` type object into a unicode string.
:param obj: the object to convert
:return: If the supplied `obj` is of type `bytes`, decode it into a unicode
string. If the `obj` is anything else (including None), the original
`obj` is returned. If the object is converted into a unicode string,
the type would be `unicode` for Python 2.x or `str` for Python 3.x.
"""
return obj.decode() if isinstance(obj, bytes) else obj |
def calculate(base_price, artist_markup, quantity):
"""
Doing the math for getting total value of the cart.
:param base_price: Base price of the product
:param artist_markup: Artist markup value from the cart.
:param quantity: Quntity from the cart.
:return: Price of the product
"""
return (base_price + round(base_price * artist_markup / 100)) * quantity |
def check_for_debug(supernova_args, nova_args):
"""
If the user wanted to run the executable with debugging enabled, we need
to apply the correct arguments to the executable.
Heat is a corner case since it uses -d instead of --debug.
"""
# Heat requires special handling for debug arguments
if supernova_args['debug'] and supernova_args['executable'] == 'heat':
nova_args.insert(0, '-d ')
elif supernova_args['debug']:
nova_args.insert(0, '--debug ')
return nova_args |
def get_comment_style(fextension):
"""
get the comment style for the specific extension
extension: (before, after)
"""
comments = {'.py': ('#', ''),
'.cfg': ('#', ''),
'.js': ('//', ''),
'.html': ('<!--', ' -->'),
'.css': ('/*', '*/')}
if not fextension in comments:
print('[WARNING] Unkown extension {0} will assume comment style "#TEXT" '\
.format(fextension))
values = comments.get(fextension, ('#', ''))
return values |
def eea(a, b):
"""
Calculates u*a + v*b = ggT
returns (ggT, u, v, steps)
"""
u, v, s, t, steps = 1, 0, 0, 1, 0
while b > 0:
q = a//b
a, b = b, a-q*b
u, s = s, u-q*s
v, t = t, v-q*t
steps += 1
return a, u, v, steps |
def iou(box1, box2):
""" Calculate intersection over union between two boxes
"""
x_min_1, y_min_1, width_1, height_1 = box1
x_min_2, y_min_2, width_2, height_2 = box2
assert width_1 * height_1 > 0
assert width_2 * height_2 > 0
x_max_1, y_max_1 = x_min_1 + width_1, y_min_1 + height_1
x_max_2, y_max_2 = x_min_2 + width_2, y_min_2 + height_2
area1, area2 = width_1 * height_1, width_2 * height_2
x_min_max, x_max_min = max([x_min_1, x_min_2]), min([x_max_1, x_max_2])
y_min_max, y_max_min = max([y_min_1, y_min_2]), min([y_max_1, y_max_2])
if x_max_min <= x_min_max or y_max_min <= y_min_max:
return 0
else:
intersect = (x_max_min-x_min_max) * (y_max_min-y_min_max)
union = area1 + area2 - intersect
return intersect / union |
def get_degree_abbrev(degree):
"""Replaces long names of degrees to shorter names of those degrees
Example: Bachelor of Science => BSc"""
subs = {
'Bachelor of Science': 'BSc',
'Master of Science': 'MSc',
'Master of Science, Applied': 'MScA',
'Bachelor of Arts': 'BA',
'Master of Arts': 'MA',
'Bachelor of Arts and Science': 'BAsc',
'Bachelor of Engineering': 'BEng',
'Bachelor of Software Engineering': 'BSE',
'Master of Engineering': 'MEng',
'Bachelor of Commerce': 'BCom',
'Licentiate in Music': 'LMus',
'Bachelor of Music': 'BMus',
'Master of Music': 'MMus',
'Bachelor of Education': 'BEd',
'Master of Education': 'MEd',
'Bachelor of Theology': 'BTh',
'Master of Sacred Theology': 'STM',
'Master of Architecture': 'MArch',
'Bachelor of Civil Law': 'BCL',
'Bachelor of Laws': 'LLB',
'Master of Laws': 'LLM',
'Bachelor of Social Work': 'BSW',
'Master of Social Work': 'MSW',
'Master of Urban Planning': 'MUP',
'Master of Business Administration': 'MBA',
'Master of Management': 'MM',
'Bachelor of Nursing (Integrated)': 'BNI',
'Doctor of Philosophy': 'PhD',
'Doctor of Music': 'DMus'
} #Most of these degrees probably won't work with minervac, but this list may be slightly useful
for sub in subs:
degree = degree.replace(sub,subs[sub])
return degree |
def string_to_dependencies(text: str) -> set:
"""Return the set of pip dependencies from a multi-line string.
Whitespace and empty lines are not significant.
Comment lines are ignored.
"""
lines = text.splitlines()
lines = [line for line in lines if not line.startswith("#")]
collapsed_lines = [line.replace(" ", "") for line in lines if line]
items = set(collapsed_lines)
if "" in items:
items.remove("") # empty string from blank lines
return items |
def _equivalence(self, other):
"""A function to assert equivalence between client and server side copies of model
instances"""
return type(self) == type(other) and self.uid == other.uid |
def calculateTopicNZ(topicCoOccurrenceList, coOccurrenceDict):
""" Calculates and returns a topic's total NZ. """
sumNZ = 0
for topicCoOccurrence in topicCoOccurrenceList:
if coOccurrenceDict[topicCoOccurrence] == 0.0:
sumNZ += 1
return sumNZ |
def set_chunk_size(data_type, stream_id, new_size):
"""
Construct a 'SET_CHUNK_SIZE' message to adjust the chunk size at which the RTMP library works with.
:param data_type: int the RTMP datatype.
:param stream_id: int the stream which the message will be sent on.
:param new_size: int the new size of future message chunks from the client (1<=size<=2147483647).
NOTE: All sizes set after 16777215 are equivalent.
"""
msg = {'msg': data_type,
'stream_id': stream_id,
'chunk_size': new_size}
return msg |
def get_mean(iterable):
"""
Returns the mean of a given iterable which is defined as the sum divided by
the number of items.
"""
return sum(iterable) / len(iterable) |
def parse_mode(cipher_nme):
"""
Parse the cipher mode from cipher name
e.g. aes-128-gcm, the mode is gcm
:param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ...
:return: str/None The mode, cfb, gcm ...
"""
hyphen = cipher_nme.rfind('-')
if hyphen > 0:
return cipher_nme[hyphen:]
return None |
def find_kth(nums1, nums2, k):
"""find kth number of two sorted arrays
>>> find_kth([1, 3], [2], 2)
2
>>> find_kth([2], [1, 3], 1)
1
>>> find_kth([1, 3], [2], 3)
3
>>> find_kth([1], [2], 1)
1
>>> find_kth([1], [2], 2)
2
"""
# assume len(nums1) <= len(nums2)
if len(nums2) < len(nums1):
nums1, nums2 = nums2, nums1
# if nums1 is empty
if not nums1:
return nums2[k - 1]
if k == 1:
return min(nums1[0], nums2[0])
# divide and conquer
if len(nums1) < k // 2:
return find_kth(nums1, nums2[k - k // 2:], k // 2)
elif nums1[k // 2 - 1] == nums2[k - k // 2 - 1]:
return nums1[k // 2 - 1]
elif nums1[k // 2 - 1] < nums2[k - k // 2 - 1]:
return find_kth(nums1[k // 2:], nums2[:k - k // 2], k - k // 2)
else:
return find_kth(nums1[:k // 2], nums2[k - k // 2:], k // 2) |
def excel_column_name(index):
"""
Converts 1-based index to the Excel column name.
Parameters
----------
index : int
The column number. Must be 1-based, ie. the first column
number is 1 rather than 0.
Returns
-------
col_name : str
The column name for the input index, eg. an index of 1 returns 'A'.
Raises
------
ValueError
Raised if the input index is not in the range 1 <= index <= 18278,
meaning the column name is not within 'A'...'ZZZ'.
Notes
-----
Caches the result so that any repeated index lookups are faster,
and uses recursion to make better usage of the cache.
chr(64 + remainder) converts the remainder to a character, where
64 denotes ord('A') - 1, so if remainder = 1, chr(65) = 'A'.
"""
if not 1 <= index <= 18278: # ensures column is between 'A' and 'ZZZ'.
raise ValueError(f'Column index {index} must be between 1 and 18278.')
col_num, remainder = divmod(index, 26)
# ensure remainder is between 1 and 26
if remainder == 0:
remainder = 26
col_num -= 1
if col_num > 0:
return excel_column_name(col_num) + chr(64 + remainder)
else:
return chr(64 + remainder) |
def rotate(i, length):
"""Given integer i and number of digits, rotate its digits by 1 spot"""
s = str(i)
ans = 0
if len(s) == 1:
return i
if len(s) == 2:
ans = int(s[1] + s[0])
else:
ans = int(s[1:] + s[0])
while len(str(ans)) < length: #solve for 011 being rotated to 11 instead of 110
ans *= 10
return ans |
def CacheKey(state, status, urlkey):
"""Calculates the cache key for the given combination of parameters."""
return 'GetBugs_state_%s_status_%s_key_%s' % (state, status, urlkey) |
def get_ylabel(toa_files, ohu_files, ohc_files):
"""Get the label for the yaxis"""
toa_plot = False if toa_files == [] else True
ohu_plot = False if ohu_files == [] else True
ohc_plot = False if ohc_files == [] else True
ylabel = 'heat uptake/storage (J)'
if not ohc_plot:
ylabel = 'heat uptake (J)'
elif not (toa_plot or ohu_plot):
ylabel = 'change in OHC (J)'
return ylabel |
def create_node_string(identifier,
event_type,
event_type_uri,
example_incidents):
"""
"""
line_one = f'{identifier}[label=<<table>'
line_two = f'<tr><td href="{event_type_uri}">{event_type}</td></tr>'
lines = [line_one, line_two]
for index, uri in enumerate(example_incidents, 1):
line = f'<tr><td href="{uri}">Example {index}</td></tr>'
lines.append(line)
last_line = '</table>>]'
lines.append(last_line)
return '\n'.join(lines) |
def bool2str(x):
"""Return Fortran bool string for bool input."""
return '.true.' if x else '.false.' |
def convert_args_to_str(args, max_len=None):
""" Convert args to a string, allowing for some arguments to raise
exceptions during conversion and ignoring them.
"""
length = 0
strs = ["" for i in range(len(args))]
for i, arg in enumerate(args):
try:
sarg = repr(arg)
except:
sarg = "< could not convert arg to str >"
strs[i] = sarg
length += len(sarg) + 2
if max_len is not None and length > max_len:
return "({}".format(", ".join(strs[:i+1]))[:max_len]
else:
return "({})".format(", ".join(strs)) |
def String_to_File(string,file_name="test"):
"""Saves a string as a file"""
out_file=open(file_name,'w')
out_file.write(string)
out_file.close()
return file_name |
def format_message(name, message, version):
"""Message formatter to create `DeprecationWarning` messages
such as:
'fn' is deprecated and will be remove in future versions (1.0).
"""
return "'{}' is deprecated and will be remove in future versions{}. {}".format(
name,
' ({})'.format(version) if version else '',
message,
) |
def areaTriangle(base: float, height: float) -> float:
"""Finds area of triangle"""
area: float = (height * base) / 2
return area |
def is_in_bounds(grid, x, y):
"""Get whether an (x, y) coordinate is within bounds of the grid."""
return (0 <= x < len(grid)) and (0 <= y < len(grid[0])) |
def get_fi_repeated_prime(p, k=1):
"""
Return Euler totient for prime power p^k
:param p: prime number
:param k: power
:return: fi(p^k)
"""
return pow(p, k - 1) * (p - 1) |
def last_index(arr, item):
"""Return not first (as `.index`) but last index of `item` in `arr`.
"""
return len(arr) - arr[::-1].index(item) - 1 |
def diff(previous, current):
"""Deep diff 2 dicts
Return a dict of new elements in the `current` dict.
Does not handle removed elements.
"""
result = {}
for key in current.keys():
value = current[key]
p_value = previous.get(key, None)
if p_value is None:
result[key] = value
continue
if isinstance(value, dict):
difference = diff(previous.get(key, {}), value)
if difference:
result[key] = difference
elif isinstance(value, list):
value = [x for x in value if x not in p_value]
if value != []:
result[key] = value
elif value != p_value:
result[key] = value
return result |
def format_trace_id(trace_id):
"""Format the trace id according to b3 specification."""
# hack: trim traceID to LSB
return format(trace_id, "016x")[-16:] |
def check_related_lot_status(tender, award):
"""Check if related lot not in status cancelled"""
lot_id = award.get('lotID')
if lot_id:
if [l['status'] for l in tender.get('lots', []) if l['id'] == lot_id][0] != 'active':
return False
return True |
def within_bounds(world_state, pose):
""" Returns true if pose is inside bounds of world_state """
if pose[0] >= len(world_state) or pose[1] >= len(world_state[0]) or pose[0] < 0 or pose[1] < 0:
return False
else:
return True |
def divisors(n):
"""Return the integers that evenly divide n.
>>> divisors(1)
[1]
>>> divisors(4)
[1, 2]
>>> divisors(12)
[1, 2, 3, 4, 6]
>>> [n for n in range(1, 1000) if sum(divisors(n)) == n]
[1, 6, 28, 496]
"""
return [1] + [x for x in range(2, n) if n % x == 0] |
def adjust_kafka_timestamp(data):
"""
This is needed for the log-event-duration service to work properly
"""
if data is not None and "timestamp" in data:
data["@timestamp"] = data["timestamp"]
return data |
def rgb_to_hex_v2(r: int, g: int, b: int) -> str:
"""
Dengan menggunakan:
* [list comprehension](\
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)
* [conditional expressions](\
https://docs.python.org/3/reference/expressions.html#conditional-expressions)
Kita bisa menuliskan fungsi ini dalam beberapa baris Python.
>>> rgb_to_hex_v2(0, 0, 0)
'000000'
>>> rgb_to_hex_v2(1, 2, 3)
'010203'
>>> rgb_to_hex_v2(255, 255, 255)
'FFFFFF'
>>> rgb_to_hex_v2(-10, 255, 300)
'00FFFF'
>>> rgb_to_hex_v2(150, 0, 180)
'9600B4'
"""
return "".join(
["00" if x <= 0 else "FF" if x >= 255 else f"{x:02X}" for x in (r, g, b)]
) |
def list_to_string(item_name, values):
"""Return a pretty version of the list."""
values = sorted(values)
if len(values) < 5:
values_string = "{}{}={}".format(
item_name,
"s" if len(values) > 1 else "",
",".join(values)
)
else:
values_string = "{} {}s from {} to {}".format(
len(values),
item_name,
values[0],
values[-1]
)
return values_string |
def normalize_content(content: str) -> str:
"""
Remove preceding and trailing whitespaces from `content` string.
:param content: string to be normalized.
:returns: normalized string.
"""
return content.strip(' \n\t') |
def delta(a, b):
"""
Kronecker delta function
"""
return 1 if a == b else 0 |
def temp_ampersand_fixer(s):
"""As a workaround for ampersands stored as escape sequences in database, unescape text before use on a safe page
Explicitly differentiate from safe_unescape_html in case use cases/behaviors diverge
"""
return s.replace('&', '&') |
def _rot_list(l, k):
"""Rotate list by k items forward. Ie. item at position 0 will be
at position k in returned list. Negative k is allowed."""
n = len(l)
k %= n
if not k: return l
return l[n-k:] + l[:n-k] |
def desi_dr8_url(ra, dec):
"""
Construct URL for public DESI DR8 cutout.
from SkyPortal
"""
return (
f"http://legacysurvey.org/viewer/jpeg-cutout?ra={ra}"
f"&dec={dec}&size=200&layer=dr8&pixscale=0.262&bands=grz"
) |
def hit2csv_header(csv_writer, ichunk, is_simplified):
"""
Returns the header row of the csv that is created.
For the simplified export, only the article title and text content are included.
"""
es_header_names = kb_header_names = []
metadata_header_name = ["metadata"]
if not is_simplified:
es_header_names = ["_id", "_score"]
if is_simplified:
kb_header_names = ["article_dc_title", "text_content"]
else:
kb_header_names = \
["identifier", # 2
"paper_dc_date", # 3
"paper_dc_identifier", # 4
"paper_dc_identifier_resolver", # 5
"paper_dc_language", # 6
"paper_dc_title", # 7
"paper_dc_publisher", # 8
"paper_dc_source", # 9
"paper_dcterms_alternative", # 10
"paper_dcterms_isPartOf", # 11
"paper_dcterms_isVersionOf", # 12
"paper_dcterms_issued", # 13
"paper_dcterms_spatial", # 14
"paper_dcterms_spatial_creation", # 15
"paper_dcterms_temporal", # 16
"paper_dcx_issuenumber", # 17 can contain '-' instead of a number
"paper_dcx_recordRights", # 18
"paper_dcx_recordIdentifier", # 19
"paper_dcx_volume", # 20
"paper_ddd_yearsDigitized", # 21
"article_dc_identifier_resolver", # 21
"article_dc_subject", # 22
"article_dc_title", # 23
"article_dcterms_accessRights", # 24
"article_dcx_recordIdentifier", # 25
"text_content"] # 26
if ichunk == 0:
csv_writer.writerow(metadata_header_name + es_header_names + kb_header_names)
return es_header_names, kb_header_names |
def to_camel_case(snake_str: str) -> str:
"""
Converts snake case to camel case.
:param snake_str: The string in snake case to be converted
:return: The converted string in camel case
"""
components = snake_str.split('_')
return ' '.join(x.title() for x in components) |
def pluralize(n: int, singular: str, plural: str) -> str:
"""Choose between the singular and plural forms of a word depending on the
given count.
"""
if n == 1:
return singular
else:
return plural |
def fast_non_dominated_sort(p):
"""NSGA-II's fast non dominated sort
:param p: values to sort
:type p: iterable
:return: indices of values sorted into their domination ranks (only first element used)
:rtype: list of lists of indices
"""
S = [[] for _ in p] # which values dominate other?
front = [[]] # group values by number of dominations
n = [0]*len(p) # how many values does the value at this position dominate?
# rank = [0]*len(p) # rank within domination tree (unused)
# compare all elements, see which ones dominate each other
for i in range(0, len(p)):
for j in range(0, len(p)):
if p[i].dominates(p[j]) and j not in S[i]:
S[i].append(j)
elif p[j].dominates(p[i]):
n[i] += 1
if n[i] == 0:
# element is not dominated: put in front
# rank[i] = 0
if i not in front[0]:
front[0].append(i)
i = 0
while(len(front[i]) > 0):
Q = []
for p in front[i]:
for q in S[p]:
n[q] -= 1
if n[q] == 0:
# rank[q] = i+1
if q not in Q:
Q.append(q)
i = i+1
front.append(Q)
front.pop(len(front) - 1)
return front |
def sgi_2016_to_1973(sgi_id: str) -> str:
"""
Convert the slightly different SGI2016 to the SGI1973 id format.
:examples:
>>> sgi_2016_to_1973("B55")
'B55'
>>> sgi_2016_to_1973("B55-19")
'B55-19'
>>> sgi_2016_to_1973("E73-02")
'E73-2'
"""
if "-" not in sgi_id:
return sgi_id
start, end = sgi_id.split("-")
return start + "-" + str(int(end)) |
def s2i(symbols):
"""
Examples:
>>> symbols=['H', 'Li', 'H', 'F']
>>> s2i(symbols)
{'H': [0, 2], 'F': [3], 'Li': [1]}
"""
out = {}
for i, symbol in enumerate(symbols):
if symbol not in out:
out[symbol] = []
out[symbol].append(i)
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.