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... |
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_... |
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... |
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:... |
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("\\", "/").startswi... |
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 patt... |
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)... |
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... |
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) #... |
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."
els... |
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 Algori... |
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
... |
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'] = orde... |
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 ... |
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['Str... |
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 ... |
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
... |
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 : d... |
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.... |
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... |
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[... |
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... |
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_... |
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:
... |
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 "
... |
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 != '':
... |
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": {
"siz... |
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 s... |
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 '-... |
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... |
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 exc... |
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 Berezhn... |
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... |
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]
... |
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:... |
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 arr... |
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
getI... |
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
... |
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 % {'bui... |
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 val... |
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... |
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
... |
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 -... |
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)... |
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:
... |
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 p... |
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)
r... |
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... |
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]) ... |
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
... |
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 ... |
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
... |
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:
... |
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)
... |
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.