content
stringlengths 42
6.51k
|
---|
def n50(values):
"""Return the N50 of the list of numbers"""
values.sort(reverse=True)
target = sum(values) / 2.
total = 0
for v in values:
total += v
if total >= target:
return v
return 0
|
def _method_1(a, b):
"""Thought of this, on the fly, January 15, 2022."""
import string
o = 0
for character in string.ascii_lowercase:
a_count = a.count(character)
b_count = b.count(character)
difference = abs(a_count - b_count)
if difference > 0:
o += difference
return o
|
def __is_victory(player_state, victory_condition):
"""
Returns true if the provided state represents a provided victory state
:param player_state: The state under evaluation
:param victory_condition: The victory condition to test against
:return: True if the state represents the provided victory condition, false otherwise
"""
mask = player_state & victory_condition
if mask ^ victory_condition == 0:
return True
|
def strip_enclosing_quotes(string: str) -> str:
"""Strip leading/trailing whitespace and remove any enclosing quotes"""
stripped = string.strip()
# Need to check double quotes again in case they're nested inside
# single quotes
for quote in ['"', "'", '"']:
if stripped.startswith(quote) and stripped.endswith(quote):
stripped = stripped[1:-1]
return stripped
|
def summ(sin: float, cos: float) -> float:
"""
Calculate the Z2n power value.
Parameters
----------
sin : float
A float that represents the sine value.
cos : float
A float that represents the cosine value.
Returns
-------
value : float
A float that represents the Z2n power.
"""
value = sin + cos
return value
|
def unwrap_distributed(state_dict):
"""
Unwraps model from DistributedDataParallel.
DDP wraps model in additional "module.", it needs to be removed for single
GPU inference.
:param state_dict: model's state dict
"""
new_state_dict = {}
for key, value in state_dict.items():
new_key = key.replace('module.1.', '')
new_key = new_key.replace('module.', '')
new_state_dict[new_key] = value
return new_state_dict
|
def skip_zone_record(zone_record):
"""Whether a zone record should be skipped or not.
Records are skipped if they are empty or start with
a # (indicating a comment).
:param zone_record: Full zone record, including the command (e.g. ADD).
:returns: True if the record should be skipped, false otherwise.
"""
zone_record = zone_record.strip()
return not zone_record or zone_record[:1] == "#"
|
def get_tag_list(keys, tags):
"""
Returns a list of dicts with tags to act on
keys : set of keys to get the values for
tags : the dict of tags to turn into a list
"""
tag_list = []
for k in keys:
tag_list.append({'Key': k, 'Value': tags[k]})
return tag_list
|
def hex2text(hex):
"""
Convert hex to text
:param hex: hex to convert
:return: text string
"""
return ''.join(chr(int(hex[i:i+2], 16)) for i in range(0, len(hex), 2))
|
def vector_subtract(v, w):
"""subtrai elementos correspondentes"""
return [v_i - w_i
for v_i, w_i in zip(v, w)]
|
def find_parent_row(parsed_rows, parent_name):
"""
finds a parent row by a given name
"""
for row in parsed_rows:
task_name = row['name']
if not task_name:
continue
if task_name == parent_name:
return row
return None
|
def label_to_AI(labels):
"""Transforms a list of {0, 1} labels into {-, AI} labels"""
return ['AI' if lab == 1 else '-' for lab in labels]
|
def is_none(x):
"""
Helper function since x == None doesn't work well on arrays. Returns True if x is None.
"""
return isinstance(x, type(None))
|
def available_through_years(available_year_list, start_year):
"""Return a list of available through/ending years that are >= the start year.
:param available_year_list: List of available years from the input file
:type available_year_list: list
:param start_year: The start year chosen
:type start_year: int
:return: list of available through/ending years
"""
# Construct options for drop down based on input parameters
options = []
for i in available_year_list:
if int(i['value']) >= int(start_year):
options.append(i)
return options
|
def ip2string(splited_ip):
"""
Funcion que devuelve el string apropiado para la lista de la IP
fragmentada
"""
return str(splited_ip[0]) + "." + str(splited_ip[1]) + "." + str(splited_ip[2]) + "." + str(splited_ip[3])
|
def print_dependencies_check(data_string: str) -> str:
"""
Prints the results of the dependencies check
"""
try:
from colorama import Fore, Style, init
init()
start_ok_color = Fore.GREEN
start_fault_color = Fore.RED
stop_color = Style.RESET_ALL
except ImportError as _:
start_ok_color = start_fault_color = stop_color = ""
if data_string is None:
return f"{start_ok_color}OK{stop_color}"
return f"{start_fault_color}{data_string}{stop_color}"
|
def mean(dictionary: dict):
"""
Author: SW
Returns the mean of each value in the dictionary for each key
:param dictionary: dict: an input dictionary of iterables
:return: dict: dictionary with the mean of all values
"""
for key, value in dictionary.items():
dictionary[key] = sum(value) / len(value)
return dictionary
|
def adjust_val_to_360(val):
"""
Take in a single numeric (or null) argument.
Return argument adjusted to be between
0 and 360 degrees.
"""
if not val and (val != 0):
return None
else:
try:
return float(val) % 360
except ValueError:
return val
|
def get_interaction_dict(clean_pdbs, verbose=False):
"""Generates interaction dictionary. This is a dictionary of dictionaries. Each chain id is the key of the first
dictionary, and as value a dictionary. The dictionary inside has tuples of interactiong resiudes (their number)
from chain 1 to 2 as keys and for value it has a tuple of chain object 1, chain object 2 and interaction resiudes from 2 to 1:
For instance:
{Chain1 id : {
(first interacting residues number from chain 1 to 2): (Chain1 instance,
Chain2 instance,
interacting residues number from chain 2 to 1)
}
(second interacting resiudes...) : (... , ... , ... )
...
Chain2 id : {
(first interacting residues number from chain 2 to 1): (Chain2 instance,
(Chain1 instance,
interacting residues number from chain 1 to 1)
(second interacting resiudes...) : (... , ... , ... )
...
"""
interaction_dict = dict()
if verbose:
print("Generating interaction dictionary...")
for pdb in clean_pdbs:
chain1, chain2 = list(pdb.get_chains())
inter1_2, inter2_1 = chain1.get_interactions(chain2) # Generates interaction tuples,
# from chain 1 to 2 and from 2 to 1. For instance:
# inter1_2 = (2,40,120)
# inter2_1=(34, 20)
if inter1_2 != (): # If tuple is not empty (there is an interaction)
interaction_dict.setdefault(chain1.id, dict())[inter1_2] = (chain1, chain2, inter2_1) # Update dictionary
if inter2_1 != (): # Same for the other interaction
interaction_dict.setdefault(chain2.id, dict())[inter2_1] = (chain2, chain1, inter1_2)
if verbose:
print("Interaction dictionary generated")
return interaction_dict
|
def _update_post_node(node, options, arguments):
"""
Extract metadata from options and populate a post node.
"""
node["date"] = arguments[0] if arguments else None
node["tags"] = options.get("tags", [])
node["author"] = options.get("author", [])
node["category"] = options.get("category", [])
node["location"] = options.get("location", [])
node["language"] = options.get("language", [])
node["redirect"] = options.get("redirect", [])
node["title"] = options.get("title", None)
node["image"] = options.get("image", None)
node["excerpt"] = options.get("excerpt", None)
node["exclude"] = "exclude" in options
node["nocomments"] = "nocomments" in options
return node
|
def _lang_range_check(range, lang):
"""
Implementation of the extended filtering algorithm, as defined in point
3.3.2, of U{RFC 4647<http://www.rfc-editor.org/rfc/rfc4647.txt>}, on
matching language ranges and language tags.
Needed to handle the C{rdf:PlainLiteral} datatype.
@param range: language range
@param lang: language tag
@rtype: boolean
@author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">}
Taken from `RDFClosure/RestrictedDatatype.py`__
.. __:http://dev.w3.org/2004/PythonLib-IH/RDFClosure/RestrictedDatatype.py
"""
def _match(r, l_):
"""
Matching of a range and language item: either range is a wildcard
or the two are equal
@param r: language range item
@param l_: language tag item
@rtype: boolean
"""
return r == "*" or r == l_
rangeList = range.strip().lower().split("-")
langList = lang.strip().lower().split("-")
if not _match(rangeList[0], langList[0]):
return False
if len(rangeList) > len(langList):
return False
return all(_match(*x) for x in zip(rangeList, langList))
|
def ind_l1_ball( w, lamb=1 ):
"""! Compute the indication function of the \f$\ell_1\f$-ball
Parameters
----------
@param w : input vector
@param lamb : penalty paramemeter
Returns
----------
@retval : whether the input is in $\ell_1$-ball
"""
# norm_w = np.linalg.norm(w, ord=1)
# if norm_w > lamb:
# return np.inf
# else:
# return 0.0
return 0.0
|
def get_pass_room_count_honeycomb(position):
"""
1-depth room count : 1 (0-1)
2-depth room count : 6 (2-7)
3-depth romm count : 12 (8-19)
4-depth romm count : 18 (20-37)
N-depth room count : 6*(N-1) (2+(6*(N-2), 1+(6*N-1))
"""
if position == 1:
return 1
count = 2
left_edge = 2
right_edge = 7
while True:
if position >= left_edge and position <= right_edge:
return count
left_edge += (count-1)*6
right_edge += count*6
count += 1
if left_edge > 1000000000:
break
return -1
|
def sum_dicts(source, dest):
""" Adds values from source to corresponding values in dest.
This is intended for use as a merge_func parameter to merge_value.
"""
for k, v in source.items():
dest.setdefault(k, 0)
dest[k] += v
return dest
|
def versiontuple(v: str) -> tuple:
"""
Function to converts a version string into a tuple that can be compared, copied from
https://stackoverflow.com/questions/11887762/how-do-i-compare-version-numbers-in-python/21065570
"""
return tuple(map(int, (v.split("."))))
|
def mem_to_label(value, mem_split):
"""turn mem to label"""
for index, split in enumerate(mem_split):
if value <= split:
return index
|
def is_listlike(x):
"""
>>> is_listlike("foo")
False
>>> is_listlike(5)
False
>>> is_listlike(b"foo")
False
>>> is_listlike([b"foo"])
True
>>> is_listlike((b"foo",))
True
>>> is_listlike({})
True
>>> is_listlike(set())
True
>>> is_listlike((x for x in range(3)))
True
>>> is_listlike(range(5))
True
"""
return hasattr(x, "__iter__") and not isinstance(x, (str, bytes))
|
def hass_to_unifi_brightness(value):
"""Convert hass brightness 0..255 to unifi 1..6 scale."""
return max(1, round((value / 255) * 6))
|
def denormalize(x):
"""denormalize image
CelebA images are mapped into [-1, 1] interval before training
This function applies denormalization
Arguments:
x -- image
"""
x = x * .5 + .5
return x
|
def rotations(integer):
"""gibt eine Liste der Rotationen einer Zahl (197 -> 971 and 719) aus
"""
zahl = str(integer)
rot = []
for i in range(len(zahl)-1): # -1 weg, wenn integer mit ausgegeben werden soll
zahl = zahl[-1] + zahl[0:-1]
rot.append(int(zahl))
return rot
|
def by_hex(fg, bg = "#000000", attribute = 0):
"""
Return string with ANSI escape code for set text colors
fg: html hex code for text color
bg: html hex code for background color
attribute: use Attribute class variables
"""
# Delete #
fg = fg.replace("#", "")
bg = bg.replace("#", "")
fg_r = int(fg[0:2], 16)
fg_g = int(fg[2:4], 16)
fg_b = int(fg[4:6], 16)
fg_rgb = f"{fg_r};{fg_g};{fg_b}"
bg_r = int(bg[0:2], 16)
bg_g = int(bg[2:4], 16)
bg_b = int(bg[4:6], 16)
bg_rgb = f"{bg_r};{bg_g};{bg_b}"
return f"\033[{attribute};38;2;{fg_rgb};48;2;{bg_rgb}m"
|
def is_magic_variable(var_name):
"""
Determines if a variable's name indicates that it is a 'magic variable'.
That is, it starts and ends with two underscores. e.g. '__foo__'. These
variables should not be injected.
Args:
var_name the name of the variable.
Returns:
True if var_name starts and ends with two underscores, False
otherwise.
"""
return var_name[0] == '_' and var_name[1] == '_' and \
var_name[len(var_name) - 1] == '_'and \
var_name[len(var_name) - 2] == '_'
|
def edge_count(adjList):
"""Compute number of edges in a graph from its adjacency list"""
edges = {}
for id, neigh in enumerate(adjList):
for n in neigh:
edges[max(n, id), min(n, id)] = id
return len(edges)
|
def get_ruler_auto_size(screenwidth, worldwidth):
"""get most appropriate unit for zoom level"""
unit = 1
order = 0
if worldwidth == 0.0:
return unit
while True:
# find pixels per unit
pixelsize = screenwidth / (worldwidth / float(unit))
if pixelsize < 50 and order < 20:
unit *= 10
order += 1
else:
break
return unit
|
def is_same_url(a, b):
"""Check if different forms of same URL match"""
return a and b and a.strip().strip('/') == b.strip().strip('/')
|
def clamp(x: float, minimum=0.0, maximum=1.0):
"""Clamp a number.
This is a synonym of clipping.
Parameters
----------
x
minimum
maximum
"""
return max(min(x, maximum), minimum)
|
def delta_masso_from_soga(s_orig, s_new, m_orig):
"""Infer a change in mass from salinity"""
delta_m = m_orig * ((s_orig / s_new) - 1)
return delta_m
|
def viewMethod(obj, method):
"""Fetch view method of the object
obj - the object to be processed
method - name of the target method, str
return target method or AttributeError
>>> callable(viewMethod(dict(), 'items'))
True
"""
viewmeth = 'view' + method
ometh = getattr(obj, viewmeth, None)
if not ometh:
ometh = getattr(obj, method)
return ometh
|
def string_manipulation(ans_lst):
"""
change the type of answer from list to string
:param ans_lst: list, the process of the answer with list type
:return: str, the process of the answer with string type
"""
word = ""
for i in range(len(ans_lst)):
word += ans_lst[i]
return word
|
def h2(text):
"""Heading 2.
Args:
text (str): text to make heading 2.
Returns:
str: heading 2 text.
"""
return '## ' + text + '\r\n'
|
def verifyInfo(in_dict, sample_dict):
"""Verify whether the input dictionary is valid.
An input dictionary is valid when 1) all the keys in the sample dictionary
can be found in the input dictionary; 2) values in the input dictionary
should have the same datatype as what in the smaple dictionary
Args:
in_dict (dict): An input dictionary.
sample_dict (dict): An sample dictionary.
Returns:
(tuple): tuple containing:
bool: True if the input dictionary is valid else False.
str: Detialed message about the checking status.
"""
for key, ddtype in sample_dict.items():
if key not in in_dict:
msg = "{} key not found".format(key)
return False, msg
if type(in_dict[key]) is not ddtype:
msg = "{} value not correct type".format(key)
return False, msg
return True, ""
|
def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
if len(value) > length:
return value[:length] + '...'
return value
|
def parse_original_im_name(im_name, parse_type='id'):
"""Get the person id or cam from an image name."""
assert parse_type in ('id', 'cam')
if parse_type == 'id':
parsed = -1 if im_name.startswith('-1') else int(im_name[:4])
else:
parsed = int(im_name[4]) if im_name.startswith('-1') \
else int(im_name[6])
return parsed
|
def is_folder(item):
"""
Check the item's 'type' to determine whether it's a folder.
"""
return item['type'] == "folder"
|
def cleanRawText(text):
"""
vtype text: str
rtype text: str / utf8
"""
text = text.encode('ascii', 'replace')
text = text.replace(b'?', b'')
text = text.replace(b'\r\n', b'\n')
text = text.replace(b'\n', b' ')
text = text.strip()
text = text.decode('utf8')
return(text)
|
def needs_marker(string, pattern, marker):
"""Check if a substring is following a certain marker.
Args:
string (str) - string to search in
pattern (str) - pattern to search for
marker (str) - marker to be followed by pattern, can be U, C, M, etc.
"""
pattern_start_pos = string.find(pattern)
if pattern_start_pos != -1:
if pattern_start_pos < 2:
return True
marker_check_pos = pattern_start_pos - 2
if string[marker_check_pos] != marker and 'L(' not in string:
return True
return False
|
def get_relative_error(approximation, real):
"""Return the relative error of two values"""
return abs(approximation - real) / real
|
def svg_polygon(coordinates, color):
"""
Create an svg triangle for the stationary heatmap.
Parameters
----------
coordinates: list
The coordinates defining the polygon
color: string
RGB color value e.g. #26ffd1
Returns
-------
string, the svg string for the polygon
"""
coord_str = []
for c in coordinates:
coord_str.append(",".join(map(str, c)))
coord_str = " ".join(coord_str)
polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color)
return polygon
|
def value_left(self, right):
"""
Returns the value of the right type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression.
"""
return right.value if isinstance(right, self.__class__) else right
|
def update_pesos(pesos, muestra, delta):
""" Funcion que actualiza pesos """
n_pesos = []
for m, p in zip(muestra, pesos):
p = p + m * delta
n_pesos.append(p)
return n_pesos
|
def getSquareDistanceOriginal(p1, p2):
"""
Square distance between two points
"""
dx = p1['x'] - p2['x']
dy = p1['y'] - p2['y']
return dx * dx + dy * dy
|
def objectIdentifier(callingObject):
"""Returns a human-readable string identifier for a provided object.
callingObject -- the object to be identified
This method figures out the best name to use in identifying an object, taking queues from:
- its _name_ attribute, if avaliable
- more to be added as this evolves...
Returns a string that can be used to identify the object to the user.
"""
if hasattr(callingObject, '_name_'): #object has a _name_ attribute
name = getattr(callingObject, '_name_')
if name: #name is not False (or None)
return name #just return the name
else: #name is False or None
return callingObject.__class__.__name__ + " @ " + hex(id(callingObject)) #_name_ is None or False, return a reinterpretation of the str representation
else:
return callingObject.__class__.__name__ + " @ " + hex(id(callingObject))
|
def _get_policy_name(policy_arn):
"""
Translate a policy ARN into a full name.
"""
return policy_arn.split(':')[-1].split('/')[-1]
|
def isstringlike(item):
"""
Checks whether a term is a string or not
"""
ret = 1
try:
float(item)
ret = 0
except ValueError:
pass
return ret
|
def unbox_usecase(x):
"""
Expect a list of numbers
"""
res = 0
for v in x:
res += v
return res
|
def godel(x,y):
"""
>>> godel(3, 81)
3547411905944302159585997044953199142424
>>> godel(51, 29)
154541870963391800995410345984
"""
return (2**x)*(3**y)
|
def VerifyFileOwner(filename):
"""Verifies that <filename> is owned by the current user."""
# On Windows server OSs, files created by users in the
# Administrators group will be owned by Administrators instead of
# the user creating the file so this check won't work. Since on
# Windows GRR uses its own temp directory inside the installation
# dir, whenever someone can modify that dir it's already game over
# so this check doesn't add much.
del filename
return True
|
def calculate_total_bill(subtotal):
"""
(float) -> float
subtotal is passed through as an input
HST_RATE variable in this function is multiplied by inputted variable
Function returns the resulting variable "total", rounded and formatted to 2 decimal points.
Variable "total" is then rounded to the nearest 5 cents using the following nickel rounding scheme standard rules in Canada:
0.01 to 0.02 will round down to 0.00. 0. 03 to 0.04 will round up to 0.05. 0.06 to 0.07 will round down to 0.05.
0.08 to 0.09 will round up to 0.10
>>> calculate_total_bill(3.0)
3.40
>>> calculate_total_bill(6.67)
7.55
>>> calculate_total_bill(2.05)
2.30
"""
HST_RATE = 1.13
total_bill = subtotal *HST_RATE
return format(round(0.05 * round(float(total_bill)/0.05), 2), '.2f')
|
def startswith_field(field, prefix):
"""
RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING
"""
if prefix.startswith("."):
return True
# f_back = len(field) - len(field.strip("."))
# p_back = len(prefix) - len(prefix.strip("."))
# if f_back > p_back:
# return False
# else:
# return True
if field.startswith(prefix):
if len(field) == len(prefix) or field[len(prefix)] == ".":
return True
return False
|
def intToRoman(num):
"""
:type num: int
:rtype: str
"""
dict_ = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
result = ''
remain = num
while remain != 0:
for i in sorted(dict_, reverse=True):
if i <= remain:
result += dict_.get(i)
remain -= i
break
return result
|
def addGMSHLine( number, startPoint, endPoint ):
""" Add a line to GMSH """
string = "Line(" + str(number) + ") = {" + str(startPoint) + ", " + str(endPoint) + "};"
return string
|
def trim(data):
"""removes spaces from a list"""
ret_data = []
for item in data:
ret_data += item.replace(' ', '')
return ret_data
|
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.2f %s" % (num, x)
num /= 1024.0
|
def normalize_copy(numbers):
"""
normalize_copy
:param numbers:
:return:
"""
numbers = list(numbers)
total = sum(numbers)
result = []
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
|
def tag2ot(ote_tag_sequence):
"""
transform ote tag sequence to a sequence of opinion target
:param ote_tag_sequence: tag sequence for ote task
:return:
"""
n_tags = len(ote_tag_sequence)
ot_sequence = []
beg, end = -1, -1
for i in range(n_tags):
tag = ote_tag_sequence[i].split("-")[0]
if len(ote_tag_sequence[i].split("-")) > 1:
polarity = ote_tag_sequence[i].split("-")[-1]
else:
polarity = "NEU"
if tag == 'S':
ot_sequence.append(tuple([i, i, polarity]))
elif tag == 'B':
beg = i
elif tag == 'E':
end = i
if end > beg > -1:
ot_sequence.append(tuple([beg, end, polarity]))
beg, end = -1, -1
return ot_sequence
|
def _get_priority_restrictions_regex(max_priority):
"""Returns something like:
((?!.*tp)|(?=.*tp[0-2]))"""
return "((?!.*tp)|(?=.*tp[0-%s]))" % max_priority
|
def grid_width(cluster_num, i=0): # 3 closest is 4 so return 2; 6 closest is 9 so return 3; 11 closest is 16 so return 4, etc.
"""
Function to acquire appropriate (square) grid width for plotting.
"""
while i**2 < cluster_num:
i+=1;
return i
|
def getOpString(mean, std_dev):
"""
Generate the Operand String to be used in workflow nodes to supply
mean and std deviation to alff workflow nodes
Parameters
----------
mean: string
mean value in string format
std_dev : string
std deviation value in string format
Returns
-------
op_string : string
"""
str1 = "-sub %f -div %f" % (float(mean), float(std_dev))
op_string = str1 + " -mas %s"
return op_string
|
def __render_one_rtsec_element(element):
"""
Takes a message block rich text section element and renders it to a string, which it returns.
Private method.
"""
ret = ""
element_type = element.get('type', None)
if element_type == "text":
# This can contain an optional style block that contains a hash with keys that are useful, and values that are true.
ret += "<span class='"
formats = element.get('style', {})
ret += " ".join(formats.keys())
ret += "'>"
ret += element.get('text', '')
ret += "</span>"
elif element_type == "link":
ret += f"<a href={element.get('url', 'ERROR: link element contains no URL')}>{element.get('text', element.get('url', 'ERROR: link element contains no URL or text'))}</a>"
else:
ret += f"ERROR: rich_text_section element type {element_type}: unknown"
return ret
|
def speed_of_sound_gas(k, R, T):
"""
k : ratio of specific heats
R : gas constant
T : absolute temperature
from http://www.engineeringtoolbox.com/speed-sound-d_519.html
"""
return (k * R * T) ** 0.5
|
def getSim(w1, w2):
"""
:param w1: winner cell which should be a list
:param w2:
:return: simularity score
"""
w1 = set(w1)
w2 = set(w2)
return len(w1 & w2) / len(w1 | w2)
|
def trans_type(code):
"""Translates transaction code for human readability.
:param code: The code to be converted
:type code: str
:return: Human-readable transaction type
:rtype: str
"""
if code == "B":
return "Beginning Balance"
if code == "C":
return "Check"
if code == "D":
return "Deposit"
if code == "W":
return "Withdrawal"
|
def make_values(repo_pkg, cur_ver, new_ver, branch, check_result):
"""
Make values for push_create_pr_issue
"""
values = {}
values["repo_pkg"] = repo_pkg
values["cur_version"] = cur_ver
values["new_version"] = new_ver
values["branch"] = branch
values["check_result"] = check_result
return values
|
def fibonacci(nth):
""" recursive form, according to definition
"""
if nth>30:
print("nth is too big for ")
return -1
elif nth> 2:
return fibonacci(nth-1) + fibonacci(nth-2)
else:
if nth== 1:
return 1
if nth== 2:
return 1
|
def idxs_of_duplicates(lst):
""" Returns the indices of duplicate values.
"""
idxs_of = dict({})
dup_idxs = []
for idx, value in enumerate(lst):
idxs_of.setdefault(value, []).append(idx)
for idxs in idxs_of.values():
if len(idxs) > 1:
dup_idxs.extend(idxs)
return dup_idxs
|
def _represent_args(*args, **kwargs):
"""Represent the aruments in a form suitable as a key (hashable)
And which will be recognisable to user in error messages
>>> print(_represent_args([1, 2], **{'fred':'here'}))
[1, 2], fred='here'
"""
argument_strings = [repr(a) for a in args]
keyword_strings = ["=".join((k, repr(v))) for k, v in kwargs.items()]
return ", ".join(argument_strings + keyword_strings)
|
def generate_file_from_template(template_path, output_path, template_values):
"""Write to file.
Args:
template_path (str): Input template path
output_path (str): Path of the output file
template_values (dict): Values to replace the
ones in the input template
Returns:
bool: Whether or not file has been generated
"""
try:
with open(template_path, 'r') as in_tmpl:
tmpl_contents = in_tmpl.read()
out_contents = tmpl_contents.format(**template_values)
with open(output_path, 'w') as out_file:
out_file.write(out_contents)
return True
except EnvironmentError:
pass
return False
|
def sign(x):
"""Sign of a number. Note only works for single values, not arrays."""
return -1 if x < 0 else 1
|
def plan_cost(plan):
"""Convert a plan to a cost, handling nonexistent plans"""
if plan is None:
return float('inf')
else:
return len(plan)
|
def bool_(x):
"""Implementation of `bool`."""
return x.__bool__()
|
def format_price(number):
"""[It takes a float value and converts it to 2 decimal places and appends a '$' in front.
Returns the converted value.]
Args:
number ([float]): [The raw float value with multiple decimal places.]
"""
#pylint: disable=consider-using-f-string
return("-$" if number<0 else "$")+"{0:.2f}".format(abs(number))
|
def parseFilterStr(args):
"""Convert Message-Filter settings in '+<addr> -<addr> ...' format to a dict of the form
{ '<addr>':True, '<addr>':False, ... }
Returns a list: ['<prefix>', filters]
"""
out = {}
if isinstance(args,str):
args = [args]
prefix = None
for arg in args:
head = None
for plus in arg.split('+'):
minus = plus.split('-')
plusfs = minus.pop(0).strip()
if len(plusfs):
plusfs = '/' + plusfs.strip('/')
if (head == None) and (plusfs != "/*"):
head = plusfs
elif len(plusfs):
if plusfs == '/*':
out = { '/*':True } # reset all previous filters
else:
out[plusfs] = True
for minusfs in minus:
minusfs = minusfs.strip()
if len(minusfs):
minusfs = '/' + minusfs.strip('/')
if minusfs == '/*':
out = { '/*':False } # reset all previous filters
else:
out[minusfs] = False
if prefix == None:
prefix = head
return [prefix, out]
|
def is_bigstore_file(filename):
"""
Sniff a file to see if it looks like one of ours.
:param filename: filename to inspect
:return: True if the file starts with `bigstore`
"""
prefix = 'bigstore\n'
try:
with open(filename) as fd:
return fd.read(len(prefix)) == prefix
except IOError:
return False
|
def extract_vulnerabilities(debian_data, base_release='jessie'):
"""
Return a sequence of mappings for each existing combination of
package and vulnerability from a mapping of Debian vulnerabilities
data.
"""
package_vulnerabilities = []
for package_name, vulnerabilities in debian_data.items():
if not vulnerabilities or not package_name:
continue
for cve_id, details in vulnerabilities.items():
releases = details.get('releases')
if not releases:
continue
release = releases.get(base_release)
if not release:
continue
status = release.get('status')
if status not in ('open', 'resolved'):
continue
# the latest version of this package in base_release
version = release.get('repositories', {}).get(base_release, '')
package_vulnerabilities.append({
'package_name': package_name,
'cve_id': cve_id,
'description': details.get('description', ''),
'status': status,
'urgency': release.get('urgency', ''),
'version': version,
'fixed_version': release.get('fixed_version', '')
})
return package_vulnerabilities
|
def version_to_tuple(v):
"""Quick-and-dirty sort function to handle simple semantic versions like 1.7.12 or 1.8.7."""
if v.endswith('(preview)'):
return tuple(map(int, (v[:-9].split('.'))))
return tuple(map(int, (v.split('.'))))
|
def get_patch_position(tile,patch):
"""
tile: tuple -> (tile x position, tile y position, tile size)
patch: tuple -> (patch x position, patch y position, patch size)
"""
tx,ty,ts = tile
px,py,ps = patch
return (px-tx,py-ty,ps)
|
def get_canonical_tensor_name(name: str) -> str:
"""
Legal tensor names are like: name, ^name, or name:digits. Please refert to:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/graph/tensor_id.cc#L35
"""
parts = name.split(":")
is_control_input = name.startswith("^")
if len(parts) == 1:
suffix = "" if is_control_input else ":0"
return name + suffix
elif len(parts) == 2 and parts[1].isdecimal() and not is_control_input:
return name
else:
raise Exception(f"Invalid tensor name: {name}")
|
def vlsp_2018_Acc(y_true, y_pred, score, classes=3):
"""
Calculate "Acc" of sentiment classification task of VLSP 2018.
"""
assert classes in [2, 3], "classes must be 2 or 3."
if classes == 3:
total=0
total_right=0
for i in range(len(y_true)):
if y_true[i]==3:continue
total+=1
tmp=y_pred[i]
if tmp>=3:
if score[i][0]>=score[i][1] and score[i][0]>=score[i][2]:
tmp=0
elif score[i][1]>=score[i][0] and score[i][1]>=score[i][2]:
tmp=1
else:
tmp=2
if y_true[i]==tmp:
total_right+=1
sentiment_Acc = total_right/total
else:
total=0
total_right=0
for i in range(len(y_true)):
if y_true[i]>=3 or y_true[i]==1:continue
total+=1
tmp=y_pred[i]
if tmp>=3 or tmp==1:
if score[i][0]>=score[i][2]:
tmp=0
else:
tmp=2
if y_true[i]==tmp:
total_right+=1
sentiment_Acc = total_right/total
return sentiment_Acc
|
def check_for_dict_key(dict, key, **additional_params):
"""Search for keys and add additiona keys if found."""
if dict.get(key):
if additional_params.get('index') is not None:
return dict[key][additional_params['index']]
else:
return dict[key]
else:
if additional_params.get('default') is not None:
return additional_params.get('default')
else:
return None
|
def maxProfit(nums):
"""
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
:param nums:
:return:
"""
# n = len(nums)
# res = [0 for _ in range(n)]
# pre = nums[0]
# for i in range(1, n):
# pro = nums[i] - pre
# res[i] = max(pro, res[i - 1])
# if pro < 0:
# pre = nums[i]
# return res[-1]
n = len(nums)
res = 0
pre = nums[0]
for i in range(1, n):
pro = nums[i] - pre
res = max(pro, res)
if pro < 0:
pre = nums[i]
return res
|
def searchList(listOfTerms, query: str, filter='in'):
"""Search within a list"""
matches = []
for item in listOfTerms:
if filter == 'in' and query in item:
matches.append(item)
elif filter == 'start' and item.startswith(query):
matches.append(item)
elif filter == 'end' and item.endswith(query):
matches.append(item)
elif filter == 'exact' and item == query:
matches.append(item)
return matches
|
def _normalize_dicts(dict1, dict2):
"""Helper function that converts two dicts to lists that are aligned to each other."""
def add_keys_from(dist1, dist2):
"""If dist1 contains a key that dist2 doesn't, add it to dict2."""
for k in dist1.keys():
if k not in dist2:
dist2[k] = 0
def values_sorted_by_key(dist):
"""Get the values of dist, sorted by the keys."""
return [dist[k] for k in sorted(dist.keys())]
add_keys_from(dict1, dict2)
add_keys_from(dict2, dict1)
n_dict1 = values_sorted_by_key(dict1)
n_dict2 = values_sorted_by_key(dict2)
return n_dict1, n_dict2
|
def path(name):
"""
Generate a path object
"""
return {'$OBJECT': 'path', 'paths': [name]}
|
def cast_pureDP_zCDP(epsilon):
"""cast a epsilon-DP measurement to a (xi, rho)-zCDP measurement
Proposition 1.4: https://arxiv.org/pdf/1605.02065.pdf#subsubsection.1.2.1
"""
return 0, epsilon ** 2 / 2
# also valid under Lemma 8.3
# return epsilon, 0
|
def dotProduct(d1, d2):
"""
@param dict d1: a feature vector represented by a mapping from a feature (string) to a weight (float).
@param dict d2: same as d1
@return float: the dot product between d1 and d2
"""
if len(d1) < len(d2):
return dotProduct(d2, d1)
else:
return sum(d1.get(f, 0) * v for f, v in d2.items())
|
def _merge_secrets(secrets):
"""
Merge a list of secrets. Each secret should be a dict fitting the following JSON structure:
[{ "sourceVault": { "id": "value" },
"vaultCertificates": [{ "certificateUrl": "value",
"certificateStore": "cert store name (only on windows)"}] }]
The array of secrets is merged on sourceVault.id.
:param secrets:
:return:
"""
merged = {}
vc_name = 'vaultCertificates'
for outer in secrets:
for secret in outer:
if secret['sourceVault']['id'] not in merged:
merged[secret['sourceVault']['id']] = []
merged[secret['sourceVault']['id']] = \
secret[vc_name] + merged[secret['sourceVault']['id']]
# transform the reduced map to vm format
formatted = [{'sourceVault': {'id': source_id},
'vaultCertificates': value}
for source_id, value in list(merged.items())]
return formatted
|
def BlendColour(fg, bg, alpha):
"""
Blends the two colour component `fg` and `bg` into one colour component, adding
an optional alpha channel.
:param `fg`: the first colour component;
:param `bg`: the second colour component;
:param `alpha`: an optional transparency value.
"""
result = bg + (alpha*(fg - bg))
if result < 0.0:
result = 0.0
if result > 255:
result = 255
return result
|
def convert_ftp_url(url):
"""Convert FTP to HTTPS URLs."""
return url.replace('ftp://', 'https://', 1)
|
def _isIp(value):
"""
Check if the input string represents a valid IP address.
A valid IP can be one of the two forms:
1. A string that contains three '.' which separate the string into
four segments, each segment is an integer.
2. A string be either "INVALID_IP(XXXl)" or "AUTO/NONE(XXXl)",
where XXX is a long value.
Return a tuple, first element in the tuple is a boolean tells the validation result, while
the second element contains the error message if there is one.
"""
addrArray = value.split(".")
if not len(addrArray) == 4:
if value.startswith("INVALID_IP") or value.startswith("AUTO/NONE"):
tail = value.split("(")
if len(tail) == 2:
longStrParts = tail[1].split("l")
if len(longStrParts) == 2:
try:
int(longStrParts[0])
return True, None
except ValueError:
return False, "Invalid ip string: '{}'".format(value)
return False, "Invalid ip string: '{}'".format(value)
else:
for segments in addrArray:
try:
segmentVal = int(segments)
except ValueError:
return (
False,
"Ip segment is not a number: '{}' in ip string: '{}'".format(
segments, value
),
)
if not 0 <= segmentVal <= 255:
return (
False,
"Ip segment is out of range 0-255: '{}' in ip string: '{}'".format(
segments, value
),
)
return True, None
|
def configureOutput(path):
"""configureOutput(path)
Set the directory into which results like images and text output files are written."""
return {"Output" : path }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.