content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def _generate_input_weights(
N,
dim_input,
dist="custom_bernoulli",
connectivity=1.0,
dtype=global_dtype,
sparsity_type="csr",
seed=None,
input_bias=False,
**kwargs,
):
"""Generate input or feedback weights for a reservoir.
Weights are drawn by default from... | 4201fda2f693d0ee0f189e94762de09877059b08 | 3,643,895 |
import re
def _get_variable_name(param_name):
"""Get the variable name from the tensor name."""
m = re.match("^(.*):\\d+$", param_name)
if m is not None:
param_name = m.group(1)
return param_name | 4f6258667383c80b584054af20ac9a61cf25381f | 3,643,896 |
def np_gather(params, indices, axis=0, batch_dims=0):
"""numpy gather"""
if batch_dims == 0:
return gather(params, indices)
result = []
if batch_dims == 1:
for p, i in zip(params, indices):
axis = axis - batch_dims if axis - batch_dims > 0 else 0
r = gather(p, i, ... | 9dc89cb6e48a6c8126fbee1421a4d7058f35b9e0 | 3,643,897 |
def texture(data):
"""Compute the texture of data.
Compute the texture of the data by comparing values with a 3x3 neighborhood
(based on :cite:`Gourley2007`). NaN values in the original array have
NaN textures.
Parameters
----------
data : :class:`numpy:numpy.ndarray`
multi-dimensi... | e1a57e9e37a1730de5c4e919ba6fa65eaf301c79 | 3,643,898 |
from typing import Tuple
def joos_2013_monte_carlo(
runs: int = 100, t_horizon: int = 1001, **kwargs
) -> Tuple[pd.DataFrame, np.ndarray]:
"""Runs a monte carlo simulation for the Joos_2013 baseline IRF curve.
This function uses uncertainty parameters for the Joos_2013 curve calculated by
Olivie and ... | 3fd791eae464bd1c73fcbf3fa16c7e8634dd6f80 | 3,643,899 |
import torch
def pairwise_l1_loss(outputs, targets):
"""
"""
batch_size = outputs.size()[0]
if batch_size < 3:
pair_idx = np.arange(batch_size, dtype=np.int64)[::-1].copy()
pair_idx = torch.from_numpy(pair_idx).cuda()
else:
pair_idx = torch.randperm(batch_size).cuda()
... | 4030a83bbdb5575ff7735328134d72748bc6af51 | 3,643,900 |
def get_mwis(input_tree):
"""Get minimum weight independent set
"""
num_nodes = input_tree['num_nodes']
nodes = input_tree['nodes']
if num_nodes <= 0:
return []
weights = [0, nodes[0][0]]
for idx, node_pair in enumerate(nodes[1:], start=1):
node_weight, node_idx = node_pair
... | 3df82615d1060756b1a4863fe168ea542dfed4f9 | 3,643,901 |
def info(tid, alternate_token=False):
"""
Returns transaction information for the transaction
associated with the passed transaction ID
:param id: String with transaction ID.
:return: Dictionary with information about transaction.
"""
if not tid:
raise Exception('info() requires id ... | 109e3f34603dacfc3b31e5d90cd092f02a45b4f7 | 3,643,902 |
def find_extrema(array, condition):
"""
Advanced wrapper of numpy.argrelextrema
Args:
array (np.ndarray): data array
condition (np.ufunc): e.g. np.less (<), np.great_equal (>=) and etc.
Returns:
np.ndarray: indexes of extrema
np.ndarray: values of extrema
"""
# get indexes of extrema
indexes = argrelextr... | a356c2af0d992dbc447802120094dd8880f80e3e | 3,643,903 |
def compute_all_metrics_statistics(all_results):
"""Computes statistics of metrics across multiple decodings."""
statistics = {}
for key in all_results[0].keys():
values = [result[key] for result in all_results]
values = np.vstack(values)
statistics[key + "_MEAN"] = np.mean(values, axis=0)
statist... | c1708e78a375ddac0438b31c16f2fedcd357a4d9 | 3,643,904 |
from typing import Tuple
def parse_pubkey(expr: str) -> Tuple['PubkeyProvider', str]:
"""
Parses an individual pubkey expression from a string that may contain more than one pubkey expression.
:param expr: The expression to parse a pubkey expression from
:return: The :class:`PubkeyProvider` that is p... | 8731384a7aca25a5655c474925677f1e8dff9252 | 3,643,905 |
def XOR(*conditions):
"""
Creates an XOR clause between all conditions, e.g.
::
x <> 1 XOR y <> 2
*conditions* should be a list of column names.
"""
assert conditions
return _querybuilder.logical_xor(conditions) | a2870b7bbafa5247fd3786d5ca10446ae9d7662a | 3,643,906 |
def Interpolator(name=None, logic=None):
"""Returns an interpolator
:param name: Specify the name of the solver
:param logic: Specify the logic that is going to be used.
:returns: An interpolator
:rtype: Interpolator
"""
return get_env().factory.Interpolator(name=name, logic=logic) | 0f2e33f3bb98578f8f24236fb4e0c32875183f38 | 3,643,907 |
def trim_to_min_length(bits):
"""Ensures 'bits' have min number of leading zeroes.
Assumes 'bits' is big-endian, and that it needs to be encoded in 5 bit blocks.
"""
bits = bits[:] # copy
# make sure we can be split into 5 bit blocks
while bits.len % 5 != 0:
bits.prepend('0b0')
# Ge... | d740ce27e0ebce30f382844a9810f7792c9b4669 | 3,643,908 |
def get_attributes_callback(get_offers_resp):
"""Callback fn for when get_attributes is called asynchronously"""
return AttributesProvider(get_offers_resp) | e901d2914cb1653454b4b19e4948b02f1ed304c8 | 3,643,910 |
def display(choices, slug):
"""
Get the display name for a form choice based on its slug. We need this function
because we want to be able to store ACS data using the human-readable display
name for each field, but in the code we want to reference the fields using their
slugs, which are easier to ch... | e177fa4596de8a9921d05216d51344e95dce89ab | 3,643,911 |
def autocorrelation(data):
"""Autocorrelation routine.
Compute the autocorrelation of a given signal 'data'.
Parameters
----------
data : darray
1D signal to compute the autocorrelation.
Returns
-------
ndarray
the autocorrelation of the signal x.
"""
n_points ... | 205a4ffd7a3b2f6cd4608edc58407478c0e29588 | 3,643,912 |
def yes_or_no(question, default="no"):
"""
Returns True if question is answered with yes else False.
default: by default False is returned if there is no input.
"""
answers = "yes|[no]" if default == "no" else "[yes]|no"
prompt = "{} {}: ".format(question, answers)
while True:
answe... | 496137bcd3d99a3f0bcc5bb87ab3dc090f8fc414 | 3,643,913 |
import requests
from io import StringIO
def query_airnow(param, data_period, bbox, key=None):
"""Construct an AirNow API query request and parse response.
Args:
param (str):
The evaluation parameter for which to query data.
data_period (list):
List with two elements, t... | 97dbfddd4abaee8491c7aa90e2d5c46796e825ac | 3,643,914 |
def compile(string):
"""
Compile a string to a template function for the path.
"""
return tokens_to_function(parse(string)) | ace794e2378b493b8d6ea06c0185ada5e90289a2 | 3,643,915 |
import math
def flajolet_martin(data, k):
"""Estimates the number of unique elements in the input set values.
Inputs:
data: The data for which the cardinality has to be estimated.
k: The number of bits of hash to use as a bucket number. The number of buckets is 2^k
Output:
Returns the es... | da7513b8c672278eebf00e71ca8a37a442b7fee0 | 3,643,916 |
def decode(encoded: list):
"""Problem 12: Decode a run-length encoded list.
Parameters
----------
encoded : list
The encoded input list
Returns
-------
list
The decoded list
Raises
------
TypeError
If the given argument is not of `list` type
"""
... | 8fb273140509f5a550074c6d85e485d2dc1c79d0 | 3,643,918 |
import random
def create_offset(set_point_value):
"""Docstring here (what does the function do)"""
offset_value = random.randint(-128, 128)
offset_value_incrementation = float(offset_value / 100)
return set_point_value - offset_value_incrementation | 8b41ce32d98edd87c2317a971d87f9b74c3f1b6c | 3,643,919 |
def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_len... | 88a7bd54dbaa8fedfc1cc09665dc3676d5effc8f | 3,643,920 |
import hashlib
import queue
def startpeerusersync(
server, user_id, resync_interval=OPTIONS["Deployment"]["SYNC_INTERVAL"]
):
"""
Initiate a SYNC (PULL + PUSH) of a specific user from another device.
"""
user = FacilityUser.objects.get(pk=user_id)
facility_id = user.facility.id
device_in... | c32ac73c11bf7114477fe49bd53ea8beb012522b | 3,643,921 |
import re
def clean_url(str_text_raw):
"""This function eliminate a string URL in a given text"""
str_text = re.sub("url_\S+", "", str_text_raw)
str_text = re.sub("email_\S+", "", str_text)
str_text = re.sub("phone_\S+", "", str_text)
return(re.sub("http[s]?://\S+", "", str_text)) | f14d4647bad72ec08aa64f19bbdd2726eb47d63b | 3,643,922 |
def compare_strategies(strategy, baseline=always_roll(5)):
""" Вернуть среднее отношение побед STRATEGY против BASELINE """
as_first = 1 - make_average(play)(strategy, baseline)
as_second = make_average(play)(baseline, strategy)
return (as_first + as_second) / 2 | 609e6ecc057e72f081fd033a8ee2a02cead20b36 | 3,643,923 |
from pathlib import Path
def process_geo(
path_geo_file: Path,
*,
add_pop: bool = True,
add_neighbors: bool = True,
add_centroids: bool = False,
save_geojson: bool = False,
path_pop_file: Path = PATH_PA_POP,
path_output_geojson: Path = PATH_OUTPUT_GEOJSON,
) -> geopandas.GeoDataFrame:
... | 2f5e0d546a1fe3c1ad30501726fca48ae4549d0e | 3,643,924 |
def nml_poisson(X, sum_x, sum_xxT, lmd_max=100):
"""
Calculate NML code length of Poisson distribution. See the paper below:
yamanishi, Kenji, and Kohei Miyaguchi. "Detecting gradual changes from data stream using MDL-change statistics."
2016 IEEE International Conference on Big Data (Big Data). IEEE, ... | bfcb71189e6c5a132e930c6fb83a59cdf7752982 | 3,643,925 |
import prometheus_client
def setup_metrics(app):
"""
Setup Flask app with prometheus metrics
"""
app.before_request(before_request)
app.after_request(after_request)
@app.route('/metrics')
def metrics():
# update k8s metrics each time this url is called.
global PROMETHEUS_M... | 347893ca8ef01b7a3443bb0e75cf39a62b541847 | 3,643,926 |
def _getFormat(fileformat):
"""Get the file format constant from OpenSSL.
:param str fileformat: One of ``'PEM'`` or ``'ASN1'``.
:raises OpenSSLInvalidFormat: If **fileformat** wasn't found.
:returns: ``OpenSSL.crypto.PEM`` or ``OpenSSL.crypto.ASN1`` respectively.
"""
fileformat = 'FILETYPE_' +... | 7aaa2ab3a8b2580052dd27e605242bda24ac8220 | 3,643,927 |
def clip(
arg: ir.NumericValue,
lower: ir.NumericValue | None = None,
upper: ir.NumericValue | None = None,
) -> ir.NumericValue:
"""
Trim values at input threshold(s).
Parameters
----------
arg
Numeric expression
lower
Lower bound
upper
Upper bound
... | 9e8992e4323e97dcf6524e0275aac701fae5a305 | 3,643,929 |
def human_time_duration(seconds: int) -> str:
"""For a passed-in integer (seconds), return a human-readable duration string.
"""
if seconds <= 1:
return '<1 second'
parts = []
for unit, div in TIME_DURATION_UNITS:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
... | 714c5a90fb298deb9652703625c78c19e384296e | 3,643,930 |
def reindex_network_nodes(network):
"""Reindex the nodes of a channel network."""
node_reindexer = SegmentNodeReindexer()
network.for_each(node_reindexer)
return network | d98c6f2a8c1e2c6b1d1a79e80d873f7437f33401 | 3,643,931 |
def avg_arrays_1d(data, axis=None, weights=None, **kws):
"""Average list of 1D arrays or curves by interpolation on a reference axis
Parameters
----------
data : lists of lists
data_fmt : str
define data format
- "curves" -> :func:`curves_to_matrix`
- "lists" -> :func:`curve... | 31b441b5e8884c20b664466435af0cd54f3d4c03 | 3,643,933 |
def _is_double(arr):
"""
Return true if the array is doubles, false if singles, and raise an error if it's neither.
:param arr:
:type arr: np.ndarray, scipy.sparse.spmatrix
:return:
:rtype: bool
"""
# Figure out which dtype for data
if arr.dtype == np.float32:
return False
... | f476d5cf088c2dc8877858099978cb4a47dcd6de | 3,643,934 |
def HfcVd(M, far='default'):
"""
Computes the vitual dimensionality (VD) measure for an HSI
image for specified false alarm rates. When no false alarm rate(s) is
specificied, the following vector is used: 1e-3, 1e-4, 1e-5.
This metric is used to estimate the number of materials in an HSI scene.
... | d70813a914ff6c210f2084d2f576499f1bea46cc | 3,643,935 |
def load_multicenter_aids_cohort_study(**kwargs):
"""
Originally in [1]::
Siz: (78, 4)
AIDSY: date of AIDS diagnosis
W: years from AIDS diagnosis to study entry
T: years from AIDS diagnosis to minimum of death or censoring
D: indicator of death during follow up
... | a318fcf1397d4a26d98843fc32e9d75393d7ca03 | 3,643,936 |
def bomb():
"""Bomb context appropriate for testing all simple wires cases."""
bomb = Bomb()
bomb.serial = 'abc123'
bomb.batteries = True
bomb.labels = ['FRK']
return bomb | 20ba13d5c61272dc1ebad8d05d618025659d873f | 3,643,937 |
def get_loss(pred, label):
"""
:param pred: BxNxC
:param label: BxN
:param smpw: BxN
:return:
"""
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=label, logits=pred)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
tf.add_to_coll... | 9b70057cf9019d9352e4795a6908827e2cfbc15a | 3,643,939 |
def calculate_prec_at_k(k, prediction, target):
"""
Calculating precision at k.
"""
best_k_pred = prediction.argsort()[:k]
best_k_target = target.argsort()[:k]
return len(set(best_k_pred).intersection(set(best_k_target))) / k | 61637938078b938e90f6ada70888512a97435ca1 | 3,643,940 |
def get_ttl(cur):
"""Get the 'extract' table as lines of Turtle (the lines are returned as a list)."""
# Get ttl lines
cur.execute(
"""WITH literal(value, escaped) AS (
SELECT DISTINCT
value,
replace(replace(replace(value, '\\', '\\\\'), '"', '\\"'), '
... | 454b843bfc47b5a6f11cc06ea881773421499eed | 3,643,941 |
import numpy
def pnm80(date1, date2):
"""
Wrapper for ERFA function ``eraPnm80``.
Parameters
----------
date1 : double array
date2 : double array
Returns
-------
rmatpn : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - -
e r a P n ... | e88ca2b9398a0403530c00925b0a25df85b5dbb0 | 3,643,942 |
def db_table_ddl(conn, table_name, table_cols, table_seqs, table_cons, **kwargs):
""" Generate create table DDL
"""
# Sequences
if table_seqs:
for s_ in table_seqs:
c_ = _t.m.daffkv(table_cols, "col_name", s_["col_name"])
if c_:
c_["is_seq"] = True
... | ad053a7999a57d295481533de5edf1a5bc7725d4 | 3,643,943 |
def ne_to_wgs(northing, easting):
"""
Convert Northings and Eastings (NAD 83 Alaska Albers
Equal Area Conic) to WGS84 lat/long .
:param northing: AK Albers in meters
:param easting: AK Albers in meters
:returns: transformed coordinates in WGS84 lat long
"""
wgspoint = osr.SpatialReferen... | a282958652f2edc4707fd09068c06b40341b1d54 | 3,643,944 |
import random
def check_for_greeting(sentence, context):
"""If any of the words in the user's input was a greeting, return a greeting response"""
if (sentence.strip() in GREETING_KEYWORDS) and (context==True):
return getCurrentTimeGreeting()+", "+random.choice(GREETING_RESPONSES)
else:
ret... | 5a7fc501deb283c0a57cf3303cd3f533c8ea27da | 3,643,945 |
def user_is_aidant(view=None, redirect_field_name="next"):
"""
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
requires the user to be :term:`allowed to create mandats`.
By default, this redirects users to home of espace aidants.
"""
def test(user):
return user.ca... | c5f4577aba513f7f0c3206637209c6fe0b28a20d | 3,643,946 |
from datetime import datetime
def get_time_zone_offset(time_zone, date_time=None):
"""
Returns the time zone offset (e.g. -0800) of the time zone for given datetime
"""
date_time = datetime.now(utc) if date_time is None else date_time
return _format_time_zone_string(time_zone, date_time, '%z') | b52c87fcb94044dded0aca53b4340a1afc1ac20b | 3,643,947 |
import torch
def loss_fn_kd(scores, target_scores, T=2.):
"""Compute knowledge-distillation (KD) loss given [scores] and [target_scores].
Both [scores] and [target_scores] should be tensors, although [target_scores] should be repackaged.
'Hyperparameter': temperature"""
device = scores.device
l... | 2a68cc317731cb98c1bfd5ea7e4eb878b9b9cfb7 | 3,643,948 |
def geom_cooling(temp, k, alpha = 0.95):
"""Geometric temperature decreasing."""
return temp * alpha | 4263e4cc8a5de21d94bc560e8ff364d8c07f97fd | 3,643,949 |
def metadata_version(metadata, osmelem, grp_feat, res_feat, feature_suffix):
"""Compute the version-related features of metadata and append them into
the metadata table
Parameters
----------
metadata: pd.DataFrame
Metadata table to complete
osmelem: pd.DataFrame
original data us... | 3ad4c51bc471f5be3ab8d6e211ce17cb56ec8b52 | 3,643,950 |
def train_lin_reg():
"""Trains a LR model and persists it as pickle file"""
return render_template(
'default_html.html',
endpoint='train_model',
data=lr.train_model(),
) | 606e961bf67cb6c3fe19093592cc390352b9101f | 3,643,951 |
import re
def bytes_to_escaped_str(data, keep_spacing=False, escape_single_quotes=False):
"""
Take bytes and return a safe string that can be displayed to the user.
Single quotes are always escaped, double quotes are never escaped:
"'" + bytes_to_escaped_str(...) + "'"
gives a valid Python st... | fe8aa0ed3a8e3f2c7a2cf1aaeebc555b7281bde7 | 3,643,952 |
def _session_path():
"""
Return the path to the current session
:return:
"""
path = bpy.data.filepath
return path | 7bff6b26d8654399c8b8c04689f28dfa56300211 | 3,643,953 |
def user_auth(f):
"""Checks whether user is logged in or raises error 401."""
def decorator(*args, **kwargs):
if True is False:
abort(401)
return f(*args, **kwargs)
return decorator | 36d13ea587abc404c49e3fdb98d11a848a44de1a | 3,643,954 |
import warnings
def is_tensorrt_plugin_loaded():
"""Check if TensorRT plugins library is loaded or not.
Returns:
bool: plugin_is_loaded flag
"""
# Following strings of text style are from colorama package
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31... | 98db366dbb7f8fcce425381c229d85ea1e231160 | 3,643,955 |
import urllib
import json
def check_md5(config):
"""
Find MD5 hash in providers.
:param config: Parameters object
:type config: Parameters
:return: plain string with text or exception if not found hash
:rtype: str
:raises: HashNotFound, InvalidHashFormat
"""
if not isinstance(co... | b5b493f73cc3d5041e2449f39d374d4a0b01ea6a | 3,643,956 |
def is_polindrom(string):
""" This function checks whether the given string is a polindrom or not. """
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True | 94e3cdb68c538da7b18e4567dc62fb35a58ebebb | 3,643,957 |
def sensitive_file_response(file):
""" This function is helpful to construct your own views that will return the
actual bytes for a sensitive image. You need to pass the literal bytes for
sensitive photos through your server in order to put security checks in front
of those bytes. So for instance you might put ... | 8e66b65943b28ee3c7fce0e2f29df60da43be4de | 3,643,959 |
def get_unmapped_read_count_from_indexed_bam(bam_file_name):
"""
Get number of unmapped reads from an indexed BAM file.
Args:
bam_file_name (str): Name of indexed BAM file.
Returns:
int: number of unmapped reads in the BAM
Note:
BAM must be indexed for lookup using samtool... | 9088ab1476703d5c845b9c1bed960eb2209e0b5d | 3,643,960 |
from re import T
def model_setup(model_dict, X_train, y_train, X_test, y_test, X_val,
y_val, rd=None, layer=None):
"""
Main function to set up network (create, load, test, save)
"""
rev = model_dict['rev']
dim_red = model_dict['dim_red']
if rd != None:
# Doing dimensio... | 4a17d298a1ea3574ba21d651e0bfc4da957c01f4 | 3,643,961 |
def AreEqual(image1, image2, tolerance=0, likely_equal=True):
"""Determines whether two images are identical within a given tolerance.
Setting likely_equal to False enables short-circuit equality testing, which
is about 2-3x slower for equal images, but can be image height times faster
if the images are not equ... | 7e9dbe469aefd089e87104100ede776996b65c83 | 3,643,962 |
def ppc_deconvolve(im, kernel, kfft=None, nchans=4,
same_scan_direction=False, reverse_scan_direction=False):
"""PPC image deconvolution
Given an image (or image cube), apply PPC deconvolution kernel
to obtain the intrinsic flux distribution.
If performing PPC deconvolution, make sure to... | a2d6b05c33591d7f5e2f25b7f51258e5433ad970 | 3,643,963 |
def split_data(ratings, min_num_ratings, p_test=0.1, verbose=False, seed=988):
"""
Splits the data set (ratings) to training data and test data
:param ratings: initial data set (sparse matrix of dimensions n items and p users)
:param min_num_ratings: all users and items must have at least min_num_rating... | 9f77f8b35465de1e97082f4ba897ecd94db33801 | 3,643,965 |
def _adjust_block(p, ip, filters, block_id=None):
"""Adjusts the input `previous path` to match the shape of the `input`.
Used in situations where the output number of filters needs to be changed.
Arguments:
p: Input tensor which needs to be modified
ip: Input tensor whose shape needs to be matched
... | 3ba9b4cc7736511dd54bd907975752c942d82fa2 | 3,643,966 |
def filter_points(points: np.array, image_width: int, image_height: int) -> np.array:
"""
function finds indexes of points that are within image frame ( within image width and height )
searches for
points with x coordinate greater than zero, less than image_width
points with y coordinate gre... | 6020984195f4f5f2a9eb8f1efde3ee186ca82328 | 3,643,968 |
import inspect
def url_of_LumpClass(LumpClass: object) -> str:
"""gets a url to the definition of LumpClass in the GitHub repo"""
script_url = LumpClass.__module__[len("bsp_tool.branches."):].replace(".", "/")
line_number = inspect.getsourcelines(LumpClass)[1]
lumpclass_url = f"{branches_url}{script_u... | dcd5adf9914055afb10b537d032c2ada32406950 | 3,643,969 |
def correlation_sum(indicators, embedding_dim):
"""
Calculate a correlation sum
Useful as an estimator of a correlation integral
Parameters
----------
indicators : 2d array
matrix of distance threshold indicators
embedding_dim : integer
embedding dimension
Returns
... | 9d5e82d6e9e4107ca14e114ed501ced67abfe25f | 3,643,970 |
def find_suitable_serializer(obj):
"""
Find serializer that is suitable for this operation
:param T obj: The object that needs to be serialized
:return: The first suitable serializer for this type of object
:rtype: mlio.io.serializers.implementations.SerializerBase
"""
for serializer in __s... | b162e5eed35e18485c1d7c21dd27de3b2fd55a47 | 3,643,971 |
def square(x):
"""Return x squared."""
return x * x | d3177d90b4d1c76c0a426b3613c17cced404db45 | 3,643,972 |
def int_div_test(equation, val):
"""
Comparison for the integer division binary search.
:equation: Equation to test
:val: Input to the division
"""
r1 = equation(val)
if r1 == None:
return None
r2 = equation(val - 1)
if r2 == None:
return None
if r1 == 1 and r2 ... | 16b9106ddb1fc7472339019926a891c6c1942d18 | 3,643,973 |
def get_market_deep(symbols=None, output_format='json', **kwargs):
"""
Top-level function to obtain DEEP data for a symbol or list of symbols
Parameters
----------
symbols: str or list, default None
A symbol or list of symbols
output_format: str, default 'json', optional
Desired... | f54dfc58835f1b10b35f54b8abd9635ffa2f5ace | 3,643,974 |
def read_ss(path, dataset, order=None):
""" Read secondary structure prediction file
using specified order or automatically determined order based on results"""
with open(path, 'r') as f:
lines = f.readlines()
lines = [line.split() for line in lines]
start = 0
length = len(dataset.sequences[0])
for i,... | 691c03ed6a0c1375a74b27bfe498d197b1820723 | 3,643,975 |
def get_model():
"""
"""
# Describe the Convolutional Neural Network
model = tf.keras.Sequential([
# Convolutions
# Pooling
# Flatten units
tf.keras.layers.Flatten(),
# Input Layer
# Avoid overfitting
# Output layer - NUM_SHAPE_TYPES units
... | cc8403ec943acdae2916554378fb9ba475400dce | 3,643,976 |
def Packet_genReadVpeMagnetometerAdvancedTuning(errorDetectionMode, buffer, size):
"""Packet_genReadVpeMagnetometerAdvancedTuning(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t"""
return _libvncxx.Packet_genReadVpeMagnetometerAdvancedTuning(errorDetectionMode, b... | f4652a1d432b5c8df2e9abacd9ea990b5a07a09d | 3,643,977 |
def compare(times_list=None,
name=None,
include_list=True,
include_stats=True,
delim_mode=False,
format_options=None):
"""
Produce a formatted comparison of timing datas.
Notes:
If no times_list is provided, produces comparison reports on ... | 7fc41c5544fb0be7569aa133e86e5bd98d8aae65 | 3,643,978 |
def spaces(elem, doc):
"""
Add LaTeX spaces when needed.
"""
# Is it in the right format and is it a Space?
if doc.format in ["latex", "beamer"] and isinstance(elem, Space):
if isinstance(elem.prev, Str) and elem.prev.text in ["«", "“", "‹"]:
return RawInline("\\thinspace{}", "te... | 68350ceeee26a6184df3a1767f725bdd65a48823 | 3,643,979 |
import re
def clean_caption(text):
"""
Remove brackets with photographer names or locations at the end of some captions
:param text: a photo caption
:return: text cleaned
"""
text = str(text)
text = re.sub(r'\s*\[.+?\]$', '.', text)
text = re.sub(r'\s*\(photo.+?\)', '', text)
retur... | f07713de58c8304e437904914c78f89c795d9776 | 3,643,980 |
def take_slasher_snapshot(client):
"""
Collects all the command changes from the client's slash command processor.
Parameters
----------
client : ``Client``
The client, who will be snapshotted.
Returns
-------
collected : `None` or `tuple` of (`dict` of (`int`, `list` o... | f932b7bc7cef8957ae6f269907427d2ad15fd641 | 3,643,981 |
def zigpy_device_mains(zigpy_device_mock):
"""Device tracker zigpy device."""
def _dev(with_basic_channel: bool = True):
in_clusters = [general.OnOff.cluster_id]
if with_basic_channel:
in_clusters.append(general.Basic.cluster_id)
endpoints = {
3: {
... | e9fff1a96e2f3d544dfb3c48b5b574f087a0d406 | 3,643,982 |
def compute_average_precision(precision, recall):
"""Compute Average Precision according to the definition in VOCdevkit.
Precision is modified to ensure that it does not decrease as recall
decrease.
Args:
precision: A float [N, 1] numpy array of precisions
recall: A float [N, 1] numpy ... | cffc91d4bab5fdaf7ae99d3babaf01348f3d1160 | 3,643,983 |
def minimize_experiment_document(document):
"""
Takes a document belonging to an experiment or to a library in an experiment
and strips it down to a subset of desired fields. This differs from other
non-experiment documents in that the attachment is a dictionary rather than
a simple string concaten... | d06c7d7f80c6f6f1e6b7808a42e3d668fe877a46 | 3,643,984 |
import pathlib
def detect_container(path: pathlib.Path) -> type[containers.Container]:
"""Detect the container of a file"""
container_type = filetype.archive_match(path)
container_mime_type = container_type.mime if container_type else None
return containers.get_container_by_mime_type(container_mime_t... | f30d625b8e4933da20c7ce707494d78b0e8c286b | 3,643,985 |
import math
def score_mod(mod, word_count, mod_count, mod_match_unlabel):
"""计算模式的评分"""
p = word_count[mod]
u = len(mod_match_unlabel[mod])
t = mod_count[mod]
return (p / t) * math.log(u + 1, 2) * math.log(p + 1, 2) | 1184800a2b6a2ebfbbbdcbcbf4a0d8f8cb261e98 | 3,643,986 |
def get_matrix(costs='direct'):
"""Table used to compare the most appropriate building class for DCs"""
health_care = eeio(['233210/health care buildings/us'], [1])
manu_bldg = eeio(['233230/manufacturing buildings/us'], [1])
util_bldg = eeio(['233240/utilities buildings and infrastructure/us'], [1])
... | ba77546026f03cee45224c9b5338296db79db56d | 3,643,987 |
def redshift_resource(context):
"""This resource enables connecting to a Redshift cluster and issuing queries against that
cluster.
Example:
.. code-block:: python
from dagster import ModeDefinition, execute_solid, solid
from dagster_aws.redshift import redshift_resource
... | 55f59c34f2102c69b11a6e6a1fc3bd09a87f96af | 3,643,988 |
def ifft2(a, s=None, axes=(-2, -1), norm=None):
"""Compute the two-dimensional inverse FFT.
Args:
a (cupy.ndarray): Array to be transform.
s (None or tuple of ints): Shape of the transformed axes of the
output. If ``s`` is not given, the lengths of the input along the
ax... | fc8c73fec7d8bd46f86cf5e3051747915bc5e2db | 3,643,989 |
def get_displayable_story_summary_dicts(user_id, story_summaries):
"""Returns a displayable summary dict of the story summaries
given to it.
Args:
user_id: str. The id of the learner.
story_summaries: list(StorySummary). A list of the
summary domain objects.
Returns:
... | 8ae157e824e42173674d3c15704e032a3d3c406d | 3,643,990 |
from fuzzy.Exception import FuzzyException
def checkRange(value, ranges):
"""Checks if the value is in the defined range.
The range definition is a list/iterator from:
- float values belonging to the defined range M{x \in {a}}
- 2-tuples of two floats which define a range not including th... | 49907dfe7a18054eb710bac9e3ec38e459d85e9b | 3,643,991 |
import json
def read_anno_content(anno_file: str):
"""Read anno content."""
with open(anno_file) as opened:
content = json.load(opened)
return content | 208d5f92d479ebfc0aa1e93d26ca68d3ce2a1e7e | 3,643,992 |
def openRotatorPort(portNum=0, timeout=5):
"""
Open a serial port for the rotator
Open commport ``portNum`` with a timeout of ``timeout``.
Parameters
----------
portNum : integer, default: 0
commport for the serial connection to the rotator
timeout : number, default: 5 sec
... | e479e41a11591964f1a7cf9ea88a4bbbc51e943c | 3,643,993 |
from typing import List
from typing import Dict
def disable_poll_nodes_list(
nodes: List[str],
credentials: HTTPBasicCredentials = Depends(
check_credentials
), # pylint: disable=unused-argument
) -> Dict[str, str]:
"""Disable (snmp) polling on a list of nodes.
Exple of simplest call :
... | 18900b0458c2a5b358d82ffdb4ed4ab9e382410d | 3,643,994 |
import re
import json
def twitter_sp(name):
"""
This function is dedicated to extract location names from Twitter data(.txt file)
:param name: str, filename
:return: None
"""
def twitter_profile(user):
"""
This function fetch the the Twitter user's profiles for the location in... | 4bff0e862d9d7be250687363693dcb8f33713b03 | 3,643,995 |
def extrudePoints(points, disp):
"""
Return a list of points including the initial points and extruded end
"""
farEnd=deepcopy(points)
farEnd[:,0]+=disp[0]
farEnd[:,1]+=disp[1]
farEnd[:,2]+=disp[2]
return np.vstack( (points,farEnd) ) | c544ef372bb621bd6a96f9e91147bec6b1be800d | 3,643,996 |
def hex_form(hash):
"""Returns the hash formatted in hexadecimal form"""
final_hash = ''
for i in range(len(hash)):
final_hash += format(hash[i], '02x')
return final_hash | 67c1d376352517a9f368dfc56f03f1af3d45e128 | 3,643,997 |
import itertools
def rangeFromString(commaString):
""" Convert a comma string like "1,5-7" into a list [1,5,6,7]
Returns
--------
myList : list of integers
Reference
-------
http://stackoverflow.com/questions/6405208/\
how-to-convert-numeric-string-ranges-to-a-list-in-python
"""
... | f0a176e35c71882edbc64a515022346e199c08cb | 3,643,998 |
def wup(synset1: Synset, synset2: Synset) -> float:
"""Return the Wu-Palmer similarity of *synset1* and *synset2*."""
lch = synset1.lowest_common_hypernyms(synset2, simulate_root=True)[0]
n = lch.max_depth() + 1
n1 = len(synset1.shortest_path(lch, simulate_root=True))
n2 = len(synset2.shortest_path(... | 8e49126143fec99211abcafe04aa1f6fdb275e3a | 3,643,999 |
from typing import List
def sum_per_agent(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Calculates summed values per agent for each given column individually"""
all_values_per_agent = pd.DataFrame(columns=columns)
for column in columns:
function = calc_sum(column)
value_per_age... | b828e68a2f2555b9b12f4c17376a7f88211611d4 | 3,644,000 |
def calc_one_sample_metric(sample):
""" 计算 V1 数据一个样本的 rouge-l 和 bleu4 分数 """
if len(sample['best_match_scores']) == 0: # bad case
return -1, -1
pred_answers, ref_answers = [], []
pred_answers.append({'question_id': sample['question_id'],
'question_type': sample['quest... | 37ce17d36e2d6b31e0fdae29172de442d87fd676 | 3,644,002 |
def ta_1d(x, a, w_0, w_1):
"""1d tanh function."""
return a * np.tanh(w_0 + (w_1 * x)) | ce062d87f3040d95d8bc5360a58b0b7c4625e877 | 3,644,003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.