content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def init_console(parser):
"""Initialises the console"""
font = pygame.font.SysFont("Courier", 12)
text = Text(font, size=(200, 40), position=(0, 0))
error_text = init_error_message(parser)
return Console(parser, text, error_text) | 8f387f83fca2fbe25283dc62c3c6ed50ec24ebd3 | 3,626,048 |
import _datetime
def seconds_function(context, string=None):
"""
The date:seconds function returns the number of seconds specified by the
argument string. If no argument is given, then the current local
date/time, as returned by date:date-time is used as a default argument.
Implements version 1.
... | 8d9d1d5d6cd9d5261746ca14257bf8c2e0dc9886 | 3,626,052 |
def mean_of_cluster(list_of_points):
"""Calculates the center of the list of points
"""
number_of_points = float(len(list_of_points))
vector_total = [float(0), float(0)]
for point in list_of_points:
for index, component in enumerate(point):
vector_total[index] += component
re... | b94b5ea40fb08253bcade35282692bbb58b85e98 | 3,626,053 |
def symlog(values, threshold):
"""
Convert values to log with linear threshold near zero
"""
return np.sign(values) * np.log10(1 + np.abs(values) / threshold) | f0bcd06326eedc7a2dd65b239b2ad81499ae2d68 | 3,626,054 |
def cluster_by_best_antecedent(document, predictions, threshold=0.5):
"""
Clusters the document's mentions by matching each with its best antecedent
with a score above the 0.5 threshold.
@arg predictions Mention-pair predictions.
@arg threshold The classification threshold, above this value mention... | a4c3db4ae799047340c2cfcfa4f21d7414797a86 | 3,626,055 |
def max_pooling(x, pool_h, pool_w, stride):
"""Max pooling."""
validator.check_integer("stride", stride, 0, Rel.GT, None)
num, channel, height, width = x.shape
out_h = (height - pool_h)//stride + 1
out_w = (width - pool_w)//stride + 1
col = im2col(x, pool_h, pool_w, stride)
col = col.reshap... | c427c2ecd555ce48d73aa989ccfd4595d84ef36d | 3,626,056 |
def get_unique_pairs(pairs, return_indices=False) -> np.array:
"""Extract unique pairs."""
# idx: Indices in triples of unique pairs
_, idx = np.unique(pairs, return_index=True, axis=0)
sorted_indices = np.sort(idx)
# uniquoe pairs where original order of triples is preserved
unique_pairs = pai... | 3f8c6408d9a6f871e7f89278448dcaa1b5028c12 | 3,626,058 |
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, vocab, world_size=None):
"""Train/eval Data preparation function."""
label_dtype = 'int32' if task.class_labels else 'float32'
truncate_length = max_len - 3 if task.is_pair else max_len - 2
trans = partial(convert_examples_to_feat... | 8ee375a58d8a827f3ab09658bf3d3927696c303b | 3,626,059 |
def revSequence(channels, n_block):
"""Make a sequence of multiple reversible block
Arguments:
channels {[int]} -- [number of channels fixed]
n_block {[int]} -- [Number of blocks]
Returns:
[nn.Module] -- [The reversible sequence]
"""
sequence = []
for i in range(n_block):
sequence.append(revBlock(chan... | cd145bb5901b2e389a5fa772e3e08abba44b227d | 3,626,060 |
def calculate_angle(v1, v2):
"""
Calculate the angle ([0, Pi]) between two vectors according to:
p = u * v = |u||v|cos(a)
Parameters
----------
v1 : arr
v2 : arr
Returns
-------
angle : float
The angle ([0, Pi]) between these two given vectors
"""
product = np... | 9c50fe95f15ff2a6dc41d9c30f792e8aee27d831 | 3,626,061 |
def range_overlap(a_min, a_max, b_min, b_max):
"""
Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max) | c05d8b0799f62300760ad69704a5091c3830ad26 | 3,626,062 |
def flip_errors(data):
"""Flip sign for lower boundary responses.
:Arguments:
data : numpy.recarray
Input array with at least one column named 'RT' and one named 'response'
:Returns:
data : numpy.recarray
Input array with RTs sign flipped wher... | 2ae325534658c055ff4d0cb841de696875a46aa6 | 3,626,063 |
from datetime import datetime
import ipaddress
import socket
from operator import or_
def is_clone(nickname, hostmask, withdate=False):
"""
Checks whether a nickname is considered a clone by the bot.
:param withdate: Whether to return a tuple containing both matches and the last timestamp of connection
... | 8d7ee5d6a39e8fdb356f61d7e3890a9f34e3b4ca | 3,626,065 |
import logging
import copy
def test_online_reads_checkpoint():
"""Test that online analysis reads the checkpoint correctly in all cases"""
current_log_level = logger.level
logger.setLevel(logging.ERROR) # Temporarily suppress some of the logging output
raw_template_script = get_template_script()
... | 0a89f8bccbb7f278c7d236834518fc45b28236bb | 3,626,066 |
def preview(df,preview_rows,preview_max_cols):
""" Returns a preview of a dataframe, which contains both header
rows and tail rows.
"""
assert type(df) is pd.DataFrame
if preview_rows <= 0:
preview_rows = 1
initial_max_cols = pd.get_option('display.max_columns')
pd.set_option('displa... | 10a6ee5c59de16cf9ff11bcb739afa8cdc8bf462 | 3,626,067 |
import json
def read_json(json_file_path: str) -> dict:
"""Takes a JSON file and returns a dictionary"""
with open(json_file_path, "r") as fp:
data = json.load(fp)
return data | 07cb6c606de83b2b51ddcbf64f7eb45d6907f973 | 3,626,068 |
def _log10_cumulative_shmf(logmp, y0, m, xc, x0, kc, dy):
"""Differentiable kernel of the cumulative subhalo mass function."""
y = y0 + m * (logmp - x0)
return _jax_sigmoid(logmp, xc, kc, y, y - dy) | cb82fb8d6d0cffbfe6553c9e11b4ff006ab24583 | 3,626,069 |
def internal_token_encoder() -> TokenEncoder[InternalToken]:
"""Return InternalToken encoder with correct secret embedded."""
return TokenEncoder(
schema=InternalToken,
secret=INTERNAL_TOKEN_SECRET,
) | e9239e81dfa0f385f02387886a52399d2093fd94 | 3,626,070 |
def index(request):
"""
Serve view for home page
"""
return render(request, "index.html") | ddcafaf5312f7c811f4aacbb3fcb6285e9b6ab22 | 3,626,073 |
from typing import Tuple
def _get_property_types(layer: Layer) -> Tuple[str, ...]:
"""Given a GDAL Layer, return the non-geometry field types."""
layer_definition = layer.GetLayerDefn()
type_codes = tuple(
layer_definition.GetFieldDefn(index).GetType()
for index in range(layer_definition.G... | 54377e5fb50b7c6953a3cf863bbaa8bf3831b0e5 | 3,626,075 |
def TInt_GetKiloStr(*args):
"""
TInt_GetKiloStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetKiloStr(*args) | b2a0582548d86dcf3eb9e3b489776116ae9d68bc | 3,626,076 |
def linear(x, n_units, scope=None, stddev=0.02,
activation=lambda x: x):
"""Fully-connected network.
Parameters
----------
x : Tensor
Input tensor to the network.
n_units : int
Number of units to connect to.
scope : str, optional
Variable scope to use.
stdd... | e0b2a70f6480dae16e384ceab6aabfc21daaa5ca | 3,626,077 |
def RadialSymmetryFunction(R, rc, rs, e):
"""Calculates radial symmetry function.
B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_filters
Parameters
----------
R: tf.Tensor of shape (B, N, M)
Distance matrix.
rc: float
Interaction cutoff [Angstrom].
rs: float
Gaussian dista... | 7f6dc67d6f7c1d490d116528c14ca90f2b732d8d | 3,626,078 |
def plot_curve(axis, params, train_column, valid_column, linewidth = 2, train_linestyle = "b-", valid_linestyle = "g-"):
"""
Plots a pair of validation and training curves on a single plot.
"""
model_history = np.load(Paths(params).train_history_path + ".npz")
train_values = model_history[train_colu... | 2efcf1a780091ae2ce2025555aeb270d20dc07e9 | 3,626,079 |
from typing import Optional
from typing import Dict
def set_magmoms(
atoms: Atoms,
elemental_mags_dict: Optional[Dict] = None,
copy_magmoms: bool = True,
mag_default: Optional[float] = 1.0,
mag_cutoff: float = 0.05,
) -> Atoms:
"""
Sets the initial magnetic moments in the Atoms object.
... | 80aee80bb737963247dfdd8ff2e223dbe3c9b971 | 3,626,080 |
def round_list(x, digits=6):
"""helper for approximate tests, round a list"""
if isinstance(x, csr_matrix):
x = sparse_to_dense(x)
return [round(_, digits) for _ in list(x)] | ff61b1266bf6bfc5618aed13af125a64333d1457 | 3,626,081 |
def iter_to_table(value):
"""Convert raw API responses to response tables."""
if isinstance(value, list):
return _format_list(value)
if isinstance(value, dict):
return _format_dict(value)
return value | a4d12f677e425330368218f050d2a83d9d459a4f | 3,626,082 |
def get_last_line(fn):
"""Returns the last line of a file
Args:
fn (str): File name of the file to read from
"""
with open(fn, 'r') as fin:
for line in fin:
pass
return line | 40867816657af6350aa400ab17d60b816566d5c5 | 3,626,083 |
def _gen_tinynet(variant_cfg, channel_multiplier=1.0, depth_multiplier=1.0, depth_trunc='round', pretrained=False, **kwargs):
"""Creates a TinyNet model.
"""
arch_def = [
['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'],
['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'... | 4836e4fbacb36af927b8ad6b81084cbd769111d3 | 3,626,084 |
from typing import OrderedDict
def full_sdssmatch(img1,img2,inst,gmaglim=19):
"""
This function requires two stacked images, one each filter that will be used
in solving the color equations. The purpose of this function is to first
collect all of the SDSS sources in a given field using the
``odi.s... | b8640db90998eda702709dff33130a84301891d6 | 3,626,085 |
def calcula_menor_caminho(nome, origem, destino):
"""Retorna o menor caminho entre os dois pontos."""
mapa = Mapa()
rotas = Rota.objects.filter(nome=nome)
for rota in rotas:
mapa.add_ponto(rota.origem)
mapa.add_rota(rota.origem,
rota.destino,
... | 44000464ec156c5a0abc5e93c91564921aa827ba | 3,626,086 |
import re
def HasServices(proto_path):
"""Does a .proto file have any service definitions?
Args:
proto_path: path to .proto.
Returns:
True iff there are service definitions in the .proto at proto_path.
"""
with open(proto_path, 'r', encoding='utf8') as f:
for line in f:
if re.match(SERVI... | e8393a0ec23dece420d7074df122adf52fe142f6 | 3,626,089 |
import posixpath
import requests
def _remote_file_size(url=None, file_name=None, pn_dir=None):
"""
Get the remote file size in bytes.
Parameters
----------
url : str, optional
The full url of the file. Use this option to explicitly
state the full url.
file_name : str, optional... | 62d478f3620dd5532e9ee5657946afbce1d233b2 | 3,626,090 |
import random
import tqdm
import torch
def estimate_compression(model, data, nsamples, context, batch_size, verbose=False):
"""
Estimates the compression by sampling random subsequences instead of predicting all characters.
NB: This doesn't work for GPT-2 style models with super-character tokenization, s... | 700e13925d7781f383c3470cd273be1d83acdab5 | 3,626,091 |
def filter_by_distance(points, mindist=4):
"""Evaluate the distance between each pair os points in @points
and return just the ones with distance gt @mindist
Args:
points(set of tuples): set of positions
mindist(int): minimum distance
Returns:
set: set of points with a minimum distance be... | 1fe33da983fee9bab2fcde533191d93180cdb01e | 3,626,093 |
def read_point_cloud_log(path: str, row_size: int, double_precision: bool = True) -> np.ndarray:
"""Reads a .pcl file and containing x, y, z values specifying a point cloud."""
with open(path, 'rb') as f:
data_type = np.double if double_precision else np.single
data = np.fromfile(f, data_type)
... | a63eb568a73f803bbb194fbd67f8759fe0b21c73 | 3,626,094 |
def HLRBRep_CurveTool_Parabola(*args):
"""
:param C:
:type C: Standard_Address
:rtype: gp_Parab2d
"""
return _HLRBRep.HLRBRep_CurveTool_Parabola(*args) | 557fd2b10fd86db72d443fcd1f534a2496d232bc | 3,626,095 |
import uuid
def unique_variable_name():
"""Creates a unique variable name. Useful when attempting to introduce
a new token to see if it can fix specific cases of SyntaxError."""
name = uuid.uuid4()
return "_%s" % name.hex | d4b54a8ab76fa8bddd6fe62a735f1dd886e9e62a | 3,626,096 |
def impersonated_session_status(request):
"""
Adds variable to all contexts
:param request:
:return bool:
"""
return {"is_impersonated_session": is_impersonated_session(request)} | 2499946653a2cb411fbe7e2b389f72c08fcec92d | 3,626,097 |
def random_dates(start, end, size):
"""
Generate random dates within range between start and end.
Adapted from: https://stackoverflow.com/a/50668285
"""
# Unix timestamp is in nanoseconds by default, so divide it by
# 24*60*60*10**9 to convert to days.
divide_by = 24 * 60 * 60 * 10**9
st... | 589b974b262d41f5903362fd62bfc506ed8ff40d | 3,626,098 |
def cleaner_unicode(string):
"""
Objective :
This method is used to clean the special characters from the report string and
place ascii characters in place of them
"""
if string is not None:
return string.encode('ascii', errors='backslashreplace')
else:
return string | f4e2c4b9fa7f4a644e409a5d429531a34bc1c6c2 | 3,626,099 |
def transform_stamped_to_pq(msg):
"""Convert a C{geometry_msgs/TransformStamped} into position/quaternion np arrays
@param msg: ROS message to be converted
@return:
- p: position as a np.array
- q: quaternion as a numpy array (order = [x,y,z,w])
"""
return transform_to_pq(msg.transform) | 345946e47993972dc11bd017b663f07bf874b238 | 3,626,100 |
def parse_args():
"""Parsing command line arguments. """
parser = ArgumentParser()
parser.add_argument('--postgres-pass', dest='postgres_pass', type=str,
help='PostgreSQL user password', default='')
parser.add_argument('--postgres-user', dest='postgres_user', type=str,
... | 4305830ffaecb546936b88e768dc79722cc6f054 | 3,626,101 |
from typing import OrderedDict
def recursive_module_dict(model: nn.Module) -> OrderedDict:
"""Recursively generates an OrderedDict representing the module structure in a nn.Module.
:param model: The (sub-)module for which to generate the structure
:type model: torch.nn.Module
:return: Structure of th... | 061f29b55582147d07822d64ef23ba1f5e519efa | 3,626,103 |
from cntk.ops.cntk1 import ReduceMin
def reduce_min(value, axis=0, name=None):
"""
For axis < rank computes the minimum of a tensor along the specifed axis. In the result the corresponding axis is dropped, i.e. the rank of the result tensore is smaller that the rank of the input tensor.
if axis==rank, the... | f25f106b4b9ae18e33ff580464ca782201ac6f28 | 3,626,104 |
def sparse_js_distance(p, q):
"""Compute the Jensen-Shannon distance between two discrete distributions.
NOTE: JS divergence is not a metric but the sqrt of JS divergence is a
metric and is called the JS distance.
Parameters
----------
p : np.array
probability mass array (sums to 1)
... | 7b05f567594a8cfcc3907006569fe73ede153343 | 3,626,105 |
def key_or_none(value):
"""
Attempts to parse a value into an instance of an `ndb.Key`.
:returns: None if value cannot be converted to an `ndb.Key`.
"""
if not value:
return None
if isinstance(value, str) and len(value) < 1:
return None
return ndb.Key(urlsafe=value) | 60480c7841cd87c762bb3debb0e212eb0011c0d3 | 3,626,106 |
def get_training_dataset(workspace, class_count, vocab, max_chapter_len=50, max_para_len=50):
"""
Get the GB h2 chapter training dataset.
:param workspace: The workspace directory where the TFRecords are kept.
:param class_count: The number of classes to be classified.
:param vocab: the set of vocab... | 14d135dde973f155ee0f5883297f5c2a376ba61a | 3,626,107 |
def get_https_host(request):
"""Common enabler code for returning https urls
This is to map links to HTTPS to avoid Mixed Content warnings from Chrome browsers
SECURE_PROXY_SSL_HEADER is referenced because it is used in redirecting URLs - if
it is changed it may affect this code.
Using relative lin... | f48445ae0fd12c81b175543c4445f11155302f75 | 3,626,108 |
from typing import Callable
def start(action: QueryAction) -> Callable:
"""Initialize the query for a given action, ensuring no action has started."""
def wrapper(fn):
def wrapped(self, *args, **kwargs):
if self._action != QueryAction.unset:
raise BuildError(f"query alread... | 2d9d2e92803405ae40758b1b1c28ac7275ff7b5b | 3,626,109 |
def xtea_decrypt_all(data, key, endian="!"):
"""Decrypt a entire string using XTEA block cypher"""
newdata = ''
data_s = len(data)
data_p = data_s%8
if data_p:
data_pl = 8-data_p
data+=(data_pl*chr(0))
data_s+=data_pl
for i in xrange(data_s/8):
block = data[i*8:(i*8)+8]
newdata+=xtea_decrypt(block, key,... | 19fdfb1bdca3033bf7dd6d7a84641a936d32b7aa | 3,626,110 |
def enthalpy_Shomate(T, hCP):
"""
enthalpy_Shomate(T, hCP)
NIST vapor, liquid, and solid phases
heat capacity correlation
H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 +
1/4*D*t^4 - E*1/t + F - H
t (K) = T/1000.0
H_ref is enthalpy in kJ/mol at 298.15 K... | 05e3f3a35a87f767a44e2e1f4e35e768e12662f7 | 3,626,112 |
from typing import Union
from typing import List
import array
def hz_to_mel(frequencies: Union[float, List[float], array],
htk: bool = False) -> array:
"""Convert Hz to Mels
This function is aligned with librosa.
"""
freq = np.asanyarray(frequencies)
if htk:
return 2595.0 *... | 16373a9358e4bbae3baef02567c80abc4ba48c83 | 3,626,113 |
def get_acres(grid, coordinates):
"""Get acres from coordinates on grid."""
acres = []
for row, column in coordinates:
if 0 <= row < len(grid) and 0 <= column < len(grid[0]):
acres.append(grid[row][column])
return acres | e4ba6aabe07d8859481aefaba4d4559f1ec25e96 | 3,626,116 |
def parse_noj():
"""
Parsing Nojabrsk (NOJ) airport arrivals and departure data
:return: list [list of dicts arrivals, list of dicts departures]
"""
print('parse_noj')
json_data = get_json(NOJ_URL).get('result').get('response').get('airport').get('pluginData').get('schedule')
arr_data = get... | 601ac9f1bc5d6f2fed4f08f8fb91e095bceadf7f | 3,626,118 |
def _filter_unlabeled_sentences(
characterwise_predicted_label_names_per_sentence, words_per_sentence,
unlabeled_sentence_filter):
"""Filters sentences without any predicted labels. Keeps every nth entry."""
sentences_without_label = 0
filtered_characterwise_predicted_label_names_per_sentenc... | a17a0dc3ba61ce542585cba31c87621f5a772e20 | 3,626,119 |
def highest_mag(slide):
"""Returns the highest magnification for the slide
"""
return int(slide.properties['aperio.AppMag']) | d42361c979a5addf0ebf4c7081a284c9bc0477ec | 3,626,120 |
def is_crud(crud):
"""Check if item is subclass of <GQL>"""
its_crud = False
try:
if not crud == GQL:
its_crud = issubclass(crud, GQL)
except TypeError:
pass
return its_crud | 2e817cdb0adaa880d7f027a4020ff490b76c5f56 | 3,626,121 |
def pegar_por_href(navegador, link):
"""Encontrar o elemento `a` com o link `link`.
Argumentos:
- browser = Instancia do browser [firefox, chrome, ...]
- link = link (ou parte dele) que será procurado em toda as tags `a`
"""
elementos = chrome.find_elements_by_tag_name('a')
for e... | 8c3ea4ebc42b03d61c79f6a6666b82d41cb36902 | 3,626,124 |
def import_txt(file_name, two_dimensional=False, **kwargs):
""" Reads control points from a text file and generates a 1-dimensional list of control points.
The following code examples illustrate importing different types of text files for curves and surfaces:
.. code-block:: python
:linenos:
... | 5b17f8fe85de759ad240b36544b4c9231afdcda9 | 3,626,125 |
def sizeAbove(resource, value):
"""
Check if the contentSize attribute of the <contentInstance> resource is
equal to or greater than the specified value.
:param resource:
:type resource:
:param value:
:type value:
:return:
:rtype:
"""
try:
return resource.contentSize ... | 50e92811c9c8ee13db615137f6d92c4a3edabfda | 3,626,126 |
import re
def enumerate_destination_file_name(destination_file_name):
"""
Append a * to the end of the provided destination file name.
Only used when query output is too big and Google returns an error
requesting multiple file names.
"""
if re.search(r'\.', destination_file_name):
dest... | 6b398597db26a175e305446ac39c363a5077ba96 | 3,626,128 |
def Flux_Quad(wpert, thetapert):
"""
Separates fluxes into quadrants
Arguments:
wpert -- array of w perturbations
thetapert -- array of theta perturbations
Returns:
[up_warm, down_warm, up_cold, down_cold] -- arrays, np.nans are fillers
"""
[rows, columnsx, columnsy] = ... | d1f6a278deb60507cd05ed367b0c6dd13704ad28 | 3,626,129 |
def demistoVersion():
"""Retrieves server version and build number
Returns:
dict: Objects contains server version and build number
"""
return {
'version': '5.5.0',
'buildNumber': '12345'
} | 39ef34f88f44ecfad9d30a80bcdb74ad1833c3ae | 3,626,130 |
def classification_metric(all_real, all_pred, all_prob):
""" Metric used for experiments
Args:
all_real (list): real labels (ground truth) with n values
all_pred (list): predictions for n predictions
all_prob (list or np.array): probabilities (confidence).
If it is ... | 69f03e92c298e951b56ec32fd268fe859d66927e | 3,626,131 |
def camel_to_human(s, lower=True):
"""
Converts camel case to 'human' case
Arguments:
----------
lower: bool (default: False)
Convert output to lower
"""
ret = start_of_camel.sub(r" \1", s).strip()
if lower:
ret = ret.lower()
return ret | c00c21f469bca03af484a8d9ada86bfa3ed7e6b7 | 3,626,132 |
import random
def dice_game ():
"""
Function for manage all the game.
@rtype: None
@return: Return None when the game is ended
"""
scores = { TypeOfPlayers.PLAYER: 0, TypeOfPlayers.COMPUTER: 0 }
who_play = TypeOfPlayers.COMPUTER
while not game_is_ended(scores):
print('------------------... | d5940ac0d2c4aec3ba225b72e30de4da443080df | 3,626,133 |
def edit_affiliations(request, affiliation_formset):
"""
Edit affiliation information
Helper function for `project_authors`.
"""
if affiliation_formset.is_valid():
affiliation_formset.save()
messages.success(request, 'Your author affiliations have been updated')
return True
... | 04cfddd8be2299531d27baf8cb74c909ef40da19 | 3,626,135 |
import json
def tojson(x):
"""
python2/3 compatible conversion to json string
"""
return tobytes(json.dumps(x)) | 94ec37a5c5a22516369d69a4b60f63c4196cb329 | 3,626,136 |
def prob_remap_bcg(upid, host_halo_mass,
mhalo_table=(13.5, 13.75, 14, 15), prob_table=(0, 0.1, 0.5, 1)):
"""
"""
ngals = len(upid)
prob_remap = np.interp(np.log10(host_halo_mass), mhalo_table, prob_table)
uran = np.random.rand(ngals)
uran[upid != -1] = 1.0
return uran < prob_re... | 0e2c4bdd6f57e9f751b80a8ac366737d2756ae4c | 3,626,137 |
from typing import List
import requests
import json
def retrieve_all_plans() -> List[str]:
"""Return the names of all plans stored in the plan engine."""
url = _plan()
response = requests.get(url=url)
_raise_for_status(response)
plans: List[str] = json.loads(response.text)
return plans | e915cf64f5e17fca6ac0fcf17b3f2b68b2fb615a | 3,626,139 |
from typing import List
def load_task_names(path: str) -> List[str]:
"""
Loads the task names a model was trained with.
:param path: Path where model checkpoint is saved.
:return: A list of the task names that the model was trained with.
"""
return load_args(path).task_names | b9feb1e91d3449bbc98aa376a60ba40ac7d440b2 | 3,626,140 |
def sample_seq2seq(news_config: LMConfig, initial_context, eos_token, ignore_ids=None, p_for_topp=0.95,
do_topk=False, max_len=1025):
"""
Sample multiple outputs for a model in a seq2seq way.
:param news_config: Configuration used to construct the model
:param initial_context: [batch... | a9e5d3beb052acbb9cd8b753df5975ac319fac34 | 3,626,141 |
def unquote_plus(s):
"""unquote('%7e/abc+def') -> '~/abc def'"""
s = s.replace('+', ' ')
return unquote(s) | 2ffe054ae8fbec96d6435e242bf88ec7c871270e | 3,626,142 |
def _rankf(x):
""" Return an integer valuation of float32 x """
shift = int32(31)
mask = int32((1 << 31) - 1)
i32 = x.view(int32)
value = i32 >> shift
value &= mask
value ^= i32
return value | 841d49acd08b39dba716b6c41bdb3316208a9c43 | 3,626,143 |
from typing import List
def reorder_tables(openapi_yaml: sy.YAML) -> List[sy.Str]:
"""Orders the tables so no table references another table that might be defined after.
Parameters
----------
openapi_yaml
Contains the openapi format describing the database schema
Returns
-------
t... | a16f496effe1b52a685c8d82a7f85a3ecc6282e7 | 3,626,145 |
def video_feed():
"""
Video streaming route. Put this in the src attribute of an
img tag.
"""
txt = 'multipart/x-mixed-replace; boundary=frame'
# WS added passing a message to the Camera class
return Response(gen(Camera(message=msg)), mimetype=txt) | e5626cf86617beecd54afe173eb052629cd58179 | 3,626,146 |
def bias_act(x, b=None, dim=1, gain=None, clamp=None):
"""Slow reference implementation of `bias_act()`
"""
# spec = activation_funcs[act]
# alpha = float(alpha if alpha is not None else 0)
gain = float(gain if gain is not None else 1)
clamp = float(clamp if clamp is not None else -1)
# Add... | 3e98d5941d29c78ecd5c46c9ec960f14cedc36e9 | 3,626,147 |
import click
import io
import yaml
def init():
"""Return top level command handler."""
ctx = {}
@click.group()
@click.option('--cell', required=True,
envvar='TREADMILL_CELL',
callback=cli.handle_context_opt,
expose_value=False)
@click.option(... | b19e0b358f2b1288aeda6c963240de4f0369d187 | 3,626,148 |
def process_json_file(file_name, grounding_ns=None, extract_filter=None,
grounding_mode=default_grounding_mode):
"""Return an EidosProcessor by processing the given Eidos JSON-LD file.
This function is useful if the output from Eidos is saved as a file and
needs to be processed.
... | e8dedc0adad8e1e22199e6c6b83c3489f20c0570 | 3,626,149 |
def accumulate_ip_for_certificate(value):
"""
A convenience function that wraps the results of 'search_ip_for_certificate' into a Python list.
:param value: The certificate value for which to search
:return: The list of IP addresses
:raises LookupException: If there was an error performing the look... | 80664c1111bb113237247a7b35e4dafb60fdd4f5 | 3,626,150 |
def combine_envs(*envs):
"""Combine zero or more dictionaries containing environment variables.
Environment variables later from dictionaries later in the list take
priority over those earlier in the list. For variables ending with
``PATH``, we prepend (and add a colon) rather than overwriting.
If... | feb6e00b9c0b1262220339feac6c5ac2ae6b6b17 | 3,626,151 |
import logging
def get_request_data() -> dict:
"""
Get keys & values from request.
(Note that this method parse requests with
content type "application/x-www-form-urlencoded")
"""
data = dict(request.values)
logging.info(f"received request: {data}")
return data | 0f3b2a104d0282a6846031ed84e68af1e91071ac | 3,626,152 |
import torch
def generate_square_subsequent_mask(sz):
"""
Generate attention mask using triu (triangle) attention
"""
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = (
mask.float()
.masked_fill(mask == 0, float("-inf"))
.masked_fill(mask == 1, float(0.0)... | 5631e89a275eee13c4b01a7b856421f6b45c2588 | 3,626,153 |
def tree_graph(data, attrs=_attrs):
"""Return graph from tree data format.
Parameters
----------
data : dict
Tree formatted graph data
Returns
-------
G : NetworkX OrderedDiGraph
attrs : dict
A dictionary that contains two keys 'id' and 'children'. The
correspo... | 2cc012b7ffc32f1bd0ac5db0ac5bd912dec81c75 | 3,626,154 |
def retry_on_mysql_lock_fail(metric=None, metric_tags=None):
"""Function decorator to backoff and retry on MySQL lock failures.
This handles these MySQL errors:
* (1205) Lock wait timeout exceeded
* (1213) Deadlock when trying to get lock
In both cases, restarting the transaction may work.
It... | 91c2d82401677e6cdab1d4131a9f02be26cbbbf8 | 3,626,155 |
from datetime import datetime
def eot(date: datetime.date, offset: int = 0) -> datetime.date:
"""
Returns the end of the calendar trimester, i.e. one of
30 April, 31 August or 31 December, then optionally offsets it
by :code:`offset` trimesters
Parameters
----------
date : datetime.date... | 5594d60c7e5ebe8c1f2686f6b8eb68f89ddb0987 | 3,626,156 |
def generate_activation_url(token_name: str, token_value: str) -> str:
"""
Generates url with token_name=token_value embedded in it.
:param token_name:
:param token_value:
:return:
"""
return Config.FRONT_END_URL + "?" + f"{token_name}={token_value}" | db58a3d4b55276229486dbddb86ea51383393a10 | 3,626,157 |
import struct
def native_type_range(fmt):
"""Return range of a native type."""
if fmt == 'c':
lh = (0, 256)
elif fmt == '?':
lh = (0, 2)
elif fmt == 'f':
lh = (-(1<<63), 1<<63)
elif fmt == 'd':
lh = (-(1<<1023), 1<<1023)
else:
for exp in (128, 127, 64, 6... | dc8362aadece611b45b05f775cd0a95eefabcad7 | 3,626,158 |
def get_action(affordance_map, epsilon, open_scales):
"""Get action based on affordance_map.
Args:
affordance_map: [S, K, W, H]
epsilon: random aciton based on prob VS choose best aciton. If epsilon < 0: get action with best score
open_scales: list of open_scales [S]
Returns:
... | df34e426ba85198bd84f81046969b92dec9013a8 | 3,626,159 |
def drop_shadow(image, offset=(5, 5), background=0xffffff, shadow=0x444444,
border=8, iterations=5):
"""
Add a gaussian blur drop shadow to an image.
image - The image to overlay on top of the shadow.
offset - Offset of the shadow from the image as an (x,y) tuple. Can be
... | f8bb75d7e648144bf351527f43c74c801e1a7120 | 3,626,160 |
import random
import tqdm
def get_s_test(z_test_grad, z_losses, params, damp=0.01, scale=25.0, recursion_depth=20000, threshold=1e-8):
"""s_test can be precomputed for each test point of interest, and then
multiplied with grad_z to get the desired value for each training point.
Here, strochastic estimatio... | cdf460d305ade66cc106f53ca0b7bd687c1dcf3e | 3,626,161 |
def to_fft_image(fft_mat, is_shift=False):
"""Convert frequency matrix to visual image"""
if is_shift:
fft_mat = np.fft.fftshift(fft_mat)
log_mat = 20*np.log(np.abs(fft_mat))
return np.uint8(np.around(log_mat)) | f1bd9c50879a32a0624db62587463a94e3cbbd09 | 3,626,162 |
def np_normal(shape, random_state, scale=0.01):
"""
Builds a numpy variable filled with normal random values
Parameters
----------
shape, tuple of ints or tuple of tuples
shape of values to initialize
tuple of ints should be single shape
tuple of tuples is primarily for conv... | b12b82602d2d465195f0576bdb29446a6a7b9331 | 3,626,163 |
from typing import Optional
from typing import Callable
from typing import Awaitable
def head(
path: str, /, *, name: Optional[str] = None, include_in_schema: bool = True
) -> Callable[[Callable[[Request], Awaitable[Response]]], Route]:
"""decorator to create a Starlette Route for HEAD requests from an endpoi... | 162ea8d05926e3fad6a285ff8b6db86efb800bd5 | 3,626,164 |
def api_hash_key(*args, **kwargs):
"""参考cachetools hashkey实现,对WSGIRequest参数对象进行特殊处理"""
new_args, _ = deal_request_args(False, *args)
return hashkey(*new_args, **kwargs) | 15527ebd43b809d27919aec1648aa24802d61826 | 3,626,165 |
def len_column(table):
"""
Add length column containing the length of the original entry in the seq column.
Insert a number column with numbered entries for each row.
"""
for pos, i in enumerate(table):
i.insert(0, pos)
i.append(len(i[1]))
return table | 5a9215bc2feade70873de6adccd2b4c4b6acfed9 | 3,626,166 |
def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None):
"""Binary roc auc score"""
if len(np.unique(y_true)) != 2:
raise ValueError("Only one class present in y_true. ROC AUC score "
"is not defined in that case.")
fpr, tpr, _ = roc_curve(y_true, y_sco... | a21058fb927fb5dfa9d727eaa5f8251ebc9a0c5e | 3,626,167 |
import logging
def build_service_set(gtfs_data):
"""Based on the calendar, figure out which service IDs should run for
each date"""
# The master dict of days
# Keys are the dates, the values are a list of service IDs that run for
# that day
service_days = {}
# Loop through each service ID... | 16bab43dd5607e94e4775428b87fb7836fe6ec13 | 3,626,168 |
def manage_org_users(request):
"""
View to manage the users of an organisation
Should only be accessed by admin users of the organisation
"""
if request.user.is_org_admin:
context_dict = {}
context_dict['organisation_users'] = request.user.organisation.get_users()
context_dic... | def1899fc8c6afb50166361ec80b7355a71f2773 | 3,626,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.