content stringlengths 42 6.51k |
|---|
def last(seq):
"""Returns the last item in the sequence or iterator.
Returns None if the sequence is empty."""
try:
return seq[-1]
except IndexError:
return None
except TypeError:
item = None
for item in seq:
pass
return item |
def makeSafeXML( someString:str ) -> str:
"""
Replaces special characters in a string to make it for XML.
"""
return someString.replace('&','&').replace('"','"').replace('<','<').replace('>','>') |
def seconds2human(seconds, keep_short=True, full_name=False):
"""Returns a human readable time range string for a number of seconds.
>>> lib.base2.seconds2human(0.125)
'0.12s'
>>> lib.base2.seconds2human(1)
'1s'
>>> lib.base2.seconds2human(59)
'59s'
>>> lib.base2.seconds2human(60)
'... |
def fake_context(*args, **kwargs):
"""Empty 'function' to fool context."""
if args:
return args[0] |
def get_distance(source, target):
"""Get Manhattan distance between points source and target."""
return sum(abs(val1 - val2) for val1, val2 in zip(source, target)) |
def multiple(a,b):
"""
Return True if a is a multiple of b and False instead
"""
if a%b == 0 :
return True
return False |
def change_true(arg):
"""Change True to true for request headers"""
if arg == True:
arg = 'true'
return arg |
def remap( v, fromLo, fromHi, toLo, toHi):
""" remaps a value (v) from one range to another """
return float(v-fromLo)/(fromHi-fromLo)*(toHi-toLo)+toLo |
def join_dicts(*args):
"""Joins any number of dictionaries into a new single dictionary.
Args:
*args: one or more dictionaries
Returns:
a single dictionary containing all items.
"""
d = {}
for di in args:
d.update(di)
return d |
def format_internal_data_var(data_var):
"""Convert data_var to a properly formatted Python code string"""
def _format_dict(d, indent):
dict_str = indent + '{\n'
for key, value in d.items():
if type(value) == str:
v = repr(value)
else:
v = s... |
def aggregate_keane_wolpin_utility(wage, nonpec, continuation_value, draw, delta):
"""Calculate the utility of Keane and Wolpin models.
Note that the function works for working and non-working alternatives as wages are
set to one for non-working alternatives such that the draws enter the utility
functi... |
def damerau_levenshtein(string_1, string_2):
"""
Calculates the Damerau-Levenshtein distance between two strings.
In addition to insertions, deletions and substitutions,
Damerau-Levenshtein considers adjacent transpositions.
This version is based on an iterative version of the Wagner-Fischer algor... |
def bedroom_count(sfmain, site):
""" (float, float) -> int
Return 3, 2, or 1 indicating the number of bedrooms a backyard house could have
based on the size of the lot (site), and the size of the main house (sfmain).
The area of the main structure plus the backyard house should be less than
the siz... |
def dottedname(entity):
"""Return a dotted name to the given named entity"""
return entity.__module__ + '.' + entity.__name__ |
def _is_type_hint(obj):
""" Check if object is stored along with its type in the typical format:
[str, str] => [typehint, value] e.g. ['$complex', (3 + 4j)]
"""
return isinstance(obj, list) \
and len(obj) == 2 \
and isinstance(obj[0], str) \
and obj[0][0] == '$' |
def solution(array):
"""
Returns the value of the maximal product of three values in an array.
"""
array.sort()
# For the maximal product, we might have to multiply two negative values,
# that is why we compare the product of the three biggest elements with
# the product of the biggest element and the... |
def reduce(func, llist, initval):
""" Successively applying the given function to the elements in the LinkedList with an initial value """
while llist != None:
try:
initval = func([initval, llist.elt])
except:
initval = func.call([initval, llist.elt])
llist = lli... |
def brute_force(goal=1000):
"""Brute force method to find Pythagorean triplet with some of goal.
Since a < b < c:
* a is less than a third (1/3) of the goal, (a < goal//3)
* b is greater than a and less than half(1/2) of the goal (a < b < goal//2)
* c is one of the remaining numbers (goal//2 <= c)... |
def rot(c, n):
""" Helper Function: rotates a single character c forward by n
spots in the alphabet
"""
# check to ensure that c is a single character
assert(type(c) == str and len(c) == 1)
# Put the rest of your code for this function below.
if 'a' <= c <= 'z': #Low... |
def load_report(report):
"""Splits the report from a string into a list of list of "bits" """
return [list(c for c in code) for code in report.split("\n") if len(code)] |
def c_terminal_proline(amino_acids):
"""
Is the right-most (C-terminal) amino acid a proline?
"""
return amino_acids[-1] == "P" |
def sort_tuple(tup, y) -> set:
"""returns sorted tuple"""
tup.sort(key=lambda x: x[y])
return tup |
def average(a:int,b:int) -> float:
"""
Returns average of two given numbers
>>> average(2,2)
2.0
"""
return (a+b)/2 |
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
index = 0
for p in paragraphs:
if select(p):
if ... |
def getValue( x ):
"""
If x is a tuple return the first entry, else return x.
Arguments:
x: The object to get the value of.
"""
if isinstance( x, tuple ):
return x[ 0 ]
else:
return x |
def AND(a,b):
""" logical and of a and b """
if (a != 0 and b != 0):
return 1
else:
return 0 |
def get_color(matrix):
"""Returns the color of the matrix (excluding black)
"""
for a in matrix:
for color in a:
if color != 0:
return color |
def slugify_url(url):
"""
Turn '/study/connect_me/' into 'study-connect-me'.
"""
return url.lower().strip("/").replace(":", "-").replace("/", "-").replace("_", "-") |
def prettyprint_file_size(size_b: int) -> str:
"""
Format a filesize in terms of bytes, KB, MB, GB, whatever is most appropriate.
:param size_b: int size in bytes
:return: string
"""
if size_b < 1024:
# bytes
ret = "%d B" % size_b
elif size_b < 1024*1024:
# kilobytes
s = size_b / 1024
ret = "{:.2f} KB"... |
def decode(byte_data):
"""
Decode the byte data to a string if not None.
:param byte_data: the data to decode
"""
if byte_data is None:
return None
return byte_data.decode() |
def add_titles(hot_list, children):
"""
adds new titles to hottlist
"""
for child in children:
hot_post = child.get('data')
title = hot_post.get('title')
hot_list.append(title)
return hot_list |
def wrapto180(angles):
"""
Put all angles (in degrees) in the range -180..180
:param angles: numpy vector or scalar
:return:
"""
return (angles % 360 + 180) % 360 - 180 |
def convert_BtoI(vector):
"""Convierte un vector booleano a un vector de ceros y unos"""
result = []
for i in vector:
if i == True:
result.append(1)
else:
result.append(0)
return result |
def dict_item_to_string(key, value):
"""
inputs: key-value pairs from a dictionary
output: string 'key=value' or 'key=value1,value2' (if value is a list)
examples: 'fmt', 'csv' => 'fmt=csv' or 'r', [124, 484] => 'r=124,484'
"""
value_string = str(value) if not isinstance(value, list) else ','.jo... |
def function_reduce(function_to_apply, iterable):
"""Apply function of two arguments cumulatively"""
ret = None
for i, it in enumerate(iterable):
if i == 0:
ret = it
continue
ret = function_to_apply(ret, it)
return ret |
def parse_url(url):
"""Parse a PIM connection string """
scheme, dest = url.split("://")
host = None
if scheme == "tcp":
host, port = dest.split(":") if ":" in dest else (dest, 2101)
elif scheme == "serial":
host, port = dest.split(":") if ":" in dest else (dest, 4800)
else:
... |
def sz_to_ind(sz, charge, nsingle):
"""
Converts :math:`S_{z}` to a list index.
Parameters
----------
sz : int
Value :math:`S_{z}` of a spin projection in the z direction.
charge : int
Value of the charge.
nsingle : int
Number of single particle states.
Returns
... |
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val |
def gcd(a, b):
"""
>>> gcd(2, 3)
1
>>> gcd(-2, 3)
1
"""
if a > b:
return gcd(b, a)
if a < 0:
return gcd(0-a, b)
if a == 0:
return b
return gcd(b % a, a) |
def construct_line(label, line):
"""Build a data line using generic numbers for features"""
# Can scale the label (target) here, and convert multiclass datasets
# to have label vectors.
# Ex: if label==4 and there are 5 possible classes,
# target vector = 0,0,0,1,0 (start class index at 1)... |
def triple_length(m: int, n: int) -> int:
"""Returns the length of the triangle formed by the Pythagorean triple
(m^2 - n^2, 2mn, m^2 + n^2)."""
return 2 * m * (m + n) |
def _wiki_url(title: str):
"""
GitHub Wiki collapses directory structure.
After `wiki_migrate.py` replaced the path separator `/` with space,
GitHub converts spaces to dashes in the URLs.
Therefore, the original Trac links must get dashes as well.
"""
return title.replace('/', '-') |
def pipe_info(source, sink):
"""Return stream information header."""
# First line
if source is None:
source = ''
else:
source = f' from {repr(source)}'
if sink is None:
sink = ''
else:
sink = f' to {repr(sink)}'
return f"{source}{sink}" |
def equivalent_chrono_pairs(pair_a, pair_b, model = None):
"""Returns True if the two chronostratigraphic pairs are equivalent"""
if pair_a == pair_b:
return True
if pair_a is None or pair_b is None:
return False
if pair_a == (None, None) or pair_b == (None, None):
return False
... |
def parse_line_4(bitmap):
"""converts 4 bytes into 1 byte. Used in 4-color modes"""
ba = bytearray()
for i in range(len(bitmap) // 4):
b1 = bitmap[i * 4 + 0]
b2 = bitmap[i * 4 + 1]
b3 = bitmap[i * 4 + 2]
b4 = bitmap[i * 4 + 3]
if b1 > 3 or b2 > 3 or b3 > 3 or b4 > 3:
... |
def unpack(seq):
""" Unpack sequence of length one
>>> unpack([1, 2, 3])
[1, 2, 3]
>>> unpack([1])
1
"""
seq = list(seq)
if len(seq) == 1:
seq = seq[0]
return seq |
def get_pod_selector(pod):
"""
Returns:
The string representing the labelSelector to select pods of this
general type.
"""
labels = pod['metadata'].get('labels', {})
# We don't use the 'pod-template-hash' label because we want to schedule
# our new pods onto the node they're curr... |
def slice_pagination(page_range, current_page):
"""Slices paginator.page_range to limit which page links are displayed
The logic for which page numbers are shown is based on Google Search's
pagination.
Examples:
When current_page is within the first four pages
1 [2] 3 4 5 6 7 8
When ... |
def get_args_command_name(layer: int):
"""Return the specified layer's command name"""
return "__layer{layer}_command".format(layer=layer) |
def is_prefixed_with(str, prefix):
"""
:param str: An input word / sub-word
:param prefix: A prefix to check in the word / sub-word
:return bool: True if prefix, else False
"""
return(str.find(prefix) == 0) |
def replace_spaces(text: str) -> str:
"""Replaces spaces with '+' in given text.
:param text: The text to be formatted.
returns: Text with spaces replaced with '+'.
"""
return text.replace(" ", "+") |
def viz_table(body, border=0, cellborder=1, cellpadding=2, cellspacing=0, # pylint: disable=too-many-arguments, unused-argument
bgcolor="white", color="dodgerblue3"): # pylint: disable=unused-argument
"""Create HTML table for graphviz"""
return (
'<TABLE ... |
def _validate_BC(bc):
"""Checks if boundary condition 'bc' is valid.
Each bc must be either 'dirichlet' or 'neumann'
"""
if isinstance(bc, str):
bc = [bc, bc]
if not isinstance(bc, list):
raise TypeError("bc must be a single string or list of strings")
if not len(bc) == 2:
... |
def normal_response(response):
"""
Construct non-error response for API from giving response
dictionary. Return a dictionary.
"""
response = dict(response)
response["error"] = None
return response |
def sec2sec_ms(sec):
"""Converts float seconds into seconds and microseconds
Parameters
----------
sec : float
Returns
-------
seconds : int
microsec : int
"""
microsec = (sec - int(sec)) * 1e+6
microsec = float("%.1f" % microsec)
return int(sec), int(microsec) |
def total_length(l):
"""
Returns the sum of the lengths of the elements in a given list of strings.
"""
total = 0
for x in l:
total += len(x)
return total |
def square2(value):
""" Return the square of a value"""
new_value = value ** 2
return new_value |
def postprocess_continuations(continuation_set, ocp_map_inverse):
"""
Post processes the data after the continuation process has run.
:param continuation_set: The set of all continuation processes.
:param ocp: The compiled OCP.
:param prob: The compiled BVP.
:param ocp_map_inverse: A mapping co... |
def cast_bytes_to_memory_string(num_bytes: float) -> str:
"""
Cast a number of bytes to a readable string
>>> from autofaiss.utils.cast import cast_bytes_to_memory_string
>>> cast_bytes_to_memory_string(16.*1024*1024*1024) == "16.0GB"
True
"""
suffix = "B"
for unit in ["", "K", "M", "G... |
def _fp_almost_equal(x: float, y: float, delta: float = 1e-10) -> bool:
"""Compares given two floating point numbers with delta compensation"""
return abs(x - y) < delta |
def inverse(x):
"""Compute the inverse of x if x not null."""
if x != 0:
return 1 / x
else:
return 10e10 |
def difference_two(struct1, struct2):
"""
This function compares two lists of fields.
This function accepts two lists, as might be returned by the previous function, and compares the different fields. It returns
a dictionary with for each separate list, detailing the number of fields in that list ... |
def _rgb_to_webcode(rgb_values):
"""
Convert RGB values to webcodes.
Inputs:
rgb_value: a tuple of RGB values (0~1, float)
Returns:
webcode: a webcode string encoding the RGB values
"""
webcode = "#"
for value in rgb_values:
code_ = hex(int(value*255)).replace('0x', '')
... |
def _parse_string_as_bool(s):
"""Parses a string as a boolean argument."""
lower = s.lower()
if lower == "true":
return True
elif lower == "false":
return False
else:
raise ValueError("Expected either 'true' or 'false'; got {}".format(s)) |
def build_profile2(first, last, **user_info):
"""Build dict containing everything we know about a user"""
profile = {}
profile['first name'] = first
profile['last name'] = last
for key, value in user_info.items():
profile[key] = value
return profile |
def get_es_mapping(es, es_index):
"""
Get es mapping for given doc type (so we can handle type=nested)
Note this is the mechanism by which we "enable" the ability to do nested searches
ie: only enabled on single index searches. You could feasibly add more criteria.
:param es: elasticsearch client
... |
def find_lowest(tem, l):
"""
:param tem:int, the temperature that user entered.
:param l:int, the lowest temperature so far.
This function finds the lowest temperature.
"""
min = l
if tem < l:
return tem
return l |
def escape_string(string):
"""Escape a string for use in Gerrit commands.
:arg str string: The string to escape.
:returns: The string with necessary escapes and surrounding double quotes
so that it can be passed to any of the Gerrit commands that require
double-quoted strings.
"""
... |
def change_value(obj,key,value):
"""
This function accept three params
and iterats over the obj(dict) and replace value
of the key
Arg:
obj (dict) : dictionary object
key : pass the key.
value = value to be replaced insitited of previous val... |
def validate_byr(field):
"""
byr (Birth Year) - four digits; at least 1920 and at most 2002.
"""
return field.isdigit() and 1920 <= int(field) <= 2002 |
def hm_to_float(hours: int, minutes: int) -> float:
"""Convert time in hours and minutes to a fraction of a day
:type hours: int
:type minutes: int
:rtype: float
"""
if not (0 <= hours < 24 and 0 <= minutes < 60):
raise ValueError("Incorrect time")
return hours / 24 + minutes / 60 /... |
def numeric_to_native(val):
"""
Given a numeric string (as defined by fluent spec),
return an int or float
"""
# val matches this EBNF:
# '-'? [0-9]+ ('.' [0-9]+)?
if '.' in val:
return float(val)
return int(val) |
def rivers_with_station(stations):
"""Build and return a set of all rivers
with at least one station."""
rivers = set()
for station in stations:
rivers.add(station.river)
return rivers |
def wpm_to_cps(typing_speed):
"""Convert words per minute to characters per second
Assumes that 1 word per minute is the same as 5 characters per second
Args:
typing_speed (float): Typing Speed in Words per minute
Returns:
float: typing speed in characters per second
"""
assert... |
def add(*ops):
"""
(+) ;=> 0
(+ op) ;=> op
(+ op1 op2 ...)
"""
sum = 0
for op in ops:
sum += op
return sum |
def sqrt(x):
"""
Calulate the square root of argument x
"""
# Intitial guess for the square root
z = x / 2.0
#Continuously improve guess
while abs(x - (z*z)) > 0.0000001:
z = z - ((z*z -x) / (2*z))
return z |
def ksi_of_t_rhythmic(T, r):
"""
Local regressor.
Rhythmic system
"""
return 0 * T + r |
def to_bolean(value, default_value=False):
"""
Convert string value to a boolean.
"""
if value is None:
return default_value
if isinstance(value, bool):
return value
return not (value.lower() == 'false') |
def get_words(text: str) -> list:
"""Returns the words list of the first line in list
vars:
:param text: A string of lines
:returns: a list of words split on whitespace
"""
try:
text = text.rstrip()
lower_string = text.lower()
lower_string = lower_str... |
def teraflops_for_accelerator(accel):
"""
Stores the number of TFLOPs available to a few accelerators, including driver handicaps.
Args:
accel (str): A string descriptor of which accelerator to use. Must be either "3090" or "V100".
Returns:
accel_flops (int): an integer of how many TFL... |
def find_repeated(items):
"""Arguments:
items: the items to be searched for repeated elements.
Returns:
A set of elements that are repeated in 'items'."""
seen, seen_twice = set(), set()
seen_twice_add = seen_twice.add
seen_add = seen.add
for item in items:
if i... |
def init_nested_dict_brackets(first_level_keys, second_level_keys):
"""Initialise a nested dictionary with two levels
Parameters
----------
first_level_keys : list
First level data
second_level_keys : list
Data to add in nested dict
Returns
-------
nested_dict : dict
... |
def timeout2float(timeout):
"""Converts a timeout expressed in milliseconds or seconds into a timeout expressed
in seconds using a floating point number.
:Parameters:
timeout : int, long or float
The input timeout. Assumed to be expressed in number of
milliseconds if the type is i... |
def boolToString(value):
"""
converts a boolean value to a human readable string value
@param value: boolean, the value to convert
@return: A string of "Yes" or "No"
"""
if(value):
return "Yes"
else:
return "No" |
def ConvertTokenToInteger(string, location, tokens):
"""Pyparsing parse action callback to convert a token into an integer value.
Args:
string (str): original string.
location (int): location in the string where the token was found.
tokens (list[str]): tokens.
Returns:
int: integer value or None... |
def password_valid(password):
"""
Passwords must contain at least one digit or special character.
Passwords must be between 8 and 128 characters.
Passwords cannot contain spaces.
Returns: True if password meets conditions, False otherwise
"""
conds = [
lambda s: any(x.isdigit() or n... |
def get_unique_counter_from_url(sp):
"""
Extract the unique counter from the URL if it has one. Otherwise return
null.
"""
pos = sp.rfind('%23')
if pos != -1:
return int(sp[(pos + 3):])
else:
return None |
def format_runtime_string(raw_seconds: float) -> str:
"""Creates a nice format string from a potentially large number of seconds.
Args:
raw_seconds: A number of seconds.
Returns:
The seconds divided into hours, minutes, and remaining seconds, formatted
nicely. For example, 2h3m5.012s.
"""
mi... |
def is_palindrome(str_):
"""Returns True if given string is palindrome, else False
:param str_: Given string
:returns: True if given string is palindrome else False
"""
start = 0
end = len(str_) - 1
while start < end:
if str_[start] != str_[end]:
break
start += 1... |
def _lstrip(string: str) -> str:
"""find the leftmost non-whitespace character and lstrip to that index"""
lstrip_list = [x for x in string.splitlines() if not len(x.strip()) == 0]
start_points = (len(x) - len(x.lstrip()) for x in lstrip_list)
min_point = min(start_points)
new_lstrip_list = (x[min_p... |
def capitalize(s):
"""Upcase the first character in a string s."""
return s[:1].upper() + s[1:] if s else s |
def make_case_insensitive(strings):
"""
Adds additional regex modifiers to make the resulting list of search terms
case insensitive (?i)
"""
converted = list(map(lambda s: "(?i)" + s, strings))
return converted |
def elapsed_readable(seconds, decimals=0):
"""Given an elapsed time in seconds and optionally number of decimal places to round seconds to,
return a human-readable string describing it.
"""
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(int(minutes), 60)
s = f"{round(seconds, dec... |
def pvr(b3, b4):
"""
Photosyntetic Vigour Ratio (Metternicht, 2003).
.. math:: PVR = (b3 - b4)/(b3 + b4)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:returns PVR: Index value
.. Tip::
Metternicht, G. 2003. Vegetation... |
def clean_dict(data):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
for key, value in list(data.items()):
if value is None:
del data[key]
elif isinstance(value, dict):
... |
def check_digit13(firsttwelvedigits):
"""Check sum ISBN-13."""
# minimum checks
if len(firsttwelvedigits) != 12:
return None
try:
int(firsttwelvedigits)
except Exception: # pragma: no cover
return None
# checksum
val = sum(
(i % 2 * 2 + 1) * int(x) for i, x i... |
def ifdel(dictt, key):
""" If a key is in a dictionary delete it. Return [modified] dictionary.
"""
try:
del dictt[key]
return(dictt)
except:
return(dictt) |
def phs_correction(z_h, z_e, de_vbm, de_cbm):
""" Compute the PHS correction
:param z_h: number of holes in the PHS
:param z_e: number of electrons in the PHS
:param de_vbm: correction of the VBM
:param de_cbm: correction of the CBM"""
return - z_h * de_vbm, z_e * de_cbm |
def merge_m_e(tup):
"""
Merges the mantissa and exponent channel to parse it in single greyscale image
Give one sign byte and 2 bytes for exponent
"""
if abs(tup[1]) > 99:
print(tup)
assert 564 == 5464
if tup[1] >= 0:
return tup[0] * 1000 + tup[1]
else:
r... |
def memory_index(indices, t):
"""Location of an item in the underlying memory."""
memlen, itemsize, ndim, shape, strides, offset = t
p = offset
for i in range(ndim):
p += strides[i]*indices[i]
return p |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.