uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3298842ab2d06422a2705ab | train | function | def instanceNorm2dTest(bnd, dtype, atol, calctype):
batchsize, maps, h, w = 3, 4, 5, 5
epsilon, norm = 1e-5, h * w
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1).astype(calctype)
data = bnd.GP... | def instanceNorm2dTest(bnd, dtype, atol, calctype):
| batchsize, maps, h, w = 3, 4, 5, 5
epsilon, norm = 1e-5, h * w
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1).astype(calctype)
data = bnd.GPUArray.toGpu(hostData)
scale, bias = bnd.GPUArray.t... | ingrad.get(), atol=atol)
assert np.allclose(hostScaleGrad.ravel(), scalegrad.get(), atol=atol)
assert np.allclose(hostBiasGrad.ravel(), biasgrad.get(), atol=atol)
hostMean = np.random.randn(*hostMean.shape).astype(np.float32)
hostVar = 1.0 + np.random.randn(*hostInvVar.shape).astype(np.float32)**2
mean, var = b... | 201 | 201 | 671 | 16 | 185 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | instanceNorm2dTest | instanceNorm2dTest | 138 | 182 | 138 | 138 | 0eccbadf768a3b4c9a6fca82e31fe23325f215fd | bigcode/the-stack | train |
c55264e89ddcbdb1d901854a | train | function | def backendTest(Backend):
for deviceIdx in range(Backend.getDeviceCount()):
bnd = Backend.getBackend(deviceIdx, initmode=2)
for dtype, atol in bnd.dtypesSupported():
batchNorm2dTest(bnd, dtype, atol, np.float32)
batchNorm3dTest(bnd, dtype, atol, np.float32)
instanceNorm2dTest(bnd, dtype, atol, np.float32... | def backendTest(Backend):
| for deviceIdx in range(Backend.getDeviceCount()):
bnd = Backend.getBackend(deviceIdx, initmode=2)
for dtype, atol in bnd.dtypesSupported():
batchNorm2dTest(bnd, dtype, atol, np.float32)
batchNorm3dTest(bnd, dtype, atol, np.float32)
instanceNorm2dTest(bnd, dtype, atol, np.float32)
mapLRN2dTest(bnd, dt... | import itertools
import numpy as np
def unittest():
from PuzzleLib.Cuda import Backend
backendTest(Backend)
def backendTest(Backend):
| 31 | 64 | 127 | 6 | 25 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | backendTest | backendTest | 10 | 20 | 10 | 10 | 99ffa73b44780f693108605ca9cfe74a5f6fb062 | bigcode/the-stack | train |
a40b0fdea115cd9724c2a5cf | train | function | def batchNorm3dTest(bnd, dtype, atol, calctype):
batchsize, maps, d, h, w = 2, 5, 2, 3, 2
epsilon, norm = 1e-5, batchsize * d * h * w
hostData = np.random.randn(batchsize, maps, d, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1, 1).asty... | def batchNorm3dTest(bnd, dtype, atol, calctype):
| batchsize, maps, d, h, w = 2, 5, 2, 3, 2
epsilon, norm = 1e-5, batchsize * d * h * w
hostData = np.random.randn(batchsize, maps, d, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1, 1).astype(calctype)
data = bnd.GPUArray.toGpu(hostData... |
hostInGrad = hostGrad * hostScale * hostInvVar + (2 * hostVarGrad * (hostData - hostMean) + hostMeanGrad) / norm
hostInGrad = hostInGrad.astype(dtype)
assert np.allclose(hostInGrad, ingrad.get(), atol=atol)
assert np.allclose(hostScaleGrad.ravel(), scalegrad.get(), atol=atol)
assert np.allclose(hostBiasGrad.rav... | 256 | 256 | 879 | 16 | 240 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | batchNorm3dTest | batchNorm3dTest | 80 | 135 | 80 | 80 | fb17bc6ad52c84c40a78a2c61011b13a1c3d38c7 | bigcode/the-stack | train |
163b66205d2ed24eb7f95ca6 | train | function | def unittest():
from PuzzleLib.Cuda import Backend
backendTest(Backend)
| def unittest():
| from PuzzleLib.Cuda import Backend
backendTest(Backend)
| import itertools
import numpy as np
def unittest():
| 11 | 64 | 17 | 3 | 7 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | unittest | unittest | 5 | 7 | 5 | 5 | a553aa0316865e8345de7d2ff1c89949ff61ab6c | bigcode/the-stack | train |
15b84a0b3f1594cb6be2bd9a | train | function | def batchNorm2dTest(bnd, dtype, atol, calctype):
batchsize, maps, h, w = 4, 5, 2, 3
epsilon, norm = 1e-5, batchsize * h * w
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1).astype(calctype)
data ... | def batchNorm2dTest(bnd, dtype, atol, calctype):
| batchsize, maps, h, w = 4, 5, 2, 3
epsilon, norm = 1e-5, batchsize * h * w
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
hostScale = np.random.randn(1, maps, 1, 1).astype(calctype)
hostBias = np.random.randn(1, maps, 1, 1).astype(calctype)
data = bnd.GPUArray.toGpu(hostData)
scale, bias = bnd... | import itertools
import numpy as np
def unittest():
from PuzzleLib.Cuda import Backend
backendTest(Backend)
def backendTest(Backend):
for deviceIdx in range(Backend.getDeviceCount()):
bnd = Backend.getBackend(deviceIdx, initmode=2)
for dtype, atol in bnd.dtypesSupported():
batchNorm2dTest(bnd, dtype, ato... | 168 | 254 | 847 | 16 | 152 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | batchNorm2dTest | batchNorm2dTest | 23 | 77 | 23 | 23 | 0ad4b65d9c85e17699a2a1b802f6dce5ce823a73 | bigcode/the-stack | train |
bf0ddc883a9d3832feaa4e9b | train | function | def crossMapLRN2dTest(bnd, dtype, atol):
batchsize, maps, h, w = 2, 10, 2, 3
N, alpha, beta, K = 5, 1.0, 0.5, 2.0
lookBehind = int((N - 1) / 2)
lookAhead = N - lookBehind
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
data = bnd.GPUArray.toGpu(hostData)
outdata = bnd.dnn.crossMapLRN(data, N=N... | def crossMapLRN2dTest(bnd, dtype, atol):
| batchsize, maps, h, w = 2, 10, 2, 3
N, alpha, beta, K = 5, 1.0, 0.5, 2.0
lookBehind = int((N - 1) / 2)
lookAhead = N - lookBehind
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
data = bnd.GPUArray.toGpu(hostData)
outdata = bnd.dnn.crossMapLRN(data, N=N, alpha=alpha, beta=beta, K=K)
norms = ... | (0, x - lookBehind), min(w, x + lookAhead))
slcdata, slcgrad = hostData[b, c, slcy, slcx].ravel(), hostGrad[b, c, slcy, slcx].ravel()
slcnorms = norms[b, c, slcy, slcx].ravel()
hostInGrad[b, c, y, x] -= k * hostData[b, c, y, x] * np.dot(slcgrad, slcdata / slcnorms**(beta + 1))
hostInGrad = hostInGrad.astype(d... | 164 | 164 | 549 | 15 | 149 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | crossMapLRN2dTest | crossMapLRN2dTest | 230 | 268 | 230 | 230 | a09671a60b5f8c83b5b075b61e98c0c82ef4af00 | bigcode/the-stack | train |
1eb7b43eac218641fce35c1a | train | function | def mapLRN2dTest(bnd, dtype, atol):
batchsize, maps, h, w = 2, 2, 9, 10
N, alpha, beta, K = 5, 1.0, 0.5, 2.0
lookBehind = int((N - 1) / 2)
lookAhead = N - lookBehind
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
data = bnd.GPUArray.toGpu(hostData)
outdata = bnd.dnn.mapLRN(data, N=N, alpha=al... | def mapLRN2dTest(bnd, dtype, atol):
| batchsize, maps, h, w = 2, 2, 9, 10
N, alpha, beta, K = 5, 1.0, 0.5, 2.0
lookBehind = int((N - 1) / 2)
lookAhead = N - lookBehind
hostData = np.random.randn(batchsize, maps, h, w).astype(dtype)
data = bnd.GPUArray.toGpu(hostData)
outdata = bnd.dnn.mapLRN(data, N=N, alpha=alpha, beta=beta, K=K)
norms = np.em... | (hostInvVar.shape, dtype=np.float32)
for b, c in itertools.product(range(batchsize), range(maps)):
hostCorrs[b, c] = np.dot(hostScGrad[b, c].ravel(), hostNormData[b, c].ravel()) / norm
hostInGrad = (hostScGrad - np.mean(hostScGrad, axis=(2, 3), keepdims=True) - hostCorrs * hostNormData) * hostInvVar
hostInGrad =... | 178 | 178 | 596 | 14 | 164 | EmilPi/PuzzleLib | Cuda/Wrappers/CuDnnNorm.py | Python | mapLRN2dTest | mapLRN2dTest | 185 | 227 | 185 | 185 | 6e59afd93b64523883ef2b90cdff96d83256b20e | bigcode/the-stack | train |
fe6511623deb22b1fed3e548 | train | class | class Config:
def __init__(self):
self.verbosity: int = 0
self.searcher: str = "ausearch"
self.params: Dict[str, Dict[str, Union[str, List[str]]]] = {}
self.format: str = "str"
self.modules: List[str] = []
self.checker: str = "ezcheck"
self.default_dist: str =... | class Config:
| def __init__(self):
self.verbosity: int = 0
self.searcher: str = "ausearch"
self.params: Dict[str, Dict[str, Union[str, List[str]]]] = {}
self.format: str = "str"
self.modules: List[str] = []
self.checker: str = "ezcheck"
self.default_dist: str = "cipheydists:... | Any]] = {}
def mark_ctext(self, ctext: Any) -> bool:
if isinstance(ctext, (str, bytes)) and len(ctext) < 4:
logging.debug(f"Candidate {ctext.__repr__()} too short!")
return False
if ctext in self._cache:
logging.debug(f"Deduped {ctext.__repr__()}")
... | 256 | 256 | 1,283 | 3 | 253 | yezz123/Ciphey | ciphey/iface/_config.py | Python | Config | Config | 54 | 227 | 54 | 54 | ada0eeb1d4c44cb930d8b14394f5b002f087b86e | bigcode/the-stack | train |
7033fc3f017f2bfb0591d500 | train | class | class Cache:
"""Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions"""
def __init__(self):
self._cache: Dict[Any, Dict[str, Any]] = {}
def mark_ctext(self, ctext: Any) -> bool:
if isinstance(ctext, (str, bytes)) and len(ctext) < 4:
... | class Cache:
| """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions"""
def __init__(self):
self._cache: Dict[Any, Dict[str, Any]] = {}
def mark_ctext(self, ctext: Any) -> bool:
if isinstance(ctext, (str, bytes)) and len(ctext) < 4:
loggi... | import datetime
import os
import pydoc
from typing import Any, Callable, Dict, List, Optional, Type, Union
import appdirs
import yaml
import logging
from rich.logging import RichHandler
from . import _fwd
from ._modules import PolymorphicChecker, ResourceLoader, Searcher
class Cache:
| 71 | 80 | 269 | 3 | 67 | yezz123/Ciphey | ciphey/iface/_config.py | Python | Cache | Cache | 15 | 47 | 15 | 15 | 559f929acb02a5a42aae294adf07896d3c7a727e | bigcode/the-stack | train |
434d7bf556dae01bae571ac3 | train | function | def split_resource_name(full_name: str) -> (str, str):
return full_name.split("::", 1)
| def split_resource_name(full_name: str) -> (str, str):
| return full_name.split("::", 1)
| res
val = get_value()
target[keyname] = val
return val
def try_get(self, ctext: Any, keyname: str):
return self._cache[ctext].get(keyname)
def split_resource_name(full_name: str) -> (str, str):
| 64 | 64 | 26 | 15 | 49 | yezz123/Ciphey | ciphey/iface/_config.py | Python | split_resource_name | split_resource_name | 50 | 51 | 50 | 50 | b668c41f702a00c7f2dc3024a10a2ebb7b1bfe03 | bigcode/the-stack | train |
638feb6aa56b4defb9bb1c73 | train | class | class Thermometer_GFX(displayio.Group):
def __init__(self, celsius=True, usa_date=True):
"""Creates a Thermometer_GFX object.
:param bool celsius: Temperature displayed as F or C
:param bool usa_date: Use mon/day/year date-time formatting.
"""
# root displayio group
r... | class Thermometer_GFX(displayio.Group):
| def __init__(self, celsius=True, usa_date=True):
"""Creates a Thermometer_GFX object.
:param bool celsius: Temperature displayed as F or C
:param bool usa_date: Use mon/day/year date-time formatting.
"""
# root displayio group
root_group = displayio.Group(max_size=20)... | """
GFX helper file for
thermometer.py
"""
import board
import displayio
from adafruit_display_text.label import Label
from adafruit_bitmap_font import bitmap_font
cwd = ("/"+__file__).rsplit('/', 1)[0] # the current working directory (where this file is)
# Fonts within /fonts folder
info_font = cwd+"/fonts/Nunito-Bl... | 112 | 256 | 1,215 | 9 | 103 | injectedfusion/Adafruit_Learning_System_Guides | PyPortal_Smart_Thermometer/thermometer_helper.py | Python | Thermometer_GFX | Thermometer_GFX | 16 | 147 | 16 | 16 | 65c7c4ecf6f4263108300c851468c73f9645eae9 | bigcode/the-stack | train |
7c5e378db1a19eb963c096aa | train | class | class LAVaccineCountyDemographics(LAVaccineCounty):
variables = {
"PercInt": variables.INITIATING_VACCINATIONS_ALL,
"PercComp": variables.FULLY_VACCINATED_ALL,
}
def normalize(self, data):
data = self.arcgis_jsons_to_df(data)
# formatted as: {'demographic':[demographic valu... | class LAVaccineCountyDemographics(LAVaccineCounty):
| variables = {
"PercInt": variables.INITIATING_VACCINATIONS_ALL,
"PercComp": variables.FULLY_VACCINATED_ALL,
}
def normalize(self, data):
data = self.arcgis_jsons_to_df(data)
# formatted as: {'demographic':[demographic value columns], ...}
demographcis = {
... | ace_by_Parish", 0, 5)
def normalize(self, data):
df = self.arcgis_jsons_to_df(data)
df = df.rename(
columns={
"PFIPS": "location",
}
)
df["dt"] = self._retrieve_dt("US/Central")
melted = df.melt(
id_vars=["dt", "location"]... | 182 | 182 | 607 | 12 | 170 | christopherturner/can-scrapers | can_tools/scrapers/official/LA/la_county.py | Python | LAVaccineCountyDemographics | LAVaccineCountyDemographics | 45 | 117 | 45 | 45 | 1b6ae6127660f1be2458bcf9bb6823d6af475ca3 | bigcode/the-stack | train |
772dce28cb0b5f0ec15f1db9 | train | class | class LAVaccineCounty(ArcGIS):
provider = "state"
ARCGIS_ID = "O5K6bb5dZVZcTo5M"
has_location = True
location_type = "county"
state_fips = int(us.states.lookup("Louisiana").fips)
source = "https://ladhh.maps.arcgis.com/apps/opsdashboard/index.html#/7b2a0703a129451eaaf9046c213331ed"
source_na... | class LAVaccineCounty(ArcGIS):
| provider = "state"
ARCGIS_ID = "O5K6bb5dZVZcTo5M"
has_location = True
location_type = "county"
state_fips = int(us.states.lookup("Louisiana").fips)
source = "https://ladhh.maps.arcgis.com/apps/opsdashboard/index.html#/7b2a0703a129451eaaf9046c213331ed"
source_name = "Louisiana Department of H... | import pandas as pd
import us
import numpy as np
from can_tools.scrapers import variables
from can_tools.scrapers.official.base import ArcGIS
class LAVaccineCounty(ArcGIS):
| 42 | 90 | 302 | 9 | 32 | christopherturner/can-scrapers | can_tools/scrapers/official/LA/la_county.py | Python | LAVaccineCounty | LAVaccineCounty | 8 | 42 | 8 | 8 | 93c9f30edc577884e97eceb888d154aa93dfd2e7 | bigcode/the-stack | train |
b2977337a3fe478fa2becffc | train | function | def plot_colors(ax, alphabet):
x_space=0.1
y_space=0.3
scheme_names = sorted(graphics.list_color_scheme_names(alphabet))
scheme_names.reverse()
schemes = [graphics.get_color_scheme(name, alphabet)
for name in scheme_names]
for i, scheme in enumerate(schemes):
for j, color ... | def plot_colors(ax, alphabet):
| x_space=0.1
y_space=0.3
scheme_names = sorted(graphics.list_color_scheme_names(alphabet))
scheme_names.reverse()
schemes = [graphics.get_color_scheme(name, alphabet)
for name in scheme_names]
for i, scheme in enumerate(schemes):
for j, color in enumerate(scheme):
... | otite color schemes
=====================
This script displays the available color schemes.
"""
# Code source: Patrick Kunzmann
# License: BSD 3 clause
import biotite.sequence as seq
import biotite.sequence.graphics as graphics
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSp... | 85 | 85 | 284 | 7 | 77 | danijoo/biotite | doc/examples/scripts/sequence/color_schemes.py | Python | plot_colors | plot_colors | 18 | 42 | 18 | 18 | 6a588dde40a631955e4e5b0a82c03cadebcd0961 | bigcode/the-stack | train |
923c172a30ad0ab1832802ab | train | function | def get_world_size():
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
| def get_world_size():
| if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
| .stack(labels, dim=0),
# "image_id": torch.as_tensor(img_id)}
return images, targets
def mkdir(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def get_world_size():
| 64 | 64 | 27 | 5 | 58 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | get_world_size | get_world_size | 347 | 350 | 347 | 347 | 9516930b77987bf423071b75969326f09c6a4600 | bigcode/the-stack | train |
920077ba768f90c30d996b9d | train | function | def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq,
train_loss=None, train_lr=None, warmup=False):
model.train()
metric_logger = MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]... | def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq,
train_loss=None, train_lr=None, warmup=False):
| model.train()
metric_logger = MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
lr_scheduler = None
if epoch == 0 and warmup is True: # 当训练第一轮(epoch=0)时,启用warmup训练方式,可理解为热身训练
warmup_factor = ... | import math
import sys
import time
import datetime
import pickle
import os
import torch
import errno
from collections import defaultdict, deque
import torch.distributed as dist
from train_utils.coco_utils import get_coco_api_from_dataset
from train_utils.coco_eval import CocoEvaluator
def train_one_epoch(model, optimiz... | 93 | 165 | 553 | 31 | 61 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | train_one_epoch | train_one_epoch | 15 | 76 | 15 | 16 | 326ffe048e6c2776ef0f17ef744d0307e017c090 | bigcode/the-stack | train |
e8521fe03be2ca8274bc8085 | train | function | def setup_for_distributed(is_master):
"""
This function disables when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args,... | def setup_for_distributed(is_master):
| """
This function disables when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args, **kwargs)
__builtin__.print = pr... | .all_gather(tensor_list, tensor)
data_list = []
for size, tensor in zip(size_list, tensor_list):
buffer = tensor.cpu().numpy().tobytes()[:size]
data_list.append(pickle.loads(buffer))
return data_list
def setup_for_distributed(is_master):
| 64 | 64 | 82 | 8 | 55 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | setup_for_distributed | setup_for_distributed | 432 | 444 | 432 | 432 | 0238ffb8209f9703edb96b7ce40153ed27ddaaab | bigcode/the-stack | train |
582e46b997693768458bf5e7 | train | function | def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor):
def f(x):
"""根据step数返回一个学习率倍率因子"""
if x >= warmup_iters: # 当迭代数大于给定的warmup_iters时,倍率因子为1
return 1
alpha = float(x) / warmup_iters
# 迭代过程中倍率因子从warmup_factor -> 1
return warmup_factor * (1 - alpha) + ... | def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor):
| def f(x):
"""根据step数返回一个学习率倍率因子"""
if x >= warmup_iters: # 当迭代数大于给定的warmup_iters时,倍率因子为1
return 1
alpha = float(x) / warmup_iters
# 迭代过程中倍率因子从warmup_factor -> 1
return warmup_factor * (1 - alpha) + alpha
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr... | stats
coco_mAP = print_txt[0]
voc_mAP = print_txt[1]
if isinstance(mAP_list, list):
mAP_list.append(voc_mAP)
# return coco_evaluator
def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor):
| 64 | 64 | 129 | 16 | 47 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | warmup_lr_scheduler | warmup_lr_scheduler | 148 | 157 | 148 | 148 | 2b0cc1302b2f0ea3b8144d92a1fbb0b9486bae86 | bigcode/the-stack | train |
a7ea4fdcd0d868741cc66fe6 | train | function | def init_distributed_mode(args):
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
elif 'SLURM_PROCID' in os.environ:
args.rank = int(os.environ['SLU... | def init_distributed_mode(args):
| if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
elif 'SLURM_PROCID' in os.environ:
args.rank = int(os.environ['SLURM_PROCID'])
args.gpu = a... | not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def is_main_process():
return get_rank() == 0
def save_on_master(*args, **kwargs):
if is_main_process():
torch.save(*args, **kwargs)
def init_distributed_mode(args):
| 65 | 65 | 218 | 7 | 58 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | init_distributed_mode | init_distributed_mode | 462 | 484 | 462 | 462 | 545a7f9ef35877b0a2afd79bf486eaef72a08e9d | bigcode/the-stack | train |
03c8f6719ad13df13010c5e6 | train | class | class MetricLogger(object):
def __init__(self, delimiter="\t"):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for k, v in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinsta... | class MetricLogger(object):
| def __init__(self, delimiter="\t"):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for k, v in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinstance(v, (float, int))
... | # @property 是装饰器,这里可简单理解为增加median属性(只读)
d = torch.tensor(list(self.deque))
return d.median().item()
@property
def avg(self):
d = torch.tensor(list(self.deque), dtype=torch.float32)
return d.mean().item()
@property
def global_avg(self):
return self.total / self.... | 211 | 211 | 706 | 5 | 205 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | MetricLogger | MetricLogger | 231 | 318 | 231 | 231 | 42cba1e687ad8a01b1e2c600557a3f256e4d2527 | bigcode/the-stack | train |
5e165e6b7ff7c0ac038c9df5 | train | function | def mkdir(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
| def mkdir(path):
| try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
| # img_id.append(t["image_id"])
# targets = {"boxes": torch.stack(boxes, dim=0),
# "labels": torch.stack(labels, dim=0),
# "image_id": torch.as_tensor(img_id)}
return images, targets
def mkdir(path):
| 64 | 64 | 33 | 4 | 59 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | mkdir | mkdir | 339 | 344 | 339 | 339 | ff1fb8753dac1eccd0a07f91d5efeafa29919aae | bigcode/the-stack | train |
aaa16b3bf24b0325a09224ce | train | function | def save_on_master(*args, **kwargs):
if is_main_process():
torch.save(*args, **kwargs)
| def save_on_master(*args, **kwargs):
| if is_main_process():
torch.save(*args, **kwargs)
| _print(*args, **kwargs)
__builtin__.print = print
def get_rank():
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def is_main_process():
return get_rank() == 0
def save_on_master(*args, **kwargs):
| 64 | 64 | 25 | 10 | 53 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | save_on_master | save_on_master | 457 | 459 | 457 | 457 | c1e94f8099c4afa2527253887e061ad9410e5341 | bigcode/the-stack | train |
0263d5ad5586750f2f17e8f7 | train | function | def _get_iou_types(model):
model_without_ddp = model
if isinstance(model, torch.nn.parallel.DistributedDataParallel):
model_without_ddp = model.module
iou_types = ["bbox"]
return iou_types
| def _get_iou_types(model):
| model_without_ddp = model
if isinstance(model, torch.nn.parallel.DistributedDataParallel):
model_without_ddp = model.module
iou_types = ["bbox"]
return iou_types
| values.append(input_dict[k])
values = torch.stack(values, dim=0)
dist.all_reduce(values)
if average:
values /= world_size
reduced_dict = {k: v for k, v in zip(names, values)}
return reduced_dict
def _get_iou_types(model):
| 64 | 64 | 52 | 8 | 55 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | _get_iou_types | _get_iou_types | 381 | 386 | 381 | 381 | e89fb45cdc1175b9f42a9ed2be5c8a5a0cef9165 | bigcode/the-stack | train |
4a0362139116825b628ff330 | train | function | def is_main_process():
return get_rank() == 0
| def is_main_process():
| return get_rank() == 0
| force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args, **kwargs)
__builtin__.print = print
def get_rank():
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
def is_main_process():
| 64 | 64 | 14 | 5 | 59 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | is_main_process | is_main_process | 453 | 454 | 453 | 453 | 6852438052f77c102fbf1377859085121625dd6d | bigcode/the-stack | train |
2d37b1d9357c60560c10fe01 | train | function | def collate_fn(batch):
images, targets = tuple(zip(*batch))
# images = torch.stack(images, dim=0)
#
# boxes = []
# labels = []
# img_id = []
# for t in targets:
# boxes.append(t['boxes'])
# labels.append(t['labels'])
# img_id.append(t["image_id"])
# targets = {"bo... | def collate_fn(batch):
| images, targets = tuple(zip(*batch))
# images = torch.stack(images, dim=0)
#
# boxes = []
# labels = []
# img_id = []
# for t in targets:
# boxes.append(t['boxes'])
# labels.append(t['labels'])
# img_id.append(t["image_id"])
# targets = {"boxes": torch.stack(boxes... | total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print('{} Total time: {} ({:.4f} s / it)'.format(header,
total_time_str,
tota... | 63 | 64 | 131 | 6 | 57 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | collate_fn | collate_fn | 321 | 336 | 321 | 321 | 91caf9dfddb695252996c33c0b98898e63908023 | bigcode/the-stack | train |
b85d59b3c0dcc861147b4019 | train | class | class SmoothedValue(object):
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
self.deque = deque(maxlen=wind... | class SmoothedValue(object):
| """Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size=20, fmt=None):
if fmt is None:
fmt = "{median:.4f} ({global_avg:.4f})"
self.deque = deque(maxlen=window_size) # deque简单理解成加强版list... | up_factor):
def f(x):
"""根据step数返回一个学习率倍率因子"""
if x >= warmup_iters: # 当迭代数大于给定的warmup_iters时,倍率因子为1
return 1
alpha = float(x) / warmup_iters
# 迭代过程中倍率因子从warmup_factor -> 1
return warmup_factor * (1 - alpha) + alpha
return torch.optim.lr_scheduler.LambdaLR(o... | 122 | 122 | 409 | 6 | 116 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | SmoothedValue | SmoothedValue | 160 | 219 | 160 | 160 | 5be398a09362b9cd9e37ab77324d4f1a81e74d7b | bigcode/the-stack | train |
5531b645a105bf05dfa03d7b | train | function | def get_rank():
if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
| def get_rank():
| if not is_dist_avail_and_initialized():
return 0
return dist.get_rank()
| import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if is_master or force:
builtin_print(*args, **kwargs)
__builtin__.print = print
def get_rank():
| 64 | 64 | 25 | 4 | 59 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | get_rank | get_rank | 447 | 450 | 447 | 447 | e122dce68d2cda515c8d89bfad2510beb21dee83 | bigcode/the-stack | train |
5a387c7fe2fe65d8b9c2bb1d | train | function | def reduce_dict(input_dict, average=True):
"""
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Reduce the values in the dictionary from all processes so that all processes
have the averaged results. Returns a dict with the same fields ... | def reduce_dict(input_dict, average=True):
| """
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Reduce the values in the dictionary from all processes so that all processes
have the averaged results. Returns a dict with the same fields as
input_dict, after reduction.
"""... | try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def get_world_size():
if not is_dist_avail_and_initialized():
return 1
return dist.get_world_size()
def reduce_dict(input_dict, average=True):
| 64 | 64 | 211 | 9 | 55 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | reduce_dict | reduce_dict | 353 | 378 | 353 | 353 | 451f88dd12dcf3d2727a2edd34da3d3f93800254 | bigcode/the-stack | train |
8f821696ccca22b0e6d366c2 | train | function | def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = get_world_size()
if world_size == 1:
return [data]
# seriali... | def all_gather(data):
| """
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = get_world_size()
if world_size == 1:
return [data]
# serialized to a Tensor
bu... | torch.stack(values, dim=0)
dist.all_reduce(values)
if average:
values /= world_size
reduced_dict = {k: v for k, v in zip(names, values)}
return reduced_dict
def _get_iou_types(model):
model_without_ddp = model
if isinstance(model, torch.nn.parallel.DistributedData... | 105 | 105 | 353 | 6 | 98 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | all_gather | all_gather | 389 | 429 | 389 | 389 | 3ef381b08e10fb3858f2ddd3d0ae6a75bb3b3694 | bigcode/the-stack | train |
4ff4faf9b7ce7dc51ce855fb | train | function | @torch.no_grad()
def evaluate(model, data_loader, device, data_set=None, mAP_list=None):
n_threads = torch.get_num_threads()
# FIXME remove this and make paste_masks_in_image run on the GPU
torch.set_num_threads(1)
cpu_device = torch.device("cpu")
model.eval()
metric_logger = MetricLogger(delimi... | @torch.no_grad()
def evaluate(model, data_loader, device, data_set=None, mAP_list=None):
| n_threads = torch.get_num_threads()
# FIXME remove this and make paste_masks_in_image run on the GPU
torch.set_num_threads(1)
cpu_device = torch.device("cpu")
model.eval()
metric_logger = MetricLogger(delimiter=" ")
header = "Test: "
if data_set is None:
data_set = get_coco_api... | _value)
if not math.isfinite(loss_value): # 当计算的损失为无穷大时停止训练
print("Loss is {}, stopping training".format(loss_value))
print(losses_dict_reduced)
sys.exit(1)
optimizer.zero_grad()
losses.backward()
optimizer.step()
if lr_scheduler is not Non... | 177 | 177 | 592 | 23 | 154 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | evaluate | evaluate | 79 | 144 | 79 | 80 | 442c47e54f1fc0b00d41d8519830c48542878cee | bigcode/the-stack | train |
3336d5ca6e58b6859697fe72 | train | function | def is_dist_avail_and_initialized():
"""检查是否支持分布式环境"""
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
| def is_dist_avail_and_initialized():
| """检查是否支持分布式环境"""
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
|
def value(self):
return self.deque[-1]
def __str__(self):
return self.fmt.format(
median=self.median,
avg=self.avg,
global_avg=self.global_avg,
max=self.max,
value=self.value)
def is_dist_avail_and_initialized():
| 64 | 64 | 44 | 8 | 56 | chuanfuye/object_detection | ssd/train_utils/train_eval_utils.py | Python | is_dist_avail_and_initialized | is_dist_avail_and_initialized | 222 | 228 | 222 | 222 | 5d7c5d3c2fa590a0ed4342c71b273989f0deb7a7 | bigcode/the-stack | train |
92487f2547dfcd5e2424faad | train | function | async def async_get_conditions(
opp: OpenPeerPower, device_id: str
) -> List[Dict[str, str]]:
"""List device conditions."""
conditions: List[Dict[str, str]] = []
entity_registry = await async_get_registry(opp)
entries = [
entry
for entry in async_entries_for_device(entity_registry, d... | async def async_get_conditions(
opp: OpenPeerPower, device_id: str
) -> List[Dict[str, str]]:
| """List device conditions."""
conditions: List[Dict[str, str]] = []
entity_registry = await async_get_registry(opp)
entries = [
entry
for entry in async_entries_for_device(entity_registry, device_id)
if entry.domain == DOMAIN
]
for entry in entries:
device_class ... | ): cv.entity_id,
vol.Required(CONF_TYPE): vol.In(IS_OFF + IS_ON),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
async def async_get_conditions(
opp: OpenPeerPower, device_id: str
) -> List[Dict[str, str]]:
| 64 | 64 | 214 | 27 | 37 | pcaston/Open-Peer-Power | openpeerpower/components/binary_sensor/device_condition.py | Python | async_get_conditions | async_get_conditions | 197 | 232 | 197 | 199 | 2957171d5122f4cc7e01111ad7e37cff4199b0d3 | bigcode/the-stack | train |
4c7efc0d88e3726c02d7a36a | train | function | async def async_get_condition_capabilities(opp: OpenPeerPower, config: dict) -> dict:
"""List condition capabilities."""
return {
"extra_fields": vol.Schema(
{vol.Optional(CONF_FOR): cv.positive_time_period_dict}
)
}
| async def async_get_condition_capabilities(opp: OpenPeerPower, config: dict) -> dict:
| """List condition capabilities."""
return {
"extra_fields": vol.Schema(
{vol.Optional(CONF_FOR): cv.positive_time_period_dict}
)
}
| CONF_ENTITY_ID],
condition.CONF_STATE: stat,
}
if CONF_FOR in config:
state_config[CONF_FOR] = config[CONF_FOR]
return condition.state_from_config(state_config)
async def async_get_condition_capabilities(opp: OpenPeerPower, config: dict) -> dict:
| 64 | 64 | 57 | 21 | 43 | pcaston/Open-Peer-Power | openpeerpower/components/binary_sensor/device_condition.py | Python | async_get_condition_capabilities | async_get_condition_capabilities | 258 | 264 | 258 | 258 | f47e416588d135a52c5248c1fff1e81fe5b83563 | bigcode/the-stack | train |
54d1702205d97e2a022709c8 | train | function | @callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
"""Evaluate state based on configuration."""
if config_validation:
config = CONDITION_SCHEMA(config)
condition_type = config[CONF_TYPE]
if condition_type in IS_ON:
... | @callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condition.ConditionCheckerType:
| """Evaluate state based on configuration."""
if config_validation:
config = CONDITION_SCHEMA(config)
condition_type = config[CONF_TYPE]
if condition_type in IS_ON:
stat = "on"
else:
stat = "off"
state_config = {
condition.CONF_CONDITION: "state",
condition... | device_id": device_id,
"entity_id": entry.entity_id,
"domain": DOMAIN,
}
for template in templates
)
)
return conditions
@callback
def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> condit... | 64 | 64 | 146 | 27 | 36 | pcaston/Open-Peer-Power | openpeerpower/components/binary_sensor/device_condition.py | Python | async_condition_from_config | async_condition_from_config | 235 | 255 | 235 | 238 | 43bbef124f061fd379b2729a3c1dcfc0f25457d7 | bigcode/the-stack | train |
0c6f2507b1de2d01d29c92cd | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, ... | class Migration(migrations.Migration):
| initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | # Generated by Django 2.2 on 2020-11-06 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
| 36 | 93 | 311 | 7 | 28 | anirudhs1998/profiles-rest-api | profiles_api/migrations/0001_initial.py | Python | Migration | Migration | 6 | 33 | 6 | 7 | f207818ea7ba3c279efc672f8bc0d5ef9e8d86fb | bigcode/the-stack | train |
705af5b12cf15b62ce88a244 | train | class | @pytest.mark.django_db
class TestInstitutionList:
@pytest.fixture()
def institution_one(self):
return InstitutionFactory()
@pytest.fixture()
def institution_two(self):
return InstitutionFactory()
@pytest.fixture()
def url_institution(self):
return '/{}institutions/'.fo... | @pytest.mark.django_db
class TestInstitutionList:
@pytest.fixture()
| def institution_one(self):
return InstitutionFactory()
@pytest.fixture()
def institution_two(self):
return InstitutionFactory()
@pytest.fixture()
def url_institution(self):
return '/{}institutions/'.format(API_BASE)
def test_return_all_institutions(
self, a... | import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import InstitutionFactory
@pytest.mark.django_db
class TestInstitutionList:
@pytest.fixture()
| 38 | 90 | 301 | 16 | 21 | gaybro8777/osf.io | api_tests/institutions/views/test_institution_list.py | Python | TestInstitutionList | TestInstitutionList | 7 | 49 | 7 | 10 | cc20b57b0294fc92d7da8ddbdab5812e6a5e76e3 | bigcode/the-stack | train |
e5434f83f47447f2f436800a | train | function | @app.route('/reset', methods=['POST'])
def reset():
# Reset session information
session['random_number'] = random.randrange(0,101)
session['number_of_guesses'] = 0
session['state'] = "empty"
session['user_guess'] = 0
session['current_guesses'] = ""
return redirect('/')
| @app.route('/reset', methods=['POST'])
def reset():
# Reset session information
| session['random_number'] = random.randrange(0,101)
session['number_of_guesses'] = 0
session['state'] = "empty"
session['user_guess'] = 0
session['current_guesses'] = ""
return redirect('/')
| _guess']) < session['random_number']:
session['state'] = "low"
if int(session['user_guess']) > session['random_number']:
session['state'] = "high"
return redirect('/')
@app.route('/reset', methods=['POST'])
def reset():
# Reset session information
| 63 | 64 | 76 | 18 | 45 | JosephAMumford/CodingDojo | Python/FlaskFundamentals/GreatNumberGame/server.py | Python | reset | reset | 43 | 52 | 43 | 45 | 745aefa1e2cf2b8d79fffc4af143b3f63d5d3252 | bigcode/the-stack | train |
8019566709b4b6ab0417d34e | train | function | @app.route('/')
def index():
# Initialize session values
if 'random_number' not in session:
session['random_number'] = random.randrange(0,101)
if 'number_of_guesses' not in session:
session['number_of_guesses'] = 0
if 'state' not in session:
session['state'] = "empty"
if 'use... | @app.route('/')
def index():
# Initialize session values
| if 'random_number' not in session:
session['random_number'] = random.randrange(0,101)
if 'number_of_guesses' not in session:
session['number_of_guesses'] = 0
if 'state' not in session:
session['state'] = "empty"
if 'user_guess' not in session:
session['user_guess'] = 0
... | from flask import Flask, render_template, request, redirect, session
import random
app = Flask(__name__)
app.secret_key = 'MySecretKey'
@app.route('/')
def index():
# Initialize session values
| 44 | 64 | 127 | 12 | 32 | JosephAMumford/CodingDojo | Python/FlaskFundamentals/GreatNumberGame/server.py | Python | index | index | 7 | 21 | 7 | 9 | 0dd4f33e3ea68af807e2649752bea5957a7c6678 | bigcode/the-stack | train |
d595cb45243a0390ce5032a3 | train | function | @app.route('/process', methods=['post'])
def process():
# Keep track of how many guesses
session['number_of_guesses'] += 1
# Keep track of which numbers have been guessed already
session['current_guesses'] += str(request.form['user_guess']) + ", "
session['user_guess'] = request.form['user_guess']
... | @app.route('/process', methods=['post'])
def process():
# Keep track of how many guesses
| session['number_of_guesses'] += 1
# Keep track of which numbers have been guessed already
session['current_guesses'] += str(request.form['user_guess']) + ", "
session['user_guess'] = request.form['user_guess']
# Check if guess is higher, lower, or equal to random number
if int(session['user_gu... | not in session:
session['user_guess'] = 0
if 'current_guesses' not in session:
session['current_guesses'] = ""
return render_template('index.html')
@app.route('/process', methods=['post'])
def process():
# Keep track of how many guesses
| 64 | 64 | 166 | 21 | 43 | JosephAMumford/CodingDojo | Python/FlaskFundamentals/GreatNumberGame/server.py | Python | process | process | 24 | 41 | 24 | 26 | 6af2d8ba1bd7225ec419ffecc30b55132c30afd2 | bigcode/the-stack | train |
f048fb1c02af61a5f3c2a4b1 | train | function | def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding="utf-8") as fd:
return re.sub(text_type(r":[a-z]+:`~?(.*?)`"), text_type(r"``\1``"), fd.read())
| def read(filename):
| filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding="utf-8") as fd:
return re.sub(text_type(r":[a-z]+:`~?(.*?)`"), text_type(r"``\1``"), fd.read())
|
from setuptools import find_packages, setup
# Get some values from the setup.cfg
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
conf = ConfigParser()
conf.read(["setup.cfg"])
metadata = dict(conf.items("metadata"))
def read(filename):
| 63 | 64 | 74 | 4 | 59 | sergioangulo/aves | setup.py | Python | read | read | 18 | 22 | 18 | 18 | c0e56ac6ec441e8343aee53a0e67cdea2ada30fd | bigcode/the-stack | train |
577c08d86fb78ba03f967c19 | train | function | def predict(test):
out2 = []
count = 0
for i,j in(test):
m1 = i[0]
m1 = m1.reshape((1, 62, 50))
p1 = i[1]
p1 = p1.reshape((1, 25, 600))
predict = model2(m1, p1)
out2.append(predict)
count += 1
if count == 50:
break
... | def predict(test):
| out2 = []
count = 0
for i,j in(test):
m1 = i[0]
m1 = m1.reshape((1, 62, 50))
p1 = i[1]
p1 = p1.reshape((1, 25, 600))
predict = model2(m1, p1)
out2.append(predict)
count += 1
if count == 50:
break
return out2
| #from train import
##############################################
ligand_path = "C:/Users/User/python/kiba/ligands_can.txt"
protein_path = "C:/Users/User/python/kiba/protein1.txt"
affinity_path = "C:/Users/User/python/kiba/Y"
##############################################
def predict(test):
| 63 | 64 | 109 | 4 | 59 | abchotujnn1/drug-protein-binding | deepdta/predict.py | Python | predict | predict | 13 | 26 | 13 | 13 | 8af867050237ed20bf7957a62148b87b683821d6 | bigcode/the-stack | train |
684ad7c42e17a7d6cb3a7265 | train | function | def import_by_name(name, prefixes=[None]):
# type: (unicode, List) -> Tuple[unicode, Any, Any, unicode]
"""Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if pref... | def import_by_name(name, prefixes=[None]):
# type: (unicode, List) -> Tuple[unicode, Any, Any, unicode]
| """Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name... | if currmodule:
prefixes.insert(0, currmodule + "." + currclass)
else:
prefixes.insert(0, currclass)
return prefixes
def import_by_name(name, prefixes=[None]):
# type: (unicode, List) -> Tuple[unicode, Any, Any, unicode]
| 64 | 64 | 164 | 30 | 33 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | import_by_name | import_by_name | 564 | 580 | 564 | 565 | eb547b27acc0aa9b34c761bc44c429ad35aefb7c | bigcode/the-stack | train |
0691c8e063b769e3a9e9c324 | train | class | class FakeDirective(DocumenterBridge):
def __init__(self):
# type: () -> None
super(FakeDirective, self).__init__({}, None, Options(), 0) # type: ignore
| class FakeDirective(DocumenterBridge):
| def __init__(self):
# type: () -> None
super(FakeDirective, self).__init__({}, None, Options(), 0) # type: ignore
| " ", u"\u00a0")
par[j] = nodes.Text(new_text)
except IndexError:
pass
# -- autodoc integration -------------------------------------------------------
# current application object (used in `get_documenter()`).
_app = None # type: Sphinx
class FakeDirective(DocumenterBridge):
| 64 | 64 | 46 | 7 | 56 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | FakeDirective | FakeDirective | 173 | 176 | 173 | 173 | e775b29be3839054402450969d39699a28064ff5 | bigcode/the-stack | train |
b4f0bd13bd136327d473b502 | train | function | def autosummary_toc_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_toc) -> None
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
| def autosummary_toc_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_toc) -> None
| """Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
| , nodes.section):
continue
if subnode not in crawled:
crawl_toc(subnode, depth + 1)
crawl_toc(doctree)
def autosummary_toc_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_toc) -> None
| 64 | 64 | 47 | 28 | 36 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autosummary_toc_visit_html | autosummary_toc_visit_html | 133 | 136 | 133 | 134 | 162e9149efe596763cab1aba2f6371129742588b | bigcode/the-stack | train |
5b0868c4ec818658c81f5714 | train | class | class autosummary_toc(nodes.comment):
pass
| class autosummary_toc(nodes.comment):
| pass
| inx.ext.autodoc import Documenter # NOQA
logger = logging.getLogger(__name__)
periods_re = re.compile(r'\.(?:\s+)')
literal_re = re.compile(r'::\s*$')
# -- autosummary_toc node ------------------------------------------------------
class autosummary_toc(nodes.comment):
| 64 | 64 | 11 | 8 | 56 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autosummary_toc | autosummary_toc | 103 | 104 | 103 | 103 | 1a4b431af10630b90d204fee4bfc1fed747f13a8 | bigcode/the-stack | train |
569d913d69cb61367aeadae2 | train | function | def limited_join(sep, items, max_chars=30, overflow_marker="..."):
# type: (unicode, List[unicode], int, unicode) -> unicode
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: join... | def limited_join(sep, items, max_chars=30, overflow_marker="..."):
# type: (unicode, List[unicode], int, unicode) -> unicode
| """Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(full_str) < max_chars:
return full_str
n_chars = 0
n... |
# strip literal notation mark ``::`` from tail of summary
summary = literal_re.sub('.', summary)
return summary
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
# type: (unicode, List[unicode], int, unicode) -> unicode
| 64 | 64 | 184 | 36 | 27 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | limited_join | limited_join | 515 | 537 | 515 | 516 | b2fcd4e9a9e5f894c522aa4cb1092ebb0a02f0f2 | bigcode/the-stack | train |
a157c9ff5f55f20023707a1b | train | function | def _import_by_name(name):
# type: (str) -> Tuple[Any, Any, unicode]
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
... | def _import_by_name(name):
# type: (str) -> Tuple[Any, Any, unicode]
| """Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
mod = import_module(modname)
return getattr(mod, name_... | name])
else:
prefixed_name = name
obj, parent, modname = _import_by_name(prefixed_name)
return prefixed_name, obj, parent, modname
except ImportError:
tried.append(prefixed_name)
raise ImportError('no module named %s' % ' or '.join(tried))
def... | 94 | 94 | 315 | 22 | 72 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | _import_by_name | _import_by_name | 583 | 622 | 583 | 584 | 396338cfb6434c22ba6d2788f2688b14f75fb056 | bigcode/the-stack | train |
fa05a1e208a8eb3d8354bf36 | train | function | def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
# I need autodoc
app.setup_extension('sphinx.ext.autodoc')
app.add_node(autosummary_toc,
html=(autosummary_toc_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosu... | def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
# I need autodoc
| app.setup_extension('sphinx.ext.autodoc')
app.add_node(autosummary_toc,
html=(autosummary_toc_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosummary_noop, autosummary_noop),
man=(autosummary_noop, autosumma... | your source_suffix does not contain .rst. Skipped.'))
return
generate_autosummary_docs(genfiles, builder=app.builder,
warn=logger.warning, info=logger.info,
suffix=suffix, base_path=app.srcdir,
app=app)
def setup(app... | 84 | 84 | 280 | 26 | 58 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | setup | setup | 699 | 720 | 699 | 701 | 51c0778b58b5120b49fd7cfd624a918beafa48d0 | bigcode/the-stack | train |
2f348c2e1941d732194ffc4c | train | function | def get_documenter(*args):
# type: (Any) -> Type[Documenter]
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from... | def get_documenter(*args):
# type: (Any) -> Type[Documenter]
| """Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import DataDocumenter, ModuleDocumenter
i... | ] = nodes.Text(new_text)
except IndexError:
pass
# -- autodoc integration -------------------------------------------------------
# current application object (used in `get_documenter()`).
_app = None # type: Sphinx
class FakeDirective(DocumenterBridge):
def __init__(self):
# type: () -> N... | 111 | 111 | 372 | 20 | 90 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | get_documenter | get_documenter | 179 | 222 | 179 | 180 | 0b12cf64c471cb1d5f2d5f60763504e1616342cb | bigcode/the-stack | train |
3f79097e60f5268fb2d0d1fb | train | function | def autosummary_noop(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None
pass
| def autosummary_noop(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None
| pass
| (self, node):
# type: (nodes.NodeVisitor, autosummary_toc) -> None
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None
| 64 | 64 | 27 | 24 | 39 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autosummary_noop | autosummary_noop | 139 | 141 | 139 | 140 | 9b2e244411a38600b9f88be87e5af46769251f35 | bigcode/the-stack | train |
dbd56ab43f39054caee8c8c4 | train | function | def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):
# type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> Tuple[List[nodes.Node], List[nodes.Node]] # NOQA
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
other... | def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):
# type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> Tuple[List[nodes.Node], List[nodes.Node]] # NOQA
| """Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = None # type: Tuple[List[nodes.Node], List[nodes.Node]]
r = env.get_domain('py').role('obj')(
'obj', rawtext, etext... | :autolink: (smart default role) -------------------------------------------
def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):
# type: (unicode, unicode, unicode, int, Inliner, Dict, List[unicode]) -> Tuple[List[nodes.Node], List[nodes.Node]] # NOQA
| 76 | 77 | 258 | 64 | 12 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autolink_role | autolink_role | 627 | 647 | 627 | 628 | be6cca02dd6724e2fb23cd30ab0ea7613cfee609 | bigcode/the-stack | train |
03e731879a84c3abec38978f | train | function | def extract_summary(doc, document):
# type: (List[unicode], Any) -> unicode
"""Extract summary from docstring."""
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so an... | def extract_summary(doc, document):
# type: (List[unicode], Any) -> unicode
| """Extract summary from docstring."""
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so anything after shouldn't be part of the
# summary
for i, piece in enumerat... | not sig:
sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars - 4)
elif len(sig) < max_chars - 4 - 2 - 3:
sig += "[, %s]" % limited_join(", ", opts,
max_chars=max_chars - len(sig) - 4 - 2)
return u"(%s)" % sig
def extract_summary(do... | 105 | 105 | 353 | 21 | 83 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | extract_summary | extract_summary | 466 | 512 | 466 | 467 | 756c81c513a29857da87b48e16178a6da0a7532c | bigcode/the-stack | train |
4596751bcbbfb843d54e659f | train | class | class Autosummary(SphinxDirective):
"""
Pretty table containing short signatures and summaries of functions etc.
autosummary can also optionally generate a hidden toctree:: node.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
... | class Autosummary(SphinxDirective):
| """
Pretty table containing short signatures and summaries of functions etc.
autosummary can also optionally generate a hidden toctree:: node.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
option_spec = {
'toctree': d... | else:
# old style arguments: (obj, parent)
app = _app
obj, parent = args
warnings.warn('the interface of get_documenter() has been changed. '
'Please give application object as first argument.',
RemovedInSphinx20Warning)
if inspect.ismodu... | 256 | 256 | 1,574 | 7 | 249 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | Autosummary | Autosummary | 227 | 409 | 227 | 227 | aedc1df44646acb6e8217a4a3aea580a165b22c3 | bigcode/the-stack | train |
5c4d0dc2211e9d9f8d915e79 | train | function | def get_import_prefixes_from_env(env):
# type: (BuildEnvironment) -> List
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None] # type: List
currmodule = env.ref_context.get('py:module')
if currmodule:
prefixes.insert(0, cu... | def get_import_prefixes_from_env(env):
# type: (BuildEnvironment) -> List
| """
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None] # type: List
currmodule = env.ref_context.get('py:module')
if currmodule:
prefixes.insert(0, currmodule)
currclass = env.ref_context.get('py:class')
if currclass:
... | max_chars - len(overflow_marker):
n_items += 1
else:
break
return sep.join(list(items[:n_items]) + [overflow_marker])
# -- Importing items -----------------------------------------------------------
def get_import_prefixes_from_env(env):
# type: (BuildEnvironment) -> List
| 63 | 64 | 136 | 20 | 43 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | get_import_prefixes_from_env | get_import_prefixes_from_env | 542 | 561 | 542 | 543 | c2637619535fec77dc0b732689b3f1e917739987 | bigcode/the-stack | train |
59840cb8d43b32b29f3b099d | train | function | def autosummary_table_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_table) -> None
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode... | def autosummary_table_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_table) -> None
| """Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(subnode, nodes.Text):
new_tex... | node):
# type: (nodes.NodeVisitor, nodes.Node) -> None
pass
# -- autosummary_table node ----------------------------------------------------
class autosummary_table(nodes.comment):
pass
def autosummary_table_visit_html(self, node):
# type: (nodes.NodeVisitor, autosummary_table) -> None
| 64 | 64 | 142 | 26 | 37 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autosummary_table_visit_html | autosummary_table_visit_html | 150 | 164 | 150 | 151 | 367ba604af324f062ddcb1f919bc1b7bc4f7e635 | bigcode/the-stack | train |
7d3c7eeef4630bfcea1cb360 | train | function | def process_generate_options(app):
# type: (Sphinx) -> None
genfiles = app.config.autosummary_generate
if genfiles and not hasattr(genfiles, '__len__'):
env = app.builder.env
genfiles = [env.doc2path(x, base=None) for x in env.found_docs
if os.path.isfile(env.doc2path(x)... | def process_generate_options(app):
# type: (Sphinx) -> None
| genfiles = app.config.autosummary_generate
if genfiles and not hasattr(genfiles, '__len__'):
env = app.builder.env
genfiles = [env.doc2path(x, base=None) for x in env.found_docs
if os.path.isfile(env.doc2path(x))]
if not genfiles:
return
from sphinx.ext.aut... | # type: ignore
return parser_class.supported
suffix = None # type: unicode
for suffix in app.config.source_suffix:
if 'restructuredtext' in get_supported_format(suffix):
return suffix
return None
def process_generate_options(app):
# type: (Sphinx) -> None
| 71 | 71 | 237 | 17 | 53 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | process_generate_options | process_generate_options | 669 | 696 | 669 | 670 | 0607a8a6b23fe778062c4ae006eaf269a7d0e37b | bigcode/the-stack | train |
344ba105624ee08ad7381802 | train | function | def strip_arg_typehint(s):
# type: (unicode) -> unicode
"""Strip a type hint from argument definition."""
return s.split(':')[0].strip()
| def strip_arg_typehint(s):
# type: (unicode) -> unicode
| """Strip a type hint from argument definition."""
return s.split(':')[0].strip()
| col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name)
col2 = summary
append_row(col1, col2)
return [table_spec, table]
def strip_arg_typehint(s):
# type: (unicode) -> unicode
| 64 | 64 | 37 | 17 | 47 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | strip_arg_typehint | strip_arg_typehint | 412 | 415 | 412 | 413 | 9d4f690172c6ce2d92f32937055f71df4e3728be | bigcode/the-stack | train |
e5ec93eac5c7ab908c2fb9ae | train | class | class autosummary_table(nodes.comment):
pass
| class autosummary_table(nodes.comment):
| pass
| -> None
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self, node):
# type: (nodes.NodeVisitor, nodes.Node) -> None
pass
# -- autosummary_table node ----------------------------------------------------
class autosummary_table(nodes.comment):
| 64 | 64 | 10 | 7 | 57 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | autosummary_table | autosummary_table | 146 | 147 | 146 | 146 | b79d8e0eda1a626d0b13a8ff8b76149d5a451979 | bigcode/the-stack | train |
7488c16f093c938b2527fd0a | train | function | def mangle_signature(sig, max_chars=30):
# type: (unicode, int) -> unicode
"""Reformat a function signature to a more compact form."""
# Strip return type annotation
s = re.sub(r"\)\s*->\s.*$", ")", sig)
# Remove parenthesis
s = re.sub(r"^\((.*)\)$", r"\1", s).strip()
# Strip strings (whic... | def mangle_signature(sig, max_chars=30):
# type: (unicode, int) -> unicode
| """Reformat a function signature to a more compact form."""
# Strip return type annotation
s = re.sub(r"\)\s*->\s.*$", ")", sig)
# Remove parenthesis
s = re.sub(r"^\((.*)\)$", r"\1", s).strip()
# Strip strings (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", s... | real_name, rst.escape(sig)) # type: unicode # NOQA
else:
col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name)
col2 = summary
append_row(col1, col2)
return [table_spec, table]
def strip_arg_typehint(s):
# type: (unicode) -> unicode
"""Strip a typ... | 127 | 127 | 424 | 23 | 104 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | mangle_signature | mangle_signature | 418 | 463 | 418 | 419 | 0ec47269a6c89c20606da2968645eb2c1d6991c0 | bigcode/the-stack | train |
379424c9af8dd3a19c94d4ac | train | function | def get_rst_suffix(app):
# type: (Sphinx) -> unicode
def get_supported_format(suffix):
# type: (unicode) -> Tuple[unicode]
parser_class = app.registry.get_source_parsers().get(suffix)
if parser_class is None:
return ('restructuredtext',)
if isinstance(parser_class, st... | def get_rst_suffix(app):
# type: (Sphinx) -> unicode
| def get_supported_format(suffix):
# type: (unicode) -> Tuple[unicode]
parser_class = app.registry.get_source_parsers().get(suffix)
if parser_class is None:
return ('restructuredtext',)
if isinstance(parser_class, string_types):
parser_class = import_object(par... | except ImportError:
content_node = pnode[0]
r[0][0] = nodes.emphasis(rawtext, content_node[0].astext(),
classes=content_node['classes'])
return r
def get_rst_suffix(app):
# type: (Sphinx) -> unicode
| 64 | 64 | 143 | 17 | 46 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | get_rst_suffix | get_rst_suffix | 650 | 666 | 650 | 651 | 9e3c5175205f08b6ce7ffbf5f9786533c43d66f0 | bigcode/the-stack | train |
5a9eb5e94fbbc349ebb227b3 | train | function | def process_autosummary_toc(app, doctree):
# type: (Sphinx, nodes.Node) -> None
"""Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
env = app.builder.env
crawled = {}
def crawl_toc(node, depth=1):
# type: (nodes.Node, int) -> None
... | def process_autosummary_toc(app, doctree):
# type: (Sphinx, nodes.Node) -> None
| """Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
env = app.builder.env
crawled = {}
def crawl_toc(node, depth=1):
# type: (nodes.Node, int) -> None
crawled[node] = True
for j, subnode in enumerate(node):
... | .(?:\s+)')
literal_re = re.compile(r'::\s*$')
# -- autosummary_toc node ------------------------------------------------------
class autosummary_toc(nodes.comment):
pass
def process_autosummary_toc(app, doctree):
# type: (Sphinx, nodes.Node) -> None
| 64 | 64 | 209 | 26 | 37 | vladbragoi/indoor_localization_system | localization_service/venv/lib/python3.5/site-packages/sphinx/ext/autosummary/__init__.py | Python | process_autosummary_toc | process_autosummary_toc | 107 | 130 | 107 | 108 | 0cca04bd0b9941881e5eee2cf385db0329cb0b89 | bigcode/the-stack | train |
1adc05a66822346fff638cbf | train | class | class FullNodeRpcApi:
def __init__(self, service: FullNode):
self.service = service
self.service_name = "chia_full_node"
self.cached_blockchain_state: Optional[Dict] = None
def get_routes(self) -> Dict[str, Callable]:
return {
# Blockchain
"/get_blockchai... | class FullNodeRpcApi:
| def __init__(self, service: FullNode):
self.service = service
self.service_name = "chia_full_node"
self.cached_blockchain_state: Optional[Dict] = None
def get_routes(self) -> Dict[str, Callable]:
return {
# Blockchain
"/get_blockchain_state": self.get_blo... | from typing import Any, Callable, Dict, List, Optional
from chia.consensus.block_record import BlockRecord
from chia.consensus.pos_quality import UI_ACTUAL_SPACE_CONSTANT_FACTOR
from chia.full_node.full_node import FullNode
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.types.coin_record import... | 164 | 256 | 3,848 | 6 | 157 | kim08888/chia-rosechain | chia/rpc/full_node_rpc_api.py | Python | FullNodeRpcApi | FullNodeRpcApi | 17 | 429 | 17 | 17 | c0bcc6dc6c7ba1c1ef623ef4a3a2a8aca217d2e7 | bigcode/the-stack | train |
bda55562dda54f2e009bdd43 | train | class | class SpecProductAssignment(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, spec_id=None, product_id=None, default_value=None, default_option_id=None):
"""
SpecProductAssignment - a model de... | class SpecProductAssignment(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, spec_id=None, product_id=None, default_value=None, default_option_id=None):
"""
SpecProductAssignment - a model defined in Swagger
:param dict... | # coding: utf-8
"""
OrderCloud
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0
Contact: ordercloud@four51.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Ve... | 206 | 256 | 979 | 6 | 199 | klreeher/python-sdk | OrderCloud/models/spec_product_assignment.py | Python | SpecProductAssignment | SpecProductAssignment | 30 | 203 | 30 | 30 | 6909826a94b8c9d284f38a2395ea9b80226a4abd | bigcode/the-stack | train |
9afc664b9dda1275cbbec624 | train | class | class FixedOrderUpToPolicy(OrderPolicy):
def __init__(self, item_id, order_level=5):
self.item_id = item_id
self.order_up_lvl = order_level
def action(self, hospital):
qty = self.order_up_lvl - hospital.curr_inventory_position[self.item_id]
return max(0, qty)
| class FixedOrderUpToPolicy(OrderPolicy):
| def __init__(self, item_id, order_level=5):
self.item_id = item_id
self.order_up_lvl = order_level
def action(self, hospital):
qty = self.order_up_lvl - hospital.curr_inventory_position[self.item_id]
return max(0, qty)
| class OrderPolicy:
def action(self, hospital):
return 0
class FixedOrderUpToPolicy(OrderPolicy):
| 25 | 64 | 72 | 9 | 15 | surgical-supply-inventory-control/advance-booking-information | scm_simulation/order_policy.py | Python | FixedOrderUpToPolicy | FixedOrderUpToPolicy | 6 | 14 | 6 | 7 | ee64ee5e09b75733b4f6afb516ed1b434bb30102 | bigcode/the-stack | train |
0b324131e78ff8b948494274 | train | class | class FixedSsPolicy(OrderPolicy):
def __init__(self, item_id, order_up_lvl, reorder_lvl):
self.item_id = item_id
self.order_up_lvl = order_up_lvl
self.reorder_lvl = reorder_lvl
def action(self, hospital):
iid = self.item_id
qty = self.order_up_lvl if hospital.c... | class FixedSsPolicy(OrderPolicy):
| def __init__(self, item_id, order_up_lvl, reorder_lvl):
self.item_id = item_id
self.order_up_lvl = order_up_lvl
self.reorder_lvl = reorder_lvl
def action(self, hospital):
iid = self.item_id
qty = self.order_up_lvl if hospital.curr_inventory_position[iid] <= self.r... | )
# Cap to policy max levels
x = hospital.curr_inventory_position[self.item_id]
t_to_go = min(27, hospital.sim_time-hospital.clock)
action = self.la_model.order_la(t_to_go, x, info_state)
return action
class FixedSsPolicy(OrderPolicy):
| 64 | 64 | 93 | 7 | 56 | surgical-supply-inventory-control/advance-booking-information | scm_simulation/order_policy.py | Python | FixedSsPolicy | FixedSsPolicy | 71 | 81 | 71 | 72 | e5a0b350c2f4707a47c100e749968f00db7c7d68 | bigcode/the-stack | train |
737a7b8a2ecbeba3f698f67b | train | class | class AdvancedInfoSsPolicy(OrderPolicy):
def __init__(self, item_id, policy={}, granularity=1):
self.is_stationary = True if isinstance(policy, dict) else False
self.item_id = item_id
self.policy = policy
self.info_horizon = len(list(policy.keys())[0]) if self.is_stationary el... | class AdvancedInfoSsPolicy(OrderPolicy):
| def __init__(self, item_id, policy={}, granularity=1):
self.is_stationary = True if isinstance(policy, dict) else False
self.item_id = item_id
self.policy = policy
self.info_horizon = len(list(policy.keys())[0]) if self.is_stationary else len(list(policy[0].keys())[0])
s... | class OrderPolicy:
def action(self, hospital):
return 0
class FixedOrderUpToPolicy(OrderPolicy):
def __init__(self, item_id, order_level=5):
self.item_id = item_id
self.order_up_lvl = order_level
def action(self, hospital):
qty = self.order_up_lvl - hospital.c... | 96 | 123 | 413 | 8 | 88 | surgical-supply-inventory-control/advance-booking-information | scm_simulation/order_policy.py | Python | AdvancedInfoSsPolicy | AdvancedInfoSsPolicy | 17 | 44 | 17 | 18 | 0f69b51dddc521f2a06cb2c86f08d01964c18f0b | bigcode/the-stack | train |
499a18c448715c3a5d7ac33b | train | class | class OrderPolicy:
def action(self, hospital):
return 0
| class OrderPolicy:
| def action(self, hospital):
return 0
| class OrderPolicy:
| 4 | 64 | 16 | 4 | 0 | surgical-supply-inventory-control/advance-booking-information | scm_simulation/order_policy.py | Python | OrderPolicy | OrderPolicy | 1 | 3 | 1 | 1 | e65754dc4205f8900d6a585ec671f4e9a87f5af2 | bigcode/the-stack | train |
c450eab8556f0ed0f6c8dd07 | train | class | class LAPolicy(OrderPolicy):
def __init__(self, item_id, la_model):
self.item_id = item_id
self.la_model = la_model
self.granularity = 1
def action(self, hospital):
iid = self.item_id
ts = range(hospital.clock, min(hospital.clock + 14, hospital.max_periods-1))
... | class LAPolicy(OrderPolicy):
| def __init__(self, item_id, la_model):
self.item_id = item_id
self.la_model = la_model
self.granularity = 1
def action(self, hospital):
iid = self.item_id
ts = range(hospital.clock, min(hospital.clock + 14, hospital.max_periods-1))
# Extract info state fr... | _lvl, reorder_lvl = self.policy[info_state] if self.is_stationary \
else self.policy[hospital.clock % 7][info_state]
action = order_up_lvl - hospital.curr_inventory_position[iid] \
if hospital.curr_inventory_position[iid] <= reorder_lvl else 0
return action
class LAPolicy(Ord... | 72 | 72 | 241 | 6 | 65 | surgical-supply-inventory-control/advance-booking-information | scm_simulation/order_policy.py | Python | LAPolicy | LAPolicy | 47 | 68 | 47 | 48 | 982486bd9957c8fa04a248a81db41c64ba54f35e | bigcode/the-stack | train |
24b62bec66786fed2d8ab214 | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('store', '0007_rating'),
]
operations = [
migrations.CreateModel(
name='Review',
fields=[
('id', models.BigAutoField(auto_crea... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('store', '0007_rating'),
]
operations = [
migrations.CreateModel(
name='Review',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=Fa... | # Generated by Django 3.2.7 on 2021-10-31 12:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 156 | 7 | 43 | Extraordinary01/freshnesecom | Backend/core/store/migrations/0008_review.py | Python | Migration | Migration | 8 | 26 | 8 | 9 | 093b64f4da85cbbae77771fa6cbc814b77df1422 | bigcode/the-stack | train |
77a461342642d6497ba1f19d | train | class | class Input_Files(QWidget):
"""
Create the widget for saving / loading data
"""
sig_tx = QtCore.pyqtSignal(object) # sent when loading filter ('data_changed')
def __init__(self, parent):
super(Input_Files, self).__init__(parent)
self.tab_label = 'Files'
self.tool_tip = "Load... | class Input_Files(QWidget):
| """
Create the widget for saving / loading data
"""
sig_tx = QtCore.pyqtSignal(object) # sent when loading filter ('data_changed')
def __init__(self, parent):
super(Input_Files, self).__init__(parent)
self.tab_label = 'Files'
self.tool_tip = "Load and save filter designs."
... | VBoxLayout, QMessageBox, QPixmap, QIcon)
import pyfda.version as version
import pyfda.pyfda_lib as pyfda_lib
import pyfda.pyfda_dirs as dirs
import pyfda.filterbroker as fb
from pyfda.pyfda_rc import params
from pyfda.pyfda_io_lib import extract_file_ext
from pyfda import qrc_resources # contains all icons
import nu... | 256 | 256 | 4,798 | 6 | 249 | toddrme2178/pyfda | pyfda/input_widgets/input_files.py | Python | Input_Files | Input_Files | 57 | 463 | 57 | 57 | 4ed8594310600ff72ea22479b5da460aeee394c9 | bigcode/the-stack | train |
be5b983402d08def66021113 | train | class | class EventBridgeClient(object):
def __init__(self, name):
self._client = get_authenticated_boto3_client('events')
self.name = name
def cron(self, cron):
self.cron = cron
return self
def role_arn(self, role_arn):
self.role_arn = role_arn
return self
de... | class EventBridgeClient(object):
| def __init__(self, name):
self._client = get_authenticated_boto3_client('events')
self.name = name
def cron(self, cron):
self.cron = cron
return self
def role_arn(self, role_arn):
self.role_arn = role_arn
return self
def state_machine_arn(self, state_ma... | import json
from metaflow.metaflow_config import get_authenticated_boto3_client
class EventBridgeClient(object):
| 24 | 98 | 327 | 6 | 17 | hsezhiyan/metaflow | metaflow/plugins/aws/step_functions/event_bridge_client.py | Python | EventBridgeClient | EventBridgeClient | 6 | 59 | 6 | 7 | bd3acd0ae7d4937aa9db39cfbc89b2819ce280dc | bigcode/the-stack | train |
25b90bbd9956103becd37aa3 | train | function | def VCTK_collate(batch):
src, tgt = zip(*batch)
return segmenting_or_padding(src), segmenting_or_padding(tgt)
| def VCTK_collate(batch):
| src, tgt = zip(*batch)
return segmenting_or_padding(src), segmenting_or_padding(tgt)
| _len > maxn:
rand = np.random.randint(item_len - maxn)
item_ = item[:, rand:rand + maxn]
else:
item_ = item
audio += [item_]
return torch.tensor((np.array(audio)))
def VCTK_collate(batch):
| 63 | 64 | 32 | 8 | 55 | ishine/tpse-vc | code/data/vctk_dataset.py | Python | VCTK_collate | VCTK_collate | 27 | 29 | 27 | 27 | b6e8956b2ec67134b4fea757bfd9094999ba153c | bigcode/the-stack | train |
9bef0192ef87e69aedccd959 | train | class | class VCTKDateset_name(Dataset):
def __init__(self, audio_path):
self.audio_path = audio_path
self.audios_source = os.listdir(self.audio_path)
self.audios_target = copy.deepcopy(self.audios_source)
random.shuffle(self.audios_source)
random.shuffle(self.audios_target)
def... | class VCTKDateset_name(Dataset):
| def __init__(self, audio_path):
self.audio_path = audio_path
self.audios_source = os.listdir(self.audio_path)
self.audios_target = copy.deepcopy(self.audios_source)
random.shuffle(self.audios_source)
random.shuffle(self.audios_target)
def __getitem__(self, index):
... | np.load(os.path.join(self.audio_path, self.audios_source[index]))
tgt = np.load(os.path.join(self.audio_path, self.audios_target[index]))
return src, tgt
def __len__(self):
return len(self.audios_source)
class VCTKDateset_name(Dataset):
| 64 | 64 | 153 | 10 | 54 | ishine/tpse-vc | code/data/vctk_dataset.py | Python | VCTKDateset_name | VCTKDateset_name | 49 | 63 | 49 | 49 | 121205d0291cfb7836d30b473d96138664f65210 | bigcode/the-stack | train |
6b040db15ca2d3c2e758c466 | train | function | def segmenting_or_padding(audios):
maxn = 128
audio = []
for item in audios:
item_len = int(item.shape[1])
assert item_len >= maxn
if item_len > maxn:
rand = np.random.randint(item_len - maxn)
item_ = item[:, rand:rand + maxn]
else:
item_ =... | def segmenting_or_padding(audios):
| maxn = 128
audio = []
for item in audios:
item_len = int(item.shape[1])
assert item_len >= maxn
if item_len > maxn:
rand = np.random.randint(item_len - maxn)
item_ = item[:, rand:rand + maxn]
else:
item_ = item
audio += [item_]
... | import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import os
import random
import copy
def segmenting_or_padding(audios):
| 35 | 64 | 102 | 8 | 26 | ishine/tpse-vc | code/data/vctk_dataset.py | Python | segmenting_or_padding | segmenting_or_padding | 9 | 24 | 9 | 9 | d90da62e73a7cd985c509a7bd868c8b68ef4afdd | bigcode/the-stack | train |
31f1b59afa7f1359cf756bbb | train | class | class VCTKDateset(Dataset):
def __init__(self, audio_path):
self.audio_path = audio_path
self.audios_source = os.listdir(self.audio_path)
self.audios_target = copy.deepcopy(self.audios_source)
random.shuffle(self.audios_source)
random.shuffle(self.audios_target)
def __ge... | class VCTKDateset(Dataset):
| def __init__(self, audio_path):
self.audio_path = audio_path
self.audios_source = os.listdir(self.audio_path)
self.audios_target = copy.deepcopy(self.audios_source)
random.shuffle(self.audios_source)
random.shuffle(self.audios_target)
def __getitem__(self, index):
... | item_ = item
audio += [item_]
return torch.tensor((np.array(audio)))
def VCTK_collate(batch):
src, tgt = zip(*batch)
return segmenting_or_padding(src), segmenting_or_padding(tgt)
class VCTKDateset(Dataset):
| 64 | 64 | 134 | 9 | 55 | ishine/tpse-vc | code/data/vctk_dataset.py | Python | VCTKDateset | VCTKDateset | 32 | 46 | 32 | 32 | 797b4b22a86f982b69a85eba927470d9905bfce6 | bigcode/the-stack | train |
28945320a760fd9e2d23ee70 | train | function | def getKeyLength():
return 32
| def getKeyLength():
| return 32
| .new(128, initial_value=0))
return cipher.encrypt(data)
def aesDecrypt(data, key):
cipher = AES.new(key, AES.MODE_CTR, counter=Counter.new(128, initial_value=0))
return cipher.decrypt(data)
has_aes = True
def getKeyLength():
| 64 | 64 | 10 | 5 | 58 | DataDog/beaker | beaker/crypto/pycrypto.py | Python | getKeyLength | getKeyLength | 33 | 34 | 33 | 33 | e35268a988d08caec88630fbc7f63ddbe68c7931 | bigcode/the-stack | train |
d5418211d19f12171ef9411b | train | class | class DQN(nn.Module):
def __init__(self):
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size = 8, stride = 4)
self.conv2 = nn.Conv2d(32, 64, kernel_size = 4, stride = 2)
self.conv3 = nn.Conv2d(64, 64, kernel_size = 3, stride = 1)
self.f1 = nn.Linear(22*16*6... | class DQN(nn.Module):
| def __init__(self):
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size = 8, stride = 4)
self.conv2 = nn.Conv2d(32, 64, kernel_size = 4, stride = 2)
self.conv3 = nn.Conv2d(64, 64, kernel_size = 3, stride = 1)
self.f1 = nn.Linear(22*16*64, 512)
self.f... | = Transition(*args)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
###############################################
# define model
class DQN(nn.Module):
| 64 | 64 | 202 | 6 | 57 | KarlXing/NeuromodulationDQN | main.py | Python | DQN | DQN | 58 | 73 | 58 | 58 | f9bf56189b363cea027c20303d7be47bcbaa8aea | bigcode/the-stack | train |
7bd34b45d59476fb5fa08d09 | train | class | class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
se... | class ReplayMemory(object):
| def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
self.position = (self.position... | # plt.ion()
# select device (gpu or cpu)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
writer = SummaryWriter()
###############################################
# define Transition and ReplayMemory
Transition = namedtuple('Transition', 'state action next_state reward')
class ReplayMemory(objec... | 64 | 64 | 113 | 5 | 59 | KarlXing/NeuromodulationDQN | main.py | Python | ReplayMemory | ReplayMemory | 41 | 54 | 41 | 41 | 8f6c75493005ce764948e3677cf2cf4f02f731fb | bigcode/the-stack | train |
91a20afc01127098ca1cfed8 | train | function | def optimize_model():
if len(memory) < BATCH_SIZE:
return
transitions = memory.sample(BATCH_SIZE)
batch = Transition(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.next_state)), device = device, dtype = torch.uint8)
... | def optimize_model():
| if len(memory) < BATCH_SIZE:
return
transitions = memory.sample(BATCH_SIZE)
batch = Transition(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.next_state)), device = device, dtype = torch.uint8)
non_final_next_sta... | loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))
# optimizer.zero_grad()
# loss.backward()
# for param in policy_net.parameters():
# param.grad.data.clamp_(-1, 1)
# optimizer.step()
# loss_cpu = loss.data.cpu()
# # del loss and outputs to keep memo... | 90 | 90 | 303 | 4 | 85 | KarlXing/NeuromodulationDQN | main.py | Python | optimize_model | optimize_model | 140 | 162 | 140 | 140 | b93d954ed0795e1fcffcc9c574a0a0cd272118f5 | bigcode/the-stack | train |
05452379a749bcaabad1d682 | train | function | def select_action(state):
global steps_done
sample = random.random()
eps_threshold = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * steps_done / EPS_DECAY)
steps_done += 1
if sample > eps_threshold:
with torch.no_grad():
state = torch.from_numpy(np.transpose(state,(2,0,1))).flo... | def select_action(state):
| global steps_done
sample = random.random()
eps_threshold = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * steps_done / EPS_DECAY)
steps_done += 1
if sample > eps_threshold:
with torch.no_grad():
state = torch.from_numpy(np.transpose(state,(2,0,1))).float().unsqueeze(0).to(devic... | )
with torch.no_grad():
target_net = DQN().to(device)
target_net.load_state_dict(policy_net.state_dict())
optimizer = optim.RMSprop(policy_net.parameters(), lr = 0.0001)
memory = ReplayMemory(100000)
steps_done = 0
def select_action(state):
| 64 | 64 | 126 | 5 | 58 | KarlXing/NeuromodulationDQN | main.py | Python | select_action | select_action | 96 | 106 | 96 | 96 | 5b44cdee62c3d8d9e074cc78b1685d4367c4cab6 | bigcode/the-stack | train |
e02f3da9a85a21889cd7d087 | train | function | def scigrid_2011_01_04_05():
ppc = {"version": '2'}
ppc["baseMVA"] = 100.0
ppc["bus"] = array([
[586, 3, 0, 0, 0, 0, 0, 1.0, 0, 220.0, 0, 1.1, 0.9 ],
[589, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[590, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[593, 2, 0... | def scigrid_2011_01_04_05():
| ppc = {"version": '2'}
ppc["baseMVA"] = 100.0
ppc["bus"] = array([
[586, 3, 0, 0, 0, 0, 0, 1.0, 0, 220.0, 0, 1.1, 0.9 ],
[589, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[590, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[593, 2, 0, 0, 0, 0, 0, 1.0, 0, ... | from numpy import array
def scigrid_2011_01_04_05():
| 19 | 256 | 292,075 | 14 | 4 | thanever/SOC | Data/scigrid-de/pypower/scigrid_2011_01_04_05.py | Python | scigrid_2011_01_04_05 | scigrid_2011_01_04_05 | 2 | 5,429 | 2 | 2 | e600070c77f41b2e4fe61f7e7fa91219a9bfc19f | bigcode/the-stack | train |
4cf7504394d20023b98f8210 | train | class | class FeedForward(nn.Module):
def __init__(self, dim, mult = 4, dropout = 0., activation = None, glu = False):
super().__init__()
activation = default(activation, GELU)
self.glu = glu
self.w1 = nn.Linear(dim, dim * mult * (2 if glu else 1))
self.act = activation()
se... | class FeedForward(nn.Module):
| def __init__(self, dim, mult = 4, dropout = 0., activation = None, glu = False):
super().__init__()
activation = default(activation, GELU)
self.glu = glu
self.w1 = nn.Linear(dim, dim * mult * (2 if glu else 1))
self.act = activation()
self.dropout = nn.Dropout(dropou... | 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
GELU = nn.GELU if hasattr(nn, 'GELU') else GELU_
class FeedForward(nn.Module):
| 64 | 64 | 187 | 6 | 58 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | FeedForward | FeedForward | 592 | 613 | 592 | 592 | 79d64e08ab3547c4590407ce19a62491c15d9438 | bigcode/the-stack | train |
086df4c1d38fd267f82ce555 | train | function | def default(val, default_val):
return default_val if val is None else val
| def default(val, default_val):
| return default_val if val is None else val
| _dim = tensor.shape
tensor = tensor.reshape(-1, last_dim)
summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)]
return torch.cat(summed_tensors, dim=0).reshape(orig_size)
def default(val, default_val):
| 64 | 64 | 18 | 7 | 57 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | default | default | 46 | 47 | 46 | 46 | 31c0a81af5ff295736d2dfcf25bb3bdc8f367bb6 | bigcode/the-stack | train |
42e39c423e0ffcb1d57d1dcf | train | class | class ScaleNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.g = nn.Parameter(torch.ones(1))
self.eps = eps
def forward(self, x):
n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps)
return x / n * self.g
| class ScaleNorm(nn.Module):
| def __init__(self, dim, eps=1e-5):
super().__init__()
self.g = nn.Parameter(torch.ones(1))
self.eps = eps
def forward(self, x):
n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps)
return x / n * self.g
| Zero(nn.Module):
def __init__(self, fn):
super().__init__()
self.g = nn.Parameter(torch.zeros(1))
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) * self.g
class ScaleNorm(nn.Module):
| 64 | 64 | 83 | 6 | 57 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | ScaleNorm | ScaleNorm | 130 | 138 | 130 | 130 | bacdb48daaa203e4a86a3d98f0de864fe71eeaa9 | bigcode/the-stack | train |
346ad88b478df8101d449ba1 | train | class | class ReformerLM(nn.Module):
def __init__(self, num_tokens, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 4, ff_chunks = 100, attn_chunks = 1, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_mult = 4, ff_activation = None, ff_glu = False, post_attn_dropo... | class ReformerLM(nn.Module):
| def __init__(self, num_tokens, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 4, ff_chunks = 100, attn_chunks = 1, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_mult = 4, ff_activation = None, ff_glu = False, post_attn_dropout = 0., layer_dropout = 0., ... | for ind in range(depth):
layer_num = ind + 1
use_pkm = layer_num in cast_tuple(pkm_layers)
parallel_net = None
attn = get_attn()
if use_pkm:
parallel_net = get_pkm()
elif twin_attention:
parallel_net = get_attn()
... | 220 | 220 | 734 | 7 | 213 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | ReformerLM | ReformerLM | 716 | 751 | 716 | 716 | af1756894103933cb856cfb605643f6686ba581b | bigcode/the-stack | train |
8e7c4eff854c68182aa5bbe2 | train | class | class Chunk(nn.Module):
def __init__(self, chunks, fn, along_dim = -1):
super().__init__()
self.dim = along_dim
self.chunks = chunks
self.fn = fn
def forward(self, x, **kwargs):
if self.chunks == 1:
return self.fn(x, **kwargs)
chunks = x.chunk(self.ch... | class Chunk(nn.Module):
| def __init__(self, chunks, fn, along_dim = -1):
super().__init__()
self.dim = along_dim
self.chunks = chunks
self.fn = fn
def forward(self, x, **kwargs):
if self.chunks == 1:
return self.fn(x, **kwargs)
chunks = x.chunk(self.chunks, dim = self.dim)
... | def __init__(self, norm_class, dim, fn):
super().__init__()
self.norm = norm_class(dim)
self.fn = fn
def forward(self, x, **kwargs):
x = self.norm(x)
return self.fn(x, **kwargs)
class Chunk(nn.Module):
| 64 | 64 | 111 | 5 | 59 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | Chunk | Chunk | 149 | 160 | 149 | 149 | daebe824264bcfdc79fb9f1b1905f2fc6500827b | bigcode/the-stack | train |
59714693625ce3e4901990c3 | train | class | class FixedPositionalEmbedding(nn.Module):
def __init__(self, dim):
super().__init__()
inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
def forward(self, x):
t = torch.arange(x.shape[1], device=x.device).type_as(self.i... | class FixedPositionalEmbedding(nn.Module):
| def __init__(self, dim):
super().__init__()
inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
def forward(self, x):
t = torch.arange(x.shape[1], device=x.device).type_as(self.inv_freq)
sinusoid_inp = torch.einsu... | __init__(self, dim, max_seq_len):
super().__init__()
self.emb = nn.Embedding(max_seq_len, dim)
def forward(self, x):
t = torch.arange(x.shape[1], device=x.device)
return self.emb(t)
class FixedPositionalEmbedding(nn.Module):
| 64 | 64 | 141 | 8 | 56 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | FixedPositionalEmbedding | FixedPositionalEmbedding | 626 | 636 | 626 | 626 | 31e074cdd5088265c2e1165622635c4e6bbc16e0 | bigcode/the-stack | train |
0cb758689a65c940b60be618 | train | function | def merge_dims(ind_from, ind_to, tensor):
shape = list(tensor.shape)
arr_slice = slice(ind_from, ind_to + 1)
shape[arr_slice] = [reduce(mul, shape[arr_slice])]
return tensor.reshape(*shape)
| def merge_dims(ind_from, ind_to, tensor):
| shape = list(tensor.shape)
arr_slice = slice(ind_from, ind_to + 1)
shape[arr_slice] = [reduce(mul, shape[arr_slice])]
return tensor.reshape(*shape)
| return wrapper
return inner_fn
def expand_dim(dim, k, t):
t = t.unsqueeze(dim)
expand_shape = [-1] * len(t.shape)
expand_shape[dim] = k
return t.expand(*expand_shape)
def merge_dims(ind_from, ind_to, tensor):
| 64 | 64 | 55 | 11 | 53 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | merge_dims | merge_dims | 92 | 96 | 92 | 92 | 13afb9f665061430e282998b211f746006a891c7 | bigcode/the-stack | train |
ddc4ed09526de33dd1d9e4a0 | train | class | class ReZero(nn.Module):
def __init__(self, fn):
super().__init__()
self.g = nn.Parameter(torch.zeros(1))
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) * self.g
| class ReZero(nn.Module):
| def __init__(self, fn):
super().__init__()
self.g = nn.Parameter(torch.zeros(1))
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) * self.g
| self.transpose = transpose
self.normalize = normalize
def forward(self, x):
tensor = self.tensor
if self.normalize:
tensor = F.normalize(tensor, dim=-1)
if self.transpose:
tensor = tensor.t()
return x @ tensor
class ReZero(nn.Module):
| 64 | 64 | 60 | 6 | 57 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | ReZero | ReZero | 121 | 128 | 121 | 121 | e633dea7a224835e1241d0069c1040771b240f4b | bigcode/the-stack | train |
ccbc0ea4129074e2d787c414 | train | function | def batched_index_select(values, indices):
last_dim = values.shape[-1]
return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim))
| def batched_index_select(values, indices):
| last_dim = values.shape[-1]
return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim))
|
# helper fns
def sort_key_val(t1, t2, dim=-1):
values, indices = t1.sort(dim=dim)
t2 = t2.expand_as(t1)
return values, t2.gather(dim, indices)
def batched_index_select(values, indices):
| 64 | 64 | 41 | 9 | 55 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | batched_index_select | batched_index_select | 27 | 29 | 27 | 27 | 79c95680c0dd83d7c0851e71c192e7057a2831be | bigcode/the-stack | train |
4aa2057b9b53c3c6e676ec6a | train | function | def expand_dim(dim, k, t):
t = t.unsqueeze(dim)
expand_shape = [-1] * len(t.shape)
expand_shape[dim] = k
return t.expand(*expand_shape)
| def expand_dim(dim, k, t):
| t = t.unsqueeze(dim)
expand_shape = [-1] * len(t.shape)
expand_shape[dim] = k
return t.expand(*expand_shape)
| kwargs)
else:
val = fn(self, *args, **kwargs)
if set_cache:
setattr(self, cache_attr, {**_cache, **{_keyname: val}})
return val
return wrapper
return inner_fn
def expand_dim(dim, k, t):
| 64 | 64 | 45 | 9 | 54 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | expand_dim | expand_dim | 86 | 90 | 86 | 86 | 5fff5e2f487f7f735f09519a38c9a1a972fa8790 | bigcode/the-stack | train |
14f304d28a3b94961159bfc1 | train | class | class MatrixMultiply(nn.Module):
def __init__(self, tensor, transpose = False, normalize = False):
super().__init__()
self.tensor = tensor
self.transpose = transpose
self.normalize = normalize
def forward(self, x):
tensor = self.tensor
if self.normalize:
... | class MatrixMultiply(nn.Module):
| def __init__(self, tensor, transpose = False, normalize = False):
super().__init__()
self.tensor = tensor
self.transpose = transpose
self.normalize = normalize
def forward(self, x):
tensor = self.tensor
if self.normalize:
tensor = F.normalize(tensor, ... | _index(dim, index, t):
pre_slices = (slice(None),) * dim
l = (*pre_slices, slice(None, index))
r = (*pre_slices, slice(index, None))
return t[l], t[r]
# helper classes
class MatrixMultiply(nn.Module):
| 64 | 64 | 93 | 6 | 57 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | MatrixMultiply | MatrixMultiply | 106 | 119 | 106 | 106 | 731a01c87c4288cfe239832d2e6942a2af1ae776 | bigcode/the-stack | train |
3d422d8ccc1a26e5b10a304d | train | function | def cache_method_decorator(cache_attr, cache_namespace, reexecute = False):
def inner_fn(fn):
@wraps(fn)
def wrapper(self, *args, key_namespace=None, fetch=False, set_cache=True, **kwargs):
namespace_str = str(default(key_namespace, ''))
_cache = getattr(self, cache_attr)
... | def cache_method_decorator(cache_attr, cache_namespace, reexecute = False):
| def inner_fn(fn):
@wraps(fn)
def wrapper(self, *args, key_namespace=None, fetch=False, set_cache=True, **kwargs):
namespace_str = str(default(key_namespace, ''))
_cache = getattr(self, cache_attr)
_keyname = f'{cache_namespace}:{namespace_str}'
if fet... | s(f)
def cached_fn(*args, **kwargs):
nonlocal cache
if cache is not None:
return cache
cache = f(*args, **kwargs)
return cache
return cached_fn
def cache_method_decorator(cache_attr, cache_namespace, reexecute = False):
| 64 | 64 | 166 | 16 | 47 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | cache_method_decorator | cache_method_decorator | 66 | 84 | 66 | 66 | eb07f48d5e306f84a9a5b8182c4a6a53eb7cd66b | bigcode/the-stack | train |
047c3cf5fef6a45638e3ca40 | train | class | class FullQKAttention(nn.Module):
def __init__(self, causal = False, dropout = 0.):
super().__init__()
self.causal = causal
self.dropout = nn.Dropout(dropout)
def forward(self, qk, v, query_len = None, input_mask = None, input_attn_mask = None, **kwargs):
b, seq_len, dim = qk.sh... | class FullQKAttention(nn.Module):
| def __init__(self, causal = False, dropout = 0.):
super().__init__()
self.causal = causal
self.dropout = nn.Dropout(dropout)
def forward(self, qk, v, query_len = None, input_mask = None, input_attn_mask = None, **kwargs):
b, seq_len, dim = qk.shape
query_len = default(qu... | , seqlen * seqlen, device=device)
unsorted_dots.scatter_add_(1, attn_unsort, dots.view_as(attn_unsort))
del attn_unsort
unsorted_dots = unsorted_dots.reshape(batch_size, total_hashes, seqlen, seqlen)
attn = torch.sum(unsorted_dots[:, :, 0:query_len, :] * probs, dim=1)
... | 129 | 129 | 430 | 8 | 120 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | FullQKAttention | FullQKAttention | 428 | 469 | 428 | 428 | f3c3443de8fe3f3661e745d3ae1c4f3cc95b9b0e | bigcode/the-stack | train |
eb7fc5c6f7e7d5e812d8d1c3 | train | class | class GELU_(nn.Module):
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
| class GELU_(nn.Module):
| def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
| , t, -1)
out = torch.cat((local_out, out), dim=1)
out = split_heads(out).view(b, t, -1)
out = self.to_out(out)
return self.post_attn_dropout(out)
# feed forward
class GELU_(nn.Module):
| 64 | 64 | 54 | 7 | 56 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | GELU_ | GELU_ | 586 | 588 | 586 | 586 | a9c61675666d0e91e28209d8734218bf3c8fae43 | bigcode/the-stack | train |
2fb9b179210078feb0546d18 | train | class | class LSHAttention(nn.Module):
def __init__( self,
dropout = 0.,
bucket_size = 64,
n_hashes = 8,
causal = False,
allow_duplicate_attention = True,
attend_across_buckets = True,
rehash_each_r... | class LSHAttention(nn.Module):
| def __init__( self,
dropout = 0.,
bucket_size = 64,
n_hashes = 8,
causal = False,
allow_duplicate_attention = True,
attend_across_buckets = True,
rehash_each_round = True,
... | def __init__(self, norm_class, dim, fn):
super().__init__()
self.norm = norm_class(dim)
self.fn = fn
def forward(self, x, **kwargs):
x = self.norm(x)
return self.fn(x, **kwargs)
class Chunk(nn.Module):
def __init__(self, chunks, fn, along_dim = -1):
super()._... | 256 | 256 | 3,024 | 7 | 248 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | LSHAttention | LSHAttention | 167 | 424 | 167 | 167 | 863a11d992676e45ae4e367211095ed93110d850 | bigcode/the-stack | train |
bbd89830606b9b27d0f0d5ec | train | class | class LSHSelfAttention(nn.Module):
def __init__(self, dim, heads = 8, bucket_size = 64, n_hashes = 8, causal = False,
dim_head = None, attn_chunks = 1, random_rotations_per_head = False,
attend_across_buckets = True, allow_duplicate_attention = True,
num_mem_kv ... | class LSHSelfAttention(nn.Module):
| def __init__(self, dim, heads = 8, bucket_size = 64, n_hashes = 8, causal = False,
dim_head = None, attn_chunks = 1, random_rotations_per_head = False,
attend_across_buckets = True, allow_duplicate_attention = True,
num_mem_kv = 0, one_value_head = False, use_fu... | TN_VALUE
masked_value = max_neg_value(dot)
# Input mask for padding in variable lengthed sequences
if input_mask is not None:
mask = input_mask[:, 0:query_len, None] * input_mask[:, None, :]
mask = F.pad(mask, (0, seq_len - mask.shape[-1]), value=True)
dot.ma... | 256 | 256 | 1,424 | 8 | 247 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | LSHSelfAttention | LSHSelfAttention | 473 | 582 | 473 | 473 | 653c06fe5cb922a966b0b5978afddb343509fca0 | bigcode/the-stack | train |
54b3de11c0dfa8f165c4461f | train | function | def split_at_index(dim, index, t):
pre_slices = (slice(None),) * dim
l = (*pre_slices, slice(None, index))
r = (*pre_slices, slice(index, None))
return t[l], t[r]
| def split_at_index(dim, index, t):
| pre_slices = (slice(None),) * dim
l = (*pre_slices, slice(None, index))
r = (*pre_slices, slice(index, None))
return t[l], t[r]
| merge_dims(ind_from, ind_to, tensor):
shape = list(tensor.shape)
arr_slice = slice(ind_from, ind_to + 1)
shape[arr_slice] = [reduce(mul, shape[arr_slice])]
return tensor.reshape(*shape)
def split_at_index(dim, index, t):
| 64 | 64 | 57 | 10 | 54 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | split_at_index | split_at_index | 98 | 102 | 98 | 98 | ad8337ca5e181b8be9279470dc8cf4788e88b55a | bigcode/the-stack | train |
9752a19b804eb9a4bb8c686a | train | function | def process_inputs_chunk(fn, chunks=1, dim=0):
def inner_fn(*args, **kwargs):
keys, values, len_args = kwargs.keys(), kwargs.values(), len(args)
chunked_args = list(zip(*map(lambda x: x.chunk(chunks, dim=dim), list(args) + list(values))))
all_args = map(lambda x: (x[:len_args], dict(zip(keys... | def process_inputs_chunk(fn, chunks=1, dim=0):
| def inner_fn(*args, **kwargs):
keys, values, len_args = kwargs.keys(), kwargs.values(), len(args)
chunked_args = list(zip(*map(lambda x: x.chunk(chunks, dim=dim), list(args) + list(values))))
all_args = map(lambda x: (x[:len_args], dict(zip(keys, x[len_args:]))), chunked_args)
output... | , t2.gather(dim, indices)
def batched_index_select(values, indices):
last_dim = values.shape[-1]
return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim))
def process_inputs_chunk(fn, chunks=1, dim=0):
| 64 | 64 | 144 | 14 | 50 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | process_inputs_chunk | process_inputs_chunk | 31 | 38 | 31 | 31 | 8cee279587ebf6557814ebeb7afb7d0150716ccd | bigcode/the-stack | train |
ab6715b98a86dc0325d83816 | train | function | def max_neg_value(tensor):
return -torch.finfo(tensor.dtype).max
| def max_neg_value(tensor):
| return -torch.finfo(tensor.dtype).max
| =0)]
return torch.cat(summed_tensors, dim=0).reshape(orig_size)
def default(val, default_val):
return default_val if val is None else val
def cast_tuple(x):
return x if isinstance(x, tuple) else (x,)
def max_neg_value(tensor):
| 63 | 64 | 19 | 7 | 56 | wilson1yan/reformer-pytorch | reformer_pytorch/reformer_pytorch.py | Python | max_neg_value | max_neg_value | 52 | 53 | 52 | 52 | ea7f0789892d2837dc9c2e01cc84504dfc1d1e4f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.