content
stringlengths 42
6.51k
|
---|
def get_key(url):
"""
Given a URL path convert it to an S3 Key by replacing some parts of the path
with empty strings
"""
return url.replace("/v0/submission/", "").replace("/files", "")
|
def remove_last_line_from_string(data):
"""
Author: Chaitanya Vella ([email protected])
Common function to remove the last line of the string
:param data:
:return:
"""
return data[:data.rfind('\n')]
|
def getResults(workers):
"""
Converts a list of finished workers into a result.
:param workers: Finished workers.
:return: Results
"""
results = []
for worker in workers:
results += worker.getResults()
return results
|
def unique_number_from_list(input_list):
"""
Produce a list of integers corresponding to the number of times an
element in the input list has been observed.
Parameters
----------
input_list : list
list of values
Returns
-------
occurrence : list
integer list
Examples
--------
unique_number_from_list(['a','a','b','c','c','c'])
unique_number_from_list(['a','b','c'])
"""
dups = {}
occurrence = []
for i, val in enumerate(input_list):
if val not in dups:
# Store index of first occurrence and occurrence value
dups[val] = [i, 1]
# Increment occurrence value,
else:
dups[val][1] += 1
# Use stored occurrence value
occurrence.append(dups[val][1])
return occurrence
|
def PrintBox(loc, height, width, style='r-'):
"""A utility function to help visualizing boxes."""
xmin, ymin, xmax, ymax = loc[0] * width, loc[1] * height, loc[2] * width, loc[3] * height
#pyplot.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], style)
return [xmin, ymin, xmax, ymax]
|
def _split_comma_separated(string):
"""Return a set of strings."""
return set(filter(None, string.split(',')))
|
def trimVersionString(version_string):
### from munkilib.updatecheck
"""Trims all lone trailing zeros in the version string after major/minor.
Examples:
10.0.0.0 -> 10.0
10.0.0.1 -> 10.0.0.1
10.0.0-abc1 -> 10.0.0-abc1
10.0.0-abc1.0 -> 10.0.0-abc1
"""
if version_string == None or version_string == '':
return ''
version_parts = version_string.split('.')
# strip off all trailing 0's in the version, while over 2 parts.
while len(version_parts) > 2 and version_parts[-1] == '0':
del(version_parts[-1])
return '.'.join(version_parts)
|
def processLine(sym_line):
"""Reverses symbols in line"""
new_line = list(reversed(sym_line))
return new_line
|
def underscore_to_camelcase(value):
"""
Converts underscore notation (something_named_this) to camelcase notation (somethingNamedThis)
>>> underscore_to_camelcase('country_code')
'countryCode'
>>> underscore_to_camelcase('country')
'country'
>>> underscore_to_camelcase('price_GBP')
'priceGBP'
>>> underscore_to_camelcase('recommended_horizontal_resolution')
'recommendedHorizontalResolution'
>>> underscore_to_camelcase('postal_or_zip_code')
'postalOrZipCode'
>>> underscore_to_camelcase('test_ABC_test')
'testABCTest'
"""
words = value.split('_')
return '%s%s' % (words[0], ''.join(x if x.isupper() else x.capitalize() for x in words[1:]))
|
def corrfac(z, params):
"""
Correlation coefficient between galaxy distribution and velocity field, r(z).
"""
r_g = params['r_g'] #0.98
return r_g + 0.*z
|
def _to_w2v_indexes(sentence, w2v_vocab):
"""
Return which tokens in a sentence cannot be found inside the
given embedding
:param sentence: current sentence (tokenized)
:param w2v_vocab: embedding matrix
:return: a list of the tokens which were not found
"""
total_missing = []
for word in sentence:
if word in w2v_vocab:
pass
elif word.title() in w2v_vocab:
pass
elif word.isdigit() or word.find("DIGIT") != -1:
pass
else:
total_missing.append(word)
return total_missing
|
def get_column_positions(column_headings, feature_list):
"""
Return a list of the corresponding position within column_headings of each feature in feature_list.
This can be used to get the position of lists of features for use in pipelines and transformers where
one cannot rely on the input being a pandas DataFrame.
"""
feature_to_pos = {}
for i in range(len(column_headings)):
feature_to_pos[column_headings[i]] = i
feature_positions = [feature_to_pos[feature] for feature in feature_list]
return feature_positions
|
def first_not_null(*args):
"""
get list obj first not-null object
>>> first_not_null(None, 'a', 'b')
return 'a'
"""
if args is not None:
for arg in args:
if arg is not None:
return arg
return None
|
def is_under_remote(ref, remote):
"""Return True if a Git reference is from a particular remote, else False.
Note that behavior is undefined if the ref is not fully qualified, i.e.
does not begin with 'refs/'.
Usage example:
>>> is_under_remote("refs/remotes/origin/mywork", "origin")
True
>>> is_under_remote("refs/remotes/origin/mywork", "alt")
False
>>> is_under_remote("refs/headsmywork", "origin")
False
"""
return ref.startswith('refs/remotes/' + remote + '/')
|
def normalize_rgb(rgb):
"""
Normalize rgb to 0~1 range
:param rgb: the rgb values to be normalized, could be a tuple or list of tuples
:return:
"""
if isinstance(rgb, tuple):
return tuple([float(a)/255 for a in rgb])
elif isinstance(rgb, list):
norm_rgb = []
for item in rgb:
norm_rgb.append(normalize_rgb(item))
return norm_rgb
else:
raise NotImplementedError('Data type: {} not understood'.format(type(rgb)))
|
def sentence2id(sent, word2id):
"""
:param sent:
:param word2id:
:return:
"""
sentence_id = []
for word in sent:
if word.isdigit():
word = '<NUM>'
if word not in word2id:
word = '<UNK>'
sentence_id.append(word2id[word])
return sentence_id
|
def pluck(input_dictionary):
"""Destructures a dictionary (vaguely like ES6 for JS)
Results are SORTED by key alphabetically! You must sort your receiving vars
"""
items = sorted(input_dictionary.items())
return [item[1] for item in items]
|
def get_readme(readme_file_location="./README.md"):
"""
Purpose:
Return the README details from the README.md for documentation
Args:
readme_file_location (String): Project README file
Return:
requirement_files (List of Strings): Requirement Files
"""
readme_data = "Description Not Found"
try:
with open(readme_file_location, "r") as readme_file_object:
readme_data = readme_file_object.read()
except Exception as err:
print(
f"Failed to Get README.md Data from {readme_file_location}: {err}"
)
return readme_data
|
def strip_ws(puzzle_string):
"""Remove newline and space characters from a string."""
return puzzle_string.replace('\n', '').replace(' ','')
|
def get_filenames(fileNameA):
"""
Custom function for this specific dataset.
It returns the names of corresponding files in the 2 classes along with the common name by which it should be saved.
Args:
fileNameA(str) : Filename in the first class
Created By Leander Maben
"""
return fileNameA, fileNameA[:32]+'-A.wav', fileNameA[:32]+'.wav'
|
def sparsifyApprox(probs, err_thresh):
""" Sparsify a probability vector. """
# FIXME
# sorted_indices = None
return probs
|
def us_territories():
"""USA postal abbreviations for territories, protectorates, and military.
The return value is a list of ``(abbreviation, name)`` tuples. The
locations are sorted by name.
"""
# From http://www.usps.com/ncsc/lookups/abbreviations.html
# Updated 2008-05-01
return [
("AS", "American Samoa"),
("AA", "Armed Forces Americas"),
("AE", "Armed Forces Europe/Canada/Middle East/Africa"),
("AP", "Armed Forces Pacific"),
("FM", "Federated States of Micronesia"),
("GU", "Guam"),
("MH", "Marshall Islands"),
("MP", "Northern Mariana Islands"),
("PW", "Palau"),
("PR", "Puerto Rico"),
("VI", "Virgin Islands"),
]
|
def binary_search_recursive(array, left, right, key):
"""
Funkce rekurzivne ve vzestupne usporadanem poli 'array' vyhleda klic
'key'. Hleda se pouze v rozsahu od indexu 'left' do indexu 'right'.
Funkce vraci index nalezeneho prvku, pokud prvek v posloupnosti
neni, vraci -1.
"""
if left == right:
return left if array[left] == key else -1
mid = (left + right) // 2
if key < array[mid]:
return binary_search_recursive(array, left, mid - 1, key)
if key > array[mid]:
return binary_search_recursive(array, mid + 1, right, key)
return mid
|
def _host_is_same(host1: str, host2: str) -> bool:
"""Check if host1 and host2 are the same."""
return host1.split(":")[0] == host2.split(":")[0]
|
def decode_read_data(read: list, encoding='utf-8'):
"""
Interprets bytes under the specified encoding, to produce a decoded string.
"""
decoded = ""
try:
decoded = bytes(read).decode(encoding).rstrip('\0')
except UnicodeDecodeError:
return decoded
return decoded
|
def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float:
"""
Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
>>> fahrenheit_to_kelvin(273.354, 3)
407.236
>>> fahrenheit_to_kelvin(273.354, 0)
407.0
>>> fahrenheit_to_kelvin(0)
255.37
>>> fahrenheit_to_kelvin(20.0)
266.48
>>> fahrenheit_to_kelvin(40.0)
277.59
>>> fahrenheit_to_kelvin(60)
288.71
>>> fahrenheit_to_kelvin(80)
299.82
>>> fahrenheit_to_kelvin("100")
310.93
>>> fahrenheit_to_kelvin("fahrenheit")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'fahrenheit'
"""
return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits)
|
def git_unicode_unescape(s: str, encoding: str = "utf-8") -> str:
"""Undoes git/gitpython unicode encoding."""
if s is None:
return ""
if s.startswith('"'):
return s.strip('"').encode("latin1").decode("unicode-escape").encode("latin1").decode(encoding)
return s
|
def purge_key_deep(a_dict, key):
"""Removes given key from all nested levels of a_dict
"""
try:
a_dict.pop(key)
except KeyError:
pass
for k in a_dict.keys():
if isinstance(a_dict[k], dict):
a_dict[k] = purge_key_deep(a_dict[k], key)
return a_dict
|
def get_download_url_from_commit(package, commit):
"""
Return the download URL for this commit
@package - :user/:repo combination
@commit - commit hash
"""
return "https://codeload.github.com/%s/legacy.tar.gz/%s" % (package, commit)
|
def dicts_are_essentially_equal(a, b):
"""Make sure that a is a subset of b, where None entries of a are ignored."""
for k, v in a.items():
if v is None:
continue
if b.get(k) != v:
return False
return True
|
def frozendict (d):
"""Convert a dictionary to a canonical and immutable form."""
return frozenset(d.items())
|
def seconds(data, freq):
"""
Returns number of seconds from track data based on frequency
:param track: wav audio data
:param freq: frequency of audio data
:return: number of seconds
"""
return len(data)/freq
|
def appn(s1, s2):
"""Append two strings, adding a space between them if either is nonempty.
Args:
s1 (str): The first string
s2 (str): The second string
Returns:
str: The two strings concatenated and separated by a space.
"""
if not s1: return s2
elif not s2: return s1
else: return s1 + " " + s2
|
def is_match(str_a, str_b):
"""Finds if `str_a` matches `str_b`
Keyword arguments:
str_a -- string
str_b -- string
"""
len_a, len_b = len(str_a) + 1, len(str_b) + 1
matches = [[False] * len_b for _ in range(len_a)]
# Match empty string with empty pattern
matches[0][0] = True
# Match empty string with .*
for i, element in enumerate(str_b[1:], 2):
matches[0][i] = matches[0][i - 2] and element == '*'
for i, char_a in enumerate(str_a, 1):
for j, char_b in enumerate(str_b, 1):
if char_b != '*':
# The previous character has matched and the current one
# has to be matched. Two possible matches: the same or .
matches[i][j] = matches[i - 1][j - 1] and \
char_b in (char_a, '.')
else:
# Horizontal look up [j - 2].
# Not use the character before *.
matches[i][j] |= matches[i][j - 2]
# Vertical look up [i - 1].
# Use at least one character before *.
# p a b *
# s 1 0 0 0
# a 0 1 0 1
# b 0 0 1 1
# b 0 0 0 ?
if char_a == str_b[j - 2] or str_b[j - 2] == '.':
matches[i][j] |= matches[i - 1][j]
return matches[-1][-1]
|
def split_required_col(req):
"""
>>> split_required_col('col_a')
('col_a', None)
>>> split_required_col('col_B,integer')
('col_b', 'integer')
>>> split_required_col('col_c,some(parametric,type)')
('col_c', 'some(parametric,type)')
"""
split = req.lower().split(',', 1)
# no type, just a value
if len(split) == 1:
return (split[0], None)
return (split[0], split[1])
|
def getEndIndex(string):
"""Returns the index of the space after the value before its units
>>> string = ' R2 = 1 173 Ohm\\n'
>>> getEndIndex(string)
13
"""
lastIndex = len(string) - 1
while string[lastIndex] != ' ':
lastIndex -= 1
return lastIndex
|
def buildIndirectMapping(a, b):
"""Given a maps x->y, b maps y->z, return map of x->z."""
assert(len(a) == len(b))
assert(isinstance(list(b.keys())[0], type(list(a.values())[0])))
c = dict()
for x in a.keys():
y = a[x]
z = b[y]
c[x] = z
return c
|
def find_empty(board):
"""
Finds an empty cell and returns its position as a tuple
:param board: the board to search
"""
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return i, j
|
def mulND(v1, v2):
"""Returns product of two nD vectors
(same as itemwise multiplication)"""
return [vv1 * vv2 for vv1, vv2 in zip(v1, v2)]
|
def matrix2bytes(matrix):
"""
Converts a 4x4 matrix to bytes
"""
return bytes(sum(matrix, []))
|
def compute_capacity(n_seats, aw2_capacity, target_density):
"""
Compute RS capacity for target density
"""
return (aw2_capacity - n_seats) * target_density / 4 + n_seats
|
def _convert_key_and_value(key, value):
"""Helper function to convert the provided key and value pair (from a dictionary) to a string.
Args:
key (str): The key in the dictionary.
value: The value for this key.
Returns:
str: The provided key value pair as a string.
"""
updated_key = f'"{key}"' if isinstance(key, str) else key
updated_value = f'"{value}"' if isinstance(value, str) else value
return f"{updated_key}: {updated_value}, "
|
def input_2_word(word_in):
"""
This function takes a string from the input file ''word_in'',
and returns an array of that ''word'' in a format which is
more useable by the rest of the code.
The input file is a .txt file written in the following way:
1,13,18,25,...
5,11,12,19,...
...
where each line is an individual word from the puzzle and
the numbers correspond to letters (the code to be broken).
When this is read in by Python each line results in a single string
'1,13,18,25,...'
but we want the array ['1','13','18','25',...] to perform opperations on.
This code performs the operation '1,13,18,25,...' -> ['1','13','18','25',...]
MUST BE PERFORNED LINE BY LINE.
"""
word = [] # Initialise the array we will return
k = 0 # k to be looped over the size of the ''word_in''.
switch = 1 # We need a switch because we need to check if the unsolved code is two letters in size.
# i.e. it is import that '11,12' -> ['11','12'] not ['1','1','1','2'].
for char in word_in: # go through every character in the input.
k += 1 # k checks the index one ahead.
if switch == 1: # switch set to zero if the kth character already in word.
if char != ',': # We want to remove the commas.
if k != len(word_in): # dont want to go outside the size of input.
if word_in[k] != ',': # This means we have a double sized coded letter (i.e. '11')
word.append(char + word_in[k]) # Append both characters of double sized letter to one array slot.
switch = 0 # Prevents double storing of double characters.
else:# Coded letter only one character long
word.append(char)# Append to array.
else:
word.append(char)#if k = len(word_in) then the last one can only be one letter character long.
elif switch == 0:
switch = 1# This resets the switch after skipping the second of the double character code.
return word
|
def get_matched_primer_pair(le,ri):
"""
Inputs:
two lists of primers
get matching primers from a list (get primer pair from same amplicon)
Returns:
matched primer pair (same amplicon) if any
"""
for l in le:
for r in ri:
if l[2] == r[2]:
return l, r
return None, None
|
def get_location(http_info):
"""Extract the redirect URL from a pysaml2 http_info object"""
assert 'headers' in http_info
headers = http_info['headers']
assert len(headers) == 1
header_name, header_value = headers[0]
assert header_name == 'Location'
return header_value
|
def get_brief_classification(crslt):
"""
crslt: dictionary of classification results
"""
return {cat: cla[0] for cat, cla in crslt.items()}
|
def remove_nipsa_action(index, annotation):
"""Return an Elasticsearch action to remove NIPSA from the annotation."""
source = annotation["_source"].copy()
source.pop("nipsa", None)
return {
"_op_type": "index",
"_index": index,
"_type": "annotation",
"_id": annotation["_id"],
"_source": source,
}
|
def get_sentence(line: str, column_number: int) -> str:
"""
Parse the Tab Separated Line to return
the sentence coloumn.
"""
sentence_list = line.split('\t') # Tab separation
sentence_column = sentence_list[1] # Second Column
sentence = sentence_column[:-1] # Remove newline
return sentence
|
def _get_complete_session_attribute_name(session_attribute_name, namespace_name = None):
"""
Retrieves the complete session attribute name from the session
attribute name and the namespace name.
:type session_attribute_name: String
:param session_attribute_name: The session attribute name.
:type namespace_name: String
:param namespace_name: The namespace name.
:rtype: String
:return: The complete session attribute name.
"""
# in case the namespace name is not set
if not namespace_name:
# returns the "original" session attribute name
# as the complete session attribute name
return session_attribute_name
# creates the complete session attribute name by prepending the namespace
# name to the session attribute name
complete_session_attribute_name = namespace_name + "." + session_attribute_name
# returns the complete session attribute name
return complete_session_attribute_name
|
def is_triangular(num):
"""
Determine if a number is of the form (1/2)n(n+1).
"""
from math import floor, sqrt
assert isinstance(num, int) and num > 0
near_sqrt = floor(sqrt(2 * num))
return bool(int((1 / 2) * near_sqrt * (near_sqrt + 1)) == num)
|
def add_css_to_html(html: str, css: str) -> str:
"""Sticks the css into a <style> tag."""
return f'''<style>{css}</style>{html}'''
|
def is_started_with(src, find, ignore_case=True):
"""Verifies if a string content starts with a specific string or not.
This is identical to ``str.startswith``, except that it includes
the ``ignore_case`` parameter.
Parameters
----------
src : str
Current line content.
find : str
Current line content.
ignore_case : bool, optional
Case sensitive or not. The default value is ``True``.
Returns
-------
bool
``True`` if the src string starts with the pattern.
"""
if ignore_case:
return src.lower().startswith(find.lower())
return src.startswith(find)
|
def is_magic(name: str) -> bool:
"""
Checks whether the given ``name`` is magic.
>>> is_magic('__init__')
True
>>> is_magic('some')
False
>>> is_magic('cli')
False
>>> is_magic('__version__')
True
>>> is_magic('__main__')
True
"""
return name.startswith('__') and name.endswith('__')
|
def verify_authorization(perm, action):
"""Check if authorized or not.
"""
if perm == 'all':
return True
if perm == 'read':
return action not in {
'token', 'lock', 'unlock',
'mkdir', 'mkzip', 'save', 'delete', 'move', 'copy',
'backup', 'unbackup', 'cache', 'check',
}
if perm == 'view':
return action in {'view', 'info', 'source', 'download', 'static'}
return False
|
def _split_digits(number, sign_literal):
"""
Split given number per literal and sign
:param number:
:type number: int | str
:param base:
:type base: int
:param sign_literal:
:type sign_literal: str
:return: sign, digits
:rtype: int, list
"""
digits = list(str(number))
sign = 1
if digits[0] == sign_literal:
sign = -1
digits = digits[1:]
return sign, digits
|
def _parse_detector(detector):
"""
Check and fix detector name strings.
Parameters
----------
detector : `str`
The detector name to check.
"""
oklist = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9',
'n10', 'n11']
altlist = [str(i) for i in range(12)]
if detector in oklist:
return detector
elif detector in altlist:
return 'n' + detector
else:
raise ValueError('Detector string could not be interpreted')
|
def embedding_name(model_key):
"""
'src_embed.query_emb.language.lut.weight',
'src_embed.query_emb.main.lut.weight',
'trg_embed.lut.weight'"""
if "embed" in model_key and model_key.endswith("lut.weight"):
name_parts = model_key.split('.')
if name_parts[0] == "enc_embeds":
field_name = name_parts[1] # src or inflection
else:
field_name = name_parts[0].split("_")[0]
return field_name if "language" not in model_key else "_".join([field_name, "language"])
else:
return None
|
def merge_list_of_dicts(list_of_dicts):
"""
Merge list of dicts into one dict.
Paramters
---------
list_of_dicts : STRING
list of dicts to be merged.
Returns
-------
merged_dict : STRING
"""
merged_dict = {k: v for d in list_of_dicts for k, v in d.items()}
return merged_dict
|
def yesno(obj: object) -> str:
"""
Convert an object into 'Yes' or 'No'.
"""
return "Yes" if obj else "No"
|
def TransformExtract(r, *keys):
"""Extract an ordered list of values from the resource for the specified keys.
Args:
r: A JSON-serializable object.
*keys: The list of keys in the resource whose associated values will be
included in the result.
Returns:
The list of extracted values.
"""
try:
return [r[k] for k in keys if k in r]
except TypeError:
return []
|
def get_entangler_map(map_type, num_qubits, offset=0):
"""Utility method to get an entangler map among qubits.
Args:
map_type (str): 'full' entangles each qubit with all the subsequent ones
'linear' entangles each qubit with the next
'sca' (shifted circular alternating entanglement) is a
circular entanglement where the 'long' entanglement is
shifted by one position every block and every block the
role or control/target qubits alternate
num_qubits (int): Number of qubits for which the map is needed
offset (int): Some map_types (e.g. 'sca') can shift the gates in
the entangler map by the specified integer offset.
Returns:
list: A map of qubit index to an array of indexes to which this should be entangled
Raises:
ValueError: if map_type is not valid.
"""
ret = []
if num_qubits > 1:
if map_type == 'full':
ret = [[i, j] for i in range(num_qubits) for j in range(i + 1, num_qubits)]
elif map_type == 'linear':
ret = [[i, i + 1] for i in range(num_qubits - 1)]
elif map_type == 'sca':
offset_idx = offset % num_qubits
if offset_idx % 2 == 0: # even block numbers
for i in reversed(range(offset_idx)):
ret += [[i, i + 1]]
ret += [[num_qubits - 1, 0]]
for i in reversed(range(offset_idx + 1, num_qubits)):
ret += [[i - 1, i]]
else: # odd block numbers
for i in range(num_qubits - offset_idx - 1, num_qubits - 1):
ret += [[i + 1, i]]
ret += [[0, num_qubits - 1]]
for i in range(num_qubits - offset_idx - 1):
ret += [[i + 1, i]]
else:
raise ValueError("map_type only supports 'full', 'linear' or 'sca' type.")
return ret
|
def number_checker(input):
"""Finds type of input (in, float, other).
Args:
input : a string of alphanumeric characters
Returns:
input : the string converted to an int, float
or error message depending on contents of string.
"""
# handling an integer
if input.isnumeric():
input = int(input)
return input
else:
# input is a float or its a mix of other chars
try:
# is the input a float?
input = float(input)
return input
except ValueError:
# input is something else
print("This app requires numeric data.")
return False
|
def last_patient_wait_time(total_patients: int, time_duration: int) -> int:
"""Calculate the wait time for the last patient.
Return wait time in minutes.
"""
# Find the max wait time for all patients ahead of the last patient.
total_max_wait = ((total_patients - 1) * time_duration)
# Find the total patient time of all patients ahead of the last patient.
total_patient_time = (10 * (total_patients - 1))
# Return the difference.
last_patient_wait_time = total_patient_time - total_max_wait
return last_patient_wait_time
|
def process_pane_capture_lines(data, nlines=None):
"""Given the string blob of data from `tmux capture-pane`, returns an array of line strings.
Arguments:
data -- String blob of data from `tmux capture-pane`
nlines -- Maximum number of lines to return
Returns:
An array of line strings. Each line string corresponds to a single visible line such that
a wrapped line is returned as multiple visible lines. Nonprintable characters are removed
and tabs are converted to spaces.
"""
# processes pane capture data into an array of lines
# also handles nonprintables
lines = [
''.join([
' ' if c == '\t' else (
c if c.isprintable() else ''
)
for c in line
])
for line in data.split('\n')
]
if nlines != None:
lines = lines[:nlines]
return lines
|
def reduce_reflex_angle_deg(angle: float) -> float:
""" Given an angle in degrees, normalises in [-179, 180] """
# ATTRIBUTION: solution from James Polk on SO,
# https://stackoverflow.com/questions/2320986/easy-way-to-keeping-angles-between-179-and-180-degrees#
new_angle = angle % 360
if new_angle > 180:
new_angle -= 360
return new_angle
|
def module_to_xapi_vm_power_state(power_state):
"""Maps module VM power states to XAPI VM power states."""
vm_power_state_map = {
"poweredon": "running",
"poweredoff": "halted",
"restarted": "running",
"suspended": "suspended",
"shutdownguest": "halted",
"rebootguest": "running",
}
return vm_power_state_map.get(power_state)
|
def distribute_atoms(atoms, n):
""" split a 1D list atoms into n nearly-even-sized chunks.
"""
k, m = divmod(len(atoms), n)
return [atoms[i*k+min(i,m) : (i+1)*k+min(i+1,m)] for i in range(n)]
|
def m_to_mile(value):
"""Converts distance in meters to miles
Args:
value: floating point representing the distance in meters
Returns: distance in miles
"""
if value is None:
return None
return value / 1609
|
def get_binary(number):
"""
Return the binary string of number (>=0) without 0b prefix.
For e.g 5 returns "101", 20 returns "10100" etc.
"""
return bin(number)[2:]
|
def get_entities_bio(seq):
"""Gets entities from sequence.
note: BIO
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
seq = ['B-PER', 'I-PER', 'O', 'B-LOC', 'I-PER']
get_entity_bio(seq)
#output
[['PER', 0,1], ['LOC', 3, 3]]
"""
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
chunks = []
chunk = [-1, -1, -1]
for indx, tag in enumerate(seq):
if tag.startswith("B-"):
if chunk[2] != -1:
chunks.append(chunk)
chunk = [-1, -1, -1]
chunk[1] = indx
chunk[0] = tag.replace("B-", "")
chunk[2] = indx
if indx == len(seq) - 1:
chunks.append(chunk)
elif tag.startswith('I-') and chunk[1] != -1:
_type = tag.replace("I-", "")
if _type == chunk[0]:
chunk[2] = indx
if indx == len(seq) - 1:
chunks.append(chunk)
else:
if chunk[2] != -1:
chunks.append(chunk)
chunk = [-1, -1, -1]
return set([tuple(chunk) for chunk in chunks])
|
def find_symmetric_difference(list1, list2):
"""
show difference
:param list1:
:type list1:
:param list2:
:type list2:
:return:
:rtype:
"""
difference = set(list1).symmetric_difference(set(list2))
list_difference = list(difference)
return list_difference
|
def getFibonacciIterative(n: int) -> int:
"""
Calculate the fibonacci number at position n iteratively
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a
|
def transform(string):
"""
Capitalizes string, deletes all whitespaces and counts the len of the
product.
"""
string = string.upper()
string = string.replace(" ", "")
length = len(string)
return (string, length)
|
def splitpasswd(user):
"""splitpasswd('user:passwd') -> 'user', 'passwd'."""
user, delim, passwd = user.partition(':')
return user, (passwd if delim else None)
|
def make_status_readable(status):
"""
Returns a readable status
"""
if not status:
return "None"
return '%.2f%% (d: %.1f kb/s up: %.1f kB/s p: %d)\r' % (
status.progress * 100, status.download_rate / 1000,
status.upload_rate / 1000,
status.num_peers
)
|
def map_ips_from_nodes(all_nodes):
"""Creates a mapping of IP address to Node ID and IP Alias.
{'1.1.1.1': {'node_id': 12, 'alias': '2.2.2.2'},
'1.2.3.4': {'node_id': 3, 'alias': None}}
"""
filtered_node_ips = {}
for node in all_nodes:
node_ips = {}
for alloc in node['relationships']['allocations']['data']:
ip = alloc['attributes']['ip']
alias = alloc['attributes']['alias']
if ip not in node_ips:
node_ips[ip] = {'node_id': node['id'],
'node_fqdn': node['fqdn'], 'alias': alias,
'total_allocs': 0, 'used_allocs': 0}
if alloc['attributes']['assigned']:
node_ips[ip]['used_allocs'] += 1
node_ips[ip]['total_allocs'] += 1
filtered_node_ips.update(node_ips)
return filtered_node_ips
|
def average_timeseries(timeseries):
"""
Give the timeseries with avg value for given timeseries containing several values per one timestamp
:param timeseries:
:return:
"""
avg_timeseries = []
for i in range(len(timeseries)):
if len(timeseries[i])>1:
count = len(timeseries[i])-1
avg_timeseries.append([timeseries[i][0], '%.3f' % (sum(timeseries[i][1:])/count)])
return avg_timeseries
|
def json_str_formatter(str_dict):
"""Formatting for json.loads
Args:
str_dict (str): str containing dict of spead streams (received on ?configure).
Returns:
str_dict (str): str containing dict of spead streams, formatted for use with json.loads
"""
# Is there a better way of doing this?
str_dict = str_dict.replace('\'', '"') # Swap quote types for json format
str_dict = str_dict.replace('u', '') # Remove unicode 'u'
return str_dict
|
def do_import(name):
"""Helper function to import a module given it's full path and return the
module object.
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
|
def get_config_option(config, option, required=True):
"""
Get an option (value of key) from provided config dictionary. If the key
does not exist, exit with KeyError (required=True) or return None
(required=False).
"""
try:
value = config[option]
return value
except KeyError:
if required:
raise KeyError(
"Oops! I couldn't find the required option in the "
"config file. Check your config file to ensure the the {} "
"option is populated".format(option)
)
else:
return None
|
def as_gb(in_size: int) -> int:
"""
Converter functions to convert the size in bytes to gigabytes.
"""
conv = 1024 * 1024 * 1024
return in_size // conv
|
def activityToType(jobActivity):
"""
Function to map a workflow activity to a generic CMS job type.
:param jobActivity: a workflow activity string
:return: string which it maps to
NOTE: this map is based on the Lexicon.activity list
"""
activityMap = {"reprocessing": "production",
"production": "production",
"relval": "production",
"harvesting": "production",
"storeresults": "production",
"tier0": "tier0",
"t0": "tier0",
"integration": "test",
"test": "test"}
return activityMap.get(jobActivity, "unknown")
|
def make_tag_dict(tag_list):
"""Returns a dictionary of existing tags.
Args:
tag_list (list): a list of tag dicts.
Returns:
dict: A dictionary where tag names are keys and tag values are values.
"""
return {i["Key"]: i["Value"] for i in tag_list}
|
def GC_skew(seq, window=100):
"""Calculates GC skew (G-C)/(G+C) for multiple windows along the sequence.
Returns a list of ratios (floats), controlled by the length of the sequence
and the size of the window.
Does NOT look at any ambiguous nucleotides.
"""
# 8/19/03: Iddo: added lowercase
values = []
for i in range(0, len(seq), window):
s = seq[i: i + window]
g = s.count('G') + s.count('g')
c = s.count('C') + s.count('c')
skew = (g-c)/float(g+c)
values.append(skew)
return values
|
def _jupyter_labextension_paths():
"""Called by Jupyter Lab Server to detect if it is a valid labextension and
to install the widget.
Returns:
src: Source directory name to copy files from. Webpack outputs generated
files into this directory and Jupyter Lab copies from this directory
during widget installation.
dest: Destination directory name to install widget files to. Jupyter Lab
copies from `src` directory into <jupyter path>/labextensions/<dest>
directory during widget installation.
"""
return [{
'src': 'labextension',
'dest': 'open3d',
}]
|
def stringify_groups(groups):
"""Change a list of Group (or skills) objects into a
space-delimited string.
"""
return u','.join([group.name for group in groups])
|
def maximumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value above n.
Example:
.. code-block:: none
&target=maximumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent more than 1000 packets/min.
"""
results = []
for series in seriesList:
if max(series) > n:
results.append(series)
return results
|
def parse_int(text: str) -> int:
"""
Takes in a number in string form and returns that string in integer form
and handles zeroes represented as dashes
"""
text = text.strip()
if text == '-':
return 0
else:
return int(text.replace(',', ''))
|
def _split_escape_string(input, keep_escape = True, splitchar = ',', escapechar = '\\'):
""" Splits a string but allows escape characters """
results = []
string = ""
escaped = False
for c in input:
if not escaped and c == escapechar:
escaped = True
if keep_escape:
string += c
elif not escaped and c == splitchar:
results.append(string)
string = ""
else:
string += c
escaped = False
results.append(string)
return results
|
def get_server_port(meta, server, val=None):
"""
Gets the server port value from configuration.
"""
val = server.getConf('port') if val is None else val
if '' == val:
val = meta.getDefaultConf().get('port', 0)
val = int(val) + server.id() - 1
return int(val)
|
def url_encode(string: str):
"""Take a raw input string and URL encode it."""
replacements = {"!": "%21", "#": "%23", "$": "%24", "&": "%26", "'": "%27",
"(": "%28", ")": "%29", "*": "%2A", "+": "%2B", ",": "%2C",
"/": "%2F", ":": "%3A", ";": "%3B", "=": "%3D", "?": "%3F",
"@": "%40", "[": "%5B", "]": "%5D", " ": "%20", "\"": "%22",
"-": "%2D", ".": "%2E", "<": "%3C", ">": "%3E", "\\": "%5C",
"^": "%5E", "_": "%5F", "`": "%60", "{": "%7B", "|": "%7C",
"}": "%7D", "~": "%7E", "%": "%25"}
encoded = ""
for char in string:
encoded += replacements.get(char, char)
return encoded
|
def hex_to_dec(val):
"""Converts hexademical string to integer"""
return int(val, 16)
|
def valid_lecture(lecture_number, lecture_start, lecture_end):
"""Testing if the given lecture number is valid and exist."""
if lecture_start and lecture_end:
return lecture_start <= lecture_number <= lecture_end
elif lecture_start:
return lecture_start <= lecture_number
else:
return lecture_number <= lecture_end
|
def fetch_parts(summary):
"""Picks out elements of the document summary from Entrez"""
AssemblyAccession = summary["AssemblyAccession"]
AssemblyStatus = summary["AssemblyStatus"]
WGS = summary["WGS"]
Coverage = summary["Coverage"]
SubmissionDate = summary["SubmissionDate"]
LastUpdateDate = summary["LastUpdateDate"]
biosampleID = summary["BioSampleId"]
return AssemblyAccession, AssemblyStatus, WGS, Coverage, SubmissionDate, LastUpdateDate, biosampleID
|
def _is_user_option_true(value):
""" Convert multiple user inputs to True, False or None """
value = str(value)
if value.lower() == 'true' or value.lower() == 't' or value.lower() == 'yes' or value.lower() == 'y' or value.lower() == '1':
return True
if value.lower() == 'false' or value.lower() == 'f' or value.lower() == 'no' or value.lower() == 'n' or value.lower() == '0':
return False
return None
|
def _reset_nuisance(x, like, cache):
"""Internal function which sets the values of the nuisance
parameters to those found in a previous iteration of the
optimizer. Not intended for use outside of this package."""
sync_name = ""
icache = 0
if x in cache:
params = cache[x]
for iparam in range(len(like.model.params)):
if sync_name != like[iparam].srcName:
like.syncSrcParams(sync_name)
sync_name = ""
if(like.model[iparam].isFree()):
like.model[iparam].setValue(params[icache])
sync_name = like[iparam].srcName
icache += 1
if sync_name != "":
like.syncSrcParams(sync_name)
return True
return False
|
def matchKeys(keyA, keyB):
"""Return the tuple (keyA, keyB) after removing bits where Bob's measured photon
was absorbed. Assumes a value of -1 in keyB represents an absorbed photon.
"""
match = [False if k == -1 else True for k in keyB]
keyB = [keyB[k] for k in range(len(keyB)) if match[k]]
while len(match) < len(keyA):
match.append(True)
keyA = [keyA[k] for k in range(len(keyA)) if match[k]]
return (keyA, keyB)
|
def find_url(list_of_links):
"""
There are many apis which get same work done.
The idea here is to show the best one.
Here is the logic for picking the best one.
* if there is only one element in the list, the choice is obvious.
* if there are more than one:
return for a link which does not contain "~action" in them and which contain "id:{}" in them.
"""
if len(list_of_links) == 1:
return list_of_links[0]['href'], list_of_links[0]['method']
non_action_link = None
for link in list_of_links:
if '~action=' not in link['href']:
if "id:" in link['href']:
return link['href'], link['method']
if non_action_link is None:
non_action_link = link
if non_action_link is None:
# all links have ~action in them. check if any of them has id: and return it.
for link in list_of_links:
if "id:" in link['href']:
return link['href'], link['method']
# all links have ~action in them and none of them have id: (pick any one)
return list_of_links[0]['href'], list_of_links[0]['method']
return non_action_link['href'], non_action_link['method']
|
def lc(value):
"""Lower case and remove any periods to normalize for comparison."""
if not value:
return ''
return value.lower().strip('.')
|
def mod_pow(base, power, mod):
"""
Solve x = a^b % c
:param base: a
:param power: b
:param mod: c
:return: x
"""
if power < 0:
return -1
base %= mod
result = 1
while power > 0:
if power & 1:
result = (result * base) % mod
power = power >> 1
base = (base * base) % mod
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.