content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def set_edge_font_size_mapping(table_column, table_column_values=None, sizes=None, mapping_type='c', default_size=None,
style_name=None, network=None, base_url=DEFAULT_BASE_URL):
"""Map table column values to sizes to set the edge size.
Args:
table_column (str): Name of C... | 7360f57d1e4921d58eaf5af4e57a6c5f636fefdb | 20,500 |
def compute_time_overlap(appointment1, appointment2):
"""
Compare two appointments on the same day
"""
assert appointment1.date_ == appointment2.date_
print("Checking for time overlap on \"{}\"...".
format(appointment1.date_))
print("Times to check: {}, {}".
format(appointmen... | c459ef52d78bc8dd094d5be9c9f4f035c4f9fcaa | 20,501 |
def set_up_prior(data, params):
"""
Function to create prior distribution from data
Parameters
----------
data: dict
catalog dictionary containing bin endpoints, log interim prior, and log
interim posteriors
params: dict
dictionary of parameter values for creation of pri... | eb75965b9425bbf9fe3a33b7f0c850e27e2d454a | 20,502 |
def is_nonincreasing(arr):
""" Returns true if the sequence is non-increasing. """
return all([x >= y for x, y in zip(arr, arr[1:])]) | 6d78ef5f68ca93767f3e204dfea2c2be8b3040af | 20,503 |
def restore_missing_features(nonmissing_X, missing_features):
"""Insert columns corresponding to missing features.
Parameters
----------
nonmissing_X : array-like, shape (n_samples, n_nonmissing)
Array containing data with missing features removed.
missing_features : array-like, shape (n_m... | 733fd72d36ea86269472949eaa12a306835578f9 | 20,504 |
def get_sample_type_from_recipe(recipe):
"""Retrieves sample type from recipe
Args:
recipe: Recipe of the project
Returns:
sample_type_mapping, dic: Sample type of the project
For Example:
{ TYPE: "RNA" } , { TYPE: "DNA" }, { TYPE: "WGS" }
"""
return find_mapping(recipe_type_mapping, recipe) | 57cef2f592d530ad15aed47cc51da4441430f3d2 | 20,505 |
import yaml
def _is_download_necessary(path, response):
"""Check whether a download is necessary.
There three criteria.
1. If the file is missing, download it.
2. The following two checks depend on each other.
1. Some files have an entry in the header which specifies when the file was
... | 69cd2778fb6d4706ff88bd35c1b5c1abda9a39ba | 20,506 |
import hashlib
def hash64(s):
"""Вычисляет хеш - 8 символов (64 бита)
"""
hex = hashlib.sha1(s.encode("utf-8")).hexdigest()
return "{:x}".format(int(hex, 16) % (10 ** 8)) | e35a367eac938fdb66584b52e1e8da59582fdb9a | 20,507 |
def course_runs():
"""Fixture for a set of CourseRuns in the database"""
return CourseRunFactory.create_batch(3) | 1ffd4efe008e44f9e2828c9128acfe3cdafb5160 | 20,508 |
import json
def _response(data=None, status_code=None):
"""Build a mocked response for use with the requests library."""
response = MagicMock()
if data:
response.json = MagicMock(return_value=json.loads(data))
if status_code:
response.status_code = status_code
response.raise_for_st... | 0ccd38a954d28a4f010becc68319b49896323de0 | 20,509 |
def findtailthreshold(v, figpath=None):
"""
function [f,mns,sds,gmfit] = findtailthreshold(v,wantfig)
<v> is a vector of values
<wantfig> (optional) is whether to plot a diagnostic figure. Default: 1.
Fit a Gaussian Mixture Model (with n=2)
to the data and find the point that is greater t... | 8ef0c3267582d604621bd98fa7c81976b76b2c51 | 20,510 |
from typing import Optional
from typing import Dict
import asyncio
async def make_request_and_envelope_response(
app: web.Application,
method: str,
url: URL,
headers: Optional[Dict[str, str]] = None,
data: Optional[bytes] = None,
) -> web.Response:
"""
Helper to forward a request to the ca... | 22d18de671cc84d3471120273a7b0599fda26210 | 20,511 |
import os
def _app_node(app_id, existing=True):
"""Returns node path given app id."""
path = os.path.join(z.SCHEDULED, app_id)
if not existing:
path = path + '#'
return path | dca3abc7376c50f015a64767333432b89a2d7009 | 20,512 |
def get_provincial_miif_sets(munis):
"""
collect set of indicator values for each province, MIIF category and year
returns dict of the form {
'cash_coverage': {
'FS': {
'B1': {
'2015': [{'result': ...}]
}
}
}
}
"""
prov_sets = defaultdi... | a4484a40a30f8fe9e702735f6eccf78c395ea446 | 20,513 |
def create_kernel(radius=2, invert=False):
"""Define a kernel"""
if invert:
value = 0
k = np.ones((2*radius+1, 2*radius+1))
else:
value = 1
k = np.zeros((2*radius+1, 2*radius+1))
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask = x**2 ... | 33bbfa6141eb722180ffa9111555e4e00fbdac6a | 20,514 |
def edimax_get_power(ip_addr="192.168.178.137"):
"""
Quelle http://sun-watch.net/index.php/eigenverbrauch/ipschalter/edimax-protokoll/
"""
req = """<?xml version="1.0" encoding="UTF8"?><SMARTPLUG id="edimax"><CMD id="get">
<NOW_POWER><Device.System.Power.NowCurrent>
</Device.System.Power.No... | 9de1720f00ca4194b66f79048314bac1cac950ed | 20,515 |
import torch
def get_class_inst_data_params_n_optimizer(nr_classes, nr_instances, device):
"""Returns class and instance level data parameters and their corresponding optimizers.
Args:
nr_classes (int): number of classes in dataset.
nr_instances (int): number of instances in dataset.
... | f97e12b99a42f32bb3629df5567ca44477d71dc0 | 20,516 |
def inc(x):
""" Add one to the current value """
return x + 1 | c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c | 20,517 |
def regionError(df, C, R):
"""Detects if a selected region is not part of one of the selected countries
Parameters:
-----------
df : Pandas DataFrame
the original dataset
C : str list
list of selected countries
R : str list
list of selected regions
Returns
---... | 53e237bba7c1696d23b5f1e3c77d4b2d2a4c9390 | 20,518 |
def lherzolite():
"""
Elastic constants of lherzolite rock (GPa) from
Peselnick et al. (1974), in Voigt notation
- Abbreviation: ``'LHZ'``
Returns:
(tuple): tuple containing:
* C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``)
* rho (float): Density (3270 ... | 4d7e16fcfc1732ee3a881d4b1c2d755bbd9035f3 | 20,519 |
def int_to_bit(x_int, nbits, base=2):
"""Turn x_int representing numbers into a bitwise (lower-endian) tensor."""
x_l = tf.expand_dims(x_int, axis=-1)
x_labels = []
for i in range(nbits):
x_labels.append(
tf.floormod(
tf.floordiv(tf.to_int32(x_l),
tf.to_int32(base... | a9529c737e058da664d31055aa85cc7e6179f585 | 20,520 |
def create_ldap_external_user_directory_config_content(server=None, roles=None, role_mappings=None, **kwargs):
"""Create LDAP external user directory configuration file content.
"""
entries = {
"user_directories": {
"ldap": {
}
}
}
entries["user_directories"]... | baaf3d7a02f2f4e18c3ccddb7f3ff4d5b379c1d4 | 20,521 |
def intersection(lst1, lst2):
"""!
\details Finds hashes that are common to both lists and stores their location in both documents
Finds similarity that is measured by
sim(A,B) = number of hashes in intersection of both hash sets divided by minimum of the number of hashes in lst1 and lst2
\param l... | 7288e523e743fda89596e56f217aac8c87899b50 | 20,522 |
def allrad2(F_nm, hull, N_sph=None, jobs_count=1):
"""Loudspeaker signals of All-Round Ambisonic Decoder 2.
Parameters
----------
F_nm : ((N_sph+1)**2, S) numpy.ndarray
Matrix of spherical harmonics coefficients of spherical function(S).
hull : LoudspeakerSetup
N_sph : int
Decod... | a34cfd7719c36dd8abf1313e3eca4aa2ce49477b | 20,523 |
import os
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
from skimage.exposure import match_histograms
def match_histogram(reference, image, ref_mask=None, img_mask=None):
"""Match the histogram of the T2-like anatomical with the EPI."""
nii_img = nb.load(image)
... | 3af65929e05955d297ae11ea6e8cd77884b544b9 | 20,524 |
def outfeed(token, xs):
"""Outfeeds value `xs` to the host. Experimental.
`token` is used to sequence infeed and outfeed effects.
"""
flat_xs, _ = pytree.flatten(xs)
return outfeed_p.bind(token, *flat_xs) | 1b4b8c289ebd5dbb90ddd7b565c98ea9ebaec038 | 20,525 |
def add_gaussian_noise(images: list, var: list, random_var: float=None, gauss_noise: list=None):
"""
Add gaussian noise to input images. If random_var and gauss_noise are given, use them to compute the final images.
Otherwise, compute random_var and gauss_noise.
:param images: list of images
:param ... | e453f1fda24ec428eb1e33aec87db9456fa015b2 | 20,526 |
def get_sso_backend():
"""
Return SingleSignOnBackend class instance.
"""
return get_backend_instance(cfg.CONF.auth.sso_backend) | 4c2a9b857006405f804826b1c096aa8d828d6e42 | 20,527 |
def conv_relu_pool_forward(x, w, b, conv_param, pool_param):
"""
Convenience layer that performs a convolution, a ReLU, and a pool.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
- pool_param: Parameters for the pooling layer
Returns a tuple... | 20d5f3d4b30edd91ef54b53a7b09882b3e2ab9b8 | 20,528 |
def ConnectWithReader(readerName, mode):
""" ConnectWithReader """
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != SCARD_S_SUCCESS:
raise EstablishContextException(hresult)
hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, readerName,
mode, SCARD_PROTOC... | af7606fb9ad669185c7a655967d0193b59404fe1 | 20,529 |
def interpolate(points: type_alias.TensorLike,
weights: type_alias.TensorLike,
indices: type_alias.TensorLike,
normalize: bool = True,
allow_negative_weights: bool = False,
name: str = "weighted_interpolate") -> type_alias.TensorLike:
"""... | 13d49a570ac482a0b2b76ab0bb49bf7994df7204 | 20,530 |
def calcADPs(atom):
"""Calculate anisotropic displacement parameters (ADPs) from
anisotropic temperature factors (ATFs).
*atom* must have ATF values set for ADP calculation. ADPs are returned
as a tuple, i.e. (eigenvalues, eigenvectors)."""
linalg = importLA()
if not isinstance(atom, ... | 0a0a0db2ca99d4a3b754acb9cd22ec4659af948f | 20,531 |
def _create_groups(properties):
"""Create a tree of groups from a list of properties.
Returns:
Group: The root group of the tree. The name of the group is set to None.
"""
# We first convert properties into a dictionary structure. Each dictionary
# represents a group. The None key correspon... | bb3c582074c718250a1eb16a29830242b4ccaa5f | 20,532 |
def bitset(array, bits):
"""
To determine if the given bits are set in an array.
Input Parameters
----------------
array : array
A numpy array to search.
bits : list or array
A list or numpy array of bits to search.
Note that the "first" bit is denoted as zero,
w... | cbae61dabfbe0789ff349f12b0df43860db72df7 | 20,533 |
import os
def build_classifier_pipeline(
input_files,
output_files,
config,
use_fake_tables = False,
converter_impl = ConverterImplType.PYTHON,
):
"""Pipeline for converting finetuning examples."""
if len(output_files) != len(input_files):
raise ValueError(f'Size mismatch: {output_files} ... | 04c62ac25e3161316858f0e77cafc6796130d160 | 20,534 |
from typing import OrderedDict
def sample_gene_matrix(request, variant_annotation_version, samples, gene_list,
gene_count_type, highlight_gene_symbols=None):
""" highlight_gene_symbols - put these genes 1st """
# 19/07/18 - Plotly can't display a categorical color map. See: https://gith... | 70ed9387ebba73664efdf3c94fe08a67ed07acc9 | 20,535 |
import requests
import yaml
import os
def validate_yaml_online(data, schema_uri=None):
"""
Validates the given data structure against an online
schema definition provided by schema_uri.
If schema_uri is not given, we try to get it from
the 'descriptor_schema' field in 'data'.
Returns: True/Fal... | 624b9aa706fc0afda24bf9c0afc8756637c8a9bd | 20,536 |
import random
def normal218(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(zz2)... | aec17f55306691395dc2797cf30e175e0cb5b9e8 | 20,537 |
def get_fast_loaders(dataset, batch_size, test, device, data_path=None, train_transform=None, validation_transform=None,
train_percentage=0.85, workers=4):
"""Return :class:`FastLoader` for training and validation, outfitted with a random sampler.
If set to run on the test set, :param:`tra... | 444ff949ba247ebc21f1e34fcfcb752ccbf6360d | 20,538 |
from typing import List
def find_paths(root: TreeNode, required_sum: int) -> List[List[int]]:
"""
Time Complexity: O(N^2)
Space Complexity: O(N)
Parameters
----------
root : TreeNode
Input binary tree.
required_sum : int
Input number 'S'.
Returns
-------
all_p... | 71cd37db1be97015173748e8d2142601e306552b | 20,539 |
import time
import requests
import json
def macro_bank_switzerland_interest_rate():
"""
瑞士央行利率决议报告, 数据区间从20080313-至今
https://datacenter.jin10.com/reportType/dc_switzerland_interest_rate_decision
https://cdn.jin10.com/dc/reports/dc_switzerland_interest_rate_decision_all.js?v=1578582240
:return: 瑞士央... | 14eb2ce7dc85e0611a8d55147172256ed8a2c71e | 20,540 |
def create_dataframe(message):
"""Create Pandas DataFrame from CSV."""
dropdowns = []
df = pd.DataFrame()
if message != "":
df = pd.read_csv(message)
df = df.sample(n = 50, random_state = 2) # reducing Data Load Running on Heroku Free !!!!
if len(df) == 0:
return pd.D... | c0d764ed47cba31d0129d1c61e645065ba2e99b5 | 20,541 |
def load_model(path):
"""
This function ...
:param path:
:return:
"""
# Get the first line of the file
with open(path, 'r') as f: first_line = f.readline()
# Create the appropriate model
if "SersicModel" in first_line: return SersicModel.from_file(path)
elif "ExponentialDiskMo... | 425113abe09b1de1efa1d5cf1ca2df4d999886c2 | 20,542 |
import functools
def add_metaclass(metaclass):
"""
Class decorator for creating a class with a metaclass.
Borrowed from `six` module.
"""
@functools.wraps(metaclass)
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not Non... | f6ee3feef418d5bff4f0495fdbfc98c9a8f48665 | 20,543 |
import torch
def max_pool_nd_inverse(layer, relevance_in : torch.Tensor, indices : torch.Tensor = None,
max : bool = False) -> torch.Tensor :
"""
Inversion of LogSoftmax layer
Arguments
---------
relevance : torch.Tensor
Input relavance
indices : torch.Ten... | ae3ad1b2a3791063c90568f0c954d3de6f3985f8 | 20,544 |
def aroon_up(close, n=25, fillna=False):
"""Aroon Indicator (AI)
Identify when trends are likely to change direction (uptrend).
Aroon Up - ((N - Days Since N-day High) / N) x 100
https://www.investopedia.com/terms/a/aroon.asp
Args:
close(pandas.Series): dataset 'Close' column.
n(... | 2a44c15b06e9a1d2facaa800a186b780fc226717 | 20,545 |
import os
import hashlib
def hash_file(filename):
"""
computes hash value of file contents, to simplify pytest assert statements for
complex test cases that output files. For cross-platform compatibility, make sure
files are read/written in binary, and use unix-style line endings, otherwise hashes
... | e26f92869a44c0e60fcd58764069b0c7828dee95 | 20,546 |
def spatial_batchnorm_forward(x, gamma, beta, bn_param):
"""
Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- bn_param: Dictionary with the following keys... | 0b27b4b00e21de2117a1f079741f0b968fd30042 | 20,547 |
def triangulate(points):
""" triangulate the plane for operation and visualization
"""
num_points = len(points)
indices = np.arange(num_points, dtype=np.int)
segments = np.vstack((indices, np.roll(indices, -1))).T
tri = pymesh.triangle()
tri.points = np.array(points)
tri.segments = seg... | d18a7d171715217b59056337c86bf5b49609b664 | 20,548 |
def immutable():
""" Get group 1. """
allowed_values = {'NumberOfPenguins', 'NumberOfSharks'}
return ImmutableDict(allowed_values) | 851853b54b106cbc3ee621119a863a7b2862e8d5 | 20,549 |
def test_plot_colors_sizes_proj(data, region):
"""
Plot the data using z as sizes and colors with a projection.
"""
fig = Figure()
fig.coast(region=region, projection="M15c", frame="af", water="skyblue")
fig.plot(
x=data[:, 0],
y=data[:, 1],
color=data[:, 2],
size... | 4a9f2727d046d91445504d8f147fcef95a261cb5 | 20,550 |
def predict_to_score(predicts, num_class):
"""
Checked: the last is for 0
===
Example: score=1.2, num_class=3 (for 0-2)
(0.8, 0.2, 0.0) * (1, 2, 0)
:param predicts:
:param num_class:
:return:
"""
scores = 0.
i = 0
while i < num_class:
scores += i * ... | ee4038583404f31bed42bed4eaf6d0c25684c0de | 20,551 |
def quasi_diagonalize(link):
"""sort clustered assets by distance"""
link = link.astype(int)
sort_idx = pd.Series([link[-1, 0], link[-1, 1]])
num_items = link[-1, 3] # idx of original items
while sort_idx.max() >= num_items:
sort_idx.index = list(range(0, sort_idx.shape[0] * 2, 2)) # make ... | 8f10f62d5f0b3dc7b8687134497dd42f183194b4 | 20,552 |
import os
import fnmatch
def dataset_files(rootdir, pattern):
"""Returns a list of all image files in the given directory"""
matches = []
for root, dirnames, filenames in os.walk(rootdir):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))... | b99d24d48b26393cc7cbf4df9e7cd7f1d7c018e0 | 20,553 |
def keyword(variable):
"""
Verify that the field_name isn't part of know Python keywords
:param variable: String
:return: Boolean
"""
for backend in ADAPTERS:
if variable.upper() in ADAPTERS[backend]:
msg = (
f'Variable "{variable}" is a "{backend.upper()}" '
... | b1c6322d3ce3c9ee4bda4eff251af44ca3e2c699 | 20,554 |
import logging
import json
def gcp_api_main(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/... | 21ec4b1dba4ad6f5dac518a3907cd15579a0ba00 | 20,555 |
def box_area_3d(boxes: Tensor) -> Tensor:
"""
Computes the area of a set of bounding boxes, which are specified by its
(x1, y1, x2, y2, z1, z2) coordinates.
Arguments:
boxes (Union[Tensor, ndarray]): boxes for which the area will be computed. They
are expected to be in (x1, y1, ... | be8b3c4d58d301d2044e7cfe2844516933c1247f | 20,556 |
from sqlalchemy import create_mock_engine
import re
def mock_engine(dialect_name=None):
"""Provides a mocking engine based on the current testing.db.
This is normally used to test DDL generation flow as emitted
by an Engine.
It should not be used in other cases, as assert_compile() and
assert_sq... | d773a6e2cd0b2060e5dd66d5ec4e758ac7f1f504 | 20,557 |
def get_feedback_thread_reply_info_by_reply_to_id(reply_to_id):
"""Gets the domain object corresponding to the model which is fetched by
reply-to-id field.
Args:
reply_to_id: str. The reply_to_id to search for.
Returns:
FeedbackThreadReplyInfo or None. The corresponding domain object.
... | e27521030717a1dc15cd9e678dabafba86007f90 | 20,558 |
def _cross_correlations(n_states):
"""Returns list of crosscorrelations
Args:
n_states: number of local states
Returns:
list of tuples for crosscorrelations
>>> l = _cross_correlations(np.arange(3))
>>> assert l == [(0, 1), (0, 2), (1, 2)]
"""
l = n_states
cross_corr =... | c11c5655ba655a29991421c6627a3eaca4f7681d | 20,559 |
def select_interface(worker):
"""
It gets a worker interface channel to do something.
"""
interfaces = worker.interfaces_list()
if len(interfaces) == 0:
print ' Error. Worker without interface known.'
return -1
elif len(interfaces) == 1:
return 1
option = raw_input('... | 97d90670dd69d57b4e1f85df250a0abc56106fb6 | 20,560 |
def get_middle(arr):
"""
Get middle point ????
"""
n_val = np.array(arr.shape) / 2.0
n_int = n_val.astype(np.int0)
# print(n_int)
if n_val[0] % 2 == 1 and n_val[1] % 2 == 1:
return arr[n_int[0], n_int[1]]
if n_val[0] % 2 == 0 and n_val[1] % 2 == 0:
return np.average(arr[... | 9651bcadc991bbf7a0c635a8870356f422d43e7e | 20,561 |
def annotate_segmentation(image, segmentation):
"""Return annotated segmentation."""
annotation = AnnotatedImage.from_grayscale(image)
for i in segmentation.identifiers:
region = segmentation.region_by_identifier(i)
color = pretty_color()
annotation.mask_region(region.border.dilate()... | 2fadbe8d2339e37bea0dbfe054199002a3997b20 | 20,562 |
def get_champ_data(champ: str, tier: int, rank: int):
"""
Gives Champ Information by their champname, tier, and rank.
"""
champ_info = NewChampsDB()
try:
champ_info.get_data(champ, tier, rank)
champs_dict = {
"name": f"{champ_info.name}",
"released": champ_i... | 7d810fc5ced3d187c68533f42c2443ef8bec651b | 20,563 |
import http
import os
def handler(event, context):
"""
Handler method for insert resource function.
"""
if event is None:
return response(http.HTTPStatus.BAD_REQUEST, Constants.error_insufficient_parameters())
if event is None or Constants.event_body() not in event or Constants.event_http_... | 671144bed701c8bd2480b86522bd2002ccd35e73 | 20,564 |
def serving_input_receiver_fn():
"""This is used to define inputs to serve the model.
Returns:
A ServingInputReciever object.
"""
csv_row = tf.placeholder(shape=[None], dtype=tf.string)
features, _ = _make_input_parser(with_target=False)(csv_row)
return tf.estimator.export.ServingInputReceiver(features... | bcc6f0c4050d40df114ba4e5d895524f736b463a | 20,565 |
import time
def offsetTimer():
"""
'Starts' a timer when called, returns a timer function that returns the
time in seconds elapsed since the timer was started
"""
start_time = time.monotonic()
def time_func():
return time.monotonic() - start_time
return time_func | 348105a408ccedd1fcb840b73d5a58dfd59dd8cc | 20,566 |
import os
def _get_sender(pusher_email):
"""Returns "From" address based on env config and default from."""
use_author = 'GITHUB_COMMIT_EMAILER_SEND_FROM_AUTHOR' in os.environ
if use_author:
sender = pusher_email
else:
sender = os.environ.get('GITHUB_COMMIT_EMAILER_SENDER')
return ... | 09167bfd09ff031d60b4ca033fbb0cad206393f9 | 20,567 |
from typing import Callable
import functools
def find_resolution(func: Callable = None) -> Callable:
"""Decorator that gives the decorated function the image resolution."""
@functools.wraps(func)
def wrapper(self: MultiTraceChart, *args, **kwargs):
if 'width' not in kwargs:
kwargs['wi... | 70edffcec5ac772bd52cb819db589d26497fda87 | 20,568 |
def transform_spikes_to_isi(self, spikes, time_epoch, last_event_is_spike=False):
"""Convert spike times to data array, which is a suitable format for optimization.
Parameters
----------
spikes : numpy array (num_neuron,N), dtype=np.ndarray
A sequence of spike times for each neuron on each tri... | cc2b54e80e00b10b8cabf79093509fde1980b804 | 20,569 |
def api_github_v2(user_profile, event, payload, branches, default_stream, commit_stream, issue_stream, topic_focus = None):
"""
processes github payload with version 2 field specification
`payload` comes in unmodified from github
`default_stream` is set to what `stream` is in v1 above
`commit_stream... | bed307903d7ddcce216919d18accb3ecfd94937d | 20,570 |
from typing import Iterable
from typing import Optional
from typing import Callable
from typing import Dict
def concatenate(
iterable: Iterable[Results],
callback: Optional[Callable] = None,
modes: Iterable[str] = ("val", "test"),
reduction: str = "none",
) -> Results:
"""Returns a concatenated Re... | 6833a50ddc84d44c942c6e85c1ebbdb793bd78a9 | 20,571 |
def parse_version(s: str) -> tuple[int, ...]:
"""poor man's version comparison"""
return tuple(int(p) for p in s.split('.')) | 445cd029efa3c8d4331e916f9925daddbc277ada | 20,572 |
def replay_train(DQN, train_batch):
"""
여기서 train_batch는 minibatch에서 가져온 data들입니다.
x_stack은 state들을 쌓는 용도로이고,
y_stack은 deterministic Q-learning 값을 쌓기 위한 용도입니다.
우선 쌓기전에 비어있는 배열로 만들어놓기로 하죠.
"""
x_stack = np.empty(0).reshape(0, DQN.input_size) # array(10, 4)
y_stack = np.empty(0).reshape(0, DQN.output_size) # arr... | 05b85aab223b82637a23853d15cd8e073ecca845 | 20,573 |
def make_reverse_macro_edge_name(macro_edge_name):
"""Autogenerate a reverse macro edge name for the given macro edge name."""
if macro_edge_name.startswith(INBOUND_EDGE_FIELD_PREFIX):
raw_edge_name = macro_edge_name[len(INBOUND_EDGE_FIELD_PREFIX) :]
prefix = OUTBOUND_EDGE_FIELD_PREFIX
elif ... | 807efcc26fb21e553241b2de4d2c6633a24548a2 | 20,574 |
def unescaped_split(pattern,
string,
max_split=0,
remove_empty_matches=False,
use_regex=False):
"""
Splits the given string by the specified pattern. The return character (\\n)
is not a natural split pattern (if you don't specif... | 5a5cec1a54b94840e13ddec3ca8796a73e908898 | 20,575 |
def citation_distance_matrix(graph):
"""
:param graph: networkx graph
:returns: distance matrix, node labels
"""
sinks = [key for key, outdegree in graph.out_degree() if outdegree==0]
paths = {s: nx.shortest_path_length(graph, target=s) for s in sinks}
paths_df = pd.DataFrame(paths)#, index... | b3c41164c2081704b3b36ce0c5b1ca55440a88be | 20,576 |
from typing import IO
def read_into_dataframe(file: IO, filename: str = "", nrows: int = 100,max_characters: int = 50) -> pd.DataFrame:
"""Reads a file into a DataFrame.
Infers the file encoding and whether a header column exists
Args:
file (IO): file buffer.
filename (str): filename. Used... | fe95c60870779353f2aa751c20ed331a2e0156bf | 20,577 |
import torch
def load_generator(config: dict):
"""
Create the generator and load its weights using the function `load_weights`.
Args:
config (dict): Dictionary with the configurations.
Returns:
BigGAN.Generator: The generator.
"""
# GPU
device = "cuda"
torch.backends.... | ad6ae9536610e12106e53ce94d9d1d60beff2fc5 | 20,578 |
from typing import OrderedDict
import torch
def Navigatev0_action_to_tensor(act: OrderedDict, task=1):
"""
Creates the following (batch_size, seq_len, 11) action tensor from Navigatev0 actions:
0. cam left
1. cam right
2. cam up
3. cam down
4. place + jump
5. place
6... | 39d481d2e8597902b18695de97f041606f24f035 | 20,579 |
def asfarray(a, dtype=mstype.float32):
"""
Similar to asarray, converts the input to a float tensor.
If non-float dtype is defined, this function will return a float32 tensor instead.
Args:
a (Union[int, float, bool, list, tuple, numpy.ndarray]): Input data, in
any form that can be... | 4da49b2bcab9686b2757cf1b9066c21876f992e6 | 20,580 |
from typing import Optional
from typing import Callable
import click
def _verify_option(value: Optional[str], value_proc: Callable) -> Optional[str]:
"""Verifies that input value via click.option matches the expected value.
This sets ``value`` to ``None`` if it is invalid so the rest of the prompt
can fl... | 4d0f58827982924a9d027112ffa3aaeef7634fe8 | 20,581 |
def batch_jacobian(output, inp, use_pfor=True, parallel_iterations=None):
"""Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`.
e.g.
x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
y = x * x
jacobian = batch_jacobian(y, x)
# => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]]
... | dd42fcc9542bba8033a1eb204bf0d3a91b192dbc | 20,582 |
def declare(baseFamily=None, baseDefault=0, derivedFamily=None, derivedDefault=""):
"""
Declare a pair of components
"""
# the declaration
class base(pyre.component, family=baseFamily):
"""a component"""
b = pyre.properties.int(default=baseDefault)
class derived(base, family=der... | 30c8d8f7d264a0e908f4305198b07c3d76a3cfac | 20,583 |
from datetime import datetime
def parse_iso8601(dtstring: str) -> datetime:
"""naive parser for ISO8061 datetime strings,
Parameters
----------
dtstring
the datetime as string in one of two formats:
* ``2017-11-20T07:16:29+0000``
* ``2017-11-20T07:16:29Z``
"""
return... | 415a4f3a9006109e31ea344cf99e885a3fd2738d | 20,584 |
def CalcCurvature(vertices,faces):
"""
CalcCurvature recives a list of vertices and faces
and the normal at each vertex and calculates the second fundamental
matrix and the curvature by least squares, by inverting the 3x3 Normal matrix
INPUT:
vertices -nX3 array of vertices
faces -mX3 a... | b0e31073fe8aff61e60d0393098cca390bb95708 | 20,585 |
from typing import Optional
def query_abstracts(
q: Optional[str] = None,
n_results: Optional[int] = None,
index: str = "agenda-2020-1",
fields: list = ["title^2", "abstract", "fullname", "institution"],
):
"""
Query abstracts from a given Elastic index
q: str, query
n_results: int, n... | 4ed554231c863c3164c5368978da900e3647570d | 20,586 |
import typing
import pickle
def PretrainedEmbeddingIndicesDictionary() -> typing.Dict[str, int]:
"""Read and return the embeddings indices dictionary."""
with open(INST2VEC_DICITONARY_PATH, "rb") as f:
return pickle.load(f) | d4c0c8f5d7c83d99927342c5cacd8fd80a4f7d56 | 20,587 |
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color | 1806af9c915740612a6a11df723f1439c73bde2f | 20,588 |
import os
import fnmatch
def globpattern(dir, pattern):
"""
Return leaf names in the specified directory which match the pattern.
"""
if not hasglob(pattern):
if pattern == '':
if os.path.isdir(dir):
return ['']
return []
if os.path.exists(util... | b5d37fc5ffa69df67e3370cbb7abb2884c482d08 | 20,589 |
def get_student_discipline(person_id: str = None):
"""
Returns student discipline information for a particular person.
:param person_id: The numeric ID of the person you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getStudentDiscipline', perso... | 4e96fb4e9d566af7094b16b29540617bbb230f67 | 20,590 |
import argparse
import torch
import os
import tqdm
import time
import json
def main():
"""evaluate gpt-model fine-tune on qa dataset"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--model_name',
type=str,
default='gpt2',
help='pretrained model name')
parser... | 59be7014ff8d677261263ee8ab69ec1e0a1771e4 | 20,591 |
from re import X
def dot(p1, p2):
"""
Dot product
:param p1:
:param p2:
:return:
"""
return p1[X] * p2[X] + p1[Y] * p2[Y] | 13ba17e8757ebf9022f07d21b58a26376520f84a | 20,592 |
def logout():
"""View function which handles a logout request."""
tf_clean_session()
if current_user.is_authenticated:
logout_user()
# No body is required - so if a POST and json - return OK
if request.method == "POST" and _security._want_json(request):
return _security._render_jso... | 0343be8ec063b5c215a0a019003cbf137588171a | 20,593 |
import os
import pkgutil
def _lookup_configuration():
"""Lookup the configuration file.
:return: opened configuration file
:rtype: stream
"""
for pth in CONFIG_PATH:
path = os.path.abspath(os.path.expanduser(pth))
LOGGER.debug('Checking for %s', path)
if os.path.exists(pat... | 1f3e23baa2947bf5ffd8df080fe52c37235e94b6 | 20,594 |
def splinter_session_scoped_browser():
"""Make it test scoped."""
return False | a7587f6edff821bab3052dca73929201e98dcf56 | 20,595 |
from typing import Counter
def sample_mask(source, freq_vocab, threshold=1e-3, min_freq=0, seed=None, name=None):
"""Generates random mask for downsampling high frequency items.
Args:
source: string `Tensor` of any shape, items to be sampled.
freq_vocab: `Counter` with frequencies vocabulary.... | 30fca98f95ac7a6aa2f3a3576f32abf271a693bb | 20,596 |
def _xList(l):
"""
"""
if l is None:
return []
return l | ef09d779c7ebc2beb321d90726f43603c0ac8315 | 20,597 |
def IABN2Float(module: nn.Module) -> nn.Module:
"""If `module` is IABN don't use half precision."""
if isinstance(module, InplaceAbn):
module.float()
for child in module.children():
IABN2Float(child)
return module | 587565ad78afd08d3365f637ab5b98b17e977566 | 20,598 |
from datetime import datetime
def start_of_day(val):
"""
Return a new datetime.datetime object with values that represent
a start of a day.
:param val: Date to ...
:type val: datetime.datetime | datetime.date
:rtype: datetime.datetime
"""
if type(val) == date:
val = datetime.fr... | 74e302513edf428f825f9e24567e23b3a5e5d4f5 | 20,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.