content
stringlengths 42
6.51k
|
---|
def make_row(values, val_bufs, breaks=[]):
"""Creates a row for the results table."""
row = "|" + "|".join([str(values[i]) + " " * val_bufs[i] for i in range(len(values))]) + "|"
for i in range(len(breaks)):
row = row[:breaks[i]+i] + "\n" + row[breaks[i]+i:]
return row
|
def get_library_name(library_name):
"""
Utility to split between the library name and version number when needed
"""
name = library_name
for sign in ['!=', '==', '>=', '~=']:
name = name.split(sign)[0]
return name.strip()
|
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if type(item) == type([]):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis
|
def pax_to_human_time(num):
"""Converts a pax time to a human-readable representation"""
for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']:
if num < 1000.0:
return "%3.3f %s" % (num, x)
num /= 1000.0
return "%3.1f %s" % (num, 's')
|
def split_str(str):
"""
:param str: str
:return: list-> odd as coordinate location, even as value
"""
seps = str.split('\n')
repeat = 3
for j in range(repeat):
for i, sep in enumerate(seps):
if '\r' in sep:
seps[i] = sep[:-1]
if sep == '':
del seps[i]
return seps
|
def check_conditions(directory, conditions):
"""
Function to check if a condition is known and accounted for.
Parameters
----------
directory : string
the name of a directory that is the condition to check for
conditions : list of strings
a list of known and accounted for conditions
Returns
-------
directory : string or None
either returns an unaccounted-for condition or returns None.
"""
for condition in conditions:
if condition in directory:
return None
return directory
|
def signed_is_negative(num, nbits=32):
""" Assuming the number is a word in 2s complement, is it
negative?
"""
return num & (1 << (nbits - 1))
|
def news_dictionary_maker(articles_list:list) -> list:
"""
Description:
Function to make a smaller list which doesn't contain the 'seen' key
Arguments:
articles_list {list} : list contains dictionary's with the 'seen' and 'articles' keys
Returns:
news_list {list} : list containing just the 'articles' jey from the list in arguments
"""
news_list = []
# cycles through each news article and appends dictionary if article hasn't been seen before
x = 0
for i in articles_list:
if articles_list[x]['seen'] == 0:
news_list.append(articles_list[x]['articles'])
x = x + 1
return news_list
|
def binary_add(first, second):
"""Binary voodoo magic."""
if second == 0:
return first
elif first == 0:
return second
xor = first ^ second
carry = (first & second) << 1
return binary_add(xor, carry)
|
def upper(s: str) -> str:
"""
Return a copy of the string with all the characters converted to uppercase
"""
return s.upper()
|
def get_bg_len(offset_ms, samplerate):
"""
Return length of samples which belongs to no-beacon signal part
"""
return int((- offset_ms) / 1000.0 * samplerate)
|
def _parse_cigar(cigartuples):
"""Count the insertions in the read using the CIGAR string."""
return sum([item[1] for item in cigartuples if item[0] == 1])
|
def startswith_strip(s, startswith='http://', ignorecase=True):
""" Strip a prefix from the beginning of a string
>>> startswith_strip('HTtp://TotalGood.com', 'HTTP://')
'TotalGood.com'
>>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False)
'HTtp://TotalGood.com'
"""
if ignorecase:
if s.lower().startswith(startswith.lower()):
return s[len(startswith):]
else:
if s.endswith(startswith):
return s[len(startswith):]
return s
|
def construct_cpe(vendor, product, version):
"""
Construct a Common Platform Enumeration (CPE) for a given software.
Args:
vendor (str): The vendor name of the software.
product (str): The product name of the software.
version (str): The software version.
Returns:
str: The constructed CPE.
"""
return 'cpe:/a:' + vendor + ':' + product + ':' + version
|
def bytesfilter(num, suffix='B'):
"""Convert a number of bytes to a human-readable format."""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.0f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.0f %s%s" % (num, 'Yi', suffix)
|
def get_extra_options_appropriate_for_command(appropriate_option_names, extra_options):
"""
Get extra options which are appropriate for
pipeline_printout
pipeline_printout_graph
pipeline_run
"""
appropriate_options = dict()
for option_name in appropriate_option_names:
if option_name in extra_options:
appropriate_options[option_name] = extra_options[option_name]
return appropriate_options
|
def get_run_name_nr(_run_name: str, _run_nr: int) -> str:
"""
Args:
_run_name: e.g. 'runA'
_run_nr: e.g. 1
Returns:
_run_name_nr: e.g. 'runA-1'
"""
return f"{_run_name}-{_run_nr}"
|
def ith_byte_block(block_size: int, i: int) -> int:
"""
Return the block to which the byte at index i belongs.
:param block_size: The block size.
:param i: The index of the interesting byte.
:return: The index of the block to which the byte at index i belongs.
"""
assert block_size > 0
assert i >= 0
return i // block_size
|
def get_number_and_percentage(total, n, percentage):
"""n takes priority
"""
if n == -1:
return (total, 1.0)
elif n is not None and n > 0:
if n >= total:
return (total, 1.0)
else:
return (n, float(n) / total)
else:
assert isinstance(percentage, float)
return (int(total*percentage), percentage)
|
def __calculate_variance(profile_jsons, feature_name):
"""
Calculates variance for single feature
Parameters
----------
profile_jsons: Profile summary serialized json
feature_name: Name of feature
Returns
-------
variance : Calculated variance for feature
"""
feature = profile_jsons.get("columns").get(feature_name)
variance = feature.get("numberSummary").get("stddev") ** 2 if feature.get("numberSummary") is not None else 0
return variance
|
def af_to_ip_header_fields(address_family, header_field):
"""Return the correct header name for an IP field with similar IPv4 and IPv6 usage.
Keyword arguments:
address_family -- desired address-family
header_field -- header field name (use the IPv4 one)
"""
headers = {"ipv6": {"tos": "tc", "id": "fl"}}
# return the original ipv4 header field name if it is not found in dict
return headers.get(address_family, {}).get(header_field, header_field)
|
def calc_G(y, symbol_values):
"""
Calculates the shear modulus from the provided modulus and another elastic quantity in the
provided symbol_values dictionary.
Returns:
(float): value of the shear modulus or None if the calculation failed.
"""
if "K" in symbol_values.keys():
k = symbol_values["K"]
return 3 * k * y / (9 * k - y)
elif "l" in symbol_values.keys():
l = symbol_values["l"]
return (y - 3 * l + (y ** 2 + 9 * l ** 2 + 2 * y * l) ** (0.5)) / 4
elif "v" in symbol_values.keys():
v = symbol_values["v"]
return y / (2 * (1 + v))
elif "M" in symbol_values.keys():
m = symbol_values["M"]
return (3 * m + y - (y ** 2 + 9 * m ** 2 - 10 * y * m) ** (0.5)) / 8
else:
raise Exception("Missing required inputs to evaluate Shear Modulus")
|
def replace_space(target_str):
"""
:params target_str: str
return: str
"""
new_str = target_str.replace(" ", "20%")
return new_str
|
def legendre(a: int, p: int) -> int:
"""
Calculate value of Legendre symbol (a/p).
:param a: Value of a in (a/p).
:param p: Value of p in (a/p).
:returns: Value of (a/p).
"""
return pow(a, (p - 1) // 2, p)
|
def revpad(s):
"""
This function is to remove padding.
parameters:
s:str
string to be reverse padded
"""
k=ord(s[-1])
temp=0 #temporary variable to check padding
for i in range (1,k): #for loop to check padding
if(s[-i]!=s[-1]): #comparision of bytes with the last Byte
temp=1
if(temp==0):
return (s[:-k]) #Reverse padded string
else:
return ("Wrong padding")
|
def _nth_digit(i, n):
"""
Determine the nth digit of an integer, starting at the right and counting
from zero.
>>> [_nth_digit(123, n) for n in range(5)]
[3, 2, 1, 0, 0]
"""
return (i // 10**n) % 10
|
def get_idx_set(i, sets):
"""
find out the idx of set where `i is an element
"""
idxs = []
for j, set_j in enumerate(sets):
if i in set_j: idxs.append(j)
return idxs
|
def pluralize(n, text, suffix='s'):
# type: (int, str, str) -> str
"""Pluralize term when n is greater than one."""
if n != 1:
return text + suffix
return text
|
def fix_carets(expr):
"""Converts carets to exponent symbol in string"""
import re as _re
caret = _re.compile('[\^]')
return caret.sub('**',expr)
|
def get_unit(quantity_name):
"""
Returns the unit string corresponding to QUANTITY_NAME, or None if an error
occurs during name extraction.
"""
if not quantity_name:
return None
if ("power" in quantity_name):
unit = "kW"
elif ("energy" in quantity_name):
unit = "kWh"
else:
unit = "unknown"
return unit
|
def clean_lines(lines):
"""removes blank lines and commented lines"""
lines2 = []
for line in lines:
line2 = line.split('#')[0].strip()
if line2:
lines2.append(line2)
return lines2
|
def lookup_next_stage_start(stage_boundaries, t):
"""
Returns the next stage start timestamp from a list/set of stage
boundaries and current time.
"""
next_boundaries = [x for x in stage_boundaries if x > t]
if len(next_boundaries) == 0:
return None
else:
return min(next_boundaries)
|
def normalized(name, feed_entries, start):
"""Returns a list of normalized kvstore entries."""
data = []
for feed_entry in feed_entries:
if 'indicator' not in feed_entry or 'value' not in feed_entry:
continue
# Make the entry dict.
entry = feed_entry.copy()
entry['splunk_source'] = name
entry['splunk_last_seen'] = start
data.append(entry)
return data
|
def rgb2hex(rgb):
"""Converts an RGB 3-tuple to a hexadeximal color string.
EXAMPLE
-------
>>> rgb2hex((0,0,255))
'#0000FF'
"""
return ('#%02x%02x%02x' % tuple(rgb)).upper()
|
def ignore_this_demo(args, demo_reward, t, last_extras):
"""In some cases, we should filter out demonstrations.
Filter for if t == 0, which means the initial state was a success.
Also, for the bag envs, if we end up in a catastrophic state, I exit
gracefully and we should avoid those demos (they won't have images we
need for the dataset anyway).
"""
ignore = (t == 0)
if 'exit_gracefully' in last_extras:
assert last_extras['exit_gracefully']
return True
if (args.task in ['bag-color-goal']) and demo_reward <= 0.5:
return True
return False
|
def simple_compression(string):
""" Simple way to compress string. """
compressed_string = "";
last, n = ("", 1)
for cha in string:
if cha==last:
n+=1
else:
if n>1:
compressed_string += str(n)
compressed_string += cha
last, n = (cha, 1)
if n>1:
compressed_string+=str(n)
return compressed_string
|
def add_result(return_value, confusion_matrix, instance_specific_pixel_information, instance_specific_instance_information):
"""
Add the result of one image pair to the result structures.
"""
result, pixel_information, instance_information = return_value
if confusion_matrix is None:
confusion_matrix = result
elif result is not None:
confusion_matrix += result
for label, values in pixel_information.items():
instance_specific_pixel_information[label]['raw_true_positives'] += values['raw_true_positives']
instance_specific_pixel_information[label]['weighted_true_positives'] += values['weighted_true_positives']
instance_specific_pixel_information[label]['raw_false_negatives'] += values['raw_false_negatives']
instance_specific_pixel_information[label]['weighted_false_negatives'] += values['weighted_false_negatives']
if instance_information is not None:
instance_specific_instance_information += [instance_information]
return (confusion_matrix, instance_specific_pixel_information, instance_specific_instance_information)
|
def get_default_ext(delim):
"""Retrieves the default extension for a delimiter"""
if delim == ',':
return "csv"
if delim == '\t':
return "tsv"
return "txt"
|
def extract_content(last_metadata_line, raw_content):
"""Extract the content without the metadata."""
lines = raw_content.split("\n")
content = "\n".join(lines[last_metadata_line + 1 :])
return content
|
def indent(level):
""" Indentation string for pretty-printing
"""
return ' '*level
|
def line_parameters_xy(pt_1, pt_2):
"""
Used in lines_intersection
from:
https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines-in-python
"""
a=(pt_1[1]-pt_2[1])
b=(pt_2[0]-pt_1[0])
c=(pt_1[0]*pt_2[1]-pt_2[0]*pt_1[1])
return a, b,-c
|
def aes_key_pad(key):
"""
Return padded key string used in AES encrypt function.
:param key: A key string.
:return: Padded key string.
"""
if not key:
raise ValueError('Key should not be empty!')
aes_key_length = 32
while len(key) < aes_key_length:
key += key
return key[:aes_key_length]
|
def join_url(*sections):
"""
Helper to build urls, with slightly different behavior from
urllib.parse.urljoin, see example below.
>>> join_url('https://foo.bar', '/rest/of/url')
'https://foo.bar/rest/of/url'
>>> join_url('https://foo.bar/product', '/rest/of/url')
'https://foo.bar/product/rest/of/url'
>>> join_url('https://foo.bar/product/', '/rest/of/url')
'https://foo.bar/product/rest/of/url'
>>> # We need this helper because of below
... # urllib.parse.urljoin behavior that is not suitable
... # for our purpose.
>>> import urllib.parse
>>> urllib.parse.urljoin('https://foo.bar/product', '/rest//of/url')
'https://foo.bar/rest/of/url'
"""
return '/'.join(s.strip('/') for s in sections)
|
def hanoi(disks: int) -> int:
"""
The minimum number of moves to complete a Tower of Hanoi is known as a Mersenne Number.
"""
return 2 ** disks - 1
|
def calc_word_score(word, letters_count, letters_score):
"""Evaluate word's score. If the word contains letters outside provided scope,
the output will be \infty.
"""
output = 0
# keep track of the used letters
letters_remaining = dict(letters_count)
for w in word:
if w not in letters_count:
# contains a letter outside the provided scope
return 0
if letters_remaining[w] == 0:
# too many occurrences of that letter
return 0
output += letters_score[w]
letters_remaining[w] -= 1
return output
|
def _set_vce_type(vce_type, cluster, shac):
""" Check for argument conflicts, then set `vce_type` if needed. """
if vce_type not in (None, 'robust', 'hc1', 'hc2', 'hc3', 'cluster',
'shac'):
raise ValueError("VCE type '{}' is not supported".format(vce_type))
# Check for conflicts
if cluster and shac:
raise ValueError("Cannot use `cluster` and `shac` together.")
elif cluster and vce_type != 'cluster' and vce_type is not None:
raise ValueError("Cannot pass argument to `cluster` and set `vce_type`"
" to something other than 'cluster'")
elif shac and vce_type != 'shac' and vce_type is not None:
raise ValueError("Cannot pass argument to `shac` and set `vce_type`"
" to something other than 'shac'")
# Set `vce_type`
new_vce = 'cluster' if cluster else 'shac' if shac else vce_type
return new_vce
|
def _get_message_mapping(types: dict) -> dict:
"""
Return a mapping with the type as key, and the index number.
:param types: a dictionary of types with the type name, and the message type
:type types: dict
:return: message mapping
:rtype: dict
"""
message_mapping = {}
entry_index = 2 # based on the links found, they normally start with 2?
for _type, message in types.items():
message_mapping[_type] = entry_index
entry_index += 1
return message_mapping
|
def check_not_errors_tcp(requets_raw, response_raw, consulta):
"""
Chequea si hay errores en la trama, formato TCP
:param requets_raw: trama con la cual se hizo la solicitud
:type requets_raw: bytes
:param response_raw: trama de respuesta
:type response_raw: bytes
:return: True si la no hay errores
:rtype: bool
"""
OK = 1
# codigo funcion y id no concuerdan con el requests
if requets_raw[:5] != response_raw[:5]:
OK = 0
# la longitud de datos no coincide con la que reporta el esclavo que envia
if len(response_raw[6:]) != (int.from_bytes(response_raw[4:6], "big")):
OK = 0
return OK
|
def get_users(username, public_key):
"""This function returns part of user-data which is related
to users which should be created on remote host.
:param str username: Username of the user, which Ansible will use to
access this host.
:param str public_key: SSH public key of Ansible. This key will be placed
in ``~username/.ssh/authorized_keys``.
:return: A list of the data, related to users
:rtype: list
"""
return [
{
"name": username,
"groups": ["sudo"],
"shell": "/bin/bash",
"sudo": ["ALL=(ALL) NOPASSWD:ALL"],
"ssh-authorized-keys": [public_key]
}
]
|
def stripReverse(s):
"""Returns the string s, with reverse-video removed."""
return s.replace('\x16', '')
|
def validate_pixels(pixels):
"""
Checks if given string can be used as a pixel value for height or width.
Height or Width or assumed to never surpass 10000
"""
try:
pixels = int(pixels)
except:
return False
return 0 < pixels < 10000
|
def cleaning_space(string_inst):
"""arg : instruction line
return : (string) instruction line cleared of space and tab before and after """
while string_inst[0] == ' ' or string_inst[0]== "\t":
string_inst = string_inst[1:]
while string_inst[-1] == ' ' or string_inst[-1] == '\t':
string_inst = string_inst[:-1]
return string_inst
|
def get_jaccard_score(a, s):
"""
Function that computes the jaccard score between two sequences
Input: two tuples; (start index of answer, length of answer). Guaranteed to overlap
Output: jaccard score computed for the two sequences
"""
a_start = a[0]
a_end = a[0]+a[1]-1
start = s[0]
end = s[0]+s[1]-1
pred_ids = set(range(start, end+1))
label_ids = set(range(a_start, a_end+1))
jacc = len(pred_ids.intersection(label_ids)) / len(pred_ids.union(label_ids))
return jacc
|
def map2dict(darray):
""" Reformat a list of maps to a dictionary
"""
return {v[0]: v[1] for v in darray}
|
def one(iter):
""" Returns True if exactly one member of iter has a truthy value, else False.
Args:
iter (iterable): an iterable containing values that can be evaluated as bools.
Returns:
(bool): True if exactly one member is truthy, else False.
>>> one({"a", None, True})
False
>>> one({None, None, None})
False
>>> one({True, False, False})
True
>>> one({False, False, True})
True
"""
return len([s for s in iter if s]) == 1
|
def group(l):
"""
Group a list into groups of adjacent elements. e.g.
> group(list("AAABBCCDBBBBA"))
[("A", 3), ("B", 2), ("C", 2), ("D", 1), ("B", 4), ("A", 1)]
"""
result = []
previous = None
count = 0
for elem in l:
if previous is None:
previous = elem
count = 1
elif previous == elem:
count += 1
else:
result.append((previous, count))
previous = elem
count = 1
if previous is not None:
result.append((previous, count))
return result
|
def poly2(k, x):
""" line function """
return k[0] * x * x + k[1] * x + k[2]
|
def _component_name(idx):
"""Helper to get the name of a component."""
return "component_%i" % idx
|
def xml_has_javascript(data):
"""
Checks XML for JavaScript. See "security" in :doc:`customization <../../customization>` for
additional information.
:param data: Contents to be monitored for JavaScript injection.
:type data: str, bytes
:return: ``True`` if **data** contains JavaScript tag(s), otherwise ``False``.
:rtype: bool
"""
from re import search, IGNORECASE, MULTILINE
data = str(data, encoding='UTF-8')
print(data)
# ------------------------------------------------
# Handles JavaScript nodes and stringified nodes.
# ------------------------------------------------
# Filters against "script" / "if" / "for" within node attributes.
pattern = r'(<\s*\bscript\b.*>.*)|(.*\bif\b\s*\(.?={2,3}.*\))|(.*\bfor\b\s*\(.*\))'
found = search(
pattern=pattern,
string=data,
flags=IGNORECASE | MULTILINE
)
if found is not None:
return True
# ------------------------------------------------
# Handles JavaScript injection into attributes
# for element creation.
# ------------------------------------------------
from xml.etree.ElementTree import fromstring
parsed_xml = (
(attribute, value)
for elm in fromstring(data).iter()
for attribute, value in elm.attrib.items()
)
for key, val in parsed_xml:
if '"' in val or "'" in val:
return True
# It is (hopefully) safe.
return False
|
def filter_availability(availability, start_date, end_date):
"""
Removes dates that are not in the range of start_date.day to end_date.day
"""
filtered_availability = []
for time_range in availability:
if time_range["start"] < start_date:
continue
if time_range["end"] <= end_date:
filtered_availability.append(time_range)
return filtered_availability
|
def reformat_slice(
sl_in: slice,
limit_in: int,
mirror: bool) -> slice:
"""
Reformat the slice, with optional reverse operation.
Note that the mirror operation doesn't run the slice backwards across the
same elements, but rather creates a mirror image of the slice. This is
to properly accommodate the data segment reverse symmetry transform.
Parameters
----------
sl_in : slice
From prior processing, it is expected that `sl_in.step` is populated,
and `sl_in.start` is non-negative, and `sl_in.stop` is non-negative or
`None` (only in th event that `sl_in.step < 0`.
limit_in : int
The upper limit for the axis to which this slice pertains.
mirror : bool
Create the mirror image slice?
Returns
-------
slice
"""
if sl_in.step is None:
raise ValueError('input slice has unpopulated step value')
if sl_in.start is not None and sl_in.start < 0:
raise ValueError('input slice has negative start value')
if sl_in.stop is not None and sl_in.stop < 0:
raise ValueError('input slice has negative stop value')
if mirror:
# make the mirror image of the slice, the step maintains the same sign,
# and will be reversed by the format function
if sl_in.step > 0:
start_in = 0 if sl_in.start is None else sl_in.start
stop_in = limit_in if sl_in.stop is None else sl_in.stop
if sl_in.step > (stop_in - start_in):
step_in = stop_in - start_in
else:
step_in = sl_in.step
# what is the last included location?
count = int((stop_in - start_in)/float(step_in))
final_location = start_in + count*step_in
return slice(limit_in - final_location, limit_in - start_in, step_in)
else:
start_in = limit_in - 1 if sl_in.start is None else sl_in.start
stop_in = -1 if sl_in.stop is None else sl_in.stop
if sl_in.step < (stop_in - start_in):
step_in = stop_in - start_in
else:
step_in = sl_in.step
count = int((stop_in - start_in) / float(step_in))
final_location = start_in + count*step_in
return slice(limit_in - final_location, limit_in - start_in, step_in)
else:
return sl_in
|
def stringify_dict(d):
"""
If a dict contains callable (functions or classes) values, stringify_dict replaces them with their __name__ attributes.
Useful for logging the dictionary.
"""
str_d = {}
for k,v in d.items():
if isinstance(v, dict):
str_d[k] = stringify_dict(v)
else:
if callable(v):
str_d[k] = v.__name__
elif isinstance(v, list):
str_d[k] = str(v)
else:
str_d[k] = v
return str_d
|
def encrypt(input_string: str, key: int) -> str:
"""
Shuffles the character of a string by placing each of them
in a grid (the height is dependent on the key) in a zigzag
formation and reading it left to right.
>>> encrypt("Hello World", 4)
'HWe olordll'
>>> encrypt("This is a message", 0)
Traceback (most recent call last):
...
ValueError: Height of grid can't be 0 or negative
>>> encrypt(b"This is a byte string", 5)
Traceback (most recent call last):
...
TypeError: sequence item 0: expected str instance, int found
"""
grid = [[] for _ in range(key)]
lowest = key - 1
if key <= 0:
raise ValueError("Height of grid can't be 0 or negative")
if key == 1 or len(input_string) <= key:
return input_string
for position, character in enumerate(input_string):
num = position % (lowest * 2) # puts it in bounds
num = min(num, lowest * 2 - num) # creates zigzag pattern
grid[num].append(character)
grid = ["".join(row) for row in grid]
output_string = "".join(grid)
return output_string
|
def translate_precision_to_integer(precision: str) -> int:
"""This function translates the precision value to indexes used by wikidata
Args:
precision (str): [description]
Returns:
int: wikidata index for precision
"""
if isinstance(precision, int):
return precision
precision_map = {
"gigayear": 0,
"gigayears": 0,
"100 megayears": 1,
"100 megayear": 1,
"10 megayears": 2,
"10 megayear": 2,
"megayears": 3,
"megayear": 3,
"100 kiloyears": 4,
"100 kiloyear": 4,
"10 kiloyears": 5,
"10 kiloyear": 5,
"millennium": 6,
"century": 7,
"10 years": 8,
"10 year": 8,
"years": 9,
"year": 9,
"months": 10,
"month": 10,
"days": 11,
"day": 11,
"hours": 12,
"hour": 12,
"minutes": 13,
"minute": 13,
"seconds": 14,
"second": 14
}
return precision_map[precision.lower()]
|
def build_openlibrary_urls(isbn):
"""Build Open Library urls."""
url = "https://covers.openlibrary.org/b/isbn"
return {
"is_placeholder": False,
"small": "{url}/{isbn}-S.jpg".format(url=url, isbn=isbn),
"medium": "{url}/{isbn}-M.jpg".format(url=url, isbn=isbn),
"large": "{url}/{isbn}-L.jpg".format(url=url, isbn=isbn),
}
|
def remove_emoticon(entry):
""" Remove emoticon from tweet (use in pd.df.apply)
Args:
entry (entry of pandas df): an entry of the tweet column of the
tweet dataframe
Returns:
output: tweet with emoticon remove
"""
output = entry.encode('ascii', 'ignore').decode('ascii')
return output
|
def map_per_image(label, predictions):
"""Computes the precision score of one image.
Parameters
----------
label : string
The true label of the image
predictions : list
A list of predicted elements (order does matter, 5 predictions allowed per image)
Returns
-------
score : double
"""
try:
return 1 / (predictions[:5].index(label) + 1)
except ValueError:
return 0.0
|
def hasgetattr(obj, attr, default=None):
""" Combines hasattr/getattr to return a default if hasattr fail."""
if not hasattr(obj, attr):
return default
return getattr(obj, attr)
|
def get_nearest_n(x, n):
"""Round up to the nearest non-zero n"""
rounded = -(-x // n) * n
return rounded if rounded else n
|
def get_type(value):
"""
Get the type of a Python object.
"""
return type(value).__name__
|
def is_int(value):
""" Return true if can be parsed as an int """
try:
int(value)
return True
except:
return False
|
def is_bool(target: bool) -> bool:
"""Check target is boolean."""
if not isinstance(target, bool):
return False
return True
|
def getTweetUserLocation(tweet):
""" If included, read the user from the tweet and return their self-supplied location"""
if 'user' in tweet and \
tweet['user'] is not None and \
'location' in tweet['user'] :
return tweet['user']['location']
else :
return None
|
def create_variant_slider_filter(min_variant_group: int, max_variant_group: int) -> dict:
"""
Create a variant slider filter to be used in a trace filter sequence.
Args:
min_variant_group:
An integer denoting the variant group on the lower bound.
max_variant_group:
An integer denoting the variant group on the upper bound.
Returns:
A dictionary containing the filter.
"""
return {
'type': 'variantSliderFilter',
'min': min_variant_group,
'max': max_variant_group
}
|
def _partition_2(list_, i, j):
"""Rearrange list_[i:j] so that items < list_[i] are at
the beginning and items >= list_[i] are at the end,
and return the new index for list_[i].
@param list list_: list to partition
@param int i: beginning of partition slice
@param int j: end of partition slice
@rtype: int
>>> _partition_2([1, 5, 2, 4, 3], 1, 4)
3
"""
v = list_[i]
k = i + 1
j -= 1
while k <= j:
if list_[k] < v:
k += 1
else:
list_[k], list_[j] = list_[j], list_[k]
j -= 1
list_[i], list_[j] = list_[j], list_[i]
return j
|
def leap_year(year):
"""Check whether given year is a leap year."""
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
|
def rgb_to_hex(*args: float) -> str: # pragma: no cover
"""Convert RGB colors into hexadecimal notation.
Args:
*args: percentages (0% - 100%) for the RGB channels
Returns:
hexadecimal_representation
"""
red, green, blue = (
int(255 * args[0]),
int(255 * args[1]),
int(255 * args[2]),
)
return f'#{red:02x}{green:02x}{blue:02x}'
|
def element(e, **kwargs):
"""Utility function used for rendering svg"""
s = "<" + e
for key, value in kwargs.items():
s += " {}='{}'".format(key, value)
s += "/>\n"
return s
|
def quantization_error(t_ticks, q_ticks):
"""
Calculate the error, in ticks, for the given time for a quantization of q ticks.
:param t_ticks: time in ticks
:type t_ticks: int
:param q_ticks: quantization in ticks
:type q_ticks: int
:return: quantization error, in ticks
:rtype: int
"""
j = t_ticks // q_ticks
return int(min(abs(t_ticks - q_ticks * j), abs(t_ticks - q_ticks * (j + 1))))
|
def merge(args_array, cfg, log):
"""Function: merge_repo
Description: This is a function stub for merge_repo.merge_repo.
Arguments:
args_array -> Stub argument holder.
cfg -> Stub argument holder.
log -> Stub argument holder.
"""
status = True
if args_array and cfg and log:
status = True
return status
|
def check_unit(number):
"""
The function that check the number and return the unit
Parameter:
number (float) : the answer from calculation
Return:
The unit of the answer
"""
# check if the values is greater than one.
if(number > 1):
# return the unit with "s"
return "square meters"
else:
# otherwise return unit without "s"
return "square meter"
|
def clean_float_value_from_dict_object(dict_object, dict_name, dict_key, post_errors, none_allowed=False, no_key_allowed=False):
"""
This function takes a target dictionary and returns the float value given by the given key.
Returns None if key if not found and appends any error messages to the post_errors list
:param dict_object: (type: dictionary) target object to get integer from
:param dict_name: (type: string) name of target dictionary
:param dict_key: (type: string) target dictionary key
:param post_errors: (type: list) list of error messages
:param none_allowed: (type: boolean) whether Null values are allowed for given key, default is False
:param no_key_allowed: (type: boolean) whether the or not to allow for absence of target key in target dictionary,
default is False
:return: (type: float or None) Integer type value for given target key, or None
"""
if dict_key not in dict_object:
if no_key_allowed:
return None
else:
post_errors.append("{!r} key not found in {!r} object".format(dict_key, dict_name))
elif dict_object[dict_key] is None and not none_allowed:
post_errors.append("Value for {!r} in {!r} object is Null".format(dict_key, dict_name))
elif (dict_object[dict_key] is None and none_allowed is False) and not isinstance(dict_object[dict_key], float) and not isinstance(dict_object[dict_key], int):
post_errors.append("Value for {!r} in {!r} object is not an float".format(dict_key, dict_name))
elif dict_object[dict_key] == '':
post_errors.append("Value for {!r} in {!r} object is and empty string".format(dict_key, dict_name))
else:
return float(dict_object[dict_key])
|
def skip_mul(n):
"""Return the product of n * (n - 2) * (n - 4) * ...
>>> skip_mul(5) # 5 * 3 * 1
15
>>> skip_mul(8) # 8 * 6 * 4 * 2 * 0
0
"""
if n == 0:
return 0
else:
return n * skip_mul(n - 2)
|
def column_to_list(data, index):
"""Return a list with values of a specific column from another list
Args:
data: The list from where the data will be extracted
index: The index of the column to extract the values
Returns:
List with values of a specific column
"""
column_list = []
# Tip: You can use a for to iterate over the samples, get the feature by index and append into a list
for sample in data:
column_list.append(sample[index])
return column_list
|
def escape_formatting(username: str) -> str:
"""Escapes Discord formatting in the given string."""
return username.replace("_", "\\_").replace("*", "\\*")
|
def resource_from_path(path):
"""Get resource name from path (first value before '.')
:param path: dot-separated path
:return: resource name
"""
index = path.find('.')
if index == -1:
return path
return path[:index]
|
def determine_edit_type(values, previous_values):
""" Determine whether an edit is editorial (0) or content (1).
This is dependent on whether there are substantial additions in content volume.
It is only a content contribution if:
1) both text and links/urls are added (not text in isolation)
2) images are added.
Editorial counts:
- words only
- categories
- any deletions
"""
changes = {key: values[key] - previous_values.get(key, 0) for key in values}
if changes["images"] > 0:
return "content"
elif changes["words"] > 0 and changes["links"]+changes["urls"] > 0:
return "content"
else:
return "editorial"
|
def ph_color_code(value):
"""
:param value: This is a pH value which is having its color multiplexed.
Description:
This takes a pH value as input and returns a color to be used in the form of a string.
"""
if value > 12.6:
return 'navy'
elif value >11.2:
return 'blue'
elif value >9.8:
return 'dodgerblue'
elif value >8.4:
return 'aqua'
elif value >7.0:
return 'darkgreen'
elif value >5.6:
return 'lawngreen'
elif value >4.2:
return 'yellow'
elif value >2.8:
return 'orange'
elif value >1.4:
return 'indianred'
else:
return 'red'
|
def parse_spec(spec):
"""Return parsed id and arguments from build spec."""
if isinstance(spec, dict):
return spec['type'], spec.get('args', {})
if isinstance(spec, (tuple, list)) and isinstance(spec[0], str):
return spec[0], {} if len(spec) < 2 else spec[1]
if isinstance(spec, str):
return spec, {}
raise ValueError('Invalid build spec: {}'.format(spec))
|
def type_match(node_a, node_b):
""" Checks whether the node types of the inputs match.
:param node_a: First node.
:param node_b: Second node.
:return: True if the object types of the nodes match, False otherwise.
:raise TypeError: When at least one of the inputs is not a dictionary
or does not have a 'node' attribute.
:raise KeyError: When at least one of the inputs is a dictionary,
but does not have a 'node' key.
"""
return isinstance(node_a['node'], type(node_b['node']))
|
def my_function(lhs: int, rhs: int) -> int:
"""Add two numbers together
Parameters
----------
lhs: int
first integer
rhs: int
second integer
Raises
------
value errror if lhs == 0
Examples
--------
>>> my_function(1, 2)
3
>>> my_function(0, 2)
Traceback (most recent call last):
...
ValueError
"""
if lhs == 0:
raise ValueError()
return lhs + rhs
|
def _len(L):
"""
Determines the length of ``L``.
Uses either ``cardinality`` or ``__len__`` as appropriate.
EXAMPLES::
sage: from sage.misc.mrange import _len
sage: _len(ZZ)
+Infinity
sage: _len(range(4))
4
sage: _len(4)
Traceback (most recent call last):
...
TypeError: object of type 'sage.rings.integer.Integer' has no len()
"""
try:
return L.cardinality()
except AttributeError:
return len(L)
|
def str_between(string, start, end=None):
"""(<abc>12345</def>, <abc>, </def>) -> 12345"""
content = string.split(start, 1)[-1]
if end is not None:
content = content.rsplit(end, 1)[0]
return content
|
def _get_nested_vulnerability(data, key_path=None):
"""Get nested vulnerability."""
if key_path:
for component in key_path.split('.'):
data = data[component]
return data
|
def search(target: int, prime_list: list) -> bool:
"""
function to search a number in a list using Binary Search.
>>> search(3, [1, 2, 3])
True
>>> search(4, [1, 2, 3])
False
>>> search(101, list(range(-100, 100)))
False
"""
left, right = 0, len(prime_list) - 1
while left <= right:
middle = (left + right) // 2
if prime_list[middle] == target:
return True
elif prime_list[middle] < target:
left = middle + 1
else:
right = middle - 1
return False
|
def get_max_value(register):
"""Get maximum value from register."""
return max(register.values())
|
def _scalarise(value):
""" Converts length 1 lists to singletons """
if isinstance(value, list) and len(value) == 1:
return value[0]
return value
|
def iterate(source, *keys):
"""Iterate a nested dict based on list of keys.
:param source: nested dict
:param keys: list of keys
:returns: value
"""
d = source
for k in keys:
if type(d) is list:
d = d[int(k)]
elif k not in d:
d[k] = {}
else:
d = d[k]
return d
|
def predict_callback(data):
"""
user defined
:param data: dict
:return:
"""
kwargs = data.get('kwargs')
# print(kwargs)
num = kwargs.get('num')
if num > 10:
return True
return False
|
def floatToFixed(value, precisionBits):
"""Converts a float to a fixed-point number given the number of
precisionBits. Ie. int(round(value * (1<<precisionBits))).
"""
return int(round(value * (1<<precisionBits)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.