content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def step(adv):
"""Show player's step count.
Args:
adv: namedtuble holding the game data
Modifies: nothing
Returns:
string: message showing steps so far
"""
return adv.messages["step"].format(adv.player["step"]) | b467e5e0e9e43a6e862137f94f6af0aa98dde60e | 615,356 |
def pyver() -> str:
""" Returns string with python version number in major.minor.micro format.
(e.g. 3.7.3 or 2.7.12)
"""
return '.'.join(str(i) for i in __import__('sys').version_info[:3]) | d84ca1fc251acbafb454565ad925b847e158f03d | 615,357 |
def bin2dec(n):
"""Convert a binary number to decimal.
Args:
n (str): The string representation of a binary number to convert.
Returns:
int: The result decimal number if n is valid.
"""
return int(n, 2) | a1f06656ce2f399dcb7b6eb7d9ca678724b72a0f | 615,358 |
def connect(from_endpoint, to_endpoint):
"""Connects an upstream endpoint to a downstream endpoint.
This is a convenience function only. Endpoint users may instead
choose to write the 3 eq statements required to make a connection.
Example uses:
m.d.comb += connect(one_components_output, another_c... | d610fd227e7d5ae2d56fed7dc2880b19143709ad | 615,360 |
import importlib
def cfg_instantiate(cfg, *args, **kwargs):
"""Create a instance of a class specified in cfg."""
package_name, classname = cfg.classname.rsplit(".", 1)
package = importlib.import_module(package_name)
constructor = getattr(package, classname)
obj = constructor(*args, **(cfg.kwargs o... | 5768b1ebf7dc12a3bf2279f911fa0c93367ec9e9 | 615,361 |
def flatten(values, mask):
"""Flatten the spatial dimensions of the input array
and removed masked points
"""
# Flatten and mask the input array
args = [-1] if values.ndim < 4 else values.shape[:2]
maskflat = mask.ravel().astype(bool)
valuesflat = values.reshape(*args, len(maskflat))[..... | cea9732079f37f921f2b80d21f181cab0dd019d7 | 615,363 |
import string
def remove_punc(words):
"""Function that removes punctuation from a string
Arguments
---------
words -- string to have punctuation removes
"""
trans = {ord(c): None for c in string.punctuation}
no_punc = words.translate(trans)
return no_punc | c5226cc6b2dfb37f7d697f95f2433b0a23f06343 | 615,366 |
import re
def remove_numbers(words):
"""Remove numbers and words that start with numbers
"""
new_words = []
for w in words:
if not re.match(r"\d+.*", w):
new_words.append(w)
return new_words | 88513102f75f516e6afe22ee05604bc533855f13 | 615,367 |
def convert_quat(q, to="xyzw"):
"""
Converts quaternion from one convention to another.
The convention to convert TO is specified as an optional argument.
If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa.
Args:
q: a 4-dim numpy array corresponding to a quaternion
... | f59e7fd11338f36ae4bd9c393277a0e354b633ac | 615,370 |
import six
def to_bed12(f, db, child_type='exon', name_field='ID'):
"""
Given a top-level feature (e.g., transcript), construct a BED12 entry
Parameters
----------
f : Feature object or string
This is the top-level feature represented by one BED12 line. For
a canonical GFF or GTF... | d4042b979840b0eb41d23690182a030278473b1b | 615,371 |
def latest_date_between(date_1, date_2):
"""Utility function to compare the dates and return latest date."""
if date_1 > date_2:
return date_1
else:
return date_2 | 6ef511dc35812ca2cf1842cec8a9454fe0503891 | 615,373 |
import asyncio
import functools
def schedule_callback(delay, callback, *args, **kwargs):
"""
Schedule callback (which is passed args and kwargs) to be called on
running event loop after delay seconds (can be floating point). Returns
asyncio.TimerHandle on which cancel() can be called to cancel the
... | a0806bc5b936e6ad6aaf451f120fd3e19627a85c | 615,374 |
import random
def generate_random_input(seed, n):
"""Generates a list with n uint8 numbers."""
random.seed(a=seed)
return [random.randint(0, 255) for _ in range(n)] | 3aa4ad4b2da91008b1c77267992d4d7b02781aa2 | 615,375 |
import typing
def _assert_str(item: typing.Any) -> str:
"""Check that item is a string."""
assert isinstance(item, str)
return item | 634c0bce23191dc940b600846544b939d842bc52 | 615,377 |
def create_GAN_hparams(generator_hidden_layers=[30, 30], discriminator_hidden_layers=[30, 30], learning_rate=None,
epochs=100, batch_size=32, activation='relu',
optimizer='Adam', loss='mse', patience=4, reg_term=0, generator_dropout=0,
discriminator_d... | 026057d375ee0183ef5460377210d9ba8d8226dc | 615,379 |
def acid_installed(request):
"""
Acid is installed.
Args:
request: Pytest request.
Returns:
bool: Acid installed
"""
return request.config.getoption("--installed") | fc2ff11bd138d44dfbd52d76d1d6de61b51ff43c | 615,380 |
def sindex(string, row, col):
"""Get index of the character at `row`/`col` in `string`.
:Parameters:
- `row`: row number, starting at 1.
- `col`: column number, starting at 1.
:Returns: ``i``, starting at 0 (but may be <1 if row/col<0)
:Note: This works for text-strings with '\... | 83d9506da07daf4559e73cc06f53803e01fd5da9 | 615,393 |
def mag_cut(mag, low, high):
"""
Define a high and low value and flag the
values that fall within those boundaries
"""
isGood = 0
if mag <= high and mag >= low:
isGood = 1
return isGood | f6f6408df30f4d1e075a80e989a52438d141db8a | 615,396 |
def find_integer(f):
"""Finds a (hopefully large) integer such that f(n) is True and f(n + 1) is
False.
f(0) is assumed to be True and will not be checked.
"""
# We first do a linear scan over the small numbers and only start to do
# anything intelligent if f(4) is true. This is because it's ve... | 9eda2455a31779e9dfc4a009e12300c88baeb9c0 | 615,399 |
def format_table_row_single(lbl, label, value):
""" Format table row string representing a single value (two cells:
label, value)
Input:
- lbl: Short/abbreviated label string
- label: Full label string
- value: Value at specified label (type agnostic)
Output: String to be used ... | 652800524a9ef493112f92ca2bcabee43da5098d | 615,401 |
import re
def _remove_multiple_spaces(text: str) -> str:
"""Remove multiple white spaces.
e.g. "The koala is angry !"
Args:
text (str): The text.
Returns:
str: CLeaned text.
"""
return re.sub(' +', ' ', text) | 3cfc3db1193f601eeecf5f026bfcc356e57c88d8 | 615,403 |
def hasPTC(sequence):
"""
Determines whether a PTC exits in a sequence
Arguments:
sequence (str): IMGT gapped sequence in frame 1.
Returns:
int: negative if not PTCs, position of PTC if found.
"""
ptcs = ("TAA", "TGA", "TAG", "TRA", "TRG", "TAR", "TGR", "TRR")
for i in range(0... | 9116ff203dba6acb79d8481d9475f0288fae62bb | 615,404 |
def gens(x):
"""
Return the generators of ``x``.
EXAMPLES::
sage: R.<x,y> = SR[]
sage: R
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: gens(R)
(x, y)
sage: A = AbelianGroup(5, [5,5,7,8,9])
sage: gens(A)
(f0, f1, f2, f3, f4)
... | 362fcc78f6a44fd3b8d8ab650cdfb9459af5c344 | 615,406 |
async def pull_content_from_unit_file(unit, path: str) -> str:
"""Pull the content of a file from one unit.
Args:
unit: the Juju unit instance.
path: the path of the file to get the contents from.
Returns:
the entire content of the file.
"""
action = await unit.run(f"cat {p... | 538ffc9d91b150c308be628b9c2292d749ca4505 | 615,407 |
def write_csv(paths, headers):
"""
Takes in an array of .csv paths and appends them all together using
python fucntions. This allows us to pull in a large dataset, relying
on disk space, while preserving limited system memory.
"""
csv_out = "consolidated.csv"
csv_merge = open(csv_out, "w")
... | 759d5669080e6a47f44c5d388fa93afb32cb3ed0 | 615,408 |
from datetime import datetime
def dateFormat(timestamp):
"""
Format timestamp (nb of sec, float) into a human-readable date string
"""
formatStr = '%a %b %d, %Y - %H:%M'
try:
return datetime.fromtimestamp(int(timestamp) or 86400).strftime(formatStr)
except OSError as e:
return ... | cb73ea04d9cc30dfe998e9cdcc84644e68781ae6 | 615,409 |
def extract_items(topitems_or_libraryitems):
"""Extracts a sequence of items from a sequence of TopItem or LibraryItem objects."""
list = []
for i in topitems_or_libraryitems:
list.append(i.get_item())
return list | 8ae08d827d16f626a41cdd499873a6c36ef4912a | 615,410 |
def save_cluster(cluster):
"""Save cluster's units and origin
Parameters
----------
cluster : class
StarCluster
Returns
-------
cluster.units, cluster.origin : str
units and origin of StarCluster
History:
-------
2018 - Written - Webb (UofT)
"""
return... | 74075a1e7e8f3724b56e57b468873b132dd174f9 | 615,411 |
def _compress_list(l):
"""Removes consecutive duplicate elements from |l|.
>>> _compress_list([])
[]
>>> _compress_list([1, 1])
[1]
>>> _compress_list([1, 2, 1])
[1, 2, 1]
"""
result = []
for e in l:
if result and result[-1] == e:
continue
result.append(e)
return result | c5766047f075a42303ec5e46322d2616e7e71409 | 615,412 |
def rotate_inertia(rotation_matrix, inertia):
"""Returns an inertia tensor expressed in a reference frame which has
been rotated with respect to the frame the inertia tensor is currently
expressed in.
Parameters
----------
rotation_matrix : numpy.matrix, shape(3,3)
Three-dimensional rot... | e0831c79ef4ee5775cc22727bb0222a026516c59 | 615,413 |
def get_tolerance_min_max(value, expected_tolerance):
"""
Get minimum and maximum tolerance range
Args:
value(int): value to find minumum and maximum range
expected_tolerance ('int'): Expected tolerance precentage
Returns:
minimum and maximum value of tol... | 6ab5ffe1cc78e952c2a7dff01d406adc5ce30d07 | 615,415 |
def _fill_deque_by_initial_value(
deque_obj, initial_value, buffer_size):
"""
Fill the deque object with the initial value.
Parameters
----------
deque_obj : collections.deque
The deque object to add to.
initial_value : int or float
Initial value to be referenced.
bu... | fef8fb44412fe0b56999ffa1d9e73c1848e58ee8 | 615,416 |
import torch
def heaviside(X):
"""
A pytorch-differentiable version of the Heaviside function
.. math::
H\\left(x\\right) = \\frac{\\operatorname{sign}(x) + 1)}{2}
Args:
X: tensor input
"""
return (torch.sign(X) + 1.0) / 2.0 | 7a487ffb3a610f11c5f7a31f58ba0ecc78b1271c | 615,417 |
def distance(a, b):
"""Simple distance between two 1D arrays"""
return ((a - b) ** 2).sum() ** (0.5) | 073b5e7ceb41266dd8edd1cafd62da140ac55846 | 615,419 |
def evaluate(v1, v2, operator):
"""Evaluation function for two values and an operator.
Args:
v1 (obj): object one
v2 (obj): object two
operator (string): operator that is being used
Returns:
bool: result of the equation v1 operator v2
"""
if operator == '==':
... | afbb4d9c970ef02cef1eff0d78ca9ccacba1a448 | 615,420 |
import pickle
def read_model(file_name):
"""Loads the specified pickle file.
Parameters
----------
file_name : str
The location the pickle file.
Returns
-------
dict
The dictionary inside the pickle.
"""
with open(file_name, "rb") as model_file:
return p... | 96e42e94886107f5581f042f7524effd8b3a97dd | 615,421 |
def nx_edge_data_weight(edge_u, edge_v, edge_data):
"""Return custom edge data value to be used as a callback by nx."""
if edge_data.get("hop"):
return edge_data["hop"]
return 1 | a7e9ca1292b0531275f2091ddc370660c92147f4 | 615,424 |
def avg_Q(q_S, q_D):
"""
Return total transmission capacity of station, assuming transmission evenly distributed over hexagonal cell
Parameters
----------
q_S : float
channel capacity in Mbps
q_D : float
data demand rate in Mbps
Returns
... | db78680a57319d642e367fe8fbacdbf8f31648ff | 615,427 |
def read_text(abspath, encoding="utf-8"):
"""
Read string from a file.
:type abspath: str
:type encoding: str
:rtype: str
"""
with open(abspath, "rb") as f:
return f.read().decode(encoding) | 7c3a4ca6829eff5bd8b1597979face440af42d5f | 615,430 |
def _prepare_params(dirty_params, prefix=None):
"""Prepares parameters to be sent to challonge.com.
The `prefix` can be used to convert parameters with keys that
look like ("name", "url", "tournament_type") into something like
("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
... | 55c880a48a9f13a6cb49f0d5f1b3b4ca4b6c5f1c | 615,432 |
import re
def parse_RA_Dec(ra_string, dec_string):
"""Convert input RA and Dec strings to floats
Parameters
----------
ra_string : str
String containing RA information. Can be in the form 10:12:13.2
or 10h12m13.2s
dec_string : str
String containing Declination informatio... | 540fa848d90d9e4e33c2f9bef42fe3962b6069d3 | 615,433 |
def version_tuple_to_string(evrTuple):
"""
Convert a tuple representing a package version to a string.
@param evrTuple: A 3-tuple of epoch, version, and release.
Return the string representation of evrTuple.
"""
(e, v, r) = evrTuple
s = ""
if e not in [0, '0', None]:
s += ... | 76c93ad27ce299b33f4bd1d8789eef3f774a9185 | 615,437 |
def parse_version(version):
"""Parse version string and return version date integer."""
try:
if "-" in version:
return int(version.split("-", 1)[0])
except TypeError:
return version | 3238c1b73f82beeeac6921ec301b2da1e268583a | 615,441 |
def unicode_to_hex(unicode_string):
"""
Return a string containing the Unicode hexadecimal codepoint
of each Unicode character in the given Unicode string.
Return ``None`` if ``unicode_string`` is ``None``.
Example::
a => U+0061
ab => U+0061 U+0062
:param str unicode_string: ... | 8a7e01e2ad1b82501b8874b65a16207f27311455 | 615,446 |
def _get_operator_name(spec):
"""
Gives operator name from YAML short hand naming format
"""
components = spec.split("_")
name = "".join(x[:1].upper() + x[1:] for x in components)
if spec.endswith("dataset"):
return name
return name + "Operator" | 8d1e33650e9867a9f88c9cc9a448a5f30e0640ac | 615,448 |
def format_float_as_percentage(value):
"""Format float value as a percentage string."""
return f"{value:.0%}" | e4c92b5b88690423a4570500d60a6e09f9e9a7f1 | 615,450 |
def _GetValue(skey, tlist):
"""Get data for subfield code skey, given the subfields list."""
for (subkey, subval) in tlist:
if skey == subkey:
return subval
return None | 3ce74f2020385b08c161d15318460852a10691b5 | 615,451 |
import re
import string
def run(text: str, mode: str) -> str:
"""
Remove the numbers/punctuation from a text.
:param text: a text to process
:param mode: the mode of processing
- n: remove numbers
- p: remove punctuation
- np: remove numbers and punctuation
:return: the pr... | 9f2c4c1dc3860b5adae786acf8efab7a6b85b293 | 615,452 |
def item_bias(df, movie_id):
"""Calculate item bias: average rating for all items minus the items average rating"""
return df.loc[df['movie_id'] == movie_id, 'rating'].mean() - df['rating'].mean() | 29fd6e53d526c3c5cb2b2e6c86ca46987a6ae339 | 615,454 |
from typing import List
def boolean_array_to_integer(values: List[bool]) -> int:
"""Converts a boolean array to integer by interpretting it in binary with LSB 0 bit numbering.
Args:
values (List[bool]): The list of booleans to convert.
Returns:
int: The interpretted integer.
"""
... | 5630199d6932edc6c7d215e93a58a94a4d9fdb06 | 615,455 |
import pickle
def unpickle_object(save_path):
"""
Unpickle object saved to save_path location
Parameters:
-- save_path (str) : path to pickled object
Returns:
-- obj : pickled object
"""
infile = open(save_path, 'rb')
obj = pickle.load(infile)
infile.close()
retu... | 24ed66f2b5b09f0c51c163aaf54ffb49352e06e8 | 615,463 |
from functools import wraps
def check_field_is_empty(field_name):
"""Returns decorator that bypasses cleaning for empty fields.
"""
def decorator(fun):
"""Decorator that checks if a field is empty if so doesn't do the cleaning.
Note Django will capture errors concerning required fields that are empty.... | 1aae1f5436d3a78bf35f9cfbbb6467bc6b6b3524 | 615,464 |
def get_injected_files(personality):
"""Create a list of injected files from the personality attribute.
At this time, injected_files must be formatted as a list of
(file_path, file_content) pairs for compatibility with the
underlying compute service.
"""
injected_files = []
for item in pers... | befc8adaeb2d75d37f0956cbda933e84df93f496 | 615,466 |
def exec_fn(func):
"""Executes given function, returns {error,result} dict"""
try:
return {'result': func()}
except Exception as error: # pylint: disable=broad-except
return {'error': str(error)} | 21a122f634833855413767013bbab03167f3ee86 | 615,470 |
def predict(x_test, feature_names):
"""
Prediction is positive if the student has negative
to math and portuguese in the 3rd period
:param x_test:
:param feature_names:
:return: list of predictions correspondent to the x_test
"""
predictions = []
# get index of target columns
m... | 6e5071f7f9551c71df8baec31eda2ed517faa388 | 615,471 |
def cases_fou(col,lig):
"""Retourne la liste des indices (col,lig) des cases où peut se
déplacer un fou positionné sur la case (col, lig)
Ex: fou en (2,3)
- - - - - - - - - -
| x |
| x x |
| x x |
| F |
| x x |
| x ... | af281d19c364bedeabcd3da97057a6e975190b42 | 615,476 |
def getInternalIntfList(ch):
"""
Takes a chute object and uses the key:networkInterfaces to return a list of the internal
network interfaces that will exist in the chute (e.g., eth0, eth1, ...)
Returns:
A list of interface names
None if networkInterfaces doesn't exis... | a1364cb2f327d9a0baa01c8ab7eb27f925bdda5f | 615,477 |
def list_replace(subject_list, replacement, string):
"""
To replace a list of items by a single replacement
:param subject_list: list
:param replacement: string
:param string: string
:return: string
"""
for s in subject_list:
string = string.replace(s, replacement)
return str... | 941415a0870012fe52b20986ef77c397aef1aae8 | 615,479 |
def get_transpositions(sequence):
""" Given a series of pitch names (no flats or sharps - just abcdefg),
return a list of the 7 possible transpositions of the melody. This is used
when generating an elastic search query to look for all transpositions of a
user specified pitch sequence.
The URL for ... | 3f89486446ad66525f1ed36eab2654f14a1b5d46 | 615,481 |
def parse_options(options, return_list=True):
""" Parse dictionary/json of options, and return arg list for xtb """
cmd_options = []
for key, value in options.items():
if value is not None:
txt = f"--{key} {value}"
else:
txt = f"--{key}"
cmd_options.append... | 737ebdccf983ab9c8d1323ef998caa4ba947203f | 615,485 |
def get_date_time_from_timestamp(timestamp):
"""Get the date time from a timestamp.
The timestamp must have the following format:
'year.month.day.hour.minutes'
Example:
'2017.12.20.10.31' -> '2017/12/20 10:31'
"""
date_time_string = timestamp
sp = timestamp.split('.')
if len(sp) >= ... | 0516cac91f3b18108de635d78291e545efe0b716 | 615,490 |
def HINGED_PROPERTIES(ELEMENTS):
"""
This function creates an array with the hinge properties per node.
Input
ELEMENTS | Elements properties | Py Numpy array
| Node 0 ... Node (N_NODES - 1), Material ID, |
| Geometry ID, Hinge ID n... | 80a604bda28a69f40c6b8028d92b62249eb0607b | 615,492 |
from typing import Dict
from typing import Union
from typing import Sequence
def prepare_register_list(register_dict: Dict[str, Union[bool, Sequence[int]]]):
"""
Canonicalize classical addresses for the payload and ready MemoryReference instances
for serialization.
This function will cast keys that a... | 7ca517ba10497bd9cc5bf7aaf2ed17fcd6e25165 | 615,493 |
def is_succeeded(status, **_):
"""For when= function to test if a pod has succeeded."""
return status.get('phase') == 'Succeeded' | 508d6d0e8d7ef97785a8d0517f449850e810175e | 615,495 |
def l1_norm(vals):
"""Calculate the L1 norm of a vector."""
if len(vals)==0:
return []
try:
# If inputs are awesomediff.variable objects:
return sum([abs(v.val) for v in vals])
except:
return sum([abs(v) for v in vals]) | c419c53123fb17021b6fe3849a9aed9c87c94062 | 615,497 |
def ParseUrl(url):
"""Parses a URL string according to RFC 1738.
Note: We allow '/' character in 'user', so we can specify workgroup of smb
user.
Args:
url: An URL string.
Returns:
A dict with optional keys 'scheme', 'user', 'password', 'host', 'port', and
'urlpath'.
"""
result = {}
schem... | b1349f2091dad5daf404d672ee737dcfb904739a | 615,501 |
def sort_ongoing_wars(wars: list) -> list:
"""
Sort a provided list of wars for ongoing wars.
:param wars: A list of wars to be iterated through. Objects must contain "turnsleft" and "winner" keys.
:return: A list of active wars.
"""
return [war for war in wars if int(war["turnsleft"]) > 0 and ... | 2ef0c66b086de32ce26b52798a6918bf6a220d1a | 615,503 |
def gradient_correction(inputs, grads):
"""
Transforms vectors g=[g1,g2] and i=[i1,i2] into h=[h1, h2]
where h2 = 1/2 * 1/(i2 + 1/g2) and h1 = 2 * h2 * (g1/g2 - i1)
:param inputs: a tensor of inputs with shape ``batch_shape + [num_data]``,
:param grads: a tensor of gradients with shape ``batch_shap... | 790cf9df0b21fb5e8bcca07ebb17cbfc68af4a2f | 615,504 |
def gray_encode(i):
"""Gray encode the given integer."""
return i ^ (i >> 1) | 213d7b0e9ee178ab0aaf0efc1799bee57ed45e8e | 615,508 |
def get_tweet_node(graph, status):
"""
Search for a Tweet node in the graph matching this status, and return it
if it exists (otherwise None).
"""
return graph.nodes.match("Tweet", tweet_id=status.id).first() | 6c10eb7f9aa38659677fa1742ba324f436ac094c | 615,509 |
def get_field_errors(validation_error, field_name):
"""
Return an individual field's validation error messages.
:type validation_error: Django ValidationError
:type field_name: str
:rtype: list
"""
error_dict = validation_error.error_dict
assert field_name in error_dict
return error... | 219cad5cda31d4abf5e6148d8acab340432e97c9 | 615,510 |
import time
import select
def read_all(end, stream, append):
"""Read all buffered lines from a stream."""
while not end or time.time() < end:
line = stream.readline()
if not line:
return True # Read everything
# Strip \n at the end if any. Last line of file may not have on... | dedbbedfe949c789785b11665495715b2ec567c7 | 615,513 |
def process_activities(activities_str: str) -> list:
"""
Split activities as a pipe-separated string into a list of activities.
"""
activities_split = activities_str.split(" | ")
# Ignore row of no activities, which will be a single null string after
# splitting.
if len(activities_split) ==... | cafbd1c1689d9836ec95873a11e732ff258f32b0 | 615,515 |
import random
def efrons_biased_coin(n_subjects, bias=None, seed=None):
""" Create a randomization list using Efron's Biased Coin
Efron's Biased Coin weights the assignment of a new subject by adjusting
the probability of the Bernoulli random variable used to determine the next
group according to whi... | 3e87d5e2b1aa1cbceb24195987071e0ab95e994f | 615,518 |
def merge_dict(a, b):
""" merge dict a, b, with b overriding keys in a """
c = a.copy()
c.update(b)
return c | 45c5c9a0990ec193d85c190733465576b3a811cb | 615,520 |
from typing import Optional
import requests
def _find_city(ip: str) -> Optional[str]:
"""
Uses ip-api to find the city in which an IP address is located.
:param ip: the ip address to geolocate
:return: the city where theIP address is located or None
"""
geo_ip_url = "http://ip-api.com/json/... | 06b5dd3b6f3c904855ca7d201aee96fd1d4acb5f | 615,525 |
import six
def canonicalize_input_bounds(input_bounds):
"""Converts string constant 'none' representing unspecified bound into None.
Args:
input_bounds: The input_min or input_max hyperparameter of
`tfl.layers.Linear` layer.
Returns:
A list of [val, val, ...] where val can be a float or None, or... | da62fa1c1151914957d5228cd4942fa7a7364874 | 615,526 |
import platform
def verify(p):
"""Wait for executable to exit and verify status."""
try:
out, err = p.communicate()
except Exception as e:
raise Exception("Error running %s: %s", p.args, e)
if p.returncode:
raise Exception("""%s exit code %s
vvvvvvvvvvvvvvvv
%s
^^^^^^^^^^^^^^^^... | a68c07e75ed16ea6d0615cdeaed9b746f22aec10 | 615,527 |
def get_motion(obj_idx, frame_idx, motion_trajectory):
"""Returns the motion of a specified object at a specified frame."""
motion = motion_trajectory[frame_idx]['objects'][obj_idx]
return motion | ce09bf9752a5741f6f371e0de6285a543665c45b | 615,528 |
import pathlib
def get_parent_folder_name(path):
"""
:param str path: The full path to the file or folder.
:return str: The parent folder name.
Returns the parent folder name, given a full path.
"""
return str(pathlib.Path(path).parent) | 9801b3518174a062c1f23a5cfaf9c0f5d3a694a7 | 615,529 |
def band_select(bands):
"""
Return image/mask pair where spectral bands in image have been selected as a list.
Parameters
----------
bands : list
Spectral bands, defined with respect to input's final dimension.
Returns
-------
apply_transform : func
Transformation for i... | 7f067ee7c06c683bc8f602a68344e03e69f45d50 | 615,530 |
def get_processed_comment_sequence(comment_subtokens):
"""Returns sequence without tag string. Tag strings are excluded for evaluation purposes."""
if len(comment_subtokens) > 0 and comment_subtokens[0] in ['@param', '@return']:
return comment_subtokens[1:]
return comment_subtokens | 6e7b7894a4531f214907e95cde9d4b5ec85c812d | 615,538 |
import re
def find_and_replace(line, substitutions):
"""
Function performs find and replace on a string given a dictionary of
substitution criteria. (Designed to be a sed-like command that can replace
multiple strings in a single pass)
Parameters
----------
line : str
line of text... | 1bb62b3c87da467098fe8f5a5ca6acdfe62acdb9 | 615,541 |
import json
def create_json(fname, data):
""" Create JSON file
:param fname: Name of the file to be saved
:param data: Array or dictionary to be converted to JSON
"""
with open(fname, 'w') as outfile:
json.dump(data, outfile, indent=2, separators=(',', ': '))
return True | 05b8e4b47cadcdc4802c037133df0f4026a9dd48 | 615,542 |
def retrieve(result_queue, queue_size):
""" Retrieve results from a shared queue.
"""
results = []
while queue_size:
results.append(result_queue.get())
queue_size -= 1
return results | 7b51e1d80ed293cabc949acc6c60bae9275bf795 | 615,546 |
def validate_string(datum, **kwargs):
"""
Check that the data value is string
Parameters
----------
datum: Any
Data being validated
kwargs: Any
Unused kwargs
"""
return isinstance(datum, str) | 25b6d2d1dd5151cc60f4ae7e307023a000ca9d5a | 615,547 |
import re
def section_heads(value):
"""
Search through a block of text and replace <p><b>text</b></p>
with <h4 class="section-head">text</h4
"""
value = re.sub(r'<p>\w*<b>(.+?)</b>\w*</p>', u'<h4 class="section-head">\\1</h4>', value)
return value | ede2c66729b1b88f0bceb9f88bab92bc3113adbe | 615,548 |
def outer_subspace_product(subspace1: list, subspace2: list, reverse: bool = False) -> list:
"""
Forms the outer (cartesian) product of two subspaces which are both aligned
with the comp. basis.
:param subspace1: list, list containing the computational basis vectors which
spa... | 42125a265d3c142f951dbbdf12a02093a5f3b81e | 615,550 |
def denary2BinaryStr(n, l=8):
"""
Convert denary integer n to binary string bs, left pad to length l
"""
bs = ''
if n < 0: raise ValueError("must be a positive integer")
if n == 0: return '0'
while n > 0:
bs = str(n % 2) + bs
n = n >> 1
return bs.rjust(l,'0') | 4711171a7ce8687c05ac0a5659038fbce273fa93 | 615,554 |
def test_value_generator(total_rows, row_number, previous_row_values):
"""
test function for generating column values
Returns
_______
int
the row number plus the previous row value (or zero if it's the first)
"""
return row_number + len(previous_row_values) | e87858ea9c8807ae387f3a1977797ae1e3204324 | 615,555 |
import inspect
def cleandoc(docstring):
"""Clean documentation string (docstring) per PEP 257 rules.
Args:
docstring: supplied docstring.
Returns:
Clean docstring.
Note:
This is just a wrapper around ``inspect.cleandoc``.
"""
return inspect.cleandoc(docstring) | 0786c137beeadcbfe54d8198fa00eee1da1b15ed | 615,556 |
def get_data_from_films_locations_file(path):
"""
Return data with location and year of every film in file
(str) -> dict
ex. dict1['2020'] = {location1: {film1, ...}, location2: {film2, ...}}
"""
film_locations_data = {}
with open(path, encoding='utf-8', errors='ignore') as f:
for l... | 08d185c84fcad20c39ace8da44b67749b059aeaf | 615,558 |
def str_to_nat(s):
"""Convert string to natural number."""
return ord(s) - ord("a") | b20aec44887c9d9393690528967ab799d9898d1e | 615,563 |
def check_deps(sent):
"""
Checks that each dependency link refer to an existing word id
Args: list of tuples (ln, word objs)
Return: list of tuples (ln, word objs) with false head
"""
headless_words = []
ids = [word.nid for ln, word in sent]
for ln, word in sent:
# on zappe les c... | 827ca5e5dff0cf23fd51cc9b4017dd8ca50620a0 | 615,567 |
def get_activating_points(trace, rcon_alpha):
"""
Returns a list of time instances where the trace is activated by RCon ⍺
:param trace: One trace (a list of states in time)
:param rcon_alpha: A proposition indicating the ⍺ of the RCon
:return: a list of time instances where the trace is activated
... | ab6136e4cb1223f94c233d87f46fa3f67e94bdc8 | 615,569 |
import hashlib
def create_hash(text):
"""
Runs hashing function from hashlib
:param text: text to hash
:return: hash value of text
"""
return hashlib.sha256(text.encode('utf-8')).hexdigest() | d2134fc6d1099ab1650b493ee195becc024c6b36 | 615,570 |
def get_patch_values(patch, path):
"""Get the patch values corresponding to the specified path.
If there are multiple values specified for the same path
(for example the patch is [{'op': 'add', 'path': '/name', 'value': 'abc'},
{'op': 'add', 'path': '/name', 'value': 'bca'}])... | 50ced52dab4d3a5d396ad6f8ab0dd559d574daf9 | 615,572 |
def freq(a=0):
""" Processor frequency """
return 240*1000000 | f1c614c9e1b40c11f1bcb5f4c2e3e030564cac79 | 615,573 |
def risk_genes(disorder=None):
"""Outputs names of GWAS-derived risk genes for a given disorder (author: @saratheriver)
Parameters
----------
disorder : {'adhd', 'asd', 'bipolar', 'depression', 'epilepsy', 'hippocampal_volume', 'ocd', 'schizophrenia', 'tourette'}
Name of disorde... | 8fdfc873981c1a2c4249c7d2e5b68905e69a8f58 | 615,577 |
from typing import Callable
from typing import Mapping
from typing import Any
import inspect
def _invoke(f: Callable, kwargs: Mapping[str, Any]) -> Any:
"""
Invoke the given function with a given dictionary of keyword arguments, silently ignoring any extra arguments.
"""
signature = inspect.signature(... | 1b54b9dc84f3054b0613570fd76f28adaefa11fa | 615,578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.