content stringlengths 42 6.51k |
|---|
def make_batch_indexes(size, data_len):
"""
Creates a list of start and stop indexes where start is <size> away from end.
The start and stop indexes represent the start and stop index of each batch ranging for the entire data set.
Parameters
----------
size: int
The size of the batches... |
def is_odd(x):
"""returns true only if x is odd"""
return x % 2 != 0 |
def Binary(data):
"""returns binary encoding of data"""
return ''.join(["%02X" % ord(i) for i in data]) |
def time_check(message):
"""
check if the duration for the quick search preference is a valid input
"""
time = 0
try:
time = int(message)
except Exception as e:
return False
if time < 1 or time > 8:
return False
return True |
def getsearchtype(searchtype):
"""Returns search code for posting requests to http://apps.webofknowledge.com/UA_GeneralSearch.do"""
if searchtype == 'title':
search = 'TI'
elif searchtype == 'topic':
search = 'TS'
elif searchtype == 'author':
search = 'AU'
elif searchtype ==... |
def _format_num_lists_already_formatted(num_lists):
"""
This function assumes that the numbers are already within the given bases and do not have leading zeros, or "already formated"
An example is [1, 20]. All the values, "1" and "20", are less than the given bases [24, 60] for 24 hour time
Replace an... |
def fmt(n):
"""format number with a space in front if it is single digit"""
if n < 10:
return " " + str(n)
else:
return str(n) |
def median(array):
"""
Calculates the median of an array/vector
"""
import numpy as np
array=np.array(array)
result= np.median(array)
return result |
def authorization_method(original_method):
"""The method that will be injected into the authorization target to perform authorization"""
global _authorization_method
_authorization_method = original_method
return original_method |
def scale3(v, s):
"""
scale3
"""
return (v[0] * s, v[1] * s, v[2] * s) |
def ABCDFrequencyList_to_SFrequencyList(ABCD_frequency_list,Z01=complex(50,0),Z02=complex(50,0)):
""" Converts ABCD parameters into s-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,S11,S12,S21,S22],...],
"""
s_frequency_list=[]
for row in ABCD_fr... |
def compute_wu_bound_strong(lipschitz_constant, gamma, n_samples, batch_size, verbose=True):
"""
compute the bound in the strongly convex case
basically copied from
https://github.com/tensorflow/privacy/blob/1ce8cd4032b06e8afa475747a105cfcb01c52ebe/tensorflow_privacy/privacy/bolt_on/optimizers.py
""... |
def is_bg(file):
""" if image file is background map """
return file.endswith('_bg.png') |
def file_name_to_ref_p_and_restored_p(fileName):
"""
Returns the appropriate filename based on the extension as denoted in the pipeline
:param fileName:
:return: Tuple of reference and restored filenames
"""
refPuncFileName = fileName + "_reference_punc.txt"
restoredPuncFileName = fil... |
def _has_symbol(symbol, name):
"""
Check if has provided symbol in name.
Recognizes either the _SYMBOL pattern at end of string, or _SYMBOL_ in
middle.
"""
return name.endswith('_' + symbol) or ('_' + symbol + '_') in name |
def hourAngleFormatter(ra):
"""String formatter for "hh:mm"
Args:
deg: float
Return:
String
"""
if ra < 0:
ra += 360
hours = int(ra//15)
minutes = int(float(ra - hours*15)/15 * 60)
if minutes:
return "${:d}^{{{:>02}}}$h".format(hours, minutes)
return... |
def solution(A):
# write your code in Python 3.6
"""
########PSEUDOCODE###########
sort array
for index in range(len):
if index == 0:
continue
if array[index] == array[index - 1]:
continue
if array[index] - arr... |
def to_int(a):
"""Length of linked list"""
i = 0
while a:
i += 1
a = a.next
return i |
def find_indices(predicate, List):
"""
Returns an array of all the indices of the
elements which pass the predicate. Returns an
empty list if the predicate never passes.
find-indices even, [1 2 3 4] #=> [1, 3]
>>> find_indices(lambda x: x > 2, [1, 2, 30, 404, 0, -1, 90])
[2, 3, 6]
... |
def perform_iteration(ring, length, pos):
"""
Solve the Day 10 puzzle.
"""
if pos + length < len(ring):
ring[pos: pos+length] = ring[pos: pos+length][::-1]
else:
seq = ring[pos:] + ring[:pos + length - len(ring)]
len_new_left = pos + length - len(ring)
len_new_right =... |
def count_ones(n):
"""
:type n: int
:rtype: int
"""
counter = 0
while n:
counter += n & 1
n >>= 1
return counter |
def block_sizes(max_size):
"""
Return all possible block sizes of an inter-predicted frame (min size is 4x8 or 8x4)
:param max_size: maximum exponent of the power of 2 specifying width/height (e.g. 6 = 32x32), max value is 8
:return: string list of "width x height" sizes
"""
if max_size > 8:
... |
def convert_to_snake(inputstring: str):
"""Convert inputstring from camel case to snake case."""
return ''.join('_' + char.lower() if char.isupper() else char for char in inputstring).lstrip('_') |
def _deweird(s):
"""
Sometimes numpy loadtxt returns strings like "b'stuff'"
This converts them to "stuff"
@ In, s, str, possibly weird string
@ Out, _deweird, str, possibly less weird string
"""
if type(s) == str and s.startswith("b'") and s.endswith("'"):
return s[2:-1]
else:
return s |
def f1_score (true_positive, positive, gt_positive):
"""Compute the F1-score
Args:
true_positive (Int): Number of true positives
positive (Int): Number of positively classified samples
gt_positive (Int): Number of effectively positive samples
Returns:
float: F1-score
""... |
def encode_to_bytes(value, encoding="utf-8"):
"""Returns an encoded version of the string as a bytes object.
Args:
encoding (str): The encoding.
Resturns:
bytes: The encoded version of the string as a bytes object.
"""
return value if isinstance(value, bytes) else value.encode(enco... |
def to_dict(d, default=None):
"""
Convert a ``dict`` or a ``list`` of pairs or single keys (or mixed) into a ``dict``.
If a list element is single, `default` value is used.
"""
if d is None:
return {}
if isinstance(d,dict):
return d
res={}
for e in d:
if isin... |
def get_density(lon, lat, alt, datarr, datlats):
"""
Function for taking array of electron densities and returning the right one
for a particular location/altitude.
(You give us the data and we'll do the work for you!)
The density array is assumed to have the form of Rob Gillies' density profiles
... |
def LabelIsMaskedByField(label, field_names):
"""If the label should be displayed as a field, return the field name.
Args:
label: string label to consider.
field_names: a list of field names in lowercase.
Returns:
If masked, return the lowercase name of the field, otherwise None. A label
is mas... |
def int_prop(name, node):
"""Boolean property"""
try:
return int(node.get(name))
except KeyError:
return None |
def _validate_bokeh_marker(value):
"""Validate the markers."""
all_markers = (
"Asterisk",
"Circle",
"CircleCross",
"CircleX",
"Cross",
"Dash",
"Diamond",
"DiamondCross",
"Hex",
"InvertedTriangle",
"Square",
"SquareC... |
def check_tie(board):
""" Checks if the board's state is tie.
"""
for element in board:
if not element:
return False
return True |
def _PointListToSVG(points, dupFirst=0):
""" convenience function for converting a list of points to a string
suitable for passing to SVG path operations
"""
outStr = ''
for i in range(len(points)):
outStr = outStr + '%.2f,%.2f ' % (points[i][0], points[i][1])
# add back on the first point. This i... |
def valid_file(path: str) -> bool:
"""
Check if regressi file is valid
:param path: path to the file to test
:return: whether the file is valid or not
"""
with open(path, 'r') as file:
if file.readline() == "EVARISTE REGRESSI WINDOWS 1.0":
return False
else:
... |
def minify_html(html):
"""Perform a template-specific, rudimentary HTML minification for displaCy.
Disclaimer: NOT a general-purpose solution, only removes indentation and
newlines.
html (unicode): Markup to minify.
RETURNS (unicode): "Minified" HTML.
"""
return html.strip().replace(" ", ... |
def prettyPrint(string, maxlen=75, split=" "):
"""Pretty prints the given string to break at an occurrence of
split where necessary to avoid lines longer than maxlen.
This will overflow the line if no convenient occurrence of split
is found"""
# Tack on the splitting character to guarantee a final... |
def recursive_rename_keys(old_dict: dict, old_to_new_map: dict):
"""
Given a nested dictionary 'old_dict', recursively update all keys according to old_to_new_map
"""
if not isinstance(old_dict, dict):
return old_dict
new_dict = {}
for key, value in old_dict.items():
if key in ... |
def func_a_p(a=2, *, p="p"):
"""func.
Parameters
----------
a: int
p: str, optional
Returns
-------
a: int
p: str
"""
return None, None, a, None, p, None, None, None |
def link_cmd(path, link):
"""Returns link creation command."""
return ['ln', '-sfn', path, link] |
def frange(range_def, sep=','):
"""
Return the full, unabbreviated list of ints suggested by range_def.
This function takes a string of abbreviated ranges, possibly
delimited by a comma (or some other character) and extrapolates
its full, unabbreviated list of ints.
Parameters
----------
... |
def to_int_percent(items):
""" Converts a list of numbers to a list of integers that exactly sum to
100. """
nitems = len(items)
total = sum(items)
if total == 0:
return [0] * nitems
perc = [100 * p // total for p in items]
s = sum(perc)
i = 0
while s < 100:
if ite... |
def white_to_len(string, length):
"""
Fills white space into a string to get to an appropriate length. If the string is too long, it cuts it off.
:param string: String to format.
:param length: The desired length.
:return: The final string.
"""
if len(string) < length:
string = stri... |
def xor(message, key):
""" Xor a message with a key.
"""
return bytes(m ^ k for m, k in zip(message, key)) |
def tsv_line(value_list):
"""Create tab-delimited line from Python list
Given a Python list, returns a tab-delimited string with
each value in the last converted to a string.
Arguments:
value_list: Python list of values
Returns:
String with list values separated by tabs.
"""
... |
def find_relocation(func, start, end):
"""
Finds a relocation from `start` to `end`. If `start`==`end`, then they will be expanded to the closest instruction boundary
:param func: function start and end are contained in
:param start: start address
:param end: end address
:return: corrected start and end addresses... |
def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq |
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
... |
def simple_object_hash(obj):
"""
Turn an arbitrary object into a hash string. Use SHA1.
"""
import hashlib
obj_str = str(obj)
hash_object = hashlib.sha1(obj_str.encode())
hex_dig = hash_object.hexdigest()
return hex_dig |
def expand_prefix(tag, prefixes):
"""
Substitutes the namespace prefix, if any, with the actual namespace in an XML tag.
:param tag: the XML tag
:type tag: str
:param prefixes: the prefix mapping
:type prefixes: dict
:return: the tag with the explicit XML namespace
"""
# See if `nam... |
def map_vectors(vectors, fun):
"""map function over vectors of image information"""
new_vectors = []
for vector in vectors:
new_vector = []
for elem in vector:
new_vector.append(fun(elem))
return(new_vectors) |
def map_range(value, from_min=0, from_max=1, to_min=0, to_max=1):
"""
Scale value from
Thanks to this SO post: http://stackoverflow.com/a/5295202/2730823
"""
return ((to_max-to_min)*(value - from_min) / (from_max - from_min)) + to_min |
def extract_node_name(node_address):
"""Given a graph node address, returns the label. For the sake of clarity, COMMENT node addresses return empty.
:param node_address: The node address
:return: The label
"""
node_type = node_address[2]
if node_type == "COMMIT":
return node_address[3][-... |
def _excel2num(x):
"""
Convert Excel column name like 'AB' to 0-based column index.
Parameters
----------
x : str
The Excel column name to convert to a 0-based column index.
Returns
-------
num : int
The column index corresponding to the name.
Raises
------
... |
def now(timespec='auto'):
""" Datetime string
Returns:
str : datetime now
"""
import datetime
return datetime.datetime.now().isoformat(timespec=timespec) |
def format_tag(organization, standard, version, tag_name):
"""
Format a YAML tag.
"""
return 'tag:{0}:{1}/{2}-{3}'.format(
organization, standard, tag_name, version) |
def flip_array_bit(ba, bitnum):
"""flips a bit in an array, 0 = MSB. Works with numpy arrays or byte arrays"""
ba[bitnum >> 3] ^= (1 << (7 - (bitnum % 8)))
return ba |
def fullname(o):
""" Returns a full module name of an object"""
return o.__module__ + "." + o.__name__ |
def compute_map(P):
"""Solution to exercise R-13.6.
Compute a map representing the last function used in the Boyer-Moore
pattern-matching algorithm for characters in the pattern string:
"the quick brown fox jumped over a lazy cat".
"""
m = len(P)
last = {}
for k in range(m):
las... |
def unit_test_sorting(func, *args):
"""
Unit testing, but only for sorting functions.
"""
out = func(*args)
if out is None:
out = args[0]
exp = sorted(args[0])
if out != exp:
print("Test Failed: " + func.func_name)
print("Expected = " + str(exp))
print("Actual... |
def split_tag(tag):
"""
parse an xml tag into the tag itself and the tag index
Parameters
----------
tag : str
xml tag that might or might not have a [n] item
Returns
-------
tuple: fgdc_tag, index
"""
if "[" in tag:
fgdc_tag, tag = tag.split("[")
index ... |
def check_goal(state):
"""
Returns True if state is the goal state. Otherwise, returns False.
"""
n = len(state[0])
for i in range(0, n):
for j in range(0, n):
if state[i][j] != (j + 1) + (i * n):
if not(i == j == (n - 1) and state[i][j] == '*'):
... |
def discard_unknown_labels(labels):
"""Function for discarding medial wall (unknown) labels from a list
of labels.
Input arguments:
================
labels : list
List of labels. Each label must be an instance of the MNE-Python
Label class.
Output arguments:
====... |
def decode_dict(obj: dict) -> dict:
"""
This function simply parses a dict from the Redis database
and decode every value.
returns: dict
"""
return {key.decode("utf-8"): val.decode("utf-8")
for key, val in obj.items()} |
def And(input1,input2):
"""
Logic for AND operation
Parameters
----------
input1 (Required) : First input value. Should be 0 or 1.
input2 (Required) : Second input value. Should be 0 or 1.
"""
return f"( {input1} & {input2} )" |
def compute_sliced_len(slc, sequence_len):
"""
Compute length of sliced object.
Parameters
----------
slc : slice
Slice object.
sequence_len : int
Length of sequence, to which slice will be applied.
Returns
-------
int
Length of object after applying slice o... |
def encode_run_length(string):
"""I'm aware this is a dirty solution."""
encoded = ""
count = 1
for char, next_char in zip(string, string[1:] + "\n"):
if char == next_char:
count += 1
else:
encoded += f"{count}{char}"
count = 1
return encoded |
def add_xy_grid_meta(coords):
"""Add x,y metadata to coordinates"""
# add metadata to x,y coordinates
if "x" in coords:
x_coord_attrs = dict(coords["x"].attrs)
x_coord_attrs["long_name"] = "x coordinate of projection"
x_coord_attrs["standard_name"] = "projection_x_coordinate"
... |
def remove_punc(sent):
"""
Filter out punctuations
"""
punc_lst = [".", ",", "!", "?", ";"]
for punctuation in punc_lst:
sent = sent.replace(punctuation, "")
sent = sent.replace(" ", " ")
return sent |
def gather_possible_containers(the_rules, bag_color="shiny gold"):
"""
evaluate recursively how many continers can possibly contain a bag_color colored bag
"""
containers_found = []
for rule in the_rules:
for child in rule['children']:
if child['color'] == bag_color and rule['col... |
def get_minmax_size(bbox):
"""Get aspect ratio of bbox"""
ymin, xmin, ymax, xmax = bbox
width, height = xmax - xmin, ymax - ymin
min_size = min(width, height)
max_size = max(width, height)
return min_size, max_size |
def date_time(seconds):
"""Current date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UST"""
from datetime import datetime
timestamp = str(datetime.fromtimestamp(seconds))
return timestamp |
def _get_color_list(n_sets):
"""
color list for dimensionality reduction plots
Args:
n_sets: number of dataset
Returns:
list of colors for n_sets
"""
color_list = ['#1a9850', '#f46d43', '#762a83', '#41b6c4',
'#ffff33', '#a50026', '#dd3497', '#ffffff',
... |
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
>>> is_palindrome_v3('')
True
>>> is_palindrome_v3(' ')
True
"""
... |
def transform_annotation(annotation):
"""Transform annotation dumbly, asserting it is a string."""
assert isinstance(annotation, str)
return annotation |
def unitary_gate_counts_real_deterministic(shots, hex_counts=True):
"""Unitary gate circuits reference counts."""
targets = []
if hex_counts:
# CX01, |00> state
targets.append({'0x0': shots}) # {"00": shots}
# CX10, |00> state
targets.append({'0x0': shots}) # {"00": shots}
... |
def _trim_doc_string(text):
""" Trims a doc string to make it format
correctly with structured text. """
lines = text.replace('\r\n', '\n').split('\n')
nlines = [lines.pop(0)]
if lines:
min_indent = min([len(line) - len(line.lstrip())
for line in lines])
fo... |
def total_reward(responses):
"""Calculates the total reward from a list of responses.
Args:
responses: A list of SimpleSequentialResponse objects
Returns:
reward: A float representing the total clicks from the responses
"""
reward = 0.0
for r in responses:
reward += r.reward
return reward |
def get_field_names(elems):
""" Return unique name attributes """
res = []
seen = set()
for el in elems:
if (not getattr(el, 'name', None)) or (el.name in seen):
continue
seen.add(el.name)
res.append(el.name)
return res |
def recall_at(target, scores, k):
"""Calculation for recall at k."""
if target in scores[:k]:
return 1.0
else:
return 0.0 |
def get_short_desc(long_desc):
""" Get first sentence of first paragraph of long description """
found = False
olines = []
for line in [item.rstrip() for item in long_desc.split('\n')]:
if (found and (((not line) and (not olines))
or (line and olines))):
olines.append(line... |
def IsFPExt(path, extentions):
""" Returns whether the file in the filepath is in the extension/type list given.
:param path str: file path
:param extentions list: extension/type list
:returns boolean:
"""
is_ext = False
for ext in extentions:
if path.endswith(ext):
is_ex... |
def get_word(line):
"""
Get word from each line
:param line: line from FILE
:return: str, word got from line
"""
word = ''
# Run each letter in line
for ch in line:
if ch.islower():
word += ch
return word |
def sub2indSH(m,n):
"""
i = sub2indSH(m,n)
Convert Spherical Harmonic (m,n) indices to array index i
Assumes that i iterates from 0 (Python style)
"""
i = n**2 + n + m
return i |
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
#slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
slash, dot = ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX... |
def cmp(x, y):
"""
Replacement for built-in funciton cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and strictly positive if x > y.
"""
if x is None and y is None:
... |
def get_images_regions(body_response):
"""
Gets the list of regions that have been found in the Image service with its public URL
:param body_response: Keystone response (/token)
:return: List of regions found with name and public URL
"""
service_list = body_response['access']['serviceCatalog']
... |
def solve_a(grid):
"""Solve Part A"""
overlapping = 0
for pos in grid:
# count how many ids are stored at each position
# any inches with more than one claim id are considered overlapping
if len(grid[pos]) > 1:
overlapping += 1
return overlapping |
def try_get(src, getter, expected_type=None):
"""Getter for Object with type checking.
Args:
src (object): Object for getter.
getter (lambda): Lambda expression for getting item from Object.
expected_type (type, optional): Expected type from the getter. Defaults to None.
Returns:
... |
def parse_unknown_args(uargs):
"""uargs: a list of strings from the command line.
parse using the rule nargs='+' """
uargdict = {}
if not uargs:
return uargdict
opt = ''
values = []
while uargs:
term = uargs.pop(0)
if term.startswith('--') or term.startswith('-'):
... |
def clean(in_word):
"""cast to lowercase alpha-only."""
chars = []
for c in in_word:
if c.isalpha():
chars.append(c.lower())
return "".join(chars) |
def ZellerDayOfWeek(input_date):
"""Uses Zeller's congruence (Gregorian) to return the day of week.
Returns 0 for Saturday, 1 for Sunday, .... 6 for Friday"""
date = [0,0,0]
date[0] = input_date[0]
date[1] = input_date[1]
date[2] = input_date[2]
if date[1] == 1 or date[1] == 2:
date[... |
def join_paths(*args):
"""Join paths without duplicating separators.
This is roughly equivalent to Python's `os.path.join`.
Args:
*args (:obj:`list` of :obj:`str`): Path components to be joined.
Returns:
:obj:`str`: The concatenation of the input path components.
"""
result = ""
... |
def currency_display(value, currency='AUD', show_complete=False, include_sign=True):
"""
Create a human readable string to display a currency from some number of smallest units (e.g. cents).
:param value: value of currency in smallest units (cents)
:param currency: e.g. 'AUD'
:param show_complete... |
def ordinalize(given_number: int) -> str:
"""Ordinalize the number from the given number
Args:
given_number (int): integer number
Example:
>>> ordinalize(34)
'34th'
Returns:
str: string in ordinal form
"""
suffix = ["th", "st", "nd", "rd"]
thenum = int(given_number... |
def kwargs_to_filter(kw):
"""Converts key/values in the form year=yyyy to key/values usable as queryset
filters, pretty inefficient and with no checks on data.
"""
d = {}
for k in ('year', 'month', 'day', 'hour', 'minute', 'second'):
if k in kw:
try:
d['da... |
def gather_txt(input_files, output_file, skip_empty=False):
"""
Very simple concatenation of text files labeled by file name.
"""
lines = []
for input_file in input_files:
with open(input_file, "r") as txt:
lines.append("### FILE {f}:\n{t}".format(f=input_file,
... |
def not_found(environ, start_response):
"""Called if no URL matches."""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['Not Found'] |
def str_count(string, target, start=0, end=None):
"""
Description
----------
Count the number of times a target string appears in a string.
Parameters
----------
string : str - string to iterate\n
target : str - string to search for\n
start : int, optional - start index (default is ... |
def polynomial_carre(a: float, b: float, c: float, x: float) -> float:
"""Retourne la valeur de ax^4 + bx^2 + c
"""
return ((a*x*x + b) * x*x) + c |
def retrieve_item(item_id):
"""
This is a stubbed method of retrieving a resource. It doesn't actually do anything.
"""
return {
"id": item_id,
"brand_name": "Clean Breathing",
"name": "Air Purifier",
"weight": 12.3,
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.