content stringlengths 42 6.51k |
|---|
def comma_replacement(random, population, parents, offspring, args):
"""Performs "comma" replacement.
This function performs "comma" replacement, which means that
the entire existing population is replaced by the best
population-many elements from the offspring. This function
makes the assumpti... |
def is_logged_in(session):
"""Check if the user is currently logged in.
If the user has a teamID in their session return success:1 and a message
If they are not logged in return a message saying so and success:0
"""
if 'tid' in session:
return {'success': 1, 'message': 'You appear to be log... |
def is_int(val):
"""
Is this lua object an integer?
"""
try:
_ = int(val)
return True
except (ValueError, TypeError):
return False |
def ascii_encodable(text):
"""
Return True if the given TEXT can be losslessly encoded in
ASCII. Otherwise, return False.
"""
return all(ord(char) < 128 for char in text) |
def partition_from_region(region_name):
"""
returns the partition for a given region
Note: this should be a Boto3 function and should be deprecated once it is.
On success returns a string
On failure returns NoneType
"""
parts = region_name.split('-')
try:
if parts[0] == 'us':
... |
def function_with_cpp_numpy_returns_arange(start, stop, step):
"""this is a doctring
"""
__cpp__ = """
return PyArray_Arange(PyFloat_AsDouble(start), PyFloat_AsDouble(stop), PyFloat_AsDouble(step), NPY_FLOAT64);
"""
i = 0
return 5 |
def text_of_list(t):
"""
Convert a string list to multiline text.
"""
return '\n'.join(t) |
def l1_loss(x: float, y: float) -> float:
"""
Compute the L1 loss function.
This is the absolute value of the difference of the inputs.
https://www.bitlog.com/knowledge-base/machine-learning/loss-function/#l1-error
Parameters
----------
x : float
The estimate
y : float
... |
def _find_first_of(line, substrings):
"""Find earliest occurrence of one of substrings in line.
Returns pair of index and found substring, or (-1, None)
if no occurrences of any of substrings were found in line.
"""
starts = ((line.find(i), i) for i in substrings)
found = [(i, sub) for i, sub i... |
def quote(string):
""" string -> 'string' """
return "'" + str(string) + "'" |
def text_to_list_of_lines(text):
"""Convert text into a list of lines, each being a list of words."""
return [line.split() for line in text.strip().split('\n')] |
def is_sublist(smallList, bigList):
"""
Checks if smallList is a sublist of bigList
"""
def n_slices(n, list_):
for i in range(len(list_)+1-n):
yield(list_[i:i+n])
for slice_ in n_slices(len(smallList), bigList):
if slice_ == smallList:
return True
return ... |
def find_longest_distinct_subarray(ls):
"""
Question 13.10: Find longest subarray
with distinct entries
"""
# maximum trackers
max_begin = 0
max_len = 0
# current trackers
cur_begin = 0
cur_len = 0
seen = {}
for idx, elt in enumerate(ls):
if elt not in seen or ... |
def get_update_cmd(update_fields, query_type, insert_type):
"""
Creates the update command to use with an insertion to a PostgreSQL database,
given the fields to be updated
Parameters
----------
update_fields: list of strs
Fields that will be updated
query_type: str
The type... |
def LimiterG4forHYU(dU1, dU2):
"""Return the limiter for Harten-Yee Upwind TVD limiter function.
This limiter is further used to calculate the modified flux limiter
function given by Equation 6-131.
Calculated using Equation 6-135 in CFD Vol. 1 by Hoffmann.
"""
if dU2 != 0:
S = ... |
def df_level(value, bounds="80:95"):
"""Convert a numeric value to "success", "warning" or "danger".
The two required bounds are given by a string.
"""
# noinspection PyTypeChecker
warning, error = [float(x) for x in bounds.split(":")]
if value < warning <= error or error <= warning < value:
... |
def time_to_float(hour, minute):
"""
Convert time to float number
:param hour:
:param minute:
:return:
"""
if not isinstance(hour, float):
hour = float(hour)
if not isinstance(minute, float):
minute = float(minute)
minute = minute * 1 / 60
if hour > 0:
ret... |
def flatten(categories):
"""Flatten incoming categories list
>>> flatten({'name':'test'})
[{'name': 'test', 'parent': None}]
>>> flatten({'name': 'Category 8', 'children': [{'name': 'Category 22'}, {'name': 'Category 23'}]})
[{'name': 'Category 8', 'parent': None}, {'name': 'Category 22', 'parent':... |
def get_docserver_setup(public, stable, server, intranet, group):
"""Returns a setup for BOB_DOCUMENTATION_SERVER.
What is available to build the documentation depends on the setup of
``public`` and ``stable``:
* public and stable: only returns the public stable channel(s)
* public and not stable:... |
def string_to_ord(string):
"""Convert string to corresponding list of int values."""
return [ord(char) for char in string] |
def validate_odd_size(size):
"""
Validates that a kernel shape is of odd ints and of size 2
:param size: the shape (size) to be checked
:return: False if size is invalid
"""
if type(size) not in (list, tuple):
return False
if len(size) != 2:
return False
if size[0] % 2 ... |
def unstacked_index(size, index):
"""
Convert an index into a column-stacked square operator with `size` rows and
columns, into a pair of indices into the unstacked operator.
"""
return index % size, index // size |
def get_tables(doctype, fields):
"""extract tables from fields"""
tables = ['`tab' + doctype + '`']
# add tables from fields
if fields:
for f in fields:
if "." not in f: continue
table_name = f.split('.')[0]
if table_name.lower().startswith('group_concat('):
table_name = table_name[13:]
if tab... |
def create_resource(resource_name, items, more=False, next_id=None):
"""Generates a Resource Object given a resource name."""
resource = {}
if items:
resource[resource_name] = items
if resource_name == "objects" or resource_name == "versions":
if next_id and resource:
resourc... |
def model_light(grid, steps):
"""
Simulate steps
:param grid: grid of octopuses
:param steps: number of steps to simulate
:return: number of flashes
"""
flashes = 0
for step in range(0, steps):
previous_flashes = -1
for i in range(0, len(grid)):
for j in range... |
def write_bool(data):
"""Writes a formatted string from a float.
Booleans are printed as a string of either ' true' or 'false'. Note that
both are printed out as exactly 5 characters.
Args:
data: The value to be read in.
Returns:
A formatted string.
"""
return "%5.5s" % (str(data)) |
def join(values, separator=',', lastSeparator='and'):
"""
Helper method to print a list of values
[1,2,3] -> '1, 2 and 3'
"""
values = [str(x) for x in values]
if len(values) < 1:
return ""
elif len(values) is 1:
return values[0]
else:
separator = '%s ' % separato... |
def division(a, b):
"""This function returns the division of the given 2 numeric values."""
if b != 0:
return a//b |
def reason_key_for_alert(alert):
"""Computes the reason key for an alert.
The reason key for an alert is used to group related alerts together. Alerts
for the same step name and reason are grouped together, and alerts for the
same step name and builder are grouped together.
"""
# FIXME: May need something ... |
def lower(value: str): # Only one argument.
"""Converts a string into all lowercase"""
return value.lower() |
def is_str(s):
"""return True or False if input is a string or not.
python3 compatible.
"""
return isinstance(s, str) |
def split_octet(hexstr):
""" Split a hexadecimal string (without the prefix 0x)
into a list of bytes described with a 2-length hexadecimal string
"""
return [hexstr[i:i+2] for i in range(0, len(hexstr), 2)] |
def _build_error(error_code, message, data=None, rpc_id=None):
"""
Build a JSON RPC error dict
Args:
error_code (int): JSON or app error code
message (string): Message to display
data : Json serializable data
rpc_id (int): The request id
Returns:
dict the json_rp... |
def remove_stop_words(tokens: list, stop_words: list) -> list:
"""
Removes stop words
:param tokens: a list of tokens
:param stop_words: a list of stop words
:return: a list of tokens without stop words
e.g. tokens = ['the', 'weather', 'is', 'sunny', 'the', 'man', 'is', 'happy']
stop_words =... |
def hexdump(data, columns=16, indentlvl=""):
"""Return the hexadecimal representation of the data"""
def do_line(line):
return (
indentlvl +
" ".join("{:02x}".format(ord(b)) for b in line) +
" " * (columns - len(line)) +
" " +
"".join(b if ... |
def extract_command_name(line: str) -> str:
"""Read command name from text"""
# Use the method call to break the string
before_call = line.split("(")[0]
# The remaining text should end with the method_name
*_, method_name = before_call.split()
return method_name |
def dirac(t, n, freq, pulse_delay):
"""
:param t: time sequence (s).
:type t: list of floats
:param n: time iteration index
:type n: int
:param freq: frequency of the sinusoid (Hz)
:type freq: float
:param pulse_delay: number of iteration for the delay of the signal defined
... |
def validate_version(version: str):
"""Check whether parsed version is valid.
Args:
version (str): E.g "1.0.1"
Returns:
bool: Whether is valid.
"""
return version == "increment" or (
len(version.split(".")) == 3 and all([i.isdecimal() for i in version.split(".")])
) |
def applyToChildren(a, f):
"""Apply the given function to all the children of a"""
if a == None:
return a
for field in a._fields:
child = getattr(a, field)
if type(child) == list:
i = 0
while i < len(child):
temp = f(child[i])
if type(temp) == list:
child = child[:i] + temp + child[i+1:]
... |
def convert_to_centuries(time):
"""
Convert time from days to centuries
Args:
time (float or array of floats): time in days
Returns:
time in centuries
"""
return time/(100.*365.24217) |
def ctz(v: int, bits: int) -> int:
""" count trailing zeroes """
count = 0
while count < bits and (v % 2) == 0:
count += 1
v //= 2
return count |
def shell_sort(list_: list) -> list:
"""Returns a sorted list, by shell sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by shell sort method
"""
half = len(list_) // 2
while half > 0:
for i in range(half, len(list_)):
... |
def get_options(iterable):
"""
Populates a dash dropdawn from an iterable
"""
return [{"label": x, "value": x} for x in iterable] |
def get_unique_pairs(mentions):
"""Get unique pairs of search term and pub DOI.
Parameters
----------
mentions: list of dictionaries
example xdd_search GetMentions.mentions
[{'xdd_id':'5d41e5e40b45c76cafa2778c',
'pub_doi': '10.3133/OFR20191040',
'search_t... |
def isatty(file):
"""Convenience method to check if a file object exists, is open, and refers
to a TTY.
"""
return file is not None and not file.closed and file.isatty() |
def process(data):
"""Perform any desired processing of the JSON data."""
# This is a no-op for now but is a placeholder in case we want to do things
# like filter out certain task specs or rename things.
return data |
def assy_name(wb, raw, top_lvl_assy):
"""write assembly name in overiew (assy_head missed this out)"""
try:
desc = raw[raw.partcode == top_lvl_assy].desc.values[0]
ws = wb.Worksheets("Overview")
ws.Cells(12, 5).Value = desc.strip()
except:
pass
return wb |
def little_endian_encode(value, word_size, bits):
"""Transform long integer to list of small."""
copy_value = value
size = bits // word_size
if value < 0:
raise ValueError('Cannot encode negative value: {value}'
.format(value=value))
if value == 0:
return [0]... |
def get_domains(common_name=None, sans=None):
"""Get unique list of domains for input criteria
:param common_name: Certificate common name
:type common_name: str or None
:param sans: Certificate SANs List
:type sans: list(str) or None
:return: unique list of domains
:rtype: set(str)
"""... |
def clip(v, vMin, vMax):
"""
@param v: number
@param vMin: number (may be None, if no limit)
@param vMax: number greater than C{vMin} (may be None, if no limit)
@returns: If C{vMin <= v <= vMax}, then return C{v}; if C{v <
vMin} return C{vMin}; else return C{vMax}
"""
try:
return... |
def vector_query_nuts(vector_table_requested, area_selected):
"""
this function will return an array of the vector table selected from a selection at hectare level
:param vector_table_requested:
:param geometry:
:return:
"""
vector_table_requested = str(vector_table_requested)
query= "wi... |
def pcc(circ, supp, verbose=False):
"""
Args:
circ(list(list(tuple))): Circuit
supp(list): List of integers
Returns:
list(list(tuple)): Past causal cone of supp
"""
circ_rev= circ[::-1]
circ_reduced = []
supp_coded = 0
for s in supp:
supp_coded |= (1<<s)
... |
def sign(num):
"""
+1 when positive, -1 when negative and 0 at 0
"""
if num > 0:
return 1
elif num < 0:
return -1
else:
return 0 |
def create_centroid_ranges(centroids, tol=15):
"""
Create high and low BGR values to allow for slight variations in layout
:param centroids: legend colors identified from get_centroids
:param tol: int, number of pixels any of B, G, R could vary by and still
be considered part of the original centroi... |
def rrx(carry, value, count, width=32):
"""
Rotate Right Extended
(original carry must also be passed in)
>>> rrx(0, 0xff, 4) == (1, 0xe000000f)
True
>>> rrx(1, 0xff, 4) == (1, 0xf000000f)
True
"""
count %= width
value &= (1 << width) - 1
# First shift 1 to the left to leave... |
def compute_exp_depth(exp):
"""
Doc String
"""
if isinstance(exp, tuple):
return 1 + max([compute_exp_depth(sub) for sub in exp])
return 0 |
def hTest_postSelectedCounts(n, counts, k = 1):
"""
Returns `counts` with some entries deleted according to postselection described in paper [SCC19].
[SCC19] is "Entanglement spectroscopy with a depth-two quantum circuit".
`k` is such that rho is a state on 2k qubits, and rho_A is k qubits.
`counts` should be t... |
def get_symbol_name(symbol):
"""Returns __name__ attribute or empty string if not available."""
if hasattr(symbol, "__name__"):
return symbol.__name__
else:
return "" |
def disambiguate_list(l, spec):
""" Replace the choice list with a determined choice
"""
ret = []
for propert in l:
if type(propert) is dict:
prop = list(propert.keys())[0]
choices = propert[prop]
if prop not in spec:
print(prop, " not specifie... |
def fix_taiko_big_drum(ticks, hitsounds):
"""
Remove finishes when there is another note next tick
"""
for i,tick in enumerate(ticks):
if tick+1 in ticks:
if hitsounds[i] & 4 == 4: # has finish hitsound == big drum
hitsounds[i] -= 4
return hitsounds |
def wrap(x, extents):
"""Wrap first two components of x into extents."""
a, b = extents
d = b - a
if x[0] < a:
x[0] += d
if x[1] < a:
x[1] += d
if x[0] > b:
x[0] -= d
if x[1] > b:
x[1] -= d
return x |
def tryDecode(input):
""" Python 2/3 compatibility hack
"""
try:
return input.decode()
except:
return input |
def parse(output):
"""Parse (normalize) output and return a list of lines."""
output = output.split('\r\n')
output = [line for line in output if line]
return output |
def get_single_language(kanton):
""" Returns the language given the canton abbreviation for a single canton
"""
if (kanton == "TI"):
return "IT"
elif (kanton in ["FR", "VD", "NE", "JU", "GE", "VS"]):
return "FR"
else:
return "DE" |
def get_precision(number):
"""
Returns leading precision of number.
- convert float to string
- find position of decimal point relative to the length of the string
Args:
number (int, float)
Returns:
precision (int)
Example:
| >> get_precision(5.00000)
... |
def _get_socket_port(suite_name, start_port, current_batch):
"""Returns the used port based on the given parameters
The same function is used in do.py. If this one changes, the other has to change too.
"""
port_py_inc = 200
if ('toy-socket' in suite_name) or ('rw-top-trumps' in suite_name):
... |
def extract_bearer_token(auth_header):
"""
>>> extract_bearer_token(u'Bearer some-token')
u'some-token'
>>> extract_bearer_token('Bearer ') is None
True
>>> extract_bearer_token('Something Else') is None
True
"""
prefix = 'Bearer '
if auth_header is None or not auth_header.starts... |
def merge_sort(arr):
"""
time complexity: O(n*logn)
space complexity: O(n)
:prarm arr: list
:return: list
"""
if not isinstance(arr, list):
raise TypeError
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid... |
def search_key_for_dictionary(dictionary):
"""Generate a string search key for a dictionary"""
elements = []
elements.append(dictionary['name'])
return u' '.join(elements) |
def cleanPath(path_arr):
"""Takes a list with a path and cleans its element.
Cleaning its element currently only consists in removing singel and double
quotes.
"""
def _cleanPathElement(x):
return x.strip().replace('\'', '').replace('"', '')
return list(map(_cleanPathElement, path_arr)) |
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
if not technique.get('x_mitre_deprecated'):
for phase in technique['kill_ch... |
def mean(xs):
"""A function mean(xs) that takes a sequence xs of numbers, and returns the (arithmetic) mean
(i.e. the average value)."""
count = 0
for i in xs:
count += i
return count / len(xs) |
def map_indices_py(arr):
"""
Returns a dictionary with (element, index) pairs for each element in the
given array/list
"""
return dict([(x, i) for i, x in enumerate(arr)]) |
def findPivot(lst):
"""
worked... but not a recommended way..
length = len(lst)
if(sum(lst[1:])==0): # for test case where right-side yields to 0 -- somme ambiguity here.. what if left..??
return 0
for i in range(1, length):
if sum(lst[0:i]) == sum(lst[i+1: length]):
... |
def camelcase_to_underscore_joined(camelcase_str):
"""Convert camelCase string to underscore_joined string
:param camelcase_str: The camelCase string
:returns: the equivalent underscore_joined string
"""
if not camelcase_str:
raise ValueError('"camelcase_str" cannot be empty')
r = came... |
def _js_repr(val):
"""Return a javascript-safe string representation of val"""
if val is True:
return 'true'
elif val is False:
return 'false'
elif val is None:
return 'null'
else:
return repr(val) |
def rename_classes(schema):
"""
rename future class names to get rid of https://w3id.org/cwl/salad
"""
for item in schema:
item['name'] = item['name'].split('#')[-1]
return schema |
def check_line(line, unexpected_char=["\n", "", " ", "#"]):
"""
Check if the line starts with an unexpected character.
If so, return False, else True
"""
for item in unexpected_char:
if line.startswith(item):
return False
return True |
def odd_man_out(inp):
"""If input looks like an odd integer, return
twice its value; otherwise, return None"""
try: #If it's a number, can it be cast as an integer?
inp = int(inp)
except:
return None
#try: #Is it a number at all? If not, give up.
#inp/1
#except:
... |
def unproxy_weakproxy(proxy):
"""
Returns the actual object weak-referenced by a weakproxy.proxy object
Much like
>>> a = weakref.ref(b)
>>> a() is b
True
"""
return proxy.__repr__.__self__ |
def handle_single_argument(passed_arguments: list, passed_keywords: dict, search_key: str) -> dict:
"""Handle a single argument that is provided without keywords.
Reviews arguments passed to a method and injects them into the keyword dictionary if they
match the search string.
"""
if len(passed_arg... |
def _single_line_sanitize(s):
"""Remove problematic newlines."""
# For example, when setting a :alt: for an image, it shouldn't have \n
# This is a function in case we end up finding other things to replace
return s.replace('\n', ' ') |
def _anticommutation_factor(many_particle_state: int, initial_position: int, final_position: int) -> int:
"""
Calculate the sign factor needed to move an operator from initial_position to final_position in the sequence
of creation operators that create many_particle_state from the vacuum, assuming that it a... |
def nSwitch(order : int, theta : float) -> float:
"""
Estimate the sample number when the first VRF diagonal elements of an EMP/FMP pair will match
Uses approximate relationships to estimate the switchover point for an EMP/FMP pair when the
0th element of the VRF diagonals will match, e.g. approxim... |
def normalizeX(value):
"""
Normalizes x coordinate.
* **value** must be an :ref:`type-int-float`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)):
raise TypeError("X coordinates must be instances of "
":ref:`type-i... |
def format_memory(nbytes):
"""Returns a formatted memory size string"""
KB = 1024
MB = 1024 * KB
GB = 1024 * MB
if (abs(nbytes) >= GB):
return '{:.2f} Gb'.format(nbytes * 1.0 / GB)
elif (abs(nbytes) >= MB):
return '{:.2f} Mb'.format(nbytes * 1.0 / MB)
elif (abs(nbytes) >= KB)... |
def colour(string: str) -> str:
"""\
Paint it green!
"""
string = f"\033[32m{string}\033[0m"
return string |
def get_cookie_value( cookiejar, name ):
"""
Retrieves the value of a cookie from a CookieJar given its name.
"""
value = None
for cookie in cookiejar:
if cookie.name == name:
value = cookie.value
break
return value |
def make_to_dict(item, include_timestamp):
"""Make a row dict for a cell mapping like ttypes.TResult.columns."""
return {
'%s:%s' % (cell.family, cell.qualifier): (cell.value, cell.timestamp) if include_timestamp else cell.value
for cell in item
} |
def shortestPath(graph, start, end, path=None):
"""
Uses recursion to find the shortest path from one node to
another in an unweighted graph. Adapted from
http://www.python.org/doc/essays/graphs.html .
Parameters:
graph: A mapping of the graph to analyze, of the form
... |
def tokenise_stream(stream):
"""Process stream to an array of tokens."""
return [token for token in stream] |
def unpacking_args(args, args_name, traced_args_list):
"""
@params:
args: tuple of args sent to a patched function
args_name: tuple containing the names of all the args that can be sent
traced_args_list: list of names of the args we want to trace
Returns a list of (arg name, arg) of ... |
def clean(data, parameters):
"""
Cleans a dictionary to only includ valid parameters and non empty values.
"""
# Only take valid parameters.
data = {key: data.get(key) for key in parameters}
# Remove empty parameters.
data = {key: value for key, value in data.items() if value is not None}
... |
def is_mp4_pattern(resource: bytes) -> bool:
""" Determines whether a byte sequence (resource) mathces the
signature for MP4"""
if len(resource) < 4:
return False
box_size = int.from_bytes(resource[:4], 'big')
if len(resource) < box_size or box_size % 4 != 0:
return False
if res... |
def _remove_outer_div(html: str) -> str:
"""Remove outer <div> tags."""
html = html.replace("<div>", "", 1)
html = "".join(html.rsplit("</div>", 1))
return html |
def _create_source(foci, sample_sizes, space="MNI"):
"""Create dictionary according to nimads(ish) specification.
.. versionadded:: 0.0.4
Parameters
----------
foci : :obj:`dict`
A dictionary of foci in xyz (mm) coordinates whose keys represent
different studies.
sample_sizes :... |
def to_dicts(todos):
"""Convert a list of :class:`todotxtio.Todo` objects to a list of todo dict.
:param list todos: List of :class:`todotxtio.Todo` objects
:rtype: list
"""
return [todo.to_dict() for todo in todos] |
def _find_value_by_key(a_dict, key):
"""Find a key and return it, with a flag saying if it was found"""
try:
val = a_dict[key]
except KeyError:
return (False, None)
return (True, val) |
def as_binary_digits(number):
"""
break a number into 2 binary digits
"""
n = round(number)
upper = n // 10
lower = n % 10
return (upper, lower) |
def tint_red(text: str) -> str:
"""Tints a given text red.
:param text: The text to be tinted
:type text: str
:returns: The same text but tinted red
:rtype: str
"""
return ("\x1b[31m%s\x1b[0m" % text) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.