content stringlengths 42 6.51k |
|---|
def mapVal2Color(colorInt):
"""
Maps an integer to a color
Args:
- colorInt: the integer value of the color to map
Returns:
returns a string of the mapped color value
"""
colorDict = {1: "Green",
2: "Red",
3: "Blue",
... |
def get_element_present_in_list(elements, list_):
"""Return the first element that is present in `list`, otherwise None."""
for element in elements:
if element in list_:
return element
return None |
def scinotation(num):
"""Write in scientific notation
>>> scinotation(1./654)
' 1.52905E-03'
>>> scinotation(-1./654)
'-1.52905E-03'
"""
ans = "%10.5E" % num
broken = ans.split("E")
exponent = int(broken[1])
if exponent<-99:
return " 0.000E+00"
if exponent<0:
... |
def convertShape(shapeString):
""" Convert xml shape string into float tuples.
This method converts the 2d or 3d shape string from SUMO's xml file
into a list containing 3d float-tuples. Non existant z coordinates default
to zero. If shapeString is empty, an empty list will be returned.
"""
cs... |
def get_template(config, key):
"""Get an interpolation template out of the config.
Args:
config (dict): Dictionary.
key (str): Template key.
Returns:
str: Template.
"""
# Get the template out of the configuration
template = config['templates'][key]
# Convert list t... |
def id_query(doc_id):
"""Create a query for a document with the given id.
Parameters
----------
doc_id : str
The document id to match.
Returns
-------
dict
A query for a document with the given `doc_id`.
"""
return {'id': doc_id, 'refresh': True, 'ignore': 404} |
def rm_non_ascii(s):
"""
remove any non ascii characters
"""
if not isinstance(s, str):
return s
s = s.strip()
s = ''.join(filter(lambda x: ord(x)<128, s))
return str(s) |
def clean_place_string(place_string):
""" takes e.g. 'St. Lorenzen (St. Michaelsburg)' and
returns the tuple ('St. Lorenzen', 'St Michaelsburg') """
first_place = place_string.split("(")[0]
lg = " ".join(place_string.split("(")[1:])
lg = lg.replace(')', '')
return(first_place, lg) |
def join(l, sep='\n'):
# type: (str, str) -> str
"""Concatenate list of strings."""
return sep.join(v for v in l if v) |
def sanitizer(name):
"""
Sanitizes a string supposed to be an entity name. That is,
invalid characters like slashes are substituted with underscores.
:param name: A string representing the name.
:returns: The sanitized name.
:rtype: str
"""
return name.replace("/", "_") |
def scale(a: tuple, scalar: float) -> tuple:
"""Scales the point."""
return a[0] * scalar, a[1] * scalar |
def populateCounts(end) :
"""
Given the maximum number through which the table needs to be populated, we form the table.
Parameters
----------
end - the extent of continuous missing letters in string (or the length of the table needed)
Return
------
table - with i'th index pointing to ... |
def change_ttw(x):
"""Math function which creates next time to wait (ttw)
Args:
x (int): number of checks
Returns:
time to wait
"""
if x < 15:
return 0
elif x > 42:
return 120
return 1.2 ** (x - 15) |
def dictionarify_recpat_data(recpat_data):
"""
Covert a list of flat dictionaries (single-record dicts) into a dictionary.
If the given data structure is already a dictionary, it is left unchanged.
"""
return {track_id[0]: patterns[0] for track_id, patterns in \
[zip(*item.items()) for ... |
def get_eng_file_rel_path(file_prefix, num_qbits):
"""
Returns path to English file.
Returns
-------
str
"""
return file_prefix + '_' + str(num_qbits) +\
'_eng.txt' |
def _getitem(self, key):
"""A function to provide dict like indexing"""
return getattr(self, key, None) |
def remSpecialChar(text):
"""removes special LaTeX/BibTeX characters from a string"""
text = text.replace("{","").replace("}","")
text = text.replace("\\","")
text = text.replace("&","")
return text |
def mock_create_config(authentication_token="", **kwargs):
"""A mock version of the create_config function adjusted to the
store_account function.
"""
return {"api": {"authentication_token": authentication_token, **kwargs}} |
def is_number(obj):
#todo: delete?
"""
Shorter name for is_probably_a_number_since_it_behaves_like_one().
"""
try:
obj + 3.7
except TypeError:
return False
return True |
def normalise_commodity_code(code: str) -> str:
"""
Normalises a string which is a candidate for a commodity code.
Removes all dots.
"""
code = code.replace(".", "")
return code |
def black_percentage(rgb):
"""
rgb: rgb tuple of a pixel
returns: pixel percentage of black
"""
if isinstance(rgb, int):
return 100 - rgb
return 100 - (int((((rgb[0] + rgb[1] + rgb[2])/3)*100)/255)) |
def maxwell_eucken(phi):
"""
:param
phi: np.ndarray
Porosity [unit-less]
:return
So: np.ndarray
Maxwell Eucken model of macroscopic suppression function
"""
So = (1 - phi) / (1 + phi / 2)
return So |
def _seed_id_keyfunction(x):
"""
Keyfunction to use in sorting two (partial) SEED IDs
Assumes that the last (or only) "."-separated part is a channel code.
Assumes the last character is a the component code and sorts it
"Z"-"N"-"E"-others_lexical.
"""
# for comparison we build a list of 5 S... |
def srgb_to_linear(color: float):
""" Convert a sRGB gamma encoded color value to linear color value """
if color <= 0.04045:
return color / 12.92
else:
return pow(((color+0.055) / 1.055), 2.4) |
def is_dict(var):
"""
is this a dict-like?
"""
# see also collections.Mapping
return isinstance(var, dict) |
def decode_pin_tpm2(_module, json_jwe, keys):
"""Decode a tpm2 pin JWE.
Return <tpm2 (pin)> <tpm2 config> <keys> <error>"""
pin = {}
tpm2_keys = ["hash", "key", "pcr_bank", "pcr_ids", "pcr_digest"]
for key in tpm2_keys:
if key in json_jwe:
pin[key] = json_jwe[key]
return "t... |
def remap(diff):
"""Changes the format of a chain diff.
:param diff: A diff in the format {district: [node 1, node 2, ...]}
:returns: A diff in the format {node 1: district, node 2: district, ...}
"""
flipped = {}
for district, nodes in diff.items():
for node in nodes:
f... |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums:
return 0
if max(nums) < 0:
return max(nums)
#Implementation of Kadan... |
def is_in(objet: dict, indexes: list):
"""
check if a list of indexes exist in a dict
:param objet: reference dict for the search
:param indexes: list of searched index
:return: bool
"""
for elem in indexes:
if str(elem) in objet:
continue
else:
retur... |
def weight_path(spec_path, element_path):
"""Determine the weighting number for a matchingRule path spec applied to an actual element path from a
response body.
Both paths are passed in as lists which represent the paths split per split_path()
In spec version 2 paths should always start with ['$', 'bo... |
def comp4(array1, array2):
"""
Another experiment
"""
if not array2 or not array1:
return False
array1.sort()
array2.sort()
array1 = [num**2 for num in array1]
for i, num in enumerate(array1):
if num != array2[i]:
return False
return True |
def collapse_complexes(data):
"""Given a list or other iterable that's a series of (real, imaginary)
pairs, returns a list of complex numbers. For instance, this list --
[a, b, c, d, e, f]
this function returns --
[complex(a, b), complex(c, d), complex(e, f)]
The returned list is a new li... |
def is_snapshot_from_cluster(source_snapshot_arn):
"""
Returns whether a snapshot was generated from a cluster (Aurora)
or a "regular" RDS databases
:param source_snapshot_arn: arn of the snapshot
"""
if 'cluster' in source_snapshot_arn:
return True
return False |
def parseGenreList(value):
"""
"""
if not isinstance(value, list) or not value:return []
return [v.lower() for v in value] |
def get_output(outputs, key):
"""
Parse and return values from a CloudFormation outputs list.
:param list outputs: A list of ``dict`` having items of `(`OutputKey``,
``OutputValue``).
:param unicode key: The key for which to retrieve a value from ``outputs``.
:returns: A ``unicode`` value.
... |
def index_to_letter(idx):
"""Convert a numerical index to a char."""
if 0 <= idx < 20:
return chr(97 + idx)
else:
raise ValueError('A wrong idx value supplied.') |
def get_all_tags(queries):
""" Returns a list of all tags specified within the source files """
tags = []
for q in queries:
tags.extend(q['tags'])
return sorted(list(set(tags))) |
def is_decay_profile(profile):
""" Check if a profile string is for DM decay """
tokens = profile.split('_')
return tokens[-1] in ['point', 'dmap', 'dradial'] |
def sqrt(x, tolerance=0.0000001):
"""
Find a value r with r*r within tolerance of x.
"""
l = 0.0
r = float(x)
while r-l > tolerance:
m = l + 0.5*(r-l)
s = m*m
if s < x:
l = m
else:
r = m
return l |
def from_pcl(infile, outfile):
"""Convert a pcl file to biom format using the biom package
:param infile: String; name of the input tsv or pcl file
:param outfile: String; name of the resulting converted biom file
External dependencies
- biom-format: http://biom-format.org/
"""
cmd="bi... |
def _safe_int(string):
"""Simple function to convert strings into ints without dying.
Helps when we define versions like 0.1.0dev"""
try:
return int(string)
except ValueError:
return string |
def upto(limit: str, text: str) -> str:
""" return all the text up to the limit string """
return text[0 : text.find(limit)] |
def invert_dict(dct: dict) -> dict:
"""Invert dictionary, i.e. reverse keys and values.
Args:
dct: Dictionary
Returns:
Dictionary with reversed keys and values.
Raises:
:class:`ValueError` if values are not unique.
"""
if not len(set(dct.values())) == len(dct.values())... |
def update_board(board, player, x, y):
"""
updates the given coordinates(0-based) of the board with player's token.
if the given coordinate corresponds to a nonnempty square returns False without making any modifications.
returns True otherwise
"""
# Your code starts here.
if board[x][y] != ... |
def valid_user_role(specified_role):
"""Returns whether or not a role is valid in the DDS."""
return specified_role in [
"Super Admin",
"Unit Admin",
"Unit Personnel",
"Project Owner",
"Researcher",
] |
def decimal_digits(x: float, precision: int) -> int:
"""Forms an integer from the base-10 digits of a floating-point number.
Args:
x: A floating point number, which may be negative.
precision: The number of digits after the decimal point to include.
Returns:
An integer containing a... |
def time_to_words(h, m):
"""
:type h: int
:type m: int
:rtype: str
"""
hours = {
0: "o' clock",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
... |
def _count_worker(cluster_spec):
"""Counts the number of workers in cluster_spec.
Workers with TaskType.WORKER and TaskType.MASTER are included in the return
value.
Args:
cluster_spec: a ClusterSpec instance that describes current deployment.
Returns:
The total number of eligible workers.
If '... |
def xor(_a_: bool, _b_: bool) -> bool:
"""XOR logical operation.
:param _a_: first argument
:param _b_: second argument
:return: xor-ed value
"""
#pylint: disable-msg=superfluous-parens
return bool((not(_a_) and _b_) or (_a_ and not(_b_))) |
def phantom_bullet_dict(phantom_request_dict):
"""Phantom bullet property values as a dictionary."""
bullet_dict = {'0': '147 tests'}
bullet_dict.update(phantom_request_dict)
return bullet_dict |
def get_numbers_and_square(num_list: list) -> dict:
"""Returns a dict with number and number^2 from a list."""
return {num: num * num for num in num_list} |
def gardner(vp, alpha=310, beta=0.25):
"""
Compute bulk density (in kg/m^3) from vp (in m/s).
"""
return alpha * vp**beta |
def _parseline(line):
"""Parse Line to dict"""
if line.startswith("#"):
return None, None
line = line.replace("\n","")
if line.strip():
quote_delimiter = max(
line.find('\'', line.find('\'') + 1),
line.find('"', line.rfind('"')) + 1 #: find first comment mar... |
def exclude_exprs(La, Lb):
"""
Returns list that's in a, but not in b
"""
b_unique_strs = set([node.unique_str() for node in Lb])
return [node for node in La if node.unique_str() not in b_unique_strs] |
def sum_regular(data):
"""
Sums all elements in passed sequence.
You may assume that all elements in passed argument is numeric
>>> sum_regular([3, 6, 9])
18
>>> sum_regular(range(10))
45
>>> sum_regular((8.2, 6.3, 13.1))
27.6
>>> sum_regular([])
0
Args:
data: i... |
def isEven(number: int) -> bool:
"""
Checks if the given number is even or odd.
>>> isEven(4)
True
>>> isEven(3)
False
>>> not isEven(3)
True
"""
return ((number % 2) == 0) |
def dedent(text: str) -> str:
"""Remove whitespaces before and after newlines"""
return '\n'.join(x.strip() for x in text.split('\n')) |
def create_zero_matrix(rows: int, columns: int) -> list:
"""
Creates a matrix rows * columns where each element is zero
:param rows: a number of rows
:param columns: a number of columns
:return: a matrix with 0s
e.g. rows = 2, columns = 2
--> [[0, 0], [0, 0]]
"""
if not isinstance(ro... |
def validate_category_or_command_name(name):
"""
Validates the given category name.
Parameters
----------
name : `str`
The name of a category or command.
Returns
-------
name : `str`
The validated name.
Raises
------
TypeError
If `name` ... |
def solution(A, K):
"""
In the below example we calculate the real value of K (by removing full
loops) and then shift by K using list ranges.
This could be also implemented by using the list.pop() method, however
the time complexity would be greater (if somewhat more legible paraphs)
Warning:
... |
def _get_expected_score(player_rating, opponent_rating):
"""
https://wikimedia.org/api/rest_v1/media/math/render/svg/51346e1c65f857c0025647173ae48ddac904adcb
Returns the expected score rounded to two decimals
For instance, a player with 100 less ELO points than their opponent has an expected score
... |
def is_exception(val):
"""Returns whether a given value is an exception type (not an instance)."""
return isinstance(val, type) and issubclass(val, Exception) |
def trimVersionString(version_string):
"""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 == '':
... |
def disposable_income(income, wealth, income_taxes, wealth_taxes, benefits, params):
"""Calculate disposable income.
Args:
income (pd.Series)
taxes (pd.Series)
benefits (pd.Series)
params (pd.Series)
Returns:
disposable_income (pd.Series)
"""
return income ... |
def curverad_center_dist_texts(left_curverad, right_curverad, center_dist):
"""
Generates texts for curvature radius and center distance.
:param left_curverad: left curvature radius.
:param right_curverad: right curvature radius.
:param center_dist: center distance.
:return: list of strings.
... |
def asr(value, count, width=32):
"""Arithmetic Shift Right (assuming unsigned input)"""
count %= width
value &= (1 << width) - 1
msb = value >> (width - 1)
value -= (1 << width) * msb # Convert to signed.
# First shift 1 to the left to leave room for the carry.
value <<= 1
value >>= cou... |
def next_token(text, i):
""" syntax Find next token in raw string starting at some index
"""
search = "TBD"
nested = 1
h = i
while i < len(text):
single = text[i:i+1]
double = text[i:i+2]
if search == "TBD":
if double == b'<<':
search = "DICT"
... |
def convert_metadata_1_0_to_1_1(metadata):
"""
Convert 1.0 to 1.1 metadata format
:arg metadata: The old metadata
:returns: The new metadata
Changes from 1.0 to 1.1:
* ``supported_by`` field value ``curated`` has been removed
* ``supported_by`` field value ``certified`` has been added
... |
def actionStatus(status):
"""
Get a transformed status based on the workflow status.
"""
if status == 'success':
return 'passed'
elif status == 'failure':
return 'failed'
return 'passed with warnings' |
def format_values(values):
"""Formats a set of values."""
return '{ ' + ', '.join('{:.15g}'.format(x) for x in values) + ' }' |
def unique(seq, idfun=None):
"""
Finds the unique items in a list and returns them in order found.
Inspired by discussion on ``http://www.peterbe.com/plog/uniqifiers-benchmark``
Notably f10 Andrew Dalke and f8 by Dave Kirby
Parameters
----------
seq : an iterable object
... |
def Not(query):
"""The negation of a query"""
return '(NOT %s)' % (query,) |
def check_pg_num(pool, pg_num, size, num_osds=0, max_pgs_per_osd=200, pools={}):
"""
Returns empty string only if the Pool PG numbers are correct for the OSDs.
Otherwise returns an error message like the one Ceph would return.
"""
# The original check in C++ from the Ceph source code is:
#
#... |
def keymap(fn, d):
"""returns {fn(k): v for k, v in d.items()}"""
return {fn(k): v for k, v in d.items()} |
def dump_profiles(profiles):
"""
Dump profiles into json format accepted by the plotting library
:return: list of dicts representing points in the profiles
"""
data = []
for cp_profile in profiles:
for i, row in cp_profile.profile.iterrows():
data.append(dict(zip(cp_profile.... |
def _get_caliper_indices_out_of_range(lst_coords, strt, end):
"""
Remove shapes that fall off the display in internal tracks
:return: 2 tuple of if any measurement is removed, and the corresponding indices in sorted order
"""
removed = False
idxs = []
for idx, (x0, x1, y0, y1) in enumerate... |
def frame_number(time_seconds, frames_per_second):
"""Utility function to calculate the frame number for a particular time
given the anticipated frames per second for the animation.
Args:
time_seconds (float or int): time in seconds to convert to frames
frames_per_second (float or int): num... |
def _check_base_estimator(estimator):
""" Validates base estimator """
return (
hasattr(estimator, "fit") and
hasattr(estimator, "predict")
) |
def _near_words(first, second, distance, exact=False):
"""
Returns a query item matching messages that two words within a certain
distance of each other.
Args:
first (str): The first word to search for.
second (str): The second word to search for.
distance (int): How many words ... |
def assign_allergenes(ingredient_allergenes: dict) -> dict:
"""return a dict with each ingredient and its allergene"""
assigned_allergenes = dict()
while ingredient_allergenes:
assigned_allergene = str()
assigned_ingredient = str()
for ingredient, allergenes in ingredient_allergenes... |
def factors(num, length):
"""
Sped up greatly by assuming that for a number to be divisible by n numbers, there's gotta be at least n/5
factors in the first n natural numbers, which prove true
:param num: current triangle to test
:param length: maximum length of the array
:return: number of fact... |
def isEnabled(newStates, enable, estopState):
"""
Function to handle enable and estop states. it was getting annoying to look at.
"""
enable = True
return enable |
def map_sequence(word_sequence, word2idx):
"""
Get embedding indices for the given word sequence.
:param word_sequence: sequence of words to process
:param word2idx: dictionary of word mapped to their embedding indices
:return: a sequence of embedding indices
"""
return [map(word, word2idx)... |
def is_int_even_v01(num):
"""
Use the modulo operator to evaluate whether an integer provided by
the caller is even or odd, returning either True or False.
Parameters:
num (int): the integer to be evaluated.
Returns:
is_even (boolean): True or False depending on the modulo check
... |
def replace_unique_items(iterable, replace_with=None):
"""
replaces items after the first unique item in a list
with replace_with.
::default behavior::
----------------------------------
In : x = [1, 1, 2, 2]
Out : replace_unique_items(x)
[1, None, 2, None]
"""
result = []
... |
def _minimum_possible(skew, loc, scale):
"""
Compute the minimum possible value that can be fitted to a distribution
described by a set of skew, loc, and scale parameters.
:param skew:
:param loc:
:param scale:
:return:
"""
alpha = 4.0 / (skew * skew)
# calculate the lowest po... |
def largest_prime_factor(input_num):
"""
Function returns the largest prime factor of an input.
REQ: input_num >= 0 and whole
:param input_num: {int} is original input number
:return: {int} the largest prime factor of the input or {NoneType} if input_num < 2
"""
# if input is less than 2,... |
def indices(a, func):
"""
Returns the indices of a which verify a condition defined by a lambda function.
Args:
a: The list to be interrogated
func: The function to be applied to the list
Returns:
List of the indices of the list that satisfy the function
Example:
yea... |
def get_size_class(earlength):
"""Determine the size class of earlength based on Dr. Grangers specification"""
if earlength > 15:
size_class = 'extralarge'
elif earlength > 10:
size_class = 'large'
if earlength < 8:
size_class = 'medium'
else:
size_class = 'small'
... |
def get_location(data_str: str) -> str:
"""Get the category field from either a ``prices`` or ``pdates`` index's
key's data"""
return data_str.split(",")[2] |
def _default_alias_is_added(fn_aliases, default_alias_name):
"""
Checks if the `default alias` is part of a list of aliases
"""
for alias in fn_aliases:
if alias["Name"] == default_alias_name:
return True
return False |
def pop_recursive(dictionary, pop_func):
"""Recursively remove a named key from dictionary
and any contained dictionaries."""
pop_func(dictionary)
for key, value in dictionary.items():
# If remove_key is in the dict, remove it
if isinstance(value, dict):
pop_recursive(value... |
def dist3D(pt1, pt2):
"""Returns distance between two 3D points (as two 3-tuples)"""
return ((pt2[0]-pt1[0])**2 + (pt2[1]-pt1[1])**2 + (pt2[2]-pt1[2])**2)**0.5 |
def line_starts_with(line, string, case_insensitive=True):
"""
Checks if the line starts with the given string.
:param line: The line to check.
:param string: The string to look for.
:param case_insensitive: Whether the check should disregard case.
:return: ... |
def get_bsj(seq, bsj):
"""Return transformed sequence of given BSJ"""
return seq[bsj:] + seq[:bsj] |
def _split_title(title):
"""Split title into component parts."""
parts = title.split(";")
return list(map(str.strip, parts)) |
def parse_processes(processes_list: list) -> list:
"""
This function gets a processes list and retrives specific data from each process and builds a new list of the
parsed process data.
:param processes_list: the raw processes list
:return: the parsed processes list
"""
parsed_processes_list... |
def get_corners(center_x, center_y, width, height):
"""
Transform coordinates of the center, width and height of the bounding
box into coordinates of the top-left and right-bottom corners.
"""
x1 = center_x - width/2
y1 = center_y - height/2
x2 = center_x + width/2
y2 = center_y + height... |
def button_action (date, action, value) :
""" Create a button for time-tracking actions """
''"approve", ''"deny", ''"edit again"
if not date :
return ''
return \
'''<input type="button" value="%s"
onClick="
if(submit_once()) {
document.forms.edit_... |
def mgmt_url(base, **kwargs):
"""Join a base url with url parameters
Used to help pass a url a function like add_modal
Args:
base (string) : Base url string (already resolved by Django)
kwargs (dict) : Key value url parameters to append
"""
params = "&".join(["{}={}".format(k,v) fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.