content stringlengths 42 6.51k |
|---|
def dot(a, b):
""" Scalar product of real-valued vectors """
return sum(map(lambda x, y: x*y, a, b)) |
def abs2(x):
""" Calculates the squared magnitude of a complex array.
"""
return x.real * x.real + x.imag * x.imag |
def _replace_suffix(string, old, new):
"""Returns a string with an old suffix replaced by a new suffix."""
return string.endswith(old) and string[:-len(old)] + new or string |
def AdjListDictToString(AdjListDict):
"""Convert AdjListDict to it's string representation"""
assert isinstance(AdjListDict, dict)
AdjListString = str(AdjListDict)
return AdjListString |
def format_query(query):
"""Replaces spaces for %20"""
return "%20".join(query.split()) |
def VAR(src_column):
"""
Builtin variance aggregator for groupby. Synonym for tc.aggregate.VARIANCE
Example: Get the rating variance of each user.
>>> sf.groupby("user",
... {'rating_var':tc.aggregate.VAR('rating')})
"""
return ("__builtin__var__", [src_column]) |
def mkSSnam(S):
"""In : S (a set of states, possibly empty)
Out: A string representing the set of states.
Make the DFA state names the same as the NFA state
names bashed together.
"""
if S==set({}):
return "BH"
else:
S1 = list(S)
S1.sort()
return "".join(
... |
def catalan(n):
"""
>>> catalan(2)
2
>>> catalan(5)
42
>>> catalan(-1)
Traceback (most recent call last):
...
IndexError: list assignment index out of range
"""
# Base Case
if n == 0 or n == 1:
return 1
# To store the result of subproblems
cat_num = ... |
def value_to_float(value_encoded: str):
"""
A simple wrapper around float() which supports empty strings (which are converted to 0).
"""
if len(value_encoded) == 0:
return 0
return float(value_encoded) |
def assert_positive_int(str_number, str_name):
"""
Check whether a string represents a positive integer.
:param str_number: The string representation.
:param str_name: The name to print on error.
:return: The string representation if it was a positive interger.
Exits with error code 12 othe... |
def in_list(value, comma_separated_list):
"""
This filter checks whether a given string value is contained in a comma separated list
:param value: The value which should be checked
:type value: str
:param comma_separated_list: The list of comma-separated strings
:type comma_separated_list: str... |
def _get_block_sizes(resnet_size):
"""Retrieve the size of each block_layer in the ResNet model.
The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
Args:
resn... |
def stringify_baseclass(baseclass):
"""Convert baseclass into printable form by converting typemap object"""
# Replace typename instance with its name.
pbase = []
for basetuple in baseclass:
(access_specifier, ns_name, baseclass) = basetuple
pbase.append((access_specifier, ns_name, basec... |
def generate_bio_entity_tags(token_list, mentions):
"""
Generate BIO/IOB2 tags for entity detection task.
"""
bio_tags = ['O'] * len(token_list)
for mention in mentions:
start = mention['start']
end = mention['end']
bio_tags[start] = 'B-E'
for i in range(start + 1, en... |
def _integral_average(func, Xi, Xf):
"""Take the integral with a constant derivative at the average value."""
return func((Xi+Xf)/2)*(Xf-Xi) |
def readable_to_kb(raw_value):
"""
Convert readable value to integer in kb
:param raw_value: string
:return: int
"""
# from math import ceil
value_in_kb = 0
if raw_value.find('KB') != -1:
value_in_kb = int(raw_value.replace('KB', ''))
elif raw_value.find('MB') != -1:
... |
def is_overlaping(start1: float, end1: float, start2: float, end2: float) -> float:
"""how much does the range (start1, end1) overlap with (start2, end2)
Looks strange, but algorithm is tight and tested.
Args_i:
start1: start of interval 1, in any unit
end1: end of interval 1
start2... |
def _already_all_imported(group, imported_filepaths):
""" Test is all the filepaths in groups are already imported in
imported_filepaths"""
nimported = 0
for fp in group:
if fp in imported_filepaths:
nimported += 1
if nimported == len(group):
return True
else:
... |
def _compute_padding_to_prevent_task_description_from_moving(unfinished_tasks):
"""Compute the padding to have task descriptions with the same length.
Some task names are longer than others. The tqdm progress bar would be constantly
adjusting if more space is available. Instead, we compute the length of th... |
def empty_slot(nb_empty):
"""Return a list of n empty strings
"""
return ['']*nb_empty |
def get_data(stats):
"""format the statistics into a dictionary"""
data = {}
for s in stats:
info = s.split()
key = info[0][:-1]
data[key] = "\t".join(info[1:])
return data |
def split(pathnfile):
"""Return file and directory path from string"""
sp = pathnfile.split('/')
if len(sp) == 1:
filename = sp[0]
path = './'
else:
filename = sp.pop(len(sp) - 1)
path = '/'.join(sp) + '/'
return path, filename |
def _retain_centroids(numbers, thres):
"""Only keep one number for each cluster within thres of each other"""
numbers.sort()
prev = -1
ret = []
for n in numbers:
if prev < 0 or n - prev > thres:
ret.append(n)
prev = n
return ret |
def genSchedulerTrigger(trigger_name, repo, refs, path_regexps, builds):
"""Generate the luci scheduler job for a given build config.
Args:
trigger_name: Name of the trigger as a string.
repo: Gitiles URL git git repository.
refs: Iterable of git refs to check. May use regular expressions.
path_reg... |
def go_match_fuzzy(name, string):
"""Check if string matches name using approximation."""
if not string:
return False
name_len = len(name)
string_len = len(string)
if string_len > name_len:
return False
if name_len == string_len:
return name == string
# Attempt to ... |
def phone_cleanup(s):
"""Clean the phones' output"""
if not s:
return ''
s = ''.join([c for c in s if c.isdigit() or c == '+'])
if s and s[0] != '+' and len(s) == 10:
s = '+39' + s # if not already internationalized, make it Italian
return '-'.join([s[:3], s[3:7], s[7:]]) if s.start... |
def recursiveIndex(nestedList, query):
"""
Find index of element (first occurrence) in an arbitrarily nested list.
Args:
nestedList(list): list object to search in
query: target element to find
Returns:
list: Position indices
"""
for index, element in enumerate(nestedLi... |
def make_freq_dict(text):
""" Return a dictionary that maps each byte in text to its frequency.
@param bytes text: a bytes object
@rtype: dict{int,int}
>>> d = make_freq_dict(bytes([65, 66, 67, 66]))
>>> d == {65: 1, 66: 2, 67: 1}
True
"""
res = {}
text = list(text)
... |
def create_500(cause=None, verbose=None) -> dict:
"""
creates a dictionary with error code, type, message
"""
return {
"status": 500,
"error": {
"cause": cause,
"type": "Internal Server Error",
"message": "Could not process request due to an internal s... |
def _get_comma_tab(lines):
""" Get parallel collections of comma- and tab-delimiter lines """
return [l.replace("\t", ",") for l in lines], \
[l.replace(",", "\t") for l in lines] |
def clean_integer(num):
""" Pasa de string a int """
ntmp = num.replace('.', '')
return int(ntmp) |
def str2bool(value):
"""Converts string to bool."""
value = value.lower()
if value in ('yes', 'true', 't', '1'):
return True
if value in ('no', 'false', 'f', '0'):
return False
raise ValueError('Boolean argument needs to be true or false. '
'Instead, it is %s.' %... |
def _test_pbm(h):
"""PBM (portable bitmap)"""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r':
return 'pbm' |
def label(originalLabel):
"""reformat some instrument labels for legends and stuff"""
labels = {
'TESSERACT+TESS' : 'TESS',
'CHAT+i' : 'CHAT'
}
try:
label = labels[originalLabel]
except KeyError:
label = originalLabel
return label |
def merge_datamodels(user, default):
"""Merges datamodel files
alternative - try hiyapyco package or yamlload for merging purposes
"""
if isinstance(user, dict) and isinstance(default, dict):
for kk, vv in default.items():
if kk not in user:
user[kk] = vv
... |
def set_offsets(offsets, offset_sys = None, cy = 0, cz = 0):
"""Takes 6 offset values from ETABS and converts into GSA standard
('LENGTHOFFI', 'OFFSETYI', 'OFFSETZI',
'LENGTHOFFJ', 'OFFSETYJ', 'OFFSETZJ')
off_x1, off_x2, off_y, off_z
Note that we need a coordinate system to implement ... |
def remove_question_mark_and_point(url):
"""
Used by the BBC links
:param url:
:return:
"""
if url != "":
pos = url.find("?")
if pos != -1:
url = url[:pos]
poi = url.find(".app")
if poi != -1:
url = url[:poi]
return url |
def redact_url(url):
"""Remove user:password from the URL."""
protocol = url[:url.index('://')+3]
remainder = url.split('@', 1)[-1]
# return f'{protocol}[redacted]@{remainder}'
return protocol + '[redacted]@' + remainder |
def gnome_sort(unsorted):
"""Pure implementation of the gnome sort algorithm in Python."""
if len(unsorted) <= 1:
return unsorted
i = 1
while i < len(unsorted):
if unsorted[i - 1] <= unsorted[i]:
i += 1
else:
unsorted[i - 1], unsorted[i] = unsorted[i], u... |
def find_quad_residue(m):
"""Return a list of all quadratic residues modulo m"""
L = []
for i in range(m):
q = i**2 % m
if q not in L:
L.append(q)
L.sort()
return L |
def dsfr_accordion_group(items: list) -> dict:
"""
Returns a group of accordion items. Takes a list of dicts as parameters (see the accordeon
tag for the structure of these dicts.)
**Tag name**::
dsfr_accordion_group
**Usage**::
{% dsfr_accordion_group data_list %}
"""
retur... |
def fib(n):
"""
Fibonacci
:param n:
:return:
"""
sum = 0
if n > 2:
first = 1
second = 1
sum = first + second
count = 3
while count <= n:
temp = first + second
first = second
second = temp
sum += temp
... |
def separate_times(data:dict,primary_key) -> dict:
"""
This will, given a synchronized and homogenized dictionary of timeseries with a designated main timeseries, transform it into a dictionary timeseries with two data fields.
These data fields corresponds to the primary timeseries data and to the smaller t... |
def strip_prefix(path, prefix):
"""Returns the path with the specified prefix removed.
Args:
path: The path to strip prefix from
prefix: The prefix to strip
"""
if path.startswith(prefix):
return path[len(prefix):]
return path |
def valid_range(minimum, maximum, variable):
"""
Check range of valid values
:param minimum: Minimum value
:param maximum: Maximum value
:param variable: Check value
:return: True - value is valid
"""
if (variable >= minimum) and (variable <= maximum):
result = Tr... |
def gen_col_list(num_signals):
"""
Given the number of signals returns
a list of columns for the data.
E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3']
"""
col_list = ['Time']
for i in range(1, num_signals + 1):
col = 'Signal' + str(i)
col_list.append(c... |
def generate_matrix2(n):
"""
:type n: int
:rtype: List[List[int]]
"""
max_num = n * n
output = []
for i in range(n):
lists = [0 for i in range(n)]
output.append(lists)
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = c = di = 0
for num in range(1, max_num + 1):
... |
def wep_check_some_params_against_set(valid_params: set, request: dict) -> str:
"""
Check one or more request parameters against a set of valid inputs.
Args:
valid_params: a set of valid parameters
request: the request object containing zero or more parameters
Returns:
The inva... |
def _decode_helper(obj):
"""A decoding helper that is TF-object aware."""
if isinstance(obj, dict) and 'class_name' in obj:
if obj['class_name'] == '__tuple__':
return tuple(_decode_helper(i) for i in obj['items'])
elif obj['class_name'] == '__ellipsis__':
return Ellipsi... |
def get_model_name(epoch):
"""
Return filename of model snapshot by epoch
:param epoch: global epoch of model
:type epoch: int
:return: model snapshot file name
:rtype: str
"""
return 'network-snapshot-{:04d}.pth'.format(epoch) |
def new_symbol(grammar, symbol_name="<symbol>"):
"""Return a new symbol for `grammar` based on `symbol_name`"""
if symbol_name not in grammar:
return symbol_name
count = 1
while True:
tentative_symbol_name = symbol_name[:-1] + "-" + repr(count) + ">"
if tentative_symbol_name not... |
def _remove_duplicates(items):
"""Return `items`, filtering any duplicate items.
Disussion: https://stackoverflow.com/a/7961390/4472195
NOTE: this requires Python 3.7+ in order to preserve order
Parameters
----------
items : list
[description]
Returns
-------
list
... |
def wind_chill(temp, wind_speed, a=13.12, b=0.6215, c=-11.37, d=0.16, e=0.3965):
"""
Converts temperature and wind speed into wind-chill index.
Formula: wci = a + b*T + c*W^d + e*T*W^d, where T is temperature and W is wind speed
Parameters
temp: temperature in Celsius
wind_speed: wind sp... |
def merge(numbs1, numbs2):
"""
Go through the two sorted arrays simultaneously from
left to right. Find the smallest element between the
two in the two arrays. Append the smallest element
to a third array and increase the index from which the
element was taken by one. If the two elements are the... |
def escape_path(value: bytes) -> str:
"""
Take a binary path value, and return a printable string, with special
characters escaped.
"""
def human_readable_byte(b: int) -> str:
if b < 0x20 or b >= 0x7F:
return "\\x{:02x}".format(b)
elif b == ord(b"\\"):
return... |
def normalize(name):
"""Normalize the name of an encoding."""
return name.replace('_', '').replace('-', '').upper() |
def style(text,mute, recon):
"""Styles some text.
The two styles are:
muted: When something was not selected in filter_by but show_all is true.
recon: When something was the initiator (client) or target of possible
recon activity indicators.
"""
styles = []
if ... |
def normalizeFileFormatVersion(value):
"""
Normalizes a font's file format version.
* **value** must be a :ref:`type-int`.
* Returned value will be a ``int``.
"""
if not isinstance(value, int):
raise TypeError("File format versions must be instances of "
":ref:`t... |
def find_peak(list_of_integers):
"""
Function that finds the peak in a list of unsorted integers
"""
if list_of_integers:
list_of_integers.sort()
return list_of_integers[-1]
else:
return None |
def build_feature_dict(opt):
"""Make mapping of feature option to feature index."""
feature_dict = {}
if opt['use_in_question']:
feature_dict['in_question'] = len(feature_dict)
feature_dict['in_question_uncased'] = len(feature_dict)
if opt['use_tf']:
feature_dict['tf'] = len(feat... |
def count_refs_in_mapping( references, mapping ):
"""Count the number of references in the mapping"""
count = 0
for r in references:
if r in mapping:
count += 1
return count |
def param_encode(payload):
"""
This is to get around the default url encode of requests.get(). We need
*.* to be encoded as *%3A* but it's encoding it as %2A.%2
IntroSpect doesn't like that
"""
payload_str = "&".join("%s=%s" % (k,v) for k,v in payload.items())
return payload_str.replace('.',... |
def parse_video_response(video=dict()):
"""
Parse video dict to extract key metadata, including:
id, title, description, tags, viewCount, likeCount, likeCount, dislikeCount
:param video:
:return:
"""
result = dict()
result['id'] = video['id']
result['title'] = video['snippet']['t... |
def binary_search_iterative(array, value) -> int:
"""Use moving pointers to size the array at each iteration."""
left = 0
right = len(array)
while left < right:
mid = (right - left) // 2 + left # take lower mid
if array[mid] == value:
return mid
if array[mid] > value... |
def closest_half_integer(number):
"""
Round a number to the closest half integer.
>>> closest_half_integer(1.3)
1.5
>>> closest_half_integer(2.6)
2.5
>>> closest_half_integer(3.0)
3.0
>>> closest_half_integer(4.1)
4.0
"""
return round(number * 2) / 2.0 |
def create_fake_drs_uri(object_id: str):
"""Create a fake DRS URI based on an object id."""
return f"drs://www.example.org/{object_id}" |
def make_terms_from_string(s):
"""turn string s into a list of unicode terms"""
u = s
return u.split() |
def is_exactly_one_not_none(*args):
"""
>>> is_exactly_one_not_none(1, 2, 3)
False
>>> is_exactly_one_not_none(None, 2, 3)
False
>>> is_exactly_one_not_none(1, None, 3)
False
>>> is_exactly_one_not_none(1, 2, None)
False
>>> is_exactly_one_not_none(1, None, None)
T... |
def to_float(x, error=float('nan'), dir='N'):
"""Convert argument to float, treating errors and direction."""
try:
sign = -1 if dir in 'SW' else 1
return float(x) * sign
except (ValueError, TypeError):
return error |
def is_none(attribute):
"""Filter SQLAlchemy attribute is None"""
return attribute == None # pylint: disable=singleton-comparison |
def crossProd(a,b):
"""Pretty self-explanatory, this function bakes cookies"""
normal_vect = [
a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
return normal_vect |
def validate_under_over_sampling_input(class_populations, minority_labels, majority_labels,
base_minority=None, base_majority=None):
"""
This is to validate the arguments of two methods in the class `Sampler` in
`sampling.sampler`, namely `undersample` and `oversample`... |
def digit_count(num):
"""
Returns the count of the digits (length) of the number
"""
return len(f"{num}") |
def greeter(name :str)->str:
"""greeter function to New Comer"""
return 'Hello,%s' %(name) |
def to_title(text):
"""
Description: Convert text to title type and remove underscores
:param text: raw text
:return: Converted text
"""
return str(text).title().replace('_', ' ') |
def enumer(value):
"""
Conversion routine for enumeration values. Accepts ints or
strings.
:param str value: The value to convert.
:returns: A value of an appropriate type.
"""
try:
# Convert as an integer
return int(value)
except ValueError:
# Return the stri... |
def clean_code(code: str) -> str:
"""Replaces certain parts of the code, which cannot be enforced via the generator"""
# Mapping used for replacement
replace_map = [
("...", "default_factory=list"),
("type_class", "typeClass"),
("type_name", "typeName"),
("from core", "from ... |
def isarray(value):
"""Is the value a container, like tuple, list or numpy array?"""
from six import string_types
if isinstance(value,string_types): return False
if hasattr(value,"__len__"): return True
else: return False |
def split_ents_no_mix(ents, targets):
"""Split ents into target and non-target
targets: list of target entity in text
returns: qids of target and nontarget ent
"""
target_qids = []
non_target_qids = []
for i, ent in enumerate(ents, 0):
ent_start = ent[1]
ent_end = ent[2]
qid = ent[0]
is_ta... |
def _format_path_with_rank_zero(path: str) -> str:
"""Formats ``path`` with the rank zero values."""
return path.format(
rank=0,
local_rank=0,
node_rank=0,
) |
def replace_qp_value(payload, key, value):
"""
Replaces the given value of the query parameter
"""
payload_split = payload.split('&')
for i, query_p in enumerate(payload_split):
if query_p.startswith(key+'='):
payload_split[i] = key+'='+value
return '&'.join(payload_split) |
def cross(coords1, coords2):
"""
Find the cross product of two 3-dimensional points
Parameters
coords1: coordinates of form [x,y,z]
coords2: coordinates of form [x,y,z]
Returns
list: Cross product coords2 and coords1 (list)
"""
list = []
x = ... |
def filterize(d):
"""
Return dictionary 'd' as a boto3 "filters" object by unfolding it to a list of
dict with 'Name' and 'Values' entries.
"""
return [{'Name': k, 'Values': [v]} for k, v in d.items()] |
def xor_bytes(a: bytes, b: bytes):
"""XOR function for two byte sequences of arbitrary (but equal) length"""
assert len(a) == len(b)
return bytes([x ^ y for x,y in zip(a, b)]) |
def eps(newEps=None):
""" Get/Set the epsilon for float comparisons. """
global _eps
if newEps is not None:
_eps = newEps
return _eps |
def update(old, new, priority='new'):
""" Update a nested dictionary with values from another
This is like dict.update except that it smoothly merges nested values
This operates in-place and modifies old
Parameters
----------
priority: string {'old', 'new'}
If new (default) then the n... |
def parentheses_match(string):
"""
Return True if opening and closing brackets are
all matched in an input logical expression
"""
verification_stack = []
matched = True
itr_index = 0
while itr_index < len(string) and matched:
if string[itr_index]=="(":
verification_stack.append(string[itr_index])
elif st... |
def BuildVersion(major, minor, revision):
"""Calculates int version number from major, minor and revision numbers.
Returns: int representing version number
"""
assert isinstance(major, int)
assert isinstance(minor, int)
assert isinstance(revision, int)
return (1000000 * major +
10000 * minor... |
def find_gcd(a: int, b: int):
"""Uses Euclid's Algorithm to find the greatest common denomenator between
two numbers, a and b."""
while a != 0:
a, b = b % a, a
return b |
def package_name(build_number, host):
"""Returns the file name for a given package configuration.
>>> package_name('1234', 'linux')
'clang-1234-linux-x86.tar.bz2'
"""
return 'clang-{}-{}-x86.tar.bz2'.format(build_number, host) |
def extract_text(pdf_list):
"""Extract text from a list of pdfs
Usage:
extract_text(pdf_list):
pdf_list -- a list of PyPDF4.PdfFileReader objects
Returns a list of lists of strings. Each list of strings is a list
comprised of one string for each line of text on a pdf page.
"""
... |
def radii(mag):
"""The relation used to set the radius of bright star masks.
Parameters
----------
mag : :class:`flt` or :class:`recarray`
Magnitude. Typically, in order of preference, G-band for Gaia
or VT then HP then BT for Tycho.
Returns
-------
:class:`recarray`
... |
def __check_colnames_type(cols):
"""Check if it is a list-like object."""
if cols is None or cols == []:
return None
elif not isinstance(cols, list):
raise TypeError("Third item of the tuple (func, args, cols) must be list-like \
object not a {} object".format(type(cols)))
else:
... |
def is_valid_passport_no(passport_no):
"""A very basic passport_no validation check"""
return len(passport_no) >= 1 |
def calc_precision_recall(frame_results):
"""Calculates precision and recall from the set of frames by summing the true positives,
false positives, and false negatives for each frame.
Args:
frame_results (dict): dictionary formatted like:
{
'frame1': {'true_pos': int, '... |
def play_game(game):
"""
Play cards. Higher card wins. If value on the cards for both players
is same or lower than count of cards players have in package, then
the sub-game is playing. Result of subgame determine winner of parent game.
If the game is in infinitive loop, then the winner is automatic... |
def _next_major(entry, major):
"""Create next major heading index."""
# First appendix.
if entry.get("appendix", False):
return "A"
# Chapters are numbered.
if isinstance(major, int):
return major + 1
# Appendices are lettered.
assert isinstance(major, str) and (len(major) ... |
def calc_consumer_sentiment(scenario, years, total_sales):
"""OPPORTUNITY: Consumer Sentiment - Increasing consumer sentiment and increasing sales of products
Args:
scenario (object): The farm scenario
years (int): No. of years for analysis
total_sales (list): Waste-adju... |
def freqdistlines(lines):
"""freqdist generates a frequency distribution over tokens in lines format """
fd = {}
for tokens in lines:
for w in tokens:
fd[w] = 1 + fd.get(w, 0)
return fd |
def order_flds(flds):
"""
Arguments:
- `flds`:
"""
FNKEYS = ["PRJ_CD", "SAM", "EFF", "SPC", "GRP", "FISH", "AGEID", "FOODID"]
# order the fields so that we have keys first then alphabetically after that:
key_flds = [x for x in FNKEYS if x in flds]
data_flds = [x for x in flds if x not ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.