content stringlengths 42 6.51k |
|---|
def area(a):
"""
Returns the area of a rectangle.
"""
if a is None: return 0
(x, y, w, h) = a
return w * h |
def corsikaConfigFileName(arrayName, site, primary, zenith, viewCone, label=None):
"""
Corsika config file name.
Parameters
----------
arrayName: str
Array name.
site: str
Paranal or LaPalma.
primary: str
Primary particle (e.g gamma, proton etc).
zenith: float
... |
def split_ado(string):
"""
a replacement for re
:param string: any string
:return: alpha, digit, other parts in a list
"""
prev_chr_type = None
acc = ""
parts = []
for c in string:
if c.isalpha():
cur_chr_type = "alpha"
elif c.isdigit():
cur_ch... |
def binary_mask_to_str(m):
"""
Given an iterable or list of 1s and 0s representing a mask, this returns
a string mask with '+'s and '-'s.
"""
m = list(map(lambda x: "-" if x == 0 else "+", m))
return "".join(m) |
def mnist_model_preprocess(image):
"""Processing which should be combined with model for adv eval."""
return 2. * image - 1. |
def preprocessText(text):
"""
This script parses text and removes stop words
"""
# Remove unwanted characters
unwanted_chars = set(["@", "+", '/', "'", '"', '\\', '', '\\n', '\n',
'?', '#', '%', '$', '&', ';', '!', ';', ':', "*", "_", "="])
for char in unwanted_chars:
... |
def inpath(entry, pathvar):
"""Check if entry is in pathvar. pathvar is a string of the form
`entry1:entry2:entry3`."""
return entry in set(pathvar.split(':')) |
def arg_list(items, prefix=''):
"""Process a list or string of arguments into a string containing them
Used so users can pass arguments as a string or list in the configuration file.
:param items:
:param prefix:
:return:
"""
if not items:
return ''
list_of_items = items.split(... |
def card_remover(decklist, card):
"""
Given a decklist and a card name, returns the decklist with the card removed.
Parameters:
decklist: list of str
A decklist represented by a list of strings of card names.
card: str
The card to be removed from the decklist
:ret... |
def my_str(in_str):
"""Convert a given string to tex-able output string.
"""
out_str = in_str.replace("_", "\\textunderscore ")
return out_str |
def count(generator):
"""Count the number of items in the stream."""
counter = 0
for _ in generator:
counter += 1
return counter |
def gen_all_party_key(all_party):
"""
Join all party as party key
:param all_party:
"role": {
"guest": [9999],
"host": [10000],
"arbiter": [10000]
}
:return:
"""
if not all_party:
all_party_key = 'all'
elif isinstance(all_party, di... |
def _merge_dicts(d, *args, **kw):
"""Merge two or more dictionaries into a new dictionary object.
"""
new_d = d.copy()
for dic in args:
new_d.update(dic)
new_d.update(kw)
return new_d |
def get_time_in_video(total_frames, frame_rate, curr_frame):
"""Calculate current time of video"""
# return (total_frames * frame_rate) / curr_frame
return curr_frame / frame_rate |
def strip_dav_path(path):
"""Removes the leading "remote.php/webdav" path from the given path.
:param str path: path containing the remote DAV path "remote.php/webdav"
:return: path stripped of the remote DAV path
:rtype: str
"""
if 'remote.php/webdav' in path:
return path.split('remote... |
def botobool(obj):
""" returns boto results compatible value """
return u'false' if not bool(obj) else u'true' |
def filterv(fn, *colls):
"""A greedy version of filter."""
return list(filter(fn, *colls)) |
def dicts_equal(lhs, rhs):
"""
>>> dicts_equal({}, {})
True
>>> dicts_equal({}, {'a': 1})
False
>>> d0 = {'a': 1}; dicts_equal(d0, d0)
True
>>> d1 = {'a': [1, 2, 3]}; dicts_equal(d1, d1)
True
>>> dicts_equal(d0, d1)
False
"""
if len(lhs.keys()) != len(rhs.keys()):
... |
def get_num(x: str) -> int:
""" Extracts all digits from incomig string """
return int(''.join(ele for ele in x if ele.isdigit())) |
def _select_encoding(consumes, form=False):
"""
Given an OpenAPI 'consumes' list, return a single 'encoding' for CoreAPI.
"""
if form:
preference = [
'multipart/form-data',
'application/x-www-form-urlencoded',
'application/json'
]
else:
pre... |
def str_to_int(exp):
"""
Convert a string to an integer.
The method is primitive, using a simple hash based on the
ordinal value of the characters and their position in the string.
Parameters
----------
exp : str
The string expression to convert to an int.
Returns
-------
... |
def convert_to_dict(obj):
"""Converts a OpenAIObject back to a regular dict.
Nested OpenAIObjects are also converted back to regular dicts.
:param obj: The OpenAIObject to convert.
:returns: The OpenAIObject as a dict.
"""
if isinstance(obj, list):
return [convert_to_dict(i) for i in ... |
def xenon1t_detector_renamer(input):
"""Function: xenon1t_detector_renamer
"""
if input.get("detector") == 'muon_veto':
input['detector'] = 'mv'
return input |
def envelope(value, minval, maxval):
"""Adjust `value` to be within min/max bounds."""
return min(max(value, minval), maxval) |
def is_c_func(func):
"""Return True if given function object was implemented in C,
via a C extension or as a builtin.
>>> is_c_func(repr)
True
>>> import sys
>>> is_c_func(sys.exit)
True
>>> import doctest
>>> is_c_func(doctest.testmod)
False
"""
return not hasattr(func,... |
def say_hello_something(config, http_context):
"""
"Hello <something>" using slug
Usage:
$ export XSESSION=`curl -s -k -X POST --data '{"username":"<user>", "password":"<password>"}' https://localhost:2345/login | sed -E "s/^.+\"([a-f0-9]+)\".+$/\1/"`
$ curl -s -k -H "X-Session:$XSESSION" "https://... |
def format_test_id(test_id) -> str:
"""Format numeric to 0-padded string"""
test_str = str(test_id)
test_str = '0'*(5-len(test_str)) + test_str
return test_str |
def gmof(x, sigma):
"""
Geman-McClure error function
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared) |
def get_bib_ident(cite_data):
"""Return the best identifier (ISBN, DOI, PMID, PMCID, or URL)"""
data = cite_data["data"]
return data.get(
"isbn", data.get("pmcid", data.get("pmid", data.get("doi", data.get("url"))))
) |
def change_zp(flux, zp, new_zp):
"""Converts flux units given a new zero-point.
**Note:** this assumes that the new zero-point is in the same magnitude system as the current one.
Parameters
----------
flux : float or array
Fluxes.
zp : float or array
Current zero-point for the ... |
def accumulate(combiner, base, n, term):
"""Return the result of combining the first n terms in a sequence and base.
The terms to be combined are term(1), term(2), ..., term(n). combiner is a
two-argument commutative, associative function.
>>> accumulate(add, 0, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5
... |
def decolumnify(columns):
"""Takes ['afkpuz', 'bglqv', 'chrmw', 'dinsx', 'ejoty']
and outputs abcdefghijklmnopqrstuvwxyz
"""
comp = ''
keyword_length = len(columns)
for row_num in range(len(columns[0])):
for column_num in range(keyword_length):
try:
c... |
def parse_target_from_json(one_target, command_line_list):
"""parse the targets out of the json file struct
Parameters
----------
one_target: dict
dictionary with all target's details
command_line_list: list
list to update with target parameters
"""
target_kind, *sub_type = ... |
def init_parameters(parameter):
"""Auxiliary function to set the parameter dictionary
Parameters
----------
parameter: dict
See the above function initTemplates for further information
Returns
-------
parameter: dict
"""
parameter['pitchTolUp'] = 0.75 if 'pitchTolUp' not in... |
def mac_byte_mask(mask_bytes=0):
"""Return a MAC address mask with n bytes masked out."""
assert mask_bytes <= 6
return ':'.join(['ff'] * mask_bytes + (['00'] * (6 - mask_bytes))) |
def get_idx(array_like, idx):
"""
Given an array-like object (either list or series),
return the value at the requested index
"""
if hasattr(array_like, 'iloc'):
return array_like.iloc[idx]
else:
return array_like[idx] |
def palindrome(my_str):
"""
Returns True if an input string is a palindrome. Else returns False.
"""
stripped_str = "".join(l.lower() for l in my_str if l.isalpha())
return stripped_str == stripped_str[::-1] |
def to_snippet(text, length=40):
"""Shorten a string with ellipses as necessary to meet the target length"""
if len(text) <= length:
return text
return text[:length-3] + '...' |
def compare_unhashable_list(s, t):
"""
Compare list of unhashable objects (e.g. dictionaries). From SO by Steven Rumbalski.
"""
t = list(t) # make a mutable copy
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t |
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))
if name == 'ndict':
name = 'dict'
ret... |
def vals_are_multiples(num, vals, digits=4):
"""decide whether every value in 'vals' is a multiple of 'num'
(vals can be a single float or a list of them)
Note, 'digits' can be used to specify the number of digits of accuracy
in the test to see if a ratio is integral. For example:
... |
def get_arb_formatted(input):
"""Arbitrary formatter takes a string and returns a string."""
return f'X{input}X' |
def build_constituents(sent_id: int, s: str) -> dict:
"""Generates a frame for a constituent tree JSON object."""
s = s.rstrip().lstrip()
open_bracket = s[0]
close_bracket = s[-1]
return {
'sentenceId': sent_id,
'labeledBracketing': f'{open_bracket}ROOT {s}{close_bracket}' if s[1:5]... |
def get_next_xtalk(expressions, tx_prefix=""):
"""Get the list of all the Near End XTalk a list of excitation. Optionally prefix can
be used to retrieve driver names.
Example: excitation_names ["1", "2", "3"] output ["S(1,2)", "S(1,3)", "S(2,3)"]
Parameters
----------
expressions :
list... |
def get_file_type(path):
""" Sort volume files by type. """
if 'alto/' in path:
if path.endswith('.xml') or path.endswith('.xml.gz'):
return 'alto'
return None
if 'images/' in path:
if path.endswith('.jp2'):
return 'jp2'
if path.endswith('.jpg'):
... |
def mapValues(function, dictionary):
""" Map `function` to the values of `dictionary`. """
return {key: function(value) for key, value in dictionary.items()} |
def strip_quotes(table_name):
"""
Strip quotes off of quoted table names to make them safe for use in index
names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
scheme) becomes 'USER"."TABLE'.
"""
has_quotes = table_name.startswith('"') and table_name.endswith('"')
retu... |
def _crc32(data, crc, table):
"""Calculates the 32-bit CRC value for the provided input bytes.
This computes the CRC values using the provided reversed form CRC table.
"""
crc = ~crc & 0xFFFFFFFF
for byte in data:
index = (crc ^ byte) & 0xFF
crc = (crc >> 8) ^ table[index]
ret... |
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c.
Note:
Copied without modification from Python 3.6.1 tokenize standard library module
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Sof... |
def formatter(type):
"""Format floating point numbers in scientific notation
(integers use normal integer formatting)."""
if type == int:
return "%d"
elif type == float:
return "%.3e" |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given color values."""
return '#%02x%02x%02x' % (red, green, blue) |
def get_hosted_zone_id(session, hosted_zone):
"""Look up Hosted Zone ID by DNS Name
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hosted_zone (string) : DNS Name of the Hosted Zone to loo... |
def booth(X, Y):
"""constraints=10, minimum f(1, 3)=0"""
return ((X) + (2.0 * Y) - 7.0) ** 2 + ((2.0 * X) + (Y) - 5.0) ** 2 |
def interval(mu,sigma):
""" methods of estimators """
a = mu - 4*sigma
b = mu + 4*sigma
return a, b |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled for... |
def getit(key, h):
"""Return h[key]. If key has '.' in it like static.max_fuel, return h[static][max_fuel]
getit('physics.tyre_wear', h') will get you h['physics']['tyre_wear'].
It's just syntactic sugar, but easier to read.
Exceptions are not catched
"""
if '.' in key:
keys = key.split... |
def apply_tariff(kwh, hour):
"""Calculates cost of electricity for given hour."""
if 0 <= hour < 7:
rate = 12
elif 7 <= hour < 17:
rate = 20
elif 17 <= hour < 24:
rate = 28
else:
raise ValueError(f'Invalid hour: {hour}')
return rate * kwh |
def real_units(bias, fb, mce_bias_r=467, dewar_bias_r=49, shunt_r=180E-6,
dewar_fb_r=5280, butterworth_constant=1218,
rel_fb_inductance=9, max_bias_voltage=5, max_fb_voltage=0.958,
bias_dac_bits=16, fb_dac_bits=14):
"""
Given an array of biases and corresponding arra... |
def timeout_check(value):
"""
Checks timeout for validity.
Args:
value:
Returns:
Floating point number representing the time (in seconds) that should be
used for the timeout.
NOTE: Will raise an exception if the timeout in invalid.
"""
from argparse import ArgumentType... |
def update_orders(orders_dict, orders):
"""Updates current orders list and returns it"""
orders_dict['orders'] = orders
return orders_dict |
def underscore_to_camelcase(word):
"""Humanizes function names"""
return ' '.join(char.capitalize() for char in word.split('_')) |
def swap_chunk(chunk_orig):
"""Swap byte endianness of the given chunk.
Returns:
swapped chunk
"""
chunk = bytearray(chunk_orig)
# align to 4 bytes and pad with 0x0
chunk_len = len(chunk)
pad_len = chunk_len % 4
if pad_len > 0:
chunk += b'\x00' * (4 - pad_len)
chun... |
def DerepCount(titleline):
"""
Takes a title from a uSearch dep'd fasta sequence, and returns the sequence count as an integer
"""
return int((titleline.split('size=')[1]).split(';')[0]) |
def _DistanceOfPointToRange( point, range ):
"""Calculate the distance from a point to a range.
Assumes point is covered by lines in the range.
Returns 0 if point is already inside range. """
start = range[ 'start' ]
end = range[ 'end' ]
# Single-line range.
if start[ 'line' ] == end[ 'line' ]:
# 0 ... |
def iterable(x):
"""Tell whether an object is iterable or not."""
try:
iter(x)
except TypeError:
return False
else:
return True |
def prepareIDNName(name):
"""
Encode a unicode IDN Domain Name into its ACE equivalent.
This will encode the domain labels, separated by allowed dot code points,
to their ASCII Compatible Encoding (ACE) equivalent, using punycode. The
result is an ASCII byte string of the encoded labels, separated ... |
def gen_xacro_robot(macro):
"""
Generates (as a string) the complete urdf element sequence for a xacro
robot definition. This is essentially a string concatenation operation.
Note that the ``macro`` sequence should already be a string.
:param macro: The xacro macro to embed, ``str``
:returns: ... |
def rec_ctp(grid, x, y, m, n):
"""
Recursive approach
"""
if x == 0 and y == n - 1:
return 1
if x < 0 or y > n-1:
return 0
if grid[x][y]:
return 0
return (rec_ctp(grid, x-1, y, m, n) + rec_ctp(grid, x, y+1, m, n))%1000003 |
def find_words(root):
""" print out all words in trie """
result = []
def find_words_path(node, path):
if node is None:
return
if node.is_end_word:
result.append(path + node.char)
if node.char is not None:
path += node.char
for child in no... |
def reformat_variable(var, n_dim, dtype=None):
"""This function takes a variable (int, float, list, tuple) and reformat it into a list of desired length (n_dim)
and type (int, float, bool)."""
if isinstance(var, (int, float)):
var = [var] * n_dim
elif isinstance(var, (list, tuple)):
if l... |
def tensor2np(x):
"""Convert torch.Tensor to np.ndarray
Args:
x (torch.Tensor)
Returns:
np.ndarray
"""
if x is None:
return x
return x.cpu().detach().numpy() |
def _collected_label(collect, label):
"""Label of a collected column."""
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label |
def replace(scope, strings, source, dest):
"""
Returns a copy of the given string (or list of strings) in which all
occurrences of the given source are replaced by the given dest.
:type strings: string
:param strings: A string, or a list of strings.
:type source: string
:param source: Wha... |
def split_strings(strings, start, chr_lens):
"""split strings based on string lengths and given start"""
return [strings[i-start:j-start] for i, j in zip([start]+chr_lens[:-1], chr_lens)] |
def is_mixed_case(string: str) -> bool:
"""Check whether a string contains uppercase and lowercase characters."""
return not string.islower() and not string.isupper() |
def linear (x, parameters):
"""Sigmoid function
POI = a + (b * x )
Parameters
----------
x: float or array of floats
variable
parameters: dict
dictionary containing 'linear_a', and 'linear_b'
Returns
-------
float or array of floats:
function re... |
def blank(l1):
"""
Display the length of the letters by " - " .
"""
bl = ""
for i in range(l1):
bl = bl + "-"
return bl |
def find_length(list_tensors):
"""find the length of list of tensors"""
length = [x.shape[0] for x in list_tensors]
return length |
def levenshtein(s: str, t: str, insert_cost: int = 1, delete_cost: int = 1, replace_cost: int = 1) -> int:
""" From Wikipedia article; Iterative with two matrix rows. """
# degenerate cases
if s == t:
return 0
len0 = len(s)
len1 = len(t)
if not len0:
return len1
if not len... |
def kangaroo(x1: int, v1: int, x2: int, v2: int) -> str:
"""
>>> kangaroo(0, 2, 5, 3)
'NO'
>>> kangaroo(0, 3, 4, 2)
'YES'
>>> kangaroo(14, 4, 98, 2)
'YES'
>>> kangaroo(21, 6, 47, 3)
'NO'
"""
# if v1 > v2:
# i = 0
# while i <= x2:
# i += 1
# ... |
def compute_counts(y_true, y_pred, label):
"""
:param y_true: List[str/int] : List of true labels (expected value) for each test
:param y_pred: List[str/int]: List of classifier predicted labels (observed_values) / test
:param label: label to use as reference for computing counts
:return: 5-tuple: T... |
def agenda_format_day(
number_of_days_before,
date_start,
cfg_today,
cfg_tomorrow,
cfg_in_days,
):
"""
Formats the string who indicates if the event is today, tomorrow, or else
in an arbitrary number of day.
Args:
number_of_days_before (int): The number of da... |
def relu(x):
"""
NumPy implementation of tf.nn.relu
:param x: Data to have ReLU activated
:type x: Union[ndarray, float]
:return: ReLU activated data
:rtype: Union[ndarray, float]
:History: 2018-Apr-11 - Written - Henry Leung (University of Toronto)
"""
return x * (x > 0) |
def obj_has_method(obj, method):
"""http://stackoverflow.com/questions/34439/finding-what-methods-an-object-has"""
return hasattr(obj, method) and callable(getattr(obj, method)) |
def mm2(mm):
"""Leave int values, give floats 2 decimals - for legible SVG"""
if type(mm) == int:
return str(mm)
if type(mm) == float:
return "{:.2f}".format(mm)
return "{:.2f}".format(mm) |
def get_board_as_string(game):
"""
Returns a string representation of the game board in the current state.
"""
board_str = """
{} | {} | {}
--------------
{} | {} | {}
--------------
{} | {} | {}
"""
return board_str.format(game["board"][0][0], game["board"][0][1],game["board"][0][2],ga... |
def inside(r, q):
"""See if one rectangle inside another"""
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh |
def generate_headers(token):
"""
:param token:
:return:
"""
authorization = 'Bearer ' + token
headers = {
'Authorization': authorization,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
return headers |
def surface_margin_dist (A_approx_dist, A_real_dist):
"""
Calculates the surface margin.
Parameters
----------
A_approximate_dist : float
The approximate heat ransfer area, [m**2]
A_real_dist : float
The real heat transfer area, [m**2]
Returns
-------
surface_margin :... |
def equal_without_whitespace(string1, string2):
"""Returns True if string1 and string2 have the same nonwhitespace tokens
in the same order."""
return string1.split() == string2.split() |
def EVLAAIPSName( project, session):
"""
Derive AIPS Name. AIPS file name will be project+session with project
truncated to fit in 12 characters.
* project = project name
* session = session code
"""
################################################################
Aname = Aname=(proje... |
def hex_to_dec(x):
"""Convert hex to decimal.
:param x:
:return:
"""
return int(x, 16) |
def _get_suffix(pop_scenario, throughput_scenario, intervention_strategy):
"""
Get the filename suffix for each scenario and strategy variant.
"""
suffix = '{}_{}_{}'.format(
pop_scenario, throughput_scenario, intervention_strategy)
suffix = suffix.replace('baseline', 'base')
return s... |
def median(y):
"""
Return the median (middle value) of numeric y.
When the number of y points is odd, return the middle y point.
When the number of y points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median([1, 3, 5, ... |
def nested_dict_get_path(key, var):
"""Searches a nested dictionary for a key and returns
a list of strings designating the
complete path to that key.
Returns an empty list if key is not found.
Warning: if key is in multiple nest levels,
this will only return one of those values."""
path = []
if hasat... |
def _cdp_no_split_aligned_count(aligned_count_1, query_seq_fwd, query_seq_rvs, seq_dict_1):
"""
:param aligned_count_1:
:param query_seq_fwd:
:param query_seq_rvs:
:param seq_dict_1:
:return:
"""
if query_seq_fwd in seq_dict_1:
aligned_count_1 += seq_dict_1[query_seq_fwd]
... |
def transformInput(data):
""" separate input to seq_args and global_args
Args:
data: input data
Returns:
separated input data
"""
p3py_data = {}
p3py_data['seq_args'] = {}
p3py_data['global_args'] = {}
for key in data.keys():
if('SEQUENCE_' in key.upper()):
... |
def get_proxy_dict(ip, port, proxy_type='http' or 'socks5'):
"""get_proxy_dict return dict proxies as requests proxies
http://docs.python-requests.org/en/master/user/advanced/
:param ip: ip string
:param port: int port
:param proxy_type: 'http' or 'socks5'
"""
proxies = {
'http': '{... |
def parse_test_names(test_name_args):
"""Returns a dictionary mapping test case names to a list of test functions
:param test_name_args: The parsed value of the ``--test`` or ``--skip``
arguments
:return: None if ``test_name_args`` is None, otherwise return a dictionary
mapping test case n... |
def WrapInTuple(response):
"""Wraps the response in a tuple to support legacy behavior.
Dictionaries and strings are placed in a tuple, while lists are unpacked into
the tuple. None will not be wrapped in a tuple at all.
Args:
response: mixed The response from the API to wrap in a tuple. Could be a
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.