content
stringlengths 42
6.51k
|
---|
def floatOrNone(val):
"""
Returns None if val is None and cast it into float otherwise.
"""
if val is None:
return None
else:
return float(val)
|
def generate_competitor_configs(count):
""" Returns a dict containing plugin configs for the given number of
competitors. """
to_return = []
for i in range(count):
competitor_config = {
"log_name": "results/memory_copy_competitor_%d.json" % (i,),
"filename": "./bin/memory_copy.so",
"thread_count": 512,
"block_count": 512,
"additional_info": {
"buffer_size": 1024 * 1024 * 1024,
"copy_subdivisions": 1,
"sync_every_copy": False
}
}
to_return.append(competitor_config)
return to_return
|
def generate_initial_states(matrices):
"""Reads a list of matrices and outputs a list of tuples of initial states
each element in the list will be a tuple ([flavours hadron 1, flavours hadron 2])
for each matrix
"""
initial_flavours = []
for matrix in matrices:
initials = matrix.initial_states
flavs_1, flavs_2 = zip(*initials)
if matrix.mirror_initial_states:
m2, m1 = zip(*initials)
flavs_1 += m1
flavs_2 += m2
initial_flavours.append((flavs_1, flavs_2))
return initial_flavours
|
def Imu_I0c1c2c3c4(mu, c):
"""
I(mu, c) where c = (I0, c1, c2, c3, c4)
"""
return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.))
|
def terminal_format(args):
"""
args is a list of tuples and returns one string line.
2-tuples are "{x[1]}".format(x[0]) i.e. value, format
3-tuples are "{}={x[2]}".format(x[0],x[1]) i.e. label, value, format
"""
line = ""
for x in args:
if len(x) == 3:
line += ("{}={"+str(x[2])+"}").format(str(x[0]), x[1])
elif len(x) == 2:
line += ("{"+str(x[1])+"}").format(x[0])
line += " "
return line
|
def fix_model_name(name: str):
"""
Takes a filename string and makes it safe for further use. This method will probably need expanding.
E.g. "modflow .1.zip" becomes "modflow__1.zip". Also file names will be truncated to 40 characters.
@param name: the name of the file uploaded by the user
@return: that name, made safe for the app to use
"""
dots = name.count('.') - 1 # for when someone decides to put a dot in the filename
name = name.replace(" ", "-").replace("_", "-").replace(".", "-", dots) # remove problematic characters
if len(name) > 44: # truncate name to 40 characters long (+4 for ".zip")
split = name.split('.')
split[0] = split[0][0:40]
name = ".".join(split)
return name
|
def filter_traceback_list(tl):
"""
Returns the subset of `tl` that originates in creator-written files, as
opposed to those portions that come from Ren'Py itself.
"""
rv = [ ]
for t in tl:
filename = t[0]
if filename.endswith(".rpy") and not filename.replace("\\", "/").startswith("common/"):
rv.append(t)
return rv
|
def setActiveUser(user):
"""
Postavlja trenutno aktivnog korisnika
"""
global _currentUser
_currentUser = user
return _currentUser
|
def _ValidateReplicationFlags(flag_dict):
"""Verifies correct usage of the bigtable replication flags."""
return (not flag_dict['bigtable_replication_cluster'] or
flag_dict['bigtable_replication_cluster_zone'])
|
def match_pattern(input_string: str, pattern: str) -> bool:
"""
uses bottom-up dynamic programming solution for matching the input
string with a given pattern.
Runtime: O(len(input_string)*len(pattern))
Arguments
--------
input_string: str, any string which should be compared with the pattern
pattern: str, the string that represents a pattern and may contain
'.' for single character matches and '*' for zero or more of preceding character
matches
Note
----
the pattern cannot start with a '*',
because there should be at least one character before *
Returns
-------
A Boolean denoting whether the given string follows the pattern
Examples
-------
>>> match_pattern("aab", "c*a*b")
True
>>> match_pattern("dabc", "*abc")
False
>>> match_pattern("aaa", "aa")
False
>>> match_pattern("aaa", "a.a")
True
>>> match_pattern("aaab", "aa*")
False
>>> match_pattern("aaab", ".*")
True
>>> match_pattern("a", "bbbb")
False
>>> match_pattern("", "bbbb")
False
>>> match_pattern("a", "")
False
>>> match_pattern("", "")
True
"""
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
dp = [[0 for i in range(len_pattern)] for j in range(len_string)]
# since string of zero length match pattern of zero length
dp[0][0] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1, len_string):
dp[i][0] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1, len_pattern):
dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1, len_string):
for j in range(1, len_pattern):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
dp[i][j] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = 0
else:
dp[i][j] = 0
return bool(dp[-1][-1])
|
def _get_json_schema_node_id(fully_qualified_name: str) -> str:
"""Returns the reference id (i.e. HTML fragment id) for a schema."""
return 'json-%s' % (fully_qualified_name,)
|
def apart_dict(raw_content, key, value):
"""
"""
result = list();
if type(raw_content) == type({}):
if value == raw_content.get(key):
result.append(raw_content)
else:
for k in raw_content.keys():
temp_result = apart_dict(raw_content[k], key, value)
if temp_result:
result.extend(temp_result)
if type(raw_content) == type([]):
for item in raw_content:
if type(item) == type({}):
if value == item.get(key):
result.append(item)
else:
for k in item.keys():
temp_result = apart_dict(item[k], key, value)
if temp_result:
result.extend(temp_result)
return result
|
def column_is_primary_key(column):
"""Returns whether a column object is marked as a primary key."""
primary_key = column["is primary key"]
if isinstance(primary_key, str):
primary_key = primary_key.lower()
if primary_key in {"y", "n", "yes", "no", "-"}:
primary_key = primary_key in {"y", "yes"}
else:
raise ValueError("primary key should be a boolean: " + primary_key)
return primary_key
|
def device(portnum):
"""Turn a port number into a device name"""
#the "//./COMx" format is required for devices >= 9
#not all versions of windows seem to support this propperly
#so that the first few ports are used with the DOS device name
if portnum < 9:
return 'COM%d' % (portnum+1) #numbers are transformed to a string
else:
return r'\\.\COM%d' % (portnum+1)
|
def format_single(v):
"""
This function formats single values
for the namelist writeout
"""
if isinstance(v, int):
# Boolean is a subclass of int
if isinstance(v, bool):
if v:
return ".true."
else:
return ".false."
else:
# Format as integer
return "{:d}".format(v)
elif isinstance(v, float):
# Truncate at 4 decimals
return "{:5.4f}".format(v)
else:
# Return the stringvalue with single quotes
return "'{:s}'".format(v)
|
def correct_values_ERA5(x, y, options):
"""
"""
z = x
if x in ['tp', 'sd', 'e']:
y = y * 1000
z = options[x]
elif x in ['t2m']:
y = y - 273.15
z = options[x]
elif x in ['u10', 'v10']:
z = options[x]
return z,y
|
def original_solution(n):
"""Return the nth fibonacci number."""
if n == 1:
return 0
a, b = 0, 1
for i in range(1, n - 1):
a, b = b, (a + b)
return b
|
def to_units(number):
"""Convert a string to numbers."""
UNITS = ('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y')
unit = 0
while number >= 1024.:
unit += 1
number = number // 1024.
if unit == len(UNITS) - 1:
break
if unit:
return '%.2f%s' % (number, UNITS[unit])
return '%d' % number
|
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: ?
Space Complexity: ?
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
## Dynamic Solution - Kadane's Algorithm
if nums == None:
return 0
if len(nums) == 0:
return 0
nums_size = len(nums)
max_so_far = nums[0]
curr_sum = 0
for i in range(0, nums_size):
curr_sum = curr_sum + nums[i]
if curr_sum < 0:
curr_sum = 0
elif (max_so_far < curr_sum):
max_so_far = curr_sum
for i in nums:
if max_so_far < i:
max_so_far = nums[i]
return max_so_far
|
def is_complex(data):
"""
Test whether the data has a complex value in it or not.
:param data:
:return:
"""
cpx_check = False
for dd in data:
cpx_check |= isinstance(dd, complex)
return cpx_check
|
def get_right_list_elements(result):
"""Some of the results are empty - therefore the try-except. Others are lists with more than one element nd only
specific elements are relevant.
Parameters
----------
- result : dict of lists
result of the xpath elements.
Returns
-------
- result : dict of strings
"""
for key in [
"title",
"ort",
"merkmale",
]: # ,'weitere_eigenschaften','beschreibung']:
try:
result[key] = result[key][0]
except:
pass
for key in ["preis", "anzahl_raeume", "wohnflaeche", "grundstuecksflaeche"]:
try:
result[key] = result[key][1]
except:
pass
return result
|
def SplitAbstract(path):
"""Splits an already 'abstract' path.
Args:
path: path to split.
Returns:
Text elements of the path.
"""
return path.split(".")
|
def fill_spaces( s:str ) ->str:
"""
Returns a (str) name
Takes a (str)name
"""
newS: list = s.split(' ')
if len(newS) == 1:
return s
else:
s2:str = newS[0]
for i in range(1,len(newS)-1):
s2 += "_" + newS[i]
return s2
|
def passenger_assigned(state):
"""
Check if passenger was assinged v2
"""
return state[-1] == 1
|
def search_for_item(project):
"""Generate a string search key for a project"""
elements = []
elements.append(project['name'])
return u' '.join(elements)
|
def ordenar(comparacion: dict, length: int = 10) -> dict:
"""Sort the results"""
# Save 10 films ordered by similarity
orden_similitud = sorted(comparacion['pels'],
key=lambda x: x['similitud'],
reverse=True)[:length]
comparacion['pels'] = orden_similitud
#print([x['pel']['title'] for x in comparacion['pels']])
return comparacion
|
def remove_duplicated_names(name_list):
"""
From a list of list of names remove the items that are duplicated
:param name_list: list of list of names to investigate
:return duplicates_removed: list of list of names freed of duplicates
"""
flattened_list = [item for sublist in name_list for item in sublist]
list_duplicated = [item for item in flattened_list
if flattened_list.count(item) > 1]
duplicates_removed = []
for names in name_list:
duplicates_removed.append([name for name in names
if name not in list_duplicated])
return duplicates_removed
|
def init_model(N, y0):
"""Initialize the SIR model.
:param int y0: Infected rate at initial time step.
:param int N: Population
:returns: Model at initial time step
:rtype: tuple(int, int, int)
"""
return N - y0, y0, 0
|
def _warning_formatter(message, category, filename, lineno, line=None):
"""Patch warning formatting to not mention itself."""
return f'{filename}:{lineno}: {category.__name__}: {message}\n'
|
def scenario_inputs(scenarios):
"""Parse the scenarios and feed the data to the test function."""
return [test_input[0] for test_input in scenarios]
|
def get_missing_header_list(input_header, spec_rows):
"""Get list of required headers that are missing
Returns:
field_list (list): list of names of missing required headers
"""
field_list = []
# check each spec variable if required
for row in spec_rows:
field_name = row['Structured name']
is_required = row['Required']
if is_required == "Yes":
if field_name not in input_header:
field_list.append(field_name)
return field_list
|
def main(distancia):
"""
Retorna o numero do sensor que a particula atingiu
"""
numero = (distancia - 5) % 8
if numero in [1, 2, 3]:
return numero
else:
return None
|
def heuristic(s):
"""
The heuristic for
1. Testing
2. Demonstration rollout.
Args:
s (list): The state. Attributes:
s[0] is the vertical coordinate
s[1] is the vertical speed
returns:
a: The heuristic to be fed into the step function defined above to determine the next step and reward.
"""
# Vertical PID
F = 0#1.15
G = 0#1.33
posz, velz = s
hover_todo = posz*F + velz*G
return [hover_todo]
|
def separate_equally(seq, n=5):
"""
#return index of equally distance of a sequence
>> separate_equally([i for i in range(100)],4)
>> ([25, 50, 75, 100], 25)
"""
delta = len(seq) / n
start, res = 0, []
while (True):
start += delta
if start > len(seq):
break
res.append(start)
return res, delta
|
def discount_arpu(arpu, timestep, global_parameters):
"""
Discount arpu based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
arpu : float
Average revenue per user.
timestep : int
Time period (year) to discount against.
global_parameters : dict
All global model parameters.
Returns
-------
discounted_arpu : float
The discounted revenue over the desired time period.
"""
discount_rate = global_parameters['discount_rate'] / 100
discounted_arpu = arpu / (1 + discount_rate) ** timestep
return discounted_arpu
|
def calculate_z_base(v_base, s_base):
"""Calculate base impedance from voltage and system base apparent power.
:param int/float v_base: base voltage (kV).
:param int/float s_base: base apparent power (MVA).
:return: (*float*) -- base impedance (ohms).
"""
return (v_base**2) / s_base
|
def str_to_bool(string: str) -> bool:
"""Takes a string, converts it to a boolean. Ignores whitespace.
Parameters
----------
string : str
Boolean-like string (e.g. "True", "true", " true", " TRUE " all return true).
Returns
-------
bool
The bool equivalent of the string.
Raises
------
ValueError
String could not be converted to a boolean.
"""
string = string.strip()
if string.upper() == "TRUE":
return True
elif string.upper() == "FALSE":
return False
raise ValueError(
f"'{string}' is not parsible into 'True' or 'False'. Double-check that it's spelled correctly."
)
|
def WrapText(text, font, width):
# ColdrickSotK
# https://github.com/ColdrickSotK/yamlui/blob/master/yamlui/util.py#L82-L143
"""Wrap text to fit inside a given width when rendered.
:param text: The text to be wrapped.
:param font: The font the text will be rendered in.
:param width: The width to wrap to."""
text_lines = text.replace('\t', ' ').split('\n')
if width is None or width == 0:
return text_lines
wrapped_lines = []
for line in text_lines:
line = line.rstrip() + ' '
if line == ' ':
wrapped_lines.append(line)
continue
# Get the leftmost space ignoring leading whitespace
start = len(line) - len(line.lstrip())
start = line.index(' ', start)
while start + 1 < len(line):
# Get the next potential splitting point
next = line.index(' ', start + 1)
if font.size(line[:next])[0] <= width:
start = next
else:
wrapped_lines.append(line[:start])
line = line[start + 1:]
start = line.index(' ')
line = line[:-1]
if line:
wrapped_lines.append(line)
return wrapped_lines
|
def process2(_str):
"""
process the too long behavior sequence
"""
_list = list(_str)
n = len(_list)
if n <= 1:
print(_str)
return
list1 = []
for i in range(n - 1):
if i < 20 and _list[i] != _list[i + 1]:
list1.append(_list[i])
elif _list[i].strip() != "d" and _list[i] != 'a' and _list[i] != 'e':
list1.append(_list[i])
list1.append(_list[-1])
str1 = ''.join(list1)
return str1
|
def clean_position_name(chrom, pos, position_names, window, my_id):
"""try to clean up chr names"""
#left = int(pos) - (window / 2 )
#right = int(pos) + (window / 2 )
name = chrom.replace("|","PIPE")
name += "_" + str(pos)
name += "_padding_" + str(window)
#now check to make sure that the name isn't already taken
if name in position_names:
name += "_" + str(my_id)
#maybe like this later
#chr#(start-padding)(end+padding) where end=start+length(ref).
return name
|
def uniquify_list_of_strings(input_list):
"""
Ensure that every string within input_list is unique.
:param list input_list: List of strings
:return: New list with unique names as needed.
"""
output_list = list()
for i, item in enumerate(input_list):
tempList = input_list[:i] + input_list[i + 1:]
if item not in tempList:
output_list.append(item)
else:
output_list.append('{0}_{1}'.format(item, i))
return output_list
|
def split_dict(dict):
""" Deletes the dictionary entries which keys are
__header__, __globals__, etc. Then splits
dict into analog and strokelitude dictionaries. """
keylist = dict.keys()
analog_keys, strokelitude_keys = [], []
for key in keylist:
if key.find('__') != -1:
del dict[key]
elif key.find('ADCAIN') != -1:
analog_keys.append(key)
elif key.find('timestamp') == -1:
strokelitude_keys.append(key)
return analog_keys, strokelitude_keys
|
def normalize_alef_maksura_xmlbw(s):
"""Normalize all occurences of Alef Maksura characters to a Yeh character
in a XML Buckwalter encoded string.
Args:
s (:obj:`str`): The string to be normalized.
Returns:
:obj:`str`: The normalized string.
"""
return s.replace(u'Y', u'y')
|
def input(line):
"""Parse a line of input to determine what the user would like to do with it.
"""
if line.startswith('#'):
return {"type": "comment", "contents": line}
else:
tokens = line.split()
if len(tokens) < 2:
raise ValueError("The line must be the name of the branch and have a "
"least one commit")
branch, _, sourceBranch = tokens[0].partition(':')
# If the user hasn't provided the name of the source branch assume it is
# origin/master.
if not sourceBranch:
sourceBranch = 'origin/master'
return {
'type': 'newBranch',
'newBranch': branch, 'sourceBranch': sourceBranch, 'commits': tokens[1:],
}
|
def has_more_than_two_occurence(x):
"""creating a function for finding words with more than 2 occurences"""
if(x[1]>1):
return(x)
|
def update_lines(string, lambda_mod):
"""
Modify lines in string by applying a lambda to them.
:param string:
:param lambda_mod:
:return:
"""
from io import StringIO
stri = StringIO(string)
output = StringIO()
while True:
nl = stri.readline()
if nl != '':
nl = nl.rstrip()
nl = lambda_mod(nl)
output.write(nl + "\n")
else:
break
return output.getvalue()
|
def convert_old_to_new(metrics_collection):
"""Convert old metric format to new oneself.
:Example:
>>> old_metric
{
"file1": {
"size_in_bytes": 84890132,
"size_in_mb": 81.0,
}
}
>>> convert_old_to_new(old_metric)
{
"file1": {
"size_in_bytes": {'value': 84890132, 'unit': ''},
"size_in_mb": {'value': 81.0, 'unit': ''},
}
}
"""
new_style_metrics = {}
for name, metrics in metrics_collection.items():
new_style_metrics[name] = {}
for metric_name, metric in metrics.items():
new_style_metrics[name][metric_name] = {}
if not isinstance(metric, dict):
new_style_metrics[name][metric_name]['value'] = metric
else:
new_style_metrics[name][metric_name] = metric
if 'unit' not in new_style_metrics[name][metric_name]:
new_style_metrics[name][metric_name]['unit'] = ''
return new_style_metrics
|
def idDupesArrRowwise(x, dupe_ids):
"""
Returns binary if the contents of the list within the cell in the dataframe have any overlap with dupe_ids
Used in combination with idDupesInArr; main function identifies the IDs that are duplicates
This function identifies all rows with those ids, not just the subsequent values.
"""
if(x == x):
return(any(set(x) & set(dupe_ids)))
else:
return(False)
|
def file_version_summary(list_of_files):
"""
Given the result of list_file_versions, returns a list
of all file versions, with "+" for upload and "-" for
hide, looking like this:
['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg']
"""
return [('+ ' if (f['action'] == 'upload') else '- ') + f['fileName'] for f in list_of_files]
|
def paradigms_to_alphabet(paradigms):
"""Extracts all used symbols from an iterable of paradigms."""
alphabet = set()
for paradigm in paradigms:
for idx, (is_var, slot) in enumerate(paradigm.slots):
for word in slot:
alphabet |= set(word)
return alphabet
|
def is_saved(file_str):
"""Checks if the file is saved locally.
>>> is_saved('README.md')
True
"""
from pathlib import Path
return Path(file_str).is_file()
|
def version_str(version_info):
"""Format the python version information"""
return "{}.{}".format(version_info[0], version_info[1])
|
def repeated(t, k):
"""Return the first value in iterable T that appears K times in a row.
>>> s = [3, 2, 1, 2, 1, 4, 4, 5, 5, 5]
>>> repeated(trap(s, 7), 2)
4
>>> repeated(trap(s, 10), 3)
5
>>> print(repeated([4, None, None, None], 3))
None
"""
assert k > 1
counter, t_iter = k, iter(t)
first = next(t_iter)
while k > 1:
second = next(t_iter)
if first == second:
k = k - 1
else:
k = counter
first = second
return first
|
def check_if_yes(user_decision: str) -> bool:
"""Checks if the player decision is affirmative"""
return user_decision.strip().lower() in {"y", "yes", "1", "true"}
|
def normalize_range(images):
"""Normalize the given float image(s) by changing the range from [0,1] to [-1,1]."""
return images * 2.0 - 1.0
|
def stirling_numbers_2(n,k):
"""Stirling Numbers of the Second Kind"""
if n == k:
return 1
if n == 0 and k == 0:
return 1
if n == 0 or k == 0:
return 0
return k*stirling_numbers_2(n-1,k) + stirling_numbers_2(n-1,k-1)
|
def _sundaram(n):
"""Sieve of Sundaram
Start with a list of the integers from 1 to n.
From this list, remove all numbers of the form i + j + 2*i*j, where:
1) 1 <= i <= j
2) i + j + 2*i*j <= n
The remaining numbers are doubled and incremented by one, giving a list
of the odd prime numbers (i.e., all primes except 2)
"""
mark = [True] * n
for i in range(1, n//3+1):
for j in range(1, (n-i)//(2*i+1)+1):
mark[i+j+2*i*j - 1] = False
return [2] + [2*(i+1)+1 for i, flag in enumerate(mark) if flag]
|
def passes_luhn_check(value):
"""
The Luhn check against the value which can be an array of digits,
numeric string or a positive integer.
Example credit card numbers can be found here:
https://www.paypal.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
:author: Alexander Berezhnoy (alexander.berezhnoy |at| gmail.com)
"""
# Prepare the value to be analyzed.
arr = []
for c in value:
if c.isdigit():
arr.append(int(c))
arr.reverse()
# Analyze
for idx in [i for i in range(len(arr)) if i % 2]:
d = arr[idx] * 2
if d > 9:
d = d / 10 + d % 10
arr[idx] = d
sm = sum(arr)
return not (sm % 10)
|
def _get_last_layer_units_and_activation(num_classes):
"""Gets the # units and activation function for the last network layer.
Args:
num_classes: Number of classes.
Returns:
units, activation values.
"""
if num_classes == 2:
activation = 'sigmoid'
units = 1
else:
activation = 'softmax'
units = num_classes
return units, activation
|
def is_improving(metric_value, best_metric_value, metric):
"""Return true if metric value improving."""
if metric not in ['spr', 'rmse', 'pearson', 'both']:
raise Exception('Unsupported metric: {}'.format(metric))
if metric == 'both':
spr = metric_value[0]
rmse = metric_value[1]
best_spr = best_metric_value[0]
best_rmse = best_metric_value[1]
return spr > best_spr and rmse < best_rmse
if metric in ['spr', 'pearson']:
return metric_value > best_metric_value
# for rmse we want to lower the loss
return metric_value < best_metric_value
|
def make_integer(value):
"""Returns a number in a string format like "10,000" as an integer."""
return int(value.replace(",", ""))
|
def implied_r(f):
""" Dimension for search implied by a skater name """
# Generally this isn't encouraged, as skaters might be created by functools.partial and folks
# may forget to apply functools.upate_wrapper to preserve the __name__
name = f if isinstance(f,str) else f.__name__
if '_r2' in name:
return 2
elif '_r3' in name:
return 3
elif '_r1' in name:
return 1
else:
return 0
|
def centered(curr_size, new_size):
"""
Use with convolution, return center indices for an array of a specific len.
Parameters
----------
curr_size: int
Length of dimension to truncate in the current array.
new_size: int
Intended length of the dimension to truncate in the new array.
Returns
-------
ind: np.ndarray, shape: (new_size,)
Indices to excise the center portion along one dimension
of the current array.
"""
curr_size = int(curr_size)
new_size = int(new_size)
center = curr_size - (curr_size + 1) // 2
return slice(center - (new_size) // 2, center + (new_size + 1) // 2)
|
def get_index_str(n, i):
"""
To convert an int 'i' to a string.
Parameters
----------
n : int
Order to put 0 if necessary.
i : int
The number to convert.
Returns
-------
res : str
The number as a string.
Examples
--------
```python
getIndexStr(100,15)
```
Out:
```
'015'
```
"""
if i < 0 or i > n:
raise ValueError("N >= i or i > 0 is required")
lm = len(str(n))
res = str(i)
while lm > len(res):
res = "0" + res
return res
|
def guess_color(r, g, b):
"""Categorize pixel based on RGB values 2: white, 1: yellow, 0: blue"""
maxi = max(r, g, b)
ave = (r + g + b) / 3
return 2 if ave >= 80 else 0 if maxi == b else 1
|
def count_ranges(a):
"""
Assumes binary array of 1 and 0 as input. Calculate longest ranges of 1's.
:param a: array with binary values
:return: [end_pos, length] of ranges in array
"""
ranges = []
count = 0
for i, v in enumerate(a):
if v == 1: # same as previous value
count += 1
else:
if count > 1:
ranges.append([i, count]) # [end, length]
count = 0
return ranges
|
def reverse(text: str) -> str:
"""Reverse the given string."""
return text[::-1]
|
def rowdict(columns, row):
"""Convert given row list into dict with column keys"""
robj = {}
for key, val in zip(columns, row):
robj.setdefault(key, val)
return robj
|
def ConstructGoldenEyeBuildDetailsUri(build_id):
"""Return the dashboard (goldeneye) URL for this run.
Args:
build_id: CIDB id for the build.
Returns:
The fully formed URI.
"""
_link = ('http://go/goldeneye/'
'chromeos/healthmonitoring/buildDetails?id=%(build_id)s')
return _link % {'build_id': build_id}
|
def run_plugin_action(path, block=False):
"""Create an action that can be run with xbmc.executebuiltin in order to run a Kodi plugin specified by path.
If block is True (default=False), the execution of code will block until the called plugin has finished running."""
return f'RunPlugin({path}, {block})'
|
def swap_downstairs_list(id1, id2, li):
"""Swap list element id1 with the next until reaches id2 (id1 > id2)."""
for i in range(id1, id2):
li[i], li[i+1] = li[i+1], li[i]
return li
|
def _gen_bia_img_url(imgname):
"""Genarate BIA Image URL"""
assert isinstance(imgname, str)
return 'http://www.istartedsomething.com/bingimages/cache/' + imgname
|
def getConsistentValue(thelist, error, emptyval=None):
"""
Function for extracting a consistent value from a list,
and throwing an error if:
a) there are differing values present, or;
b) the list is empty but no 'empty' value is supplied.
"""
if len(thelist) > 0:
# Check that the values are consistent.
if thelist.count(thelist[0]) != len(thelist):
# Raise the exception with the user supplied error string.
raise IOError(error)
# If they are, return the first value.
return thelist[0]
else:
if emptyval is not None:
return emptyval
else:
raise ValueError("Empty list supplied but no empty value given!")
|
def format_value_for_spreadsheet(value):
"""Format a value into a string to be written in a spreadsheet cell."""
if isinstance(value, (list, tuple)):
return " & ".join([format_value_for_spreadsheet(v) for v in value])
return str(value)
|
def setDefaults(configObj={}):
""" Return a dictionary of the default parameters
which also been updated with the user overrides.
"""
gain = 7 # Detector gain, e-/ADU
grow = 1 # Radius around CR pixel to mask [default=1 for 3x3 for non-NICMOS]
ctegrow = 0 # Length of CTE correction to be applied
rn = 5 # Read noise in electrons
snr = "4.0 3.0" # Signal-to-noise ratio
scale = "0.5 0.4" # scaling factor applied to the derivative
backg = 0 # Background value
expkey = "exptime" # exposure time keyword
paramDict={"gain":gain,
"grow": grow,
"ctegrow":ctegrow,
"rn":rn,
"snr":snr,
"scale":scale,
"backg":backg,
"expkey":expkey}
if (len(configObj) != 0):
for key in configObj:
paramDict[key]=configObj[key]
return paramDict
|
def generate_byte(bools):
"""Generate a byte based on a list of bools
:bools: a list of bools from which to generate the byte
:returns: a byte representing the bools
"""
bools_len = len(bools)
if bools_len > 8:
# we should never encounter this, wrong length
raise ValueError
rtn = 0 # initialize the bool we are returning
for i in range(bools_len):
rtn += ((1 if bools[bools_len - i - 1] else 0) << i)
return rtn
|
def extended_euclidean_gcd(a: int, b: int):
"""
extended euclidean algorithm, returning the gcd and two bezout coefficients
a * alpha + b * beta = 1
"""
alpha, s, beta, t = 1, 0, 0, 1
while b > 0:
a, (q, b) = b, divmod(a, b)
alpha, s = s, alpha - q * s
beta, t = t, beta - q * t
return a, alpha, beta
|
def get_pcal_line(meta_pcal,records):
"""
Get a line for the PCAL file.
Parameters
----------
meta_pcal : str
metadata.
records : list of str
records.
"""
return(meta_pcal+' '.join(records))
|
def combine_filters(fl1, fl2):
"""
Combine two filter function results
"""
assert len(fl1) == len(fl2)
r = []
for i in range(len(fl1)):
r.append(
fl1[i].intersection(fl2[i])
)
return r
|
def deci_deg_to_deg_min_sec(deci_deg):
"""https://stackoverflow.com/questions/2579535\
/convert-dd-decimal-degrees-to-dms-degrees-minutes-seconds-in-python"""
is_positive = (deci_deg >= 0)
deci_deg = abs(deci_deg)
# divmod returns quotient and remainder
minutes,seconds = divmod(deci_deg*3600,60)
degrees,minutes = divmod(minutes,60)
degrees = degrees if is_positive else -degrees
return (degrees,minutes,seconds)
|
def valid_ip(query):
"""Check if an IP address is valid."""
import socket
try:
socket.inet_aton(query)
return True
except socket.error:
return False
|
def constant_time_equals(a, b):
"""Return True iff a == b, and do it in constant time."""
a = bytearray(a)
b = bytearray(b)
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
|
def get_bot_response(message):
"""This is just a dummy function, returning a variation of what
the user said. Replace this function with one connected to chatbot."""
return "This is a dummy response to '{}'".format(message)
|
def is_palindrome(line):
"""Return True if it is palindrome string."""
return str(line) == str(line)[::-1]
|
def complete(tab, opts):
"""Get options that start with tab.
:param tab: query string
:param opts: list that needs to be completed
:return: a string that start with tab
"""
msg = "({0})"
if tab:
opts = [m[len(tab):] for m in opts if m.startswith(tab)]
if len(opts) == 1:
return opts[0]
if not len(opts):
msg = "{0}"
return msg.format("|".join(opts))
|
def parser(keyword, line):
""" Main parser function """
try:
for item in line.split(' '):
if keyword in item:
return item.split('=')[1]
except IndexError:
return "[ERR] parser: " + line
|
def remove_whitespace(seq: str) -> str:
"""
Remove whitespace from the given sequence
>>> remove_whitespace("R K D E S")
'RKDES'
>>> remove_whitespace("R K D RR K")
'RKDRRK'
>>> remove_whitespace("RKIL")
'RKIL'
"""
return "".join(seq.split())
|
def get_target_for_label(label):
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if(label == 'POSITIVE'):
return 1
else:
return 0
|
def set_name_w(name_w, w):
"""Return generic name if user passes None to the robust parameter in a
regression. Note: already verified that the name is valid in
check_robust() if the user passed anything besides None to robust.
Parameters
----------
name_w : string
Name passed in by user. Default is None.
w : W object
pysal W object passed in by user
Returns
-------
name_w : string
"""
if w != None:
if name_w != None:
return name_w
else:
return 'unknown'
return None
|
def hashable(raw):
"""If `raw` contains nested lists, convert them to tuples
>>> hashable(('a', 'b', 'c'))
('a', 'b', 'c')
>>> hashable(('a', ['b', 'c'], 'd'))
('a', ('b', 'c'), 'd')
"""
result = tuple(hashable(itm) if isinstance(itm, list) else itm
for itm in raw)
return result
|
def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short.replace(prefix + ':', prefixes[prefix])
return short
|
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(source_string[count + 1]) * 256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo < len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
|
def CheckAnyListElementSameType(in_list:list, in_type:type):
"""
This function checks all elements of a list a equal to a specific type.
:param in_list:list: a list of elements
:param in_type:type: a specific type
"""
return any(isinstance(x, in_type) for x in in_list)
|
def deploy_blacklist_to_constraints(deploy_blacklist):
"""Converts a blacklist of locations into marathon appropriate constraints
https://mesosphere.github.io/marathon/docs/constraints.html#unlike-operator
:param blacklist: List of lists of locations to blacklist
:returns: List of lists of constraints
"""
constraints = []
for blacklisted_location in deploy_blacklist:
constraints.append([blacklisted_location[0], "UNLIKE", blacklisted_location[1]])
return constraints
|
def get_region_of_all_exchanges(scenario: dict) -> dict:
"""Returns {ID: region_name, ...} map for `EnergyExchange` in given `scenario`. If no region is found, the string `Region` is applied"""
try:
exchanges = [
{exchange["Id"]: exchange["Attributes"]["Region"]}
for exchange in scenario["Agents"]
if exchange["Type"] == "EnergyExchange"
]
except KeyError:
exchanges = [
{exchange["Id"]: "Region"} for exchange in scenario["Agents"] if exchange["Type"] == "EnergyExchange"
]
output = {}
for exchange in exchanges:
output.update(exchange)
return output
|
def prepare_denominator(list_to_prepare):
"""
Method to safely divide a list of numbers while ignoring zero denominators by adding a very small value to any
zeroes.
Args:
list_to_prepare: The list to be used as a denominator
Returns:
The list with zeros replaced with small numbers
"""
return [list_to_prepare[i] if list_to_prepare[i] > 0. else 1e-10 for i in range(len(list_to_prepare))]
|
def remove_macro_defines(blocks, excludedMacros=None):
"""Remove macro definitions like #define <macroName> ...."""
if excludedMacros is None:
excludedMacros = set()
result = []
for b in blocks:
macroName = b.isDefine()
if macroName is None or macroName not in excludedMacros:
result.append(b)
return result
|
def Get_Percentage(Percentage, Max, MaxPercentage):
"""
Get Percentage of 2 Values
:param Percentage:Current Value
:param Max:Max Value
:param MaxPercentage:Max Percentage (default 100)
:return:
"""
return (Percentage * Max) / MaxPercentage
|
def convert_to_my_format_from_predicted(predicted_bbs):
"""convert (ctr_x, ctr_y, w, h) -> (x1, y1, x2, y2)"""
output_bb = []
for predicted_bb in predicted_bbs:
x = int(predicted_bb[1])
y = int(predicted_bb[2])
w = int(predicted_bb[3] / 2)
h = int(predicted_bb[4] / 2)
output_bb.append([predicted_bb[0], x - w, y - h, x + w, y + h, predicted_bb[5]])
return output_bb
|
def byte_length(text: str) -> int:
"""
Return the string length in term of byte offset
"""
return len(text.encode("utf8"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.