content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import click
import yaml
import os
import csv
import copy
import time
def upload_subjects(
subject_set_id,
manifest_files,
allow_missing,
remote_location,
mime_type,
file_column,
):
"""
Uploads subjects from each of the given MANIFEST_FILES.
Example with only local files:
$ p... | 11d53ad1593250f73085bcf8c756b06dd2c71f70 | 3,634,000 |
def get_next_prev(qt_id, topic_id):
""" Find the "next" and "previous" qtemplates, by topic, position. """
if not topic_id:
return None, None
# This is very inefficient, but with the way questions are stored,
# I didn't see a better way. Could maybe be revisited some time?
questionli... | 0b1d13eb79864b24b293ee7d85816b9d03c949e0 | 3,634,001 |
def get_text_and_video_items(full_dict):
"""
Return new OrderedDict filtered by hasaudio attribute = False
"""
items_by_has_not_audio = {
k: v
for k,v in full_dict.items() if not v[dk.hasAudio]}
return items_by_has_not_audio | 63300c73d1e7d4202900a303716b471a0edb9ed9 | 3,634,002 |
def svm_predict(model, samples):
"""Predicts the response based on the trained model"""
return model.predict(samples)[1].ravel() | a510a64e602bbe14a3aa192cacd11b996704d91e | 3,634,003 |
import ast
from typing import List
from typing import Tuple
def _get_sim300(node: ast.Compare) -> List[Tuple[int, int, str]]:
"""
Get a list of all Yoda conditions.
Compare(
left=Constant(value='Yoda', kind=None),
ops=[Eq()],
comparators=[Name(id='i_am', ct... | 47db7b6e292ec49855d42d7b51c52ed906d3749d | 3,634,004 |
def dbl_cos_fit_func(p, x):
# the frequency is fixed
"""
A double sinus (fundamental + 1st harmonic) used as a fit function
"""
startidx = 0
base = 0
if len(p) % 2 != 0:
base = p[0]
startidx = 1
first_harm = p[startidx] * np.cos(
2 * np.pi * x + 2 * np.pi * p[star... | 7a8c816c6d47703ac32c85296dcc554f4e7c6f0d | 3,634,005 |
def __none_to_zero(string):
"""
Return '0' if the string is "none" or "null";
return the string itself otherwise.
@type string: C{string}
@param string: The string to test for values of "none" or "null".
@rtype: C{string}
@return: '0' if the string is "none" or "null", the string itself
... | 45da6720f4e8b6047e161dfe985421c8c7b37a38 | 3,634,006 |
def get_homepage_header():
""" Returns the page header image of the homepage """
homepage_id = get_homepage_id()
if homepage_id is None:
return None
return get_page_header(homepage_id) | 17ec01907c1a735964e7da8e2016ef36b414878c | 3,634,007 |
from typing import List
from typing import Dict
import ast
def trigger_data_load(
regions: List[str],
cluster_config_path: str,
default_config_path: str,
env_config_path: str,
input_vars: Dict[str, str],
) -> dict:
"""
:param regions: AWS regions in which the EMR job ne... | 9f51c3284de2acb65105615ec40b2611603d7a24 | 3,634,008 |
def _test_afqt(df):
""" NLSY provides percentile information for AFQT scores, reconstructed here
as a check based on NLSY instructions.
"""
# Breaking the logic of the code a bit, copies of the object are drawn from here.
df_internal = df.copy(deep=True)
# Adjust for missing values here, even ... | 97937957fc8d8782dde655fbf5f063264fe2e575 | 3,634,009 |
import csv
def _load_roiscsv(fp):
"""
Loads the specified ROIs CSV file.
:param fp: the file object for the ROIs CSV data to load
:type fp: file
:return: the list of predictions
:rtype: list
"""
result = []
reader = csv.DictReader(fp)
for i, row in enumerate(reader):
... | 13c697e224aba1562d15b39dac18c932a2b2fa0e | 3,634,010 |
def argmin(array):
""" Return the index to the maximum element of an array """
return min(zip(array, xrange(len(array))))[1] | 17e30a433d20eeef8d5a3cc48361245ba9ad9328 | 3,634,011 |
def braid_group_rep_loss(input_dim=1):
"""
Purpose
-------
loss for the braid group. When the loss is minimal, the braid group relations are satisfied for the generator R_op.
Parameters
----------
input_dim, the dimension of the R_op generator for the braid group.
... | 1d76f8a950ba997bc5a692cb56daa413d853491e | 3,634,012 |
def strains():
"""
Endpoint that returns a list of all available strains.
Returns
-------
strains : JSON
Returns a JSON array of all available strains.
"""
try:
strains = df2.to_json(orient="records")
except Exception as e:
raise e
return strains | 793a8cc692247c6a9b930f69a2956620b23f5809 | 3,634,013 |
def _number_of_digits(number: int) -> int:
""" Returns the number of digits in the given number """
return int(log10(number)) + 1 | c3270c53516793345ce2b96dbc205ccbbca3adf2 | 3,634,014 |
import glob
import os
def include(d, e):
"""Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern"""
return (d, [f for f in glob.glob('%s/%s'%(d, e)) if os.path.isfile(f)]) | b1afcf1698a2991001c480cc009bbe1858ce8120 | 3,634,015 |
def get_document(doc_slug: str) -> QuerySet:
""" Возвращает документ по слагу. """
return models.Document.objects.filter(
slug=doc_slug
).select_related('category', 'publisher') | 4c169b3ba1b4486a4c5c4c851dfa4e2efdb6ca07 | 3,634,016 |
def currentsellings():
"""shows a list of the ites that the user is currently selling"""
items = Item.query.filter(
(Item.user_id == session["user_id"]) & (Item.sold == 0)).all()
return render_template("currentsellings.html", items=items) | 6aa8dd754fda4b566f15909a556e9ca1678f7a7e | 3,634,017 |
def catches(raisable: Raisable, catchable: Catchable):
"""
Tests if raisable value would be catchable by catchable value.
"""
if isinstance(catchable, type):
catchable = [catchable]
if isinstance(raisable, type):
return any(issubclass(raisable, exc) for exc in catchable)
else:
... | 14ddb2465e618ba090e0885edf1141bd9657ac2b | 3,634,018 |
def bootstrap_test(
stat_val,
bootstrap_estimates,
nobs,
stat_val_control,
bootstrap_estimates_control,
nobs_control
) -> BootstrapTestResult:
"""
:param stat_val: sample value of statistic in treatment group
:param bootstrap_estimates: bootstrap estimates (10... | 488f6c8cbd5f27f97840e511a0d8b04f5c3647dd | 3,634,019 |
import urllib
import tempfile
def query_ned_by_refcode(refcode='2011ApJS..193...18W',
root_url='http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch'):
"""
Query NED for basic data on objects cited in a particular reference.
keywords:
refcode - 19-digit reference code for journal article.
... | 31846479c7098708ff67862852b1d1f9812e4dbb | 3,634,020 |
def calc_distance_between_point_and_line(line_points, p3):
"""[Calcs the perpendicular distance between a point and a line]
Arguments:
line_points {[list]} -- [list of two 2-by-1 np arrays with the two points that define the line]
p3 {[np array]} -- [point to calculate the distance from]
... | 3993d40afc5be216c5e9e8b1dee1061c11d8dfb4 | 3,634,021 |
def set_hash_status(qhash, **kwargs):
"""
Set the enabled status of a hash
Variables:
qhash => Hash to change the status
Arguments:
None
Data Block:
"true"
Result example:
{"success": True}
"""
user = kwargs['user']
data = request.json
if len(qhash) not... | e6f5fe661b01ad1b9b591ab9c23f61b62bce81f9 | 3,634,022 |
import matplotlib.pyplot as plt
def test_generate_x(energy_model, xtrajs, sample_energies, max_energy=150,
figsize=None, layout=None, colors=None, titles=True):
""" Generates using x trajectories as an example
Parameters
----------
energy_model : Energy Model
Energy model ... | ecda1737260fbe27b9fe2adcead0e1a12dec309d | 3,634,023 |
def ubatch_to_csv(batch):
"""
Utility function to convert a batch of APIUser data to CSV.
"""
permkey = 'permissions_dict'
fields = [k for k in batch[0].keys() if k != permkey]
fields.extend(batch[0][permkey].keys())
return '{}\n{}'.format(','.join(fields), '\n'.join([
','.join([str(... | 9950cb8e1f79f2cc37580142a125717e7e534de1 | 3,634,024 |
import requests
def get_user_repositories(username: str, show_forked: bool) -> list[Repository]:
"""
Retrieve the github repositories for a specific user.
Args:
username: The github username
show_forked: Whether to keep or discard forked repos
Returns: The github repositories for the... | 97dc310b1efbfde1121dcc79fa6464a33ed943f5 | 3,634,025 |
import torch
def evaluate_sample(
ds,
sample_id,
t=None,
visualise=True,
gt_masked=None,
model=None,
mask_targ=None,
save=False,
pose=None,
):
"""
Evaluate one sample of a dataset (ds). Calculate PSNR and mAP,
and visualise different model components for this sample. Ad... | 0f87f7cd35fd6263c646de29241b4c807828055f | 3,634,026 |
from googleapiclient import discovery
from googleapiclient import errors
from typing import NamedTuple
def retrieve_best_run(
project_id: str, job_id: str
) -> NamedTuple('Outputs', [('metric_value', float), ('alpha', float),
('max_iter', int)]):
"""Retrieves the parameters of the be... | 8fdc98557703cbedf8620c1c62ca62a223f15dee | 3,634,027 |
def FindDeck(transact, msg_list):
"""
Returns None if not a deck message.
:param transact:
:param msg_list:
:return:
"""
for msg in msg_list:
if 'connectResp' in msg:
try:
deck = msg['connectResp']['deckMessage']['deckCards']
Log('Found Dec... | 98e5ce5921f43c8ec260db052fcd7058d3c9f322 | 3,634,028 |
from typing import Optional
def mean(x: VariableLike,
dim: Optional[str] = None,
*,
out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise mean over the specified dimension.
If the input has variances, the variances stored in the output are based on
the "standard ... | 471d6f36b1ed30ce5dc57ec3a018f4adc0325094 | 3,634,029 |
def HarmonicOscillator(inverse_mass_matrix, k=1.0, m=1.0):
"""Potential and Kinetic energy of an harmonic oscillator."""
def potential_energy(x: TensorVariable) -> TensorVariable:
return at.sum(0.5 * k * at.square(x))
def kinetic_energy(p: TensorVariable) -> TensorVariable:
v = inverse_mas... | bf035050405f8d7d074ff1931e25d990cfba91f0 | 3,634,030 |
def guid_to_num(guid):
"""
Convert a DHT guid to an integer.
Args:
guid: The guid to convert, as a string or unicode, in
hexadecimal.
Returns:
An integer corresponding to the DHT guid given.
"""
return int(guid.rstrip('L'), base=16) | 7da3e7a60b6ae3410baab62083714f47a3afc790 | 3,634,031 |
def script_code(script_name):
"""Returns the four-letter ISO 15924 code of a script from its long name."""
load_data()
folded_script_name = _folded_script_name(script_name)
try:
return _HARD_CODED_FOLDED_SCRIPT_NAME_TO_CODE[folded_script_name]
except:
return _folded_script_name_to_co... | 6e04beff3dbaf22b0f348edc7fd2af201d16f024 | 3,634,032 |
from typing import Dict
def get_dashboard() -> Dict:
"""Get dashboard for user
:return: Returns dictionary with surveys and reports
:rtype: Dict
"""
user = get_user()
user_surveys = get_user_surveys(user)
result = []
for survey in user_surveys:
author = get_user(survey.Author... | 28d99043ffc1cd57b40916bc1a5839e8c38ee161 | 3,634,033 |
def acos(close):
"""Vector Trigonometric ACos
:param close:
:return:
:real:
"""
return ACOS(close) | 66c3be980464bb816435ee2ef65ab3ef2a4c3cfc | 3,634,034 |
import itertools
def gather_slice_list_items(slices, key):
"""For a list of slices, get the flattened list of all of a certain key."""
return list(itertools.chain(*[s[key] for s in slices if key in s])) | 068b511aefa124f9881f0d8cdc4d115b15922066 | 3,634,035 |
def mock_rasterio_open_cogs(band):
"""Mock rasterio Open for Sentinel2 dataset."""
assert band.startswith("s3://sentinel-cogs")
band = band.replace("s3://sentinel-cogs", SENTINEL_COG_BUCKET)
return rasterio.open(band) | 53e69cf3bd01dd9697d502aece59c00e16032fed | 3,634,036 |
def advance_time(df, delay, column=None, keep_all_timestep=False):
"""
This function rolls the given columns of the given dataframe by a number of hours defined by the delay.
It also erases the last n-rows (n=delay) of each sequences.
:param df:
:param delay:
:param column:
:param keep_all_t... | f361e4b63ef68ea0cdb923bf8337787a6094fe83 | 3,634,037 |
from re import T
def course():
""" Courses Controller """
mode = session.s3.hrm.mode
def prep(r):
if mode is not None:
auth.permission.fail()
if r.component_name == "training":
s3.crud_strings["hrm_training"].label_create = T("Add Trainee")
return True
... | a3197b21baee42982b780dfe76d80fe08e043324 | 3,634,038 |
from pathlib import Path
def run_tests(datout, tests, dat_inst=None, sim_id="", trb_exp=False,
hor_avg=False, chunks=None, **kw):
"""Run test functions for WRF output postprocessed with WRFlux.
Thresholds are hard-coded.
Parameters
----------
datout : nested dict
Postproc... | 008327f019c1f57b36d8aa67eef180d2b786a044 | 3,634,039 |
def reset_password(request):
"""view to reset the password"""
if request.method == "POST":
valid, errors = validate(*['code', 'password'], **get_request_data(request))
if not valid:
return Response({"error": errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
data = get_req... | cf75ee3b2fa5249b01abc690e4adebfd6d1ac16c | 3,634,040 |
def str_to_datetime(date: str) -> dt:
"""Convert str to datetime"""
if date is None:
return None
return dt.strptime(date, '%Y-%m-%d') | 5db25c97fd6e79d7c8ed26a95c4809a5c432c705 | 3,634,041 |
def test_applies_method_filters(app):
"""Method filters are applied for generated and rendered templates"""
with app.test_request_context():
genshi = app.extensions['genshi']
@genshi.filter('html')
def prepend_title(template):
return template | Transformer('head/title').prep... | e7fecc970507fa2745cb87a6ebf0c341fb0f1c76 | 3,634,042 |
def contributions(datafile):
""" text data file => list of string """
contribs = []
with open(datafile, 'r') as data:
for line in data.readlines():
line = line.strip()
line_data = line.split(" ")
info_string = " ".join(line_data[:-1])
contrib = {}
con... | 37c5743df822be2cefdbe0bad60db35491ea599d | 3,634,043 |
from datetime import datetime
import dateutil
def utcnow():
"""
Get the current UTC time which has the time zone info.
"""
return datetime.datetime.now(dateutil.tz.tzutc()) | 9efe15bac944732ee5260ba0834b796370cae0d3 | 3,634,044 |
from corehq.apps.users.models import CouchUser
def get_xform_location(xform):
"""
Returns the sql location associated with the user who submitted an xform
"""
user_id = getattr(xform.metadata, 'userID', None)
if not user_id:
return None
user = CouchUser.get_by_user_id(user_id)
if ... | e681325e161946bc12f32db721094ce9b68192f6 | 3,634,045 |
import cloudpickle
import inspect
def wrap_non_picklable_objects(obj, keep_wrapper=True):
"""Wrapper for non-picklable object to use cloudpickle to serialize them.
Note that this wrapper tends to slow down the serialization process as it
is done with cloudpickle which is typically slower compared to pick... | fdddcfbcff2137dd98b037171563e999ef53d138 | 3,634,046 |
def values(names):
"""
Method decorator that allows inject return values into method parameters.
It tries to find desired value going deep. For convinience injects list with only one value as value.
:param names: dict of "value-name": "method-parameter-name"
"""
def wrapper(func):
@wraps... | 324bbe30c9c0ae508c479cd760d3debd84cfa3d6 | 3,634,047 |
def post():
""" Get. """
return render_template('public/post.html') | dc33760c5e45f777efa1ddde5f6dae19676e2809 | 3,634,048 |
from typing import List
def ensemble(models: List [training.Model],
model_input: Tensor) -> training.Model:
""" ensemble part
"""
outputs = [model.outputs[0] for model in models]
y = Average()(outputs)
model = Model(model_input, y, name='ensemble')
return model | 41ec18fafaa19e67b40371fe553e8bc6ebdb10b3 | 3,634,049 |
def save_layout(request, layout_id):
""" Save layout properties """
if request.method != 'POST':
return res.get_only_post_allowed({})
layout_entry = BluesteelLayoutEntry.objects.filter(id=layout_id).first()
if layout_entry is None:
return res.get_response(404, 'Bluesteel layout not foun... | 735979a70ecb128589317a4eb26d7c077705a406 | 3,634,050 |
def _to_deck(group: ParseResults) -> Deck:
"""Parse a deck into a python list."""
result: Deck
if "size" in group:
N = int(group["size"])
if group["type"] == "C":
result = ["".join(group.value)]
elif group["type"] == "I":
result = [int("".join(k)) for k in gro... | dcf67e00ae293b88386d2b58bed66b59e7588b41 | 3,634,051 |
def build_gabriel_graph_from_delaunay(X, tri, delaunay_adjacency_matrix):
"""Remove edges from delaunay triangulation and returns the adjaceny matrix of a Gabriel graph
:param delaunay_adjacency_matrix: scipy sparse matrix (csr format)
"""
# Convert adjacency matrix to coo format for direct access to ea... | 6da3883cbc03357c737e358903d875535b8ee4fc | 3,634,052 |
import os
def list_image_files(dirs):
"""lists the images files under the dirs.
:return:
a list of tuples
the shape of tuple: (image_filename, subdir, fullpath)
"""
images = []
for a_dir in dirs:
for direntry in os.listdir(a_dir):
# Anything starting with "." is ignored
if direntry[0:1] ... | e597e58a5ecf5380e4658fb36d1ee45a6b651bc3 | 3,634,053 |
import random
def randomize_demand(demand):
"""Return a randomized demand when given a static demand"""
return random.uniform(0, 2.25) * demand | 01eed8f0008e71af117920782a2a42b566055a89 | 3,634,054 |
def _collect_input_shape(input_tensors):
"""Collects the output shape(s) of a list of Keras tensors.
# Arguments
input_tensors: list of input tensors (or single input tensor).
# Returns
List of shape tuples (or single tuple), one tuple per input.
"""
input_tensors = to_list(input_t... | 4c3dfc82f999c6def2a3c78c2f323de8a4e2c67c | 3,634,055 |
from datetime import datetime
import math
def iaga2df(iaga2002_fname, D_to_radians=True):
"""
Parser the magnetometer data record stored in the IAGA-2002 format
file *iaga2002_fname*. If *D_to_radians*, declination data (D) are
converted from degrees to radians. Return the tuple with the
:class:`D... | 394d24392a00aed1be4e5975794bb67fecf03f14 | 3,634,056 |
def geom_bar(mapping=aes(), *, fill=None, color=None, position="stack", size=None):
"""Create a bar chart that counts occurrences of the various values of the ``x`` aesthetic.
Supported aesthetics: ``x``, ``color``, ``fill``
Returns
-------
:class:`FigureAttribute`
The geom to be applied.
... | 5d617797742ad4ea1e2b13424bc80054f97be436 | 3,634,057 |
import argparse
def parse_args(args):
"""define arguments"""
parser = argparse.ArgumentParser(description="go_term_enrichment")
parser.add_argument(
"file_names",
type=str,
help="Name of folder and filenames for the promoters extracted",
)
parser.add_argument(
"go_d... | 9501ca0e9e603231751a2e7fe7a1dcf90f753be4 | 3,634,058 |
def MobileNetV3_Large_Base(num_classes,
in_channels):
"""构建基础(大型)MobileNetV3
"""
return MobileNetV3_Large(num_classes=num_classes,
in_channels=in_channels,
alpha=1.0) | 979b48ee5488e0fe3a566983539a4cd9b683b862 | 3,634,059 |
def compute_trajectory_points(path, sgrid,
ugrid, xgrid,
dt=1e-2, smooth=True,
smooth_eps=1e-4):
"""Compute trajectory with uniform sampling time.
Note
----
Additionally, if `smooth` is True, the return trajectory... | 924a68984a08d4db821e94e2fdf32879bd03f356 | 3,634,060 |
import argparse
def get_split_parser():
"""
Returns the parser used for the split tool which defines all the available arguments.
This can be used for generating documentation about the tool using Sphinx.
:return: the parser object
:rtype: :class:`argparse.ArgumentParser`
"""
parser = ar... | 8d79214d1d17236d1e2ab7e8b4ad991a4f962e14 | 3,634,061 |
from typing import Tuple
def _reorder_cols(
df, key_columns: Tuple[str], master_grouping_key: str
) -> pd.DataFrame:
"""
Helper function for creating a user-friendly schema structure for the output prediction
dataframe that mirrors what would be expected (grouping columns preceding data).
:param ... | 05d51a1d8d3869dfb6bd83d5d81e6c9b56638c73 | 3,634,062 |
import subprocess
def clip(text):
"""
Attempts to copy the specified text to the clipboard, returning
a boolean indicating success.
"""
text_bytes = text.encode()
try:
pbcopy = subprocess.Popen("pbcopy", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
pbcopy.communicate(text_bytes)
return(not pbcopy.... | 7096bc53dfc1d33af0536143ebb7d09c23e29e0f | 3,634,063 |
from typing import Dict
from typing import Any
import requests
def create_rule(rule: Dict[str, Any]) -> Dict[str, Any]:
"""Create a rule, returning the result from SmartThings."""
url = _url("/rules")
params = {"locationId": CONTEXT.get().location_id}
response = requests.post(url=url, headers=_headers... | f68010520874d07b5c469d91d9e7ca804460535e | 3,634,064 |
from config import bot_config as _BOT_CONFIG
def _get_bot_config():
"""Returns the bot_config.py module. Imports it only once.
This file is called implicitly by _call_hook() and _call_hook_safe().
"""
global _BOT_CONFIG
if not _BOT_CONFIG:
return _BOT_CONFIG | 0b725caa079b37ac2274b4350c4473e5016efac2 | 3,634,065 |
def img_post_process(img_tensor):
"""Image postprocess
Convert torch.tensor() images into list of cv2 images.
1. Convert torch.tensor() to np.array(), and transpose [C, H, W] to [H, W, C].
2. Scale [0., 1.] into [0, 255].
3. Convert data format float to np.uint8.
4. Convert color channels from R... | c43ded6097d726ce62e8ad1c8ae5025ce4d21cb8 | 3,634,066 |
def apply_grid(dataset, masker=None, scale=5, threshold=None):
""" Imposes a 3D grid on the brain volume and averages across all voxels
that fall within each cell.
Args:
dataset: Data to apply grid to. Either a Dataset instance, or a numpy
array with voxels in rows and features in column... | 22727b208f9f57037e2d35dc78acc7bdbd49212a | 3,634,067 |
from pathlib import Path
from typing import Optional
from typing import Set
def cookiecutter_template(
output_dir: Path,
repo: Repo,
cruft_state: CruftState,
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
checkout: Optional[str] = None,
deleted_paths: Optional[Set[Path]] ... | 0351039fc7022de1908fca2e2bc54676cd01bc56 | 3,634,068 |
def get_item():
"""Returns a dict representing an item."""
return {
'name': 'Nikon D3100 14.2 MP',
'category': 'Cameras',
'subcategory': 'Nikon Cameras',
'extended_info': {}
} | 692c3d83ee1cc04026e71b7ad7357ebd9930f47f | 3,634,069 |
import math
def humanify_ms(ms: int) -> str:
""" Converts an amount of millis to a more readable string.
Args:
ms (int): the amount of millis to convert
Returns:
The human string that represents the given amount of millis
"""
if ms > TimeUnits.MS_IN_MIN:
return "{:d}m {:d... | 6130ea6a6de05c12b04ae14be3ff2f180c113391 | 3,634,070 |
import torch
def abs_(input):
"""
In-place version of :func:`treetensor.torch.abs`.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> t = ttorch.tensor([12, 0, -3])
>>> ttorch.abs_(t)
>>> t
tensor([12, 0, 3])
>>> t = ttorch.t... | 65b32c91cf00a72b94b950d0e65cca71390b8c24 | 3,634,071 |
import os
def n_age_sex():
"""Return DataFrame of population split by age and sex."""
path = os.path.join(INPUT_DIR, 'census/sex_by_age.xlsx')
data = pd.read_excel(path, 'Sheet 1', header=10, skipfooter=3, index_col=0)
data = data[2:][['Males', 'Females']].reset_index(drop=True)
return data | b1609aa4a4194bb3d73ddec94c46fe65706e1440 | 3,634,072 |
import pathlib
def get_filepath(filepath, overwrite):
"""
Get the filepath to download to and ensure dir exists.
Returns
-------
`pathlib.Path`, `bool`
"""
filepath = pathlib.Path(filepath)
if filepath.exists():
if not overwrite:
return str(filepath), True
... | bceb462f98f328d20226d6e516d78b027614cd01 | 3,634,073 |
import argparse
import re
import socket
def argparse_is_valid_hostname(hostname):
""" Validate the hostname passed in.
Returns the hostname if it is valid, otherwise it raises an exception.
"""
if len(hostname) > 255:
raise argparse.argumenttypeerror("Argument 'hostname' is not valid. " +... | 0a5493a94bf4859a971e4079efb2b6ca6fdbaf96 | 3,634,074 |
import sys
def compute_census(img_l: np.ndarray = None, img_r: np.ndarray = None, offset: int = 7) -> (np.ndarray, np.ndarray):
"""
Census feature extraction (for more details see https://en.wikipedia.org/wiki/Census_transform)
:param img_l: left image
:param img_r: right image
:param offset: pix... | d4beb0f04ed8a7b80ba89790cd47b17ccc338caf | 3,634,075 |
import textwrap
def dedent(text):
"""Remove any common leading whitespace from every line in a given text."""
return textwrap.dedent(text) | 514f9f41feac1c19ff92d6c9258bf54d7d3d7bd8 | 3,634,076 |
from typing import Dict
from typing import List
def get_agents(agents: Dict, nr_players: int, action_num: int, state_shape: List):
"""
Initalize agents to play the game.
:param nr_players: Number of players, amount of agents generated
:param agents: Dictionary of agent_name: number of agents pairs
... | dfaee6e93e14a33659817da626f8dd990c46d528 | 3,634,077 |
def enumerate_square(i, n):
"""
Given i in the range(n^2-n) compute a bijective mapping
range(n^2-n) -> range(n)*range(n-1)
"""
row = int(i // (n-1))
col = int(i % (n-1))
if col >= row:
col += 1
return row, col | 93d3465c88a7bc9952161524fded4d7250131a65 | 3,634,078 |
def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit,
pad_remover=None):
"""Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that co... | 41051acefd16acff70f25d6402c43bf92176217d | 3,634,079 |
def extract_names(bigrams):
"""
Tag each of the bigram tuples with the appropriate Part of Speech.
"""
named_bigrams = []
NUM_BIGRAMS = len(bigrams)
stemmer = LancasterStemmer()
for index, bigram in enumerate(bigrams):
if bigram[0].upper() in FIRST_NAMES:
person = " ".joi... | 0eaf7e29940750af52b4d096ea47bc3524897817 | 3,634,080 |
def GetActiveProjectAndAccount():
"""Get the active project name and account for the active credentials.
For use with wrapping legacy tools that take projects and credentials on
the command line.
Returns:
(str, str), A tuple whose first element is the project, and whose second
element is the account.
... | cde41445f0f0811a8e580ff617f08573fac91d9a | 3,634,081 |
import falcon
def csrf_protection(func):
"""
Protect resource from common CSRF attacks by checking user agent and referrer
"""
def wrapped(self, req, resp, *args, **kwargs):
# Assume curl and python-requests are used intentionally
if req.user_agent.startswith("curl/") or req.user_agent... | 411a89f02eee3d236ae1f1dc124dfac3a22800d8 | 3,634,082 |
from pathlib import Path
async def get_system(
system_id: UUID = Path(
..., description="ID of system to get", example=models.SYSTEM_ID
),
storage: StorageInterface = Depends(StorageInterface),
) -> models.StoredPVSystem:
"""Get a single PV System"""
with storage.start_transaction() as st:... | 99d600f5f67c6aacd93866f2f874d5aec8fe2089 | 3,634,083 |
import re
def get_playback_time(playback_duration):
""" Get the playback time(in seconds) from the string:
Eg: PT0H1M59.89S
"""
# Get all the numbers in the string
numbers = re.split('[PTHMS]', playback_duration)
# remove all the empty strings
numbers = [value for value in numbers if v... | 6a68c68ce465610b57626a725ac9c8889b527fdb | 3,634,084 |
def rate_limit(state, task_name, rate_limit, **kwargs):
"""Tell worker(s) to modify the rate limit for a task by type.
See Also:
:attr:`celery.task.base.Task.rate_limit`.
Arguments:
task_name (str): Type of task to set rate limit for.
rate_limit (int, str): New rate limit.
"""
... | abdd903fe492e64dec799e02d9a4359814067a1e | 3,634,085 |
import torch
def listdict2dictlist(listdict: list, to_array=False) -> dict:
"""
@type listdict: list
@param listdict: list of dicts with the same keys
@return: dictlist: dict of lists of the same lengths
@rtype: dict
"""
d = {k: [d[k] for d in listdict] for k in listdict[0].keys()}
if ... | 77c464d1a2e272bf43b39489ea41294603464334 | 3,634,086 |
def hitLine(lineA, lineB, point, lineWidth):
"""Checks whether the point is in line or out.
lineA tuple: a point of the line.
lineB tuple: another point of the line.
point tuple: point we want to check.
lineWidth float: width of the line.
returns: True if in and False if out.
"""
if li... | b20430c8ef161d19431c5e4cc19951cc09ffa352 | 3,634,087 |
def parse_args() -> Namespace:
"""
Parse arguments.
Parse optional arguments passed to the application during runtime and
return the results.
Returns
-------
Namespace
Returns a ``Namespace`` containing all of the arguments passed by the
user including defaults.
"""
... | 8326c37ccd1a5878dd54fb84aa25ea78a87451c8 | 3,634,088 |
def PatchWord(ea, value):
"""
Change value of a program word (2 bytes)
@param ea: linear address
@param value: new value of the word
@return: 1 if successful, 0 if not
"""
return idaapi.patch_word(ea, value) | e2e03d198764b706f643c5a41aefa7a6a67fc387 | 3,634,089 |
def _binary_array_to_hex(arr):
"""
internal function to make a hex string out of a binary array
"""
h = 0
s = []
for i, v in enumerate(arr.flatten()):
if v:
h += 2**(i % 8)
if (i % 8) == 7:
s.append(hex(h)[2:].rjust(2, '0'))
h = 0
return "... | b705e4dc1dfc48f92f7c97dd7ba9d4dd4c4d0a98 | 3,634,090 |
def float_nsf(num, precision=17):
"""n-Significant Figures"""
return ('{0:.%ie}' % (precision - 1)).format(float(num)) | c2390b69364455adc6220e1e4aad81d7081bd5e4 | 3,634,091 |
import logging
def logit_layer_for_bitext(
nb_classes, # V
inputs, # [B, M, dim]
outputs, # [B, N]
dim,
nb_softmax_samples, # S
is_training,
approximation='botev-batch',
support=None, # [S]
importance=None, # [S]
name='logit'
):
... | 1efd3cffe3194c7bca9b571ddd01369adeef9207 | 3,634,092 |
import os
def get_counts_filename(align_path, output_dir):
"""returns counts output path
Arguments:
- align_path: path to the alignment file. The basename will be
modified to use a .txt suffix
- output_dir: directory where the counts file is to be written
"""
fn = os.path.b... | 446ad99d4ab56234b41a07729003386f3a6389af | 3,634,093 |
def run_command(client: ParallelSSHClient, command: str) -> CommandResult:
"""Executes identical command on all hosts attached to client.
Will wait until all hosts complete the command execution or timeout is reached.
Re-raises pssh exceptions.
# TODO Handle more specific exceptions
"""
# stop_... | 2cf38470de443706a1109c1c08a3920ed202a6ca | 3,634,094 |
def angle_close(angle1, angle2):
""" Determines whether an angle1 is close to angle2. """
return abs(angle_difference(angle1, angle2)) < np.pi/8 | 7a480a94de8440ff50307e9c7a218424fe45675a | 3,634,095 |
def server_url():
# type: () -> Optional[str]
"""Get the configured server URL
"""
url = toolkit.config.get(SERVER_URL_CONF_KEY)
if not url:
raise ValueError("Configuration option '{}' is not set".format(
SERVER_URL_CONF_KEY))
if url[-1] == '/':
url = url[0:-1]
re... | e4958022e1beb415af4f23e93d678dd9982e1637 | 3,634,096 |
def clean_data():
"""
Method for cleaning the data and removing unnecessary features
Args:
None
Returns:
df (pandas dataframe): Return pandas dataframe
"""
df = pd.read_csv("dashboard/asset/data/kl_billboard.csv")
# Drop different types of roads such as motorway, trunk etc... | b3fa3cd8b590b5f7ec4168006a0470c0398a2f8a | 3,634,097 |
from stingray.lightcurve import Lightcurve
from stingray.events import EventList
from stingray.crossspectrum import Crossspectrum
from hendrics.io import get_file_type
from stingray.io import _retrieve_pickle_object
import logging
def load_dataset_from_intermediate_file(fname):
"""Save Stingray object to intermed... | e1603554494082bd4cc155a81d283225e4305e73 | 3,634,098 |
import functools
def _FlowMethod(func):
"""Decorator that checks the if port_id exists on board."""
@functools.wraps(func)
def wrapper(instance, port_id, *args, **kwargs):
if port_id not in instance.flows:
raise FlowManagerError('Not a exist port_id %d' % port_id)
return func(instance, port_id, *a... | d977b07b329c2943aa2dca465cab80227e8c67f3 | 3,634,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.