content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calc_overlap(row):
"""
Calculates the overlap between prediction and
ground truth and overlap percentages used for determining
true positives.
"""
set_pred = set(row.predictionstring_pred.split(' '))
set_gt = set(row.predictionstring_gt.split(' '))
# Length of each and intersection
... | 98e65250f82ab13b23de049fd80a59dea30ccce2 | 3,635,000 |
def delete_all():
""" Clear the config list """
def check_path(folder=None):
""" Check if the folder exist and return boolean """
return isdir(folder._fullpath)
# Clear the config list:
kill_list = [elem for elem in config['Elements'] if elem._hide == 0 or check_path(elem) == 0]
if... | a4c1359ee272a3f5fd7edd58913baf90ad15bd84 | 3,635,001 |
def get_range(l_list,l_position):
""" Obtaining range of points in list (optionally at position inside of list)"""
l_range = 0
l_abs_range = 0
l_max = 0
l_min = 0
ll_list = []
counter = 0
if l_position == None:
ll_list = l_list
else:
while counter < len(l_list)... | a98b1d12cd37545b5cb1932cfe273222d9c5e4c0 | 3,635,002 |
def equalise_paragraphs(a_para, b_para, sentence_ratio=DEFAULT_SENTENCE_RATIO, lowercase_glued=DEFAULT_LOWERCASE_GLUED,
stop_chars=DEFAULT_STOP_CHARS):
"""
Glues together two collections of sentences so that they're of similar
word-length. Discards sentences it cannot make parallel.
... | c77a0c066dc0e7a6fad978563d2eb7caad15825a | 3,635,003 |
def build_summary_rendering_context(schema_json, answer_store, metadata):
"""
Build questionnaire summary context containing metadata and content from the answers of the questionnaire
:param schema_json: schema of the current questionnaire
:param answer_store: all of the answers to the questionnaire
... | b59b6ffb10a7383d7168b127bf8931f16ca7dc5a | 3,635,004 |
def _bucket_from_workspace_name(wname):
"""Try to assert the bucket name from the workspace name.
E.g. it will answer www.bazel.build if the workspace name is build_bazel_www.
Args:
wname: workspace name
Returns:
the guessed name of the bucket for this workspace.
"""
revlist = [... | 4cf3f4505a894f63258846abbe41b3b787485d40 | 3,635,005 |
def load_results_with_table_definition(
result_files, table_definition, table_definition_file, options
):
"""
Load results from given files with column definitions taken from a table-definition file.
@return: a list of RunSetResult objects
"""
columns = extract_columns_from_table_definition_file... | 4bbe743774b74abbe8c9d4d6af6669cd819c9cba | 3,635,006 |
def CIFAR10(flatten=True, split=[1.0, 0.0, 0.0]):
"""Returns the CIFAR10 dataset.
Parameters
----------
flatten : bool, optional
Convert the 3 x 32 x 32 pixels to a single vector
split : list, optional
Description
Returns
-------
cifar : Dataset
Description
... | 8af9997f5c530ac2aae9d680235007b3de289d96 | 3,635,007 |
def _cut_daytime(visi, tmstp):
"""Returns visibilities with night time only.
Returns an array if a single night is present.
Returns a list of arrays if multiple nights are present.
"""
tstp = tmstp[1] - tmstp[0] # Get time step
risings = ch_eph.solar_rising(tmstp[0], tmstp[-1])
settings =... | f6a3164af732949807f5f3f8c810f5072ab19a6d | 3,635,008 |
def decay(epoch):
""" This method create the alpha"""
# returning a very small constant learning rate
return 0.001 / (1 + 1 * 30) | b3311fe38557ee18d0e72ce794a3123b04b92c7a | 3,635,009 |
import functools
import time
def timer_function(function):
"""Print time taken to execute a function"""
@functools.wraps(function)
def inner_function(name):
start = time.perf_counter()
function(name)
end = time.perf_counter()
total = end-start
print(start, end)
... | 82981c28e9401581d38c1eed6b4efab30679cec8 | 3,635,010 |
def blob_delete(cache, key, namespace):
# type: (Any, str, Optional[str]) -> bool
"""Delete stored values from memcache"""
chunk_keys = blob_get_chunk_keys(cache, key, namespace=namespace)
if not chunk_keys:
# Keys are not set, no need to remove them.
return True
keys_to_delete = list(chunk_keys)
... | d2eaa38ead9e89461341c4a5df7062d723f5e62e | 3,635,011 |
def shape_equality_robust_statistic(𝐗, args):
""" GLRT test for testing a change in the shape of
a deterministic SIRV model.
Inputs:
* 𝐗 = a (p, N, T) numpy array with:
* p = dimension of vectors
* N = number of Samples at each date
* T ... | c5f9f967e9f9bdbf314dde3d90dbe812b7dad565 | 3,635,012 |
def get_attrib_uri(json_dict, attrib):
""" Get the URI for an attribute.
"""
url = None
if type(json_dict[attrib]) == str:
url = json_dict[attrib]
elif type(json_dict[attrib]) == dict:
if json_dict[attrib].get('id', False):
url = json_dict[attrib]['id']
elif json... | 838b698e3475ebdc877b29de6f3fd446d2be1cdf | 3,635,013 |
def set_model_params(module, params_list, start_param_idx=0):
""" Set params list into model recursively
"""
param_idx = start_param_idx
for name, param in module._parameters.items():
module._parameters[name] = params_list[param_idx]
param_idx += 1
for name, child in module._module... | 7ce6edb0c1b83020280cf0b586623d66839b4b0a | 3,635,014 |
import os
import logging
import stat
def push(local_path, remote_path):
"""Upload a file to the device.
Arguments:
local_path(str): Path to the local file to push.
remote_path(str): Path or directory to store the file on the device.
Returns:
Remote path of the file.
Example:... | b9f7980a78fdc0d4a68e652212ab1dfb6a2b01be | 3,635,015 |
def concatIDF(idfObjectList, param):
"""Create tab separated strings from input yaml parameter objects"""
outString = ""
for obj in idfObjectList:
outString += "\t" + str(noneClean(obj.params[param]))
return outString | 0cd6fe6dea85b2d7365a1e225d75386629dab98e | 3,635,016 |
import inspect
def super_class_property(*args, **kwargs):
"""
A class decorator that adds the class' name in lowercase as a property of
it's superclass with a value constructed using the subclass' constructor with
the given arguments. So for example:
class A:
pass
@super_class_property(foo=5)
... | ecfd38ba3d7ea96266278ed6be6cf0ba87263d7d | 3,635,017 |
def run_deferred_and_advance_now_until(ctx, u, until):
"""
Find all rows in the deferred table where the run_at time has passed for the given user and
run the deferred action. gametime.now is set to the deferred actions run_at value to simulate
the production environment when run from a cronjob.
NOT... | 8e741cd7cc06d2883b8879af554f300d5a305625 | 3,635,018 |
def get_group_type_by_name(context, name):
"""Retrieves single group type by name."""
if name is None:
msg = _("name cannot be None")
raise exception.InvalidGroupType(reason=msg)
return db.group_type_get_by_name(context, name) | ceff65a621fece573cec1ff60291b80bdd784bb7 | 3,635,019 |
import os
def hdfs_to_local(hdfs_path, local_path, is_txt=True):
"""copy hdfs file to local
param:
* hdfs_path: hdfs file or dir
* local_path: local file or dir
return:
* res: result message
"""
res = ''
if is_txt:
f = os.popen("hadoop dfs -text {} > {}".format(hdfs_path, ... | 46ee67069c7c43c1fb23a62a1c1d8fadcf058121 | 3,635,020 |
def register_tortoise_exception(
app: FastAPI,
add_exception_handlers: bool = False,
) -> None:
""" rewrite from tortoise.contrib.fastapi import register_tortoise
"""
if add_exception_handlers:
@app.exception_handler(DoesNotExist)
async def doesnotexist_exception_handler(requ... | e9c140f61b32475cd2a396fb709aba1b578cf6bf | 3,635,021 |
import numpy
def norm_m(matrix, norm):
"""
Normaliza la matriz pasada con un formato float64 bits
tipo de nomalizacion l1
:param matrix: {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, element by element.
scipy.sparse matrices should be in CSR format to avoid... | 022f977f3eb937aa9a27deec229a19281eac281b | 3,635,022 |
def user_from_dict(user_dictionary: dict):
"""
The function converts a dictionary of User to a User object.
:param user_dict: A dictionary that contains the keys of a User.
:type user_dict: dict
:rtype: ibmpairs.query.User
:raises Exception: if not a dict.... | fb2380d316a3c939afd9b6a7d6399ad198c881c7 | 3,635,023 |
def lind_safe_fs_getdents(args):
""" Safely wrap the getdents call.
See dispatcher.repy for details.
Check the handle and count for consistancy,
then call the real getdents dispatcher.
"""
handle = args[0]
count = args[1]
check_valid_fd_handle(handle)
assert isinstance(count, int... | 4ec1b3ba52f0d24ebafc03829b4b520a93f460ee | 3,635,024 |
from datetime import datetime
def parser(): # parsing the whole circuit into lists of objects
""" Start of Parse .nodes """
file = open("{}.nodes".format(fileName))
lines = file.readlines()
saved = 0
node_list = [] # List of all nodes for the current circuit
#... | 98e828248ec02ecd68928165791d549b04962992 | 3,635,025 |
def header(columns):
"""Create html for column headers."""
cells = add_bars(columns)
return div(docfilter, div(*cells, cls='noselect'), id='header') | 1d54b6f60085e0234aa7055c9ef17d684793b6d4 | 3,635,026 |
def set_playbook_config(ctx, **kwargs):
"""
Set all playbook node instance configuration as runtime properties
:param _ctx: Cloudify node instance which is instance of CloudifyContext
:param config: Playbook node configurations
"""
def _get_secure_values(data, sensitive_keys, parent_hide=False):... | 241642acdcd3b3b37c4b3736b375a03e5bc4cbec | 3,635,027 |
def get_services_accounting_flow(device, field, output=None):
""" Get value of field from show services accounting flow
Args:
device (`obj`): Device object
field (`str`): field name in show output
output (`str`): output of show services accounting flow
Returns:
... | d2cc47826073d47a163edc9e12079705563baac1 | 3,635,028 |
import math
def moving_window_stride(array, window, step):
"""
Returns view of strided array for moving window calculation with given window size and step
:param array: numpy.ndarray - input array
:param window: int - window size
:param step: int - step lenght
:return: strided: numpy.ndarray -... | 50217f9830864375f801ef5412c99756fb9982ac | 3,635,029 |
import os
import shutil
def _run_purple(paired, het_file, depth_file, vrn_files, work_dir):
"""Run PURPLE with pre-calculated AMBER and COBALT compatible inputs.
"""
purple_dir = utils.safe_makedir(os.path.join(work_dir, "purple"))
out_file = os.path.join(purple_dir, "%s.purple.cnv" % dd.get_sample_na... | 4206ccca514c9728a1f0146146caba081862fbef | 3,635,030 |
def ecef2geodetic(ecef, radians=False):
"""
Convert ECEF coordinates to geodetic using ferrari's method
"""
# Save shape and export column
ecef = np.atleast_1d(ecef)
input_shape = ecef.shape
ecef = np.atleast_2d(ecef)
x, y, z = ecef[:, 0], ecef[:, 1], ecef[:, 2]
ratio = 1.0 if radians else (180.0 / n... | a4ef47c2f7284066e2d97b744dd144d75ccff768 | 3,635,031 |
def merge(sorted1, sorted2):
"""Merge two sorted lists into a single sorted list."""
if sorted1 == ():
return sorted2
elif sorted2 == ():
return sorted1
else:
h1, t1 = sorted1
h2, t2 = sorted2
if h1 <= h2:
return (h1, merge(t1, sorted2))
else:
... | 7c02b345b3d1e7c67e363e1535c608575a313f75 | 3,635,032 |
import os
def write_gpt_fieldmesh(fm,
outfile,
asci2gdf_bin=None,
verbose=False):
"""
Writes a GPT fieldmap file from a FieldMesh object.
Requires cylindrical geometry for now.
"""
assert fm.geometry == 'cylindrical', f'Geometry: {... | dc8cd050efa4fe60cea334dbf30e060679c5cef6 | 3,635,033 |
from datetime import datetime
import os
def _build_bundleitems_update_request(player_id, bundle_name, bundle_item_key, bundle_item_value):
"""
Build the Bundle Items update request.
"""
player_id_bundle = f'{player_id}_{bundle_name}'
timestamp = datetime.utcnow().replace(tzinfo=timezone.utc).isofo... | 0dec931485faaeeab66cf045c4cc192cfa594c89 | 3,635,034 |
from dask import delayed, compute
from dask.bytes.core import open_files, read_bytes
from dask.dataframe import from_delayed
import copy
def dask_read_avro(urlpath, blocksize=100000000, storage_options=None):
"""Read set of avro files into dask dataframes
Use this only with avro schema that make sense as tab... | a6559fbdc7a90149984f51f6d632663b36b5106e | 3,635,035 |
import csv
def msgs_csv(messages, header):
"""Return messages in .csv format."""
queue = cStringIO.StringIO()
writer = csv.writer(queue, dialect=csv.excel, quoting=csv.QUOTE_ALL)
if header:
writer.writerow(['Date', 'From', 'To', 'Text'])
for m in messages:
writer.writerow([m['date'... | f7397af4f19cd7b94bd6d56766608c607dbe6950 | 3,635,036 |
def alpha_s_plot_parameters(
alpha_curve: "list[float]",
loading: "list[float]",
section: "list[float]",
alpha_s_point: float,
reference_area: float,
molar_mass: float,
liquid_density: float,
):
"""Get the parameters for the linear region of the alpha-s plot."""
slope, intercept, co... | a06a65ec2f7e13535ac96855f2ddb8b985268d26 | 3,635,037 |
def _MutualInformationTransformAccumulate(pcol): # pylint: disable=invalid-name
"""Accumulates information needed for mutual information computation."""
return (pcol | 'VocabCountPerLabelPerTokenAccumulate' >> beam.CombinePerKey(
_CountAndWeightsMeansCombineFn())) | e3fb8c16dc025f8cb7ef4f0196d2b9341cbc0855 | 3,635,038 |
import torch
def GTLRU(input_a, input_b, n_channels: int):
"""Gated[?] Tanh Leaky ReLU Unit (GTLRU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
r_act = torch.nn.functional.leaky_relu(in_act[:, n_channels:, :], negative_slope=0.01, inplace=True)
acts = t_act * r_act
... | 62f36cda5329e3b1889abcab2f1c97d6d1448ea8 | 3,635,039 |
def get_items_by_category(category_id, limit, offset=None):
"""
Return items from catalog by category with limit and offset
:param category_id:
:param limit:
:param offset:
:return object:
"""
return session.query(Catalog).filter_by(
category=category_id).offset(offset).limit(li... | 63e82b3f67cf2ff8e5a863dfe05d7a4acb3e5543 | 3,635,040 |
def cosine(u, v, w=None):
"""
Compute the Cosine distance between 1-D arrays.
The Cosine distance between `u` and `v`, is defined as
.. math::
1 - \\frac{u \\cdot v}
{||u||_2 ||v||_2}.
where :math:`u \\cdot v` is the dot product of :math:`u` and
:math:`v`.
Para... | ad655f35963e64301686f9df440c59886984335b | 3,635,041 |
import json
def adjust_site_parameters(site):
"""Updates extra parameters with applicable datastreams from
`arm_reference_sites.json`
Parameters
----------
site: dict
Returns
-------
dict
Copy of input with updated extra parameters.
"""
with open(DEFAULT_SITEFILE) as ... | f58d10f69c95f4f3db5ef71f772e97cb4c08e8a2 | 3,635,042 |
def slice_repr(slice_obj):
"""
Get the best guess of a minimal representation of
a slice, as it would be created by indexing.
"""
slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step]
if slice_items[-1] is None:
slice_items.pop()
if slice_items[-1] is None:
if slice... | c894f66478ec830a4968d0cfc5d9e146457012b6 | 3,635,043 |
async def isAtLeastInstructor(context: commands.Context) -> bool:
"""
Returns true if context.author is either an admin or an instructor and False otherwise
:param context:
:return:
"""
return await isInstructor(context) or await isAdmin(context) | 074d3726e42288ccfc3c6f5674679bd5e3510d2a | 3,635,044 |
import kwimage
def _prob_to_dets(probs, diameter=None, offset=None, class_probs=None,
keypoints=None, min_score=0.01, num_min=10,
max_dims=None, min_dims=None):
"""
Directly convert a one-channel probability map into a Detections object.
Helper for Heatmap.detect
... | 3142495ac14122c1d42b68c527c9ec21cf3b5c68 | 3,635,045 |
def pad_sequences(sequences, pad_symbol, max_length=None,
mask_present_symbol=None, padding_mode='both'):
"""
Pads a collection of sequences. Will work only for two dimensional data.
:param sequences: list or np array, which has sequences (lists or np arrays)
that ... | 6ccdc43b63e04526a8376c878493323075f14808 | 3,635,046 |
from typing import Sequence
from typing import Tuple
def cast_cal_range(cal_range: Sequence[raw_mz_type]) -> Tuple[float, float]:
"""
:param cal_range:
"""
min_val, max_val = cal_range
return float(min_val), float(max_val) | 22bfb7461209e4a31d871aa2237a1add190abaaf | 3,635,047 |
import tarfile
from io import StringIO
import re
def get_warc_identifiers(sip):
"""Parses the SIP in HDFS and retrieves WARC/ARK tuples."""
w = webhdfs.API(prefix=WEBHDFS)
identifiers = []
tar = "%s/%s.tar.gz" % (SIP_ROOT, sip)
if w.exists(tar):
logger.debug("Found %s" % tar)
t = w.open(tar)
tar = tarfile.... | 1df6eab92c8d553b3a3e1d30752b7338482819a5 | 3,635,048 |
def request_get(url):
"""
Realisa una solicitud 'GET' en la url proporcinada, si se realiza con exito retorna el contenido
y se ocurre algun error retorna 'None'
Parametro 'url' direccion del sitio web
return: 'requests.get.content'
"""
try:
with closing(get(url, stream=True)) as ... | e13de348651c9254c1b17fa26c49faa420a670f9 | 3,635,049 |
import sys
def in_virtualenv_currently():
"""Check whether currently running inside of a virtualenv or not"""
return get_base_prefix_compat() != sys.prefix | 867bc0d73d8fca95297e7830abe6b2c896785019 | 3,635,050 |
def make_tensor(tensor):
""" 转换numpy数组到potobuf格式 """
shape = projector_pb2.Tensor.TensorShape(dim=[projector_pb2.Tensor.TensorShape.Dim(size=d)
for d in tensor.shape])
return projector_pb2.Tensor(dtype=str(tensor.dtype),
tens... | 9bfe06f21f5286b1604f3dde13d8740dc1c5a5df | 3,635,051 |
def pad(sequences, max_length, pad_value=0):
"""Pads a list of sequences.
Args:
sequences: A list of sequences to be padded.
max_length: The length to pad to.
pad_value: The value used for padding.
Returns:
A list of padded sequences.
"""
out = []
for sequence in ... | 68d0a8a19352e3e724ef012a396b51c28005ff02 | 3,635,052 |
def dict_blocks_decoder(nB, v, step, lookup: dict, dec_fmt: str):
"""
Decodes a single block from a NORB pooling design
"""
ds = Design()
dm = ds.matrix
decoder = DictBlockDecoder(dm, lookup, format=dec_fmt)
res = []
for b in range(nB):
p = v.squeeze()[step*b:step*b + step]
... | 10297e9b09919cca73962cfca54f4b6de7738f30 | 3,635,053 |
def _build_circuit_layers_and_connectivity_nearest_neighbors(n_qubits):
"""Function to generate circuit layers for processors with nearest-neighbor
connectivity
Args:
n_qubits (int): number of qubits in the qubit array
Returns:
(zquantum.core.circuit.CircuitConnectivity, zquantum.core.ci... | 62e0a9b5f1ca9e6ddb5713ee8389126983d44793 | 3,635,054 |
def band_colormap( cmap, nband=10 ):
""" -> a colormap with e.g. 10 bands """
cmap = get_cmap( cmap )
h = .5 / nband
A = cmap( np.linspace( h, 1 - h, nband ))
name = "%s-band-%d" % (cmap.name, nband)
return array_cmap( A, name, n=nband ) | dca6fa0afcefc25e288f8eb24599554286de7c05 | 3,635,055 |
def rolling_optimal_combo_stats(ret1, ret2, window_len, window_step, nsteps=20, period='monthly', rebal_period=3,
downside_vol=True):
"""Find the optimal (volatility-minimizing) combination of two return series over a rolling window.
Args:
- ret1: a sequence of period return... | 4796faf706fc8ce49588e64ffcf98222432ff031 | 3,635,056 |
def forward_backward_prop(data, labels, params, dimensions):
"""
Forward and backward propagation for a two-layer sigmoidal network
Compute the forward propagation and for the cross entropy cost,
and backward propagation for the gradients for all parameters.
Arguments:
data -- M x Dx matrix, w... | c3a774117aced21c117f2dea53f1b1891f7562db | 3,635,057 |
import copy
def generate_output_descriptors(filename_out_base,
max_block_size_voxels,
overlap_size_voxels,
dim_order,
header,
output_type,
... | ebb7ecbc3f3105ee995033fbccccd8f745a6a12d | 3,635,058 |
def clean_data(df):
"""
The function is to clean the data.
Parameters:
df (pandas dataframe): loaded data from load_data function.
Returns:
df (pandas dataframe): cleaned version of the data.
"""
# Create a dataframe of the 36 individual category columns
cate_df = df['categor... | 12706ed7889482b709f33e085d10dc92f0d1bf9e | 3,635,059 |
import math
def squeezenet1_0_fpn_feature_shape_fn(img_shape):
""" Takes an image_shape as an input to calculate the FPN output sizes
Ensure that img_shape is of the format (..., H, W)
Args
img_shape : image shape as torch.Tensor not torch.Size should have
H, W as last 2 axis
Retu... | d56fe3d834bcd9633727defe3ad9a27ea756ed40 | 3,635,060 |
from pathlib import Path
def temp_paths_2(tmp_path_factory):
"""
Makes temporary directories, for testing bak_to_git_2, and populates them
with test files. Returns pathlib.Path objects for each.
"""
temp_path: Path = tmp_path_factory.mktemp("baktogit2")
bak_path = temp_path / "_0_bak"
bak_... | da3b9ef6af7dc04bbc1aadfb3147223564f71458 | 3,635,061 |
def clip_alpha(aj, H, L):
"""
cLips alpha vaLues tHat are greater
tHan H or Less tHan L
"""
if aj > H:
aj = H
if L > aj:
aj = L
return aj | d272e2703c1b6008fc4840e887ce842005dfad62 | 3,635,062 |
def nextfig():
"""Return one greater than the largest-numbered figure currently
open. If no figures are open, return unity.
No inputs or options."""
# 2010-03-01 14:28 IJC: Created
figlist = getfigs()
if len(figlist)==0:
return 1
else:
return max(figlist)+1
retu... | d8a4ec57880f247d243f80e662e1172456551984 | 3,635,063 |
from pathlib import Path
def load_laurent2016():
"""Model dataset for refolded fold
Returns
-------
tuple
pandas data frame with loopstructural dataset and numpy array for bounding box
"""
module_path = dirname(__file__)
data = pd.read_csv(join(module_path, Path('data/refolded_f... | 01a048b4e8748e9cc4e7ef9ea1c1385bfd0faaed | 3,635,064 |
def get_user_best(key: str, user: int, mode: int = 0, limit: int = 10, type_: str = None, type_return: str = 'dict'):
"""Get the top scores for the specified user."""
params = {
'k': key,
'u': user,
'm': mode,
'limit': limit,
'type': type_}
r = req.get(urls['user_best'], params=params)
return from_json(r.text,... | b42357c0ca3553c2cf01624869931748c2df897c | 3,635,065 |
import types
def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: %s" % fn)
# The blessed way to copy a function. co... | 37fca64ddaadfc8a6a24dce012af2143038cacd2 | 3,635,066 |
from re import T
def ireport():
""" Incident Reports, RESTful controller """
resource = request.function
tablename = "%s_%s" % (module, resource)
table = db[tablename]
# Don't send the locations list to client (pulled by AJAX instead)
table.location_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(... | 02cc630ce76336ff3e94021c0378daf48fe6a3bd | 3,635,067 |
import torch
def makenetbn(dims, softmax=True, single=True):
"""A batch-normalizing version of makenet. Experimental."""
ndims = len(dims)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# the weights must be set explicitly as attributes in the class
# (i.e., we ca... | b9978c610992bbd0566cb8d855613761446a050f | 3,635,068 |
def _ccsd_t_energy(output_str):
""" Reads the CCSD(T)/UCCSD(T) energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
... | 74352ad0f717de6b6c1125508a0556635e6446a3 | 3,635,069 |
from miner_globals import getCurrentScriptPath
def getMyPath():
"""returns path of current script"""
return getCurrentScriptPath() | 7ba447d8a7b34a9e0ada1ae11cdefa81ec5a89e9 | 3,635,070 |
import random
def get_codename():
"""Helper for generating a random codename to represent a voter
in the admin interface. To protect voting privacy of our voters,
we are using hashes to make it slightly more difficult to
reveal/infer who voted for who. On the admin interface, however,
instead of u... | 6baf9cc8dd774f0d5541980d7a48be98cb4c66a0 | 3,635,071 |
def load_paste_config(app_name, options, args):
"""
Looks for a config file to use for an app and returns the
config file path and a configuration mapping from a paste config file.
We search for the paste config file in the following order:
* If --config-file option is used, use that
* If args... | 26524003ac407433eb82b196aed8836aad7ccf92 | 3,635,072 |
import numpy
def get_nearest_to_layers_mean_indicators(layers):
"""
Return indicators of weights in layers nearest
to layer weight mean.
This function, for every given layer, computes weights mean
and returns importance indicators for every weight
based on how close to it's layer mean it is.
... | 5fe27d680566097743b708c07fdeb44b1f68ce0f | 3,635,073 |
def mach_wave_angle(mach: float):
"""Return the angle of the Mach wave given the Mach number after a turn
Notes
-----
Parameters
----------
mach : float
The mach number after a turn
Returns
-------
float
The angle of the mach wave in degrees
Examples
-... | a5dd1d2021dbdf87a4c255a207ad0d8b9627a407 | 3,635,074 |
from ssl import SSLError
def download_to_file(url, file, quiet=False):
"""Downloads a URL to file. Returns the file size.
Returns -1 if the downloaded file size does not match the expected file
size
Returns -2 if the download is skipped due to the file at the URL not
being newer than the local cop... | 723d5e733c623b6b770f71b31085861433d7ad3d | 3,635,075 |
def peakfit(xvals, yvals, yerrors=None, model='Voight', background='slope',
initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False):
"""
Fit x,y data to a peak model using lmfit
E.G.:
res = peakfit(x, y, model='Gauss')
print(res.fit_repo... | 2f5aab6bb2eff7eb72217924d1487e5a2f87ec43 | 3,635,076 |
import re
def error_027_mnemonic_codes(text):
"""Fix some cases and return (new_text, replacements_count) tuple."""
(text, ignored) = ignore(text, r"https?://\S+")
(text, count1) = re.subn(r"–", "–", text)
(text, count2) = re.subn(r" ", " ", text)
text = deignore(text, ignored)
retu... | 4716e567db007ab49182ccc9fa82f556f56d55b3 | 3,635,077 |
import functools
def debug(_func, *, write=False):
"""Prints/writes debuging info for the decorated function
"""
def debug_decorator(func):
@functools.wraps(func)
def debug_decorator_wrapper(*args, **kwargs):
args_repr = [repr(arg) for arg in args]
kwargs_repr = [f"... | f55a8c9620d863292dce16e05289a0cd3a2114fb | 3,635,078 |
def memodict(f):
"""Memoization decorator for a function taking a single argument
http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
... | e49da93343320a86d07394c0015589d4d34aab97 | 3,635,079 |
def xval(v):
"""Return the scalar x value of a single vector.
>>> xval(make(1, 2, 3))
1
"""
assert is_vec3(v)
assert v.shape[0] == 1
return v[0, 0] | f4637f54e7350d7c24e40db687cf1ee8b5467a31 | 3,635,080 |
from datetime import datetime
def payload_full():
"""full jwt payload"""
return {
"iss": "https://www.myapplication.com",
"aud": "https://www.myapplication.com",
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=10),
"iat": datetime.datetime.utcnow(),
"nbf"... | c459fecc3b6de6960be7b2eabb44388e09153ca4 | 3,635,081 |
def ensure_package(
requirement_str, error_level=None, error_msg=None, log_success=False
):
"""Verifies that the given package is installed.
This function uses ``pkg_resources.get_distribution`` to locate the package
by its pip name and does not actually import the module.
Therefore, unlike :meth:... | 1006358dff21366424d2b4085599956d67542ab5 | 3,635,082 |
def deliver_image_gif(): # type: () -> str
"""Return a minimal GIF image."""
return b64decode("""
R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
""") | 9dadcba602aeae9ae64f789d594ef42ede5562f3 | 3,635,083 |
from re import L
def build_bootstrap_likelihood(lex, sentence, ontology,
alpha=0.25, meaning_prior_smooth=1e-3):
"""
Prepare a likelihood function `p(meaning | syntax, sentence)` based on
syntactic bootstrapping.
Args:
lex:
sentence:
ontology:
alpha: Mixing para... | 19274987b8ef5ace9f31638c81933bcab122d55f | 3,635,084 |
def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... | bd5b7abd1b5ceb0b273e99e30ecc248482ed7476 | 3,635,085 |
import logging
import sys
def create_dest_group(glab, dest, src_group_tree):
"""Create destination group structure"""
if '/' in dest:
logging.error('SubGroup as destination not supported "%s"', dest)
sys.exit(1)
dest_group_tree = Tree()
logging.info('Attempting to create destination gr... | 20f2839de1c86eed999a3feabc6618a61fc3c843 | 3,635,086 |
def datetime_to_jd(date):
"""
Convert a `datetime.datetime` object to Julian Day.
Parameters
----------
date : `datetime.datetime` instance
Returns
-------
jd : float
Julian day.
Examples
--------
>>> d = datetime.datetime(1985,2,17,6)
>>> d
... | 6a149aba3719eaf4e0a81e2372192b9d17676b1f | 3,635,087 |
def parse_channel_mention(part, message):
"""
If the message's given part is a channel mention, returns the respective channel.
Parameters
----------
part : `str`
A part of a message's content.
message : ``Message``
The respective message of the given content part.
... | 38b3bbe5f7a918210a4ddc4005d61c651687ab55 | 3,635,088 |
def keep_alive(headers, version, method):
""" return True if the connection should be kept alive"""
conn = set((v.lower() for v in headers.get_all('connection', ())))
if "close" in conn:
return False
elif 'upgrade' in conn:
headers['connection'] = 'upgrade'
return True
elif "... | da8e9a5908d19a5bdb5ba2915abc5f85e1e3c553 | 3,635,089 |
def apply_dies_factory(have_dies, jones_type):
"""
Factory function returning a function that applies
Direction Independent Effects
"""
# We always "have visibilities", (the output array)
jones_mul = jones_mul_factory(have_dies, True, jones_type, False)
if have_dies:
def apply_dies... | 460477cc5cd6b195f331c8db2dfd0d0ec9080750 | 3,635,090 |
def check_skip(timestamp, filename):
"""
Checks if a timestamp has been given and whether the timestamp corresponds
to the given filename.
Returns True if this condition is met and False Otherwise"
"""
if ((len(timestamp) > 0) and not(timestamp in filename)):
return True
elif ((len(... | 738043fb554f20b79fa3ac8861f9e60d0d697e5e | 3,635,091 |
from typing import Optional
from typing import Union
import re
def extract_emoji(string: str, bot: Bot) -> Optional[Union[str, Emoji]]:
"""
Extracts a single emoji or custom emote from the input string.
:param string: Input string
:param bot: Discord bot object
:return: Either a string containing... | 00d2c3614b8f4e9b8292fec781aefa231d9d4e83 | 3,635,092 |
def get_bridge(driver):
"""Call this method to get a Bridge instead of a standalone accessory."""
bridge = Bridge(driver, 'Bridge')
light_1 = LightBulb(driver, 'Red Light', pin=LedPin1)
light_2 = LightBulb(driver, 'Blue Light', pin=LedPin2)
bridge.add_accessory(light_1)
bridge.add_accessory(ligh... | e3ee071661e4cc19da8ec5f7b7b7b5017c2f76d4 | 3,635,093 |
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = Tensor(np.random.random((real_samples.size(0), 3, 1, 1)))
# Get random interpolation between real and fake samp... | 724da4c0d18996e0813e4cea6cbb33d1f3a316fc | 3,635,094 |
def is_tabledap(url):
"""
Identify a dataset as an ERDDAP TableDAP dataset.
Parameters
----------
url (str) : URL to dataset
Returns
-------
bool
"""
return "tabledap" in url | 9f4650bc3a3bc0794637b042c1779a84d7c02779 | 3,635,095 |
import argparse
import logging
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(description="compare results... | 4a579ca5b25ae85ad836d76a7dc293ba53945801 | 3,635,096 |
def generate_timestamp(time_to_use, stamp_type="default"):
""" Genrate a text timestamp """
new_stamp = time_to_use.strftime("%Y%m%d-%H%M%S")
return new_stamp | 1b386ed7375b3158867d980796c764a627c68338 | 3,635,097 |
def scr2idb(*args):
"""scr2idb(char name) -> char"""
return _idaapi.scr2idb(*args) | 0ec28ae35176b4f28c755723a063c8ddadb583df | 3,635,098 |
import torch
def compute_local_nre_maps(
source_descriptors: torch.Tensor,
target_features: torch.Tensor,
prior_target_keypoints: torch.Tensor,
norm_coarse: torch.Tensor,
window_size: int,
):
"""Compute dense local correspondence maps.
Args:
* source_descriptors: The interpolated s... | 281eb31981b81e9a9d4053786a22256ee182c7b4 | 3,635,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.