content
stringlengths 42
6.51k
|
|---|
def cut(num):
"""
Shorten the format of a number to 2 decimal places plus exponent
@param num: the number to be shorten
"""
return "{0:.2e}".format(num)
|
def get_span(start_ids, end_ids, with_prob=False):
"""
every id can only be used once
get span set from position start and end list
input: [1, 2, 10] [4, 12]
output: set((2, 4), (10, 12))
"""
if with_prob:
start_ids = sorted(start_ids, key=lambda x: x[0])
end_ids = sorted(end_ids, key=lambda x: x[0])
else:
start_ids = sorted(start_ids)
end_ids = sorted(end_ids)
start_pointer = 0
end_pointer = 0
len_start = len(start_ids)
len_end = len(end_ids)
couple_dict = {}
while start_pointer < len_start and end_pointer < len_end:
if with_prob:
if start_ids[start_pointer][0] == end_ids[end_pointer][0]:
couple_dict[end_ids[end_pointer]] = start_ids[start_pointer]
start_pointer += 1
end_pointer += 1
continue
if start_ids[start_pointer][0] < end_ids[end_pointer][0]:
couple_dict[end_ids[end_pointer]] = start_ids[start_pointer]
start_pointer += 1
continue
if start_ids[start_pointer][0] > end_ids[end_pointer][0]:
end_pointer += 1
continue
else:
if start_ids[start_pointer] == end_ids[end_pointer]:
couple_dict[end_ids[end_pointer]] = start_ids[start_pointer]
start_pointer += 1
end_pointer += 1
continue
if start_ids[start_pointer] < end_ids[end_pointer]:
couple_dict[end_ids[end_pointer]] = start_ids[start_pointer]
start_pointer += 1
continue
if start_ids[start_pointer] > end_ids[end_pointer]:
end_pointer += 1
continue
result = [(couple_dict[end], end) for end in couple_dict]
result = set(result)
return result
|
def print_errors_result(result, verbose=False):
"""
"""
spacers = 4
if verbose:
print(f"\nTotal Stats\n{spacers*' '}max. err.: {result[0]:6.3f};")
print(f"{(spacers-2)*' '}c-avg. err.: {result[1]:6.3f};")
print(f"{(spacers-2)*' '}t-avg. err.: {result[2]:6.3f}")
return None
|
def alpha_rate(iteration):
"""
alpha learning rate
:param iteration: the count of iteration
:return: alpha
"""
return 150/(300 + iteration)
|
def is_ignored(path):
"""checks if file has non-code-file extension"""
ignore_ext = ['.json', '.md', '.ps', '.eps', '.txt', '.xml', '.xsl',
'.rss', '.xslt', '.xsd', '.wsdl', '.wsf', '.yaml', '.yml',
'~', '#']
for ext in ignore_ext:
l = len(ext)
if path[-l:] == ext:
return True
return False
|
def rev_bits(x: int, width: int = 0) -> int:
"""Return the given integer but with the bits reversed.
Params:
x - integer to reverse
width - width of the integer (in bits)
Returns:
The reversed integer.
"""
if not width:
width = x.bit_length()
rev = 0
for i in range(width):
bit = x & (1 << i)
if bit: rev |= (1 << (width - i - 1))
return rev
|
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
# return gamma * (phi**2-1.)**2
# func = 1.-phi**2
# return 0.75 * gamma * max_value(func, 0.)
return gamma
|
def string_ijk1_for_cell_kji0(cell_kji0):
"""Returns a string showing indices for a cell in simulator protocol, from data in python protocol."""
return '[{:}, {:}, {:}]'.format(cell_kji0[2]+1, cell_kji0[1]+1, cell_kji0[0]+1)
|
def find_nearest_index(data, value):
"""Find the index of the entry in data that is closest to value.
Example:
>>> data = [0, 3, 5, -2]
>>> i = partmc.find_nearest_index(data, 3.4)
returns i = 1
"""
min_diff = abs(value - data[0])
min_i = 0
for i in range(1,len(data)):
diff = abs(value - data[i])
if diff < min_diff:
min_diff = diff
min_i = i
return min_i
|
def isConfigException(exception):
"""This method tries to check if the Exception was raised by the local API code (mostly while reading configuration)"""
errorList = [ValueError, KeyError, FileNotFoundError]
if type(exception) in errorList:
return True
else:
return False
|
def unwrap(runner):
"""
Unwraps all delegators until the actual runner.
:param runner: An arbitrarily nested chain of delegators around a runner.
:return: The innermost runner.
"""
delegate = getattr(runner, "delegate", None)
if delegate:
return unwrap(delegate)
else:
return runner
|
def asset_table_aoi(gee_dir):
"""return the aoi for the reclassify tests available in our test account"""
return f"{gee_dir}/reclassify_table_aoi"
|
def is_valid(s):
"""
Using a conventional stack struct, validate
strings in the form "({[]})" by:
1. pushing all openning chars: '(','{' and '[', sequentially.
2. when a closing character like ')', '}' and '] is found
we pop the last opening char pushed into stack
3. check if popped char matches the closing character found.
If stack is empty and all comparisons are a match, returns
true. False otherwise.
s: string to be validaded
return True or False depending if string is valid or not
"""
if len(s) < 2:
return False
parent_map = {
'(': ')',
'{': '}',
'[': ']',
}
stack = []
for c in s:
# if opening char
if c in parent_map.keys():
stack.append(c)
else:
if not stack:
return False
# attempt matching opening and closing chars
if parent_map[stack.pop()] != c:
return False
return not stack
|
def get_num_classes(dataset: str):
"""Return the number of classes in the dataset. """
if dataset == "imagenet":
return 1000
elif dataset == "cifar10":
return 10
|
def _get_subnet_id(connection, subnet_name):
"""
:param connection:
:param subnet_name:
:return:
"""
if not subnet_name:
print("WARNING: No subnet was specified.")
return
# Try by name
subnets = connection.describe_subnets(
Filters=[{'Name': 'tag:Name', 'Values': [subnet_name, ]}, ]
)
subnets = subnets['Subnets']
if not subnets:
# Try by id
subnets = connection.describe_security_groups(
Filters=[{'Name': 'subnet-id ', 'Values': [subnet_name, ]}, ]
)
subnets = subnets['Subnets']
return subnets[0]['SubnetId'] if subnets else None
|
def _mysql_aes_key(key):
"""Format key."""
final_key = bytearray(16)
for i, c in enumerate(key):
final_key[i % 16] ^= key[i]
return bytes(final_key)
|
def try_dict(value):
"""Try converting objects first to dict, then to str so we can easily compare them against JSON."""
try:
return dict(value)
except (ValueError, TypeError):
return str(value)
|
def word_combine(x):
""" Returns a string that combines a list of words with proper commas and trailing 'and' """
num_words = len(x)
if num_words == 1: return x[0]
combined = ""
i = 1
for item in x:
if i == num_words:
combined += "and " + item
break
if (num_words == 2 and i == 1):
combined += item + " "
else:
combined += item + ", "
i+=1
return combined
|
def checksum(code):
"""Given a byte number expressed in hex ASCII, find mod-256 8-bit checksum."""
return sum(code) % 256
|
def stepx(x, steps, total, margin):
"""Return slices with and without interpolation between batches.
"""
start = 0 if x - margin <= 0 else x - margin
end = total if steps + x + margin >= total else steps + x + margin
#end = end if start > 0 else end + margin
Interpolated = slice(start, end)
nonInterpolated = slice(x, x + steps) if (x + steps) < total else slice(x, total)
return Interpolated, nonInterpolated
|
def definition_updated_message(payload):
"""
Build a Slack notification about an updated definition.
"""
definition_url = payload['definition']['url']
definition_name = payload['definition']['name']
message = 'The <{}|{}> definition was just updated.'
message = message.format(definition_url, definition_name)
attachments = [
{
'fallback': message,
'color': 'warning',
'author_name': 'Mode',
'author_link': 'https://modeanalytics.com/',
'title': 'Definition Updated :heavy_exclamation_mark:',
'text': message
}
]
return attachments
|
def intify(i):
"""If i is a long, cast to an int while preserving the bits"""
if 0x80000000 & i:
return int((0xFFFFFFFF & i))
return i
|
def single_link(first_clustering, second_clustering, distance_function):
"""
Finds the smallest distance between any two points in the two given clusters
:param first_clustering: a set of points
:param second_clustering: a set of points
:param distance_function: a function that compares two points
:return: the smallest distance between a pair of points in the two clusters
"""
min_neighbor_distance = None
for first_neighbor in first_clustering:
for second_neighbor in second_clustering:
current_distance = distance_function(first_neighbor, second_neighbor)
if not min_neighbor_distance or min_neighbor_distance > current_distance:
min_neighbor_distance = current_distance
return min_neighbor_distance
|
def StringsExcludeSubstrings(strings, substrings):
"""Returns true if all strings do not contain any substring.
Args:
strings: List of strings to search for substrings in.
substrings: List of strings to find in `strings`.
Returns:
True if every substring is not contained in any string.
"""
for s in strings:
for substr in substrings:
if substr in s:
return False
return True
|
def shannon(data):
""" Given a hash { 'species': count } , returns the SDI
>>> sdi({'a': 10, 'b': 20, 'c': 30,})
1.0114042647073518"""
from math import log as ln
def p(n, N):
""" Relative abundance """
if n is 0:
return 0
else:
return (float(n)/N) * ln(float(n)/N)
N = sum(data.values())
return -sum(p(n, N) for n in data.values() if n is not 0)
|
def getid(obj):
"""Get obj's uuid or object itself if no uuid
Abstracts the common pattern of allowing both an object or
an object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.uuid
except AttributeError:
return obj
|
def BackslashEscape(s, meta_chars):
"""Escaped certain characters with backslashes.
Used for shell syntax (i.e. quoting completed filenames), globs, and EREs.
"""
escaped = []
for c in s:
if c in meta_chars:
escaped.append('\\')
escaped.append(c)
return ''.join(escaped)
|
def name_without_commas(name):
"""
Takes a name formatted as "[LastNames], [FirstNames]"
and returns it formatted as "[FirstNames] [LastNames]".
If a name without commas is passed it is returned unchanged.
"""
if name and "," in name:
name_parts = name.split(",")
if len(name_parts) == 2:
first_names = name_parts[1].strip()
last_names = name_parts[0].strip()
return first_names + " " + last_names
return name
|
def new_sleep_data_serie(startdate, enddate, state):
"""Create simple dict to simulate api data."""
return {"startdate": startdate, "enddate": enddate, "state": state}
|
def _remove_parenthesis(word):
"""
Examples
--------
>>> _remove_parenthesis('(ROMS)')
'ROMS'
"""
try:
return word[word.index("(") + 1 : word.rindex(")")]
except ValueError:
return word
|
def is_santas_turn(turn):
"""Check if the given turn corresponds to Santa."""
return turn % 2 == 0
|
def get_id_prefix(id_prefix=1, proxmox_node_scale=3, node=None):
"""
Default prefix if node name has no number, is 1.
"""
if not node:
return id_prefix
for i in range(1, proxmox_node_scale + 1):
if str(i) in node:
return i
return id_prefix
|
def to_unicode(value):
"""
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
try:
if isinstance(value, (str, type(None))):
return value
if not isinstance(value, bytes):
raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
return value.decode("utf-8")
except UnicodeDecodeError:
return repr(value)
|
def tuple_split(string):
"""
Split a string into a list of tuple values
from utils.tools import tuple_split
print tuple_split('')
#[]
print tuple_split('3')
#[3]
print tuple_split('3,4')
#[(3, 4)]
print tuple_split('3,5 6,1 4,2')
#[(3, 5), (6, 1), (4, 2)]
"""
values = []
if string:
try:
_string_list = string.strip(' ').replace(';', ',').split(' ')
for _str in _string_list:
items = _str.split(',')
_items = [float(itm) for itm in items]
values.append(tuple(_items))
return values
except:
return values
else:
return values
|
def url_feed_prob(url):
"""
This method gets a url and calculateds the probability of it leading to a rss feed
:param url: str
:return: int
"""
if "comments" in url:
return -2
if "georss" in url:
return -1
kw = ["atom", "rss", "rdf", ".xml", "feed"]
for p, t in zip(range(len(kw), 0, -1), kw):
if t in url:
return p
return 0
|
def dot(u, v):
"""
Dot product of 2 N dimensional vectors.
"""
s = 0
for i in range(0, len(u)):
s += u[i] * v[i]
return s
|
def split(container, count):
"""
Simple function splitting a container into equal length chunks.
Order is not preserved but this is potentially an advantage depending on
the use case.
"""
return [container[_i::count] for _i in range(count)]
|
def convert_truelike_to_bool(input_item, convert_int=False, convert_float=False, convert_nontrue=False):
"""Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True.
Parameters
----------
input_item : string or int
Item to be converted to bool (e.g. "true", 1, "WAHR" or the equivalent in several languagues)
convert_float: bool
Convert floats to bool.
If True, "1.0" will be converted to True
convert_nontrue : bool
If True, the output for input_item not recognised as "True" will be False.
If True, the output for input_item not recognised as "True" will be the original input_item.
Returns
-------
return_value : True, or input_item
If input_item is True-like, returns python bool True. Otherwise, returns the input_item.
Usage
-----
# convert a single value or string
convert_truelike_to_bool("true")
# convert a column in a pandas DataFrame
df["column_name"] = df["column_name"].apply(convert_truelike_to_bool)
"""
list_True_items = [True, 'True', "true","TRUE","T","t",'wahr', 'WAHR', 'prawdziwy', 'verdadeiro', 'sann', 'istinit',
'veritable', 'Pravda', 'sandt', 'vrai', 'igaz', 'veru', 'verdadero', 'sant', 'gwir', 'PRAWDZIWY',
'VERDADEIRO', 'SANN', 'ISTINIT', 'VERITABLE', 'PRAVDA', 'SANDT', 'VRAI', 'IGAZ', 'VERU',
'VERDADERO', 'SANT', 'GWIR', 'bloody oath', 'BLOODY OATH', 'nu', 'NU','damn right','DAMN RIGHT']
# if you want to accept 1 or 1.0 as a true value, add it to the list
if convert_int:
list_True_items += ["1"]
if convert_float:
list_True_items += [1.0, "1.0"]
# check if the user input string is in the list_True_items
input_item_is_true = input_item in list_True_items
# if you want to convert non-True values to "False", then nontrue_return_value = False
if convert_nontrue:
nontrue_return_value = False
else:
# otherwise, for strings not in the True list, the original string will be returned
nontrue_return_value = input_item
# return True if the input item is in the list. If not, return either False, or the original input_item
return_value = input_item_is_true if input_item_is_true == True else nontrue_return_value
# special case: decide if 1 as an integer is True or 1
if input_item == 1:
if convert_int == True:
return_value = True
else:
return_value = 1
return return_value
|
def redis_stream_id_subtract_one(message_id):
"""Subtract one from the message ID
This is useful when we need to xread() events inclusive of the given ID,
rather than exclusive of the given ID (which is the sensible default).
Only use when one can tolerate an exceptionally slim risk of grabbing extra events.
"""
milliseconds, n = map(int, message_id.split("-"))
if n > 0:
n = n - 1
elif milliseconds > 0:
milliseconds = milliseconds - 1
n = 9999
else:
# message_id is '0000000000000-0'. Subtracting one
# from this is neither possible, desirable or useful.
return message_id
return "{:13d}-{}".format(milliseconds, n)
|
def rectanglesOverlap(r1, r2):
"""Check whether r1 and r2 overlap."""
if ((r1[0] >= r2[0] + r2[2]) or (r1[0] + r1[2] <= r2[0])
or (r1[1] + r1[3] <= r2[1]) or (r1[1] >= r2[1] + r2[3])):
return False
else:
return True
|
def add_s8(x, y):
"""Add two 8-bit integers stored in two's complement."""
return (x + y) & 0xff
|
def get_job_type_from_image(image_uri):
"""
Return the Job type from the image tag.
:param image_uri: ECR image URI
:return: Job Type
"""
tested_job_type = None
allowed_job_types = ("training", "inference")
for job_type in allowed_job_types:
if job_type in image_uri:
tested_job_type = job_type
break
if not tested_job_type and "eia" in image_uri:
tested_job_type = "inference"
if not tested_job_type:
raise RuntimeError(
f"Cannot find Job Type in image uri {image_uri} " f"from allowed frameworks {allowed_job_types}"
)
return tested_job_type
|
def quote_it(s):
"""Return the argument quoted, suitable for a quoted-string"""
return '"%s"' % (s.replace("\\","\\\\").replace('"','\\"'))
|
def text_presence(job_desc, lan_list):
"""
Parameters
----------
job_desc : str
Job Description.
lan_list : list
List of languages.
Returns
-------
dic : dictionary
Dictionary of if each language was in description.
"""
dic = {}
for language in lan_list:
present = language in job_desc.lower()
dic[language] = int(present)
return dic
|
def initialize_dataset(input_data):
""" Input dictionary should be of the form created by parse_star_file function. Returns a new dictionary of the form:
{ 'class001.mrc' : [ (%_it1, %_it2, ...), (res_it1, res_it2, ...), (iteration value1, ...) ] }
"""
new_dictionary = {}
for entry in input_data:
proportion = entry[1]
resolution = entry[2]
iteration_value = entry[3]
new_dictionary[entry[0]] = ( [proportion], [resolution], [iteration_value] )
return new_dictionary
|
def _equal_room_tp(room, target):
"""
NOTE: Ensure <target> is always from <ALLOWED_TARGET_ROOM_TYPES>!!!!
DO NOT swap the order of arguments
"""
room = room.lower()
target = target.lower()
return (room == target) or \
((target == 'bathroom') and (room == 'toilet')) or \
((target == 'bedroom') and (room == 'guest_room'))
|
def get_result_or_same_in_list(function, value):
"""
Return the result if True or the value within a list.
Applies `function` to `value` and returns its result if it evaluates
to True. Otherwise, return the value within a list.
`function` should receive a single argument, the `value`.
"""
result = function(value)
return result if result else [value]
|
def lr_policy(initial_lr, step, N):
"""
learning rate decay
Args:
initial_lr: base learning rate
step: current iteration number
N: total number of iterations over which learning rate is decayed
"""
min_lr = 0.00001
res = initial_lr * ((N - step) / N) ** 2
return max(res, min_lr)
|
def url_joiner(url, path, trailing=None):
"""Join to sections for a URL and add proper forward slashes"""
url_link = "/".join(s.strip("/") for s in [url, path])
if trailing:
url_link += "/"
return url_link
|
def valid_ecl(ecl):
"""ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth."""
valid = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
if ecl in valid:
return True
else:
return False
|
def scrub_keys(key):
"""Replace periods (restricted by Mongo) with underscores."""
return '_'.join(key.split('.'))
|
def robot_angle_to_mount_angle(robot_angle, mount_zero=90):
"""Convert a robot angle to the corresponding mount angle.
Args:
robot_angle - the commanded direction relative to the robot's centerline
mount_zero - the direction, relative to the robot's centerline, that the
mount points when the mount is commanded to angle=0
Returns the angle, in degrees, to command the mount to point to align to
the commanded robot_angle.
"""
# Replace this naive code with a more robust algorithm:
if robot_angle == 0:
return 90
elif robot_angle == 90:
return 0
elif robot_angle == 110:
return 340
elif robot_angle == 225:
return 225
elif robot_angle == 315:
return 135
return None
|
def get_tags_from_image_ids(image_ids: list=[]):
"""
Get the tags for the given image_ids
Note that nulls and 'latest' is ignored
:param image_ids:
:return:
"""
tags = []
for image in image_ids:
if ('imageTag') in image:
tag = image['imageTag']
if (tag is None) or (tag == 'latest'):
pass
else:
tags = tags + [tag]
return tags
|
def factors(n):
"""
factors(n: int) -> tuple
Expects int, prime or composite
returns a tuple with all prime factors, also 1, and -1 if negative
"""
if not isinstance(n, int): # gotta be int
raise ValueError
if n == 0:
return (0,)
found = [1] # always
if n < 0:
found.append(-1)
n = abs(n)
# chop n down by successive prime factors
divisor = 2
while True:
if n == 1:
break # we're done
if isprime(n):
found.append(n)
break # we're done
while n % divisor == 0 and isprime(divisor):
# divides by same divisor as many times as it takes
found.append(divisor)
n //= divisor # chop it down
if divisor == 2: # even once
divisor = 3
else:
divisor = max(divisor, max(found)) + 2 # always odd
return tuple(found)
|
def part2(data):
"""Solve part 2"""
horizontalPos = 0
depth = 0
aim = 0
for command, val in data:
if(command=="forward"):
horizontalPos += int(val)
depth += (aim * int(val))
elif(command=="up"):
aim -= int(val)
elif(command=="down"):
aim += int(val)
else:
print("PROBLEM")
# print(f'Horizontal Position: {horizontalPos}\nDepth: {depth}')
return horizontalPos * depth
|
def _no_schultz_repetition(contour, allow_unflagged=False):
"""
Step 10. If all values are flagged and no more than one repetition of values exists, excluding
the first and last values, returns True.
>>> contour_with_extrema = [
... [1, {-1, 1}],
... [0, {-1}],
... [2, {1}],
... [0, {-1}],
... [2, {1}],
... [1, {-1, 1}]
... ]
>>> _no_schultz_repetition(contour=contour_with_extrema)
False
"""
if not(allow_unflagged): # Step 10
if all(x[1] for x in contour):
contour_elems = [x[0] for x in contour][1:-1] # Exclude first and last.
return len(contour_elems) <= len(set(contour_elems)) + 1 # Only allow for one repetition.
else:
return False
else: # Used in steps 11/12.
# Still only interested in the flagged values, though ;-)
contour_elems = [x[0] for x in contour if x[1]][1:-1]
return len(contour_elems) <= len(set(contour_elems)) + 1
|
def hash_algorithm(hash_string):
"""
Parse the name of the hash method from the hash string.
The hash string should have the following form ``algorithm:hash``, where
algorithm can be the name of any algorithm known to :mod:`hashlib`.
If the algorithm is omitted or the hash string is None, will default to
``"sha256"``.
Parameters
----------
hash_string : str
The hash string with optional algorithm prepended.
Returns
-------
hash_algorithm : str
The name of the algorithm.
Examples
--------
>>> print(hash_algorithm("qouuwhwd2j192y1lb1iwgowdj2898wd2d9"))
sha256
>>> print(hash_algorithm("md5:qouuwhwd2j192y1lb1iwgowdj2898wd2d9"))
md5
>>> print(hash_algorithm("sha256:qouuwhwd2j192y1lb1iwgowdj2898wd2d9"))
sha256
>>> print(hash_algorithm("SHA256:qouuwhwd2j192y1lb1iwgowdj2898wd2d9"))
sha256
>>> print(hash_algorithm("xxh3_64:qouuwhwd2j192y1lb1iwgowdj2898wd2d9"))
xxh3_64
>>> print(hash_algorithm(None))
sha256
"""
default = "sha256"
if hash_string is None:
algorithm = default
elif ":" not in hash_string:
algorithm = default
else:
algorithm = hash_string.split(":")[0]
return algorithm.lower()
|
def deduplicate(seq):
"""Remove duplicates from list/array while preserving order."""
seen = set()
seen_add = seen.add # For efficiency due to dynamic typing
return [e for e in seq if not (e in seen or seen_add(e))]
|
def recommend_random(query, k=10):
"""
Recommends a list of k random movie ids
"""
return [1, 20, 34, 25]
|
def get_parsec_params_bounds(xte):
"""
get a dictionary of (lower, upper) bounds pair for parsec parameters
:param xte:
:return:
"""
eps_zero = 1e-6
# eps_inf = np.inf
eps_inf = 1e5
parsec_params_bounds = dict()
parsec_params_bounds["rle"] = (eps_zero, eps_inf)
parsec_params_bounds["x_pre"] = (eps_zero, xte)
parsec_params_bounds["y_pre"] = (-xte, xte)
parsec_params_bounds["d2ydx2_pre"] = (-eps_inf, eps_inf)
parsec_params_bounds["th_pre"] = (-89., 89.)
parsec_params_bounds["x_suc"] = (eps_zero, xte)
parsec_params_bounds["y_suc"] = (-xte, xte)
parsec_params_bounds["d2ydx2_suc"] = (-eps_inf, eps_inf)
parsec_params_bounds["th_suc"] = (-89., 89.)
lb = [val[0] for val in parsec_params_bounds.values()] # assuming dictionary follows the order of key addition
ub = [val[1] for val in parsec_params_bounds.values()] # assuming dictionary follows the order of key addition
return parsec_params_bounds, lb, ub
|
def compute_size_by_dict(indices, idx_dict):
"""
Computes the product of the elements in indices based on the dictionary
idx_dict.
Parameters
----------
indices : iterable
Indices to base the product on.
idx_dict : dictionary
Dictionary of index _sizes
Returns
-------
ret : int
The resulting product.
Examples
--------
>>> compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
90
"""
ret = 1
for i in indices: # lgtm [py/iteration-string-and-sequence]
ret *= idx_dict[i]
return ret
|
def sample_width_to_string(sample_width):
"""Convert sample width (bytes) to ALSA format string."""
return {1: 's8', 2: 's16', 4: 's32'}.get(sample_width, None)
|
def get_lists_of_predictions(lis, predictor):
"""
n = len(lis)
this function return n-1 lists
such that the i'th list is a predicted list, which has length n (the same length as lis)
which was predicted from the first i + 1 element in lis
:param lis:
:param predictor:
:return:
"""
predicted_lists = []
for i in range(1, len(lis)):
current_list = lis[: i]
while len(current_list) < len(lis):
current_list.append(predictor.predict(current_list))
predicted_lists.append(current_list)
return predicted_lists
|
def _find_location(block, directive_name, match_func=None):
"""Finds the index of the first instance of directive_name in block.
If no line exists, use None."""
return next((index for index, line in enumerate(block) \
if line and line[0] == directive_name and (match_func is None or match_func(line))), None)
|
def _replace_dmaap_template(dmaap, template_identifier):
"""
This one liner could have been just put inline in the caller but maybe this will get more complex in future
Talked to Mike, default value if key is not found in dmaap key should be {}
"""
return {} if (template_identifier not in dmaap or template_identifier == "<<>>") else dmaap[template_identifier]
|
def findFirstObject(name, dic, rootMode=False):
"""find the first object from the dict"""
if isinstance(dic, dict):
for key in dic.keys():
temp = dic[key]
# check if this is the object we want
if name == key:
if rootMode is True:
return dic
else:
return temp
result = findFirstObject(name, temp, rootMode)
if result != None:
return result
elif isinstance(dic, list):
# go through the list
for value in dic:
result = findFirstObject(name, value, rootMode)
if result != None:
return result
|
def binom(n, k):
"""
Returns the binomial coefficient (n, k).
Program uses a dynamic programming approach.
"""
coeff = {}
for i in range(n + 1):
coeff[i] = {}
coeff[i][0] = 1
for j in range(k + 1):
coeff[j][j] = 1
for i in range(1, n + 1):
for j in range(1, i):
print(i, j)
coeff[i][j] = coeff[i-1][j-1] + coeff[i-1][j]
return coeff[n][k]
|
def countSetBits(n):
"""Counts the number of bits that are set to 1 in a given integer."""
count = 0
while (n):
count += n & 1
n >>= 1
return count
|
def calc_iou(dim: int):
"""
Calculates IoU for two boxes that intersects "querterly" (see ASCII image) in R^dim
x: dimension
"""
I = 0.5**dim
U = 2 - I
return I/U
|
def clean_dev(text):
"""clean developer text, using specific rules"""
text = text.replace("Additional work by:", "")
return text
|
def dp_edit_distance(str1, str2):
"""
Finds the minimum edit displace between
two strings
I use 1
"""
n = len(str1)
m = len(str2)
optimal_edit_distances = {}
i = n - 1
j = m - 1
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if str1[i] == str2[j]:
if i == n - 1 and j == m - 1:
optimal_edit_distances[(i, j)] = 0
elif i == n - 1:
optimal_edit_distances[(i, j)] = optimal_edit_distances[(i, j + 1)]
elif j == m - 1:
optimal_edit_distances[(i, j)] = optimal_edit_distances[(i + 1, j)]
else:
optimal_edit_distances[(i, j)] = optimal_edit_distances[(i + 1, j + 1)]
elif i == n - 1 and j == m - 1:
optimal_edit_distances[(i, j)] = 2 if n == m else 1
elif i == n - 1:
optimal_edit_distances[(i, j)] = 1 + optimal_edit_distances[(i, j + 1)]
elif j == m - 1:
optimal_edit_distances[(i, j)] = 1 + optimal_edit_distances[(i + 1, j)]
else:
optimal_edit_distances[(i, j)] = min(
1 + optimal_edit_distances[(i + 1, j)], # cost of delete
1 + optimal_edit_distances[(i, j + 1)], # cost of insert
2 + optimal_edit_distances[(i + 1, j + 1)], # cost of replace
)
return optimal_edit_distances[(0, 0)]
|
def sum67(nums):
"""Solution to the problem described in http://codingbat.com/prob/p108886
Ex:
>>> sum67([1, 2, 2])
5
>>> sum67([1, 2, 2, 6, 99, 99, 7])
5
>>> sum67([1, 1, 6, 7, 2])
4
:param nums: list
:return: int
"""
sum = 0
between_6_and_7 = False
for n in nums:
if n == 6:
between_6_and_7 = True
if not between_6_and_7:
sum += n
elif n == 7:
between_6_and_7 = False
return sum
|
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode('utf-8')
except AttributeError:
return value
|
def jwt_type_str(repo_type):
"""Return valid JWT type string for given cluster type
Arguments:
repo_type (bool): True/False, depending on wheter it is an EE cluster
or not.
Returns:
String denoting JWT type string.
"""
if repo_type:
return 'RS256'
else:
return 'HS256'
|
def wind_direction(degrees):
""" Convert wind degrees to direction """
try:
degrees = int(degrees)
except ValueError:
return ''
if degrees < 23 or degrees >= 338:
return 'N'
elif degrees < 68:
return 'NE'
elif degrees < 113:
return 'E'
elif degrees < 158:
return 'SE'
elif degrees < 203:
return 'S'
elif degrees < 248:
return 'SW'
elif degrees < 293:
return 'W'
elif degrees < 338:
return 'NW'
|
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet (a=1 ... z=26)
times its distance from start of word.
Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2.
2) The score for a word is the result of applying f to the
scores of the word's two highest scoring letters.
The first parameter to f is the highest letter score,
and the second parameter is the second highest letter score.
Ex. If f returns the sum of its arguments, then the
score for 'adD' is 12
"""
#YOUR CODE HERE
score_list = []
dist = 0
for c in word.lower():
score_list.append((ord(c)-96)*dist)
dist += 1
firstHighest = max(score_list)
del(score_list[score_list.index(firstHighest)])
secondHighest = max(score_list)
return f(firstHighest, secondHighest)
|
def mds_lon_to_xindex(lon, res=1.0):
"""
For a given longitude return the x-index as it was in MDS2/3 in a 1x1 global grid
:param lon: Longitude of the point
:param res: resolution of the field
:type lon: float
:type res: float
:return: grid box index
:rtype: integer
In the western hemisphere, borderline longitudes which fall on grid boundaries are pushed west, except
-180 which goes east. In the eastern hemisphere, they are pushed east, except 180 which goes west.
At 0 degrees they are pushed west.
"""
long_local = lon # round(lon,1)
if long_local == -180:
long_local += 0.001
if long_local == 180:
long_local -= 0.001
if long_local > 0.0:
return int(int(long_local / res) + 180 / res)
else:
return int(int(long_local / res) + 180 / res - 1)
|
def getCoords(vts):
""" Get coordinates of vortices in x, y, z form """
coords = [[], [], []]
for vt in vts:
coords = vt.appCoords(coords)
return coords
|
def get_singular_root(check_word, new_word, keywords):
"""
replaces string with a new string if == check_word
"""
if check_word in keywords:
newlist=[x for x in keywords if x != check_word]
newlist.append(new_word)
return newlist
else:
return keywords
|
def getOneAfterSpace(string):
"""returns next character after a space in given string
(Helper for countInitials)"""
result = ''
reachedSpace = False
for i in range(len(string)):
if string[i] == ' ':
return string[i+1]
return ''
|
def fetch_licenses(fw_conn):
"""Fetch Licenses
Args:
fw_conn (PanDevice): A panos object for device
"""
try:
fw_conn.fetch_licenses_from_license_server()
print('Licenses retrieved from Palo Alto Networks')
return True
except:
print('WARNING: Not able to retrieve licenses!')
return False
|
def construct_email(cfg, query, location, posts):
"""Construct an email message.
Args:
cfg: email configuration.
query: search term used.
location: location to search for jobs.
posts: dictionary containing new job listings.
Returns:
message: string containing the email message.
"""
nposts = len(posts)
# unpack required variables
user, send_to = cfg['email_from'], cfg['email_to']
# unpack optional variables
try:
name = cfg['name']
except KeyError:
# if the `name` key isn't present, then use the first part of the
# email address to address recipient.
name = cfg['email_to'].split('@')[0]
try:
sender_name = cfg['sender_name']
except KeyError:
sender_name = cfg['email_from']
try:
signature = cfg['signature']
except KeyError:
signature = ''
# some temporary variables to correct grammar in the email message
was_were = 'was' if nposts == 1 else 'were'
is_are = 'is' if nposts == 1 else 'are'
job_s = 'job' if nposts == 1 else 'jobs'
listing_s = 'listing' if nposts == 1 else 'listings'
subject = f'Job opportunities: {nposts} new {job_s} posted'
description = '{}. {jobtitle} @ {company}\nLink: {url}\nLocation: {location}\nSnippet: {desc}\n'
posts_content = '\n'.join(description.format(i+1, **p) for i, p in enumerate(posts.values()))
s = (
f'From: {sender_name} <{user}>\n'
f'To: {send_to}\n'
f'Subject: {subject}\n'
f'Hello {name},\n\n'
f'There {is_are} {nposts} new job {listing_s} to review.\n'
f'The following job {listing_s} {was_were} found for {repr(query)} in {repr(location)}:\n\n'
f'{posts_content}\n'
f'{signature}'
)
return s
|
def __exclude_zero(data, labels, delta=0.1):
"""Exclude values <= delta from data and labels
"""
d = []
l = []
for i, x in enumerate(data):
if x > delta:
d.append(x)
l.append(labels[i])
return (d, l)
|
def to_locale(language):
"""
Turns a language name (en-us) into a locale name (en_US).
Logic is derived from Django so be careful about changing it.
"""
p = language.find("-")
if p >= 0:
if len(language[p + 1 :]) > 2:
return "{}_{}".format(
language[:p].lower(),
language[p + 1].upper() + language[p + 2 :].lower(),
)
return "{}_{}".format(language[:p].lower(), language[p + 1 :].upper())
else:
return language.lower()
|
def _subs(count: int, what: str) -> str:
"""DRY."""
return f'{count} validation error{"" if count == 1 else "s"} for {what}'
|
def groupfinder(userid, request):
"""
Default groupfinder implementaion for pyramid applications
:param userid:
:param request:
:return:
"""
if userid and hasattr(request, "user") and request.user:
groups = ["group:%s" % g.id for g in request.user.groups]
return groups
return []
|
def depth(t):
"""
Returns the depth of the tree
"""
if t == None:
return -1
return max(depth(t.left)+1, depth(t.right)+1)
|
def lcs(X: str, Y: str, m: int, n: int) -> str:
"""
Returns the longest common subtring in X and Y
>>> lcs('ancsfg', 'sfac', 6, 4)
'The longest common substring is sf'
>>> lcs('zxcvbn', 'qwerthj', 6, 7)
'There is no common substring in zxcvbn and qwerthj'
>>> lcs('adgjk', 'jkfhda', 5, 6)
'The longest common substring is jk'
"""
lengths = [[0 for j in range(n + 1)] for i in range(m + 1)]
max_length = 0
row, col = 0, 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i - 1] == Y[j - 1]:
lengths[i][j] = lengths[i - 1][j - 1] + 1
if max_length < lengths[i][j]:
max_length = lengths[i][j]
row, col = i, j
else:
lengths[i][j] = 0
if max_length == 0:
return f"There is no common substring in {X} and {Y}"
common_str = ""
while lengths[row][col] != 0:
common_str += X[row - 1]
row -= 1
col -= 1
return f"The longest common substring is {common_str[::-1]}"
|
def filter_nin(value):
"""
:param value: dict
:return: list
This function will compile a users verified NINs to a list of strings.
"""
result = []
for item in value:
verified = item.get('verfied', False)
if verified and type(verified) == bool: # Be sure that it's not something else that evaluates as True in Python
result.append(item['nin'])
return result
|
def _min(*args):
"""Returns the smallest non-negative argument."""
args = [x for x in args if x > -1]
if args:
return min(args)
else:
return -1
|
def get_unlabelled(cluster):
"""
Return the value contained in the key "unlabelled_files"
"""
return cluster['unlabelled_files']
|
def write_vashishta_potential(parameters):
"""Write vashishta potential file from parameters
Parameters
----------
parameters: dict
keys are tuple of elements with the values being the parameters length 14
"""
lines = []
for (e1, e2, e3), params in parameters.items():
if len(params) != 14:
raise ValueError('vashishta three body potential expects 14 parameters')
lines.append(' '.join([e1, e2, e3] + ['{:16.8g}'.format(_) for _ in params]))
return '\n'.join(lines)
|
def get_locale_identifier(tup, sep='_'):
"""The reverse of :func:`parse_locale`. It creates a locale identifier out
of a ``(language, territory, script, variant)`` tuple. Items can be set to
``None`` and trailing ``None``\s can also be left out of the tuple.
>>> get_locale_identifier(('de', 'DE', None, '1999'))
'de_DE_1999'
.. versionadded:: 1.0
:param tup: the tuple as returned by :func:`parse_locale`.
:param sep: the separator for the identifier.
"""
tup = tuple(tup[:4])
lang, territory, script, variant = tup + (None,) * (4 - len(tup))
return sep.join(filter(None, (lang, script, territory, variant)))
|
def rreplace(string: str, old: str, new: str, count: int = 0) -> str:
"""
Return a copy of string with all occurences of substring
old replace by new starting from the right. If the optional
argument count is given only the first count occurences are
replaced.
"""
reverse = string[::-1]
if count:
return reverse.replace(old[::-1], new[::-1], count)[::-1]
return reverse.replace(old[::-1], new[::-1])[::-1]
|
def range_overlap(a_min, a_max, b_min, b_max):
"""Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max)
|
def to_ea(seg, off):
"""
Return value of expression: ((seg<<4) + off)
"""
return (seg << 4) + off
|
def to_bool(s, fallback=None):
"""
:param str s: str to be converted to bool, e.g. "1", "0", "true", "false"
:param T fallback: if s is not recognized as a bool
:return: boolean value, or fallback
:rtype: bool|T
"""
if not s:
return fallback
s = s.lower()
if s in ["1", "true", "yes", "y"]:
return True
if s in ["0", "false", "no", "n"]:
return False
return fallback
|
def crc16_ccitt(crc, data):
"""
https://stackoverflow.com/a/30357446
"""
msb = crc >> 8
lsb = crc & 255
x = data ^ msb
x ^= (x >> 4)
msb = (lsb ^ (x >> 3) ^ (x << 4)) & 255
lsb = (x ^ (x << 5)) & 255
return (msb << 8) + lsb
|
def __overwriteIfSet(overwriteable, overwriter):
"""
Returns overwriteable if overwriter is set, overwriteable otherwise
\nin:
overwriteable=object
overwriter=object
\nout:
overwriter if not None else overwriteable
"""
return overwriteable if overwriter is None else overwriter
|
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
fk_relation = fk_relations_map[(table, table_to_visit)]
unvisited_tables.remove(table_to_visit)
visited_tables.append(table_to_visit)
return fk_relation
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.