content stringlengths 42 6.51k |
|---|
def memoized_triple_step(step):
"""Find number of step combinations for maximum of three steps at a time
:param step Number of steps left
:return Number of step combinations
"""
if step < 0:
return 0
elif step == 0:
return 1
return memoized_triple_step(step - 3) + \
memoized_triple_step(step - 2) + \
memoized_triple_step(step - 1) |
def obs_color_hsluv(obs, subobs):
"""
Return a nice color for the given observable in HSLuv space.
Use obs_color() to obtain an RGB color.
"""
if obs in {'dNch_deta', 'pT_fluct'}:
return 250, 90, 55
if obs == 'dET_deta':
return 10, 65, 55
if obs in {'dN_dy', 'mean_pT'}:
return dict(
pion=(210, 85, 70),
kaon=(130, 88, 68),
proton=(30, 90, 62),
)[subobs]
if obs == 'vnk':
return {
(2, 2): (230, 90, 65),
(2, 4): (262, 80, 63),
(3, 2): (150, 90, 67),
(4, 2): (310, 70, 50),
}[subobs]
raise ValueError('unknown observable: {} {}'.format(obs, subobs)) |
def formatting_time(float_time):
"""
Computes the estimated time as a formatted string as well
"""
if float_time > 3600: time_str = '{:.2f}h'.format(float_time / 3600);
elif float_time > 60: time_str = '{:.2f}m'.format(float_time / 60);
else: time_str = '{:.2f}s'.format(float_time);
return time_str |
def grid(grid_width=None,
grid_height=None,
grid_top=None,
grid_bottom=None,
grid_left=None,
grid_right=None,
**kwargs):
"""
:param series:
other chart series data
:param grid_width:
Width of grid component. Adaptive by default.
:param grid_height:
Height of grid component. Adaptive by default.
:param grid_top:
Distance between grid component and the top side of the container.
grid_top value can be instant pixel value like 20;
it can also be percentage value relative to container width like '20%';
and it can also be 'top', 'middle', or 'bottom'.
If the grid_top value is set to be 'top', 'middle', or 'bottom',
then the component will be aligned automatically based on position.
:param grid_bottom:
Distance between grid component and the bottom side of the container.
grid_bottom value can be instant pixel value like 20;
it can also be percentage value relative to container width like '20%'.
:param grid_left:
Distance between grid component and the left side of the container.
grid_left value can be instant pixel value like 20;
it can also be percentage value relative to container width like '20%';
and it can also be 'left', 'center', or 'right'.
If the grid_left value is set to be 'left', 'center', or 'right',
then the component will be aligned automatically based on position.
:param grid_right:
Distance between grid component and the right side of the container.
grid_right value can be instant pixel value like 20;
it can also be percentage value relative to container width like '20%'.
:return:
"""
_grid = {}
if grid_width is not None:
_grid.update(width=grid_width)
if grid_height is not None:
_grid.update(height=grid_height)
if grid_top is not None:
_grid.update(top=grid_top)
if grid_bottom is not None:
_grid.update(bottom=grid_bottom)
if grid_left is not None:
_grid.update(left=grid_left)
if grid_right is not None:
_grid.update(right=grid_right)
return _grid |
def decorate(string, *formats):
"""Decorates a string using ANSI escape codes given some format enums.
Calling len(s) on a string which has been decorated in this manner will not
return the printed width. Call len(ansi_undecorate(s)) to achieve this.
Args:
string: string to decorate.
formats: any number of format enums to apply to the string.
Returns:
Decorated representation of string.
"""
# If no formats have been given, do nothing
if not formats:
return string
# Otherwise construct the start code
start = '\033['
for fmt in formats:
start += str(fmt) + ';'
# Remove final ';', append an 'm'
start = start[:-1] + 'm'
# Hard coded reset code to finish
end = '\033[0m'
return start + string + end |
def to_terminal_node(group):
"""Creates a terminal node value comprising of all instances present in the given group
Returns:
the majority label, i.e., the label used to classify the biggest amount of instances in the group
"""
# get the label of each instance in the group
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count) |
def debatch(data):
"""
convert batch size 1 to None
"""
for key in data:
if isinstance(data[key], list):
assert len(data[key]) == 1, "can't debatch with batch size greater than 1"
data[key] = data[key][0]
return data |
def all_equal(lst):
"""Returns true if all items in the list are equal."""
return len(set(lst)) == 1 |
def snake_distance(a, b):
"""
Calculate the Manhattan distance of two vectors.
"""
distance = 0
for x, y in zip(a, b):
distance += (x - y)
return distance |
def generate_ascending_descending(power):
"""
Generates lists that have ascending and descending elements
:param power: power of 2
:return: generated lists
"""
ascending = []
for i in range(2 ** power):
ascending.append(i)
descending = ascending[::-1]
return ascending, descending |
def orderlex(l1, l2, n1, n2):
""" lexicographic order on infinite words, returns :
0 if the n1-th shift of l1^infty is smaller than the n2-th shift of l2^infty, 1 if it is larger, and 2 if the two words coincide
(this can be determined by looking only length(l1)+length(l2) letters since u^infty = v^infty iff uv = vu).
"""
i = 0
while( (l1[(i+n1)%len(l1)] == l2[(i+n2)%len(l2)]) & (i <= (len(l1)+len(l2))) ):
i = i+1
if l1[(i+n1)%len(l1)] < l2[(i+n2)%len(l2)]:
return 0
else:
if l1[(i+n1)%len(l1)] > l2[(i+n2)%len(l2)]:
return 1
else:
return 2 |
def password_check(passwd):
"""
Taken from geeksforgeeks.org/password-validation-in-python/
This method is used to restrict password for registration process.
:param passwd:
:return:
"""
SpecialSym = ['$', '@', '#', '%', '.', ',']
val = True
if len(passwd) < 6:
print('length should be at least 6')
val = False
if len(passwd) > 20:
print('length should be not be greater than 20')
val = False
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in passwd):
print('Password should have at least one of the symbols $@#')
val = False
if val:
return val |
def code(value: int) -> str:
"""Constructs an ANSI code with the provided `value`."""
return f'\033[{value}m' |
def count_to_read(link_counters):
"""Find the to_read count in the counters returned by a CommunicationLink."""
for processor in link_counters.values():
if 'to_read' in processor:
return processor['to_read'] |
def get_related_topics(section_div):
"""Get topics related to the current topic.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
Returns
-------
Str:
The related topics in the format expected by the fathead.
"""
related_topics = []
try:
seealso_div = section_div.find("div",
attrs={"class": "admonition seealso"})
seealso_p = seealso_div.find("p", attrs={"class": "last"})
related_topics_a = seealso_p.find_all("a")
for topic in related_topics_a:
related_topics.append("[[" + topic["title"] + "]]")
except AttributeError:
pass
return "\\\\n".join(related_topics) |
def uri_to_entity_code(uri: str) -> str:
"""Translates URIs such as http://lcsb.uni.lu/biokb/entities/BTO_0001043 to BTO:0001043
Replaces only the first underscore with colon.
Arguments:
uri {str} -- [description]
Returns:
str -- [description]
"""
return uri.split('/')[-1].replace('_', ':', 1) |
def dct_reduce(reduce_fn, dcts):
"""Similar to `reduce`, but applies reduce_fn to fields of dicts with the
same name.
>>> dct_reduce(sum, [{"a": 1}, {"a": 2}])
{'a': 3}
"""
keys = dcts[0].keys()
return {key: reduce_fn([item[key] for item in dcts]) for key in keys} |
def _get_post_processing(params: dict) -> dict:
"""
Extract and set defaults for the post processing options
"""
pp = params.get('post_processing', {})
# ids_only - shortcut to mark both skips as true and include_highlight as false.
if pp.get('ids_only') == 1:
pp['include_highlight'] = 0
pp['skip_info'] = 1
pp['skip_data'] = 1
return pp |
def get_party_leads_sql_string_for_state(party_id, state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_votes-sr.votes) as lead,
sr.candidate_id,
loosing_candidate.fullname as runner_up,
loosing_party.name as runner_up_party,
sr.party_id,
ltr.party_id
from latest_results lr
inner join
latest_runners_up as sr
on
sr.constituency_id = lr.constituency_id
inner join
candidate c
on
c.id = lr.candidate_id
inner join
constituency cons
on
cons.id = lr.constituency_id
inner join party loosing_party
on
loosing_party.id = sr.party_id
inner join candidate loosing_candidate
on
loosing_candidate.id = sr.candidate_id
inner join last_time_winners ltr
on
ltr.constituency_id=lr.constituency_id
where
lr.party_id = %s
and
cons.state_id = %s
and
lr.status = 'COUNTING'
order by
lead DESC""" % (party_id, state_id)
return str; |
def get_db_name(db_prefix):
"""Build the SQLite DB name from the prefix."""
return '{}.sqlite.db'.format(db_prefix) |
def scale_bbox_noUB(bbox_list, width, height):
"""
Normalize a bounding box give max_x and max_y.
:param bbox_list: list of list of coodinates in format: [xmin, ymin, xmax, ymax]
:param width: image max width.
:param height: image max height
:return: list of list of normalized coordinates.
"""
results = []
for i in bbox_list:
results_tmp = []
for xmin, ymin, xmax, ymax in i:
norm_cr = [xmin/width, ymin/height, xmax/width, ymax/height]
results_tmp.append(norm_cr)
results.append(results_tmp)
return results |
def triangle_random_points(num_points, loop_triangles):
"""
Generates a list of random points over mesh loop triangles.
:arg num_points: the number of random points to generate on each triangle.
:type int:
:arg loop_triangles: list of the triangles to generate points on.
:type loop_triangles: :class:`bpy.types.MeshLoopTriangle`, sequence
:return: list of random points over all triangles.
:rtype: list
"""
from random import random
# For each triangle, generate the required number of random points
sampled_points = [None] * (num_points * len(loop_triangles))
for i, lt in enumerate(loop_triangles):
# Get triangle vertex coordinates
verts = lt.id_data.vertices
ltv = lt.vertices[:]
tv = (verts[ltv[0]].co, verts[ltv[1]].co, verts[ltv[2]].co)
for k in range(num_points):
u1 = random()
u2 = random()
u_tot = u1 + u2
if u_tot > 1:
u1 = 1.0 - u1
u2 = 1.0 - u2
side1 = tv[1] - tv[0]
side2 = tv[2] - tv[0]
p = tv[0] + u1 * side1 + u2 * side2
sampled_points[num_points * i + k] = p
return sampled_points |
def check_if_file_exists_on_disk(filepath):
"""
Checks if the file exists on the disk.
Could use os.path.exists() but some its safer to do that following.
@param filepath: path to the file including the filename
"""
try :
with open(filepath) as f :
return True
except :
return False |
def egcd(a, b):
"""return a tuple of three values: x, y and z, such that x is
the GCD of a and b, and x = y * a + z * b"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) |
def hex_to_float(val, decimals = 0):
"""Converts hex string, int or float to float. Accepts `decimals`.
Returns a float or error (which should be handled in situ).
"""
try:
val = int(val, 16)
except:
val = val
return float(val / 10 ** decimals) |
def darsium(number) -> bool:
"""It will check whether the entered number is a darsium number or not."""
s = 0
n = number
c = 0
p = n
x = n
while(p != 0):
p = p//10
c += 1
while(n != 0):
r = n % 10
s = s+(r**c)
c = c-1
n = n//10
if(s == x):
return True
else:
return False |
def without_keys(d: dict, *rm_keys):
"""Returns copy of dictionary with each key in rm_keys removed"""
return {k: v for k, v in d.items() if k not in rm_keys} |
def rules_parser(rules):
"""
Convert a list of rules to a dictionary
with predecessor as the key and successor
as its value.
Each rule must be in the form of
"[predecessor]->[successor]"
Parameter
---------
rules: list of str
A list containing production rules
Return
------
dict {str: str}
The production rules in a dictionary
"""
if not rules:
return {}
result = {}
for r in rules:
key, val = r.split("->")
result[key] = val
return result |
def _is_udp_in_ipv4(pkt):
"""If UDP is in IPv4 packet return True,
else return False. False is returned also if exception occurs."""
ipv4_type = int('0x0800', 16) # IPv4
try:
if pkt.type == ipv4_type:
if pkt.payload.proto == 17: # UDP
return True
except: # pylint: disable=bare-except
return False
return False |
def get_best_snp(snp_list):
"""
This function choses the best SNP from the tested list by the max values
:param snp_list: list of SNPs with log-likelihood values
:return: name of the best SNP anf its loading value
"""
if len(snp_list) == 0:
return None, 0, 0
# Get the best SNP
snp_max = ''
snp_val = 0
delta_max = snp_list[0][1]
for snp, delta, val, pval in snp_list:
if delta >= delta_max:
delta_max = delta
snp_max = snp
snp_val = val
return snp_max, snp_val, delta_max |
def process_kmer_string(kmer_info_string, paired_input):
"""
Process a kmer info string (last column of a Kraken 2 output file), so that
we get a dictionary mapping of tax_ids to total sum of kmer hits.
Returns:
{tax_id_#1: X kmer hits,
tax_id_#2: Y kmer hits,
...
tax_id_#N: Z kmer hits}
"""
kmer_info_string = kmer_info_string.split()
# Kraken2 classifications file for paired data contain the "|:|" delimiter
if paired_input:
kmer_info_string.remove('|:|')
# Messy list comprehension. Converts all "taxa":"num_kmer" string pairs
# into integer tuples like (taxa, num_kmers), and saves them in a list.
# Ambiguous kmers are not processed (discarded).
kmer_classifications = [
(int(x[0]), int(x[1])) for x in (
kmer_info.split(':') for kmer_info in kmer_info_string)
if x[0] != 'A']
# Further processes the (taxa, num_kmers) tuples into a dict where each
# tax_id stores the total sum of kmer hits to that tax_id.
taxa_kmer_dict = {}
for kmer_info in kmer_classifications:
if kmer_info[0] not in taxa_kmer_dict:
taxa_kmer_dict[kmer_info[0]] = kmer_info[1]
else:
taxa_kmer_dict[kmer_info[0]] += kmer_info[1]
return taxa_kmer_dict |
def dictAsString(d):
"""Helper function that returns a string representation of a dictionary"""
s = "{"
for key, val in sorted(d.items()):
s += "%s: %s, " % (key, val)
s = s.rstrip(", ") # Nuke the trailing comma
s += "}"
return s |
def str_2_bool(value):
""" Converts 'something' to boolean.
Args:
value (str)
Returns:
True for values : 1, True, "1", "TRue", "yes", "y", "t"
False otherwise
"""
if str(value).lower() in ("yes", "y", "true", "t", "1"):
return True
else:
return False |
def squash_duplicate_values(values):
"""Remove duplicates from values.
If a value has already been defined remove future values.
Args:
values (list): List of value tuples.
Returns:
values (list): List of value tuples with duplicated removed.
"""
tmp = {}
for item in values:
if item[0] not in tmp:
tmp[item[0]] = (item[1], item[2])
return [(key, tmp[key][0], tmp[key][1]) for key in tmp] |
def unique_string_list(element_list, only_string=True):
"""
Parameters
----------
element_list :
only_string :
(Default value = True)
Returns
-------
"""
if element_list:
if isinstance(element_list, list):
element_list = set(element_list)
elif isinstance(element_list, str):
element_list = [element_list]
else:
error_message = 'Invalid list data'
try:
error_message += ' {}'.format(element_list)
except:
pass
raise Exception(error_message)
if only_string:
non_string_entries = [x for x in element_list if type(x) is not str]
assert not non_string_entries, "Invalid list entries {} are not a string!".format(
non_string_entries)
return element_list |
def get_word(path):
""" extract word name from json path """
return path.split('.')[0] |
def replace_template_variables(wrangler, data):
"""
Replace variables like %foo% in template data with actual code.
"""
for group in wrangler:
for variable in wrangler[group]:
template_variable = "%{}_{}%" . format(group, variable)
data = data.replace(template_variable,
"\n" . join(wrangler[group][variable]))
return data |
def trimDocString(docstring):
"""Return properly formatted docstring.
From: https://www.python.org/dev/peps/pep-0257/
Examples
--------
>>> from pygimli.utils import trimDocString
>>> docstring = ' This is a string with indention and whitespace. '
>>> trimDocString(docstring).replace('with', 'without')
'This is a string without indention and whitespace.'
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = 2**16 - 1
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < 2**16 - 1:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed) |
def head(list):
"""Returns the first element of the given list or string. In some libraries
this function is named first"""
for x in list:
return x |
def integrator_RK(x,step_size,function_system):
"""
Integrate with Runga Kutta
Parameters
x : state
step_size
function_system
"""
k1 = function_system(x)
k2 = function_system(x + step_size * k1 / 2)
k3 = function_system(x + step_size * k2 / 2)
k4 = function_system(x + step_size * k3)
x_new = x + (step_size / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
return x_new |
def parse_ports(port_string):
"""Convert a port specification string into a list of ports."""
ports = set()
for range_string in port_string.split(","):
port_range = [int(port) for port in range_string.split("-")]
ports = ports.union(set(range(min(port_range), max(port_range) + 1)))
return sorted(ports) |
def _calculate_full_regression(temp: float, rh: float) -> float:
"""
Full heat index regression, applicable when HI from simple regression is over 80
"""
return -42.379 + (2.04901523 * temp) + (10.14333127 * rh) \
- (.22475541 * temp * rh) - (.00683783 * temp * temp) - (.05481717 * rh * rh) \
+ (.00122874 * temp * temp * rh) + (.00085282 * temp * rh * rh) - (.00000199 * temp * temp * rh * rh) |
def int_to_bits(i: int):
"""Take an integer as input and return the bits written version."""
return "{:0{}b}".format(i, i.bit_length()) |
def number_GCD(x,y):
"""GCD(x:long, y:long): long
Return the GCD of x and y.
"""
x = abs(x) ; y = abs(y)
while x > 0:
x, y = y % x, x
return y |
def class2func(path):
""" Convert a path such as 'Landroid/support/v4/app/ActivityCompat;'
into a method string 'CLASS_Landroid_support_v4_app_ActivityCompat'
so we can call d.CLASS_Landroid_support_v4_app_ActivityCompat.get_source()
"""
func = "CLASS_" + path.replace("/", "_").replace("$", "_").replace(";", "")
return func |
def __py_if_condition(statements,lineno):
"""returns a valid python if statement"""
if_condition = statements[statements.find('(')+1:statements.find(')')]
return statements[:statements.find('if')]\
+f"if {if_condition}:\n".replace('&&',' and ').replace('||',' or ').replace('!',' not ').replace('===','==').replace('{','').replace('/','//') |
def english_def_formatter(senses):
"""Formats the english definitions into a list separated by commas
Args:
senses (array with dict elements): an array of english definitions for a given vocabulary word
Returns:
formatted_definitions (string): a string containing formatted english definitions
"""
# iterate through each item in senses, and grab the english definitions
eng_def_list = []
for sense in senses:
if 'english_definitions' in sense:
# iterate through each english definition in a english_definitions, and add it to a list
for i in range(0, len(sense['english_definitions'])):
eng_def_list.append(sense['english_definitions'][i])
return ', '.join(eng_def_list) |
def f_score(precision, recall, beta=1):
"""Compute F beta score
Args:
precision (float): precision
recall (float): recall
beta (float): the weight of recall, default=1
Returns:
float: f score
"""
if recall + precision*beta**2 == 0:
return 0
else:
return (1 + beta**2)*precision*recall / (recall + precision*beta**2) |
def additive_inverse(iterable: list) -> list:
"""Find the additive inverse of the iterable."""
return [i * -1 for i in iterable] |
def b(value):
"""Returns the string 'true' if value is truthy, 'false' otherwise."""
if value:
return 'true'
else:
return 'false' |
def filter_urls(new_urls, filter_words, args_filterand):
"""Returns filtered list of URLs based on URL filtering"""
filtered_urls = []
if args_filterand != None:
for i in new_urls:
if all(x in i for x in filter_words):
filtered_urls.append(i)
filtered_urls = list(set(filtered_urls))
else:
for i in new_urls:
if any(x in i for x in filter_words):
filtered_urls.append(i)
filtered_urls = list(set(filtered_urls))
return filtered_urls |
def getEnumerationFromArray(arr):
"""Return the enumeration of an array"""
return list(map(lambda c: c[0], enumerate(arr))) |
def parse_n_features(n_features, total):
"""Parse either the `n_features` for forward
and backward selection. Namely
(a) if `param` is an int, ensure it lies on (0, `total`),
(a) if `param` is a float, ensure it lies on (0, 1).
Args:
n_features : int
An `n_features` parameter passed to forward or backward selection.
total : int
The total features in the data
Returns:
int
* number of features to select.
If `n_features` and it lies on (0, `total`),
it will be returned 'as is'.
"""
if isinstance(n_features, int) and not 0 < n_features < total:
raise ValueError(
"If an int, `n_features` must be on (0, {}).".format(
total
)
)
if isinstance(n_features, float) and not 0 < n_features < 1:
raise ValueError(
"If a float, `n_features` must be on (0, 1)."
)
if isinstance(n_features, float):
return int(n_features * total)
else:
return n_features |
def trim_resource(resource):
"""
trim_resource
"""
return resource.strip(" \t\n\r/") |
def vis14(n): # DONE
"""
O O O
OOOOOO OOOOOO OOOOOO
OOOOOO OOOOOO
OOOOOO
Number of Os:
7 13 19"""
result = 'O\n'
for i in range(n):
result += 'OOOOOO\n'
return result |
def answer(l):
"""
We start by initializing a counter for every number in the list.
This counter resembles the number of times a particular entry in the list has been a multiple of a previous number.
Each time we increment that, we can also increase our number of triplets by the factor we're currently evaluating.
For example:
[1, 2, 4, 8]
When we reach 2, 1 is obviously a factor of 2. c[2] = 1.
When we reach 4, 1 is a factor of 4. c[4] = 1.
2 is a factor of 4. c[4] = 2. triplets += c[2] (triplets is now 1)
When we reach 8, 1 is a factor of 8. c[8] = 1.
2 is a factor of 8. c[8] = 2. triplets += c[2] (triplets is now 2)
4 is a factor of 8. c[8] = 3. triplets += c[4]. (triplets is now 4)
:param l: A list of integers to be evaluated.
:return: The number of 'lucky triplets' in the given list.
"""
counts = [0] * len(l)
triplets = 0
for product in range(0, len(l)):
for factor in range(0, product):
if l[product] % l[factor] == 0:
counts[product] += 1
triplets += counts[factor]
return triplets |
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
i = 0
j = len(array)
if j == 0:
return 0
sum = 0
while i<j:
if i%2 == 0:
sum = array[i] + sum
i += 1
res = sum*array[-1]
return res |
def imf_salpeter(x):
""" Computes a Salpeter IMF
Keywords
----------
x : numpy vector
masses
Returns
-------
imf : numpy vector
unformalized IMF
"""
return x**(-2.35) |
def get_network_interfaces(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP if specified.
"""
network_interfaces = []
networks = properties.get('networks', [])
if len(networks) == 0 and properties.get('network'):
network = {
"network": properties.get('network'),
"subnetwork": properties.get('subnetwork'),
"networkIP": properties.get('networkIP'),
}
networks.append(network)
if (properties.get('hasExternalIp')):
network['accessConfigs'] = [{
"type": "ONE_TO_ONE_NAT",
}]
if properties.get('natIP'):
network['accessConfigs'][0]['natIP'] = properties.get('natIP')
for network in networks:
if not '.' in network['network'] and not '/' in network['network']:
network_name = 'global/networks/{}'.format(network['network'])
else:
network_name = network['network']
network_interface = {
'network': network_name,
}
netif_optional_props = ['subnetwork', 'networkIP', 'aliasIpRanges', 'accessConfigs']
for prop in netif_optional_props:
if network.get(prop):
network_interface[prop] = network[prop]
network_interfaces.append(network_interface)
return network_interfaces |
def gen_list_of_lists(original_list, new_structure):
"""Generates a list of lists with a given structure from a given list."""
assert len(original_list) == sum(
new_structure
), "The number of elements in the original list and desired structure don't match"
return [
[original_list[i + sum(new_structure[:j])] for i in range(new_structure[j])]
for j in range(len(new_structure))
] |
def check_exam(arr1, arr2):
"""
Marks an exam checking whether the students answers to the solution.
:param arr1: array of strings containing correct solutions.
:param arr2: array of strings containing student answers.
:return: the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer,
and +0 for each blank answer(empty string).
"""
score = 0
for x in range(len(arr1)):
if arr1[x] == arr2[x]:
score += 4
elif arr1[x] != arr2[x] and arr2[x] != "":
score -= 1
if score < 0:
return 0
return score |
def CalcMacTerminalCommand(command):
"""
Calculate what to put in popen to start a given script.
Starts a tiny Applescript that performs the script action.
"""
#
# Quoting is a bit tricky; we do it step by step.
# Make Applescript string: put backslashes before double quotes and
# backslashes.
#
command = command.replace('\\', '\\\\').replace('"', '\\"')
#
# Make complete Applescript command.
#
command = 'tell application "Terminal" to do script "%s"' % command
#
# Make a shell single quoted string (put backslashed single quotes
# outside string).
#
command = command.replace("'", "'\\''")
#
# Make complete shell command.
#
return "osascript -e '%s'" % command |
def _pytype_to_shape_fn_pytype(pytype: str) -> str:
"""Convert a JitOperator pytype to the type relevant in shape functions.
In particular, this converts `Tensor` to `List[int]`, along with a few
other special cases.
"""
# `Scalar` operands (which are represented with pytype "number") can
# be either `int` or `float`. TorchScript has no way to represent a
# signature of this type, so we hardcode it to `float`. `Scalar`
# operands don't participate in shape functions (since they are
# logically real-valued), so it doesn't really matter much, and
# `float` helps make it clearer that it's not part of the shape
# function.
if pytype == "number":
return "float"
if pytype == "Optional[number]":
return "Optional[float]"
# `torch.device` is lowercase.
if pytype == "Device":
return "device"
if pytype == "Optional[Device]":
return "Optional[device]"
# Shape functions only care about the shape of tensors.
if pytype == "Tensor":
return "List[int]"
if pytype == "Optional[Tensor]":
return "Optional[List[int]]"
if pytype == "List[Tensor]":
return "List[List[int]]"
if pytype == "List[Optional[Tensor]]":
return "List[Optional[List[int]]]"
# Generators don't contribute to shapes, and are not scriptable currently.
# So just hack them to be passed as "Any".
if pytype == "Generator":
return "Any"
if pytype == "Optional[Generator]":
return "Any"
return pytype |
def digit_only(string):
"""Removes non-digit characters"""
digits = [char for char in str(string) if char.isdigit()]
return ''.join(digits) |
def get_split_message(message, max_size=4096, search_distance=410):
"""
Splits message in chunks of less than or equal to max_size symbols.
Searches for "\n\n", "\n", ". ", and " " and tries to split message by them.
:param message: message to split.
:param max_size: maximum size of a chunk.
:param search_distance: numbers of symbols to search for new lines.
:return: chunks of message.
"""
delimiters = ["\n\n", "\n", ". ", " "]
chunks = []
i = 0
index = 0
while i < len(message):
for delimiter in delimiters:
index = message.rfind(
delimiter, max(i, i + max_size - search_distance), (i + max_size)
)
if index != -1:
index += len(delimiter)
break
if index == -1:
index = i + max_size
chunks.append(message[i:index])
i = index
return chunks |
def last_digit_of(a,b):
""" Calculates the last digit of a^b
Args:
a (int): Base of a^b
b (int): Exponent of a^b
Returns:
(int): The last digit of a^b
"""
last_digit_a = int(str(a)[-1])
if b % 4 == 0:
exp = 4
else:
exp = b % 4
return (last_digit_a ** exp) % 10 |
def get_horse_images(num_horses):
""" (int) -> list
Returns a list of GIF image files.
Each image contains the same horse image, each with a unique number 1 - 10
"""
images = []
# Get all horse images
for a_horse in range(0, num_horses):
images = images + ['images/horse_{0}_image.gif'.format(a_horse + 1)]
return images |
def TrueDiv(a1, a2, ctx=None):
"""Divides two numbers"""
if a2 == 0:
return float(f"{'-' if a1 < 0 else ''}Infinity")
return a1 / a2 |
def build_compound(compound):
"""Build a compound
Args:
compound(dict)
Returns:
compound_obj(dict)
dict(
# This must be the document_id for this variant
variant = str, # required=True
# This is the variant id
display_name = str, # required
combined_score = float, # required
rank_score = float,
not_loaded = bool
genes = [
{
hgnc_id: int,
hgnc_symbol: str,
region_annotation: str,
functional_annotation:str
}, ...
]
)
"""
compound_obj = dict(
variant=compound["variant"],
display_name=compound["display_name"],
combined_score=float(compound["score"]),
)
return compound_obj |
def count_type_changes(pattern: str):
"""Count the number of type changes in the given pattern.
The pattern is expected to describe Bloch points with single characters
where each character type represents one type of Bloch point. Example:
`iooi` -> two type changes.
"""
count = 0
for left, right in zip(pattern[:-1], pattern[1:]):
if left != right:
count += 1
return count |
def get_policy_id(token_name, utxo):
"""
retrieve policy id from token name in utxo
"""
assets_id = [k.split('.') for k in utxo['balances'].keys() if len(k.split('.')) == 2 and k.split('.')[1] == token_name]
if len(assets_id) == 1:
policy_id = assets_id[0][0]
else:
policy_id = None
return policy_id |
def cancel_dashed(guess, word, answer):
"""
:param guess: an alphabet, the right guess made by player
:param word: The word looks like that it hasn't completely been guessed correctly
:param answer: a word, the correct answer
:return: The word looks like that some of the word have been replaced by right guess
"""
ans = ''
for i in range(len(answer)):
ans_ch = answer[i]
ch = word[i]
if ans_ch == guess:
# Replace the showing string's dashes if the input_ch is a right guess.
ans += guess
else:
ans += ch
# Maintain the same word if the input_ch is not right.
return ans |
def _neo4j_sanitize(string):
"""
Auxilary functions making sure that backdashes are properly noted and managed in Python.
:param string: string to sanitize
:return:
"""
if isinstance(string, str):
return string.replace('\'', '\"').replace('\\', '\\\\')
else:
return string |
def find_number_3_multiples(x):
"""Calculate the number of times that 3 goes into x."""
mult3=x//3
return mult3 |
def darker(col, factor=0.5):
"""Function returns a darkened (by factor) color.
"""
c0 = int(col[0] * factor)
c1 = int(col[1] * factor)
c2 = int(col[2] * factor)
return (c0, c1, c2) |
def connection_failed(errno=None, errstr=None):
"""
Construct a template for SSH on connection failed
"""
tpl = { 'ssh-event': 'connection-failed' }
if errno is not None:
tpl['error-no'] = errno
if errstr is not None:
tpl['error-str'] = errstr
return tpl |
def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) |
def separate_dashed_words(token):
"""Separates dashed words and returns the list of all words.
:param token: string
:return: list
"""
return token.split('-') |
def cut(value, arg):
"""Removes all values of arg from the given string."""
return value.replace(arg, '') |
def add_default_value_to(description, default_value):
"""Adds the given default value to the given option description."""
# All descriptions end with a period, so do not add another period.
return '{} Default: {}.'.format(
description,
default_value if default_value else '""'
) |
def list_to_comma_string(val):
"""
Handle array fields by converting them to a comma-separated string.
Example:
['1','2','3'] -> 1,2,3
"""
if val is None:
return ''
if isinstance(val, list):
val = ','.join(val)
return val |
def longest_common_prefix(s1, s2):
"""
Calculate the longest common prefix of two strings.
>>> longest_common_prefix('abcdefg', 'abcabcdefg')
'abc'
>>> longest_common_prefix('abcdefg', 'abcdefg')
'abcdefg'
@arg s1: The first string.
@type s1: unicode
@arg s2: The second string.
@type s2: unicode
@return: The longest common prefix of s1 and s2.
@rtype: unicode
@todo: This is mostly used just for the length of the returned string,
and we could also return that directly.
"""
pos = 0
while pos < min(len(s1), len(s2)) and s1[pos] == s2[pos]:
pos += 1
return s1[:pos] |
def _construct_arn(owner_id, region_name, instance_id):
"""
Args:
owner_id (str): owner id
region_name (str) : region that EC2 is deployed
instance_id (str) : instance on of the EC2
Returns:
EC2 arn
"""
return 'arn:aws:ec2:{region}:{owner}:instance/instance-id/{instance_id}'.format(
region=region_name,
owner=owner_id,
instance_id=instance_id,
) |
def count_digits_func(input_value):
"""Return the number of digits in a number"""
return len(str(abs(input_value))) |
def percentage(numerator: float, denominator: float) -> float:
"""Calculate a percentage
Args:
numerator (float): The top of the fraction
denominator (float): The bottom of the fraction
Returns:
float: The numerator as a percentage of the denominator
"""
return (numerator / denominator) * 100 |
def HexToRGB(hex_str):
"""Returns a list of red/green/blue values from a
hex string.
@param hex_str: hex string to convert to rgb
"""
hexval = hex_str
if hexval[0] == u"#":
hexval = hexval[1:]
ldiff = 6 - len(hexval)
hexval += ldiff * u"0"
# Convert hex values to integer
red = int(hexval[0:2], 16)
green = int(hexval[2:4], 16)
blue = int(hexval[4:], 16)
return [red, green, blue] |
def get_plain_text_value(input: dict) -> str:
"""
Get the value of a text input field.
"""
return input.get('value', None) |
def first_name(s):
"""
Returns the first name in s
Examples:
last_name_first('Walker White') returns 'Walker'
last_name_first('Walker White') returns 'Walker'
Parameter s: a name 'first-name last-name'
Precondition: s is a string 'first-name last-name' with one or more blanks
between the two names.
"""
end_first = s.find(' ')
return s[:end_first] |
def validar_numero(numero: int) -> bool:
"""Valida un numero si es positivo o negativo
:param numero: Numero a validar
:numero type: int
:return: True si el numero es menor igual a cero, de lo contrario
False
:rtype: bool
"""
return True if numero <= 0 else False |
def b(node):
"""
Converts a string "0" or "1" to Python's ``True`` and ``False``
"""
return bool(int(node)) |
def byte_to_megabyte(byte):
"""
Convert byte value to megabyte
"""
return byte / (1024.0**2) |
def get_conf(env, node_data):
"""Extract docker configuration from the node data.
The expected node_dafa docker config looks like this:
docker:
daemon_conf:
signature-verification: false
debug: true
all_registries:
dev:
- host: hub-dev.domain
insecure: true
qa:
- host: hub-qa.domain
insecure: true
uat:
- host: hub-uat.domain
insecure: false
ca_cert: xxx
client_cert: xxx
client_key: xxx
- host: hub-uat2.domain
insecure: true
prod:
- host: hub.domain
ca_cert: xxx
client_cert: xxx
client_key: xxx
the `daemon_conf` is used as docker daemon configuration
https://docs.docker.com/engine/reference/
commandline/dockerd/#daemon-configuration-file
or (backward compatibility):
docker_registries:
- foo.domain
- bar.domain
or (backward compatibility):
docker_registries:
dev:
- hub-dev.domain
qa:
- hub-qa.domain
uat:
- hub-uat.domain
prod:
- hub.domain
The returned docker config looks like this:
{
daemon_conf:
signature-verification: False
debug: true
registries:
- host: hub-uat.domain
insecure: false
ca_cert: xxx
client_cert: xxx
client_key: xxx
- host: hub-uat2.domain
insecure: true
}
"""
docker_conf = node_data.get('docker', {})
default_regs = []
if not docker_conf and 'docker_registries' in node_data:
# Legacy configs support
registry_conf = node_data['docker_registries']
if isinstance(registry_conf, list):
# Assume we want the same registries in all environments. We do
# this by making the list the fallback default.
registries = {}
default_regs = [
{
'host': registry,
'insecure': True
}
for registry in list(registry_conf)
]
else:
# If the conf is a dict, ensure it has all necessary keys
registries = {
env: [
{
'host': registry,
'insecure': True,
}
for registry in registries
]
for env, registries in registry_conf.items()
}
docker_conf = {
'daemon_conf': {},
'all_registries': registries,
}
else:
# Normalize
docker_conf = {
'daemon_conf': docker_conf.get('daemon_conf', {}),
'all_registries': docker_conf.get('all_registries', {}),
}
return {
'daemon_conf': docker_conf['daemon_conf'],
'registries': docker_conf['all_registries'].get(env, default_regs),
} |
def bytes_to_gb(qty_bytes):
""" Return a GB value of bytes, rounded to 2 decimals """
bytes_in_gb = 1024 * 1024 * 1024
qty_gb = qty_bytes / bytes_in_gb
return round(qty_gb, 2) |
def self_affine_psd(q, pref, hurst, onedim=False):
"""Ideal self-affine power spectrum, dependent only on prefactor and Hurst exponent."""
exp = -2 * (hurst + 1)
if onedim:
exp = -1 - 2 * hurst
return pref * q**exp |
def strip_query_string(url):
# type: (str) -> str
"""
Strips the query string from a URL for use as tag in spans.
:param url: The URL to be stripped
:return: The given URL without query strings
"""
hqs, fs, f = url.partition("#")
h, _, _ = hqs.partition("?")
if not f:
return h
return h + fs + f |
def clean_data(L):
"""clean list data, strip white space and reject empty string."""
i = len(L) - 1
while i >= 0:
L[i] = L[i].strip()
if L[i] == '':
del L[i]
i -= 1
return L |
def detect_archive_type(name):
"""
Tries to guess which type an archive is.
"""
# test for tar
tar_endings = ['.tbz2', '.tar.gz']
for ending in tar_endings:
if name.endswith(ending):
return 'tar'
# test for zip
zip_endings = ['.zip', '.jar']
for ending in zip_endings:
if name.endswith(ending):
return 'zip'
# unknown
return None |
def find_possible_matches(apitools_collection_guess, apitools_collection_names):
"""Find any apitools collections that reasonably match our guess."""
possible_matches = []
for apitools_collection_name in apitools_collection_names:
split_collection_name = apitools_collection_name.split('.')
if apitools_collection_guess.lower() in split_collection_name[-1].lower(
) or split_collection_name[-1].lower() in apitools_collection_guess.lower():
possible_matches.append(apitools_collection_name)
return possible_matches |
def generate_fake_var(element):
"""Given a credential type field element, makes up something acceptable.
"""
if element['type'] == 'string':
if element.get('format', None) == 'ssh_private_key':
# this example came from the internet
return '\n'.join([
'-----BEGIN ENCRYPTED PRIVATE KEY-----'
'MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI5yNCu9T5SnsCAggA'
'MBQGCCqGSIb3DQMHBAhJISTgOAxtYwSCAWDXK/a1lxHIbRZHud1tfRMR4ROqkmr4'
'kVGAnfqTyGptZUt3ZtBgrYlFAaZ1z0wxnhmhn3KIbqebI4w0cIL/3tmQ6eBD1Ad1'
'nSEjUxZCuzTkimXQ88wZLzIS9KHc8GhINiUu5rKWbyvWA13Ykc0w65Ot5MSw3cQc'
'w1LEDJjTculyDcRQgiRfKH5376qTzukileeTrNebNq+wbhY1kEPAHojercB7d10E'
'+QcbjJX1Tb1Zangom1qH9t/pepmV0Hn4EMzDs6DS2SWTffTddTY4dQzvksmLkP+J'
'i8hkFIZwUkWpT9/k7MeklgtTiy0lR/Jj9CxAIQVxP8alLWbIqwCNRApleSmqtitt'
'Z+NdsuNeTm3iUaPGYSw237tjLyVE6pr0EJqLv7VUClvJvBnH2qhQEtWYB9gvE1dS'
'BioGu40pXVfjiLqhEKVVVEoHpI32oMkojhCGJs8Oow4bAxkzQFCtuWB1'
'-----END ENCRYPTED PRIVATE KEY-----'
])
if element['id'] == 'host':
return 'https://foo.invalid'
return 'fooo'
elif element['type'] == 'boolean':
return False
raise Exception('No generator written for {} type'.format(element.get('type', 'unknown'))) |
def _quadratic_polynomial(x, y, p):
"""Quadratic polynomial that can be fitted to an isochrone.
Args:
x: Colours of points in isochrone.
y: Magnitudes of points in isochrone.
p: Coefficients for polynomial.
Returns:
Evaluated polynomial.
"""
return p[0] + p[1] * x + p[2] * y + p[3] * x * x + p[4] * y * y + p[5] * x * y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.