content stringlengths 42 6.51k |
|---|
def add_variational_representations(variational_representation_1, variational_representation_2, radices):
"""
Add two decompositions (by variations) as multiradix numbers.
:param variational_representation_1: first decomposition
:param variational_representation_2: second decomposition
:param radic... |
def find_max(data):
"""
find the index of the maximum value in a list
"""
from collections import defaultdict
d = defaultdict(list)
for i, x in enumerate(data):
d[x].append(i)
k = max(d.keys())
return d[k] |
def IsGoodTag(prefixes, tag):
"""Decide if a string is a tag
@param prefixes: set of prefixes that would indicate
the tag being suitable
@param tag: the tag in question
"""
for prefix in prefixes:
if tag.startswith(prefix):
return True
return False |
def convert_list_type(x, type=int):
"""Convert elements in list to given type."""
return list(map(type, x)) |
def calc_precision(tp: float, fp: float) -> float:
"""
:param tp: true positive or hit
:param fp: false positive or false alarm
:return: precision
"""
try:
calc = tp / (tp + fp)
except ZeroDivisionError:
calc = 0
return calc |
def sum_of_3_and_5_multiples(s3,s5):
"""Calculate the sum of the multiples of 3 and 5."""
totalsum=s3+s5
return totalsum |
def chacha_qr(q, A, B, rot):
"""Classical implementation of the Chacha quarter round
Args:
q (int): number of bits of a site in the permutation matrix.
A (str): classical bitstring for a site of the permutation matrix.
B (str): classical bitstring for a site of the permutation matrix.
... |
def rk4(f, y0, dt):
"""
Keyword Arguments:
f --
y0 --
dt --
"""
k1 = f(y0)
k2 = f(y0 + 0.5 * dt * k1)
k3 = f(y0 + 0.5 * dt * k2)
k4 = f(y0 + dt * k3)
y1 = y0 + dt / 6 * (k1 + 2 * (k2 + k3) + k4)
return y1 |
def update_dict(dict1, dict2):
"""Helper for :meth:`_productive_morphology`."""
for field in dict1:
if field in dict2:
dict1[field] += dict2[field]
for field in dict2:
if not field in dict1:
dict1[field] = dict2[field]
for field in dict1:
if dict1[field]:
... |
def getOutput(inst):
"""
Get the outputs of the instruction
Input:
- inst: The instruction list
Output:
- Returns the outputs of the instruction
"""
return inst[1], inst[2] |
def get_as_clause(columns_to_query_lst):
"""
get_as_clause will return all column names tuples.
:param columns_to_query_lst: columns for where clause
:return:
"""
column_str = ""
for col in columns_to_query_lst:
column_str = column_str + col + ","
column_str += "update"
as_cl... |
def _test_against_patterns(patterns, entity_id):
"""Test entity against list of patterns, true if any match."""
for pattern in patterns:
if pattern.match(entity_id):
return True
return False |
def tc(val_str, bytes):
""" twos complement"""
import sys
val = int(val_str, 2)
b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False)
return int.from_bytes(b, byteorder=sys.byteorder, signed=True) |
def unpad(data: bytes) -> bytes:
"""Unpad a previously padded string."""
return data[: -ord(data[len(data) - 1 :])] |
def latexToArrayRowNames(text):
"""Converts the inside of the LaTeX tabular environment into a 2D array represented as nested lists.
The first column is treated as row names, and a list of them is returned."""
rows = []
names = []
for line in text.strip().split("\n"):
cols = [c.strip() for c... |
def _get_arg(argname, args, kwargs):
"""
Get an argument, either from kwargs or from the first entry in args.
Raises a TypeError if argname not in kwargs and len(args) == 0.
Mutates kwargs in place if the value is found in kwargs.
"""
try:
return kwargs.pop(argname), args
except Key... |
def egcd(a, b):
"""Computes the Euclidean Greatest Common Divisor"""
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y |
def resolve_absolute_path(filename):
"""Fetch filename from absolute path"""
return filename.split('/')[-1] |
def load_alpha_square(alphafile):
"""loads the ADFG(V)X matrix from a file
Args:
alphafile (str): contents of the matrix file
Raises:
ValueError: raised if matrix is not square
Returns:
list of list of str: adfgvx translation matrix
"""
alpha_square = []
for line i... |
def parse_moneyline(moneyline_bet):
"""Parse a moneyline bet object from Bovada and return, in order, the home and away moneyline"""
outcomes = moneyline_bet["outcomes"]
home_moneyline = ""
away_moneyline = ""
if len(outcomes) > 2:
raise Exception("Unexpected objects in moneyline bet")
f... |
def create_help(header, options):
"""Create formated help."""
return "\n" + header + "\n" + \
"\n".join(map(lambda x: " " + x, options)) + "\n" |
def get_good_prospects(combs=([1, 2], [5, 6])):
"""
Description
-----------
Words with just one or two letters are usually articles, prepositions, etc. Since these are not words with a
significant meaning, they will be omitted. Hence, this function returns a curated slice list where the distanc... |
def get_repo_owner(team_data, repo_name):
"""Return the name of the team that owns the repository.
:param team_data: The result of calling :func:`get_team_data`
:param repo_name: Long name of the repository, such as 'openstack/nova'.
"""
for team, info in team_data.items():
for dname, dinfo... |
def ReconstructSourceImport(item):
"""Reconstruct the original import line from values in ImportCollector.
This is used to output human-friendly error message.
"""
if item['import'] is None:
return "import %s" % item['module']
module = ''.join(['.'] * item['level'])
module += item['module'] or ''
ret... |
def sentihood_macro_F1(y_true, y_pred):
"""
Calculate "Macro-F1" of aspect detection task of Sentihood.
"""
p_all=0
r_all=0
count=0
for i in range(len(y_pred)//4):
a=set()
b=set()
for j in range(4):
if y_pred[i*4+j]!=0:
a.add(j)
... |
def value_to_status(actuator_value):
"""
Translates int corresponding to actuator status.
:param actuator_value: The value from the status.value of the actuator
:type actuator_value: int
"""
if actuator_value == 0:
return "closed"
else:
return "open" |
def mi(h1, h2, joint_h):
"""Calc Mutual Information given two entropies and their joint entropy"""
return h1 + h2 - joint_h |
def lower_frequency(center, order=1):
"""
Lower frequency of frequency band given a center frequency and order.
:param center: Center frequencies.
:param order: Fraction of octave.
.. math:: f_l = f_c \cdot 2^{\\frac{-1}{2N}}
"""
return center * 2.0**(-1.0/(2.0*order)) |
def strip_prefix(name):
"""Strip the schema and host:port from a Docker repository name."""
paths = name.split('/')
return '/'.join(p for p in paths if p and '.' not in p and ':' not in p) |
def checksum(number):
"""Calculate the checksum. The checksum is only used for the 9 digits
of the number and the result can either be 0 or 42."""
weights = (8, 7, 6, 5, 4, 3, 2, 10, 1)
return sum(w * int(n) for w, n in zip(weights, number)) % 97 |
def ip_key(key):
"""Function to make a 'canonical' IP string for sorting.
The given IP has each subfield expanded to 3 numeric digits, eg:
given '1.255.24.6' return '001.255.014.006'
"""
ip = key[0]
fields = ip.split('.')
result = []
for f in fields:
result.append('%03d' % ... |
def create_edge_attrs(prev_layer_id: str, next_layer_id: str, in_port=0, out_port=0) -> dict:
"""
Create common edge's attributes
:param prev_layer_id: id of previous layer
:param next_layer_id: id of next layer
:param in_port: 'in' port
:param out_port: 'out' port
:return: dictionary contai... |
def _minSec(*t):
"""Return a tuple of (mins, secs, ...) - two for every item passed."""
l = []
for i in t:
l.extend(divmod(int(i), 60))
return tuple(l) |
def check_indent(codestr):
"""If the code is indented, add a top level piece of code to 'remove' the indentation"""
i = 0
while codestr[i] in ["\n", "\t", " "]:
i = i + 1
if i == 0:
return codestr
if codestr[i-1] == "\t" or codestr[i-1] == " ":
if codestr[0] == "\n":
... |
def is_valid(nb, rules):
"""identify if a row is valid at all"""
for num in nb:
valid = False
for _, a, b, c, d in rules: # at least one rule has to apply
if (a <= num <= b or c <= num <= d):
valid = True
if not valid:
return False
return True |
def is_leap_year(year_input):
"""Find whether the given year is leap or not"""
is_leap = False
try:
if year_input%400 == 0:
is_leap = True
elif (year_input%100 != 0) & (year_input%4 == 0):
is_leap = True
else:
is_leap = False
except A... |
def format_size(size):
"""
Formats a filesize to use Kb
"""
kb_int = int(size / 1024)
return "{:d} KB".format(kb_int) |
def target_pad_to_len(words, padded_word_len, word_padding=0):
"""Pad words to 'padded_word_len' with padding if 'len(words) < padded_word_len'.
Example:
target_pad_to_len([1, 2, 3], 5, -1) == [1, 2, 3, -1, -1]
Args:
words (list): List of the word index.
padded_word_len (int): The le... |
def strip_lower(s):
"""It removes the useless spaces and transform all the letters to
lower-case letters.
Parameters
----------
s: str
the string to be formatted or transformed.
Returns
-------
s_t: str
the transformed string.
"""
return s.strip().lower() |
def entry_point():
"""
returns dictionary for DTS entry point
"""
resp = {
"@context": "/data/api/dts/contexts/EntryPoint.jsonld",
"@id": "/data/api/dts",
"@type": "EntryPoint",
"collections": "/data/api/dts/collections/",
"documents": "/data/api/dts/documents/",
... |
def number_of_components(params):
"""Compute number of Gaussian components."""
return int(len(params) / 3) |
def prefix(name, data):
"""Prefix all keys with value."""
data = {"{0}-{1}".format(name, k): v for (k, v) in data.items()}
data['submit'] = name
return data |
def get_k_neighbors(k, seg, seg_sim):
"""
return set of k nearest neighbors of 'seg'
"""
neighbor_list = []
sim_list = [] # sim_list[i] = similarity of seg with neighbor[i]
for i in seg_sim:
if i == seg: continue
neighbor_list.append(i)
sim_list.append(seg_sim[seg][i])
... |
def problem_8_1(x):
""" Write a method to generate the nth Fibonacci number. """
def fib(n):
if n < 0:
raise Exception('No fibonacci number below 0')
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
return fib(x) |
def file_write(file_handle, file_blocks):
"""A simple function to write a part of a file in chunks. It is decorated
with a timer to track duration.
- Args:
- file_handle (file): the open file to write
- file_blocks (file): the data to write
- Returns:
- [file]: returns the writ... |
def convert_full_transcripts_to_json(transcripts):
"""
Convert FullTranscript objects to a list of dictionarys of relevant info
"""
maps = {}
for transcript in transcripts:
# If we already started using a transcript, update the map
if transcript.transcript_id in maps:
res... |
def broadcast_chunks(*chunkss):
""" Construct a chunks tuple that broadcasts many chunks tuples
>>> a = ((5, 5),)
>>> b = ((5, 5),)
>>> broadcast_chunks(a, b)
((5, 5),)
>>> a = ((10, 10, 10), (5, 5),)
>>> b = ((5, 5),)
>>> broadcast_chunks(a, b)
((10, 10, 10), (5, 5))
>>> a = ... |
def add_key_values(d1):
"""Add key in dictionary to values if does not exist."""
for key, values in d1.items():
if key not in values:
values.append(key)
return d1 |
def _key_lookup_ignorecase(d, key):
""" Search dict for key, ignoring case
Args:
d (dict): dict to search
key (str): key to search for
Returns:
str or None: key in dict `d` matching `key` if found; else None
"""
key = [k for k in d.keys() if key.lower() == k.lower()]
if key:... |
def add_to_whitelist(fingerprint, additions):
""" Given a fingerprint, add to the whitelist """
(fp, analyzed, valid_after) = fingerprint
fp.update(additions)
return(fp, analyzed, valid_after) |
def is_valid_input(ext):
""" Checks if input file format is compatible with Acpype """
formats = ["pdb", "mdl", "mol2"]
return ext in formats |
def choose_color_according_to_operations_type(operations_parent_name):
"""
Returns a colour to colour the operations list in the gui according to the type they belong to
:param operations_parent_name: Name of operation (it included the type)
:return: The colour
"""
colour = [255, 255, 255,... |
def strip_moment(observable_key: str):
"""Convert a observable name to a base observable and a statistical moment"""
if observable_key.endswith("_std"):
moment = "stdv"
key = observable_key.rstrip("std").rstrip("_")
elif observable_key.endswith("_skew"):
moment = "skew"
key ... |
def fix_return_chars(string_value):
"""Replace existing return chars with return chars for HTTP"""
# This is needed because some apps not parse the message correctly
return '\r\n'.join(string_value.splitlines()) |
def parse_type(msg_type):
"""
Parse ROS message field type
:param msg_type: ROS field type, ``str``
:returns: base_type, is_array, array_length, ``(str, bool, int)``
:raises: :exc:`ValueError` If *msg_type* cannot be parsed
"""
if not msg_type:
raise ValueError("Invalid empty type")
... |
def get_server_success_message(data):
"""
Returns the success message
:param data: dict
:return: dict
"""
return {
'status': 'success',
'error': '',
'data': data
} |
def filter_grey_square(words:tuple, letter:str, offset:int) -> tuple:
"""
Create shorter list of words that do not contain letter.
NOTE: offset is not used; it is present for the signature.
"""
return tuple( word for word in words if letter not in word ) |
def setup(app):
"""Setup as a sphinx extension."""
# This is only a lexer, so adding it below to pygments appears sufficient.
# But if somebody knows what the right API usage should be to do that via
# sphinx, by all means fix it here. At least having this setup.py
# suppresses the sphinx warning ... |
def clean_file_name(filename):
"""Clean the filename for the client.
If it has directory structure, purge it and give only the file name.
:param filename: file name to be cleaned
:return: cleaned filename
"""
if '/' in filename:
filename = filename.split('/')[-1]
return filename |
def is_video(ext: str):
"""
Returns true if ext exists in
allowed_exts for video files.
Args:
ext:
Returns:
"""
allowed_exts = (".mp4", ".webm", ".ogg", ".avi", ".wmv", ".mkv", ".3gp")
return any((ext.endswith(x) for x in allowed_exts)) |
def pop_option (ident, argv=None):
"""A lame routine for grabbing command-line arguments. Returns a boolean
indicating whether the option was present. If it was, it's removed from
the argument string. Because of the lame behavior, options can't be
combined, and non-boolean options aren't supported. Oper... |
def make_entry_idx(name='Catalan', scriptable='yes', spell='yes'):
"""
Pass values for name, scriptable, spell attributes to the idx entry tag.
Args:
name (str), scriptable (str), spell (str): <idx:entry> attributes
Returns:
<idx:entry> tag with attributes.
Notes:
A sequentia... |
def _named(pattern, name):
"""Wraps a regex pattern in a named capture group"""
return f'(?P<{name}>{pattern})' |
def get_figsize(figsize, nrows_and_cols):
""" If `figsize` is a tuple (w, h), returns (w, h), otherwize
consider figsize as the width and returns corresponding (w, h)
depending on nrows and ncols. """
nrows, ncols = nrows_and_cols
try:
w, h = figsize
except:
w = figsize
h... |
def check_prime(x):
"""
checks, whether or not x is a prime number
"""
prime = True
for i in range(2, x):
if (x % i) == 0:
prime = False
break
return prime |
def queensAttack(n, k, r_q, c_q, obstacles):
"""
Sets the max moves to the distance to the board's edge.
It then loops through all obstacles to find out if one is in the path of the queen.
If so, max moves are updates to reflect the obstacle.
"""
diag_1 = min(r_q - 1, c_q - 1)
diag_2 = ... |
def get_size(item):
""" Recursively sums length of all strings in `item` """
if isinstance(item, str):
return len(item)
elif isinstance(item, list):
return sum(get_size(elem) for elem in item)
elif isinstance(item, dict):
return get_size(list(item.values()))
else:
ret... |
def is_valid_python_classname(name: str):
""" Indicates whether name is a valid Python identifier
Parameters
----------
name : str
A string representing a class name
Returns
-------
bool
True when name is a valid python identifier, False otherwise
"""
return str.isi... |
def _group_by_x(values, aggregationfunc, keyfunc):
"""input should be [(datetime, stuff), ...]"""
groupings = {}
for date, value in values:
key = keyfunc(date)
if key not in groupings:
groupings[key] = [value]
else:
groupings[key].append(value)
ret = []
... |
def truncateFilePath(string, suffix=None, parts=1):
"""Function that takes a file that was loaded already and truncates it to make a sub folder with a child folder specified.
Attr:
string(str): Original path to be truncated.
suffix(str): Altered path inside of truncated path.
... |
def c_source_files(file_list):
"""Filter c source files only from source files list."""
return sorted({file for file in file_list if file.endswith(".c")}) |
def getLargestDimension(geometry):
"""
Args:
geometry:
Returns:
"""
# DOCU add some docstring
if geometry['type'] == 'box':
return max(geometry['size'])
if geometry['type'] == 'cylinder':
return max((geometry['radius'], geometry['length']))
if geometry['type'] =... |
def terminate_cluster_endpoint(host):
"""
Utility function to generate the get run endpoint given the host.
"""
return f'https://{host}/api/2.0/clusters/delete' |
def _extractInlineComment(line, comment_types):
"""Find if there's a comment on the line and extract it if there is.
Args:
line(string): the file line to be checked.
comment_types(list): containing possible comment characters.
Return:
tuple containing the line without the comment p... |
def init_perfs(MODELS:list, ATTACKS:list, PERFS:list):
"""intialize a dictionary of performances
"""
all_perfs = {}
for m in MODELS:
for a in ATTACKS:
for p in PERFS:
all_perfs[''.join([p, '_', m, '_', a])] = 0.0
return all_perfs |
def unique(s):
""" Return a list of elements in s in arbitrary order, but without
duplicates.
"""
# Try using a set first, because it's the fastest and will usually work
try:
return list(set(s))
except TypeError:
pass # Move on to the next method
# Since you can't hash a... |
def concatenate_files(filenames):
""" Concatenate the specified files, adding `line directives so the lexer can track source locations.
"""
contents = []
for filename in filenames:
contents.append('`line 1 "%s" 1' % filename)
with open(filename, 'rb') as f:
contents.append(f.... |
def urlencode_unix_socket_path(socket_path):
"""Encodes a UNIX socket path string from a socket path for the `http+unix` URI form."""
return socket_path.replace("/", "%2F") |
def pascal_to_camel(string: str) -> str:
"""
Converts pascal-case to camel-case.
>>> pascal_to_camel(string="HelloAndGoodMorning") # Returns "helloAndGoodMorning"
"""
return string[0].lower() + string[1:] |
def letter_combinations(characters):
"""
Parameters
----------
characters : list
A list of characters e.g. [A, B, C]
Returns
-------
list
A list of all combinations
>>> letter_combinations(['A', 'B', 'C'])
[['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C'], ['B', '... |
def invert_bitstring_with_mask(string: int, masklen: int) -> int:
"""Invert a bitstring with a mask.
Args:
string (bitstring) - the bitstring to invert
masklen (int) - the value to mask the inverted bitstring to
Returns:
(bitstring) - a bitstring inverted up to the masking length
... |
def to_conll_iob(annotated_sentence):
""" Transforms sentences encoded without an IOB-prefix (just the entity
type), to sentences with IOB2-type tags.
Parameters
----------
annotated_sentence : list
List of tuples in the form (w,t,iob)
"""
proper_iob_tokens = []
for idx, annot... |
def calculate_upper_bounds(x_s, y_s):
"""
Calculate upper bounds of total timesteps and average episodic
return per iteration.
Parameters:
x_s - A list of lists of total timesteps so far per seed.
y_s - A list of lists of average episodic return per seed.
Re... |
def stap_signature(b):
"""0+(...-)"""
return 0 if b == 0 else (1 if b == 1 else -1) |
def acceptTrialPoint(xtry, ftry, Df, gx):
"""Accept trial point and assign new values."""
gxNew = Df(xtry)
return xtry, ftry, gxNew, gxNew - gx |
def ip_as_int(ip_address):
"""convert dot notation to int.
"""
parts = [int(x) for x in ip_address.split(".")]
return (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + parts[3] |
def polynomial(a0, a1, a2, a3 ,a4 , x):
"""
Up to x4
"""
return a0 + x*(a1+x*(a2+x*(a3+x*a4))) |
def deep_index(lst, w):
"""helper function for user_attack to find the corresponding item in weapon_dict"""
return [i for (i, sub) in enumerate(lst) if w in sub][0] |
def interpolate(x, start, stop_dist):
"""Return interpolation value of x for range(start, stop)
Args
x: int location
start: location corresponding to 1
stop_dist: distance from start corresponding to 0
"""
assert(stop_dist != 0)
stop = start + stop_dist
d = (stop - x) / (stop - start)
re... |
def get_diff(l1, l2):
"""
Returns the difference between two lists.
"""
diff = list( list(set(l1) - set(l2)) + list(set(l2) - set(l1)) )
return diff |
def expand_restart_file_names(paths, run_info):
"""
Tests if the GEOS-Chem restart file is a symbolic link to
ExtData. If so, will append the link to the remote file
to the line in which the restart file name is found.
Args:
----
paths : dict
Output of function extract_path... |
def reverseComplement(read):
"""
:param str. a read in string format
:return: str. the reverse complement of that read in string format
"""
comp=[]
for j in read:
if j == 'A': comp.append('T')
elif j == 'T': comp.append('A')
elif j == 'C': comp.append('G')
elif j... |
def unflatten_tensor(inputs, bhwc):
"""
Inverse function for flatten_tensor()
"""
if inputs is None:
return inputs
return inputs.view(bhwc).permute(0, 3, 1, 2) |
def isBottomLayer(layer):
"""
Decide if layer is a bottom layer
"""
return str(layer).startswith("Layer.B_") |
def get_column_letter(n: int) -> str:
"""
This function converts the column index to column letter
1 to A,
5 to E, etc
:param n:
:return:
"""
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string |
def bytes_identical(a_bytes, b_bytes):
"""Return a tuple (bytes a == bytes b, index of first difference)"""
if a_bytes == b_bytes:
return True, 0 # True, dummy argument
else:
pos = 0
while a_bytes[pos] == b_bytes[pos]:
pos += 1
return False, pos |
def preferred_signs_from_paulidict(pauli_basis_dict):
"""
Infers what the preferred basis signs are based on the length of gate-name
strings in `pauli_basis_dict` (shorter strings are preferred).
Parameters
----------
pauli_basis_dict : dict
A dictionary w/keys like `"+X"` or `"-Y"` and... |
def comment_fold(s): # function fold: auxiliary function: shorten long option values for output
"""auxiliary function: shorten/fold long option values in LaTeX comment output"""
offset = 28 * " "
maxlen = 120
sep = "|"
parts = s.split(sep)
lin... |
def wifi_mode(code):
"""
returns text of mode code
"""
if code==1:
return 'IEEE 802.11b'
if code==2:
return 'IEEE 802.11g'
if code==3:
return 'IEEE 802.11n'
else:
return 'unknown' |
def get_median(source_list):
"""
:param source_list: list with float to count median
:return: value of median
"""
if len(source_list) % 2 == 0:
med = int(len(source_list) / 2 - 1)
return (source_list[med] + source_list[med + 1]) / 2.0
else:
med = int(len(source_list) / 2)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.