content stringlengths 42 6.51k |
|---|
def unpack_arg(v):
"""Use for local methods."""
if isinstance(v, tuple):
return v[0], v[1]
return v, {} |
def nx_edge_data_priority(edge_u, edge_v, edge_data):
"""Return custom edge data value to be used as a callback by nx."""
if edge_data.get("priority"):
return edge_data["priority"]
return 1 |
def cost_usage_data():
""" Generates cost usage data"""
return {
"ResultsByTime": [
{
"Estimated": True,
"TimePeriod": {
"Start": "2019-11-06",
"End": "2019-11-07"
},
"Total": {
"BlendedCost": {
... |
def clean_text(text):
"""
Removes Non-ASCII characters from text.
"""
return str(text.encode().decode("ascii", errors="ignore")) |
def Build(workers, section):
"""A node can also be created by the Node decorator.outputs
The inputs to the function are turned into InputsPlugs, outputs are defined
in the decorator itself.
The wrapped function is used as the compute method.
"""
print('{0} are building the {1}'.format(', '.join... |
def ConvertToNumber(value):
"""Converts value, a string, into either an integer or a floating point
decimal number.
"""
try:
# int() automatically promotes to long if necessary
return int(value)
except:
return float(value) |
def multiply_by(multiplier: int, number: int) -> int:
"""Multiply 'number' by 'multiplier'."""
result = number * multiplier
print(f"Result: {result}")
return result |
def _downscale_incremental_strategy(current_nodes):
"""Simple downscale strategy: decrease nodes by 2."""
new_nodes = current_nodes - 2
if new_nodes < 3: # 3 is minimum number of CBT nodes
return 3
return new_nodes |
def get_operations(product_id):
"""Get ProductImageCreate operations
Parameters
----------
product_id : str
id for which the product image will be created.
Returns
-------
query : str
variables: dict
"""
query = """
mutation ProductImageCreate($product: ID!,... |
def collect(signatures):
"""
Collect a list of timestamps, returning
the most-recent timestamp from the list
signatures - a list of timestamps
returns - the most recent timestamp
"""
if len(signatures) == 0:
return 0
elif len(signatures) == 1:
return signatures[0]
... |
def copy_datastore(data_store):
"""
This is used for getting a shallow copy that is passed to the validation rules.
"""
return {k: v.copy(deep=False) if k != 'metadata' else v for k, v in data_store.items()} |
def _verify_req_cols(req_cols, allowed_output_cols):
"""
Verify user requested columns against allowed output columns.
"""
if req_cols is not None:
if not req_cols.issubset(allowed_output_cols):
raise ValueError(
"Given req_cols must be subset of %s" % (allowed_output... |
def _extract_xy_from_gdcm_str(lines, dicom_tags):
"""Get rows, columns from gdcmdump output."""
rows = 0
cols = 0
for line in lines:
line = line.lstrip()
tag = line.split(" ")[0]
if tag == dicom_tags["rows"]:
rows = line.split(" ")[2]
elif tag == dicom_tags["c... |
def _255_to_tanh(x):
"""
range [0, 255] to range [-1, 1]
:param x:
:return:
"""
return (x - 127.5) / 127.5 |
def compute_psi(alpha, market_params, maturity_time_years, characteristic_function, variable):
"""
Calculate characteristic function dependent quantity in the integrand term.
Args:
alpha: Regularization parameter.
market_params: The market parameters.
maturity_time_years: Measured in... |
def lol2str(doc):
"""Transforms a document in the list-of-lists format into
a block of text (str type)."""
return " ".join([word for sent in doc for word in sent]) |
def jsonKeys2int(x):
"""Casts str keys to int.
Args:
x (dict): Dictionary with str keys.
Returns:
dict: Dictionary with int keys.
"""
if isinstance(x, dict):
return {int(k):v for k,v in x.items()}
return x |
def is_insert(line):
"""
Returns true if the line begins a SQL insert statement.
"""
return line.startswith('INSERT INTO') or False |
def get_port_name(port):
"""Get the domain ID and index of the port."""
port_base = 7400
domain_id_gain = 250
domain_id = (port - port_base) / domain_id_gain
doffset = (port - port_base) % domain_id_gain
if doffset == 0:
nature = "MeMu"
participant_idx = 0
elif doffset == 1:... |
def ra_to_degree(catalogs):
"""Conviert el ra en grados
"""
return 15 * (
catalogs['ra_h'] +
catalogs['ra_m'] / 60.0 +
catalogs['ra_s'] / 3600.0
) |
def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return "None"
elif obj is Ellipsis:
return "Ellipsis"
cls = type(obj)... |
def rekey(x, key_map=None):
"""Replace the feature keys according to the mapping in `key_map`.
For example, if the dataset returns examples of the format:
{'foo': 'something', 'bar': 'something else'}
and key_map = {'boo': 'foo', 'spar': 'bar'} then this function will return
examples with the format
{'boo'... |
def post_data_columns(data_columns):
"""Add important data columns to the column list and return them.
Given a dict of data columns containing a list of data columns to
read, add additional important data columns to the column list, and
return the changed list.
Note that a data columns dict ... |
def get_layer_nr_id(name):
"""
For the given full layer parameter name, e.g.
language_model.model.encoder.layer.11.attention.output.dense.bias return the
numeric layer number (11) and the id ("attention.output.dense.bias")
"""
if name.startswith("language_model.model.encoder.layer."):
su... |
def log_at_level(logger, message_level, verbose_level, msg):
"""
writes to log if message_level > verbose level
Returns anything written in case we might want to drop down and output at a
lower log level
"""
if message_level <= verbose_level:
logger.info(msg)
return True
retu... |
def null_geoms_query(schema, table):
"""Returns sql query to check null geometries of a table.
Args:
schema: Name of the schema.
table: Name of the table.
Returns:
String sql query.
"""
return (
'SELECT id '
'FROM {}.{} '
'WHERE geom IS NULL '
'ORDER BY id'
).format(schema, tab... |
def any_item_in_string(items, test_string):
"""Return true if any item in items is in test_string
Args:
items ([str]): List of strings to compare against test_string.
test_string (str): String to search for the items.
Returns:
bool: True if any item exists in test_string, False oth... |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'admin' |
def get_number_of_usable_hosts_from_raw_address(raw_address: str) -> int:
"""
Return number of usable host ip addresses.
>>> get_number_of_usable_hosts_from_raw_address("192.168.1.15/24")
254
>>> get_number_of_usable_hosts_from_raw_address("91.124.230.205/30")
2
"""
slash_ind = raw_add... |
def flatten(irregular_matrix) -> list:
""" Allows flattening a matrix of nested iterables where the specific type
and shape of each iterable is not necessarily the same. Returns
the individual elements of the original nested iterable in a single
flat list.
Note that this operation's... |
def is_matched(expression):
"""https://www.hackerrank.com/challenges/ctci-balanced-brackets"""
stack = []
pairs = {"(": ")", "{": "}", "[": "]"}
for c in expression:
if c in pairs:
stack.append(pairs[c])
elif not stack or c != stack.pop():
return False
retu... |
def denormalise(x_n, x_mean, x_std):
"""Map from normalised set of vectors to non-normalised originals."""
return x_n * x_std + x_mean |
def array_extract_units(data):
"""extract the units of an array
If ``data`` is not a quantity, the units are ``None``
"""
try:
return data.units
except AttributeError:
return None |
def get_block_coordinate_range(block_number, block_size, overlap_size,
image_size):
"""
Returns the minimum and maximum coordinate values in one dimension for
an image block, where the dimension length image_size is to be split into
the number of blocks specified by block_... |
def inverse_dict(original):
"""Return a dictionary that is the inverse of the original.
Given the pair original[key] = value, the returned dictionary will give
ret[value] = key. It is important to keep two separate dictionaries in case
there is key/value collision. Trying to insert a value that matches... |
def get_e_machine(e_machine):
"""Get the machine."""
if e_machine == b'\x00\x00':
return 'No specific instruction set'
elif e_machine == b'\x02\x00':
return 'SPARC'
elif e_machine == b'\x03\x00':
return 'x86'
elif e_machine == b'\x08\x00':
return 'MIPS'
elif e_mac... |
def calculate_sum(num1, num2):
"""Returns the sum from number 1 to a number 2"""
result = 0
for n in range(num1, num2 + 1):
result = result + n
return result |
def get_object_attrs(obj):
"""
Get the attributes of an object using dir.
This filters protected attributes
"""
attrs = [k for k in dir(obj) if not k.startswith('__')]
if not attrs:
attrs = dir(obj)
return attrs |
def skip_leader(data, ii):
"""Skips data starting at ii until a non 0x55 char is found. Returns
(new_ii, datai, 0x55)"""
start_ii = ii
while((ii < len(data)) and data[ii] == 0x55):
ii = ii + 1
if (ii >= len(data)):
raise EOFError(
f'Found EOF at index {ii} in the file'... |
def strip_comment(line: str) -> str:
"""Returns the content of a line without '#' and ' ' characters
remove leading '#', but preserve '#' that is part of a tag
example:
>>> '# #hello '.strip('#').strip()
'#hello'
"""
return line.strip('#').strip() |
def end_quote(text):
"""Check for text ending quote"""
return text.endswith("'") or text.endswith('"') |
def gateway_environment(gateway_environment):
"""Enables path routing on gateway"""
gateway_environment.update({"APICAST_PATH_ROUTING": True})
return gateway_environment |
def generate_unique_name(pattern, nameset):
"""Create a unique numbered name from a pattern and a set
Parameters
----------
pattern: basestring
The pattern for the name (to be used with %) that includes one %d
location
nameset: collection
Collection (set or list) of existing names... |
def selected_data(accu, selector):
"""
Returns the selected data.
If the selector function is not None, returns the results of
applying the selector function to accu.
Otherwise returns accu.
:param accu: The data accumulator
:param selector: Optional iterable returning function that has the ... |
def print_wrapper(string, item):
"""A wrapper for log printing for APF/Levy pipeline.
Args:
string (str): The output string for wrapping.
item (:class:`astropy.table.Row`): The log item.
Returns:
str: The color-coded string.
"""
imgtype = item['imgtype']
obj = item... |
def build_attribute_dict(items, attr_name):
"""Build a dict from a list of items and one of their attributes to make
querying the collection easier.
"""
attr_dict = {}
for item in items:
attr_dict[getattr(item, attr_name)] = item
return attr_dict |
def _read_header(file, full_file_path_and_name):
"""Read the header information, returning the meta information."""
# Meta data for data information
meta_data = {
"is_univariate": True,
"is_equally_spaced": True,
"is_equal_length": True,
"has_nans": False,
"has_timest... |
def _prepare_toml(toml_dict):
"""
Prepares the dictionary of the toml, places the channel number as key and conditon name as value
Returns
-------
dict
"""
_d = {}
# Reverse the dict so we can lookup name by channel
for key in toml_dict["conditions"].keys():
channels = toml_d... |
def single_div_toggle_style(mode_val):
"""toggle the layout for single measure"""
if mode_val == "single":
return {"display": "flex", "flex-direction": "column", "alignItems": "center"}
else:
return {"display": "none"} |
def run(_word_list):
"""
Running action stub - causes no change to game state
Args:
_word_list (list): variable-length list of string arguments
Returns:
str: output for REPL confirming player ran in place
"""
response = 'You ran in place. Are you just bored?'
return resp... |
def check_string_type(possible_string):
"""Function to return 1 if the input is a string otherwise raise a TypeError."""
if type(possible_string) is str:
return 1
else:
raise TypeError(f'string not passed - got type {type(possible_string)})') |
def count_letter(content, letter):
"""Count the number of times `letter` appears in `content`.
Args:
content (str): The string to search.
letter (str): The letter to search for.
Returns:
int
# Add a section detailing what errors might be raised
Raises:
ValueError: If `letter` is not a one-c... |
def to_hex(value):
"""
Convert decimal value to hex string.
"""
return " 0x%0.4X" % value |
def createHeaderBinsNumber(number_of_bins:int):
"""
create the header for the dataset with the number of bins
:param number_of_bins: number of bins
:type number_of_bins: int
:return: vec with the labels
:rtype: int
"""
vec_designation = ['interaction_ID']
aux = 0
while aux < ... |
def fib(n):
""" Imperative definition of Fibonacci numbers """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a |
def _write_title(number_of_substances, number_of_properties, number_of_simulations):
"""Write the title page of the latex file.
Parameters
----------
number_of_substances: int
The number of unique substances in the data set.
number_of_properties: int
The number of data points in the... |
def class_hasattr(instance, attr):
"""Helper function for checking if `instance.__class__` has an attribute"""
return hasattr(instance.__class__, attr) |
def rate_color(rate: int, units: str = '') -> str:
"""
Get color schema for percentage value.
Color schema looks like red-yellow-green scale for values 0-50-100.
"""
color = '[red]'
if 30 > rate > 20:
color = '[orange_red1]'
if 50 > rate > 30:
color = '[dark_orange]'
if 7... |
def get_cfn_param(params, key_name):
"""
Get parameter value from Cloudformation Stack Parameters.
:param params: Cloudformation Stack Parameters
:param key_name: Parameter Key
:return: ParameterValue if that parameter exists, otherwise None
"""
param_value = next((i.get("ParameterValue") f... |
def jenkins_final_postprocessing(xml_job, py27):
"""
Postprocesses a job produced by :epkg:`Jenkins`.
@param xml_job :epkg:`xml` definition
@param py27 is it for :epkg:`Python` 27
@return new xml job
"""
if py27:
# options are not allowed
... |
def convert_units(props, conversion_dict):
"""Converts dictionary of properties to the desired units.
Args:
props (dict): dictionary containing the properties of interest.
conversion_dict (dict): constants to convert.
Returns:
props (dict): dictionary with properties converted... |
def _factor2(n):
"""Factorise positive integer n as d*2**i, and return (d, i).
>>> _factor2(768)
(3, 8)
>>> _factor2(18432)
(9, 11)
Private function used internally by ``miller_rabin``.
"""
assert n > 0 and int(n) == n
i = 0
d = n
while 1:
q, r = divmod(d, 2)
... |
def bio_annotate(tokens, entities):
"""Create BIO annotation for tokens and entities.
Args:
tokens (list): sentence split in token strings
entities (dictionary): entity annotation for a given sentence
Returns:
list, list, list: adjusted tokens, token names, bio labels
"""
... |
def adjust_proportion_value_list(proportion_value_list, distributable_value):
"""
Adjust the calculated progress proportion value list to ensure that
sum is equal to distributable_value.
:param proportion_value_list: calculated progress proportion value list
:param distributable_value: number o... |
def func_ab_args(a=2, b=3, *args):
"""func.
Parameters
----------
a, b: int
args: tuple
Returns
-------
a, b: int
args: tuple
"""
return None, None, a, b, args, None, None, None |
def _null_compare(column, value):
"""To reduce cognitive complexity"""
if value[0].lower() in ["y", "t", "1"]:
return column != None # noqa
else:
return column == None |
def is_a_palindrome(num):
"""
Determines if a number is a palindrome.
"""
assert isinstance(num, int)
str_form = str(num)
n_digits = len(str_form)
for k in range(0, (n_digits + 1) // 2):
if str_form[k] != str_form[-1 - k]:
return False
return True |
def get_domains(resolution, frequency, variable_fixed, no_frequencies):
"""Get the domains for the arguments provided.
Args:
resolution (int): Resolution
frequency (str): Frequency
variable_fixed (bool): Is the variable fixed?
no_frequencies (bool): True if no frequencies were p... |
def safe_min(values):
"""Calculate min, but if given an empty list return None."""
values = list(values) # In case this is a complex type, get a simple list.
if not values:
return None
else:
return min(values) |
def format_account_data(account):
"""Format the account details in printable form: name, description and country"""
name = account["name"]
description = account["description"]
Country = account["country"]
# print(f"{name}: {account['follower_count']}")
return f"{name}, a {description} from {Coun... |
def human_to_real(iops):
"""Given a human-readable IOPs string (e.g. 2K, 30M),
return the real number. Will return 0 if the argument has
unexpected form.
"""
digit = iops[:-1]
unit = iops[-1].upper()
if unit.isdigit():
digit = iops
elif digit.isdigit():
digit = int(digit... |
def delete_empty_value_dict(raw_dict: dict):
"""
This function filters all items of raw_dict that has empty value (e.g. null/none/''...)
:param raw_dict: the dict to be filtered
"""
parsed_dict = {key: value for key, value in raw_dict.items() if value}
return parsed_dict if parsed_dict else None |
def get_end_indices(size:int, num_devide:int)->list:
"""
try to equally devide input into num_devide.
"""
assert 1 <= num_devide <= size
parts_sizes = sorted([(size + i) // num_devide for i in range(num_devide)], reverse=True)
end_indices = []
#end_indices.append(parts_sizes[0])
for i ... |
def _truncate(words, cutlength):
"""Group words by stems defined by truncating them at given length.
:param words: Set of words used for analysis
:param cutlength: Words are stemmed by cutting at this length.
:type words: set(str) or list(str)
:type cutlength: int
:return: Dictionary whe... |
def count_distribution_artefacts(distribution_artefacts):
"""
Count distribution artefacts in nested list.
:param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants
:type distribution_artefacts: dict
:return: Amount of distribution artefacts
... |
def apply_rot_to_vec(rot, vec, unstack=False):
"""Multiply rotation matrix by a vector."""
if unstack:
x, y, z = vec[:, 0], vec[:, 1], vec[:, 2]
else:
x, y, z = vec
return [rot[0][0] * x + rot[0][1] * y + rot[0][2] * z,
rot[1][0] * x + rot[1][1] * y + rot[1][2] * z,
... |
def _isSet(theme, keys):
"""
Given a theme dict, recursively check that all the keys are populated
and that the associated value is truthy
"""
obj = theme
for key in keys:
if not obj or key not in obj:
return False
obj = obj[key]
return bool(obj) |
def findMissing(aList, aListMissingOne):
"""
Ex)
Given aList := [4,12,9,5,6] and aListMissingOne := [4,9,12,6]
Find the missing element
Return 5
IDEA:
Brute force! Examine all tuples.
Time: O(n*m) and Space: O(1)
Smarter: Use a hashMap, instead!
Time: O(n+m) an... |
def remove_extension(template):
"""
Given a filename or path of a template file, return the same without the
template suffix.
:param unicode template: The filename of or path to a template file which
ends with '.template'.
:return: The given filename or path without the '.template' suffix.
... |
def extract_wall_items(user: str, json_handle: dict):
"""
Function to convert JSON data for one user to a simple list.
:param user: VK user id, as mentioned in the JSON file, as string
:param json_handle: handle to JSON data
:return: List of dictionaries, each dictionary has text of post, number
... |
def is_prime(number):
""" Returns whether the given number is prime """
if number <= 1 or not number % 2:
return False
return all(number % num for num in range(3, int(number**0.5) + 1, 2)) |
def _normalize_method_name(cpp_type_name, cpp_method_name):
# type: (str, str) -> str
"""Normalize the method name to be fully-qualified with the type name."""
# Default deserializer
if not cpp_method_name:
return cpp_method_name
# Global function
if cpp_method_name.startswith('::'):
... |
def location_normalize(location):
"""
Normalize location name `location`
"""
#translation_table = dict.fromkeys(map(ord, '!@#$*;'), None)
def _remove_chars(chars, string):
return ''.join(x for x in string if x not in chars)
location = location.lower().replace('_', ' ').replace('+', ' ')... |
def figure_linguistic_type(labels):
"""
Gets linguistic type for labels
Parameters
----------
labels : list of lists
the labels of a tier
Returns
-------
the linguistic type
"""
if len(labels) == 0:
return None
elif len(labels) == 1:
return lab... |
def comma_delimited_to_list(list_param):
"""Convert comma-delimited list / string into a list of strings
:param list_param: Comma-delimited string
:type list_param: str | unicode
:return: A list of strings
:rtype: list
"""
if isinstance(list_param, list):
return list_param
if is... |
def add_python_extension_if_not_there(arg_string: str) -> str:
"""
>>> # Setup
>>> arg_string_with_py = __file__
>>> arg_string_without_py = __file__.rsplit('.py',1)[0]
>>> # Test with and without .py suffix
>>> assert add_python_extension_if_not_there(arg_string_with_py) == __file__
>>> as... |
def compute_primes(bound):
"""
Return a list of the prime numbers in range(2, bound)
"""
answer = list(range(2, bound))
for divisor in range(2, bound):
for i in answer:
if i % divisor == 0 and not i == divisor:
answer.remove(i)
return answer |
def feature_transform(
features,
single_elem_transform,
is_next_with_multi_steps=False,
replace_when_terminal=None,
terminal=None,
):
"""feature_transform is a method on a single row.
We assume features is List[features] (batch of features).
This can also be called for next_features with... |
def truncate(text, width=80):
"""
Return text truncate to given width with ellipsis if other length.
The builting textwrap.shortern does not work here if the value is a single
long word (e.g. a URL) as the entire URL is replaced with '[...]'.
https://stackoverflow.com/questions/2872512/python-trun... |
def check_diag(grid,row,col):
"""Returns true if the diagonal of the current cell is in win condition.
Counts the occurences of the cell's player's marker and if it is equal
to the size of the grid, the player has won.
Checks in which diagonal the cell is, and then counts occurences in
this diagon... |
def counts_compute(dataset):
"""
Input: $dataset, a list of lists [[]].
refer to last column as sensitive attribute (SA),
and refer for other columns as quasi-identifier attributes (QI)
For every pair (val_q, val_s) compute the related count: the number of
records (rows) that contains this ... |
def localize(value, locale):
""" Return the value appropriate for the current locale.
This is used to retrieve the appropriate localized version of a value
defined within a unit's dictionary.
If 'value' is a dictionary, we assume it is a mapping of locale names
to values, so we sel... |
def eval_condition(condition, locals):
"""Evaluates the condition, if a given variable used in the condition
isn't present, it defaults it to None
"""
import ast
condition_variables = set()
st = ast.parse(condition)
for node in ast.walk(st):
if type(node) is ast.Name:
con... |
def remote_url(url):
"""return full remote URL or None if local file"""
if url.startswith('//'):
return 'https:' + url
elif url.startswith('http://') or url.startswith('https://'):
return url |
def keep_or_del_elem(obj, elem_name_list, keep=False):
"""
keep/delete elem from input objectes
"""
del_elem_list = []
for i, n in enumerate(obj):
if (n.name in elem_name_list and not keep) or (n.name not in elem_name_list and keep):
del_elem_list.append(i)
#print("del elem ... |
def mode(is_append: bool):
"""Write mode dependend on is_append."""
return "a" if is_append else "w" |
def lucas(n):
"""Generate the nth instance of the lucas
"""
number1 = 1
number2 = 2
nth = 1
if type(n) is not int:
raise TypeError('Please enter a number')
if n == 0:
return 2
if n == 1:
return 1
for count in range(2, n + 1):
nth = number1 + number2
... |
def copy_as_new(dictionary, fields):
"""
Copies the dictionary to a new one. Copies only the fields specified.
:param dictionary:
:param fields:
:return:
"""
out = {}
for f in fields:
out[f] = dictionary[f]
return out |
def format_sizeof(num, suffix="B"):
"""
Print in human friendly format
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Yi", suffix) |
def col_list(nn):
"""
Get names for the columns containing Trace value and Signal intensity value
for a given nearest number of bases, from the dataframe returned by trace_df
Parameters
----------
nn : int for number of nearest neighbours
Returns
-------
list : list containing colu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.