content stringlengths 42 6.51k |
|---|
def _get_field_length(bit_config):
"""
Determine length of iso8583 style field
:param bit_config: dictionary of bit config data
:return: length of field
"""
length_size = 0
if bit_config['field_type'] == "LLVAR":
length_size = 2
elif bit_config['field_type'] == "LLLVAR":
... |
def paginated_api_call(api_method, response_objects_name, **kwargs):
"""Calls api method and cycles through all pages to get all objects.
Args:
api_method: api method to call
response_objects_name: name of collection in response json
kwargs: url params to pass to call, additionally to li... |
def get_path_from_operation_id(paths_dict, operation_id):
"""Find API path based on operation id."""
paths = paths_dict.keys()
for path in paths:
methods = paths_dict[path].keys()
for method in methods:
if paths_dict[path][method]["operationId"] == operation_id:
r... |
def basic_listifier(item):
"""Takes strings, tuples, and lists of letters and/or numbers separated by spaces, with and without commas, and returns them in a neat and tidy list (without commas attached at the end."""
if type(item) == tuple or type(item) == list:
final = [x.replace(',','') for x in item]
... |
def kadane_max_subarray(A):
"""
Calculate max subarray using Kadane's algorithm.
Used as a test bench against my own algorithms.
"""
max_ending_here = max_so_far = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
ret... |
def word_tokenizer(string):
"""
Splits a string by whitespace characters.
Args:
string (string): The string to be split by whitespace characters.
Returns:
list: The words of the string.
"""
return string.split() |
def print_role(roles):
"""
input: the output from get_role
function prints answer (no output)
"""
rls = ("President", "Prime minister")
for i in range(2):
if len(roles[i]) > 0:
res = rls[i] + " of "
res += ', '.join(roles[i])
print(res)
ret... |
def cleanVersion(version):
""" removes CMSSW_ from the version string if it starts with it """
prefix = "CMSSW_"
if version.startswith(prefix):
return version[len(prefix):]
else:
return version |
def task_read_files(file_paths):
"""
:param file_paths:
:return:
"""
ret = list()
for file_path in file_paths:
content = open(file_path).read()
ret.append((file_path, content))
return ret |
def try_divide(x, y, val=0.0):
"""
Try to divide two numbers
"""
if y != 0.0:
val = float(x) / y
return val |
def make_strain_id_lookup(object_list):
"""a function that lakes of list of strain objects and returns a
dictionary of dictionaries that are keyed first by species, and
then raw strain value.
strains = StrainRaw.objects.values_list("id", "species__abbrev", "strain__strain_code")
This:
[(45, '... |
def is_empty(s):
"""
s : string with description of item
returns True if string is too short
else False
"""
return len(s) <= 2 |
def replace_colon(s, replacewith="__"):
"""replace the colon with something"""
return s.replace(":", replacewith) |
def hue(value):
"""Hue of the light. This is a wrapping value between 0 and 65535."""
value = int(value)
if value < 0 or value > 65535:
raise ValueError('Hue is a value between 0 and 65535')
return value |
def label_vertices(ast, vi, vertices, var_v):
"""Label each node in the AST with a unique vertex id
vi : vertex id counter
vertices : list of all vertices (modified in place)
"""
def inner(ast):
nonlocal vi
if type(ast) != dict:
if type(ast) == list:
# pr... |
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
m1 = text.find(begin)
m2 = text.find(end)
return text[m1+1:m2] |
def convert_value(value):
"""
Convert value into string.
:param value: value
:return: string conversion of the value
:rtype: str
"""
if value is not None:
value = str(value)
return value |
def get_property(name: str) -> str:
"""Provide lookup support for module properties."""
return f'property_{name}' |
def none_check(value):
"""If value is a string containing 'none', then change it to a
NoneType object.
Parameters
----------
value : str or NoneType
Returns
-------
new_value : NoneType
"""
if isinstance(value, str):
if 'none' in value.lower():
new_value = ... |
def find_median_depth(mask_area, num_median, histg):
"""
Iterate through all histogram bins and stop at the median value. This is the
median depth of the mask.
"""
median_counter = 0
centre_depth = "0.00"
for x in range(0, len(histg)):
median_counter += histg[x][0]
if median... |
def remove_extension(filename: str) -> str:
"""
Removes the mp3 or wma extension from a string.
:param filename: Filename to parse.
:return: Filename but without the extension.
"""
for ext in [".wma", ".mp3", ".wav"]:
filename = filename.replace(ext, "")
filename = filename.replace(ext.uppe... |
def significant_round(x, precision):
"""Round value to specified precision.
Parameters
----------
x: float
Value to be rounded
precision: int
Precision to be used for rounding
Returns
-------
float
Rounded value
Examples
--------
>>> significant_rou... |
def is_palindrome(number):
""" Returns True if `number` is a palindrome, False otherwise.
"""
num_str = str(number)
num_comparisons = len(num_str) // 2
for idx in range(num_comparisons):
if num_str[idx] != num_str[-1-idx]:
return False
return True |
def generate_status_details(id, version, message=None):
"""Generate Status Details as defined in TAXII 2.1 section (4.3.1) <link here>`__."""
status_details = {
"id": id,
"version": version
}
if message:
status_details["message"] = message
return status_details |
def find_tag(tag_wrapper, tag_name):
"""Search through a collection of tags and return the tag
with the given name
:param tag_wrapper: A collection of tags in the Google Tag Manager
List Response format
:type tag_wrapper: dict
:param tag_name: The name of a tag to find... |
def z(x: float, m_x: float, s_x: float) -> float:
"""
Compute a normalized score.
>>> d = [ 2, 4, 4, 4, 5, 5, 7, 9 ]
>>> list( z( x, mean(d), stdev(d) ) for x in d )
[-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0]
The above example recomputed mean and standard deviation.
Not a best practice.
... |
def _make_text_bold(bold_msg) -> str:
"""
Return bold_msg text with added decoration using ansi code
:param msg:
:return: u"\u001b[1m"+ bold_msg + u"\u001b[0m"
"""
return u"\u001b[1m"+ bold_msg + u"\u001b[0m" |
def strip_math(s):
"""remove latex formatting from mathtext"""
remove = (r'\mathdefault', r'\rm', r'\cal', r'\tt', r'\it', '\\', '{', '}')
s = s[1:-1]
for r in remove:
s = s.replace(r, '')
return s |
def de_list(lst):
"""Turn a list into a scalar if it's of length 1, respecting Nones."""
if not lst:
return None
else:
return (lst[0] if len(lst) == 1 else lst) |
def durationToPoints(duration):
"""
less than 15 is not considered 'away'.
"""
if duration < 15:
points = 0
else:
points = duration
return points |
def _remove_duplicates(list):
"""
Returns list of unique dummies.
"""
result = []
while list:
i = list.pop()
if i in result:
pass
else:
result.append(i)
result.reverse()
return result |
def extra_same_elem(list1: list, list2: list) -> list:
"""
extract the same part between 2 lists
Args:
list1: list 1
list2: list 2
Returns:
same part between 2 lists
"""
set1 = set(list1)
set2 = set(list2)
same_elem = set1.intersection(set2)
... |
def compare_loginhashblock(a, b, DEBUG=False):
"""
This function is to compare tow login hash block. If these are same, it return True. others cases, it return False
:param a: compare login hash block
:param b: compare login hash block
:return: Bool
"""
if DEBUG:
print("[info:compar... |
def series_sum(n):
"""Create and return the nth number in a Series."""
x, j = 4, 1
if n == 0:
return "0.00"
for i in range(n - 1):
j = j + 1 / x
x = x + 3
return format(j, '.2f') |
def usage(myname="xia2ccp4i.py"):
"""return a usage string"""
msg = """%s [options]
Options:
-h, --help show this help message and exit
-p FOO, --project=FOO override the project name taken from xia2, and call
the CCP4 project FOO
-x BAR, --xia2dir=BAR specify the ... |
def ordered(obj):
"""Order map for comparison
https://stackoverflow.com/questions/25851183/
"""
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj |
def snake_to_camel_case(data):
"""
Convert all keys of a all dictionaries inside given argument from
snake_case to camelCase.
Inspired by: https://stackoverflow.com/a/19053800/1073222
"""
if isinstance(data, dict):
camel_case_dict = {}
for key, value in data.items():
... |
def convert_labels(data_in, label_map):
"""Convert labels in data=[(txt, lbl)] according to the map
Drop if label does not exist in map
"""
data = []
missing = []
for (txt, lbl) in data_in:
if lbl not in label_map:
missing.append(lbl)
else:
# convert labe... |
def wordToCamelCase(w: str) -> str:
"""
Transform a word w to its CamelCase version.
This word may already be a CamelCase.
Cannot correctly handle two successive UPPERWORDS. Will output: Upperwords
"""
res = ""
for i, c in enumerate(w):
if c.isupper() and (
i == 0 or... |
def redact_after_symbol(text:str, symbol:str) ->str:
"""Replaces all characters after a certain symbol appears with XXXXX"""
r_start = text.find(symbol)
r_len = len(text) - r_start
to_redact = text[r_start:]
return text.replace(to_redact, "X"*r_len) |
def is_dict_like(value):
"""Check if value is dict-like."""
return hasattr(value, 'keys') and hasattr(value, '__getitem__') |
def get_maximum_order_unary_only(per_layer_orders_and_multiplicities):
"""
determine what spherical harmonics we need to pre-compute. if we have the
unary term only, we need to compare all adjacent layers
the spherical harmonics function depends on J (irrep order) purely, which is dedfined by
order... |
def extractData(line):
"""Assume the first colon (:) separates the key from the value."""
separator = ':'
line_data = line.strip().split(separator)
key = line_data[0]
# the value may contain a separator so will need to be reassembled from
# possibly multiple elements
value = separator.join(l... |
def trunc(str, max_size=140):
"""Basic sring truncation"""
if len(str) > max_size:
return str[0:max_size - 3] + "..."
return str |
def is_public(data, action):
"""Check if the record is fully public.
In practice this means that the record doesn't have the ``access`` key or
the action is not inside access or is empty.
"""
return "_access" not in data or not data.get("_access", {}).get(action) |
def guess_newline(value: str, unit: str) -> float:
"""
Tries to guess where a newline in the given value with the given unit could
be, splits there and returns the first value. The unit expected to be
casefolded.
This is done because pandas has some trouble reading in table values with a
newlin... |
def build_http_request(method: str, path: str, host: str, extra_headers=[], body: str = "") -> str:
"""
Returns a valid HTTP request from the given parameters.
Parameters:
- `method` - valid HTTP methods (e.g. "POST" or "GET")
- `path` - the path part of a URL (e.g. "/" or "/index.html")
- `hos... |
def idf(duration, A, B, C):
"""Calculate intensity for specified duration given IDF parameters A, B, and C.
Args:
duration: duration to calculate intensity for. Unit: minutes
A: constant A in equation i = A / (duration + B)**C.
B: constant B in equation i = A / (duration + B)**C.
... |
def sensor_data(date, quantity, value, unit,
temp, temp_unit,
sensor_info, sensor_name, sensor_id,
instrument_name, instrument_id):
"""
Single exit point of data to ensure uniform dict structure.
"""
return {"date": date,
"quantity": quantity, "value": value, "unit": unit,
... |
def rivers_with_station(stations):
"""Takes a list of stations and returns a set of the names of the rivers"""
set_of_rivers = set() # create set (to avoid duplicates)
for s in stations:
set_of_rivers.add(s.river) # add rivers to set
return sorted(set_of_rivers) |
def parse_int(string):
"""
Like int(), but just returns None if it doesn't parse properly
"""
try:
return int(string)
except ValueError:
pass |
def access_issued(issued):
""" Access function for issued field. """
try:
return issued['date-parts'][0][0]
except:
pass |
def common(string1, string2):
""" Return common words across strings1 1 & 2 """
s1 = set(string1.lower().split())
s2 = set(string2.lower().split())
return s1.intersection(s2) |
def daily_et( alpha_pt, delta_pt, ghamma_pt, rnet, g0 ):
"""
Calculates the diurnal evapotranspiration after Prestley and Taylor (1972) in mm/day.
alpha_pt = 1.26 , this is the recommended Prestley-Taylor Coefficient
PT_daily_et( alpha_pt, delta_pt, ghamma_pt, rnet, g0 )
"""
result = (alpha_pt/28.588) * ( delta_p... |
def set_font_size(locDbl_harmonic_order):
"""
.. _set_font_size :
Decrese the font size with increased harmonic order.
A deadband is included (between 4 pt and 10 pt).
Equation for calculation:
.. code:: python
locDbl_font_size = -0.5 * abs(locDbl... |
def format_all_sides(value):
"""Convert a single value (padding or border) to a dict
with keys 'top', 'bottom', 'left' and 'right'"""
all = {}
for pos in ('top', 'bottom', 'left', 'right'):
all[pos] = value
return all |
def parse_git_version(git) :
"""Parses the version number for git.
Keyword arguments:
git - The result of querying the version from git.
"""
return git.split()[2] |
def get_index(fields, keys):
""" Get indices of *keys*, each of which is in list *fields* """
assert isinstance(keys, list)
assert isinstance(fields, list)
return [fields.index(k) for k in keys] |
def britishize_americanize(string, final_dict):
"""
Parameters:
string(str): original string
final_dict(dict): dictionary with all the different possible words in american and british english
Returns:
str: String after replacing the words
"""
string = " ".join([final_dict.get... |
def get_num_label_vols(md):
"""
Get the number of volumes used for labelling - e.g. 2 for tag-control pair data
"""
iaf = md.get("iaf", "tc")
if iaf in ("tc", "ct"):
return 2
elif iaf == "diff":
return 1
elif iaf == "mp":
return md.get("nphases", 8)
elif iaf == "v... |
def fetch_page_details(resp):
"""
Parse total element, page number and total pages from the page.
:param resp: json response.
:return: page details.
"""
total_element = resp.get('page', {}).get('totalElements', 0)
page_number = resp.get('page', {}).get('number', 0)
total_pages = resp.ge... |
def at_index(string, element_index):
""" Get the string at the specified index of a list seperated by ',' """
len_string = len(string)
current_index = 0
current_ptr = 0
is_in_quote = False
is_escaped = False
while current_ptr < len_string and current_index < element_index:
if not ... |
def sanitize_word(s):
"""Ensure that a string is in fact a single word with alphanumeric characters.
Useful for avoiding code injection.
Args:
s (str): string to be inserted into code.
Returns:
(str): the same string, stripped of whitespace.
Raises:
ValueError: the string c... |
def first(iterable, predicate=lambda x: True):
"""
Returns the first item in the `iterable` that
satisfies the `condition`.
If the condition is not given, returns the first item of
the iterable.
Raises `StopIteration` if no item satisfying the condition is found.
"""
return next(x for... |
def parse_list(string, convert_fn):
"""Parse a (possibly empty) colon-separated list of values."""
string = string.strip()
if string:
return [convert_fn(piece) for piece in string.split(':')]
else:
return [] |
def should_show_entry_state(entry, current_api_id):
"""Returns wether or not entry state should be shown.
:param entry: Contentful entry.
:param current_api_id: Current API selected.
:return: True/False
"""
return (
current_api_id == 'cpa' and
(
entry.__dict__.get('... |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for indx in range(0, len(nums)):
# print((target - nums[indx]) in d)
if ((target - nums[indx]) in d):
return [d[target - nums[indx]], indx]
d[nums[indx]] = i... |
def best_match(names, i):
"""
Find matches starting from index i.
Matches have to be at least 3 letters, otherwise it's a mess for big sets.
Go with largest set of matches instead of longer matches.
Return (number of matches, matching chars)
"""
matchlen = 3
nmatches = 1
while (i+nma... |
def parse_time(timestr):
"""Parse a human-writable time string into a number of seconds"""
if not timestr: return 0
if ":" not in timestr:
return int(timestr)
neg = timestr.startswith("-") # "-5:30" means -330 seconds
min, sec = timestr.strip("-").split(":")
time = int(min) * 60 + int(sec)
if neg: return -time... |
def resolveGeneration(dependencies):
""" resolve those who i depend on """
generated = []
def __append(me):
if me not in generated:
generated.append(me)
def __resolve(me, my_dependencies):
if len(my_dependencies) == 0:
""" i dont depend on anyone really """
... |
def create_artifact(artifact_id, artifact_alias, artifact_name, artifact_type,
artifact_checksum, artifact_label, artifact_openchain,
prev, cur, timestamp, artifact_list=[], uri_list=[]):
"""
Constructs the payload to be stored in the state storage.
Args:
... |
def CRP_next(lambdas,topic):
"""
Description
---------
Funcion: Chinese Restaurant Process
Parameter
---------
alpha: concentration parameter
topic: the exist tables
Return
------
p: the probability for a new customers to sit in each of the tables
"""
impo... |
def float_repr(value: float) -> str:
""" Pretty print float """
spl = '{:e}'.format(value).split('e')
exp = 'e' + spl[1]
if abs(int(spl[1][-2:])) <= 3:
spl[0] = '{:.8f}'.format(value)
exp = ''
return spl[0].rstrip('0').rstrip('.') + exp |
def make_GeoJson(geoms, attrs):
"""
Creates GeoJson structure with given geom and attribute lists; throws exception if both lists have different length
:param geoms: list of geometries (needs to be encoded as geojson features)
:param attrs: list of attributes
:return: dict in GeoJson structure
"... |
def concatonate_my_arguments(one, two, three):
"""In this challenge you need to concatenate all the arguments together and return the result
The arguments will always be strings
"""
return one + two + three |
def get_largest_item_size(iterable):
"""
Given a iterable, get the size/length of its largest key value.
"""
largest_key = 0
for key in iterable:
if len( key ) > largest_key:
largest_key = len( key )
return largest_key |
def is_relative_url(url):
"""Return true if url is relative to the server."""
return "://" not in url |
def _get_final_result(x):
"""Apply function for providing a final status of the application"""
result_code, attending, waitlisted, deferred, stage, app_type = x
if result_code == "denied":
return "Denied"
elif result_code in ["accepted", "cond. accept", "summer admit"]:
if attendin... |
def to_list(outputs):
"""Converts layer outputs to a nested list, for easier equality testing.
Args:
outputs: A tensor or tuple/list of tensors coming from the forward
application of a layer. Each tensor is NumPy ndarray-like, which
complicates simple equality testing (e.g., via `assertEquals`)... |
def _time_to_minutes(time_dhms):
""" Converting time from 'd-hh:mm:ss' to total minutes """
x = time_dhms.split('-')
if len(x) > 1:
days = int(x.pop(0))
else:
days = 0
x = x[0].split(':')
hours = int(x[0])
minutes = int(x[1])
# return number of minutes
return day... |
def r_to_depth(x, interval):
"""Computes rainfall depth (mm) from rainfall intensity (mm/h)
Parameters
----------
x : float,
float or array of float
rainfall intensity in mm/h
interval : number
time interval (s) the values of `x` represent
Returns
-------
output... |
def format_list_of_string_2_postgres_array(list_of_string):
"""
removes internal spaces
:param list_of_string: List of String
:return: String
"""
return "{" + str(list_of_string)[1:-1].replace(" ", "").replace("'", '"') + "}" |
def fib(n):
"""defines n as
a fibonacci number, fib()
is is a function in the Python standard library)"""
i = 0
j = 1
n = n - 1
"""assigns initial values to the varibles
i & j, assigns a calculation to the variable n"""
while n >= 0:
i, j = j, i + j
n = n - 1
return i
"""interates over th... |
def encode_http_response(
status, reason, version="HTTP/1.1",
headers=None, entity=None, **kwargs):
"""return http message encoding response"""
buf = []
# 'dictify' headers
headers = dict(headers or [])
# add status line
buf.append("%s %i %s\r\n" % (version, status, reason))
... |
def translate_special_params(func_params, attributes_map):
"""
:param func_params:
:param attributes_map:
:return:
"""
params = {}
for key, value in func_params.items():
if key in attributes_map:
params[attributes_map[key]] = value
else:
params[key] ... |
def rasterizeSegment(start_x, start_y, end_x, end_y):
"""Implementation of Bresenham's line rasterization routine.
This is a slightly modified version of the Python implementation
one Rosetta code: https://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#Python
Args:
start_x: the ... |
def build_eval_subdir(list_of_label_value):
"""Create evaluation subdir name from a list of evaluation parameters"""
tokens = []
for label,value in list_of_label_value:
if value is None:
continue
tokens.append('%s(%s)' % (label, value))
result = "_".join(tokens)
if le... |
def ordinal(n):
"""
Convert a positive integer into its ordinal representation
"""
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
if 11 <= (n % 100) <= 13:
suffix = "th"
return str(n) + suffix |
def approvals_percentage(
approvals, decimal_digits=2, default_percentage_value=0
):
"""Calculates supervisor's approvals rate percentage value.
:param approvals: A dict consisting of forms processed by supervisor
and forms sent for review by supervisor.
:param decimal_digits: The number of dig... |
def binary_to_decimal( binary_string ):
"""
Takes a binary number (as a string) and returns its decimal equivalent
"""
decimal = 0
for i in range( len( binary_string ) ):
decimal += 2**i * int( binary_string[-i-1] )
return decimal |
def filter_datastores_by_hubs(hubs, datastores):
"""Get filtered subset of datastores corresponding to the given hub list.
:param hubs: list of PbmPlacementHub morefs
:param datastores: all candidate datastores
:returns: subset of datastores corresponding to the given hub list
"""
filtered_dss ... |
def rna_id(entry):
"""
Get the UPI for the entry, or fail if there is none.
"""
if entry["DB"] == "RNAcentral":
return entry["DB_Object_ID"]
raise ValueError("All entries are expected to come from RNAcentral") |
def _mangle_user(name):
"""Mangle user variable name
"""
return "__user_{}".format(name) |
def stateful(o):
"""Mark an object as stateful
In:
- ``o`` -- the object
Return:
- ``o``
"""
if hasattr(o, '_persistent_id'):
del o._persistent_id
return o |
def calculate_distance(point1, point2):
"""Calculate the distance (in miles) between point1 and point2.
point1 and point2 must have the format [latitude, longitude].
The return value is a float.
Modified and converted to Python from:
http://www.movable-type.co.uk/scripts/latlong.html
"""
i... |
def suma_listas (l_1, l_2):
"""
list, list --> list
OBJ: sumar l_1 + l_2
"""
l_3 = []
for i in range (len(l_1)):
l_3.append (l_1[i] + l_2[i])
return l_3 |
def when_did_it_die(P0, days):
"""
Given a P0 and an array of days in which it was alive, censored or dead,
figure out its lifespan and the number of days it was alive'
Note, the lifespan is considered to last up to the last observation.
I.e., a worm that was observed to live 3 days, and died o... |
def sub2ind(range, x, y):
"""Convert subscripts to linear indices"""
return y * range + x |
def kid_friendly_validation(children):
""" Decide if kid_friendly input valid.
Parameters:
children(str): A user's input to the kid-friendly choice.
Return:
(str): A single valid string, such as "1" or "2".
"""
while children != "1" and children != "2" :
pri... |
def find_rank_type(ranks):
"""Find and return the rank type of the 3 ranks given
Rank type results:
1: no particularly interesting rank order, i.e. High Card
2: pair rank
4: straight
5: three of a kind
"""
ranks.sort()
if ranks[0] == ranks[1] == ranks[2]:
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.