content stringlengths 42 6.51k |
|---|
def get_value(rgb, animated=False):
"""
Obtains pixel value if it is enabled. Color is not supported yet here.
:param rgb:
:param animated: It is a WTF from SP1. If I do animation it requires me to invert the values...
:return:
"""
if rgb[0] > 0 or rgb[1] > 0 or rgb[2] > 0:
return "... |
def first_and_last(sequence):
"""returns the first and last elements of a sequence"""
return sequence[0], sequence[-1] |
def tick_labels(cbar_ticks: list) -> list:
"""Convert to the string in appropriate format according to the value of
the ticks for color bar.
:param cbar_ticks: class:list, the list of the ticks in color bar.
:type cbar_ticks: list
:return: the list of string which is prepared to plot in color bar.
... |
def cyclic(graph):
"""
Return True if the directed graph has a cycle.
The graph must be represented as a dictionary mapping vertices to
iterables of neighbouring vertices. For example:
>>> cyclic({1: (2,), 2: (3,), 3: (1,)})
True
>>> cyclic({1: (2,), 2: (3,), 3: (4,)})
False
"""
... |
def squeeze(xs):
"""Squeeze a sequence if it only contains a single element.
Args:
xs (sequence): Sequence to squeeze.
Returns:
object: `xs[0]` if `xs` consists of a single element and `xs` otherwise.
"""
return xs[0] if len(xs) == 1 else xs |
def get_file_line_numbers_with_enclosing_tags(
file, start_tag, end_tag, start_from=1, encoding="utf-8"
):
"""
Get file line numbers that has start enclosing tag and end enclosing tags.
Using a simple parser algorithm this function search for the enclosing tags and return the start and end line numbers... |
def format_yaml(template, config):
"""Replace in ${ENV_VAR} in template with value"""
formatted = template
for k, v in config.items():
formatted = formatted.replace('${%s}' % k, v)
return formatted |
def generate_importer_base_name(dependent_task_name: str,
input_name: str) -> str:
"""Generates the base name of an importer node.
The base name is formed by connecting the dependent task name and the input
artifact name. It's used to form task name, component ref, and executor la... |
def get_indent_level(line):
""" Counts number of tabs ( "\t" ) at the beginning of the line. """
level = 0
for c in line:
if c == "\t":
level += 1
else:
break
return level |
def get_file_lines_of_code(repo, tree, dfile):
"""
Count how many lines of code there are in a file.
"""
tloc = 0
try:
blob = repo[tree[dfile.path].id]
tloc = len(str(blob.data).split('\\n'))
except Exception as _:
return tloc
return tloc |
def k_largest_elements(lst, k):
""" Sort the list - partially, using bubblesort and inplace element exchange"""
# Edge case: length of the list < k
if (len(lst) < k):
# if those elements can be unsorted.
#return lst
# Otherwise:
k = len(lst)
# Get 3 elements using bubbl... |
def tupleMatch(a, b):
"""Part of partial ordered matching.
See http://stackoverflow.com/a/4559604
"""
return len(a) == len(b) and all(
i is None or j is None or i == j for i, j in zip(a, b)
) |
def create_bin_edges(window_start, window_width, window_name):
"""
create_bin_edges
returns two lists:
bin_edges = [(left_0, right_0), ..., (left_N, right_N)]
bin_ids = [(window_name, 0), ..., (window_name, N)]
where
right_i - left_i == window_width
Parameters
----------... |
def ret_true(obj):
"""
Returns "True" if an object is there. E.g. if given a list, will return
True if the list contains some data, but False if the list is empty.
:param obj: Some object (e.g. list)
:return: True if something is there, else False.
"""
if obj:
return True
e... |
def BigIntToBytes(n):
"""Return a big-endian byte string representation of an arbitrary length n."""
array = []
while (n > 0):
array.append(n % 256)
n = n >> 8
array.reverse()
barray = bytearray(array)
if barray[0] & 0x80:
return b'\x00' + bytes(barray)
return bytes(barray) |
def wind_speed(u, v, w):
"""Calculate the magnitude of the wind speed
Args:
u,v,w (iris.cube.Cube or numpy.ndarray): Components of the wind speed
Returns:
Wind Speed (Same type as inputs)
"""
return (u**2 + v**2 + w**2)**0.5 |
def getNearestDistanceToEntity(entitylocationList, currentPosition):
"""
This method returns the minimum distance to entity from the current pacman position to any entity.
:param entitylocationList: Gives the location of entities as a list to which we need to calculate the nearest
distance.
:type Li... |
def isDM(channel_id):
"""Helper to check if a channel ID is for a DM"""
return channel_id.startswith("D") |
def get_value(node, key):
""" """
value = node.get(key)
if value == None:
try:
value = node.find(key).text
except AttributeError:
pass
return value |
def evaluate_g6( kappa, nu, eta, tau, sigma, l, mu, s6 ):
"""
Evaluate the sixth constraint equation and also return the jacobians
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float eta: The value of the modulus eta
:param float tau:... |
def ip_env_var(site, destination, node_type):
"""Form the environment variable name from the function arguments"""
return f'{destination.upper()}_{site.upper()}_ELASTIC_{"VOTER_" if node_type == "voter" else ""}IP' |
def build_url(label):
""" Build a url from the label, a base, and an end. """
#clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
list = label.split('|')
url = list[0]
if len(list) == 1:
url = label
else:
label = list[1]
return (url, label) |
def busca_sequencial (seq, x):
""" (list, float) -> bool """
for indice in range(len(seq)):
if seq[indice] == x:
return True
return False |
def slope(A, B):
""" calculate the slope between two points """
return (A[1] - B[1]) / (A[0] - B[0]); |
def dim0(s):
"""Dimension of the slice list for dimension 0."""
return s[0].stop-s[0].start |
def _itemsToList(itemDict):
""" Convert dict of (item-id: quantity) pairs back to pyKol-style list. """
return [{'id': iid, 'quantity': qty} for iid,qty in itemDict.items()] |
def cobb_douglas_mpk(k, alpha, **params):
"""Marginal product of capital with Cobb-Douglas production."""
return alpha * k**(alpha - 1) |
def url_mapping(url):
"""
Map input URLs to output URLs for the staging test
"""
mapping = {'http://almascience.eso.org/rh/submission':
'http://almascience.eso.org/rh/submission/d45d0552-8479-4482-9833-fecdef3f8b90/submission',
'http://almascience.eso.org/rh/submission/d45d... |
def flatten_results(results: dict, derivation_config: dict) -> dict:
"""Flatten and simplify the results dict into <metric>:<result> format.
Args:
results (dict): The benchmark results dict, containing all info duch as
reduction types too
derivation_config (dict): The configuration ... |
def compFirstFivePowOf2(iset={0, 1, 2, 3, 4}):
"""
task 0.5.6
a comprehension over the given set whose value is the set consisting
of the first five powers of two, starting with 2**0
"""
return {2**x for x in iset} |
def java_step_properties(jar, main_class, arguments=None):
"""
Create java step properties
:param jar: the path of .jar file
:type jar: string
:param main_class: the package path for main class
:type main_class: string
:param arguments: arguments for the step
:type arguments: string
... |
def xor(a, b):
"""
xor two byte sequences
"""
if len(a) != len(b):
raise ValueError('a and b must be the same length')
return bytes(x ^ y for x, y in zip(a, b)) |
def blend(a, scale, b):
"""
Returns a color that's 'scale' of the way between 'a' and 'b'.
(Interpolates RGB space; very simple)
"""
ar,ag,ab = a
br,bg,bb = b
return (min(255, max(0, br- (br-ar)*(1-scale))),
min(255, max(0, bg- (bg-ag)*(1-scale))),
min(255, max(0, bb-... |
def file_size_human(size_in_B: int, verbose: bool = True):
"""
Only displays either in MB or B. Gotta update this (probably)
"""
size_in_MiB: float = (size_in_B/1024)/1024
if size_in_MiB < 1:
size_in_MiB_str = "<1 MB"
else:
size_in_MiB_str = f"{int(size_in_MiB+1)} MB"
if verb... |
def loosewwid(wwid):
"""Validity checks WWID for invalid format using loose rules - any hex values used:"""
hexstring = ""
for userchar in wwid: # Get each character in the input and isolate hex characters
userchar = userchar.lower() # For consistency convert to lower case
# Only ... |
def _normalize_slice_idx_count(arg, slice_len, default):
"""
Used for unicode_count
If arg < -slice_len, returns 0 (prevents circle)
If arg is within slice, e.g -slice_len <= arg < slice_len
returns its real index via arg % slice_len
If arg > slice_len, returns arg (in this case count must
... |
def do_lower(s):
"""
Convert a value to lowercase.
"""
return s.lower() |
def int_pow(x: float, exponent: float) -> int:
"""Finds the nearest integer to ``pow(x, exponent)``.
Args:
x: The number whose power will be found.
exponent: The number to which ``x`` will be raised.
Returns:
The result of rounding ``pow(x, exponent)`` to the nearest integer.
"... |
def _find_crack_comment(text):
"""
We are NOT in a comment. Return a ref to any code found, a ref to the
rest of the text, and the value of inComment.
"""
posn_old = text.find('/*') # multi-line comment
posn_new = text.find('//') # one-line comment
posn_sharp = text.find('#') ... |
def xgcd(a,b):
"""xgcd(a,b) returns a tuple of form (g,x,y), where g is gcd(a,b) and
x,y satisfy the equation g = ax + by."""
a1=1; b1=0; a2=0; b2=1; aneg=1; bneg=1
if(a < 0):
a = -a; aneg=-1
if(b < 0):
b = -b; bneg=-1
while (1):
quot = -(a // b)
a = a % b
a1 = a1 + quot*a2; b1 = b1 + quot*b2
if(a == ... |
def sanitize_link(link):
"""make correction so link is proper"""
if link.lower().startswith("http"):
return link
if link.startswith("#"):
return "/" + link
if not link.startswith("/"):
return "/" + link
return link |
def lyrics_to_frequencies(l):
""" Assumes l is a list with strings
Takes each string and checks if it exists as a key in the dict
If it does - it increases the value of that key by 1
If it doesn't - it creates the key with value 1
Parameters
----------
l : list
l... |
def avg(data):
"""Get the average of a list"""
return sum(data) / len(data) |
def get_planet_name(id):
""" This function returns planet`s name by id. """
planet = {1: 'Mercury',
2: 'Venus',
3: 'Earth',
4: 'Mars',
5: 'Jupiter',
6: 'Saturn',
7: 'Uranus',
8: 'Neptune'}
for key, val in plane... |
def get_network_title(network):
"""Returns the title of a network given a network
JSON as a dict
"""
cur_country = network['country_cur']
cur_region = network['region_cur']
cur_city = network['city_cur']
orig_country = network['country_origin']
orig_region = network['region_origin']
... |
def _get_library_name_from_artifact_name(artifact_name: str) -> str:
"""Reconstruct the library name, from the name of an artifact containing it."""
parts = []
for part in artifact_name.split("-"):
if part[0].isdigit():
break
parts.append(part)
return "-".join(parts) |
def get_accessory_name(accessory_info):
"""Return the name field of an accessory."""
for field in ("name", "model", "manufacturer"):
if field in accessory_info:
return accessory_info[field]
return None |
def _stringify_object(obj):
"""Try to stringify a object."""
return obj.id if hasattr(obj, 'id') else obj |
def get_gpus(env, gpu_list):
"""Gets GPU IDs given the GPU UUIDs.
:param list env: Container environment variables.
:param list gpu_list: List of GPUs from GPUtil.
:return: List of GPU IDs.
:rtype: list
"""
used_ids = []
uuids = []
for var in env:
if 'NVIDIA_VISIBLE_DEVICES... |
def compose_user_full_name(username, first_name, last_name):
"""
Return user's full name representation for the views.
Needed because of unrequired first and last names.
"""
name = (first_name or last_name) and ' '.join((first_name, last_name))
return '{} ({})'.format(name, username) if name el... |
def _prt_mode_from_unfolding(unfolding):
""" Return 'fixed' or 'staggered' depending on unfolding flag """
if unfolding == 0:
return 'fixed'
else:
return 'staggered' |
def in_size_range(lines, min_length=20, max_length=20):
"""
return lines whose size is within the given range
"""
return [line for line in lines if len(line) > min_length and len(line) < max_length] |
def enable_tabs_when_data_is_loaded(data, meta):
"""Hide tabs when data are not loaded"""
default = "Current Location: N/A"
if data is None:
return (
True,
True,
True,
True,
True,
True,
True,
default,
... |
def check_dimension(in_value):
""" Convert common dimension names to a preset value."""
if in_value in ('t', 'time', 'temporal'):
out_value = 'time'
elif in_value in ('s', 'band', 'bands', 'spectral'):
out_value = 'bands'
else:
out_value = in_value
return out_value |
def LoadPathmap(pathmap_path):
"""Load the pathmap of obfuscated resource paths.
Returns: A dict mapping from obfuscated paths to original paths or an
empty dict if passed a None |pathmap_path|.
"""
if pathmap_path is None:
return {}
pathmap = {}
with open(pathmap_path, 'r') as f:
for l... |
def find_kmers(seq, k):
""" Find k-mers in string """
n = len(seq) - k + 1
return [] if n < 1 else [seq[i:i + k] for i in range(n)] |
def example_keys_response(kid, rsa_public_key):
"""
Return an example response JSON returned from the ``/jwt/keys`` endpoint in
fence.
"""
return {"keys": [[kid, rsa_public_key]]} |
def validate_watch(value):
"""Validate "watch" parameter."""
if not value:
return None
if isinstance(value, str):
value = [_ for _ in value.split("\n") if _]
return value |
def expect_result_metadata(query_str):
""" Given a query string, return True if impalad expects result metadata"""
excluded_query_types = ['use', 'alter', 'drop', 'create', 'insert']
if True in set(map(query_str.startswith, excluded_query_types)):
return False
return True |
def factorial(num: int) -> int:
"""
>>> factorial(7)
5040
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: Number should not be negative.
>>> [factorial(i) for i in range(10)]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
"""
if num < 0:
raise ... |
def is_int(s):
"""
check if s is of type int
:param s: value to check
:return: return true if s is int
"""
try:
int(s)
return True
except ValueError:
return False |
def write(file, lines):
""" Write file from an array """
with open(file, 'w') as f:
bytes_ = f.write('\n'.join(lines[0:]) + '\n')
return bytes_ |
def taxicab_distance(a, b):
"""Calculate Manhattan distance
>>> taxicab_distance((0, 0), (0, 0))
0
>>> taxicab_distance((0, 0), (1, 1))
2
>>> taxicab_distance((-1, -1), (-4, -3))
5
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
def str_to_obj(string):
"""
Convert the string representation of a number to a number if required.
"""
try:
return float(string)
except ValueError:
return string |
def _get_location_start(data_type: str) -> str:
"""Translates data type to beginning of location code"""
if data_type == "variation":
return "R"
elif data_type == "adjusted":
return "A"
elif data_type == "quasi-definitive":
return "Q"
elif data_type == "definitive":
r... |
def parse_argument_list(cli_arg, type_fun=None, value_separator=','):
"""
Split the command-line argument into a list of items of given type.
Parameters
----------
cli_arg : str
type_fun : function
A function to be called on each substring of `cli_arg`; default: str.
value_separator... |
def match_code(code:str, raw_line:bytes)->bool:
"""returns True if code is met at the beginning of the line."""
line = raw_line.decode("ascii")
return line.startswith(code + " ") or line.startswith(code + ";") |
def count_property_range_hits(prop, node_dict, hits):
""" picks which values to use in tuples based on property
counts vals having min_val <= val < max_val
unless max_val == overall_max, where min_val <= val <= max_val
is used instead
"""
res = []
# sets tuple position to use in dict value
switcher = {
... |
def add_suffix(string, suffix):
"""
Adds a suffix to a string, if the string does not already have that suffix.
:param string: the string that should have a suffix added to it
:param suffix: the suffix to be added to the string
:return: the string with the suffix added, if it does not already end i... |
def split_dict(data, filter_keys=None): # flake8: noqa
"""Deep extract matching keys into separate dict.
Extracted data is placed into another dict. The function returns two dicts;
one without the filtered data and one with only the filtered data. The
dicts are structured so that they can be recombine... |
def slugify(name: str) -> str:
"""Slugify function for player names from DDNet
https://github.com/ddnet/ddnet-scripts/blob/203fcb4241261ae8f006362303723e4546e0e7f7/servers/scripts/ddnet.py#L167
:type name: str
:return:
"""
x = '[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+'
string = ""
for c... |
def are_all_values_the_same(dictionary_to_evaluate, keys_of_interest=(0, 1)):
"""
Work out whether all values in a dictionary have the same value over a range of integer-valued keyed. If the key is
absent from the dictionary or the key isn't an integer, it doesn't matter and the loop continues.
Args:
... |
def update(d, u):
"""Deepmerge 2 dicts."""
if not isinstance(d, dict):
return u
for k, v in u.items():
if isinstance(v, dict):
d[k] = update(d.get(k, {}), v)
else:
d[k] = v
return d |
def must_apply(elem, type):
""" Return True if the 'applied' attribute is not already true. """
if elem is None:
return False
if 'applied' in elem.attrib:
if elem.attrib['applied'].lower() == 'true':
print('Skipping', type, 'Transform that was already applied')
retur... |
def generateDeltaArray(input_arr):
"""generates delta array for given array
e.g. [4,12,15,22] -> [4,8,3,7]
"""
input_len = len(input_arr)
assert input_len > 0, 'Empty array is given'
deltas = [None] * input_len
deltas[0] = input_arr[0]
idx = 1
while idx < input_len:
deltas[idx] = input_arr[idx]-in... |
def read_file(path):
"""
Args: path: path to read file
Return: array with the lines of the file
"""
with open(path, 'r') as f:
lines = f.readlines()
return lines |
def fitness (password, test_word):
"""
fitness is number of correct chars divided by the total number of the chars
in the password
"""
if len(test_word) != len(password):
print('words must be equal length!')
return
else:
score = 0
i = 0
while i < len(passw... |
def round_to_text(value, rounding_precision):
"""
A simple method that formats values to nicestrings
:param value: the value to format
:param rounding_precision: the required rounding precision
:return:
"""
return '{:.2f}'.format(round(value, rounding_precision)) |
def _num_arg(val):
"""Try to cast the given value to an integer of float if it is a string."""
if isinstance(val, (int, float)):
return val
if isinstance(val, str):
if val.isdecimal():
return int(val)
return float(val)
raise ValueError("can't coerce value to a numbe... |
def find_E0(b,a,Ep):
"""returns the value of E0 for
a log_par+pl distribution
Args:
b: curvature
a: spectral index in the PL branch
Ep: peak value
Returns:
"""
if (b!=0.0):
c=(3-a)/(-2*b)
print ("Ep=",Ep)
return Ep/(pow(... |
def mat_like_array(start, end, step=1):
"""
Generate a matlab-like array start:end
Subtract 1 from start to account for 0-indexing
"""
return list(range(start-1, end, step)) |
def getNodeListText(nodelist):
"""
Return concatenation of text values from a supplied list of nodes
"""
rc = u""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc |
def dominates(comm1, comm2, profile):
"""Test whether a committee comm1 dominates another committee comm2. That is, test whether
each voter in the profile has at least as many approved candidates in comm1 as in comm2,
and there is at least one voter with strictly more approved candidates in comm1.
Para... |
def isFloat(string):
""" Return a true is string is convertable to a float, otherwise false.
"""
try:
float(string)
return True
except ValueError:
return False |
def set_values(value, rounding_value):
"""
Rounding may lead to values not being the right length when converted to strings. This formats them
:param value: Value to turn into a string
:type value: float | int
:param rounding_value: Rounding value target
:type rounding_value: int
:return:... |
def find_matching_endif(blocks, i):
"""Traverse the blocks to find out the matching #endif."""
n = len(blocks)
depth = 1
while i < n:
if blocks[i].isDirective():
dir_ = blocks[i].directive
if dir_ in ["if", "ifndef", "ifdef"]:
depth += 1
elif d... |
def get_pfam_of_user_entity_ids(cursor, unification_table, user_entity_ids):
"""
Get PFAM IDs of targets using their BIANA user entity ids
"""
query_pfam = ("""SELECT PF.value, PF.type
FROM externalEntityPFAM PF, {} U
WHERE U.externalEntityID = PF.externalEntit... |
def salutation(name):
"""Say hello to someone."""
return f"Hello, {name}!" |
def ts_path(path):
"""Make a URL path with a database and test suite embedded in them."""
return "/api/db_<string:db>/v4/<string:ts>/" + path |
def safe_getattr(obj, name, *defargs):
"""A getattr() that turns all exceptions into AttributeErrors."""
try:
return getattr(obj, name, *defargs)
except Exception:
# this is a catch-all for all the weird things that some modules do
# with attribute access
if defargs:
... |
def _get_normalized_vm_statuses(vm_iv):
"""Iterate over a list of virtual machine statuses and normalize them.
Arguments:
vm_iv (dict): Raw virtual machine instance view record.
Returns:
dict: Normalized virtual machine statuses
"""
normalized_statuses = {}
for s in vm_iv.get(... |
def kubectl_cmd(kubeconfig):
"""Builds the kubectl command to communicate with the cluster that can be reached by
the provided kubeconfig file.
Args:
kubeconfig (str): path to the kubeconfig file.
Returns:
str: the base kubectl command to use for communicating with the cluster.
""... |
def box(text: str, lang: str = "") -> str:
"""Get the given text in a code block.
Parameters
----------
text : str
The text to be marked up.
lang : `str`, optional
The syntax highlighting language for the codeblock.
Returns
-------
str
The marked up tex... |
def _parse_total_magnetization(line, lines):
"""Parse the total magnetization, which is somewhat hidden"""
toks = line.split()
res = {"number of electrons": float(toks[3])}
if len(toks) > 5:
res["total magnetization"] = float(toks[5])
return res |
def _read(f) -> bytes:
"""
Reads in the content of the file.
:param f: the file to read
:type f: str
:return: the content
:rtype: str
"""
return open(f, 'rb').read() |
def parse_flags(flags, flags_dict, show_unknown_flags=True, separator=" "):
"""
Parses an integer representing a set of flags. The known flags are
stored with their bit-mask in a dictionnary. Returns a string.
"""
flags_list = []
mask = 0x01
while mask <= flags:
if flags & mask:
... |
def bytes_istitle(x: bytes) -> bool:
"""Checks if given bytes object contains only titlecase elements.
Compiling bytes.istitle compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of chec... |
def roundup_10(x):
"""
Project: 'ICOS Carbon Portal'
Created: Tue May 07 10:30:00 2018
Last Changed: Tue May 07 10:30:00 2019
Version: 1.0.0
Author(s): Karolina
Description: Function that takes a number as input and
ro... |
def __has_colors(stream, allow_piping=False):
"""Check if Console Has Color."""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty(): # not being piped or redirected
return allow_piping # auto color only on TTYs
try:
import curses
curses.setupterm()
... |
def get_url(key, **kwargs):
"""Get and format the url for the given key.
"""
urls = {
'jobs': u'/jobs/', # POST -> Submit Job
'paginate jobs': u'/jobs/paginate', # GET -> paginate jobs
'job update': u'/jobs/{uuid}', # GET -> result; DELETE -> abort
'job delete': u'/jobs/{u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.