content stringlengths 42 6.51k |
|---|
def _get_instance(resp):
"""
Get the one and only match for the instance list in the response. If
there are more or less and one match, log errors and return None.
"""
instances = [i for r in resp['Reservations'] for i in r['Instances']]
# return the one and only match
if len(instances) == ... |
def center(coordinates):
"""
>>> [[0,0],[2, 2]]
(1.0, 1.0)
"""
l = float(len(coordinates))
return (sum((c[0] for c in coordinates))/l, sum(c[1] for c in coordinates)/l) |
def _bin2bcd(value):
"""Convert a binary value to binary coded decimal.
Arguments:
value - the binary value to convert to BCD. (required, no default)
"""
return value + 6 * (value // 10) |
def stack_follow(deck_size, position, *_):
"""Get new position after stacking deck."""
return deck_size - position - 1 |
def int_set_null(int_value):
"""sql util function"""
return "null" if int_value is None else str(int_value) |
def rgb2hsv(c):
"""Convert an RGB color to HSV."""
r,g,b = c
v = max(r,g,b)
mn = min(r,g,b)
range = v-mn
if v == mn:
h = 0
elif v == r:
h = 60*(g-b)/range+(0 if g >= b else 360)
elif v == g:
h = 60*(b-r)/range+120
else:
h = 60*(r-g)/range+240
s = 0 if v == 0 else 1-... |
def remove_spaces(s):
"""Returns a stripped string with all of the spaces removed.
:param str s: String to remove spaces from
"""
return s.replace(' ', '') |
def _get_bit_string(value):
"""INTERNAL. Get string representation of an int in binary"""
return "{0:b}".format(value).zfill(8) |
def bytes2human(size, *, unit="", precision=2, base=1024):
"""
Convert number in bytes to human format.
Arguments:
size (int): bytes to be converted
Keyword arguments (opt):
unit (str): If it will convert bytes to a specific unit
'KB', 'MB', 'GB', ... |
def _Underride(d, **options):
"""Add key-value pairs to d only if key is not in d.
If d is None, create a new dictionary.
d: dictionary
options: keyword args to add to d
"""
if d is None:
d = {}
for key, val in options.items():
d.setdefault(key, val)
return d |
def is_emtpy(struct):
"""
Checks wether the given struct is empty or not
"""
if struct:
return False
else:
return True |
def precision(overlap_count: int, guess_count: int) -> float:
"""Compute the precision in a zero safe way.
:param overlap_count: `int` The number of true positives.
:param guess_count: `int` The number of predicted positives (tp + fp)
:returns: `float` The precision.
"""
if guess_count == 0:
... |
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 'RunPlugin({}, {})'.format(path, ... |
def get_field_aggregation(field):
""" i..e, 'field@{sum}' """
if field and '@{' in field and '}' in field:
i = field.index('@{')
j = field.index('}', i)
cond = field[i + 2:j]
try:
if cond or cond == '':
return (field[:i], cond)
except Exception... |
def split_using(text, quote, sep = '.', maxsplit = -1):
"""
split the string on the seperator ignoring the separator in quoted areas.
This is only useful for simple quoted strings. Dollar quotes, and backslash
escapes are not supported.
"""
escape = quote * 2
esclen = len(escape)
offset = 0
tl = len(text)
en... |
def search_multiple_lines(stationList):
"""
search_multiple_lines: Searches the set of stations that have different lines.
:param
- stationList: LIST of the stations of the current cicty (-id, destinationDic, name, line, x, y -)
:return:
- multiplelines: DICTIONARY which relates the diff... |
def unitarity_decay(A, B, u, m):
"""Eq. (8) of Wallman et al. New J. Phys. 2015."""
return A + B * u ** m |
def listAxes(axd):
"""
make a list of the axes from the dictionary
"""
if type(axd) is not dict:
if type(axd) is list:
return axd
else:
print('listAxes expects dictionary or list; type not known (fix the code)')
raise
axl = [axd[x] for x in axd]
... |
def append_terminal_token(dataset, terminal_token='<e>'):
"""Appends end-of-sequence token to each sequence.
:param dataset - a 2-d array, contains sequences of tokens.
:param terminal_token (Optional) which symbol to append.
"""
return [sample + [terminal_token] for sample in dataset] |
def interpolation(x0: float, y0: float, x1: float, y1: float, x: float) -> float:
"""
Performs interpolation.
Parameters
----------
x0 : float.
The coordinate of the first point on the x axis.
y0 : float.
The coordinate of the first point on the y axis.
x1 : float.
T... |
def searchPFAMmatch(list_pfamId_orga_A:list, list_pfamId_orga_B:list, dict_ddi_sources:dict):
"""
Combine all the pfam ids and check if they exist in the dictionary of ddi, if yes the tuple was add to an array and returned.
This method check the id_pfam_A - id_pfam_B AND id_fam_B - id_pfam_A
:param lis... |
def removesuffix(s, suffix):
"""
Remove the suffix from a string, if it exists.
Avoid needing Python 3.9 just for this.
"""
return s[:-len(suffix)] if s.endswith(suffix) else s |
def nighttime_view(request):
"""Display Imager Detail."""
message = "Hello"
return {'message': message} |
def encode_as_bytes(obj):
"""
Convert any type to bytes
"""
return str.encode(str(obj)) |
def get_scope(field):
"""For a single field get the scope variable
Return a tuple with name:scope pairs"""
name = field['name']
if 'scope' in field['field']:
scope = field['field']['scope']
else:
scope = ''
return (name, scope) |
def FixName(name, uri_prefixes):
"""Converts a Clark qualified name into a name with a namespace prefix."""
if name[0] == '{':
uri, tag = name[1:].split('}')
if uri in uri_prefixes:
return uri_prefixes[uri] + ':' + tag
return name |
def get_unique_tokens(texts):
"""
Returns a set of unique tokens.
>>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl'])
{'oeffentl', 'ist'}
"""
unique_tokens = set()
for text in texts:
for token in text:
unique_tokens.add(token)
return unique_tokens |
def containsAny(s, set):
"""Check whether 'str' contains ANY of the chars in 'set'"""
return 1 in [c in str(s) for c in set] |
def initNxtTrainsIdx(stationTimetbls):
"""
initialises nxtTrainsIdx
"""
nxtTrainsIdx = {};
for stnName,timeTbl in stationTimetbls.items():
index = [];
for i in range(len(timeTbl)):
index.append(0);
nxtTrainsIdx[stnName] = index;
index = None;... |
def preprocess(X, test_X, y, test_y, X_pipeline, y_pipeline, n_train, seed):
"""
Preprocessing using `sklearn` pipelines.
"""
if X_pipeline:
X = X_pipeline.fit_transform(X)
test_X = X_pipeline.transform(test_X)
if y_pipeline:
y = y_pipeline.fit_transform(y)
test_y = ... |
def get_reference_node_parents(ref):
"""Return all parent reference nodes of reference node
Args:
ref (str): reference node.
Returns:
list: The upstream parent reference nodes.
"""
parents = []
return parents |
def even_control_policy(time):
"""Policy carrying out evenly distributed disease management."""
return [0.16]*6 |
def compound_interest(principle: int, rate_pp: float, years: int) -> float:
"""Returns compound interest."""
# print(principle, rate_pp, years)
amount = principle * (pow((1 + rate_pp / 100), years))
# print("amount: ", amount)
return amount - principle |
def int2str( binstr, nbits ):
""" converts an integer to a string containing the binary number
in ascii form, without prefix '0b' and filled with leading
zeros up to nbits
"""
return str(bin(binstr))[2:].zfill(nbits) |
def prepare_config_uri(config_uri: str) -> str:
"""Make sure a configuration uri has the prefix ws://.
:param config_uri: Configuration uri, i.e.: websauna/conf/development.ini
:return: Configuration uri with the prefix ws://.
"""
if not config_uri.startswith('ws://'):
config_uri = 'ws://{u... |
def qtr_to_quarter(qtr):
"""Transform a quarter into the standard form
Args:
qtr (str): The initial quarter
Returns:
str: The standardized quarter
"""
qtr_dict = {
1: (1, "Autumn"),
"AUT": (1, "Autumn"),
"Autumn": (1, "Autumn"),
2: (2, "Winter"),
... |
def _get_kwargs(kwargs, testcase_method):
"""Compatibility with parametrization"""
return dict(kwargs,
**getattr(testcase_method, '_parametrization_kwargs', {})) |
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
... |
def jacobsthal(n):
"""Returns Jacobsthall number.
Arguments:
n -- The index of the desired number in the Jacobsthall sequence.
Returns:
The n-th Jacobsthall number.
"""
if not isinstance(n, int):
raise TypeError('Parameter n must an integer')
if n < 0:
rais... |
def fullscan_policy(obs):
"""
A policy function that generates only fullscan data.
"""
valid_actions = obs['valid_actions']
ms1_action = len(valid_actions) - 1 # last index is always the action for MS1 scan
return ms1_action |
def ext_s(variable, value, substitution):
"""Add a value v to variable x for the given substitution s"""
new = {variable:value}
return {**substitution, **new} |
def database(database=None):
""" Filters search results by database """
if database is None: return
database = database.lower().split(" or ")
for each in database:
if each not in ("general", "astronomy", "physics"):
return ValueError("database must be either general, astronomy, or ... |
def axis_letters(dim_list):
"""Convert dimension list to string.
e.g. ['latitude', 'longitude', 'time'] -> 'yxt'
"""
dim_letters = {'latitude': 'y', 'longitude': 'x',
'time': 't', 'level': 'z'}
letter_list = []
for dim in dim_list:
assert dim in di... |
def check_layer_filters(filters_name):
"""
Check layer names and retern filter layer class
:param filters_name: Layer names
:return: Layer Class list
"""
# Get not import layers
non_target_layers = [fn for fn in filters_name
if fn not in globals().keys()]
for ln... |
def change_to_str(data, rowstr="<br>", count=4, origin_count=4):
"""
This function can turn a data which you give into a str which you can look easily.
Like a dict {"text": 1, "id":2, "reply":3}
call the function changeToStr(text)
you will look follow data:
dict(3) =>{
["text"] => 1
... |
def convert_to_fortran_bool(boolean):
"""
Converts a Boolean as string to the format defined in the input
:param boolean: either a boolean or a string ('True', 'False', 'F', 'T')
:return: a string (either 't' or 'f')
"""
if isinstance(boolean, bool):
if boolean:
return 'T'... |
def index_of(val, in_list):
"""Return index of value in in_list"""
try:
return in_list.index(val)
except ValueError:
return -1 |
def min_sum_first_attempt(arr):
"""
A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array.
Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
Correct problem descrip... |
def revert_correct_V3SciYAngle(V3SciYAngle_deg):
"""Return corrected V3SciYAngle.
Only correct if the original V3SciYAngle in [0,180) deg
Parameters
----------
V3SciYAngle_deg : float
angle in deg
Returns
-------
V3SciYAngle_deg : float
Angle in deg
"""
if V3S... |
def isnumeric(x):
"""Test whether the value can be represented as a number"""
try:
float(x)
return True
except:
return False |
def extract_include_paths(args):
"""
Extract include paths from command-line arguments.
Recognizes two argument "-I path" and one argument "-Ipath".
"""
prefixes = ["-I", "-isystem"]
include_paths = []
prefix = ""
for a in args:
if a in prefixes:
prefix = a
e... |
def _RDSParseDBInstanceStatus(json_response):
"""Parses a JSON response from an RDS DB status query command.
Args:
json_response: The response from the DB status query command in JSON.
Returns:
A list of sample.Sample objects.
"""
status = ''
# Sometimes you look for 'DBInstance', some times you n... |
def gen_team(name):
"""Generate a dict to represent a soccer team
"""
return {'name': name, 'avg_height': 0, 'players': []} |
def IsBinary(data):
"""Checks for a 0x00 byte as a proxy for 'binary-ness'."""
return '\x00' in data |
def docstringTypemap(cpptype):
"""Translate a C++ type to Python for inclusion in the Python docstrings.
This doesn't need to be perfectly accurate -- it's not used for generating
the actual swig wrapper code. It's only used for generating the docstrings.
"""
pytype = cpptype
if pytype.startswit... |
def counting_steps(t):
"""
:param t: int, starts from 0.
:return: int, return times + 1.
"""
t += 1
return t |
def areSetsIntersets(setA, setB):
"""
Check if intersection of sets is not empty
"""
return any(x in setA for x in setB) |
def attr_flag(s):
"""
Parse attributes parameters.
"""
if s == "*":
return s
attr = s.split(',')
assert len(attr) == len(set(attr))
attributes = []
for x in attr:
if '.' not in x:
attributes.append((x, 2))
else:
split = x.split('.')
... |
def hit_edge2d(out, r, c):
"""
Returns True if we hit the edge of a 2D grid
while searching for cell neighbors.
Author: Lekan Molu, September 05, 2021
"""
return ((r<0) or (c<0) or (r>=out[0]) or (c>=out[1])) |
def split_list(mylist, chunk_size):
"""Split list in chunks.
Parameters
----------
my_list: list
list to split.
chunk_size: int
size of the lists returned.
Returns
-------
chunked lists: list
list of the chunked lists.
See: https://stackoverflow.com/a/31246... |
def __write_rnx3_header_obsagency__(observer="unknown", agency="unknown"):
"""
"""
TAIL = "OBSERVER / AGENCY"
res = "{0:20s}{1:40s}{2}\n".format(observer, agency, TAIL)
return res |
def chunkIt(seq, num):
"""Seperate an array into equal lengths
:param seq: The arrray to seperate
:param num: The number of chunks to seperate the array into
:type seq: list
:type num: int
:rtype: list
:return: 2D list of chunks
"""
avg = len(seq) / float(num)
out = []
las... |
def binAndMapHits(hitIter):
"""
return map of assignments to list of reads
"""
hits = {}
hitMap = {}
for (read, hit) in hitIter:
hitMap[read] = hit
if isinstance(hit, list):
for h in hit:
hits.setdefault(h, []).append(read)
else:
hi... |
def merge(list1, list2):
"""
Merge two lists into a list of tuples
"""
return [(list1[i], list2[i]) for i in range(0, len(list1))] |
def Total_Delims(str):
"""
Function to calculate the Total Number of Delimeters in a URL
"""
delim=['-','_','?','=','&']
count=0
for i in str:
for j in delim:
if i==j:
count+=1
return count |
def calc_velocity(dist_m, time_start, time_end):
"""Return 0 if time_start == time_end, avoid dividing by 0"""
return dist_m / (time_end - time_start) if time_end > time_start else 0 |
def handler(event, context):
"""
function handler
"""
res = {}
if isinstance(event, dict):
if "err" in event:
raise TypeError(event['err'])
res = event
elif isinstance(event, bytes):
res['bytes'] = event.decode("utf-8")
if 'messageQOS' in context:
... |
def get_original_order_from_reordered_list(L, ordering):
""" Returns the original order from a reordered list. """
ret = [None] * len(ordering)
for orig_idx, ordered_idx in enumerate(ordering):
ret[ordered_idx] = L[orig_idx]
return ret |
def parse_orgs(org_json):
""" Extract what we need from Github orgs listing response. """
return [{'login': org['login']} for org in org_json] |
def rfind_str(text, sub, start=None, end=None):
"""
Finds the highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``].
Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However,
the index returned is relative to the original string ``tex... |
def Cross(a,b):
"""Cross returns the cross product of 2 vectors of length 3, or a zero vector if the vectors are not both length 3."""
assert len(a) == len(b) == 3, "Cross was given a vector whose length is not 3. a: %s b: %s" % (a, b)
c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
re... |
def phone_number(number):
"""Convert a 10 character string into (xxx) xxx-xxxx."""
#print(number)
#first = number[0:3]
#second = number[3:6]
#third = number[6:10]
#return '(' + first + ')' + ' ' + second + '-' + third
return number |
def insetRect( rectangle, horInset, vertInset):
"""
"""
x, y, w, h = rectangle
dh = horInset / 2.0
dv = vertInset / 2.0
return x+dh, y+dv, w-horInset, h-vertInset |
def escaped_call(fn, *args, **kwargs):
"""
NOTE: In its raw form, this function simply calls fn on the supplied
arguments. Only when encountered by an Autodiff context object does that
change as described below.
Allows users to call functions which can not be recompiled by Autodiff.
When an Au... |
def strings_differ(string1, string2):
"""Check whether two strings differ while avoiding timing attacks.
This function returns True if the given strings differ and False
if they are equal. It's careful not to leak information about *where*
they differ as a result of its running time, which can be very... |
def normalize_us_phone_number(number: str) -> str:
"""Clean phone number and convert is raw US phone number in international format.
:param number: Hand typed US phone number like (555) 123-1234
:return: Raw phone number like +15551231234
"""
assert type(number) == str
digits = "+0123456789"
... |
def split(list):
"""
Divide the unsorted list at midpont into two sublists
Returns two sublists - left and right half
Runs in overall O(k log n) time
"""
mid = len(list)//2
left = list[:mid]
right = list[mid:]
return left, right |
def iterable_str(iterable):
"""
Converts iterable collection into simple string representation.
Returns:
string with commans in between string representation of objects.
"""
return ', '.join((str(elem) for elem in iterable)) |
def numdiff(f, x, h=1E-5):
"""takes the first derivative of function f"""
return (f(x + h) - f(x - h)) / (2 * float(h)) |
def _escape(message):
"""Escape some characters in a message. Make them HTML friendly.
Params:
-----
- message : (str) Text to process.
Returns:
- (str) Escaped string.
"""
translations = {
'"': '"',
"'": ''',
'`': '‘',
'\n': '<br>',
... |
def ms(value):
"""
Convert kilometers per hour to meters per second
"""
return round(value / 3.6, 1) |
def _format_counters(counters, indent='\t'):
"""Convert a map from group -> counter name -> amount to a message
similar to that printed by the Hadoop binary, with no trailing newline.
"""
num_counters = sum(len(counter_to_amount)
for group, counter_to_amount in counters.items())
... |
def extra(request):
""" Add information to the json response """
return {'one': 123} |
def title_getter(node):
"""Return the title of a node (or `None`)."""
return node.get('title','') |
def find_overlapping_cds_simple(v_start, v_stop, cds_begins, strand):
"""
Find overlapping CDS within an exon given a list of CDS starts
"""
# cds_start = cds_begin[0]
if strand == '+':
return list(filter(lambda x: x[0] >= v_start and x[0] < v_stop, cds_begins))
else:
return list... |
def is_left(point0, point1, point2):
""" Tests if a point is Left|On|Right of an infinite line.
Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html
.. note:: This implementation only works in 2-dimensional space.
:param point0: Point P0
:param point1: Point P1
:param... |
def getCommunity(config):
"""Get the SNMPv1 community string from the config file
Args:
config (list[str]): The list generated from configparser.ConfigParser().read()
Returns:
str: The SNMPv1 community string with Write Access to the PDUs
"""
community = config["Credentials"]["comm... |
def n_air(P,T,wavelength):
"""
The edlen equation for index of refraction of air with pressure
INPUT:
P - pressure in Torr
T - Temperature in Celsius
wavelength - wavelength in nm
OUTPUT:
(n-1)_tp - see equation 1, and 2 in REF below.
REF:
... |
def __get_git_url(pkg_info):
"""
Get git repo url of package
"""
url = pkg_info["src_repo"]
return url |
def collect_powers(s,v):
"""
Collect repeated multiplications of string v in s and replace them by exponentiation.
**Examples**::
>>> collect_powers('c*c','c')
'c**2'
>>> collect_powers('c*c*c*c*c*c*c*c*c*c','c')
'c**10'
>>> collect_power... |
def scale_ratio(src_width, src_height, dest_width, dest_height):
"""Return a size fitting into dest preserving src's aspect ratio."""
if src_height > dest_height:
if src_width > dest_width:
ratio = min(float(dest_width) / src_width,
float(dest_height) / src_height)
... |
def str2kvdict(s, sep='@', dlm='::'):
"""Returns a key-value dict from the given string.
Keys and values are assumed to be separated using `sep` [default '@'].
Each key-value pair is delimited using `dlm` [default '::'].
.. warning::
Silently skips any elements that don't have the separator in ... |
def get_neighbor_address(ip):
"""Get the neighbor address in a subnet /30
Args:
ip (`str`): Ip address to get the neighbor for
Returns:
None
"""
# Get the neighbor IP address
ip_list = ip.split(".")
last = int(ip_list[-1])
if last % 2 == 0:
ip_... |
def find_anychar(string, chars, index=None, negate=0):
"""find_anychar(string, chars[, index]) -> index of a character or -1
Find a character in string. chars is a list of characters to look
for. Return the index of the first occurrence of any of the
characters, or -1 if not found. index is the inde... |
def bisect_right(a, x, lo=0, hi=None):
"""bisection search (right)"""
if hi is None: hi = len(a)
while lo < hi:
mid = (lo + hi)//2
if a[mid] <= x: lo = mid + 1
else: hi = mid
return lo |
def framework_supports_e_signature(framework):
"""
:param framework: framework object
:return: Boolean
"""
return framework['isESignatureSupported'] |
def get_name(idx2name, info):
"""
get name from idx2name
"""
idx = info.strip().split('_')
if len(idx) == 1:
if idx[0] in idx2name:
return idx2name[idx[0]]
else:
return idx[0]
elif len(idx) > 1:
ret = []
for i in idx:
if i i... |
def find_in_sequence(predicate, seq):
"""
Returns the index of the first element that matches the given condition, or -1 if none found.
"""
idx = 0
for elem in seq:
if predicate(elem):
return idx
idx += 1
return -1 |
def __py_def(statements,lineno):
"""returns a valid python function."""
function_name = statements.split()[1]
function_name = function_name[:function_name.find('(')]
function_parameters = statements[statements.find('(')+1:statements.find(')')]
py_function = statements[:statements.find('... |
def compute_crop(image_shape, crop_degree=0):
"""Compute padding space in an equirectangular images"""
crop_h = 0
if crop_degree > 0:
crop_h = image_shape[0] // (180 / crop_degree)
return crop_h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.