content stringlengths 42 6.51k |
|---|
def __read_class_labels(classes_file):
"""
Returns a function -> class-label dictionary. Only supports single class labels.
:param functionclasses_file: A file with the format function-name class-label
:return: Dictionary of the form {fn: class}
"""
classes = {}
with open(classes_file, 'r') ... |
def write_idx_on_disk(index_dirty, index_clean, path, path_dirty):
"""
Write a list on the disk
"""
with open(path, 'a') as fd:
for name in index_clean:
fd.write("{}\n".format(name))
with open(path_dirty, 'a') as fd:
for name in index_dirty:
fd.write("{}\n".fo... |
def isfuncdesc(desc):
"""Tests if a description is a function-type description."""
return desc is not None and 'signatures' in desc |
def is_tty (fp):
"""Check if a file object is a TTY."""
return (hasattr(fp, "isatty") and fp.isatty()) |
def get_private_key_user(user: str, index: int) -> str:
"""
Returns the keychain user string for a key index.
"""
return f"wallet-{user}-{index}" |
def u16(x):
"""Unpacks a 2-byte string into an integer (little endian)"""
import struct
return struct.unpack('<H', x)[0] |
def create_particle(p_full, p_agent, p_patient):
"""
Create a fantasy particle with a given number of
transitive and intransitive situations
"""
particle = []
nid = 0
for _ in range(p_full):
particle.extend([(nid, [0,1], [nid+1,nid+2], [], []),
(nid+... |
def keywithmaxval(dict):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
if len(dict) > 0:
v=list(dict.values())
k=list(dict.keys())
return k[v.index(max(v))]
else:
return "Check" |
def _cleanBlank(value):
""" Converts blank string to Python None """
if value == '':
return None
return value |
def reformat_wrd(wrd):
"""
1. Clean up special cases of standalone apostrophes
2. Detect valid apostrophe cases and split those into a two words
"""
if wrd[-1] == "'":
wrd = wrd[:-1]
if "'" in wrd and wrd != "'s":
wrd_lst = wrd.split("'")
wrd_lst[-1] = "'" + wrd_lst[-1]
... |
def prepare_results(cursor_description, rows):
"""
Generate result in JSON format with an entry consisting of key value pairs.
:param cursor_description: a tuple with query result columns
:param rows: list of returned sql query values
:return: dictionary
"""
if rows is None or len(rows) == 0... |
def lower_camel(name, split_char="_"):
"""Converts a given name into lower camelcase
:param name: The name to be converted
:type name: str
:param split_char: The character that separates words in the name.
:type split_char: str
:return: str
"""
words = name.split(split_char)
upper =... |
def minioString(obj):
"""
A Function to cast an object to str and then lowercase it.
This Function is helping to name paths, needed for the analysis in the right way.
Args:
- obj (Python Object): An object to turn it into a lowercase String.
Returns:
- Lower cased String (String): ... |
def row_str(dflen: int) -> str:
"""[summary]
Args:
dflen (int): [description]
Returns:
str: A formatted string with the number of rows (in millions).
"""
return str(round(dflen / 1000000, 1)) + "M rows" |
def ellipsis(text, maxlength=400):
"""Trim string to at most maxlength (default: 400) characters."""
if len(text) <= maxlength:
return text
else:
return "%s..." % (text[:maxlength - 3]) |
def doOverlap(bbox1, bbox2):
"""
:param bbox1: bounding box of the first rectangle
:param bbox2: bounding box of the second rectangle
:return: 1 if the two rectangles overlap
"""
if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]:
return False
if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]... |
def create_search_url(base_url, keyword_list):
"""Create Google search URL for a keyword from keyword_list
Args:
keyword_list (list): list of strings that contain the search keywords
base_url (str): Google's base search url
Returns:
list: Google search url like https://www.google.c... |
def str_to_bool(str_bool):
""" Helper function to convert string to boolean. """
if str_bool == "False":
return False
return True |
def time2str(s, last_unit='s'):
""" Return human readable time string from seconds.
Examples
--------
>>> from iocbio.utils import time_to_str
>>> print time_to_str(123000000)
3Y10M24d10h40m
>>> print time_to_str(1230000)
14d5h40m
>>> print time_to_str(1230)
20m30.0s
>>> pri... |
def cloudtrail_root_account_usage(rec):
"""
author: airbnb_csirt
description: Root AWS credentials are being used;
This is against best practice and may be an attacker
reference_1: https://aws.amazon.com/premiumsupport/knowledge-center/
... |
def unquote(string):
"""remove optional quotes (simple or double) from the string
:type string: str or unicode
:param string: an optionally quoted string
:rtype: str or unicode
:return: the unquoted string (or the input string if it wasn't quoted)
"""
if not string:
return string
... |
def _get_mixture_weights_constraints(n_mixtures):
"""Constrain mixture weights to be between 0 and 1 and sum to 1."""
if n_mixtures == 1:
msg = "Set the mixture weight to 1 if there is only one mixture element."
return [
{
"loc": "mixture_weights",
"ty... |
def italics(line):
""" Check if italics words exist, if exist, change them into html format
:param line: str, the line in markdown format
:return: str, the line in html format with italics style
"""
if line.count('__') >= 2:
for i in range(0, line.count('__') - line.count('__') % 2):
... |
def remove_elements_from_text(text: str, elements: str) -> str:
"""
Removes certain elements from a text.
Args:
text (:obj:`str`):
Text to process.
elements (:obj:`str`):
Elements to remove from text.
Returns:
:obj:`str`:
Text with given ele... |
def is_decorated(field_spec):
"""
is this spec a decorated one
:param field_spec: to check
:return: true or false
"""
if 'config' not in field_spec:
return False
config = field_spec.get('config')
return 'prefix' in config or 'suffix' in config or 'quote' in config |
def getChainID(line):
"""
reads the chainID from the pdbline
"""
if line == None:
return "A"
elif line[21] == " ":
return "A"
else:
return line[21] |
def parseversion(version):
""" Method to parse a version string from an AT or a BDP to turn it into ints so it can
be easily compared.
Parameters
----------
version : str
The string to parse
Returns
-------
Tuple containing the major, minor, ... |
def user_feedback(result_id, flags, comment, query, source_id=None, doc_type=None):
"""Format the properties of the ``feedback`` event.
:param result_id: the ES document ID the feedback applies to
:type result_id: str
:param flags: a dictionary with labels as keys and boolean values
:type flags: di... |
def enc_bool(val):
"""Encode a boolean as either a \0x00 or \0x01"""
# No '?' decode format in py2.4
if val:
return '\x01'
return '\x00' |
def accuracy(y_true, y_predicted):
"""
Calculate accuracy in terms of absolute coincidence
Args:
y_true: array of true values
y_predicted: array of predicted values
Returns:
portion of absolutely coincidental samples
"""
examples_len = len(y_true)
correct = sum([y1 ... |
def _split_series_episode(title):
"""Return the series and the episode titles; if this is not a
series' episode, the returned series title is empty.
This function recognize two different styles:
"The Series" An Episode (2005)
"The Series" (2004) {An Episode (2005) (#season.episode)}"""
s... |
def get_label_from_data(labels, position, prototype):
""" A simple function getting labels from a given list as in the example
of the MATLAB implementation.
"""
#print('providing label')
return labels[position] |
def raster_calculation(raster_list, weight_list):
"""
Function to calcule weighted sum of the rasters
Args:
raster_list (list): input rasters
weight_list (list): input weight of the rasters
Returns:
result raster
"""
assert len(raster_list) == len(weig... |
def can_double_bet(player_bets, player_cash):
"""
If the player has at least the amount of money as the first bet
return True else return False
:param player_bets:
:param player_cash:
:return: True or False
"""
if player_cash < sum(player_bets[0]):
return False
else:
... |
def _aggregate_wsgi_filename(filename):
"""
The WSGI profiler outputs files like this:
GET.root.000003ms.1543612537.prof
For comparison in our plotter we want them to look like this:
GET.root
"""
return ".".join(filename.split(".")[:2]) |
def format_float_to_str(num):
"""Format number into human-readable float format.
More precise it convert float into the string and remove redundant
zeros from the floating part.
It will format the number by the following examples:
0.0000001 -> 0.0
0.000000 -> 0.0
37 -> 37.0
1.000... |
def find_clones(population):
"""
Find all individuals that have a clone.
A clone is:
1) find all individuals with pattern and depot assignment
2) find all individuals with same cost
However, there is the chance that there is a clone with identical depot_chromosome but different solution.
T... |
def json_apply(fragment, check_func, func):
"""recursively searches through a nested dict/lists
if check_func(fragment) is True, then we return
func(fragment)
"""
if check_func(fragment):
return func(fragment)
elif isinstance(fragment, list):
output = []
for val in fragme... |
def _escape_template_string(template):
# type: (str) -> str
"""Escape the '$' in template strings unless followed by '{'."""
# See https://docs.python.org/2/library/string.html#template-strings
template = template.replace('${', '#{')
template = template.replace('$', '$$')
return template.replace... |
def dot_map_dict_to_nested_dict(dot_map_dict):
"""
Convert something like
```
{
'one.two.three.four': 4,
'one.six.seven.eight': None,
'five.nine.ten': 10,
'five.zero': 'foo',
}
```
into its corresponding nested dict.
http://stackoverflow.com/questions/165... |
def _get_relative_path(storage_location, path):
"""
Given a storage location and an absolute path, return
the relative path (i.e. the dump key)
"""
prefix_len = len(storage_location)
return path[prefix_len:] |
def get_deprt(lista):
"""Add together from row with same index."""
base = []
for item in lista:
base.append(item)
resultado = set(base)
return resultado |
def _adjmatType(adjMat):
"""(helper function) retruns <class 'int'> if the adjacency matrix is a (0,1)-matrix, and
returns <class 'list'> if the adjacency matrix contains edge weights, and returns None if
neither of the cases occurs.
Args:
adjMat (2D - nested - list): the adjacency matrix.
... |
def bounds(grid):
"""Return a list of tuples reporting the min and max value of each coordinate
in the given grid.
"""
xmin, ymin, zmin = list(grid.keys())[0]
xmax, ymax, zmax = xmin, ymin, zmin
for x, y, z in grid:
xmin = min(xmin, x)
ymin = min(ymin, y)
zmin = min(zmin... |
def _dictionary_product(dictionary):
"""Returns a named cartesian product of dictionary's values."""
# Converts {'a': [1, 2], 'b': [3, 4]} into
# [{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}]
product = [[]]
for values in dictionary.values():
# Iteratively grow the elements of t... |
def checkComing( visdict, dayspan=8 ):
"""Check for any visits that might be scheduled for execution in the
next <dayspan> days, and return a string reporting them to the user.
If nothing has been done lately, returns 0.
"""
daynames = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
if dayspan <= 8 ... |
def fill_dict_cols(collection):
"""
Convert the collection, which is a dictionary in which the keys are column names
and the values are the columns
"""
result = {}
max_length = 0
for col in collection:
result[col] = collection[col]
if len(collection[col]) > max_length:
max_length = len(collect... |
def zfill_to_collection_size(index: int, collection_size: int) -> str:
"""
Prepends amount of zeroes required for indexes to be string-sortable in terms of given collection size.
Examples:
for 10 items prepends up to 1 zero: 1 -> "01", 10 -> "10"
for 100 items prepends up to 2 zeroes: 7 -> "... |
def add_lists(*args):
"""
Append lists. This is trivial but it's here for symmetry with add_dicts
"""
out = []
for arg in args:
out.extend(arg)
return out |
def check_degree(num, edge, out_degree, in_degree):
"""
Check out degree and in degree
"""
out_d, in_d = [0]*num, [0]*num
for e in edge:
out_d[e[0]] = 1
in_d[e[-1]] = 1
if out_d == out_degree and in_d == in_degree:
return 1
else:
return 0 |
def get_public_attributes_and_methods(obj, exclude_parent=False):
"""Return a list of public attributes and methods for an object.
Parameters
----------
exclude_parent : bool
If ``True``, only display public attributes and methods specific to
the current class, excluding those inherited... |
def Levenshtein_Distance(str1, str2):
"""
cal str1 and str2 edit distance.
Args:
str1: string A
str2: string B
Return:
value of edit distance
"""
matrix = [[ i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1)+1):
... |
def s2f(s):
""" Convert a string to a float even if it has + and , in it. """
if s == None or s == '':
return None
if type(s) == type(0.0) or type(s) == type(0):
# Already a number
return s
if s:
return float(s.replace(',', ''))
return None |
def restructure_output(_doc):
"""Restructure the API output"""
field_mapping = {'HGNC': 'hgnc',
'ensembl.gene': 'ensembl',
'MIM': 'omim',
'entrezgene': 'entrez',
'pharos.target_id': 'pharos',
'umls.cui': 'um... |
def median(x):
""" Calculate sample Median without using numpy """
x = sorted(x)
m = int(len(x) / 2.0)
if len(x) % 2 == 0:
return (x[m] + x[m-1]) / 2.0
else:
return x[m] |
def Group(array):
"""Groups duplicate elements, e.g. [2, 1, 2, 2, 3] => [1, 2, 3], [1, 3, 1]."""
array.sort()
uniq, cnts = [], []
for i in array:
if len(uniq) == 0 or i != uniq[-1]:
uniq.append(i)
cnts.append(1)
else:
cnts[-1] += 1
return uniq, cnts |
def identify_disruptive_sequences(ambiguous_positions, threshold):
"""
Count the number of times a given sample introduces a missing character into a position which would be otherwise core
Parameters
----------
ambiguous_positions [dict] : {position: [sample list]}
threshold [int] : Max number o... |
def evaluate_tuple(columns,mapper,condition):
"""
"""
if isinstance(condition, tuple):
return condition[0](columns,mapper,condition[1],condition[2])
else:
return condition(columns,mapper) |
def risk_color_for(probability, impact, num_risks): # pylint: disable=too-many-return-statements
"""
Given a probability + impact, color a square.
If there are no risks the square will be light grey (#f0f0f0).
"""
# See https://www.colourlovers.com/palette/56122/Sweet_Lolly
colors = ["#00C176", ... |
def get_report_line(percentage, line_size):
"""Creates a string to be used in reporting the percentage done."""
report = ""
for i in range(0, line_size):
if (float(i) / line_size < percentage):
report += "="
else:
report += "-"
return report |
def get_pos(pk, token_index, pos_dict):
"""input: (file, sentId, eId, eiId) and token_index and pos_dict
output: pos_dict[(file, sentId, token_index)]
"""
if token_index == -1:
return "ROOT"
return pos_dict[(pk[0], pk[1], token_index)] |
def div(a,b):
"""Elementwise division with another vector, or with a scalar."""
if hasattr(b,'__iter__'):
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai/bi for ai,bi in zip(a,b)]
else:
return [ai/b for ai in a] |
def bbcommon(bb, bbother):
"""
Checks for overlaps of bounding boxes. First, east-west, then north-south.
Element 0 is west, element 2 is east, element 1 is north?, element 3 is
south?
All four checks must be false for chflag to be true, meaning the two
bounding boxes do not overlap.
"""
... |
def _genfmt(size, endian, sign):
"""
Generates a format string that can be used with struct.pack()
and struct.unpack().
"""
if sign not in [True, False]:
raise ValueError('sign must be either True or False')
if endian == 'little':
fmt = '<'
elif endian == 'big':
fmt ... |
def uniq_vals_incommon(list1, list2):
"""find unique values in common between two lists"""
return list(set([x for x in list1 if x in list2])) |
def splitcomma(source, sep=","):
"""split comma-separated string into list of elements,
stripping whitespace.
"""
source = source.strip()
if source.endswith(sep):
source = source[:-1]
if not source:
return []
return [ elem.strip() for elem in source.split(sep) ] |
def command_type(current_command):
"""Return command type
A_Command for @Xxx where Xxx is a symbol or decimal number
C_Command for dest=comp;jump
L_Command for Xxx where Xxx is a symbol
"""
if current_command[0] == '@':
return 'A_Command'
elif current_command[0] == '(':
return 'L_Command'
else:
return '... |
def update_intersection_properties(inters, config):
"""
Since intersection data includes properties from each contributing segment,
use the max value for each feature (as given by config file) available
and set properties for the intersection
Args:
inters - a list of intersection objects
... |
def filter_included_resources(include_list: list, resource_tuple_list: list) -> list:
"""
Filters the list returned by get_resource_urls() according to
a list of included resources.
"""
filtered_resource_list = list()
for k, v in resource_tuple_list:
if v.name in include_list:
... |
def _unary_op(result_name, func_name, arg_name):
"""
Generates a function call to func_name with argument arg_name
storing the result in result_name.
"""
return f"{result_name} = {func_name}({arg_name})" |
def str_to_animate_params(s):
"""
Parses animation parameters
:param s: A string of the form "<param> <start> <stop> <n_steps>"
:return: A tuple containing each field, (param: str, start: float, stop: float, n_steps: int)
"""
param, start, stop, n_steps = s.split(" ")
return param, float(sta... |
def pytest_error_str(error):
"""Different for different versions of Pytest"""
try:
return str(error.value)
except AttributeError:
return str(error) |
def add(x, y):
"""Add x and y."""
print(x, y)
return x + y |
def ev_fill(decimal_part):
"""Pad the first decimal part with zeros, taking into account E / V codes.
"""
if decimal_part.startswith("V"):
return "V" + decimal_part[1:].zfill(2)
elif decimal_part.startswith("E"):
return "E" + decimal_part[1:].zfill(3)
else:
return decima... |
def parse_events(props):
"""
Pull out the dashEvents from the Component props
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
list
List of Dash event strings
"""
if 'dashEvents' in props and props['dashEvents'... |
def label_mapper(label):
"""
for dales
Args:
label:
Returns:
"""
label_map = {1.0: 0, 2.0: 1, 6.0: 2, 9.0: 3, 26.0: 4}
return label_map[label] |
def calculate_safe_offset(firewall: dict) -> int:
"""Calculate the delay for making it through without getting caught"""
i = 0
while True:
s = any(True for layer, depth in firewall.items()
if not (layer+i) % (2*depth-2))
if not s:
return i
i += 1 |
def fix_relative(html, url):
""" this is fucking cheesy """
try:
base = "/".join(url.split("/")[:3])
html = html.replace("src='//", "src='http://")
html = html.replace('src="//', 'src="http://')
html = html.replace("src='/", "src='%s/" % base)
html = html.replace('src... |
def _courses_from_container(container):
"""
Pluck nested courses out of a ``container`` dictionary,
which is either the ``curriculum`` field of a program, or
a program itself (since either may contain a ``courses`` list).
"""
return [
course.get('uuid')
for course in container.ge... |
def is_prime_v1(integer):
"""Return 'True' if integer is a prime. Else 'False'."""
if integer == 0:
return False
if integer == 1:
return False # 1 is a unit, not a prime
for number in range(2, integer):
if integer % number is 0:
return False # The number has a divis... |
def divide_chunks(a_list, n):
"""Divide a list into chunks of size n.
:param a_list: an entry list.
:param n: size of each chunk.
:return: chunks in a list object.
"""
return [a_list[i:i + n] for i in range(0, len(a_list), n)] |
def EW_G_curve(EW, FeH, fitted_vals, power):
"""Calculate curve in V/EW space for a given metallicity."""
a, b, c, d, e = fitted_vals
return -1*(a - FeH + d*EW**(power) + c*EW)/(b + e*EW) |
def get_two_by_two_edges(*edges):
""" create the list of edges
Parameters
----------
* edges : list or tuple
each consecutive elements will be an edge
Returns
-------
list of 2-uple for the edges
"""
# Examples :
# G = test_graph_from_edges((1,2,3),(4,3))
... |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL.', 404 |
def to_list(tag):
"""
Put `tag` to list if it ain't list/tuple already.
Args:
tag (obj): Anything.
Returns:
list: Tag.
"""
if isinstance(tag, tuple) or isinstance(tag, list):
return tag
return [tag] |
def _DisplayValue(info, field, padding):
"""Gets the value of field from the dict info for display.
Args:
info: The dict with information about the component.
field: The field to access for display.
padding: Number of spaces to indent text to line up with first-line text.
Returns:
The value of th... |
def split_by_newline(value):
"""
Returns the value turned into a list.
"""
value = value.decode('utf-8')
return value.split('\r\n') |
def float_else_zero(sstring):
"""Return converted string to float. If conversion fail, return zero.
:param sstring: String to be converted
:return: ``float(sstrinq)`` if ``sstring`` can be converted to float
(e.g. ``"3.14"``), else ``0``
"""
try:
return float(sstring)
except Val... |
def cir_RsQ(w, Rs, Q, n):
"""
Simulation Function: -Rs-Q-
Inputs
----------
w = Angular frequency [1/s]
Rs = Series resistance [Ohm]
Q = Constant phase element [s^n/ohm]
n = Constant phase elelment exponent [-]
"""
return Rs + 1 / (Q * (w * 1j) ** n) |
def str2seq(st, func=int, sep=None):
""" "1 2 3" -> [func('1'), func('2'), func('3')]"""
# XXX check usage of this, check if we need list() at all
if sep is None:
return list(map(func, st.split()))
else:
return list(map(func, st.split(sep))) |
def xywh_iou(box1,box2):
"""
calculate iou between box1 and box2
:param box1: (4, ), format (left, upper, width, height)
:param box2: (4, ), format (left, upper, width, height)
:return: float, iou score
"""
l_max = max(box1[0], box2[0])
r_min = min(box1[0]+box1[2]-1, box2[0]+box2[2]-1)
... |
def get_modality(config_file):
"""
Gets the list of modalities to be searched.
Return None if the search is by date only.
:param config_file:
:return:
"""
if not config_file['StudyInfo']['Modality']:
return None
else:
return config_file['StudyInfo']['Modality'] |
def get_sizes(shares, amount):
"""Transform wallet shares to category sizes optimally
catsizes = [cs1, cs2, cs3, cs4] - blocks numbers of each color category
:param shares: list of wallet shares
:type shares: list in range (4)
:param amount: total amount of blocks
:type amount: int
:return: ... |
def calculate_delay_per_req(
num_total_requests: int, total_expected_execution_time: float
) -> float:
""" Calculate the delay to insert between each request sent by slave lambda """
delay_per_req = total_expected_execution_time / num_total_requests
delay_per_req = round(delay_per_req, 3)
return del... |
def base41_decode(input):
"""Decode a Base41 string.
input is the string to decode.
The decoded data is returned. A TypeError is raised if input
is not valid (odd number of chars, non-alphabet character present,
invalid word).
"""
rslt = bytearray()
i = 0
while i + 2 < len(input):
... |
def binary_to_decimal(binary):
"""Converts a binary number(str) into a decimal(int)"""
reversed_binary = binary[::- 1]
# i = corresponds to power of 2 when reversed
decimal = 0 # keep track of sum
for i, value in enumerate(reversed_binary):
if value == "0":
continue # ignore 0 ... |
def _gen_index_name(keys):
"""Generate an index name from the set of fields it is over.
"""
return u"_".join([u"%s_%s" % item for item in keys]) |
def p(*resistances: float) -> float:
"""Computes the total resistance of resistors in parallel."""
return 1 / sum(1 / r for r in resistances) |
def _ref_potential_walls_plumed(cv, at, kappa, offset=0.0, exp=2.0, eps=1.0, upper_wall=True):
"""A reference implementation of PLUMED UPPER/LOWER_WALLS restraint for testing."""
if upper_wall and cv <= at - offset:
return 0.0
elif not upper_wall and cv >= at - offset:
return 0.0
dist = ... |
def emission(height: int) -> int:
"""
Emission rate (nanoERG/block) at given height.
"""
initial_rate = 75
fixed_rate_period = 525600
epoch_length = 64800
step = 3
if height <= fixed_rate_period:
em = initial_rate
else:
em = initial_rate - (((height - fix... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.