content stringlengths 42 6.51k |
|---|
def link_is_valid(link_info, query_words, mode="all"):
"""
Tests if a link is valid to keep in search results, for a given query
:param link_info: a dict with keys "url" and "text"
:param query_words: a list of query words
:param mode: can be "all" (default), or "any"
:return: True or False
... |
def xgcd(a,b):
"""
Returns g, x, y such that g = x*a + y*b = gcd(a,b).
"""
## enter your source code here
tempa = a
tempb = b
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
g = b
# if x<... |
def Italic(string):
"""Returns string wrapped in escape codes representing italic typeface."""
return '\x1D%s\x0F' % string |
def extrapolate_statistics(scope):
"""Return an extrapolated copy of the given scope."""
c = {}
for k, v in list(scope.items()):
if isinstance(v, dict):
v = extrapolate_statistics(v)
elif isinstance(v, (list, tuple)):
v = [extrapolate_statistics(record) for record in ... |
def rightrotate_numba(x, c):
""" Right rotate the number x by c bytes."""
x &= 0xFFFFFFFF
return ((x >> c) | (x << (32 - c))) & 0xFFFFFFFF |
def split_list(alist, wanted_parts=1):
"""Split a list to the given number of parts."""
length = len(alist)
# alist[a:b:step] is used to get only a subsection of the list 'alist'.
# alist[a:b] is the same as [a:b:1].
# '//' is an integer division.
# Without 'from __future__ import division' '/' ... |
def parse_task(line):
"""
Receives a line and parses it to match the format `[subject] name`, where `subject` is a two-letter code for the subject and `name` is the name of the task.
If `subject` is invalid, the user is re-prompted until a valid entry is given. Capitalisation is automatic.
Args:
... |
def inc_password(ipw):
"""
>>> inc_password([0, 1, 2, 3, 4, 5, 6, 7])
[0, 1, 2, 3, 4, 5, 6, 8]
>>> inc_password([0, 0, 0, 0, 0, 0, 0, 25])
[0, 0, 0, 0, 0, 0, 1, 0]
>>> inc_password([0, 0, 0, 0, 5, 25, 25, 25])
[0, 0, 0, 0, 6, 0, 0, 0]
"""
result = ipw[:]
i = len(result) - 1
w... |
def get_len_utf8(key):
""" Get the length utf8 string """
if len(key) > 0:
char = ord(key[0])
if char <= 0x7F:
return 1
elif char >= 0xC2 and char <= 0xDF:
return 2
elif char >= 0xE0 and char <= 0xEF:
return 3
elif char >= 0xF0 and char <= 0xF4:
return 4
return 1
else:
return 0 |
def _spatial2d_pad_option(padding, kernel):
"""Common code to get the pad option
Parameters
----------
padding : int or str
Padding size, or ['VALID', 'SAME']
kernel : tuple of int
Conv kernel size
Returns
-------
pad_top : int
Padding size on top
pad_left... |
def get_bigram(text):
"""Counts N-gram"""
cur = '[BOS]'
bigrams = []
for token in text:
pre = cur
cur = token
bigrams.append((pre, cur))
return bigrams |
def str2int(string):
"""Convert input string into integer. If can not convert, return 0"""
try:
value = int(string)
except ValueError:
value = 0
return value |
def choose(key: str, **kwargs):
"""
:returns value associated with key in kwargs, None if no such value
"""
return kwargs.get(key, None) |
def cmp(a, b) -> bool:
"""A cmp function because one is no longer available in python3."""
return (a > b) - (a < b) |
def determine_inception(model_type):
"""
Determines if the model type is Inception v3.
:param model_type: Model type.
:return: A boolean indicating if the model is Inception v3.
"""
return True if model_type == 'inception_v3' else False |
def min_distance(queue, dist):
"""
Returns node with smallest distance in queue
"""
min_node = None
for node in queue:
if min_node is None:
min_node = node
elif dist[node] < dist[min_node]:
min_node = node
return min_node |
def reset_line_breaks(curr_boundary={}):
"""
Builds a fresh line breaks dictionary while keeping any
information provided concerning line boundaries.
Parameters
----------
curr_boundary: dict
Line boundaries to be preserved
Returns
-------
dict
The newly initialize... |
def process_survey_hist(survey_children : dict, survey_hist : list) -> dict:
"""Parses history metadata for title, date, student uid, and creation date.
:param post_hist: post history
:returns: dictionary with relevant history data pulled.
"""
result = {}
latest = survey_hist[0]
result["stu... |
def remove_salt(dict):
"""Removing salt from the ingredients"""
result_dict = dict.copy()
del result_dict["salt"]
return result_dict |
def testNumber(arg):
"""outputs True if 'f' is a number"""
try:
x = float(arg)
except ValueError:
return False
return True |
def window_decay(d: float, a: float):
"""
Only considers customers that are at most distance 'a' from the current customer.
f(d) = 1/[d < a]
:param d: distance (non-negative finite value)
:param a: maximum distance
:return: decay
"""
return 1 if d < a else 0 |
def iscomment(s):
"""
Define what we call a comment in MontePython chain files
"""
return s.startswith('#') |
def is_number(s):
""" Test if the value can be converted to a number.
"""
try:
float(s)
return True
except ValueError:
return False |
def __get_package_from_build(build, package_name):
"""
Finds a package in a build by package name
:param build:
:param package:
:return:
"""
package = None
for _package in build["packages"]:
if _package["package"] == package_name:
package = _package
break
... |
def where(lst, func):
"""Indices are particular elements
Args:
lst(list):
func(callable): one argument
Returns:
list
"""
return [i for i, l in enumerate(lst) if func(l)] |
def convert_bytes2string(thebytes: bytes):
"""Converts a "bytes" type object into a "str" type object
Examples:
>>> convert_bytes2string(b'nice string')\n
'nice string'
"""
return thebytes.decode() |
def _generate_key(key):
""" Serializes a tuple into a key for caching
"""
if isinstance(key, (list, tuple)):
return "-".join(key)
return key |
def get_neighbors(node, ajacency_list):
"""Networkx only provides the very large adjaceny list, this filters that down"""
neighs = set()
for (a, b) in ajacency_list:
if a == node:
neighs.add(b)
elif b == node:
neighs.add(a)
return neighs |
def dashify(value):
""" return an 11 digit part number with dashes.
e.g. 00000000000 becomes 00-0000-0000-0; if value is not 11 characters,
return the value """
prodstring = str(value)
if not len(str(value)) == 11:
return value
return "%s-%s-%s-%s" % (prodstring[0:2], prodstring[2:6], prodstring[6:10], p... |
def auto_widget_kwarg(widget_type, kwarg, reference_array):
"""
For a particular widget type, keyword argument, and array
of values, set reasonable defaults.
"""
if widget_type in ("CheckboxGroup", "CheckboxButtonGroup"):
reference_set = list(set(reference_array))
if kwarg ... |
def _get_message(status):
"""
Given problem status code, return a more detailed message.
Parameters
----------
status : int
An integer representing the exit status of the optimization::
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Prob... |
def convert_1bpp_to_2bpp(data):
"""
Convert 1bpp image data to planar 2bpp (black/white).
"""
output = []
for i in data:
output += [i, i]
return output |
def spin(array):
"""Spin the wheel of fortune - the function picking an asset from the list, note: it can pick duplicates"""
import random
num_choices = len(array)
secure_random = random.SystemRandom()
return secure_random.choice(array) |
def left_d_threshold_sequence(n,m):
"""
Create a skewed threshold graph with a given number
of vertices (n) and a given number of edges (m).
The routine returns an unlabeled creation sequence
for the threshold graph.
FIXME: describe algorithm
"""
cs=['d']+['i']*(n-1) # cre... |
def vector_divide(vector, value):
"""
Divides given vector by a value
:param vector: list(float, float, float)
:param value: float ,value to multiple vector by
:return: list(float, float, float)
"""
result = [vector[0] / value, vector[1] / value, vector[2] / value]
return result |
def load_candidate_bond_changes_for_one_reaction(line):
"""Load candidate bond changes for a reaction
Parameters
----------
line : str
Candidate bond changes separated by ;. Each candidate bond change takes the
form of atom1, atom2, change_type and change_score.
Returns
-------... |
def checkDebugOption(debugOptions):
"""
function to set the default value for debugOptions and turn it from
a string into a boolean value
Args:
debugOptions: string representation of boolean value for debug flag
Returns:
Boolean value for debug flag
"""
if debu... |
def factorial(n):
"""
Returns the factorial of the given number n
"""
if n <= 1 : return 1
return n*factorial(n-1) |
def flatten_list_of_lists(L):
""" Flattens a list of lists to return a single list of objects. """
return [item for sublist in L for item in sublist] |
def svid2gnssid(svid) -> int:
"""
Derive gnssId from svid numbering range.
:param int svid: space vehicle ID
:return: gnssId as integer
:rtype: int
"""
if 120 <= svid <= 158:
gnssId = 1 # SBAS
elif 211 <= svid <= 246:
gnssId = 2 # Galileo
elif (159 ... |
def dictincr(dictionary, element):
"""
Increments `element` in `dictionary`,
setting it to one if it doesn't exist.
>>> d = {1:2, 3:4}
>>> dictincr(d, 1)
3
>>> d[1]
3
>>> dictincr(d, 5)
1
>>> d[5]
1
"""
dictionary.setdefau... |
def duplicate_layers(layers):
"""Find duplicate layers in datasets."""
error_layers = list(set([item for item in layers if layers.count(item) > 1]))
error = {}
critical = False
# clean layers and report error
if error_layers:
error_layers_str = ",".join(error_layers)
layers = [i... |
def _ErrorHighlight(start, length):
"""Produces a row of '^'s to underline part of a string."""
return start * ' ' + length * '^' |
def _represents_int(s):
"""Helper function to test if a string represents an integer."""
try:
int(s)
return True
except ValueError:
return False |
def add_deformation(chn_names, data):
"""From circularity, compute the deformation
This method is useful for RT-DC data sets that contain
the circularity but not the deformation.
"""
if "deformation" not in chn_names:
for ii, ch in enumerate(chn_names):
if ch == "circularity":
... |
def prime(number):
"""
Get the n-th prime
"""
if number == 0:
raise ValueError('there is no zeroth prime')
is_prime, count = [True for i in range(1000000 + 1)], 0
for i in range(2, 1000000 + 1):
if is_prime[i]:
count += 1
if count == number:
... |
def dyads_stats(edges, n_nodes, root_idx):
"""
Compute the number of nodes that have 1-way, 2-way and no edges.
Takes O(|edges|).
NB: you need to know the num of nodes as there might be 0-degree nodes
Input:
- edges: set of (i, j) tuples
- n_nodes: number nodes in the graph... |
def atom(draw):
"""
atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
"""
#'(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
return '' |
def find_closing_characters(chunk: str) -> str:
"""Return the closing characters that complete an incomplete chunk."""
stack = []
bracket_mapping = {")": "(", "]": "[", "}": "{", ">": "<"}
bracket_mapping_reversed = {v: k for k, v in bracket_mapping.items()}
open_brackets = ["(", "[", "{", "<"]
... |
def _tl_add(tl1, tl2, alpha=1.0):
"""Summation of two tensor lists."""
return [
t1 + alpha * t2
for t1, t2 in zip(tl1, tl2)
] |
def safeintorbignumber(value):
"""safely converts value to integer or 10M"""
try:
return int(value)
except ValueError:
return 10000000 |
def ror32(x, shift):
"""Rotate X right by the given shift value"""
assert 0 < shift < 32
return (x >> shift) | ((x << (32 - shift)) & 0xffffffff) |
def insort(col, element, get=lambda x: x):
"""Python's bisect does not allow for a get/key
so it can not be used on a list of dictionaries.
Inserts element into the sorted collection col via
a binary search.
if element is not directly compairable the kwarg get may
be a callable that transforms e... |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, Nothing at this URL.', 404 |
def format_class_name(name):
"""
Formats a string to CapWords.
:param name: string to format
:type name: str
:return: string with the name in CapWords
:rtype: str
"""
fixed_name = name.title().replace("_", "")
return fixed_name |
def positive_index(index, size):
"""
Return a positive index from any index. If the index is positive, it is
returned. If negative, size+index will be returned.
Parameters
----------
index : int
The input index.
size : int
The size of the indexed dimension.
Returns
... |
def saisie_valide(saisie):
"""
Checks if the input is a valid one
Parameters
----------
saisie : str
Unique movement
Returns
-------
valid : boolean
True = movement is valid
False = movement is not valid
"""
if len(saisie) == 1: # Only FLRUDB
if saisie[0] not in "FLRUDB":
return False
elif len(... |
def _strip_prefix(key, prefix):
"""
Strip the prefix from the key.
Returns None if the key does not
have the specified prefix
:param unicode key:
:param unicode prefix:
:return: The prefix-free key
:rtype: unicode
"""
if prefix and key.startswith('%s_' % prefix):
return ... |
def flatten(lst):
"""Returns a flattened version of lst.
>>> flatten([1, 2, 3]) # normal list
[1, 2, 3]
>>> x = [1, [2, 3], 4] # deep list
>>> flatten(x)
[1, 2, 3, 4]
>>> x # Ensure x is not mutated
[1, [2, 3], 4]
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> flatten... |
def doc2vector(model, samples):
"""Infer vectors for samples
Args:
model: The instance to use to infer vectors vectors as :class:`gensim.models.Doc2Vec`.
samples: The samples as :class:`list`.
Returns:
The :class:`list` of inferred vectors.
"""
return [model.infer_vector(sa... |
def check_profiling_options(profiling_options=[]):
"""Check profiling options .
Args:
profiling_options: Profiling options.
Return:
Valid options
Raise:
If profiling_options is null or option is not `training_trace` or `task_trace`, `op_trace`'.
"""
error_mag = 'profiling options must be ... |
def teleop_out_cb(outcome_map):
"""Returns transition for end of teleop concurrence"""
if outcome_map['EXIT_LISTEN'] == 'invalid':
return 'done'
elif outcome_map['TOGGLE_LISTEN'] == 'invalid':
return 'enter_autonomy'
else:
return 'stay' |
def is_valid_tfprof_tracefilename(filename: str) -> bool:
"""
Ensure that the tracefilename has a valid format.
$ENV_BASE_FOLDER/framework/tensorflow/detailed_profiling/$START_TIME_YYYYMMDDHR/$STEP_NUM/plugins/profile/$HOSTNAME.trace.json.gz
The filename should have extension trace.json.gz
"""
... |
def mix32(i):
"""MurmurHash3 mix32 finalizer."""
i ^= i >> 16
i = (i * 0x85ebca6b) & 0xffffffff
i ^= i >>13
i = (i * 0xc2b2ae35) & 0xffffffff
i ^= i >> 16
return i |
def remove_none_attributes(attributes):
"""Return a new dict with all None values removed
:param attributes: Dictionary containing all the item attributes
"""
# out = {}
# for k, v in attributes.iteritems():
# if v is not None:
# if type(v) is dict:
# attributes[k... |
def forum(read=20, write=20):
"""Return the kwargs for creating the Forum table."""
return {
'AttributeDefinitions': [
{
'AttributeName': 'Name',
'AttributeType': 'S'
},
],
'TableName': 'Forum',
'KeySchema': [
{
... |
def bounds1D(stop, step_size, start=0):
"""
Return the bbox coordinates for a single dimension given
the size of the chunked dimension and the size of each box
"""
assert step_size > 0, f"invalid step_size: {step_size}"
i = start // step_size
beg = start
end = (i+1) * step_size
bou... |
def bb_intersection_over_union(box_a, box_b):
"""
Find out how much 2 boxes intersect
:param box_a:
:param box_b:
:return: IOU overlap
"""
# determine the (x, y)-coordinates of the intersection rectangle
x_a = max(box_a[0], box_b[0])
y_a = max(box_a[1], box_b[1])
x_b = min(box_... |
def check_word_format(w):
"""
Check whether specified word format is either ``(W, WI, WF)`` or ``(W, WI)``
Arguments
---------
w : tuple
``(W, WI, WF)`` or ``(W, WI)``, items need to be integer
Returns
-------
Tuple
``(W, WI, WF)``
"""
if len(w) == 2... |
def value_range(x1,x2,dx,epsilon=0.00001):
""" value_range(x1,x2,dx) produces float or integer results [x1, ..., x2] with step dx
This is meant to emulate Mathematica's Range[x1,x2,x], with a "<=" upper bound, in
contrast to Python's range, which is limited to integers and has an "<" upper bound.
Borr... |
def resultIsSuccess(res):
"""
JSON-decoded stake pool responses have a common base structure that enables
a universal success check.
Args:
res (dict): The freshly-decoded-from-JSON response.
Returns:
bool: True if result fields indicate success.
"""
try:
return res[... |
def strip_implicit_build_name(path):
"""Strips the implicit build names (such as BUILD) from the given path.
Args:
path: A path that may contain a BUILD name.
Returns:
The path with the name stripped.
"""
path = path.replace('/BUILD:', ':').replace('BUILD:', ':')
path = path.replace('/BUILD.anvil:... |
def pipe(*funcs):
"""
Returns the function composition of two or more functions.
:param funcs:
All functions should have one argument, except the first function. Still,
it is recommended for that function to have a single argument too.
:type funcs:
\*function
:returns:
... |
def nextday_datestr(datestr):
"""
Return the next day's datestr of the given datestr.
20171101 will be returned if 20171031 was given, for example.
"""
from datetime import datetime, timedelta
nextday = datetime.strptime(datestr, '%Y%m%d') + timedelta(days=1)
return nextday.strftime('%Y%m%d... |
def cels_from_fahr(fahr):
"""Convert a temperature in Fahrenheit to
Celsius and return the Celsius temperature.
"""
cels = (fahr - 32) * 5 / 9
return cels |
def json_parameter_validation(json_data, required_parameters):
""" Check parameter is available in json or not
:parameter:
json_data: dict, required
A dictionary that should be validate by parameter are available or not
required_params: list, required
Those list of params... |
def transform_2D_to_3D(x, y,
focal_length,
pixel_size_x, pixel_size_y,
principal_point_x, principal_point_y):
"""
Transforms 2D point on image coordinate system (ICS) to 3D point in camera coordinate system (CCS).
Camera coordinate system ... |
def mean(values):
"""
>>> mean([1, 2, 3])
2.0
>>> mean([2, 4, 8])
4.666666666666667
"""
return sum(values) / len(values) |
def map_asns_to_seq(path_list):
"""
Mutates the passed in path_list and returns a dict of mapping
:param path_list:
:return:
"""
asn_seq_map = dict() # (key, value) = (asn, seq_value)
seq_asn_map = dict() # (key, value) = (seq_value, asn)
seq_num = 0
for i, path in enumerate(path_l... |
def factorial(n):
"""Calcula el factorial de n.
n int > 0
returns n!
"""
if n == 1:
return 1
return n * factorial(n-1) |
def count_string_diff(a,b):
"""Return the number of characters in a string that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) |
def cell(y, x):
"""Derive the appropriate game state cell from curses window y, x
coordinates by correcting for the board offsets
y: y position in the curses window
x: x position in the curses window
"""
return y // 2, x // 2 |
def approximates(ref_point, point, max_deviation):
"""Helper function to check if two points are the same within the specified deviation."""
x = ref_point[0] - max_deviation <= point[0] <= ref_point[0] + max_deviation
y = ref_point[1] - max_deviation <= point[1] <= ref_point[1] + max_deviation
... |
def clues_too_many_ip(text):
""" Check for any "account sharing" clues in the response code """
text = text.lower()
for clue in ('simultaneous ip', 'multiple ip'):
if clue in text:
return True
return False |
def make_virtual_offset(block_start_offset, within_block_offset):
"""Compute a BGZF virtual offset from block start and within block offsets.
The BAM indexing scheme records read positions using a 64 bit
'virtual offset', comprising in C terms:
block_start_offset << 16 | within_block_offset
Here ... |
def _format_s3_error_code(error_code: str):
"""Formats a message to describe and s3 error code."""
return f"S3 error with code: '{error_code}'" |
def add_s(num):
"""If it's 1, return blank otherwise return s"""
if num == 1:
return ""
return "s" |
def merge_dict(d1, d2, merge=lambda x, y: y):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2. (There is no other generally
applicable me... |
def _select_resources_github(resources_list: list):
"""Returns the list of GitHub resources from the list of all resources.
Args:
resources_list (list): a list of resource dictionaries.
Returns:
list: a subset of the input list containing only GitHub resources.
"""
re... |
def egg_drop(eggs: int, floors: int) -> int:
"""
>>> egg_drop(42, 0)
0
>>> egg_drop(42, 1)
1
>>> egg_drop(1, 5)
5
>>> egg_drop(2, 100)
14
"""
s = [] # s[remaining_floors][remaining_eggs]
for floor in range(floors + 1):
row = []
for reduced_eggs in range(e... |
def convert_normalize(normalize, channel):
""" 7. Normalize """
if normalize == 1:
if channel != "None":
command = "-channel " + channel + " -equalize"
else:
command = "-equalize"
elif normalize == 2:
command = "-auto-level"
else:
command = ""
... |
def measureDistance(pointA, pointB):
"""
Determines the distance pointB - pointA
:param pointA: dict
Point A
:param pointB: dict
Point B
:return: int
Distance
"""
if (pointA['chromosome'] != pointB['chromosome']):
distance = float('inf')
if ('position'... |
def users_in_media(user_ids, media):
"""Return a list of those media where a user is in the photo"""
if type(user_ids) is not list: user_ids = [user_ids]
return [m for m in media if any(
user_id in [u.user.id for u in m.users_in_photo]
for user_id in user_ids)] |
def markdown_table_row(key, value):
"""
Create a row in a markdown table.
"""
return u"| {} | {} |\n".format(key, value) |
def rectified_linear_unit_derivative(x):
""" Returns the derivative of ReLU."""
return 1 if x > 0 else 0 |
def signal_strength(code):
"""
returns text of strength rssi value
"""
if code >= -5:
return 'Amazing'
if code >= -20:
return 'Very Good'
if code >= -50:
return 'Good'
if code >= -70:
return 'Fair'
if code >= -80:
return 'Poor'
if code >= -90:
... |
def create_model_info(data_url):
"""Given the name of a model architecture, returns information about it.
Args:
Nothing
Returns:
Dictionary of information about the model, or None if the name isn't
recognized
Raises:
ValueError: If architecture name is unknown.
"""
model_file_name = 'outp... |
def _translate(expr, trexpr, newexpr=None):
"""Private translate function to allow repeated processing (in a loop)."""
# We use the string and translation map for both paths
expr = str(expr)
trexpr = str(trexpr)
trmap = dict()
if newexpr is not None:
# Create a translation map between t... |
def qid_to_key(value_list, sep=';'):
"""convert qid list to str key
value (splited by sep). This fuction is value safe, which means
value_list will not be changed.
return str list.
"""
return sep.join(value_list) |
def exists_inferred_relationship(flow_ingress_asn, flow_egress_asn, d_global_members_customercone_ppdcases_finder):
"""
Checks the existence of AS-Relationship in the inferences dataset from (AS-Rel algorithm).
"""
exist_inferred_asrel = False
ingress_asn_info = flow_ingress_asn
egress_asn_info... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.