content stringlengths 42 6.51k |
|---|
def _get_resource_loc(model_id):
"""returns folder_id and file_id needed to find location of edited photo"""
""" and live photos for version <= Photos 4.0 """
# determine folder where Photos stores edited version
# edited images are stored in:
# Photos Library.photoslibrary/resources/media/version/XX/00/fullsizeoutput_Y.jpeg
# where XX and Y are computed based on RKModelResources.modelId
# file_id (Y in above example) is hex representation of model_id without leading 0x
file_id = hex_id = hex(model_id)[2:]
# folder_id (XX) in above example if first two chars of model_id converted to hex
# and left padded with zeros if < 4 digits
folder_id = hex_id.zfill(4)[0:2]
return folder_id, file_id |
def MoveStr2List(mv: str) -> list:
"""
param:
mv: str [x_src, y_src, x_dst, y_dst]
return:
mv_list: List-> [int: x_src, y_src, x_dst, y_dst]
"""
mv_list = []
if mv != " ":
mv_list = list(map(int, mv[1:-1].split(",")))
return mv_list |
def stations_by_river(stations):
"""creates a dictionary with river names as keys to a list of stations on each one"""
dict_rivers={} #creates empty dictionary
for station in stations:#iterates over all the station objects in the given list
if station.river in dict_rivers.keys(): #checks to see if river is already in dictionary
dict_rivers[station.river].append(station.name) #adds new station name if river has already been added as a key
else:
dict_rivers[station.river]=[station.name] #creates new river key if river isn't in dictionary
return dict_rivers |
def nvalue_to_frequency(nvalue, grid=0.00625e12):
""" converts n value into a frequency
"""
return 193.1e12 + nvalue * grid |
def wires_all_to_all(wires):
"""Wire sequence for the all-to-all pattern"""
sequence = []
for i in range(len(wires)):
for j in range(i + 1, len(wires)):
sequence += [[wires[i], wires[j]]]
return sequence |
def is_dict_empty(dictionary):
"""Validate if a dictionary is empty or no. Returns a boolean value.
Keyword arguments:
dictionary(dict) -- A dictionary to analyze
"""
return dictionary is None or len(dictionary) == 0 |
def get_continuous_segments(array):
"""
Get continuous segments for single frame.
Args:
array (array):
| ordered array with integers representing resids ~ single frame
| e.g.: array = [5, 6, 7, 12, 13, 18, 19, 20]
Returns:
SEGMENTS (list)
list of continuous segments
Example:
| >> gdt.get_continuous_segments([1,2,3,22,23,50,51,52])
| [[1, 2, 3], [22, 23], [50, 51, 52]]
"""
SEGMENTS = []
temp = []
for i in range(len(array)):
temp.append(array[i])
try:
if array[i]+1 != array[i+1]:
SEGMENTS.append(temp)
temp = []
except IndexError:
SEGMENTS.append(temp)
return SEGMENTS |
def count_till_tuple(a):
"""Counts the elements until a tuple is in the list and returns the number"""
counter = 0
for item in a:
if type(item) == tuple:
break
else:
counter += 1
return counter |
def write_input(program: list, noun: int = 12, verb: int = 2) -> list:
"""Write to the second and third positions of a program
:param program: Intcode program to write to
:param noun: int to write to the first position
:param verb: int to write to the second position
:return: Modified Intcode program
"""
program[1] = noun
program[2] = verb
return program |
def gc_content(sequence):
"""Calculate the GC content of a DNA sequence
"""
gc = 0
for base in sequence:
if (base == 'G') or (base == 'C'):
gc += 1
return 100 * (gc / len(sequence)) |
def bitListToBinString(bitList):
"""Converts a list of 0's and 1's to a string of '0's and '1's"""
return ''.join([('0','1')[b] for b in bitList]) |
def mix(parcel, environment, rate, dz):
"""
Mix parcel and environment variables (for entrainment).
Args:
parcel: Parcel value.
environment: Environment value.
rate: Entrainment rate.
dz: Distance descended.
Returns:
Mixed value of the variable.
"""
return parcel + rate * (environment - parcel) * dz |
def approx_less_equal(x,y,tol):
""" approx_equal(x,y,tol) tests whether or not x<=y to within tolerance tol
"""
return (x <= y+tol ) |
def fix_troublesome_units( mv ):
"""This handles many special cases where a variable mv has units which are not understood
by udunits or otherwise troublesome. It replaces the units with ones which work better."""
# Very ad-hoc, but more general would be less safe:
# BES - set 3 does not seem to call it rv_QFLX. It is set3_QFLX_ft0_climos, so make this just a substring search
if not hasattr(mv,'units'):
return mv
if mv.units == "gpm":
mv.units="m"
if mv.units=='mb':
mv.units = 'mbar' # udunits uses mb for something else
if mv.units=='mb/day':
mv.units = 'mbar/day' # udunits uses mb for something else
if mv.units == '(0 - 1)': # as in ERAI obs
mv.units = '1'
if mv.units == '(0-1)': # as in ERAI obs
mv.units = '1'
if mv.units == 'fraction' or mv.units=='dimensionless':
mv.units = '1'
if mv.units == 'mixed': # could mean anything...
mv.units = '1' #... maybe this will work
if mv.units == 'unitless': # could mean anything...
mv.units = '1' #... maybe this will work
if mv.units == 'W/m~S~2~N~' or mv.units == 'W/m~S~2~N':
mv.units = 'W/m^2'
if hasattr(mv,'filetable') and mv.filetable.id().ftid == 'ERA40' and\
mv.id[0:5]=='rv_V_' and mv.units=='meridional wind':
# work around a silly error in ERA40 obs
mv.units = 'm/s'
return mv |
def max_decimal_value_of_binary(num_of_bits):
"""
get max decimal value of a binary string with a fixed length
:param num_of_bits: # of bits
:type num_of_bits: int
:return: max decimal value
:rtype: int
"""
return int('1'*num_of_bits, base=2) |
def my_temperature(k,N):
""" Calculate system temperature.
Args:
Ek (float): kinetic energy
atoms (integer): number of atoms
Return:
float: temperature
"""
return k/(3*N/2) |
def split(a, n):
"""Splits list a into n approximately equal sized lists and returns lenghts of new sublists"""
k, m = divmod(len(a), n)
return [k + int(i < m) for i in range(n)] |
def _can_walk(base, subdirectories):
"""
Determine if the first element of the 'subdirectories' list can be appended
to the 'base' path and still specify a directory.
"""
# Always consider the last part of the subdirectories the filename
if len(subdirectories) < 2:
return False
# Allow any directory name that doesn't contain the <lang> placeholder
return "<lang>" not in subdirectories[0] |
def find_nth(haystack, needle, n):
"""
This function finds the index of the nth instance of a substring
in a string
"""
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start |
def valid_entry(entry, REQUIRED_FIELDS):
""" Validate the row """
if len(REQUIRED_FIELDS) == 0 or REQUIRED_FIELDS[0] == '':
return True
for value in REQUIRED_FIELDS:
if value not in entry or not entry[value]:
return False
return True |
def compare(opening, closing):
"""
This function supplements our multi bracket validation.
If the statement returns False, the function returns False.
"""
if opening == '{' and closing == '}':
return True
if opening == '(' and closing == ')':
return True
if opening == '[' and closing == ']':
return True
return False |
def get_header(oauth: str) -> dict:
"""Returns header with given oauth for the Spotify API"""
return {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {oauth}",
} |
def _split_input_slice(batch_size, work_load_list):
"""Get input slice from the input shape.
Parameters
----------
batch_size : int
The number of samples in a mini-batch.
work_load_list : list of float or int, optional
The list of work load for different devices,
in the same order as ctx
Returns
-------
slices : list of slice
The split slices to get a specific slice.
Raises
------
ValueError
If there are two many splits such that some slice can be empty.
"""
total_work_load = sum(work_load_list)
batch_num_list = [round(work_load * batch_size / total_work_load)
for work_load in work_load_list]
batch_num_sum = sum(batch_num_list)
if batch_num_sum < batch_size:
batch_num_list[-1] += batch_size - batch_num_sum
slices = []
end = 0
for batch_num in batch_num_list:
begin = int(min((end, batch_size)))
end = int(min((begin + batch_num, batch_size)))
if begin >= end:
raise ValueError('Too many slices such that some splits are empty')
slices.append(slice(begin, end))
return slices |
def _written_out_number_below_one_thousand(number: int) -> str:
"""Get a written out string representation of a given number `number` (below one thousand)."""
assert number < 1000
base_numbers_map = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
}
tens_map = {
2: 'twenty',
3: 'thirty',
4: 'forty',
5: 'fifty',
6: 'sixty',
7: 'seventy',
8: 'eighty',
9: 'ninety',
}
written_out_number = ''
hundreds = number // 100
if hundreds > 0:
written_out_number = base_numbers_map[hundreds] + ' hundred'
number %= 100
if number > 0:
if hundreds > 0:
written_out_number += ' and '
tens = number // 10
if tens >= 2:
written_out_number += tens_map[tens]
number %= 10
if number > 0:
written_out_number += '-' + base_numbers_map[number]
else:
written_out_number += base_numbers_map[number]
return written_out_number or base_numbers_map[0] |
def convert_sign(byte):
"""
Convert between signed and unsigned bytes.
"""
if byte < 0:
return 256 + byte
elif byte > 127:
return -256 + byte
return byte |
def uv60_to_uv76(u60, v60): # CIE1960 to CIE1976
""" convert CIE1960 uv to CIE1976 u"v" coordinates
:param u60: u value (CIE1960)
:param v60: v value (CIE1960)
:return: CIE1976 u', v' """
v76 = (3 * v60) / 2
return u60, v76 # CIE1976 u', v' |
def get_formatted_city_country(city, country):
"""Generate a neatly formatted city and country."""
city_country = city + ' ' + country
return city_country.title() |
def long_arr():
"""returns list for testing."""
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 1, 105, 556, 1, 2, 3, 4,
3, 3, 3, 1, 2, 3, 4] |
def _extract_values(obj, key):
"""Pull all values of specified key from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
for item in obj:
extract(item, arr, key)
return arr
results = extract(obj, arr, key)
return results |
def stringify(data):
"""Sanitize collection data into a string format for db storage.
Args:
data (str, bool, numeric, dict, list): Condition values to
squash into strings.
Returns:
list data returns as a comma separated string or '{EMPTY}'
if the list is empty.
All other data types are `str()` converted, including nested
collections in a list.
"""
if isinstance(data, list):
return ", ".join(str(i) for i in data) if data else "{EMPTY}"
# Handle dict, int, float, bool values.
return str(data) |
def _is_bool(s):
"""Check a value is a CSV bool."""
if s.lower() in ['true', 'false']:
return True
else:
return False |
def get_mean(distribution):
"""
Mean is defined as the sum of all the elements of the distribution over its size.
Parameter: a list containing the distribution of the sample or population
Returns: the mean of the distribution
"""
return sum(distribution) / len(distribution) |
def find_min_flow_on_path(adj_l, path):
"""Find min flow on path"""
min_flow = float('inf')
for i in range(len(path) - 1):
curr = path[i]
next = path[i + 1]
min_flow = min(min_flow, adj_l[curr][next])
assert min_flow > 0, f"{min_flow}\n{path}\n{adj_l}"
return min_flow |
def unique(value):
"""
"""
return list(set((value))) |
def text_to_bytes(ustr):
"""
Return bytes value for supplied string.
The intent is that the string may be an ASCII or unicode string, but not
something that has already been encoded.
"""
return ustr.encode('utf-8', 'ignore') |
def group_uniqnames(group):
"""Return group member uniqnames."""
members = group["members"]
return [x["username"].replace("@umich.edu", "") for x in members] |
def check_single_dict_differences(spec, dev, type_str, bidirectional):
"""Compare a single attribute/command
Parameters
----------
spec : dict
A single Attribute/Command dictionary form the specficication
E.g {'disp_level': 'OPERATOR',
'doc_in': 'ON/OFF',
'doc_out': 'Uninitialised',
'dtype_in': 'DevBoolean',
'dtype_out': 'DevVoid',
'name': 'Capture'}
dev : dict
A single Attribute/Command dictionary form the device
E.g {'disp_level': 'OPERATOR',
'doc_in': 'ON/OFF',
'doc_out': 'Uninitialised',
'dtype_in': 'DevBoolean',
'dtype_out': 'DevVoid',
'name': 'Capture'}
type_str : str
Either "Command" or "Attribute"
bidirectional: bool
Whether to include details on the device that is not in the specification
Returns
-------
issues : list
A list of strings describing the issues, empty list for no issues
"""
assert spec["name"] == dev["name"]
issues = []
if spec != dev:
spec_keys = set(spec.keys())
dev_keys = set(dev.keys())
keys_not_in_spec = spec_keys.difference(dev_keys)
keys_not_in_dev = dev_keys.difference(spec_keys)
mutual_keys = spec_keys.intersection(dev_keys)
if keys_not_in_spec:
keys_not_in_spec = sorted(keys_not_in_spec)
issues.append(
"{} [{}] differs, specification has keys [{}] but it's "
"not in device".format(type_str, spec["name"], ",".join(keys_not_in_spec))
)
if keys_not_in_dev and bidirectional:
keys_not_in_dev = sorted(keys_not_in_dev)
issues.append(
"{} [{}] differs, device has keys [{}] but it's "
"not in the specification".format(
type_str, spec["name"], ",".join(keys_not_in_dev)
)
)
for key in mutual_keys:
if dev[key] != spec[key]:
issues.append("{} [{}] differs:".format(type_str, spec["name"]))
issues.append(
"\t{}:\n\t\tspecification: {}\n\t\tdevice: {}".format(
key, spec[key], dev[key]
)
)
return issues |
def number_less_equal(element, value, score):
"""Check if element is lower than or equal config value.
Args:
element (float) : Usually vcf record
value (float) : Config value
score (integer) : config score
Return:
Float: Score
"""
if element <= value:
return score |
def parse_gender(gender):
"""
Parse gender, 1 for male, 0 for female.
:param gender:
:return:
"""
if not gender:
return None
gender = gender.lower()
if gender == 'male' or gender == 'm':
return 1
elif gender == 'female' or gender == 'f':
return 0
else:
return None |
def tr_w2vf(opts):
"""
:param opts: counts+post dictionary of params
:return: dictionary of params translated to w2vecf (also removing redundant ones)
"""
tr_dict={
"sub": "sample",\
"thr": "min-count"
}
new_dict=opts.copy()
for k in opts:
if k in tr_dict.keys():
new_dict[tr_dict[k]] = opts[k]
new_dict.pop(k)
return new_dict |
def isInstance( obj, classType ):
"""
Returns a boolean whether or not 'obj' is an instance of class
'classType' (not as string, pass as real class!).
"""
return isinstance( obj, classType ) |
def _notnone(x):
"""Convenience hack for checking if x is not none; needed because numpy
arrays will, at some point, return arrays for x != None."""
return type(x) != type(None) |
def prediction_string(predicted_boxes, confidences):
"""
:param predicted_boxes: [[x1, y1, w1, h1], [x2, y2, w2, h2], ...] list of predicted boxes coordinates
:param confidences: [c1, c2, ...] list of confidence values for the predicted boxes
:returns: prediction string 'c1 x1 y1 w1 h1 c2 x2 y2 w2 h2 ...'
"""
prediction_string = ""
for c, box in zip(confidences, predicted_boxes):
prediction_string += (
" " + str(c) + " " + " ".join([str(b) for b in box])
)
return prediction_string[1:] |
def str_to_bool(string: str) -> bool:
"""
Converts string to bool.
Args:
string (str): ("Yes", "No", "True", "False", "1", "0")
Returns:
bool
"""
if isinstance(string, bool):
return string
if string is None:
return False
if string.lower() in ("yes", "true", "t", "y", "1"):
return True
elif string.lower() in ("no", "false", "f", "n", "0"):
return False
return False |
def RemoveDuplicated(s1):
"""
example:
s1=['a // a', 'b // a', None, 'non']
"""
s2=list()
for x in s1:
print(x)
if x =='non':
s2.append('')
elif x is None:
s2.append('')
else:
if "//" in x:
s0= x.split(' // ')
s0 = [x.strip() for x in s0]
s01= list(set(s0))
if len(s01)==1:
s2.append(s01[0])
else:
s2.append(' // '.join(s01))
else:
s2.append(x)
return s2 |
def get_dcgm_cfg(k8s_conf):
"""
Returns Grafana enablement choice
:return: true/false
"""
if k8s_conf.get('enable_dcgm') :
return k8s_conf['enable_dcgm'] |
def busqueda_binaria(inicio, final, n, ln_ordenada, counter=0):
""" Search a number in a list in a more eficient way """
# [2, 22, 30, 50, 100]
counter += 1
medio = (inicio + final) // 2
if inicio >= final:
return False, counter
if ln_ordenada[medio] == n:
return True, counter
elif ln_ordenada[medio] < n:
return busqueda_binaria(medio + 1, final, n, ln_ordenada, counter)
else:
return busqueda_binaria(inicio, medio - 1, n, ln_ordenada, counter) |
def solve(want, func, stop):
"""Returns values of x for which func(x) == want
for x in the range 0..(stop-1)"""
solutions = list()
for x in range(stop):
if func(x) == want:
solutions.append(x)
return solutions |
def format_int(seconds):
"""
source: http://stackoverflow.com/a/13756038 (with modifications)
formatting seconds to human-readable string
:param seconds: seconds to be reformatted
:return: formatted string
"""
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('minute', 60),
('second', 1)
]
strings = []
for period_name, period_seconds in periods:
if seconds >= period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
if period_value == 1:
strings.append("%s %s" % (period_value, period_name))
else:
strings.append("%s %ss" % (period_value, period_name))
if not strings:
strings = ['0 seconds']
return ", ".join(strings) |
def intToByte(i):
"""
int -> byte
Determines whether to use chr() or bytes() to return a bytes object.
"""
return chr(i) if hasattr(bytes(), 'encode') else bytes([i]) |
def classname(obj):
"""Returns name of object's class as string."""
return type(obj).__name__ |
def which_ax(x):
"""for plotting on the correct ax"""
y = 0
y1 = 1
if x >= 3 and x < 6:
x -= 3
y = 2
y1 = 3
if x >= 6 and x < 9:
x -= 6
y = 4
y1 = 5
if x >= 9:
x -= 9
return x, y, y1 |
def is_supported_key_type(key):
"""
checks if the given key type is supported
Supported Types:
- int
- float
- str
- tuple
- NoneType
"""
if (
isinstance(key, (int, float, str, tuple, )) or
key is None
):
return True
return False |
def to_fahrenheit(celsius_temp):
"""convert celsius to degrees fahrenheit."""
return 1.8 * (celsius_temp) + 32 |
def value_tuples_to_lists(scope: dict):
"""
We need to convert all tuples to list because the tuple is serialized as list in json
and after de-serialization the tuple objects will become lists
"""
data = scope.get("data", None)
if data is not None:
data = [list(d) for d in data]
scope["data"] = data
children = scope.get("children", None)
if children is not None:
for c in children:
value_tuples_to_lists(c)
return scope |
def calc_valid_check(i, n):
"""Calculate the iteration number of the i'th validation check out of n checks."""
if n==1: return 0
else: return ((n-1)-i)*(100/(n-1)) |
def call_headers(include_content_type):
""" Create API call headers
@includeContentType boolean: flag determines whether or not the
content-type header is included
"""
if include_content_type is True:
header = {
'content-type': 'application/json',
'X-Requested-With': 'XmlHttpRequest'
}
else:
header = {
'X-Requested-With': 'XmlHttpRequest'
}
return header |
def getConfigProperty(config, *args, default=None):
"""Returns property from config dictionary"""
configElement = config
for arg in args:
if arg not in configElement:
return default
configElement = configElement[arg]
return configElement |
def find_suspicious_combinations(floss_output: str, suspicious_apis: dict) -> dict:
"""
Find all suspicious API combinations and return them as a dict.
Params
------
floss_output : str
Output generated by FLOSS string extraction
suspicious_apis : dict
Dictionary of suspicious API call combinations in the form of
{"description": [["this", "or", "this"], ["and", "either", "of", "these"]]}
Returns
-------
dict
A dictionary with all suspicious combinations
"""
suspicious_combinations_found = {}
# Cache single suspicious API for easier comparison if a complete check is needed
single_suspicious_apis = set()
for suspicious_api_combinations in suspicious_apis.values():
for suspicious_api_ors in suspicious_api_combinations:
for suspicious_api in suspicious_api_ors:
single_suspicious_apis.add(suspicious_api)
# Try to find all calls to suspicious APIs in the FLOSS output
suspicious_apis_found = set()
for line in floss_output.split('\n'):
if line in single_suspicious_apis:
suspicious_apis_found.add(line)
# Now let's check if enough APIs are found to form the suspicious combinations
for description, suspicious_api_combinations in suspicious_apis.items():
suspicious_combination = []
for ors in suspicious_api_combinations:
for api in ors:
if api in suspicious_apis_found:
suspicious_combination.append(api)
break
else:
# Found at least one of the OR clauses
break
else:
# Found all of the AND clauses, note exact combination
suspicious_combinations_found[description] = suspicious_combination
return suspicious_combinations_found |
def parseFloatList(string):
"""Parses a comma-separated string of floats into a list"""
splitarray = string.split(",")
float_list = []
for elem in splitarray:
float_list.append(float(elem))
return float_list |
def all_colors_in_combination(colors, given):
""" Returns true if all the colors in colors are part of the
given combination. False otherwise."""
number_of_colors = len(colors)
starting_position = 0
while starting_position < number_of_colors:
if colors[starting_position] not in given:
return False
starting_position += 1
return True |
def separateComment(instruction):
"""Separates any comment from the line.
Args:
instructions(str): the line to seperate comment from.
Return:
tuple(Bool, tuple) - (0)==True if comment found, (1) contains a
tuple with (instruction, comment).
"""
comment_char = None
if '!' in instruction:
comment_char = '!'
if '#' in instruction:
comment_char = '#'
if not comment_char is None:
split = instruction.split(comment_char, 1)
else:
split = [instruction]
comment_char = ''
if len(split) > 1:
return split[0].strip(), split[1].strip(), comment_char
else:
return split[0].strip(), '', comment_char |
def imbalances_after_move(ws, p_src, p_tgt, nbr_p, imbs):
"""Returns the imbalances if [ws] is moved from [p_src] to
[p_tgt]. [ws] must be normalized.
"""
new_imbs = [list(imbs_per_c) for imbs_per_c in imbs]
for w, imbs_per_c in zip(ws, new_imbs):
imbs_per_c[p_src] -= nbr_p * w
imbs_per_c[p_tgt] += nbr_p * w
return new_imbs |
def ParseSpec(arg_list):
"""Given an argument list, return a string -> string dictionary."""
# The format string is passed the cell value. Escaped as HTML?
d = {}
for s in arg_list:
try:
name, value = s.split(' ', 1)
except ValueError:
raise RuntimeError('Invalid column format %r' % s)
d[name] = value
return d |
def create_device_name(tracked_asset_pair: str) -> str:
"""Create the device name for a given tracked asset pair."""
return f"{tracked_asset_pair.split('/')[0]} {tracked_asset_pair.split('/')[1]}" |
def check_k(num_list, k):
"""Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Args:
num_list(list): A list of numbers (int)
k (int): The value to compare with
Returns:
ret_bool(bool): True if any two numbers from the list add up to k, False otherwise.
Raise:
Exception: I guess this is redundant
"""
sorted_list = sorted(num_list)
i = 0
j = len(num_list) - 1
ret_bool = False
while i<j:
sum_ij = sorted_list[i] + sorted_list[j]
if sum_ij < k:
i+=1
continue
elif sum_ij > k:
j-=1
continue
elif sum_ij == k:
ret_bool = True
break
else:
raise Exception("This was not supposed to be executed.")
return ret_bool |
def reorg_output_files(output_files):
"""
assumes output_files is a list or set of tuples:
(filename, line, path, write_object)
reorganize into a tuple (filename, [dict of last 3 items])
"""
for i in range(0, len(output_files)):
t = output_files[i]
output_files[i] = (t[0],) + (dict(line=t[1], path=t[2], write=t[3]),)
return output_files |
def unique_filename(filename, upload_id):
"""Replace filename with upload_id, preserving file extension if any.
Args:
filename (str): Original filename
upload_id (str): Unique upload ID
Returns:
str: An upload_id based filename
"""
if "." in filename:
return ".".join([upload_id, filename.rsplit(".", 1)[1]])
else:
return upload_id |
def point_in_area(line1, line2, x, y, width1, width2):
"""Check if intersection point is on defined area."""
x1, x2, x3, x4 = line1[0][0], line1[1][0], line2[0][0], line2[1][0]
y1, y2, y3, y4 = line1[0][1], line1[1][1], line2[0][1], line2[1][1]
return (min(x1, x2) <= x <= max(x1, x2) and min(x3, x4) <= x <= max(x3, x4) and
min(y1, y2) <= y <= max(y1, y2) and min(y3, y4) <= y <= max(y3, y4)) |
def fake_auth(auth_url, key):
"""
Return a false header required by authentication process
"""
return {'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer eyJraWQiOiIyMDIwMDMyNjE4MjgiLCJhbGciOiJSUzI1NiJ9.e'} |
def limiter(Q1,Q2,Q3,num,denom):
"""Use this method to apply the minmod limiter."""
if (num > 0 and denom > 0) or (num < 0 and denom < 0):
Q_r = Q1+min(num/denom,1)/2*(Q2-Q3)
else:
Q_r = Q1
return Q_r |
def remove_duplicates(res: list, remove_duplicate_results: bool):
""" Removes duplicate configurations from the results """
if not remove_duplicate_results:
return res
unique_res = list()
for result in res:
if result not in unique_res:
unique_res.append(result)
return unique_res |
def import_class(cl: str):
"""Import a class by name"""
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname) |
def encode_mv(vals):
"""For multivalues, values are wrapped in '$' and separated using ';'
Literal '$' values are represented with '$$'"""
s = ""
for val in vals:
val = val.replace('$', '$$')
if len(s) > 0:
s += ';'
s += '$' + val + '$'
return s |
def generate_configmap(instances):
""" Create the drain-machine-status configmap """
return {
'apiVersion': 'v1',
'kind': 'ConfigMap',
'metadata': {
'name': 'drain-machine-status',
},
'data': {
'terminating': " ".join(instances),
},
} |
def get_id_from_about(filename):
"""
Extract id from local filename.
"""
return filename.replace("_about.html", "").split("/")[-1] |
def selfOnParams(check, self_on_function_params, add_semicolon=False):
""" """
if self_on_function_params:
comma = ""
if add_semicolon:
comma = ","
if len(check) > 2:
return check + comma
else:
return "" |
def pluck(dictlist, key):
"""Extracts a list of dictionary values from a list of dictionaries.
::
>>> dlist = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}]
>>> pluck(dlist, 'id')
[1, 2]
"""
return [d[key] for d in dictlist] |
def calculated_hp(base_stat, level, iv, effort, nature=None):
"""Similar to `calculated_stat`, except with a slightly different formula
used specifically for HP.
"""
# Shedinja's base stat of 1 is special; its HP is always 1
if base_stat == 1:
return 1
return (base_stat * 2 + iv + effort // 4) * level // 100 + 10 + level |
def _merge_elements(elm_def):
""" Combine element with it's base elements.
"""
while 'base' in elm_def:
base_elm = elm_def['base']
elm_def.pop('base')
elm_def['paths'] = elm_def.get('paths', []) + base_elm.get('paths', [])
elm_def['labels'] = elm_def.get('labels', []) + base_elm.get('labels', [])
elm_def['shapes'] = elm_def.get('shapes', []) + base_elm.get('shapes', [])
# New anchors with same name should overwrite old
d = base_elm.get('anchors', {}).copy()
d.update(elm_def.get('anchors', {}))
elm_def['anchors'] = d
for i in base_elm:
# Everything that's not a list. New key/values overwrite old.
# If base has a base, will be added and loop will pick it up.
if i not in ['paths', 'labels', 'shapes', 'anchors'] and i not in elm_def:
elm_def[i] = base_elm[i]
return elm_def |
def xstr(s):
"""If ``s`` is None return empty string.
:param s: string
:return: s or an empty string if s is None
:rtype: str
:Example:
>>> xstr(None)
''
"""
return '' if s is None else str(s) |
def id_to_int(id_):
"""
Convert a ZMQ client ID to printable integer
This is needed to log client IDs while maintaining Python cross-version
compatibility (so we can't use bytes.hex() for example)
"""
i = 0
for c in id_:
if not isinstance(c, int):
c = ord(c)
i = (i << 8) + c
return i |
def adjust_skater_count_in_overtime(game, time, skr_count):
"""
Adjusts skater count in regular season overtimes according to skater
situation at the end of regulation and/or previous second.
"""
if game['season_type'] == 'RS' and time >= 3601:
# if the same number of skaters is on ice for both teams, we're setting
# the skater situation to 3-on-3 regardless
# NB: this doesn't account for penalties expiring in overtime that may
# lead to legitimate 4-on-4 (or even 5-on-5) situations since we have
# no information when exactly the play was interrupted, i.e. faceoff
# times
if skr_count['home'] == skr_count['road']:
skr_count['home'] = 3
skr_count['road'] = 3
# if home team is on a 5-on-4 power play change that to a 4-on-3
# NB: other player advantages (4-on-3, 5-on-3) remain unchanged
elif skr_count['home'] > skr_count['road']:
if skr_count['home'] == 5 and skr_count['road'] == 4:
skr_count['home'] = 4
skr_count['road'] = 3
# if road team is on a 5-on-4 power play change that to a 4-on-3
# NB: other player advantages (4-on-3, 5-on-3) remain unchanged
elif skr_count['road'] > skr_count['home']:
if skr_count['road'] == 5 and skr_count['home'] == 4:
skr_count['road'] = 4
skr_count['home'] = 3
return True
else:
return False |
def leaf_fanouts(conn_graph_facts):
"""
@summary: Fixture for getting the list of leaf fanout switches
@param conn_graph_facts: Topology connectivity information
@return: Return the list of leaf fanout switches
"""
leaf_fanouts = []
conn_facts = conn_graph_facts['device_conn']
""" for each interface of DUT """
for _, value in conn_facts.items():
for _, val in value.items():
peer_device = val['peerdevice']
if peer_device not in leaf_fanouts:
leaf_fanouts.append(peer_device)
return leaf_fanouts |
def shorten_sha(str):
"""
return the short (7-character) version of a git sha
"""
return str[:7] |
def enc(s):
"""UTF-8 encode a string."""
return s.encode("utf-8") |
def add_list_spacing(tokens):
"""Parse action to add spacing after seps but not elsewhere."""
out = []
for i, tok in enumerate(tokens):
out.append(tok)
if i % 2 == 1 and i < len(tokens) - 1:
out.append(" ")
return "".join(out) |
def get_index(lis, argument):
"""Find the index of an item, given either the item or index as an argument.
Particularly useful as a wrapper for arguments like channel or axis.
Parameters
----------
lis : list
List to parse.
argument : int or object
Argument.
Returns
-------
int
Index of chosen object.
"""
# get channel
if isinstance(argument, int):
if -len(lis) <= argument < len(lis):
return argument
else:
raise IndexError("index {0} incompatible with length {1}".format(argument, len(lis)))
else:
return lis.index(argument) |
def parse_size(s):
"""
Converts a string to an integer
Example input can either be: '(1234)' or '1234'
Example output: 1234
"""
s = s.replace('(', '').replace(')', '')
return int(s) |
def flipslash(value):
""" Convert all backslashes to forward slashes (for apache) """
return value.replace("\\", '/') |
def remove_padding(data: bytes, block_n_bytes: int) -> bytes:
"""Removes 0x80... padding according to NIST 800-38A"""
if len(data) % block_n_bytes != 0:
raise ValueError("Invalid data")
for i in range(len(data) - 1, -1, -1):
if data[i] == 0x80:
return data[:i]
elif data[i] != 0x00:
raise ValueError("Invalid padding")
raise ValueError("Invalid padding") |
def first_greater_than(array, x):
"""array must be sorted"""
array_rev = array[:]
array_rev.reverse()
best = None
for elt in array_rev:
if elt >= x:
best = elt
elif best is not None:
return best
return best |
def validate_ip(s):
"""
Validate the IP address of the correct format
Arguments:
s -- dot decimal IP address in string
Returns:
True if valid; False otherwise
"""
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True |
def complementBase(c):
"""
Returns the complement RNA character of c (without GU base pairs)
"""
retChar = ""
if c == "A":
retChar = "U"
elif c == "U":
retChar = "A"
elif c == "C":
retChar = "G"
elif c == "G":
retChar = "C"
return retChar |
def has_duplicates2(t):
"""Checks whether any element appears more than once in a sequence.
Faster version using a set.
t: sequence
"""
return len(set(t)) < len(t) |
def normalize_weekly(data):
"""Normalization for dining menu data"""
if "tblMenu" not in data["result_data"]["Document"]:
data["result_data"]["Document"]["tblMenu"] = []
if isinstance(data["result_data"]["Document"]["tblMenu"], dict):
data["result_data"]["Document"]["tblMenu"] = [data["result_data"]["Document"]["tblMenu"]]
for day in data["result_data"]["Document"]["tblMenu"]:
if "tblDayPart" not in day:
continue
if isinstance(day["tblDayPart"], dict):
day["tblDayPart"] = [day["tblDayPart"]]
for meal in day["tblDayPart"]:
if isinstance(meal["tblStation"], dict):
meal["tblStation"] = [meal["tblStation"]]
for station in meal["tblStation"]:
if isinstance(station["tblItem"], dict):
station["tblItem"] = [station["tblItem"]]
return data |
def compute_loss_ref_gen(generation, reflection):
"""
Compute loss percentage based on a generation count and a reflection count.
"""
if generation != 0:
loss = (1.0 - reflection / generation)*100
else:
loss = (1.0 - reflection / (generation+0.1))*100
return loss if loss >=0 else 0 |
def bin_up_factor_tag_from_bin_up_factor(bin_up_factor):
"""Generate a bin up tag, to customize phase names based on the resolutioon the image is binned up by for faster \
run times.
This changes the phase name 'phase_name' as follows:
bin_up_factor = 1 -> phase_name
bin_up_factor = 2 -> phase_name_bin_up_factor_2
bin_up_factor = 2 -> phase_name_bin_up_factor_2
"""
if bin_up_factor == 1 or bin_up_factor is None:
return ""
else:
return "__bin_" + str(bin_up_factor) |
def PacketType(byte):
"""
Retrieve the message type from the first byte of the fixed header.
"""
if byte != None:
rc = byte[0] >> 4
else:
rc = None
return rc |
def get_cn(r_n_metric, os):
"""
Reference page number: 5
Parameters
------------------------------
r_n_metric: (``float``)
Solar radiation in W/m^2
os: (``bool``)
Boolean which indicates whether to calculate G for short reference or tall reference
Returns
------------------------------
cn: (``int``)
Numerator constant
"""
cn = None
daytime = r_n_metric > 5
if os:
if daytime > 5:
cn = 37
return cn
else:
cn = 37
return cn
else:
if daytime > 5:
cn = 66
return cn
else:
cn = 66
return cn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.