content stringlengths 42 6.51k |
|---|
def rewrite_email_address(email):
""" Prettify the email address (and if it's empty, skip it by
returning None). """
if not email:
return
email = email.strip()
if not email:
return
if email[0]=='<' and email[-1] == '>':
email = email[1:-1]
# If it doesn't look like em... |
def depair(z):
"""
Pairing function inverse
"""
import math
w = math.floor((math.sqrt(8 * z + 1) - 1)/2)
t = (w**2 + w) / 2
y = int(z - t)
x = int(w - y)
# assert z != pair(x, y, safe=False):
return x, y |
def create_query_sting(param_dict):
""" turns a dict into a query string
:param param_dict: a dictionary
:type param_dict: dict
:return: a clean query string
:rtype: str
"""
params = "&".join(
[
f"{key}={value}" for key, value in param_dict.items()
]
)
r... |
def show_registration_disabled_collapse(n_clicks, is_open):
"""
Toggle the registration info div.
"""
if n_clicks:
return not is_open
return is_open |
def is_tcp_rst(tcp_data):
"""is TCP RST?"""
return tcp_data["flags"]["rst"] == 1 |
def helper(n, largest):
"""
:param n: int,
:param largest: int, to find the biggest digit
:return: int, the biggest digit in n
Because digit < 10, this function recursively check every digit of n
"""
remainder = n % 10
if n < 10: # Base case!
if remainder > largest:
return remainder
else:
return larg... |
def compute_num_cells(max_delta_x, pt0x, pt1x):
"""compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber)
Args:
max_delta_x (double): User defined maximum grid spacing.
pt0x (double): x-coordinate of bottom LHS cookstove combustion chamber
... |
def colorize(shape, fill, stroke, strokeWidth):
"""Change the color of the input shape."""
if shape is None: return None
new_shape = shape.clone()
new_shape.fillColor = fill
if strokeWidth > 0:
new_shape.strokeColor = stroke
new_shape.strokeWidth = strokeWidth
else:
new_s... |
def caseiter_to_dict(caseiter, varnames, include_errors=False):
"""
Retrieve the values of specified variables from cases in a CaseIterator.
Returns a dict containing a list of values for each entry, keyed on
variable name.
Only data from cases containing ALL of the specified variables wi... |
def format_args(args):
"""
:param args: the args to be formated
:return: the args formated
"""
args_formated = list()
args_formated.append(round(args[0], 3))
args_formated.append(round(args[1], 2))
args_formated.append(round(args[2], 5))
args_formated.append(int(args[3]))
retur... |
def _output_format(command):
"""Determine the output format for a given command."""
if 'chartjson' in command:
return 'chartjson'
elif 'valueset' in command:
return 'valueset'
return 'buildbot' |
def test_sqrs(_x, _n=2):
"""This function"""
if _x == 0 or _x == 1:
return _x
sqr = 1
while _n > 0:
sqr = sqr * _x
_n = _n - 1
return sqr |
def _compare_data(stored, desired, idx=0):
"""Calculate the virtual to be added, modified, deleted
"""
add = []
modify = []
delete = []
current = 0
total_stored = len(stored)
for virtual in desired:
while current < total_stored and virtual[idx] > stored[current][idx]:
... |
def count_a(seq):
""""THis function is for counting the number of A's in the sequence"""
# Counter for the As
result = 0
for b in seq:
if b == "A":
result += 1
# Return the result
return result |
def remove_metadata_fields(fields):
""" Strip out fields added during aggregation. """
stage = {"$project": {}}
for field in fields:
stage['$project'][field] = 0
return stage |
def get_name_from_equivalent_ids(equivalent_ids):
"""find name from equivalent id dict
params
------
equivalent_ids: a dictionary containing all equivalent ids of a bio-entity
"""
if not equivalent_ids:
return None
if equivalent_ids.get('bts:symbol'):
return equivalent_i... |
def _to_full_shapes(shapes, device_num):
"""Expanding batch dimension according to device_num, adapt to mindspore minddata graph solution."""
new_shapes = []
for shape in shapes:
new_shape = ()
for i, item in enumerate(shape):
if i == 0:
new_shape += (item * devic... |
def valid_move(moves):
"""
Valid Move checks if a position on the board is taken.
Input: all moves
Returns True if board position not taken. False if board position already
taken.
"""
for move in reversed(moves):
if moves.count(move) > 1:
return False
else:
... |
def readout_default(parameters = None):
"""
This is the most basic function to read values from
a set of Parameters within qcodes.
Arguments:
values ... List of tuples of the form:
[(instance_of_control1,value1), ...]
"""
if parameters != None:
list_of_results = li... |
def get_seq_part_from_assembly( content, contig_name, start, end ):
"""! @brief get seq from start to end; returns modified start and end position, if contig is shorter than requested sequence """
if end > len( content[ contig_name ] ):
if start < 0:
return content[ contig_name ], 0, len( content[ contig_name ... |
def rank(value_to_be_ranked, value_providing_rank):
"""
Returns the rank of ``value_to_be_ranked`` in set of values, ``values``.
Works even if ``values`` is a non-orderable collection (e.g., a set).
A binary search would be an optimized way of doing this if we can constrain
``values`` to be an order... |
def convert_str_tags_to_list(i):
"""
Input: either a list, or a string of comma-separated tags.
Output: If i is a list, it's returned.
If i is a string, the list of tags it represents is returned
(each tag is stripped of leading and trailing whitespace).
"""
r=[]
if... |
def estarmap(func, iter_, **kwargs):
"""
Eager version of it.starmap from itertools
Note this is inefficient and should only be used when prototyping and
debugging.
"""
return [func(*arg, **kwargs) for arg in iter_] |
def find_judge(N, trust):
"""
Inputs:
N -> int
trust -> List[List[int]]
Output:
int
"""
# Your code here
# base case - list is empty?
if len(trust) < N - 1:
return -1
# indegree ---> num of directed edges into a vertex == N-1
# outdegree ---> num of directed edge... |
def ft_id_parser(description):
"""return a dict of {'Description':,'Id':} from raw decription str
Examples.
FT PROPEP 25 48
FT /FTId=PRO_0000021449.
FT VARIANT 214 214 V -> I.
FT /FTId=VAR_009122.
FT ... |
def probability_in_range(probability: float, delta: float):
"""Note that this check must not be used for probability densities."""
return (probability >= -delta) and (probability <= 1 + delta) |
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i for v_i, w_i in zip(v, w)) |
def get_chunk_label(tot_minutes: int) -> str:
"""Returns a readable elapsed time."""
hours, minutes = divmod(tot_minutes, 60)
return f"{hours:02}h:{minutes:02}m" |
def equalize_string_lengths(arr, side = 'left'):
"""
Equalize the lengths of the string representations of the contents of the array.
:param arr:
:return:
"""
assert side in ('left', 'right')
strings = [str(x) for x in arr]
longest = max(len(x) for x in strings)
if side=='left':
... |
def extract_wikipedia_page(line):
"""Extracts the Wikipedia page for an entity"""
if "sitelinks" in line and "enwiki" in line["sitelinks"]:
return line["sitelinks"]["enwiki"]["title"].strip().replace(" ", "_")
return None |
def path2FileName(path):
"""Answer the file name part of the path.
>>> path2FileName('../../aFile.pdf')
'aFile.pdf'
>>> path2FileName('../../') is None # No file name
True
"""
return path.split('/')[-1] or None |
def is_float(string):
"""Check whether string is float.
See also
--------
http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
"""
try:
float(string)
return True
except ValueError:
return False |
def to_text(value, encoding="utf-8"):
"""Convert value to unicode, default encoding is utf-8
:param value: Value to be converted
:param encoding: Desired encoding
"""
if not value:
return ""
if isinstance(value, str):
return value
if isinstance(value, bytes):
return ... |
def is_valid_matrix1D(lst):
"""
Checks if there is at least one positive value in the given 1 dimensional list.
:param lst: list of elements
:return: True if at least one positive value exist otherwise false.
"""
for i in range(0, len(lst)):
if lst[i] > 0.0:
return True
... |
def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
for from_,to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
... |
def history_ping_field_names():
"""Return the field names of the packet loss stats.
Returns:
A tuple with 3 lists, the first with general stat names, the second
with ping drop stat names, and the third with ping drop run length
stat names.
"""
return [
"samples",
], ... |
def fixHTML(text):
"""replaces html-markup parts on tags"""
return str(text).replace("&", "&") \
.replace("<", "<") \
.replace(">", ">") |
def remarks(rmk):
"""Function to format remarks."""
d = {'parsed' : 'None', 'string' : 'N/A'}
if rmk == 'None':
return d
return {'parsed' : f'RMK {rmk}', 'string' : rmk} |
def compute_packet_csum(pkt):
"""Computes the checksum for the given GDB packet"""
csum = 0
for x in pkt:
csum += x
csum = csum & 0xFF
return csum |
def swap(password, swap_type, position_x, position_y):
"""Swap position_x and position_y.
If swap_type is 'letter' swap indices of corresponding letters.
"""
if swap_type == 'letter':
position_x = password.index(position_x)
position_y = password.index(position_y)
password[position_x... |
def patharg(path):
"""Back slashes need to be escaped in ITEM args, even in Windows paths."""
return path.replace('\\', '\\\\\\') |
def max(x, y):
"""
``max :: a -> a -> a``
Maximum function.
"""
return x if x >= y else y |
def calc_iou(recs):
"""
recs: A tuple containing two tuples, each representing a rectangle
returns: Float. The calculated intersection over union metric.
"""
recA, recB = recs
xminA, yminA, xmaxA, ymaxA = recA
areaA = (xmaxA-xminA) * (ymaxA-yminA)
xminB, yminB, xmaxB, ymaxB = recB... |
def get_value_in_state(key, state):
"""
Retrieve a potentially nested value in an object
:param key: the `.` separated key (i.e: a.b.c.d)
:param state: the object to access the key in
:return: the value in the state
"""
def traverse(hierarchy, current):
level = hierarchy.pop(0)
... |
def chunk(l, n):
""" Returns list l chunked into lists of length n
"""
if n < 1:
n = 1
return [l[i:i+n] for i in range(0, len(l), n)] |
def jars_from_output(output):
"""Collect jars for intellij-resolve-files from Java output."""
if output == None:
return []
return [jar
for jar in [output.class_jar, output.ijar, output.source_jar]
if jar != None and not jar.is_source] |
def sum_edge_weight(acc, w1, w2):
"""Sums up edge weights. This results in edge weights that are
dominated by dominant figures.
"""
return acc + w1 + w2 |
def _strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', '0' and ''. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y',... |
def Prepare_Suffix_List(suffix_list):
"""
Adds regular expression parts to given suffixes
"""
new_suffix_list = []
for suffix in suffix_list.split():
regex_suffix = r"(?<=\w)" + suffix + r"(?=\s)"
new_suffix_list = new_suffix_list + [regex_suffix]
return new_suffix_list |
def process_predictor_args(predictors, params=None, sds=None):
"""Returns a predictor data structure for the given lists of predictors, params,
and standard deviations.
When no parameters or deviations are provided, the predictors are a simple
list. When parameters and deviations are provided, the pred... |
def find_letter(letters, l, index):
"""
Find the first occurrence of a letter in a word after a given index.
Searches forward in the word after index-th letter. If no matching letter is found,
search backwards for the latest occurrence before the index-th letter.
:return: index of the found occurr... |
def check_min_boundary_of_measurement(value, boundary):
"""
:return:
"""
if boundary is None:
return None
elif float(value) > float(boundary):
return True
else:
return False |
def build_bootstrap(ba, metadata):
""" Helper function to construct BA action """
ba_name = ba.get('bootstrapName')
ba_path_with_args = ba.get('bootstrapScript').split()
ba_path = ba_path_with_args[0]
ba_args = ba_path_with_args[1:]
if not 's3://' in ba_path:
ba_path = '{}/{}'.format(me... |
def get_dict(obj):
""" accept dict or querydict, return a dict (or the object, if None or neither) """
if isinstance(obj, dict):
return obj
if hasattr(obj, 'dict'):
return obj.dict()
return obj |
def CalculateListAverage(values):
"""Computes the arithmetic mean of a list of numbers."""
values = [x for x in values if x != None]
if not values:
return 0
return sum(values) / float(len(values)) |
def chunks_to_string(chunks):
"""
Parameters
----------
chunks : list of strings
A list of single entities in order
Returns
-------
string :
A LaTeX-parsable string
Examples
--------
>>> chunks_to_string(['\\\\sum', '_', 'i', '^', 'n', 'i', '^', '2'])
'\\\\s... |
def grplst2str(acsiter):
""" A helper function for names of Groups """
return ",".join([ac.name for ac in acsiter]) |
def V2lambda(V):
"""
Takes a neutron velocity V in m/s and converts it to lambda in angstroms
"""
return(3956/V) |
def filter_by_attribute(data, attribute, required_key):
"""
Filters by attribute, if value is required_key.
Example `attribute`: `category`. Example `required_key`: `Permissive`.
"""
return [entry for entry in data if entry.get(attribute, 'None') == required_key] |
def check_obj(obj):
""" Check if object exists """
if obj:
return True
else:
return False |
def rule(cond, metric="foo", increment="1"):
"""
A rule for the custom metric policy
"""
return {"metric": metric,
"increment": increment,
"condition": cond,
"combine_op": "and"
} |
def values_equal(value_a, value_b, precision=0.000001):
"""
>>> values_equal(1.022, 1.02, precision=0.01)
True
>>> values_equal([1.2, 5.3, 6.8], [1.1, 5.2, 6.9], precision=0.2)
True
>>> values_equal(7, 5, precision=2)
True
>>> values_equal(1, 5.9, precision=10)
True
>>> values_eq... |
def camel_to_space(s):
"""Replace low dashes with spaces.
Parameters
----------
s : str
String that may contain "_" characters.
"""
return " ".join(s.split("_")) |
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:pa... |
def fourSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
sum_target = []
first = 0
while first < len(nums)-3:
sec = first + 1
while sec < len(nums)-2:
third = sec+1
fourth = len(nums)-1
... |
def primeiroElemento(lista: list) -> str:
"""
Devolve primeiro elemento de uma string
Parameters
----------
lista : list
lista de strings
Returns
-------
string : str
primeira string da lista
"""
try:
return lista[0]
except:
... |
def _InsertQuotes(string, left_index, right_index):
"""Insert quotes in the passed string.
Args:
string: A string in which quotes will be inserted.
left_index: An integer representing the index where
starting quote will be inserted.
right_index: An integer representing the index where
closi... |
def get_client_options():
"""Returns mock options for TargetClient.create"""
return {
"client": "testingclient",
"organization_id": "11D1C9L459CE0AD80A495CBE@AdobeOrg"
} |
def upconvert_to_list(list_or_dict):
"""
Packed CWL workflow inputs/outputs are structured as lists of dicts (e.g.
[{'id': 'input_file', 'type': 'File'},...]). Unpacked workflows may have
dicts (e.g. {'input_file': 'File'}. This function converts the dicts into
lists of dicts or returns the list
... |
def set_input_container(_container, cfg):
"""Save the input for the container in the configurations."""
if not _container:
return False
if _container.exists():
cfg["container"]["input"] = str(_container)
return True
return False |
def dict_reformat_keys(obj, format_func):
"""Convert a dictionary's keys from one string format to another.
Parameters
----------
obj : dict
A dictionary with keys that need to be reformatted
format_func : function
Will execute on each key on the dict
Returns
-------
di... |
def fibonacci(elements_num):
"""
Calculating fibonacci sequence
"""
sequence = []
for i in range(1, elements_num + 1):
if i <= 2:
sequence.append(1)
continue
next_num = sequence[-2] + sequence[-1]
sequence.append(next_num)
return sequence |
def inverse(a, n):
"""Find the inverse of a modulo n if it exists"""
t = 0
newt = 1
r = n
newr = a
while newr != 0:
quotient = int((r - (r % newr)) / newr)
tt = t
t = newt
newt = tt - quotient * newt
rr = r
r = newr
newr = rr - quotient * n... |
def local_temp(A, albedo, T, q=30):
"""Calculate local temperature experienced by a particular daisy type or
ground cover. This is a simplified version of the original.
q*(A-albedo)+T
Arguments
---------
A : float
Planetary albedo
alpha : float
Albedo of daisy type
T : f... |
def _f(fpath, dir_):
"""
Helper function for contains_parent_dir function.
"""
return fpath.startswith(dir_) |
def convert_frequency_counts_to_rank_frequency(frequency_counts):
"""
Input a a frequency counts distribution
frequency_counts[j] = # of tokens that have a frequency count of j
Output a frequency distribution of how many words of each rank appeared
rank_frequency[i] = # of occurences of ith ranked word
"""
rank... |
def two_to_n_mod_10_to_m(n, m):
"""Successive squaring. Very fast and handles very large numbers.
1. Rewrite 2^n so that n is a sum of powers of two.
2. Create a list of powers 2^(2^i) mod 10^m, by repeatedly squaring the prior result.
3. Combine, with multiplication mod 10^m, the powers in the list th... |
def location_to_field_association(loc):
"""Helper to map location to VTK/Enum value"""
if loc == "Point":
return 0
if loc == "Cell":
return 1
if loc == "Field":
return 3
return 4 |
def display_name_to_class(value):
""" Converts an aggregation display name to a string that is usable as a CSS class name """
return value.replace(" ", "_").lower() |
def _inclusive_range(start, stop=None, step=1):
"""return a range i <= j <= k
if k is not provided, return a range containing only i.
step is also supported and defaults to 1
"""
if stop is None:
stop = start
stop += 1
return range(start, stop, step) |
def fatorial(num):
"""Fazer o fatorial do numero.
Args:
param [num]: o numero a ser calculado.
opcao[s]: mostra o processo do calculo.
Returns:
Retorna o fatorial.
"""
f=1
for n in range(num,0,-1):
f*=n
return f |
def has_entry_by_id(id_key, id_key_value, dict):
"""return true if the dict entry has matching key value"""
for value in dict.values():
if value[id_key] == id_key_value:
return True
return False |
def combination_matches(combination, match_combinations):
"""
Checks if the given combination is matches for any of the given combination
globs, being those a set of combinations where if a key is missing, it's
considered matching
(key1=2, key2=3)
would match the combination match:
(key2=3... |
def merge_dicts(*dicts):
"""
Merges two or more dicts. If there are duplicate keys, later dict arguments take precedence.
Null, empty, or non-dict arguments are qiuetly skipped.
:param dicts:
:return:
"""
res = {}
for d in dicts:
if not d or type(d) != dict:
continue... |
def alloc_lists(num_alloc):
"""allocates space for a ``list`` of lists"""
return [[] for _ in range(num_alloc)] |
def true_bin_repr(A: int, num_bits=4) -> int:
"""For negative numbers, noop for positive numbers since they're already in proper form
Args:
A:
num_bits:
Returns:
Examples:
>>> bin(true_bin_repr(~int("0001", 2), num_bits=4))
'0b1110'
>>> true_bin_repr(~int("0001... |
def value_len_eq_2(value):
"""
Validates that the length of the paramter is equal to 2.
Assumes that value is an interable.
Returns:
int: 0 (FAIL) if length != 2, otherwise 1 (PASS).
"""
if len(value) != 2:
return 0
return 1 |
def extract_lmjrect_pascalvoc(label_dict):
"""Extracts box coordinates from lmjson labels to pascalvoc
Args:
label_dict (dict): lmjson label dictionary
Returns:
list: Box coordinates in Pascalvoc
[x_min, y_min, x_max, y_max]
"""
x_min = label_dict["points"][0][0]
... |
def complement(c):
"""
:param c: Nucleotide to get complement of
:return: character representing the complement of 'c'
"""
base_pairs = {
'A': 'T',
'C': 'G',
'G': 'C',
'T': 'A',
'N': 'N'
}
try:
return base_pairs[c.upper()]
except KeyError:
... |
def compute_binhash(s):
"""Compute a hash used in BIN files
FNV-1a hash, on lowercased input
"""
h = 0x811c9dc5
for b in s.encode('ascii').lower():
h = ((h ^ b) * 0x01000193) % 0x100000000
return h |
def search_genre(plot):
"""
>>> search_genre(['get up', 'discussion'])
['drama', 'drama']
"""
genre = ['drama', 'drama']
return genre |
def add_tbd_repos(tbd_repos):
"""
return the list of dummy entries for some repos, the information will be filled up later.
"""
tbd_rows = []
if len(tbd_repos) > 0:
for repo_url in tbd_repos:
if '/' in repo_url:
tbd_rows.append({
'repo_url'... |
def text_transform(ftpp, filename, content):
"""
If filename is *rss.xml*,
replaces the string *__BLOG_ROOT__* by *self._root_web*.
@param ftpp object FolderTransferFTP
@param filename filename
@param content content of the file
@return new conte... |
def _get_temperature_from_buffer(data):
"""This function reads the first two bytes of data and
returns the temperature in C by using the following function:
T = =46.82 + (172.72 * (ST/2^16))
where ST is the value from the sensor
"""
unadjusted = -46.85 + 175.72 * ((data[0] << 8) + (data[1] & 0xf... |
def consensus_decision(consensus):
""" Given a consensus dict, return list of candidates to delete/archive.
"""
delete = []
archive = []
for k, v in consensus.items():
tags = v['tags']
if 'delete' in tags or 'rfi' in tags:
delete.append(k)
elif 'archive' in tags ... |
def plus(a, b):
"""add vectors, return a + b """
return [a[i] + b[i] for i in range(len(a))] |
def binary(n,count=16,reverse=False):
"""
Display n in binary (only difference from built-in `bin` is
that this function returns a fixed width string and can
optionally be reversed
>>> binary(6789)
'0001101010000101'
>>> binary(6789,8)
'10000101'
>>> ... |
def get_available_port(curr_port, ports_dict):
"""Method to recursively check for available
ports in provided ports_dict
:param curr_port: port to be replaced
:type curr_port: str
:param ports_dict: dict to check available ports
:type ports_dict: dict
:return: next available port
:rt... |
def get_circle_points(xy, radius):
""" Returns tuples of (x0, y0), (x1, y1) for a circle centered at x, y with radius
Arguments:
xy: tuple of x, y coordinates
radius: radius of circle to draw
Returns:
[(x0, y0), (x1, y1)] for bounding box of circle centered at x, y
"""
x, y... |
def _check_values(set1: set, set2: set) -> int:
"""This checks how many of the values present inside of the first set are in the second set."""
match = 0
if set1.issuperset(set2):
match += 1
for item in set2:
if set1.issuperset({item}):
match += 1
return match |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.