content stringlengths 42 6.51k |
|---|
def add_leading_zero(number: int, digit_num: int = 2) -> str:
"""add_leading_zero function
Args:
number (int): number that you want to add leading zero
digit_num (int): number of digits that you want fill up to. Defaults to 2.
Returns:
str: number that has the leading zero
Exa... |
def _format_abc(num):
"""Lowercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+97) |
def TransformDecode(r, encoding, undefined=''):
"""Returns the decoded value of the resource that was encoded by encoding.
Args:
r: A JSON-serializable object.
encoding: The encoding name. *base64* and *utf-8* are supported.
undefined: Returns this value if the decoding fails.
Returns:
The decod... |
def _get_t(elm):
""" helper function, get text if element exists """
return elm.text.strip() if elm is not None else elm |
def popup(message, title):
"""
Function that returns UR script for popup
Args:
message: float. tooltip offset in mm
title: float. tooltip offset in mm
Returns:
script: UR script
"""
return 'popup("{}","{}") \n'.format(message, title) |
def subv3(a, b):
"""subtract 3-vector b from a"""
return (a[0]-b[0], a[1]-b[1], a[2]-b[2]) |
def atoi(text):
"""
Turn an int string into a number, but leave a non-int string alone.
"""
return int(text) if text.isdigit() else text |
def calculate_mz(
prec_mass: float,
charge: int
) -> float:
"""Calculate the precursor mono mz from mass and charge.
Args:
prec_mass (float): precursor mass.
charge (int): charge.
Returns:
float: mono m/z.
"""
M_PROTON = 1.00727646687
mono_mz = prec_mass / abs(cha... |
def check_existence(dictionary: dict, keys: list):
"""
Check the existence of all key elements in dictionary with the keys list
:param dictionary: dict to check all keys
:param keys: keys to check
"""
return all(key in dictionary for key in keys) and len(dictionary) == len(keys) |
def is_yaml(path):
"""
Checks whether the file at path is a yaml-file.
Parameters
----------
path : str
The relative path to the file that should be checked.
Returns
-------
bool
Whether or not the specified file is a yaml-file.
"""
return path.endswith('.yaml')... |
def capture_row_indices(materials, shape_only=False):
"""Captures the start and stop indices of an array based on the
contents of the array.
shape_only provides a method to control binary gap vs no-gap as
opposed to actual details of materials. This should provide a close
to optimal pairing of ind... |
def parse_loot_percentage(text):
"""Use to parse loot percentage string, ie: Roubo: 50% becomes 0.5"""
percentage = float(text.split(':')[1].strip("%")) / 100
return percentage |
def px2pt(p):
"""Convert pixels to points.
"""
return p * 72. / 96. |
def create_dict_from_filter(d, white_list):
"""Filter by key"""
return {k: v for k, v in filter(lambda t: t[0] in white_list, d.items())} |
def get_named_graph(ont):
"""
Ontobee uses NGs such as http://purl.obolibrary.org/obo/merged/CL
"""
if ont.startswith('http://'):
return ont
namedGraph = 'http://purl.obolibrary.org/obo/merged/' + ont.upper()
return namedGraph |
def combine_results(first, second):
"""Sum objects in given tuples using the __add__ method of
each object. e.g.
foo[0] = foo[0] + bar[0]
foo[1] = foo[1] + bar[1]
return foo
Used here to sum Method and Analyze objects together for trajectories
read in chunks.
... |
def slice_to_box(slice):
"""
Convert slice object to tuple of bounding box.
Parameters
----------
slice : tuple
A tuple containing slice(start, stop, step) objects.
Return
------
box : tuple
A tuple containing 4 integers representing a bounding box.
"""
box = (sl... |
def _mock_kernel(x1, x2, history):
"""A kernel that memorizes its calls and encodes a fixed values for equal/unequal
datapoint pairs."""
history.append((x1, x2))
if x1 == x2:
return 1
else:
return 0.2 |
def parse_title(title):
"""Parse the title of the measurement
@return Tuple (what, batch, src, dest), (None, None, None, None) in case of failure.
"""
tmp = title.split('-')
if len(tmp)!=4:
return (None, None, None, None)
return (tmp[0], int(tmp[1]), int(tmp[2]), int(tmp[3])) |
def kwarg(string, separator='='):
"""Return a dict from a delimited string."""
if separator not in string:
raise ValueError("Separator '%s' not in value '%s'"
% (separator, string))
if string.strip().startswith(separator):
raise ValueError("Value '%s' starts with sep... |
def message_decoder(text):
""" Decodes message content by splitting, splicing and stripping text
Args:
text (string): Input text
Returns:
dict : A hashmap containing all key value pairs of decoded text
"""
try:
first_split = text.split("-")
result = {}
for e... |
def make_blast_subject_list(local_files, addNr = True):
""" given a list of fasta filenames, make a blast list """
# helper for name breakpoints
# list of BLAST subjects
# first column is filename (for local) or database name (for NCBI)
# second column is true for local and false for NCBI
# all ... |
def _to_tag_case(x):
"""
Returns the string in "tag case" where the first letter
is capitalized
Args:
x (str): input string
Returns:
x (str): transformed string
"""
return x[0].upper() + x[1:] |
def mat_to_svec_dim(n):
"""Compute the number of unique entries in a symmetric matrix."""
d = (n * (n + 1)) // 2
return d |
def bvi_unique(yaml, bviname):
"""Returns True if the BVI identified by bviname is unique among all BridgeDomains."""
if not "bridgedomains" in yaml:
return True
ncount = 0
for _ifname, iface in yaml["bridgedomains"].items():
if "bvi" in iface and iface["bvi"] == bviname:
nco... |
def collapse(lst):
"""
Removes all sublists from a list while keeping their values
:param lst: List to be collapsed.
:return: List
"""
temp = []
for i in lst:
if type(i) is list:
temp +=collapse(i)
else:
temp +=[i]
return temp |
def valueList(name,position):
""" Concatenate the two parameter list in on list of tuple"""
values = []
for i in range(len(name)):
values += [[name[i],position[i]]]
return values |
def edit_distance(str1, str2):
""" calculates the edit distance between 2 strings
uses a DP approach with a table that calculates the edit distance between
2 substrings
dp[i][j] = edit distance between str1[i] and str2[j]
:type str1: string
:type str2: string
:rtype int: """
dp = [[0 fo... |
def multiqubit_measure_counts_deterministic(shots, hex_counts=True):
"""Multi-qubit measure test circuits reference counts."""
targets = []
if hex_counts:
# 2-qubit measure |10>
targets.append({'0x2': shots})
# 3-qubit measure |101>
targets.append({'0x5': shots})
# 4... |
def binary_sum(x : int ,y : int) -> str :
"""
Given two binary number
return their sum .
For example,
x = 11
y = 111
Return result as "1000".
Parameters:
x(int) : binary number
y(int) : binary number
Returns:
s(str) : sum of a and b in string
... |
def fetch_log_pos(server, args_array, opt_arg_list):
"""Method: fetch_log_pos
Description: Stub holder for mysql_log_admin.fetch_log_pos function.
Arguments:
"""
status = True
if server and args_array and opt_arg_list:
status = True
return status |
def getComments(header, index):
"""Get any comments before this table.
Expects the header string and the index of the table."""
cend = header.rindex('\n', 0, index) #the start of line.
cstart = cend
tmp = cend
while True: #find start of a comment.
tmp = header.rindex('\n', 0, cstart - 1)
if '//' in header[tmp... |
def build_mjolnir_utility(config):
"""Buiild arguments for calling mjolnir-utility.py
Parameters
----------
config : dict
Configuration of the individual command to run
"""
args = [config['mjolnir_utility_path'], config['mjolnir_utility']]
try:
# while sorting is not strict... |
def compute_precision_recall(results, partial=False):
""" Compute the micro scores for Precision, Recall, F1.
:param dict results: evaluation results.
:param bool partial: option to half the reward of partial matches.
:return: Description of returned object.
:rtype: updated results
"""
ac... |
def corrupt_string(input, to_insert):
"""
Takes in a base string input and another string to_insert.
Corrupts the base string by making it so each character is
followed by the string in to_insert and returns.
Parameters:
input: Base string that will be corrupted/modified.
to_insert:... |
def UpperCamelCase(lowerCamelCaseStr):
"""
Return the UpperCamelCase variant of a lower camel case string.
"""
return lowerCamelCaseStr[0].upper() + lowerCamelCaseStr[1:] |
def merge_json_objects(a, b):
"""Merge two JSON objects recursively.
- If a dict, keys are merged, preferring ``b``'s values
- If a list, values from ``b`` are appended to ``a``
Copying is minimized. No input collection will be mutated, but a deep copy
is not performed.
Parameters
----------... |
def render_filter(pattern: list):
"""
take the --filter argument list and return a k,v dict
:param pattern: type list
:return: pattern dict
"""
result = dict()
for item in pattern:
k, v = item.split(":")
result.update({k: v})
return result |
def convert_str_version_number(version_str):
"""
Convert the version number as a integer for easy comparisons
:param version_str: str of the version number, e.g. '0.33'
:returns: tuple of ints representing the version str
"""
version_numbers = version_str.split('.')
if len(version_number... |
def _compute_olympic_average(scores, dropped_scores, max_dropped_scores):
"""Olympic average by dropping the top and bottom max_dropped_scores:
If max_dropped_scores == 1, then we compute a normal olympic score.
If max_dropped_scores > 1, then we drop more than one scores from the
top and bottom and ave... |
def line_segment_intersection(p1, p2, p3, p4):
"""
- Compute the intersect of two line segments if exists
- Input:
- p1, p2 (two end points of line segment 1; L1)
- p3, p4 (two end points of line segment 2; L2)
- Output:
- (px, py) the intersect of two segments L1 and L2 i... |
def convert_tx_id(tx_id):
"""
Converts the guid tx_id to string of 16 characters with a dash between every 4 characters
:param tx_id: tx_id to be converted
:return: String in the form of xxxx-xxxx-xxxx-xxxx
"""
return (tx_id[:4] + '-' + tx_id[4:])[:19] |
def transform(timescale, dt):
"""
Transform timescale to omega
Parameters
----------
timescale : float or array
dt : float
Returns
-------
float
"""
return 0.5 * (dt / timescale) ** 2 |
def _fmt_col_rpt(col):
"""
Format rpt row for missing required column.
Parameters
----------
col : str
pd.DataFrame column name
Returns
-------
dict
Rpt row for missing required column
"""
return {
'inval_line': 'All',
'inval_col': col,
... |
def todict(conn_string, kwargs):
"""Converts the input connection string into a dictionary.
Assumption: Connection string is of the format
'driver=couchdb;server=localhost;uid=database_uid;pwd=database_pwd'
"""
ret = {}
conn_dict = {}
for c_str in conn_string:
arr = c_str.split(';')... |
def basic(context, name="world"):
"""Say hello.
This can be tested easily using cURL from the command line:
curl http://localhost:8080/ # Default value via GET.
curl http://localhost:8080/Alice # Positionally specified via GET.
curl -d name=Eve http://localhost:8080/ # Form-encoded value via POST.
"""
... |
def nodigits(s):
""" Remove #s from the string """
return ''.join([i for i in s if not i.isdigit()]) |
def _str_jobid(msg) :
"""Returns (str) job Id from input string.
E.g. returns '849160' from msg='Job <849160> is submitted to queue <psnehq>.'
"""
fields = msg.split()
if len(fields)<2 : return None
if fields[0] !='Job' : return None
return fields[1].lstrip('<').rstrip('>') |
def add_pkg_to_pkgs(pkg, pkgs):
"""Add package to dictionary of packages.
"""
name = pkg["Source"]
version = pkg["Version"]
pkgs[name][version] = pkg
return pkgs |
def pick_from_list(items, suffix):
""" Pick an element from list ending with suffix.
If no match is found, return None.
:param items list of items to be searched.
:suffix String suffix defining the match.
"""
match = None
for item in items:
if item.endswith(suffix):
mat... |
def progress_bar(percent_progress, saturation=0):
""" This function creates progress bar with optional simple saturation mark"""
step = int(percent_progress / 2) # Scale by to (scale: 1 - 50)
str_progress = '#' * step + '.' * int(50 - step)
c = '!' if str_progress[38] == '.' else '|'
if (saturati... |
def error_format(search):
"""
:param search: inputted word
:return: bool.
Checking every element in the inputted word is in alphabet.
"""
for letter in search:
if letter.isalpha() is False:
return True |
def remove(numlist):
"""Removes negative numbers and numbers above 100 from a list"""
numremove = []
for item in numlist:
if item < 0 or item > 100:
numremove.append(item)
for item in numremove:
numlist.remove(item)
return (numlist) |
def _is_dumbcaps(line):
"""Is this line mostly in dumbcaps?
Dumbcaps is like so: ``D U M B H E A D E R''.
"""
good = bad = 0
seen_space = True
for c in line:
if c == ' ':
if not seen_space:
good += 1
seen_space = True
else:
i... |
def find_channel_title(item):
"""Channel Title of the channel that published the video"""
channel_name = item['snippet']['channelTitle']
return channel_name |
def _get_conv_shape_1axis(
image_shape, kernel_shape, border_mode, subsample, dilation=1
):
"""This function compute the output shape of convolution operation.
Copied and simplified from theano (2020/11/08):
https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/abstract_conv.py
Parameter... |
def is_standalone_name(list_name, stand_alone_words):
"""Return True if standalone name."""
if any(stand_alone in list_name for stand_alone in stand_alone_words):
return True
return False |
def getArg(seq, index, default=None, func=lambda x: x):
"""Returns func(seq[index]), or 'default' if it's an invalid index"""
try:
return func(seq[index])
except IndexError:
return default |
def kw_pop(*args, **kwargs):
"""
Treatment of kwargs. Eliminate from kwargs the tuple in args.
"""
arg = kwargs.copy()
key, default = args
if key in arg:
return arg, arg.pop(key)
else:
return arg, default |
def represents_int(s):
"""
Is it an integer
:param s: String to be tested
:return: True if interger, False otherwise
"""
try:
int(s)
return True
except ValueError:
return False |
def makeiter(var):
"""Converts a variable into a list of it's not already an iterable (not including strings.
If it's already an iterable, don't do anything to it.
Parameters
------------
var
the variable to check.
Returns
------------
var
an iterable versio... |
def bool_from_user_str(bool_string):
"""Parse a string description of a hlwm boolean to
a python boolean"""
if bool_string.lower() in ['true', 'on']:
return True
if bool_string.lower() in ['false', 'off']:
return False
raise Exception(f'"{bool_string}" is not a boolean') |
def VirtualTempFromMixR(tempk, mixr):
"""Virtual Temperature
INPUTS:
tempk: Temperature (K)
mixr: Mixing Ratio (kg/kg)
OUTPUTS:
tempv: Virtual temperature (K)
SOURCE: hmmmm (Wikipedia). This is an approximation
based on a m
"""
return tempk * (1.0+0.6*mixr) |
def fromiter(iterable):
"""
Construct a binary number from a finite iterable, where the ith bit
from the right is the truth value of the iterable's ith item.
:param iterable: any iterable, usually one with boolean values.
:type iterable: Iterable
:return: the binary number.
:rtype: int
... |
def calc_max_quant_value(bits):
"""Calculate the maximum symmetric quantized value according to number of bits"""
return 2**(bits) - 1 |
def count_if(predicate, iterable):
"""Count the number of items of an iterable that satisfy predicate."""
return sum(1 for item in iterable if predicate(item)) |
def bytes_to_int(bytes: bytes) -> int:
"""
Helper function, convert set of bytes to an integer
"""
result = 0
for b in bytes:
result = result * 256 + int(b)
return result |
def peters_f(e):
"""f(e) from Peters and Mathews (1963) Eq.17
This function gives the integrated enhancement factor of gravitational
radiation from an eccentric source compared to an equivalent circular
source.
Parameters
----------
e : `float/array`
Eccentricity
Returns
-... |
def get_ref_path(openapi_major_version):
"""Return the path for references based on the openapi version
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
ref_paths = {2: 'definitions',
3: 'components/schemas'}
... |
def KK_RC6_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
r... |
def check_quote_in_text(quote_string, citation_text):
"""Returns True if the input quote is anywhere in the input text, and False if not"""
return bool(citation_text.find(quote_string) != -1) |
def human_readable_to_bytes(value: int, unit: str) -> int:
"""
Converts the given value and unit to bytes.
As an example, it should convert (8, GB) to 8388608.
Even though technically MB means 1000 * 1000, many producers actually mean
MiB, which is 1024 * 1024. Even Windows displays as unit MB, eve... |
def did_run_test_module(output, test_module):
"""Check that a test did run by looking in the Odoo log.
test_module is the full name of the test (addon_name.tests.test_module).
"""
return "odoo.addons." + test_module in output |
def remove_unencodable(str_: str) -> str:
"""
:type str_: str
:param str_: string to remove unencodable character
:return: string removed unencodable character
"""
s = str_.replace("\xb2", "")
s = s.replace("\u2013", "")
s = s.replace("\u2019", "")
return s |
def _to_gj_polyline(data):
"""
Dump a GeoJSON-like MultiLineString object to WKT.
Input parameters and return value are the MULTILINESTRING equivalent to
:func:`_dump_point`.
"""
return {
'type': 'MultiLineString',
'coordinates': [
[((pt[0], pt[1]) if pt else None) f... |
def multiply_a_list_by(a_list, number):
"""Return a list with every item multiplied by number."""
return [item * number for item in a_list] |
def offsets_to_cell_num(y_offset, x_offset):
"""
:param y_offset: The y_offset inside a block. Precondition: 0 <= y_offset < 3
:param x_offset: The x_offset inside a block. Precondition: 0 <= x_offset < 3
:return: The cell number inside a block
"""
return 3 * y_offset + x_offset |
def is_flow_cell_owner(user, flow_cell):
"""Whether or not user is owner of the given flow cell"""
if not flow_cell:
return False
else:
return flow_cell.owner == user |
def crop_string_middle(s, length=32, cropper='...'):
"""Crops string by adding ... in the middle.
Args:
s: String.
length: Length to crop to.
Returns:
Cropped string
"""
if len(s) <= length:
return s
half = (length - len(cropper)) // 2
return s[:half] + crop... |
def simpleProcessor(line, prefix):
""" Processes a simple history (e.g .bash_history)
a simple history is defined as a type of history file that contains nothing but one command in each line
"""
return line.replace(prefix, '').split(' ') |
def parseFileNameString(s):
"""Returns a list of files contained in the string."""
l = []; i = 0; N = len(s)
while i < N:
while s[i] == " ": i += 1
if s[i] == "{":
k = i+1
while k < N and s[k] != "}": k += 1
l.append(s[i+1:k])
i = k+1
... |
def find_widest_key(categories):
"""Returns width of widest key for formatting.
"""
widest_key = 0
for key in categories:
if len(key) > widest_key:
widest_key = len(key)
return widest_key |
def getHash(rawData):
"""
"""
hash = dict([ (rawData[i],rawData[i+1]) for i in range(0,len(rawData)-1,2) ])
return hash |
def xnor(*bools):
"""Takes first 2 elements and calc xnor, then use result to calc xnor with 3rd element etc"""
result = bools[0] == bools[1]
for b in bools[2:]:
result = result == b
return result |
def binstr2dec(bstr):
"""Convert binary string representation of an integer to a decimal integer.
"""
return int(bstr, base=2) |
def beautify_task(cat, subcat, name):
"""HTML format NRDiag task elements for pretty graphing"""
label_template = '<<FONT FACE="arial bold">{cat}</FONT><br/>{subcat}<br/>{name}>'
return label_template.format(cat=cat, subcat=subcat, name=name) |
def timer_list(duration, interval):
"""
reset timer list
main loop will check timer list and pop the head item to consume
:return: list consists of second (0, 30, 60, ... 1800)
"""
count = int(duration / interval)
l = []
for c in range(count + 1):
l.append(c * interval)
ret... |
def split_proj_name(proj_name):
"""Split projection name.
Projections named as follows: ${transcript_ID}.{$chain_id}.
This function splits projection back into transcript and chain ids.
We cannot just use split("."), because there might be dots
in the original transcript ID.
"""
proj_name_s... |
def _last_char(word):
"""Get last alphanumeric character of word.
:param word: word to get the last letter of.
"""
for i in range(len(word)):
if word[len(word)-1-i].isalpha() or word[len(word)-1-i].isdigit():
return len(word) - 1 - i
return -1 |
def format_args(arg_type, text):
"""Format args based on type"""
if arg_type == 'list':
args_text = text.strip().split()
else:
args_text = text.strip()
return args_text |
def removeNullTerminator(bytestring):
"""Remove null terminator from bytestring"""
bytesOut = bytestring.rstrip(b'\x00')
return bytesOut |
def _convert_terms_to_spin_blocks(terms, n_orbitals: int, n_spin_components: int):
"""
See explanation in from_openfermion in conversion between conventions of netket
and openfermion.
Args:
terms: the operator terms in tuple tree format
n_orbitals: number of orbitals
n_spin_comp... |
def convert_raw_cookie2dict(raw_cookie: str) -> dict:
"""
Convert cookie string which copied from browser
:param raw_cookie: string
:return: dict
"""
return {i.split("=")[0]: i.split("=")[-1] for i in raw_cookie.split("; ")} |
def is_port(port):
"""
returns true if the port is within the valid IPv4 range
"""
if port >= 0 and port <= 65535:
return True
return False |
def delta16(v1, v2):
"""Return the delta (difference) between two increasing 16-bit counters,
accounting for the wraparound from 65535 back to 0"""
diff = v2 - v1
if diff < 0:
diff += (1<<16)
return diff |
def f(coord, a0, a1, a2, a3, a4, a5, a6, a7, a8):
"""Evaluate 2-d function by: a0*x**2*y**2 + a1*x**2*y + ... + a8
Parameters:
coord: (x,y): (float, float)
a0,...,a8: float
"""
x, y = coord
#return a*x**2 + b*x*y + c*y**2 + d
return a0*x**2*y**2 + a1*x**2*y + a2*x**2 \
+... |
def get_stream_names(streams):
""" For an instrument, process streams (list of dictionaries), create list of stream names.
"""
stream_names = []
if streams:
for stream in streams:
if stream['stream'] not in stream_names:
stream_names.append(stream['stream'])
retur... |
def compress_amount(n):
"""\
Compress 64-bit integer values, preferring a smaller size for whole
numbers (base-10), so as to achieve run-length encoding gains on real-
world data. The basic algorithm:
* If the amount is 0, return 0
* Divide the amount (in base units) evenly by the larges... |
def write_sq_normal(fname,qs,sq):
"""
Write S(Q) data in normal, gnuplot-readable format.
"""
nd = len(qs)
with open(fname,'w') as f:
f.write('# S(Q) computed in rdf.py\n')
f.write('# Q, S(Q)\n')
for i in range(nd):
f.write(' {0:10.4f} {1:10.5f}\n'.fo... |
def calc_iou(box1, box2):
"""
:param box1: list of coordinates: row1, row2, col1, col2 [list]
:param box2: list of coordinates: row1, row2, col1, col2 [list]
:return: iou value
"""
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
xB = min(box1[2], box2[2])
yB = min(box1[3], bo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.