content stringlengths 42 6.51k |
|---|
def word_pig_latin_translation(word):
"""This function does the translation for word"""
VOVELS =['a','e','i','o','u']
#case: words containing punctuations
if not word.isalpha():
return word
#case: Capitalized words
if word[0].isupper():
return word_pig_latin_translation(word.lower()).capitalize()
#case : Words starting with Vovels
if word[0].lower() in VOVELS:
return word + 'yay'
else:
for i,char in enumerate(word):
if char.lower() in VOVELS:
return word[i:].lower() + word[:i].lower() + 'ay'
#words containing no vovel
return word + 'ay' |
def get_document(document_name):
"""
This function responds to a request for /api/document-base
with the patient's records
:return: pdf document
"""
# Create the list of people from our data
with open(document_name, "r") as f:
return f.read() |
def pageCount(n, p):
#
# Write your code here.
#
"""
###########Pseudocode###########
-> n = number of pages
-> p = target page
-> if p is close to first page:
-> return int(p/2)
-> if p is close to the last page:
-> return int(p/2)
"""
middle = int(n/2)
diff = n-p
if p <= middle:
return int(p/2)
else:
if (n%2 == 0 and diff == 0) or (n%2 != 0 and diff < 2):
return 0
elif n%2 == 0 and diff == 1 or (n%2 != 0 and diff < 5):
return 1
else:
return int((diff)/2) |
def in_region(pos, b, e):
""" Returns pos \in [b,e] """
return b <= pos and pos <= e |
def maximum(a, b):
"""
:param a: int, any number
:param b: int, any number
:return: the bigger one
"""
if a >= b:
return a
else:
return b |
def distance(a,b):
"""
Calculates the Levenshtein distance between a and b.
References
==========
http://en.wikisource.org/wiki/Levenshtein_distance#Python
"""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = list(range(n+1))
for i in range(1,m+1):
previous, current = current, [i]+[0]*m
for j in range(1,n+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n] |
def filter_json(json, *keys):
"""Returns the given JSON but with only the given keys."""
return {key: json[key] for key in keys if key in json} |
def remove_repeated_element(repeated_list):
"""
Remove duplicate elements
:param repeated_list: input list
:return: List without duplicate elements
"""
repeated_list.sort()
new_list = [repeated_list[k] for k in range(len(repeated_list)) if
k == 0 or repeated_list[k] != repeated_list[k - 1]]
return new_list |
def E_float2(y, _):
"""Numerically stable implementation of Muller's recurrence."""
return 8 - 15/y |
def length(value):
""" Gets the length of the value provided to it.
Returns:
If the value is a collection, it calls len() on it.
If it is an int, it simply returns the value passed in"""
try:
if isinstance(value, int):
return value
else:
result = len(value)
return result
except TypeError:
return None |
def json_or_default(js, key, defval=None):
"""
Loads key from the JS if exists, otherwise returns defval
:param js: dictionary
:param key: key
:param defval: default value
:return:
"""
if key not in js:
return defval
return js[key] |
def to_camelCase(in_str):
"""
Converts a string to camelCase.
:param in_str: The input string.
:type in_str: str
:return: The input string converted to camelCase.
:rtype: str
"""
if in_str.find(' ') > -1:
words = in_str.split(' ')
elif in_str.find('_') > -1:
words = in_str.split('_')
else:
return in_str.lower()
first_word = words[0].lower()
other_words = ''.join(w.title() for w in words[1:])
return '%s%s' % (first_word, other_words) |
def remove_dul(entitylst):
"""
Remove duplicate entities in one sequence.
"""
entitylst = [tuple(entity) for entity in entitylst]
entitylst = set(entitylst)
entitylst = [list(entity) for entity in entitylst]
return entitylst |
def _is_end_of_rti(line):
"""Check if line in an rti is at the end of the section."""
return (
line
and "@" not in line
and not line == "\n"
and not line.strip().startswith("#")
) |
def check_command_help_len(argv_):
"""return bool"""
return len(argv_) == 2 |
def summ(listy):
"""
Input: A list of numbers.
Output: The sum of all the numbers in the list, iterative.
"""
total = 0
for i in listy:
total += i
return total |
def merge_with_thres_LL(other_LL, thres_LL, pairs):
"""Merge the dictionaries containing the threshold-LL and other thresholds.
Other_LL will be modified in place.
"""
for u_id, l_id in pairs:
for key in thres_LL[u_id][l_id]:
other_LL[u_id][l_id][key] = thres_LL[u_id][l_id][key]
return None |
def list_union(a, b):
""" return the union of two lists """
return list(set(a) | set(b)) |
def extract_columns(spec, data):
"""Transforms some data into a format suitable for print_columns_...
The data is a list of anything, to which the spec functions will be applied.
The spec is a list of tuples representing the column names
and how to the column from a row of data. E.g.
[ ('Master', lambda m: m['name']),
('Config Dir', lambda m: m['dirname']),
...
]
"""
lines = [ [ s[0] for s in spec ] ] # Column titles.
for item in data:
lines.append([ s[1](item) for s in spec ])
return lines |
def measure_counts_deterministic(shots, hex_counts=True):
"""Measure test circuits reference counts."""
targets = []
if hex_counts:
# Measure |00> state
targets.append({'0x0': shots})
# Measure |01> state
targets.append({'0x1': shots})
# Measure |10> state
targets.append({'0x2': shots})
# Measure |11> state
targets.append({'0x3': shots})
else:
# Measure |00> state
targets.append({'00': shots})
# Measure |01> state
targets.append({'01': shots})
# Measure |10> state
targets.append({'10': shots})
# Measure |11> state
targets.append({'11': shots})
return targets |
def word_list_to_string(word_list, delimeter=" "):
"""Creates a single string from a list of strings
This function can be used to combine words in a list into one long sentence
string.
Args:
word_list (list/tuple): A list (or other container) of strings.
delimeter (str, Optional): A string to delimit the strings in the list
when combining the strings.
Returns:
A string.
"""
string = ""
for word in word_list:
string+=word+delimeter
nchar = len(string)
return str(string[0:nchar-1]) |
def polygon_clip(subjectPolygon, clipPolygon):
""" Clip a polygon with another polygon.
Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python
Args:
subjectPolygon: a list of (x,y) 2d points, any polygon.
clipPolygon: a list of (x,y) 2d points, has to be *convex*
Note:
**points have to be counter-clockwise ordered**
Return:
a list of (x,y) vertex point for the intersection polygon.
"""
def inside(p):
return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0])
def computeIntersection():
dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]]
dp = [s[0] - e[0], s[1] - e[1]]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s): outputList.append(computeIntersection())
outputList.append(e)
elif inside(s): outputList.append(computeIntersection())
s = e
cp1 = cp2
if len(outputList) == 0: return None
return (outputList) |
def Euler(diffeq, y0, t, h): # uses docstring """..."""
""" Euler's method for n ODEs:
Given y0 at t, returns y1 at t+h """
dydt = diffeq(y0, t) # get {dy/dt} at t
return y0 + h*dydt # Euler method on a vector @\lbl{line:vecop}@ |
def json_dumpb(obj: object) -> bytes:
"""Compact formating obj as JSON to UTF-8 encoded bytes."""
import json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=False).encode('utf-8') |
def create(place_found):
""" function to create response dictionary """
# add basic attributes to response
response = {
'name': place_found['name'],
'address': place_found['vicinity']
}
# if these attributes are in place_found, add those to response
if 'price_level' in place_found:
response['price_level'] = place_found['price_level']
if 'rating' in place_found:
response['rating'] = place_found['rating']
if 'opening_hours' in place_found:
response['open_now'] = place_found['opening_hours']['open_now']
return response |
def compute_agreement_score(num_matches, num1, num2):
"""
Computes agreement score.
Parameters
----------
num_matches: int
Number of matches
num1: int
Number of events in spike train 1
num2: int
Number of events in spike train 2
Returns
-------
score: float
Agreement score
"""
denom = num1 + num2 - num_matches
if denom == 0:
return 0
return num_matches / denom |
def median(inlistin):
"""median: Finds the median of the provided array.
Args:
inlistin (array): An array of numbers to find the median of
Returns:
Float: the median of the numbers given
"""
inlistin = sorted(inlistin)
inlisto = 0
length = len(inlistin)
for x in range(int(length / 2) - 1):
del inlistin[0]
del inlistin[-1]
if len(inlistin) == 2:
inlisto = (int(inlistin[0] + inlistin[1]) / 2)
else:
inlisto = inlistin[1]
return inlisto |
def calculate_amount(principal, rate, term, frequency):
""" Calculate the principal plus interest given the
principal, rate, term and frequency
"""
return round(principal * ((1 + ((rate / 100 / frequency))) ** (frequency * term)), 2) |
def format_stringv3(value):
"""Return a vCard v3 string. Embedded commas and semi-colons are backslash quoted"""
return value.replace("\\", "").replace(",", r"\,").replace(";", r"\;") |
def is_nullable(schema_item: dict) -> bool:
"""
Checks if the item is nullable.
OpenAPI does not have a null type, like a JSON schema,
but in OpenAPI 3.0 they added `nullable: true` to specify that the value may be null.
Note that null is different from an empty string "".
This feature was back-ported to the Swagger 2 parser as a vendored extension `x-nullable`. This is what drf_yasg generates.
OpenAPI 3 ref: https://swagger.io/docs/specification/data-models/data-types/#null
Swagger 2 ref: https://help.apiary.io/api_101/swagger-extensions/
:param schema_item: schema item
:return: whether or not the item can be None
"""
openapi_schema_3_nullable = 'nullable'
swagger_2_nullable = 'x-nullable'
for nullable_key in [openapi_schema_3_nullable, swagger_2_nullable]:
if schema_item and isinstance(schema_item, dict):
if nullable_key in schema_item:
if isinstance(schema_item[nullable_key], str):
if schema_item[nullable_key] == 'true':
return True
return False |
def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float:
"""
Convert a given value from Celsius to Kelvin and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
"""
return round(celsius + 273.15, ndigits) |
def is_float(s):
"""Determine whether str can be cast to float."""
try:
float(s)
return True
except ValueError:
return False |
def none_to_string(string: None) -> str:
"""Convert None types to an empty string.
:param string: the string to convert.
:return: string; the converted string.
:rtype: str
"""
_return = string
if string is None or string == "None":
_return = ""
return _return |
def has_inline_pass(line: str) -> bool:
"""True if line ends with a pass command."""
return line.endswith("phmdoctest:pass") |
def _kface_cell_value(arr, loc):
""" Returns K face value for cell-centered data. """
i, j, k = loc
# FIXME: built-in ghosts
return 0.5 * (arr(i+1, j+1, k+1) + arr(i+1, j+1, k)) |
def parse_hcount(hcount_str):
"""
Parses a SMILES hydrogen count specifications.
Parameters
----------
hcount_str : str
The hydrogen count specification to parse.
Returns
-------
int
The number of hydrogens specified.
"""
if not hcount_str:
return 0
if hcount_str == 'H':
return 1
return int(hcount_str[1:]) |
def get_tablename_query(column_id, boundary_id, timespan):
"""
given a column_id, boundary-id (us.census.tiger.block_group), and
timespan, give back the current table hash from the data observatory
"""
return """
SELECT numer_tablename, numer_geomref_colname, numer_tid,
geom_tablename, geom_geomref_colname, geom_tid
FROM observatory.obs_meta
WHERE numer_id = '{numer_id}' AND
geom_id = '{geom_id}' AND
numer_timespan = '{numer_timespan}'
""".format(numer_id=column_id,
geom_id=boundary_id,
numer_timespan=timespan) |
def build_agg_feature_name(feature_prefix: str, agg_func: str, agg_window: str) -> str:
"""
Creates the feature name for the aggregation feature based on the prefix, aggregation function and window
:param feature_prefix: The prefix
:param agg_func: The aggregation function (SUM, MIN, COUNT etc)
:param agg_window: The window (1d, 5m, 2w etc)
:return: str the full aggregation feature name
"""
return f'{feature_prefix}_{agg_func}_{agg_window}' |
def unescape_html_entities(text: str) -> str:
"""
Replaces escaped html entities (e.g. ``&``) with their ASCII representations (e.g. ``&``).
:param text:
"""
out = text.replace("&", '&')
out = out.replace("<", '<')
out = out.replace(">", '>')
out = out.replace(""", '"')
return out |
def get_insert_many_query(table_name):
"""Build a SQL query to insert a RDF triple into a SQlite dataset"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES ? ON CONFLICT (subject,predicate,object) DO NOTHING" |
def get_deltas(number, lst):
"""Returns a list of the change from a number each value of a list is"""
return [abs(i - number) for i in lst] |
def _sp_sleep_for(t: int) -> str:
"""Return the subprocess cmd for sleeping for `t` seconds."""
return 'python -c "import time; time.sleep({})"'.format(t) |
def getBits (num, gen):
""" Get "num" bits from gen. """
out = 0
for i in range (num):
out <<= 1
val = gen.next ()
if val != []:
out += val & 0x01
else:
return []
return out |
def cal_kt(raw_trajs_frequent_pattern, sd_trajs_frequent_pattern):
"""
calculate KT
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
KT
"""
concordant_count = 0
discordant_count = 0
k = 0
for i in range(len(list(raw_trajs_frequent_pattern.keys()))):
if k >= 50:
break
if list(raw_trajs_frequent_pattern.keys())[i] in sd_trajs_frequent_pattern.keys():
k += 1
for i in range(len(list(raw_trajs_frequent_pattern.keys())[:k])):
if list(raw_trajs_frequent_pattern.keys())[i] in sd_trajs_frequent_pattern.keys():
for j in range(i + 1, len(list(raw_trajs_frequent_pattern.keys())[:k])):
if list(raw_trajs_frequent_pattern.keys())[j] in sd_trajs_frequent_pattern.keys():
if (raw_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[i]] >= raw_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[j]]
and sd_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[i]] > sd_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[j]]) \
or (raw_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[i]] < raw_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[j]]
and sd_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[i]] < sd_trajs_frequent_pattern[list(raw_trajs_frequent_pattern.keys())[j]]):
concordant_count += 1
else:
discordant_count += 1
KT = (concordant_count - discordant_count) / (50 * 49 / 2)
return KT |
def is_type(typecheck, data):
"""
Generic type checker
typically used to check that a string can be cast to int or float
"""
try:
typecheck(data)
except ValueError:
return False
else:
return True |
def mbuild(width, height):
"""Build a NxN matrix filled with 0."""
result = list()
for i in range(height):
result.append(list())
for j in range(width):
result[i].append(0.0)
return result |
def measurement_id(measurement_uuid: str, agent_uuid: str) -> str:
"""
Measurement IDs used by Iris
>>> measurement_id("57a54767-8404-4070-8372-ac59337b6432", "e6f321bc-03f1-4abe-ab35-385fff1a923d")
'57a54767-8404-4070-8372-ac59337b6432__e6f321bc-03f1-4abe-ab35-385fff1a923d'
Measurement IDs used by Diamond-Miner test data
>>> measurement_id("test_nsdi_example", "")
'test_nsdi_example'
"""
s = measurement_uuid
if agent_uuid:
s += f"__{agent_uuid}"
return s |
def remove_child_items(item_list):
"""
For a list of filesystem items, remove those items that are duplicates or children of other items
Eg, for remove_child_items['/path/to/some/item/child', '/path/to/another/item', '/path/to/some/item']
returns ['/path/to/another/item', '/path/to/some/item']
If one if the items is root, then it wins
Also, all items should be the full path starting at root (/). Any that aren't are removed
"""
if '/' in item_list:
return ['/']
# Remove duplicates and any non-full path items
item_list = sorted(list(set(filter(lambda x: x.startswith('/'), item_list))))
remove_items = set([])
for i, item1 in enumerate(item_list[:-1]):
for item2 in item_list[i + 1:]:
if item1 != item2 and item2.startswith(item1 + '/'):
remove_items.add(item2)
for remove_item in remove_items:
item_list.remove(remove_item)
return sorted(list(set(item_list))) |
def get_pack_format_and_mask_for_num_bytes(num_bytes,
signed=False,
little_endian=True):
"""Return the struct pack format and bit mask for the integer values of size
|num_bytes|."""
if num_bytes == 1:
pack_fmt = 'B'
mask = (1 << 8) - 1
elif num_bytes == 2:
pack_fmt = 'H'
mask = (1 << 16) - 1
elif num_bytes == 4:
pack_fmt = 'I'
mask = (1 << 32) - 1
elif num_bytes == 8:
pack_fmt = 'Q'
mask = (1 << 64) - 1
else:
raise ValueError
if signed:
pack_fmt = pack_fmt.lower()
if num_bytes > 1:
if little_endian:
pack_fmt = '<' + pack_fmt
else:
pack_fmt = '>' + pack_fmt
return pack_fmt, mask |
def is_subpath(spath, lpath):
"""
check the short path is a subpath of long path
:param spath str: short path
:param lpath str: long path
"""
if lpath.startswith(spath):
slen, llen = len(spath), len(lpath)
return True if slen == llen else lpath[slen] == '/'
return False |
def convert_str(input_str):
"""Try to convert string to either int or float, returning the original string if this fails."""
try:
ret = int(input_str)
except ValueError:
# try float.
try:
ret = float(input_str)
except ValueError:
ret = input_str
return ret |
def page_double_hyphen(record):
"""
Separate pages by a double hyphen (--).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "pages" in record:
if "-" in record["pages"]:
p = [i.strip().strip('-') for i in record["pages"].split("-")]
record["pages"] = p[0] + '--' + p[-1]
return record |
def software_and_version(path):
""" return 'corda-os', '4.4' """
dirs = str(path).split("/")
# locate 'docs'
while dirs[0] != "docs":
dirs.pop(0)
return dirs[1], dirs[2] |
def hide_passwords(key, value):
"""
Return asterisks when the given key is a password that should be hidden.
:param key: key name
:param value: value
:return: hidden value
"""
hidden_keys = ['key', 'pass', 'secret', 'code', 'token']
hidden_value = '*****'
return hidden_value if any(hidden_key in key for hidden_key in hidden_keys) else value |
def _calculate_ticks(group_len: int, width: float):
"""Given some group size, and width calculate
where ticks would occur.
Meant for bar graphs
"""
if group_len % 2 == 0:
start = ((int(group_len / 2) - 1) * width * -1) - (width / 2.0)
else:
start = int((group_len / 2)) * width * -1
temp = []
offset = start
for _ in range(0, group_len):
temp.append(offset)
offset += width
return temp |
def column_marker(column):
"""
Unique markers modulo 7
"""
if (column)//7 == 0:
marker = 'x'
elif (column)//7 == 1:
marker = '+'
else:
marker = 'd'
return marker |
def euler_step(theta,dtheta,ddtheta,dt):
"""
Euler Step
Parameters
----------
theta (tf.Tensor):
Joint angles
(N,nq)
dtheta (tf.Tensor):
Joint velocities
(N,nq)
ddtheta (tf.Tensor):
Joint accelerations
(N,nq)
dt (float):
Delta t
Returns
-------
(thetalistNext, dthetalistNext) (tupe of tf.Tensor):
Next joint angles and velocities
(N,nq), (N,nq)
"""
return theta + dt * dtheta, dtheta + dt * ddtheta |
def parse_env(entries):
"""entries look like X=abc"""
res = {}
for e in entries:
if "=" in e:
e = e.split("=", 2)
res[e[0]] = e[1]
return res |
def aggvar_hurst_measure(measure):
"""Hurst computation parameter from aggvar slope fit.
Parameters
----------
measure: float
the slope of the fit using aggvar method.
Returns
-------
H: float
the Hurst parameter.
"""
H = float((measure+2.)/2.)
return H |
def build_predicate_direction(predicate: str, reverse: bool) -> str:
"""Given a tuple of predicate string and direction, build a string with arrows"""
if reverse:
return f"<-{predicate}-"
else:
return f"-{predicate}->" |
def generate_options_for_monitoring_tool(server=None, **kwargs):
"""
Define a list of tuples that will be returned to generate the field options
for the monitoring_tool Action Input.
In this example Mode is dependent on Monitoring_Tool. Dependencies between
parameters can be defined within the dependent parameter's page.
each tuple follows this order: (value, label)
where value is the value of the choice, and label is the label that appears
in the field.
"""
options = [('nagios', 'Nagios'),
('zabbix', 'Zabbix')
]
return options |
def align_left(msg, length):
""" Align the message to left. """
return f'{msg:<{length}}' |
def _GetSchemeFromUrlString(url_str):
"""Returns scheme component of a URL string."""
end_scheme_idx = url_str.find('://')
if end_scheme_idx == -1:
# File is the default scheme.
return 'file'
else:
return url_str[0:end_scheme_idx].lower() |
def get_modulus_residue(value, modulus):
"""
Computes the canonical residue of value mod modulus.
Parameters:
value (int): The value to compute the residue of
modulus (int): The modulus used to calculate the residue
Returns:
An integer "r" between 0 and modulus - 1, where value - r is divisible
by the modulus.
Remarks:
See the Q# source for the "Modulus" function at
https://github.com/Microsoft/QuantumLibraries/blob/master/Canon/src/Math/Functions.qs
"""
if modulus <= 0:
raise ValueError(f"Modulus {modulus} must be positive.")
r = value % modulus
if r < 0:
return r + modulus
else:
return r |
def scale_coords(coords):
"""Returns coordinate list scaled to matplotlib coordintates.
- coords: list of lists, of x,y coordinates:
[[x1,y1],[x2,y2],[x3,y3],...]
"""
new_coords = []
#get min and max x coordinates
max_x = max([c[0] for c in coords])
min_x = min([c[0] for c in coords])
#get min and max y coordinates
max_y = max([c[1] for c in coords])
min_y = min([c[1] for c in coords])
#Get scaled max values for x and y
scaled_max_x = max_x - min_x
scaled_max_y = max_y - min_y
#max scale value
max_scale = max(scaled_max_x, scaled_max_y)
scale_x = min_x
scale_y = min_y
for x,y in coords:
new_coords.append([(x-scale_x)/max_scale,\
(y-scale_y)/max_scale])
return new_coords |
def downsample_array(array):
"""down sample given array"""
skip = 5
result = array[::skip]
result.append(array[-1])
return result |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
if iteration == 300, return 2.
Args:
iteration (int): Current iteration.
cumulative_period (list[int]): Cumulative period list.
Returns:
int: The position of the right-closest number in the period list.
"""
for i, period in enumerate(cumulative_period):
if iteration <= period:
return i |
def splitList(content, cut):
"""splits an array in two.
arguments :
`content` : (ndarray/list)
the array to split in two.
`cut` : (float) in [0:1]
the ratio by which we will split the array.
"""
c = int(len(content) * cut)
return (content[:c], content[c:]) |
def cast_to_int(value: str) -> int:
"""
Casts to int. Casts the empty string to 0.
"""
if value == '':
return 0
return int(value) |
def flatten_list(li):
"""Flatten shallow nested list"""
return [element for sub_list in li for element in sub_list] |
def generate_nginx_config(app_name=None, urls=None, state_dir='/var/tmp',
app_port=8000, **kwargs):
"""
Generates an nginx config
:param app_name: Name of application
:param urls: List of public urls as strings
:param state_dir: Application state dir (default: /var/tmp)
:param app_port: Application port
"""
if not app_name or not urls:
raise RuntimeError('You must specify an app_name and urls')
cfg = 'upstream {0}_upstream {{\n'.format(app_name)
cfg += ' server 0.0.0.0:{0};\n'.format(app_port)
cfg += '}\n'
cfg += 'server {\n'
cfg += ' listen 80;\n'
cfg += ' server_name {0};\n'.format(' '.join(urls))
cfg += ' server_name_in_redirect off;\n'
cfg += ' location / {\n'
cfg += ' proxy_redirect off ;\n'
cfg += ' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n'
cfg += ' proxy_set_header X-Real-IP $remote_addr;\n'
cfg += ' proxy_set_header Host $host;\n'
cfg += ' proxy_pass http://{0}_upstream;\n'.format(app_name)
cfg += ' }\n'
cfg += '}\n'
return cfg |
def _target_selectors(targets):
"""
Return the target selectors from the given target list.
Transforms the target lists that the client sends in annotation create and
update requests into our internal target_selectors format.
"""
# Any targets other than the first in the list are discarded.
# Any fields of the target other than 'selector' are discarded.
if targets and "selector" in targets[0]:
return targets[0]["selector"]
else:
return [] |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible
looking to the right, False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412435*", 4)
True
>>> left_to_right_check("452453*", 5)
False
"""
input_line = input_line[:-1]
max_dif = -1
counter = 0
input_line = input_line[1:]
idx = int(input_line.index(min(input_line)))
if idx == 0:
counter = 1
for i in range(len(input_line)):
if max_dif < int(input_line[i]) - int(input_line[idx]) and\
int(input_line[i]) - int(input_line[idx]) != 0:
max_dif = int(input_line[i]) - int(input_line[idx])
counter += 1
if counter != pivot:
return False
return True |
def reverse2(snippet):
"""Reverse second sequence.
Change a + b to b - a and a - b or b - a to a + b.
"""
text = snippet
if '0123456789/' in text:
text = text.replace('0123456789/', '9876543210/')
else:
text = text.replace('9876543210/', '0123456789/')
return text |
def findLongestSubstring(a):
""" Finds and returns the longest consecutive subsequence of integers in the provided list. """
lsidx = leidx = csidx = ceidx = 0
# Loop through all the elements in the list with their indices
for i, n in enumerate(a):
# Check if the current number is higher than the last
if i == 0 or n > a[i-1]:
# Increase the candidate range to include the new number
ceidx += 1
# If the current candidate length is greater than the known max, set
# the new maximum
if ceidx - csidx > leidx - lsidx:
lsidx = csidx
leidx = ceidx
else:
# Set the new candidate index range
csidx = i
ceidx = i + 1
# Early stop condition. If the longest subsequence we've found is longer than
# or equal to the number of remaining ints, we know that we don't have to
# keep looking.
if leidx - lsidx >= len(a) - i:
break
return a[lsidx:leidx] |
def subfile_split(value):
"""Split a subfile into the name and payload.
:param value: The value in the SUBFILE tag.
:return: (name, data).
"""
name = value.split(b'\x00', 1)[0].decode('utf-8')
data = value[128:]
return name, data |
def valid(guess):
"""
This is a predicate function to check whether a user input is a letter and with only one letter.
:param guess:
:return: bool
"""
if guess.isalpha() and len(guess) == 1:
return True
return False |
def paths_from_issues(issues):
"""Extract paths from list of BindConfigIssuesModel."""
return [issue.path for issue in issues] |
def verify_expire_version(versioning):
"""
:type: versioning: str
:param versioning: Type of expiration versioning.
Can be only current or previous. Required.
:return: fixed versioning format
:raises: ValueError: Invalid start or limit
"""
VERSION_CONVERT = {"current": "curver_after", "previous": "prever_after"}
versioning = versioning.lower()
if versioning not in VERSION_CONVERT.keys():
raise ValueError("Versioning {0} could not be used, please use either "
"x-versions-location or x-history-location.".format(versioning))
return VERSION_CONVERT[versioning] |
def getObjectLabel(objectData, objectName):
"""
Returns the object label specified in object_data.yaml
:param objectName:
:return:
"""
if objectName not in objectData:
raise ValueError('there is no data for ' + objectName)
return objectData[objectName]['label'] |
def deduplicate(elements):
"""Remove duplicate entries in a list of dataset annotations.
Parameters
----------
elements: list(vizier.datastore.annotation.base.DatasetAnnotation)
List of dataset annotations
Returns
-------
list(vizier.datastore.annotation.base.DatasetAnnotation)
"""
if len(elements) < 2:
return elements
s = sorted(elements, key=lambda a: (a.column_id, a.row_id, a.key, a.value))
result = s[:1]
for a in s[1:]:
l = result[-1]
if a.column_id != l.column_id or a.row_id != l.row_id or a.key != l.key or a.value != l.value:
result.append(a)
return result |
def calc_longitude_shift(screen_width: int, percent_hidden: float) -> float:
"""Return the amount to shift longitude per column of screenshots."""
return 0.00000268 * screen_width * (1 - percent_hidden) * 2
# return 0.0000268 * screen_width * (1 - percent_hidden) |
def translate_ascii(number):
"""
Helper function to figure out alphabet of a particular number
* ASCII for lower case 'a' = 97
* chr(num) returns ASCII character for a number
"""
return chr(number + 96) |
def capillary(srz, ss, crmax, rzsc):
"""capillary rise"""
if rzsc - srz > crmax:
srz += crmax
ss -= crmax
else:
srz += rzsc - srz
ss -= rzsc - srz
return srz, ss |
def remove_first_line(text):
"""Remove the first line from a text block.
source: string of newline-separated lines
returns: string of newline-separated lines
"""
_, _, rest = text.partition('\n')
return rest |
def new_in_list(my_list, idx, element):
"""Replace an element in a copied list at a specific position."""
if idx < 0 or idx > (len(my_list) - 1):
return (my_list)
copy = [x for x in my_list]
copy[idx] = element
return (copy) |
def flatten_json(y):
"""
This supplemental method flattens a JSON by renaming subfields using dots as delimiters between levels
Args:
y - the JSON to flatten
Returns:
A flattened JSON string
"""
out = {}
def flatten(x, name=''):
# If the Nested key-value
# pair is of dict type
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '.')
# If the Nested key-value
# pair is of list type
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '.')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out |
def get_wind_direction_string(wind_direction_in_deg):
"""Get the string interpretation of wind direction in degrees"""
if wind_direction_in_deg is not None:
if wind_direction_in_deg <=23:
return "N"
elif wind_direction_in_deg > 338:
return "N"
elif (23 < wind_direction_in_deg <= 68):
return "NE"
elif (68 < wind_direction_in_deg <= 113):
return "E"
elif (113 < wind_direction_in_deg <= 158):
return "SE"
elif (158 < wind_direction_in_deg <= 203):
return "S"
elif (203 < wind_direction_in_deg <= 248):
return "SW"
elif (248 < wind_direction_in_deg <= 293):
return "W"
elif (293 < wind_direction_in_deg <= 338):
return "NW"
else:
return "Unavailable"
return "Unavailable" |
def convert_latitude(lat_NS):
""" Function to convert deg m N/S latitude to DD.dddd (decimal degrees)
Arguments:
lat_NS : tuple representing latitude
in format of MicroGPS gps.latitude
Returns:
float representing latitidue in DD.dddd
"""
return (lat_NS[0] + lat_NS[1] / 60) * (1.0 if lat_NS[2] == 'N' else -1.0) |
def find_in_list(content, token_line, last_number):
"""
Finds an item in a list and returns its index.
"""
token_line = token_line.strip()
found = None
try:
found = content.index(token_line, last_number+1)
except ValueError:
pass
return found |
def _context_string(context):
"""Produce a string to represent the code block context"""
msg = 'Code block context:\n '
lines = ['Selective arithmetic coding bypass: {0}',
'Reset context probabilities on coding pass boundaries: {1}',
'Termination on each coding pass: {2}',
'Vertically stripe causal context: {3}',
'Predictable termination: {4}',
'Segmentation symbols: {5}']
msg += '\n '.join(lines)
msg = msg.format(((context & 0x01) > 0),
((context & 0x02) > 0),
((context & 0x04) > 0),
((context & 0x08) > 0),
((context & 0x10) > 0),
((context & 0x20) > 0))
return msg |
def load_string_list(file_path, is_utf8=False):
"""
Load string list from mitok file
"""
try:
with open(file_path, encoding='latin-1') as f:
if f is None:
return None
l = []
for item in f:
item = item.strip()
if len(item) == 0:
continue
l.append(item)
except IOError:
print('open error %s' % file_path)
return None
else:
return l |
def is_quantity(d):
""" Checks if a dict can be converted to a quantity with units """
if(isinstance(d,dict) and len(d.keys())==2 and "value" in d and "units" in d):
return True
else:
return False |
def distance_euclidienne_carree(p1, p2):
"""
Calcule la distance euclidienne entre deux points.
"""
x = p1[0] - p2[0]
y = p1[1] - p2[1]
return x * x + y * y |
def flushsearch(hand):
"""
Returns true if a flush exists in the hand.
"""
return len(list(dict.fromkeys(x[1] for x in hand))) == 1 |
def parse_challenge(challenge):
"""
"""
items = {}
for key, value in [item.split(b'=', 1) for item in challenge.split(b',')]:
items[key] = value
return items |
def num_items_in_each_chunk(num_items, num_chunks):
"""
Put num_items items to num_chunks drawers as even as possible.
Return a list of integers, where ret[i] is the number of items put to drawer i.
"""
if num_chunks == 0:
return [0]
num_items_per_chunk = num_items // num_chunks
ret = [num_items_per_chunk] * num_chunks
for i in range(0, num_items % num_chunks):
ret[i] = ret[i] + 1
assert sum(ret) == num_items
return ret |
def _default_with_off_flag(current, default, off_flag):
"""Helper method for merging command line args and noxfile config.
Returns False if off_flag is set, otherwise, returns the default value if
set, otherwise, returns the current value.
"""
return (default or current) and not off_flag |
def sort(lst):
"""Standard merge sort.
Args:
lst: List to sort
Returns:
Sorted copy of the list
"""
if len(lst) <= 1:
return lst
mid = len(lst) // 2
low = sort(lst[:mid])
high = sort(lst[mid:])
res = []
i = j = 0
while i < len(low) and j < len(high):
if low[i] < high[j]:
res.append(low[i])
i += 1
else:
res.append(high[j])
j += 1
res.extend(low[i:])
res.extend(high[j:])
return res |
def containsAll(str, set):
"""Check whether sequence str contains ALL of the items in set."""
for c in set:
if c not in str: return 0
return 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.