content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def test_single_for_builtin_function_numpy_sum():
"""
Feature: JIT Fallback
Description: Test fallback with control flow.
Expectation: No exception.
"""
@ms_function
def control_flow_for():
x = np.array([1, 3, 5, 7, 9])
y = np.array([0, 2, 4, 6, 8])
result = x
... | 5801d02abed47cd65d33e12056717eaabe90ab64 | 59,651 |
from typing import Optional
import re
def get_default_branch_from_remote(
remote: str,
) -> Optional[str]:
"""
Get default branch from remote.
:param remote: the remote name
:return: the default branch, or None if it failed
"""
# https://stackoverflow.com/questions/28666357/git-how-to-get... | c18e20cdd5d861dc324296761c71bb5d4416e471 | 59,652 |
import re
def oerp_get_ids_from_order(po_id, oerp):
"""
Fetches the product IDs of a purchase order
:param po_id: The openERP purchase order ID
:param oerp: the openERP lib instance
:return: an array containing the openERP product IDs of a purchase
"""
po_id = int(po_id.lower().replace("po... | 88b87ed35317818f7d3bc3d693cd025385734756 | 59,653 |
def form_update_node(user, handle_id, form, property_keys=None):
"""
Take a node, a form and the property keys that should be used to fill the
node if the property keys are omitted the form.base_fields will be used.
Returns True if all non-empty properties where added.
"""
meta_fields = ['relati... | 1f1d33cd18bc6f1f186114f038065fe0518a93ca | 59,654 |
import zlib
def decompress_zip(data, # type: bytes
shape, # type: Tuple[int, int]
depth, # type: int
version # type: int
): # type: (...) -> np.ndarray
"""
Decompress zip (zlib) encoded data.
{}
"""
data = zlib.... | 3cd7d24287a8c6991de4997d83108b16251c0491 | 59,655 |
def add_user_key(request, **kwargs):
"""
Create a new User API key.
Requires a name and a readonly boolean.
"""
user = request.user
name = request.POST.get("name")
readonly = convert_to_bool(request.POST.get("readonly"))
api_key, key = UserAPIKey.objects.create_key(
name=name,... | 500512fa5f336f5d6f0aae44312ab1621005bd57 | 59,656 |
def find_neighbors_for_1D(cog, target_res, max_codon_dist=3):
"""
Overloaded version of find neighbors 1D
that allows us to find the neighbors
of only the residues we want
Parameters:
-----------
cog : dictionary
dictionary of residue ids and their
centers of geomeetry
m... | 69cf517735ca18c2f442e457ad7d59f0a33db768 | 59,657 |
def batch_norm_relu(inputs, is_training):
"""Performs a batch normalization followed by a ReLU."""
_BATCH_NORM_DECAY = 0.997
_BATCH_NORM_EPSILON = 1e-5
axis = 1
# Workaround because there is currently no NCHW fused BN on CPU
if not tf.test.is_built_with_cuda():
inputs = tf.transpose(inpu... | aeca62585c5b53f50d82e087530228629252d1ef | 59,658 |
def decode_soft_encoding_batch_rgb(x_batch, y_batch, q_ab, epsilon = 1e-8, T = 0.38, x_post_fn = None, version = 0, usegpu = False, **kwargs):
"""
q_ab = np.load(os.path.join(module_dir, "data", "pts_in_hull.npy").replace("\\", "/"))
x_batch: L channel (batchsize, height, width, 1), (height, width) --> gray... | 93a24748166047a3a9748715f46ed995975bd0a1 | 59,660 |
import torch
def word_to_one_hot(word, word2idx):
"""Return the one hot encoding of the word given to this function.
Args:
word (str): The word for which one hot representation is required.
word2idx (Dict): The dictionary mapping from word to indices.
Returns:
x (torch.Tensor): The on... | 6628f25695cacb202dd51be070ff03f9a594654d | 59,661 |
def dcopy(x):
"""
Returns a deep copy of an array.
Parameters
----------
x: array-like
The array to create a deep copy of.
Returns
-------
array-like:
The deep copy of the input.
"""
backend = getBackend(x)
if backend == 'numpy':
return x.copy()
... | 4a7cc6da52c6c3f7fc106c38524adfe3735a5806 | 59,662 |
def dhcp_offer_packet(eth_dst='00:01:02:03:04:05',
eth_src='06:07:08:09:10:11',
ip_src='0.0.0.0',
ip_dst='255.255.255.255',
ip_len=308,
ip_tos=16,
ip_ecn=None,
ip_dscp=None,
ip_ttl=128,
... | a763f6b2303624912d8fe0d91928a310be1f2b74 | 59,663 |
def save_video_categories(regionCode: str):
"""儲存該國籍的主題內容
Args:
regionCode (str): 國籍簡碼
Returns:
[bool]: 成功或報錯
"""
category = videos.get_video_category(regionCode=regionCode)
if not isinstance(category, dict):
return False
for i in category['items']:
schemas ... | 2ed1d9806727ee79a3560a7d03cc8ec0782836c1 | 59,664 |
from pathlib import Path
from typing import Type
def parse_text_level(file_path: Path) -> LevelElements:
"""Parses a level layout file into `LevelElements`.
Takes a file path to the level layout and converts the ASCII characters into
a grid of level elements (Python objects).
Args:
file_path... | c3122292474520d89426c59de9969072c824f767 | 59,665 |
from typing import Container
async def get_subscriber_subscriptions_handler(
request: web.Request, *,
subscription_service: SubscriptionService = Provide[
Container.subscription_service
],
) -> web.Response: # noqa
"""Handle subscriber subscriptions getting requests."""
ne... | 302f3e5c2f1eb397bd0305251f5b6b1bd425f140 | 59,666 |
def primary_trefoil_y(rho, phi):
"""Zernike primary trefoil Y."""
return rho**3 * e.cos(3 * phi) | f9a73da106bd4979996b609981f28a481f0b84c4 | 59,667 |
def top_5_categorical_accuracy(y, y_pred):
"""
Return the top 5 categorical accuracy of the predictions
"""
return top_n_categorical_accuracy(y, y_pred, 5) | 28b53e83e94489e903936740f815560c17e68c98 | 59,668 |
def get_to_do_filename():
"""
Asks users to enter a filename od an existing To Do file.
The user should be repeatedly prompted for a filename until a existing one is entered.
Use os.path.isfile(to_do_list_file) to check if to_do_list_file exists
:return: the existing To Do filename
"""
#... | 1aa4022315736435cfc518a1b8e15c9acb160712 | 59,669 |
async def update_item(key, value):
"""Update an existing key."""
# Query db.
result = await collection.update_one({"_id": key}, {"$set": {"value": value}})
if result.matched_count:
return result.raw_result
else:
raise HTTPException(status_code=404, detail="Item not found.") | 235e981cba897cbebc00d90b012e295e7bcbc426 | 59,670 |
import base64
def deserialize(employee_str) -> Employee:
"""
Given an base64 encoded string parse and convert to Employee object
:param employee_str: base64 encoded string
:return: Employee Object
"""
decoded = base64.b64decode(employee_str)
employee_obj = Employee()
employee_obj.Parse... | 1e516fbc5da575afe5ad9fe867f449ec3574a0fb | 59,671 |
def rev_comp(seq: str) -> str:
"""
Generates the reverse complement of a sequence.
"""
comp = {
"A": "T",
"C": "G",
"G": "C",
"T": "A",
"B": "N",
"N": "N",
"R": "N",
"M": "N",
"Y": "N",
"S": "N",
"W": "N",
"K... | cb6b95d2d3f15910ff3ad793d99bb56de898026e | 59,672 |
def strip_variables(raw_df, targ_hd):
"""
Some of the ncdf files do not have a <complete> collection of variables
(e.g. Rnet, Qg), such that the matrices are different shapes. In order
to be able to concatenate all fluxnet datasets together, this function
strips out the uncommon variables.
"""
... | b732faf83d5946807c6e74b13297e52ced18ff1d | 59,673 |
def check_unique(ser : pd.Series) -> any:
"""Check uniquness. If duplicated, raise Error.
"""
l = ser.unique()
if len(l) != 1:
raise Exception("Duplication found", l)
return(l[0]) | 7f5c5bef6447812f02cb0dd4c7ed6f44b37c12a6 | 59,674 |
import getpass
def mm_connect():
"""
Connects to a FTP-Server using the Info given in the param file
USRN and PSWD can be None to interactively get the Info.
THIS IS NOT SECURE and should be replaced with SFTP in the next Versions
"""
""" monkeypatch https://stackoverflow.com/questions/440577... | 13b03ba5ad4ad1a0e9681604ac9202bd4b6096ff | 59,675 |
def _parse_dsn(dsn_text,defaults):
"""
Convert a DSN MIME part to a dictionnary keyed by DSN fields
"""
res = []
for sub in dsn_text.split("\n"):
if ':' in sub:
res.append(map(str.strip, sub.split(':', 1)))
res = dict(res)
for d in defaults.keys():
if not d in re... | 6637acda9c66085fce9af8eca63cbe7ad8e1a989 | 59,677 |
def find_nuc_indel(gapped_seq, indel_seq):
"""
This function finds the entire indel missing in from a gapped sequence
compared to the indel_seqeunce. It is assumes that the sequences start
with the first position of the gap.
"""
ref_indel = indel_seq[0]
for j in range(1,len(gapped_seq)):
... | d1f258229300f965d9e6d0a8fba0a7cb6a071131 | 59,678 |
def expected_dice_game ():
"""Function that generates expected accumulative of dice roles in accordance to probability theory."""
def evaluateSides (list):
"""Function that generates a list of numbers that occur on each side of a normal dice"""
# initiate loop mechani... | 2c224b4d4f7ee96a643eb65f605094c1f07663c1 | 59,679 |
def data_scientists_who_like(target_interest):
"""Find the ids of all users who like the target interest."""
return [user_id
for user_id, user_interest in interests
if user_interest == target_interest] | 89a2473037d1ef30830b5383d4c39b52953e70ae | 59,680 |
from io import StringIO
import traceback
def serialize_known_exception(e):
"""
Serialize a cloudify exception into a dict
:param e: A cloudify exception
:return: A JSON serializable payload dict
"""
tb = StringIO.StringIO()
traceback.print_exc(file=tb)
trace_out = tb.getvalue()
# ... | e0c24480373d4d4d2be99f8cd4b2b8193a1f5120 | 59,681 |
def users():
""" Convert PostHistory.xml to pandas dataframe """
parsed_xml = et.parse("../../data/raw/Users.xml")
dfcols = ['Id','AccountId','CreationDate', 'Reputation','Views','UpVotes','DownVotes','LastAccessDate']
df_xml = pd.DataFrame(columns=dfcols)
i=0
for node in parsed_xml.getroot():
... | edd3e2831e9fe2286fa74fd448f10fc0c059a901 | 59,682 |
def echo_an(ma, ga, Lpk, dist, t_age, gamma, tpk, tt, deltaE_over_E=ct._deltaE_over_E_):
"""
Analytic formula for the echo spectral irradiance [Jy], with transition time as input, and assuming constant DM density. NOTE: the frequency dependence prefactor, usually (nu/nu_pivot)^-alpha, is factorized out.
Pa... | fa17ef6b9d3a51b4e5a9fbf896acd29d4a76df98 | 59,684 |
def log_out(request):
"""Log out page. Roure for 'logout'."""
logout(request)
messages.info(request, "Logged out")
return redirect("login") | 990c42a9b5de6a8c720f4d58d7c62ebc22a66af4 | 59,685 |
def _match_identifier_re():
"""
匹配BundleId
"""
return r'^Identifier:\s*([a-zA-Z0-9_\-\.]+)\s*$' | cbca0e2924e77c43211bdadba4d434c178eb8e18 | 59,686 |
from typing import Any
from typing import Tuple
from typing import Iterator
def create_generators(
df: pd.DataFrame, train: pd.DataFrame, val: pd.DataFrame, test: pd.DataFrame, plot_augmentations: Any
) -> Tuple[Iterator, Iterator, Iterator]:
"""Accepts four Pandas DataFrames: all your data, the training, val... | ae4619ebf9efad29dcadca56e342824320f31713 | 59,687 |
def get_stats_for_unweighted_hpo_aggregate_metric(
hpo_object, metric, date, hpo_name,
tables_and_classes_counted, statistics_to_average):
"""
Function is used once an HPO is found and warrants its own
AggregateMetricForHPO because it has a unique set of date
and metric parameters.
... | 2b451f6fc15b9f96e343d5577626a62fd57662b7 | 59,688 |
def part2(commands):
"""
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by your aim multiplied by X.
Calculate the horizontal position and depth you would ... | 68664bc4fc708f67d4cbce121f16f273aeeffd86 | 59,689 |
def cantor_pairing(a, b):
"""Create an unique number from two natural numbers
For more information about the Cantor pairing function, have a look at:
https://en.wikipedia.org/wiki/Pairing_function
This create an unique number from two natural numbers according to
.. math::
\pi (a,b):={\frac{... | d8849a7c7a8497393e77f2b93e3555a09f704bf3 | 59,690 |
import functools
def class_from_constructor(cls, func, **kwargs):
"""Creates a new class by extending the given one and using func as a
constructor of the new class.
Keyword arguments are passed to a metaclass."""
# For unknown reasons __doc__ attribute of type objects is
# read-only, and update... | 3159ff9387f2b5f7dc32ef8dc969a2266b46dd14 | 59,691 |
def codeblock(text):
"""
Returns text in a Markdown-style code block
:param text: Str
:return: Str
"""
return "```\n" + text + "\n```" | fb8fd7314273b47ace577a72c705742d6646aa0d | 59,693 |
def get_Rx(theta):
"""Define matrix for rotation (roll) about x axis."""
Rx = matrix([[1, 0, 0],
[0, cos(theta), -sin(theta)],
[0, sin(theta), cos(theta)]])
return Rx | 3ce94a9e7472deaaaccd44ead970fa14c31e1f26 | 59,694 |
def max(x: Tensor, axis: int = None) -> Tensor:
"""Returns the maximum value of the input tensor."""
output = Tensor(np.max(x.data, axis=axis), requires_grad=x.requires_grad)
def backward_fn():
if x.requires_grad:
local_gradient = output.grad.data * (x.data == output.data)
... | 14e91fbc5bf8bb539fcc28c6b5ae0760da9cf395 | 59,695 |
from authlib.integrations.requests_client import OAuth2Session
def set_oauth_cb(config):
"""Implement client support for KIP-768 OpenID Connect.
Apache Kafka 3.1.0 supports authentication using OpenID Client Credentials.
Native support for Python is coming in the next release of librdkafka
(version 1... | b4ee2f6574e81fcf19f662697580531655407594 | 59,696 |
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable version ... | 6ca6e8be17607427c02fa3bc82667a730a7db1fc | 59,697 |
def findDeviceID():
""" This method finds all devices available to play on a spotify account and returns the device to be used for playback. It always returns the ID of the Amazon Echo unless it is unavailable.
Returns:
deviceID(String): Returns the id of the Amazon Echo if it is available or the next... | 1bf9b8e510e697e0ae19f4834c1536d02a40960a | 59,698 |
def init_patched_conic(x,
rf = 1837400.0,
r0 = 6371000.0 + 185000.0,
phi0 = 0.0,
D = 384402000.0,
V = 2.649e-6 * 384402000.0):
"""Generic objective function. x is [lam1, v0]."""
lam1 ... | f1c6ab98114155f44ccc86effd7503cfebffb8fa | 59,699 |
def _get_docker_client():
"""Returns the docker client"""
try:
return docker.from_env(version='auto')
except docker_errors.DockerException as e:
err_msg = 'Could not create docker client: {}. Have you started the docker daemon?'.format(e)
future_utils.raise_from(ValueError(err_msg), ... | b653844c88a7b04751cc7cf76cfc786af8990b1e | 59,700 |
def generate_ensemble(num_layers, *activations):
"""Given a set of string names and a number of target layers, generate
a list of ensemble architectures with those activations
Args:
num_layers: int
the number of hidden layers in the neural network, and also
the number of activation fun... | 42bce2fc861122938d2e5da54e4538b0e6a285bc | 59,701 |
import torch
def load_data(training_file_path: str, dev_file_path: str, batch_size: int, max_length: int, device,
is_bert_model=True):
"""
loads training data from csv files
:param batch_size:
:param max_length:
:param device:
:param is_bert_model:
:param training_file_path:
... | 6b668cb8e792444ee7997c255b9e24e08b0453bc | 59,702 |
def run_cso_classifier_batch_model_single_worker(papers, modules="both", enhancement="first"):
"""Run the CSO Classifier in *BATCH MODE*.
It takes as input a set of papers, which include abstract, title, and keywords and for each one of them returns a
list of relevant concepts from CSO. This function requi... | ec11a82c4dcbd6d711ec3add837280b3f291141a | 59,703 |
def pdt2num(pdt, time_units, calendar, start_of_period=True):
"""
Convert an Iris PartialDateTime object into a Python datetime object. If
the day of the month is not specified in `pdt` then it is set as 1 in the
output unless `start_of_period` isn't True, when 30 is used as the day of
the month (be... | a06a70368db16f83d8d2c0a8fa79a395b6599546 | 59,704 |
import time
def get_log_file(name):
"""
Returns a new recomputation log file name, with a timestamp
"""
return "{dir}/{name}/{time}.txt".format(dir=logs_dir, name=name, time=time.strftime("%Y%m%d-%H%M%S")) | 02d7f6c39a064f77e58428b0422e327c8553ff0c | 59,705 |
def fib2(n):
"""Zwraca liste liczb Fibonacciego mniejszych niz n
"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result | 246f5bf991d6f5af08cb312d83c9b755f0f269c3 | 59,706 |
def int_to_string(msg):
"""Convert the integer 'msg' to a string.
This function is the inverse of string_to_int().
"""
# convert to binary first
binmsg = bin(msg)[2:]
# pad the message so length is divisible by 8
binmsg = "0"*(8-(len(binmsg)%8)) + binmsg
msg = bytearray()
# convert b... | 780a5b8e7f087eee4ca3f01e12d2b9b52b183f22 | 59,707 |
def regular_graphing_method():
"""
This function was created to determine whether the user wants to graph the data on top of each other or on separate graphs.
:return boolean regular_ontop: regular_ontop is returned to determine how the data will graph
Note: if regular_ontop is true, the non-derivativ... | 75cb8de45df76cb6facf91ac0ae6e0ca9f37cf31 | 59,708 |
def div_to_int(int_numerator, int_denominator, round_away=False):
"""Integer division with truncation or rounding away.
If round_away evaluates as True, the quotient is rounded away from
zero, otherwise the quotient is truncated.
"""
is_numerator_negative = False
if int_numerator < 0:
int_numerator =... | 3fc3b307cf691a9bea2a33a0bf468398c77db645 | 59,709 |
def get_users(recipe):
"""Get all users and times for comments"""
all_comments = recipe.comments
users = []
times = []
for comment in all_comments:
user = User.query.get(comment.user_id)
users.append(user)
times.append(comment.created_at)
return users,times | 24da2525af4c844336b4a6b2f17f439a43fbf0b3 | 59,710 |
def correct_angle(x, verbose=False, only_angles=True):
"""correct_angle
This function converts the angles obtained with normal2angle to angles that we can use on the scanner. The scanner doesn't like angles >45 degrees. If inserted, it will flip all kinds of parameters such as slice orientation and foldover.
... | b131c0304701f31f44421296936c85b94812c656 | 59,712 |
import re
def get_pids(linesl):
"""
Required layout lines.
Returns dictionary of pid:meaning
"""
pids = {}
foundstartpids = False
for line in linesl:
# After table
if "These PIDs are superseded by PIDs 194, 195, and 196." in line:
break
# Before table
if not foundstartpids and " ... | 1216b337283851ceb0e6721abd124b2a83a0157c | 59,713 |
def frontpage(request):
"""Renders OCELoT frontpage."""
if request.method == 'POST':
form = LeaderboardForm(request.POST)
submissions = Submission.objects.all().order_by('-score')
if form.data['testset']:
submissions = submissions.filter(test_set=form.data['testset'])
... | dd021b9776760f9fc7dc448781ec9d877520a07a | 59,714 |
def publish_XdFloat(self):
"""
Publish XdFloat
"""
# fix double quotes in label
self.label.replace('"', '"')
self.save()
# it is a modelling error to use multiple reference ranges with the same
# Xdinterval in a Xdquantity
used_ctid_list = []
# default return message
... | bbab0db59b4c8ebc8606fd329452db57010857d5 | 59,715 |
def __improve_tasks_info(cluster_name, tasks):
"""Get more information for a list of tasks."""
containers_instances = get_containers_instances(cluster_name)
for task in tasks:
for inst in containers_instances:
if inst["containerInstanceArn"] == task["containerInstanceArn"]:
... | a83a8e0b3ea27de7cd4d585b0d4e6efae54672fd | 59,716 |
def rf_inverse_mask(src_tile_col: Column_type, mask_tile_col: Column_type) -> Column:
"""Where the rf_mask (second) tile DOES NOT contain NODATA, replace values in the source
(first) tile with NODATA."""
return _apply_column_function('rf_inverse_mask', src_tile_col, mask_tile_col) | 556eab93f674cae611f26d6b55752f95d863f0bb | 59,717 |
from typing import OrderedDict
def register_models(database_state, models, register_indexes=False,
new_app_label='tests', db_name='default', app=evo_test):
"""Register models for testing purposes.
Args:
database_state (django_evolution.db.state.DatabaseState):
The data... | 2fa833fcda7c6e2933b3ffb0d2e0d93de5f7589f | 59,718 |
def nearest_feature(geometry, geometry_collection, r_tree=None):
""" Return nearest feature from geometry collection to given geometry
If some of the geometries intersect, the nearest feature is the one whose centroid is the closest to the centroid
of the given geometry (but distance remains 0)
:param ... | 51d43d23788661bbd8a87737276b153b9cea41eb | 59,719 |
def get_contract(contract_name):
"""
This function will grab the contract address from the config if defined; otherwise deploy mock contract and return address
Args:
contract_name (string)
Returns:
brownie.network.contract.ProjectContract: the most recently deployed ver... | 961c9206d5571f1cf3a009d5c3295542ec7dcc9a | 59,720 |
def get_profile_url(self):
"""Returns the URL for this User's profile."""
return '%s%s/' % (reverse('user', args=[self.id]), self.username) | bffce22685b8b4fe429e2c8614d4905d5bbc2e04 | 59,721 |
def tryShiftBits(rs, bits, bitsBefore, bitsAfter, tryFirst, \
f6b = False, block0FixedBits = False):
"""
Given 3 packets of data (sample, before sample, and
after sample), error correct the sample using various shifts.
The bits represent a single block of a FIS-B message,
or the entire ADS-B message.
... | 7eeb64ed50bc0699ee2bd6922eb579c5bfc03881 | 59,722 |
def non_max_suppression(boxes, scores, max_output_size, iou_threshold=None, name=None):
"""Greedily selects a subset of bounding boxes in descending order of score,
pruning away boxes that have high intersection-over-union (IOU) overlap
with previously selected boxes. Bounding boxes are supplied as
[y1... | 608075ea7aef718e6a4aa79c3d6992e1ea2a6733 | 59,723 |
def match_server_args_factory(tick_rate: int, realtime: bool, observations_only: bool, env_config_string: str):
""" Helper factory to make a argument dictionary for servers with varying ports """
def match_server_args(port):
arg_dict = {
"tick_rate": tick_rate,
"port": port,
... | 5059d0a4224067f485455a54f4e6d1f83ba68531 | 59,724 |
from typing import Iterable
from typing import Any
def parametrize(arg_names: Iterable[str], arg_values: Iterable[Iterable[Any]]):
"""
Decorator to create parameterized tests.
# Parameters
arg_names : `Iterable[str]`, required.
Argument names to pass to the test function.
arg_values : `I... | e385d2449a2572d89a055d7cbdcc2475b00b2942 | 59,725 |
def objective(hyperparameters, iteration):
"""Objective function for random search. Returns
the cross validation score from a set of hyperparameters."""
# Number of estimators will be found using early stopping
if 'n_estimators' in hyperparameters.keys():
del hyperparameters['n_estimators']
... | 605fc55866a6e42651e2faca4a0e16d0a4877ddc | 59,726 |
def get_dataset_length(audio_files):
"""Get the size of the dataset given the file paths"""
length = 0
for file in audio_files:
info = torchaudio.info(file)
samples = info.num_frames * cargan.SAMPLE_RATE / info.sample_rate
if samples < cargan.MAX_LENGTH:
length += 1
... | 1c06436b86fe8c658a652ff581598bd5f97a1e9c | 59,727 |
from bs4 import BeautifulSoup
def _req_widiget():
"""
初始化环境
:return:
"""
url = 'https://captcha.luosimao.com/api/widget?k=e7b4d20489b69bab25771f9236e2c4be&l=zh-cn&s=normal&i=_2ymuhhcry'
resp = session.get(url)
bsobj = BeautifulSoup(resp.text, 'lxml')
data_token = bsobj.select('#l_captc... | a1a45338ea01b4bd9cf5778944d300ba06d7cc48 | 59,728 |
def rotation_matrix_arbitrary_axis(angle, axis):
"""
Returns a rotation matrix of `angle` radians about `axis`.
Parameters
----------
angle : :class:`float`
The size of the rotation in radians.
axis : :class:`numpy.ndarray`
A 3 element aray which represents a vector. The vector... | 7194576e97f4d65b54021bbabe43fba8b57a8d12 | 59,729 |
import torch
def generate_metrics_table(benchmarks, dataloader, metrics, device=None, dtype=None):
"""Generate metrics table for all benchmarks.
Parameters
----------
benchmarks : dict
Dictionary where keys are benchmark names and values are instances of `Benchmark` (possible
also `to... | 8fabd19bf809416127674ecfff86fae8b89a94cb | 59,730 |
import io
def rose(factory=None):
"""Return rose image.
Resulting image is 70 x 48, RGB, truecolor.
"""
return io.read('rose:', factory=factory) | 072d8ec8afbfe250219468d3eb67061659f7bd6b | 59,731 |
def default_colors_to_resets(s):
"""Hack to make sphinxcontrib.ansi recognized sequences"""
return s.replace(b"[39m", b"[0m").replace(b"[49m", b"[0m") | 0f025233ac63416fef47e85ebb258bb543a4c115 | 59,732 |
def delete(isamAppliance, replica, session, check_mode=False, force=False):
"""
Terminating a session
"""
check_value, warnings = _check(isamAppliance)
if check_value is True:
if force is True or search(isamAppliance=isamAppliance, replica=replica, session=session) is True:
if c... | 2e9bb77d82734a541a7b0135012577b7821d3839 | 59,733 |
def plot_mean_with_runs(data, type_, ind, smooth_over, names, colours=None,
figsize=(12, 6), xlim=None, ylim=None, alpha=0.2,
plot_avg=True, env_type="continuing",
keep_shape=False, fig=None, ax=None, detrend=None):
"""
Plots the mean retur... | 47391fced6709c41cdd94c4f2cc8653a2651d86d | 59,734 |
def _load_multipage_tiff(path):
"""Load tiff images containing many images in the channel dimension"""
return np.array([np.array(p) for p in ImageSequence.Iterator(Image.open(path))]) | b61dfe371818e4a132db5d99d1b9a295473eba92 | 59,735 |
def processImage(frap_image, subtract_bg = False, prebleach_ss=True):
"""
Function which processes frap image
:param frap_image: FRAP Image
"""
# background subtraction
frap_image.reset_image_data()
frame_data = frap_image.get_image_data()
if subtract_bg:
print('Subtracting backg... | 20907395d1e034b0c04b78c77e372d0bce922ec2 | 59,736 |
def clean_input():
"""
Make sure we're not getting bad data from the front end,
format data to be machine readable
"""
if not 'password' in request.form:
abort(400)
if not 'ttl' in request.form:
abort(400)
time_period = request.form['ttl'].lower()
if not time_period in ... | 8e367250053328df80745c745b716c65f8b96412 | 59,737 |
def nchw2nhwc_func_register(func_name):
"""Register func in NCHW2NHWC_FUNCS"""
def decorator(func):
NCHW2NHWC_FUNCS[func_name] = func.__name__
def wrapper(self, call, op_args):
attrs = nchw2nhwc_attrs_changer(call.attrs)
return func(self, op_args, attrs)
return... | 450dc9c119233e5a94343b53b68d4111ea9937c3 | 59,738 |
def draw_path(data, path, draw_options=None, simplify=None):
"""Adds code for drawing an ordinary path in PGFPlots (TikZ).
"""
# For some reasons, matplotlib sometimes adds void paths which consist of
# only one point and have 0 fill opacity. To not let those clutter the
# output TeX file, bail out ... | 6d4721a5c54247c91600384330e14e05686e4709 | 59,739 |
def trailFilter(elem, osmdata):
"""
Currently filters in all trails with "highway" in the accepted highways list.
"""
return OSMData.get_tag(elem, OSMData.KEY_HIGHWAY) in OSMData.ACCEPTED_HIGHWAYS | 1120bddb4ef60c0ce415aa8405d17a072553c1b2 | 59,740 |
from geopy.geocoders import IGNFrance
def geotag_Compte(df, prefix='', IGN_API=''):
"""
This function corrects Phenix original geo coordinates (longitude and latitude).
This function uses IGN geocoding API to convert adresses into Longitude and Latitude coordinates.
Args:
df (DataFrame): 'Com... | 60eafe996faefebfb12465dbe177a050c4c5451e | 59,742 |
def mask_maxipix(mydata, mymask):
"""Mask the Maxipix frames."""
mydata[:, 255:261] = 0
mydata[255:261, :] = 0
mymask[:, 255:261] = 1
mymask[255:261, :] = 1
return mydata, mymask | 0c508c6740569e99cdb745b75b399dac8021e9bf | 59,743 |
import math
def get_distance(lat_1, lng_1, lat_2, lng_2):
"""calculates the distance between two coordinates
Args:
lat_1 (float): start latitude
lng_1 (float): start longitude
lat_2 (float): end latitude
lng_2 (float): end longitude
Returns:
float: distance in me... | 3e09826a4b556e897f2c39d792ed2f1d8da6109c | 59,746 |
import math
def spherical_to_cartesian(r, theta, phi):
"""
:param r: Radius.
:param theta: in radians.
:param phi: azimuth angle in radians
:return: x=[x1, x2, x3] coordinates.
"""
return [r*math.sin(phi)*math.cos(theta), r*math.sin(phi)*math.sin(theta), r*math.cos(phi)] | 08d0748d5acd9dab4e74a19879b2f8ac7858bb31 | 59,747 |
def forget_password(request):
"""
后台卖家忘记密码功能
:param request:
:return:
"""
return render(request, "shop/forgot-password.html") | d446d393a77c982a465f777783aba0c063ae5f79 | 59,748 |
def load_wavesolution(filenames):
""" Load the wavesolution from saved data """
wsol = WaveSolution()
wsol.load(filenames)
return wsol | e0dab57a11b16695c374fd9e43e8649ca745dbe4 | 59,749 |
def show_current(name):
"""
Display the current highest-priority alternative for a given alternatives
link
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_current editor
"""
try:
return _read_link(name)
except OSError:
log.error("alternative: %s do... | dea167ff753a0f4a1570e752047c12045e374428 | 59,750 |
import copy
def flat_ingredients_list_DFS(product):
"""
Recursive function to search the ingredients graph by doing a Depth First Search and return it as a flat list of
all nodes.
Sub ingredients are placed right after their parents.
Args:
product (dict): Dict corresponding to a product o... | d2b3ada88963d3967fa8fffc4aa294bed4b1fe31 | 59,751 |
def add_dist_along_vector(p0, p1, dist):
"""Add distance along vector"""
p0 = np.array(p0)
p1 = np.array(p1)
u = (p1 - p0) / np.linalg.norm((p1 - p0))
return p0 + dist * u | b96c6f44990fe88288a63dd7998f4c73fa8e508a | 59,752 |
import json
def hash_block(block):
"""Hashes a block and returns a string representation of it.
Arguments:
:block: The block that should be hashed.
"""
return hash_string_256(json.dumps(block, sort_keys=True).encode()) | 3e7b48307debb199c59c3116e7a0eff66879581c | 59,753 |
def _prep_torque_resources(resources):
"""Prepare resources passed to torque from input parameters.
"""
out = []
has_walltime = False
for r in resources.split(";"):
if "=" in r:
k, v = r.split("=")
k.strip()
v.strip()
else:
k = ""
... | 0832bb393d25e51be9156f814e4da4a76ce4a845 | 59,755 |
def divide_by(y):
"""divide_by(y)(x) = x / y
Note I'm using the future division here - the answer on two ints will
be a float.
Be careful with this because division is not commutative.
You may be interested in func.flip(divide_by) to reverse the arguments.
>>> divide_by(2)(4)
2.0
>>>... | c98de33a14840cdd421737bda44605142572a4f3 | 59,757 |
from typing import Union
async def filter_users(
email: str = None,
banned: bool = False,
normal: bool = True,
order_by: str = "register_date",
order: str = "desc",
page: int = 1,
limit: int = 10,
db: Session = Depends(deps.get_db),
user: Union[m... | ae169f68219bb3c9c4c2b8e99f881cd8d394845c | 59,758 |
import scipy
def pca_transform(pca, mean, arr):
"""
Apply a PCA transformation to argument
Parameters
----------
pca : sklearn.decomposition.PCA
A PCA projector. See wot.ot.get_pca
arr : numpy ndarray or scipy.sparse matrix
The array to project.
Returns
-------
re... | d0d4ea83f40b4655aadc23df5a35a4cd94a6145c | 59,760 |
async def webfonts(filename) -> Response:
"""Web font static endpoint."""
return await send_from_directory(webfonts_dir, filename) | d51d96067de2232ab3fb63a19107fab0e2546fc2 | 59,761 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.