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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11f81fe9045dcd1c74769936 | train | class | class AuthenticationMiddleware(middleware.AuthenticationMiddleware):
def process_request(self, request):
super(AuthenticationMiddleware, self).process_request(request)
if request.user.is_superuser:
request.user.acting_as_superuser = bool(
request.session.get('acting_as_s... | class AuthenticationMiddleware(middleware.AuthenticationMiddleware):
| def process_request(self, request):
super(AuthenticationMiddleware, self).process_request(request)
if request.user.is_superuser:
request.user.acting_as_superuser = bool(
request.session.get('acting_as_superuser')
)
| from django.contrib.auth import middleware
class AuthenticationMiddleware(middleware.AuthenticationMiddleware):
| 15 | 64 | 58 | 8 | 6 | tbone255/foundation | foundation/auth/middleware.py | Python | AuthenticationMiddleware | AuthenticationMiddleware | 4 | 11 | 4 | 5 | a6184267973f5565be15b789d4e65d1ce9c6826d | bigcode/the-stack | train |
dd2f7c22602f38ebec693935 | train | function | def get_grid() -> List[List[int]]:
return [
[int(number) for number in line.split()]
for line in grid_string.splitlines()
]
| def get_grid() -> List[List[int]]:
| return [
[int(number) for number in line.split()]
for line in grid_string.splitlines()
]
| 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
""".strip()
def get_grid() -> List[List[int]]:
| 64 | 64 | 34 | 9 | 55 | mattnhb/exercises-and-whatsoever | project-euler/exercise-11.py | Python | get_grid | get_grid | 55 | 59 | 55 | 55 | bb2e3d66035215c071a2cc1838801a1dc090740a | bigcode/the-stack | train |
260e38824342a4f8466cab60 | train | class | class BindExtraTest(WidecoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
# Avoid any -bind= on the command line. Force the framework to avoid
# adding -bind=127.0.0.1.
self.bind_to_localhost_only = False
self.num_nodes = 2
def setup_network(se... | class BindExtraTest(WidecoinTestFramework):
| def set_test_params(self):
self.setup_clean_chain = True
# Avoid any -bind= on the command line. Force the framework to avoid
# adding -bind=127.0.0.1.
self.bind_to_localhost_only = False
self.num_nodes = 2
def setup_network(self):
# Override setup_network() beca... | #!/usr/bin/env python3
# Copyright (c) 2014-2021 The Widecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test starting widecoind with -bind and/or -bind=...=onion and confirm
that bind happens on the expect... | 154 | 210 | 702 | 10 | 144 | widecoin-project/widecoin | test/functional/feature_bind_extra.py | Python | BindExtraTest | BindExtraTest | 27 | 92 | 27 | 27 | 66474534a43f9858744844ade800a1ac45eaf322 | bigcode/the-stack | train |
3a0a4a45d2cb5bb1e15d3ff0 | train | function | def train(agent, logger, dataset, noise_type, epochs, lr, lr_step, alpha, model_path, reward_mode=""):
optimizer = torch.optim.Adam(agent.parameters(), lr=lr, amsgrad=True)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, lr_step, 0.5)
Dataset = DatasetModelnet40 if dataset == "m40" else DatasetLinem... | def train(agent, logger, dataset, noise_type, epochs, lr, lr_step, alpha, model_path, reward_mode=""):
| optimizer = torch.optim.Adam(agent.parameters(), lr=lr, amsgrad=True)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, lr_step, 0.5)
Dataset = DatasetModelnet40 if dataset == "m40" else DatasetLinemod
train_dataset = Dataset("train", noise_type)
train_loader = torch.utils.data.DataLoader(trai... | import numpy as np
np.random.seed(42)
import torch
torch.manual_seed(42)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.set_default_dtype(torch.float32)
import torch.nn.functional as F
import torch.nn as nn
import os
from tqdm import tqdm
from prefetch_generator import Background... | 225 | 256 | 1,707 | 27 | 198 | JiazeWang/reagent | registration/train_pn_2D_projected.py | Python | train | train | 30 | 192 | 30 | 30 | 8624616cedc0926656f5dfe2859576c149212df8 | bigcode/the-stack | train |
05974b72cd4a6231cfe6c1bd | train | function | def evaluate(agent, logger, loader, prefix='test'):
agent.eval()
progress = tqdm(BackgroundGenerator(loader), total=len(loader))
predictions = []
val_losses = []
with torch.no_grad():
for data in progress:
source, target, pose_source, pose_target = env.init(data)
if c... | def evaluate(agent, logger, loader, prefix='test'):
| agent.eval()
progress = tqdm(BackgroundGenerator(loader), total=len(loader))
predictions = []
val_losses = []
with torch.no_grad():
for data in progress:
source, target, pose_source, pose_target = env.init(data)
if cfg.DISENTANGLED:
pose_target = tra.t... | fer_test = evaluate(agent, logger, test_loader)
if chamfer_test <= best_chamfer:
print(f"new best: {chamfer_test}")
best_chamfer = chamfer_test
infos = {
'epoch': epoch,
'optimizer_state_dict': optimizer.state_dict()
}
... | 155 | 155 | 519 | 12 | 143 | JiazeWang/reagent | registration/train_pn_2D_projected.py | Python | evaluate | evaluate | 195 | 239 | 195 | 195 | 3575fc76ff3c7c15bcaef6e3372e4d6910a94cca | bigcode/the-stack | train |
efc78a73ba3f61f3fd62b6d9 | train | function | def valutaEntry(numero):
if valutaFloat(numero) or valutaInteger(numero):
return True
return False
| def valutaEntry(numero):
| if valutaFloat(numero) or valutaInteger(numero):
return True
return False
| (numero) > 1:
if numero.isdigit() or \
(numero[0] == "-" and numero[1] != "0" and numero[1:].isdigit()):
return True
else:
if numero.isdigit():
return True
return False
def valutaEntry(numero):
| 64 | 64 | 24 | 5 | 58 | aleattene/python-workbook | chap_03/exe_067_polygon_perimeter.py | Python | valutaEntry | valutaEntry | 70 | 73 | 70 | 70 | 2d38c7562647475560e50bec589f88945098665c | bigcode/the-stack | train |
1dc89719cdd45096acce9c08 | train | function | def valutaInteger(numero):
if len(numero) > 1:
if numero.isdigit() or \
(numero[0] == "-" and numero[1] != "0" and numero[1:].isdigit()):
return True
else:
if numero.isdigit():
return True
return False
| def valutaInteger(numero):
| if len(numero) > 1:
if numero.isdigit() or \
(numero[0] == "-" and numero[1] != "0" and numero[1:].isdigit()):
return True
else:
if numero.isdigit():
return True
return False
| "-")) and countSigns == 1 and \
numero != "-" and numero != "+" and numero != "-." and numero != "+.":
return True
elif numero[0].isdigit() and countSigns == 0:
return True
else:
return False
def valutaInteger(numero):
| 64 | 64 | 67 | 5 | 58 | aleattene/python-workbook | chap_03/exe_067_polygon_perimeter.py | Python | valutaInteger | valutaInteger | 59 | 67 | 59 | 59 | f1b13a12cffdea50aa56f08caf5fb5f7d86146c3 | bigcode/the-stack | train |
43998f03209df95254cba91e | train | function | def valutaFloat(numero):
countPoints = 0
for char in numero:
if ord(char) == 46:
countPoints += 1
if countPoints == 1 and numero != "." and valutaNumero(numero):
if isinstance(float(numero), float):
return True
else:
return False
| def valutaFloat(numero):
| countPoints = 0
for char in numero:
if ord(char) == 46:
countPoints += 1
if countPoints == 1 and numero != "." and valutaNumero(numero):
if isinstance(float(numero), float):
return True
else:
return False
| x-coordinate (blank to quit): 0 Enter the next y-coordinate: 1
Enter the next x-coordinate (blank to quit):
The perimeter of that polygon is 3.414213562373095
"""
# IMPORT module MATH
import math
# START Definition of FUNCTIONS
def valutaFloat(numero):
| 64 | 64 | 69 | 5 | 58 | aleattene/python-workbook | chap_03/exe_067_polygon_perimeter.py | Python | valutaFloat | valutaFloat | 31 | 40 | 31 | 31 | 9f3e9b4292b03be17643eb8e04af0bc51b115366 | bigcode/the-stack | train |
fdf020b9709839dd5635026f | train | function | def computePointsDistance(x1, y1, x2, y2):
x1 = float(x1)
y1 = float(y1)
x2 = float(x2)
y2 = float(y2)
distance = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
return distance
| def computePointsDistance(x1, y1, x2, y2):
| x1 = float(x1)
y1 = float(y1)
x2 = float(x2)
y2 = float(y2)
distance = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
return distance
| :].isdigit()):
return True
else:
if numero.isdigit():
return True
return False
def valutaEntry(numero):
if valutaFloat(numero) or valutaInteger(numero):
return True
return False
def computePointsDistance(x1, y1, x2, y2):
| 64 | 64 | 80 | 16 | 47 | aleattene/python-workbook | chap_03/exe_067_polygon_perimeter.py | Python | computePointsDistance | computePointsDistance | 76 | 82 | 76 | 76 | ca3d6b2eac8039fae5bd5f6382dd4720ac6f6fc3 | bigcode/the-stack | train |
9d8352d24e6915e71181f1d8 | train | function | def valutaNumero(numero):
if numero == "":
return False
countSigns = 0
for char in numero:
if ord(char) == 45 or ord(char) == 43:
countSigns += 1
if ((numero[0] == "+") or (numero[0] == "-")) and countSigns == 1 and \
numero != "-" and numero != "+" and numero != ... | def valutaNumero(numero):
| if numero == "":
return False
countSigns = 0
for char in numero:
if ord(char) == 45 or ord(char) == 43:
countSigns += 1
if ((numero[0] == "+") or (numero[0] == "-")) and countSigns == 1 and \
numero != "-" and numero != "+" and numero != "-." and numero != "+.":
... | 0
for char in numero:
if ord(char) == 46:
countPoints += 1
if countPoints == 1 and numero != "." and valutaNumero(numero):
if isinstance(float(numero), float):
return True
else:
return False
def valutaNumero(numero):
| 64 | 64 | 126 | 5 | 58 | aleattene/python-workbook | chap_03/exe_067_polygon_perimeter.py | Python | valutaNumero | valutaNumero | 43 | 56 | 43 | 43 | a9cda513e65c1c685c8d038ee4fd3cc8fa65f262 | bigcode/the-stack | train |
11f4670459bb4b449ff8dc64 | train | class | class ConvInUpsampleNetwork(torch.nn.Module):
"""Convolution + upsampling network module."""
def __init__(
self,
upsample_scales: List[int],
nonlinear_activation: Optional[str] = None,
nonlinear_activation_params: Dict[str, Any] = {},
interpolate_mode: str = "nearest",
... | class ConvInUpsampleNetwork(torch.nn.Module):
| """Convolution + upsampling network module."""
def __init__(
self,
upsample_scales: List[int],
nonlinear_activation: Optional[str] = None,
nonlinear_activation_params: Dict[str, Any] = {},
interpolate_mode: str = "nearest",
freq_axis_kernel_size: int = 1,
... | nonlinear = getattr(torch.nn, nonlinear_activation)(
**nonlinear_activation_params
)
self.up_layers += [nonlinear]
def forward(self, c: torch.Tensor) -> torch.Tensor:
"""Calculate forward propagation.
Args:
c : Input t... | 144 | 144 | 480 | 10 | 134 | roshansh-cmu/espnet | espnet2/gan_tts/parallel_wavegan/upsample.py | Python | ConvInUpsampleNetwork | ConvInUpsampleNetwork | 127 | 186 | 127 | 127 | c04983a762e55421e91fb34321b878cb1dbff51d | bigcode/the-stack | train |
4d913f4fc6a20d54867b662c | train | class | class Conv2d(torch.nn.Conv2d):
"""Conv2d module with customized initialization."""
def __init__(self, *args, **kwargs):
"""Initialize Conv2d module."""
super().__init__(*args, **kwargs)
def reset_parameters(self):
"""Reset parameters."""
self.weight.data.fill_(1.0 / np.prod... | class Conv2d(torch.nn.Conv2d):
| """Conv2d module with customized initialization."""
def __init__(self, *args, **kwargs):
"""Initialize Conv2d module."""
super().__init__(*args, **kwargs)
def reset_parameters(self):
"""Reset parameters."""
self.weight.data.fill_(1.0 / np.prod(self.kernel_size))
if ... | T).
Returns:
Tensor: Interpolated tensor (B, C, F * y_scale, T * x_scale),
"""
return F.interpolate(
x, scale_factor=(self.y_scale, self.x_scale), mode=self.mode
)
class Conv2d(torch.nn.Conv2d):
| 64 | 64 | 100 | 10 | 54 | roshansh-cmu/espnet | espnet2/gan_tts/parallel_wavegan/upsample.py | Python | Conv2d | Conv2d | 51 | 62 | 51 | 51 | 166aa64fb9d8e2210fa6edd2262fae5f6b9fcaa3 | bigcode/the-stack | train |
b66510e0dd540e192e688412 | train | class | class UpsampleNetwork(torch.nn.Module):
"""Upsampling network module."""
def __init__(
self,
upsample_scales: List[int],
nonlinear_activation: Optional[str] = None,
nonlinear_activation_params: Dict[str, Any] = {},
interpolate_mode: str = "nearest",
freq_axis_ker... | class UpsampleNetwork(torch.nn.Module):
| """Upsampling network module."""
def __init__(
self,
upsample_scales: List[int],
nonlinear_activation: Optional[str] = None,
nonlinear_activation_params: Dict[str, Any] = {},
interpolate_mode: str = "nearest",
freq_axis_kernel_size: int = 1,
):
"""Ini... | , T * x_scale),
"""
return F.interpolate(
x, scale_factor=(self.y_scale, self.x_scale), mode=self.mode
)
class Conv2d(torch.nn.Conv2d):
"""Conv2d module with customized initialization."""
def __init__(self, *args, **kwargs):
"""Initialize Conv2d module."""
... | 141 | 141 | 473 | 8 | 133 | roshansh-cmu/espnet | espnet2/gan_tts/parallel_wavegan/upsample.py | Python | UpsampleNetwork | UpsampleNetwork | 65 | 124 | 65 | 65 | d864c87f2f54028d76c3382473c287f248dcae01 | bigcode/the-stack | train |
a06f07f6fc07a342b12d8d7c | train | class | class Stretch2d(torch.nn.Module):
"""Stretch2d module."""
def __init__(self, x_scale: int, y_scale: int, mode: str = "nearest"):
"""Initialize Stretch2d module.
Args:
x_scale (int): X scaling factor (Time axis in spectrogram).
y_scale (int): Y scaling factor (Frequency ... | class Stretch2d(torch.nn.Module):
| """Stretch2d module."""
def __init__(self, x_scale: int, y_scale: int, mode: str = "nearest"):
"""Initialize Stretch2d module.
Args:
x_scale (int): X scaling factor (Time axis in spectrogram).
y_scale (int): Y scaling factor (Frequency axis in spectrogram).
... | /kan-bayashi/ParallelWaveGAN.
"""
from typing import Any, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from espnet2.gan_tts.wavenet.residual_block import Conv1d
class Stretch2d(torch.nn.Module):
| 64 | 64 | 211 | 8 | 55 | roshansh-cmu/espnet | espnet2/gan_tts/parallel_wavegan/upsample.py | Python | Stretch2d | Stretch2d | 19 | 48 | 19 | 19 | 8a0e02a66208f8745b6f2fb1ee11c622d50a7e98 | bigcode/the-stack | train |
1aec8001a4c0e50a2c77b533 | train | class | class RegistrationError(Exception):
def __init__(self, filename, error):
self.filename = filename
self.code = str(error.returncode)
self.msg = error.output
def __str__(self):
filerr = "Unable to register VM from file " + filename + "\n"
errmsg = "Returned message was:\n"... | class RegistrationError(Exception):
| def __init__(self, filename, error):
self.filename = filename
self.code = str(error.returncode)
self.msg = error.output
def __str__(self):
filerr = "Unable to register VM from file " + filename + "\n"
errmsg = "Returned message was:\n" + self.msg
return filerr + ... | name, uuid):
self.name = str(name)
self.uuid = str(uuid)
def __str__(self):
return "No VM found for name " + self.name + " and UUID " + self.uuid
# Error when trying to register a VM from its XML file
class RegistrationError(Exception):
| 64 | 64 | 84 | 5 | 58 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | RegistrationError | RegistrationError | 33 | 42 | 33 | 33 | 14bd934fa0935f6d2b6d960ba26a4cf9e15e431b | bigcode/the-stack | train |
b749d8311417c0f08fa3d9fa | train | class | class CloseMediumError(Exception):
def __init__(self, device, target, error=None):
self.device = device
self.target = target
if error:
self.msg = error.output
else:
self.msg = ""
def __str__(self):
e = "Cannot close device " + self.device + " wit... | class CloseMediumError(Exception):
| def __init__(self, device, target, error=None):
self.device = device
self.target = target
if error:
self.msg = error.output
else:
self.msg = ""
def __str__(self):
e = "Cannot close device " + self.device + " with target " + self.target
r... | self.msg = error.output
def __str__(self):
filerr = "Unable to register VM from file " + filename + "\n"
errmsg = "Returned message was:\n" + self.msg
return filerr + errmsg
# Error for closemedium
class CloseMediumError(Exception):
| 64 | 64 | 89 | 6 | 57 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | CloseMediumError | CloseMediumError | 45 | 56 | 45 | 45 | a65b1a5aa9b45d99094457f59d443f50db1aefa0 | bigcode/the-stack | train |
1a2d92e2bb7787e9a27eac37 | train | class | class CommandError(Exception):
def __init__(self, cmd, error):
self.cmd = ' '.join(cmd)
self.code = str(error.returncode)
self.msg = error.output
def __str__(self):
return "Command " + self.cmd + " failed with code " + self.code + \
" and message:\n" + self.msg
| class CommandError(Exception):
| def __init__(self, cmd, error):
self.cmd = ' '.join(cmd)
self.code = str(error.returncode)
self.msg = error.output
def __str__(self):
return "Command " + self.cmd + " failed with code " + self.code + \
" and message:\n" + self.msg
|
# Generic class for catching and communicating errors from VBoxManage commands
class CommandError(Exception):
| 19 | 64 | 78 | 5 | 13 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | CommandError | CommandError | 3 | 11 | 3 | 3 | d754c5c6e5f19044e94e76a05472806ed6e3d0b8 | bigcode/the-stack | train |
5e9d5641327c54676345d944 | train | class | class UnknownOptionError(Exception):
def __init__(self, cmd, option):
self.cmd = cmd
self.option = option
def __str__(self):
return "Unknown Option " + self.option + " for command " + self.cmd
| class UnknownOptionError(Exception):
| def __init__(self, cmd, option):
self.cmd = cmd
self.option = option
def __str__(self):
return "Unknown Option " + self.option + " for command " + self.cmd
| = error.output
def __str__(self):
return "Command " + self.cmd + " failed with code " + self.code + \
" and message:\n" + self.msg
# Error for when using a user-specified option with a VBoxManage command fails
class UnknownOptionError(Exception):
| 64 | 64 | 54 | 6 | 57 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | UnknownOptionError | UnknownOptionError | 14 | 20 | 14 | 14 | b4ba75243e08e622f5a4b0c2227418f6ba01514d | bigcode/the-stack | train |
e577bbb4243b063802af56f3 | train | class | class NoMediumError(CloseMediumError):
def __str__(self):
return self.device + " is not a valid device"
| class NoMediumError(CloseMediumError):
| def __str__(self):
return self.device + " is not a valid device"
| error:
self.msg = error.output
else:
self.msg = ""
def __str__(self):
e = "Cannot close device " + self.device + " with target " + self.target
return e + "\n" + self.msg
class NoMediumError(CloseMediumError):
| 64 | 64 | 28 | 9 | 54 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | NoMediumError | NoMediumError | 58 | 60 | 58 | 58 | 4f7f602e33164df51bb77f33169047470131d61c | bigcode/the-stack | train |
4d4ff5cd1ce7bd707ffb5581 | train | class | class UnknownVMError(Exception):
def __init__(self, name, uuid):
self.name = str(name)
self.uuid = str(uuid)
def __str__(self):
return "No VM found for name " + self.name + " and UUID " + self.uuid
| class UnknownVMError(Exception):
| def __init__(self, name, uuid):
self.name = str(name)
self.uuid = str(uuid)
def __str__(self):
return "No VM found for name " + self.name + " and UUID " + self.uuid
| self, cmd, option):
self.cmd = cmd
self.option = option
def __str__(self):
return "Unknown Option " + self.option + " for command " + self.cmd
# Error for when the VM specified by name and UUID is unrecognized
class UnknownVMError(Exception):
| 64 | 64 | 59 | 6 | 57 | jongiddy/dcos-e2e | src/dcos_e2e_cli/_vendor/vertigo_py/error.py | Python | UnknownVMError | UnknownVMError | 24 | 30 | 24 | 24 | 0c04d7ce115c3e97523c46c749d7383359e04dca | bigcode/the-stack | train |
50445670d4915d1ec6553088 | train | function | def somaPar(lista):
soma = 0
for num in lista:
if num % 2 == 0:
soma += num
print(f'Somandos os valores pares de {lista}, temos {soma}')
| def somaPar(lista):
| soma = 0
for num in lista:
if num % 2 == 0:
soma += num
print(f'Somandos os valores pares de {lista}, temos {soma}')
| (f'Sorteando 5 valores: ', end='')
for c in range(0, 6):
n = randint(1, 10)
lista.append(n)
print(f'{n} ', end='')
sleep(0.3)
print('FIM')
def somaPar(lista):
| 64 | 64 | 50 | 5 | 59 | Caio-Moretti/115.Exercicios-Python | PythonExercicios/ex100.py | Python | somaPar | somaPar | 15 | 20 | 15 | 15 | 4f8417b70b57f65cb0c84725c02af724cba57a32 | bigcode/the-stack | train |
e3b099510de66bbfb3e0d040 | train | function | def sorteia(lista):
print(f'Sorteando 5 valores: ', end='')
for c in range(0, 6):
n = randint(1, 10)
lista.append(n)
print(f'{n} ', end='')
sleep(0.3)
print('FIM')
| def sorteia(lista):
| print(f'Sorteando 5 valores: ', end='')
for c in range(0, 6):
n = randint(1, 10)
lista.append(n)
print(f'{n} ', end='')
sleep(0.3)
print('FIM')
| from random import randint
from time import sleep
def sorteia(lista):
| 15 | 64 | 66 | 5 | 9 | Caio-Moretti/115.Exercicios-Python | PythonExercicios/ex100.py | Python | sorteia | sorteia | 5 | 12 | 5 | 5 | 65deab1a3eeb25dd89894204457962f1a72d3eba | bigcode/the-stack | train |
09b7b362b75a6d0f34d7c732 | train | class | class RelationsTestCase(unittest.HomeserverTestCase):
servlets = [
relations.register_servlets,
room.register_servlets,
sync.register_servlets,
login.register_servlets,
register.register_servlets,
admin.register_servlets_for_client_rest_resource,
]
hijack_auth... | class RelationsTestCase(unittest.HomeserverTestCase):
| servlets = [
relations.register_servlets,
room.register_servlets,
sync.register_servlets,
login.register_servlets,
register.register_servlets,
admin.register_servlets_for_client_rest_resource,
]
hijack_auth = False
def default_config(self) -> dict:
... | 2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | 256 | 256 | 11,366 | 11 | 244 | AndrewRyanChama/synapse | tests/rest/client/test_relations.py | Python | RelationsTestCase | RelationsTestCase | 33 | 1,440 | 33 | 33 | 730774e8f4de240c4969a54d8f1e00e718448d69 | bigcode/the-stack | train |
6c728d028e9ecf81d17cb7a6 | train | function | def fft2d_unitary(n1: int, n2: int, br_first: bool = True,
with_br_perm: bool = True) -> nn.Module:
""" Construct an nn.Module based on ButterflyUnitary that exactly performs the 2D FFT.
Corresponds to normalized=True.
Does not support flatten for now.
Parameters:
n1: size of t... | def fft2d_unitary(n1: int, n2: int, br_first: bool = True,
with_br_perm: bool = True) -> nn.Module:
| """ Construct an nn.Module based on ButterflyUnitary that exactly performs the 2D FFT.
Corresponds to normalized=True.
Does not support flatten for now.
Parameters:
n1: size of the FFT on the last input dimension. Must be a power of 2.
n2: size of the FFT on the second to last input dime... | ), b, br_perm,
nn.Unflatten(-1, (n2, n1))))
else:
return b if not flatten else nn.Sequential(nn.Flatten(start_dim=-2), b,
nn.Unflatten(-1, (n2, n1)))
def fft2d_unitary(n1: int, n2: int, br_first: bool = Tru... | 92 | 93 | 313 | 36 | 56 | skn123/butterfly | torch_butterfly/special.py | Python | fft2d_unitary | fft2d_unitary | 518 | 539 | 518 | 519 | 4a52c7e6cb21e33b8a2b661ee30151e009a91d7f | bigcode/the-stack | train |
fc3644e437675918ecd5c830 | train | function | def fft2d(n1: int, n2: int, normalized: bool = False, br_first: bool = True,
with_br_perm: bool = True, flatten=False) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the 2D FFT.
Parameters:
n1: size of the FFT on the last input dimension. Must be a power of 2... | def fft2d(n1: int, n2: int, normalized: bool = False, br_first: bool = True,
with_br_perm: bool = True, flatten=False) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the 2D FFT.
Parameters:
n1: size of the FFT on the last input dimension. Must be a power of 2.
n2: size of the FFT on the second to last input dimension. Must be a power of 2.
normalized: if True, corresponds to the unit... | ]
col_f = index_last_dim(col_f, br_perm)
# We just want (input_f.unsqueeze(1) * col_f).sum(dim=2).
# This can be written as a complex matrix multiply as well.
if not complex:
return nn.Sequential(Real2Complex(), b_fft, DiagonalMultiplySum(col_f), b_ifft,
Complex2Rea... | 146 | 146 | 488 | 43 | 103 | skn123/butterfly | torch_butterfly/special.py | Python | fft2d | fft2d | 487 | 515 | 487 | 488 | 092c8f4765a93195d3b1dfe4b36b7543f6e74d09 | bigcode/the-stack | train |
fe805246de4f1e06e732a1bf | train | function | def ifft2d(n1: int, n2: int, normalized: bool = False, br_first: bool = True,
with_br_perm: bool = True, flatten=False) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the 2D iFFT.
Parameters:
n1: size of the iFFT on the last input dimension. Must be a power ... | def ifft2d(n1: int, n2: int, normalized: bool = False, br_first: bool = True,
with_br_perm: bool = True, flatten=False) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the 2D iFFT.
Parameters:
n1: size of the iFFT on the last input dimension. Must be a power of 2.
n2: size of the iFFT on the second to last input dimension. Must be a power of 2.
normalized: if True, corresponds to the u... | with_br_perm=False)
b = TensorProduct(b_fft1, b_fft2)
if with_br_perm:
br_perm1 = FixedPermutation(bitreversal_permutation(n1, pytorch_format=True))
br_perm2 = FixedPermutation(bitreversal_permutation(n2, pytorch_format=True))
br_perm = TensorProduct(br_perm1, br_perm2)
return n... | 149 | 149 | 498 | 44 | 104 | skn123/butterfly | torch_butterfly/special.py | Python | ifft2d | ifft2d | 542 | 570 | 542 | 543 | ba52f58f0c6d03972ddfbe9e4579f7cdbf150909 | bigcode/the-stack | train |
a226e17c5dd90622a8299c77 | train | function | def circulant(col, transposed=False, separate_diagonal=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs circulant matrix
multiplication.
Parameters:
col: torch.Tensor of size (n, ). The first column of the circulant matrix.
transposed: if True, then the... | def circulant(col, transposed=False, separate_diagonal=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs circulant matrix
multiplication.
Parameters:
col: torch.Tensor of size (n, ). The first column of the circulant matrix.
transposed: if True, then the circulant matrix is transposed, i.e. col is the first *row*
... | permute the diagonal
b = diagonal_butterfly(b, preprocess_diag[perm[br]], diag_first=True)
if type == 2:
postprocess_diag = 2j * torch.exp(-1j * math.pi * (torch.arange(0.0, n) + 1) / (2 * n))
elif type == 4:
postprocess_diag = 2j * torch.exp(-1j * math.pi * (torch.arange(0.0, n) + 0.5) / (... | 228 | 228 | 763 | 18 | 210 | skn123/butterfly | torch_butterfly/special.py | Python | circulant | circulant | 248 | 301 | 248 | 248 | e11991975d9c09c75d29622ec766527b95e984df | bigcode/the-stack | train |
43b80ba8594202ff681ba600 | train | function | def acdc(diag1: torch.Tensor, diag2: torch.Tensor, dct_first: bool = True,
separate_diagonal: bool = True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs either the multiplication:
x -> diag2 @ iDCT @ diag1 @ DCT @ x
or
x -> diag2 @ DCT @ diag1 @ iDCT ... | def acdc(diag1: torch.Tensor, diag2: torch.Tensor, dct_first: bool = True,
separate_diagonal: bool = True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs either the multiplication:
x -> diag2 @ iDCT @ diag1 @ DCT @ x
or
x -> diag2 @ DCT @ diag1 @ iDCT @ x.
In the paper [1], the math describes the 2nd type while the implementation uses the 1st type.
Note that the DCT and i... | . multiplied by 1/sqrt(n))
increasing_stride: whether the first Butterfly in the sequence has increasing stride.
separate_diagonal: if False, the diagonal is combined into the Butterfly part.
"""
n, = diag1.shape
assert diag2.shape == diag3.shape == permutation.shape == (n,)
h1 = hadamar... | 256 | 256 | 957 | 37 | 219 | skn123/butterfly | torch_butterfly/special.py | Python | acdc | acdc | 714 | 779 | 714 | 715 | fa7a159bb582c4e6e381a2c84b0358c566afa06b | bigcode/the-stack | train |
6cb2bf063aca71549c94ad76 | train | function | def fft(n, normalized=False, br_first=True, with_br_perm=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the FFT.
Parameters:
n: size of the FFT. Must be a power of 2.
normalized: if True, corresponds to the unitary FFT (i.e. multiplied by 1/sqrt(n))
... | def fft(n, normalized=False, br_first=True, with_br_perm=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the FFT.
Parameters:
n: size of the FFT. Must be a power of 2.
normalized: if True, corresponds to the unitary FFT (i.e. multiplied by 1/sqrt(n))
br_first: which decomposition of FFT. br_first=True corresponds to decimat... |
from torch_butterfly.permutation import FixedPermutation, bitreversal_permutation, invert
from torch_butterfly.permutation import wavelet_permutation
from torch_butterfly.diagonal import Diagonal
from torch_butterfly.complex_utils import real2complex, Real2Complex, Complex2Real
from torch_butterfly.complex_utils impor... | 135 | 135 | 453 | 20 | 114 | skn123/butterfly | torch_butterfly/special.py | Python | fft | fft | 19 | 49 | 19 | 19 | 60a087b31a4fbe5f063d5e6bbe982a5c4d887f61 | bigcode/the-stack | train |
a963b3827cc655360afafc7b | train | function | def toeplitz(col, row=None, separate_diagonal=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs Toeplitz matrix
multiplication.
Parameters:
col: torch.Tensor of size (n, ). The first column of the Toeplitz matrix.
row: torch.Tensor of size (n, ). The fir... | def toeplitz(col, row=None, separate_diagonal=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs Toeplitz matrix
multiplication.
Parameters:
col: torch.Tensor of size (n, ). The first column of the Toeplitz matrix.
row: torch.Tensor of size (n, ). The first row of the Toeplitz matrix. If None, assume
row == ... | # Combine the diagonal with the last twiddle factor of b_fft
with torch.no_grad():
b_fft = diagonal_butterfly(b_fft, diag, diag_first=False, inplace=True)
# Combine the b_fft and b_ifft into one Butterfly (with nblocks=2).
b = butterfly_product(b_fft, b_ifft)
b.in_size = n
... | 123 | 123 | 411 | 18 | 105 | skn123/butterfly | torch_butterfly/special.py | Python | toeplitz | toeplitz | 304 | 342 | 304 | 304 | 1168f4f21edfd2b3efc9202d18f046fd42319075 | bigcode/the-stack | train |
1a0508b7c81d986737cd5cf0 | train | function | def wavelet_haar(n, with_perm=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the multilevel discrete
wavelet transform with the Haar wavelet.
Parameters:
n: size of the discrete wavelet transform. Must be a power of 2.
with_perm: whether to return bot... | def wavelet_haar(n, with_perm=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the multilevel discrete
wavelet transform with the Haar wavelet.
Parameters:
n: size of the discrete wavelet transform. Must be a power of 2.
with_perm: whether to return both the butterfly and the wavelet rearrangement perm... | )
return nn.Sequential(Real2Complex(), b1, Complex2Real(),
Real2Complex(), b2, Complex2Real())
else:
return nn.Sequential(Real2Complex(), b1, Complex2Real(),
Diagonal(diagonal_init=diag1[perm][br]),
... | 99 | 99 | 330 | 15 | 84 | skn123/butterfly | torch_butterfly/special.py | Python | wavelet_haar | wavelet_haar | 782 | 805 | 782 | 782 | 72981462b66ba9b0d543adcb94358ca6c9918317 | bigcode/the-stack | train |
e883c9f08e855e3e335d6832 | train | function | def fastfood(diag1: torch.Tensor, diag2: torch.Tensor, diag3: torch.Tensor,
permutation: torch.Tensor, normalized: bool = False,
increasing_stride: bool = True, separate_diagonal: bool = True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that performs Fastfood multiplication... | def fastfood(diag1: torch.Tensor, diag2: torch.Tensor, diag3: torch.Tensor,
permutation: torch.Tensor, normalized: bool = False,
increasing_stride: bool = True, separate_diagonal: bool = True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that performs Fastfood multiplication:
x -> Diag3 @ H @ Diag2 @ P @ H @ Diag1,
where H is the Hadamard matrix and P is a permutation matrix.
Parameters:
diag1: (n,), where n is a power of 2.
diag2: (n,)
diag3: (n,)
permutation... | return nn.Sequential(b_fft, DiagonalMultiplySum(col_f), b_ifft)
else:
return nn.Sequential(nn.Flatten(start_dim=-2), b_fft, DiagonalMultiplySum(col_f),
b_ifft, nn.Unflatten(-1, (n2, n1)))
def fastfood(diag1: torch.Tensor, diag2: torch.Tensor, diag3: torch.Tensor,
... | 114 | 115 | 384 | 54 | 60 | skn123/butterfly | torch_butterfly/special.py | Python | fastfood | fastfood | 684 | 711 | 684 | 686 | cdd2dad13dd60496ea69c4186a9554edc9c73f26 | bigcode/the-stack | train |
400d126cc7791cccb17d8c44 | train | function | def conv2d_circular_multichannel(n1: int, n2: int, weight: torch.Tensor,
flatten: bool=False) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs nn.Conv2d
with multiple in/out channels, with circular padding.
The output of nn.Conv2d must have t... | def conv2d_circular_multichannel(n1: int, n2: int, weight: torch.Tensor,
flatten: bool=False) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs nn.Conv2d
with multiple in/out channels, with circular padding.
The output of nn.Conv2d must have the same size as the input (i.e. kernel size must be 2k + 1,
and padding k for some integer k).
Parameters:
n1: size of the la... | 2.
n2: size of the iFFT on the second to last input dimension. Must be a power of 2.
br_first: which decomposition of iFFT. True corresponds to decimation-in-frequency.
False corresponds to decimation-in-time.
with_br_perm: whether to return both the butterfly and the bit rever... | 256 | 256 | 1,341 | 33 | 222 | skn123/butterfly | torch_butterfly/special.py | Python | conv2d_circular_multichannel | conv2d_circular_multichannel | 597 | 681 | 597 | 598 | 52c624be25e1e5c0bbe5c786495b6818e4829831 | bigcode/the-stack | train |
4fba1477fa8f22166c2ac0c3 | train | class | class DiagonalMultiplySum(nn.Module):
def __init__(self, diagonal_init):
"""
Parameters:
diagonal_init: (out_channels, in_channels, size)
"""
super().__init__()
self.diagonal = nn.Parameter(diagonal_init.detach().clone())
self.complex = self.diagonal.is_co... | class DiagonalMultiplySum(nn.Module):
| def __init__(self, diagonal_init):
"""
Parameters:
diagonal_init: (out_channels, in_channels, size)
"""
super().__init__()
self.diagonal = nn.Parameter(diagonal_init.detach().clone())
self.complex = self.diagonal.is_complex()
def forward(self, input):... | ([-1]), (0, n - kernel_size)).roll(-padding, dims=-1)
return circulant(col.squeeze(1).squeeze(0), separate_diagonal=separate_diagonal)
# We write this as an nn.Module just to use nn.Sequential
class DiagonalMultiplySum(nn.Module):
| 64 | 64 | 125 | 8 | 55 | skn123/butterfly | torch_butterfly/special.py | Python | DiagonalMultiplySum | DiagonalMultiplySum | 417 | 434 | 417 | 417 | 7954ca55225ecb2040cb4e983b30a5177cf550f1 | bigcode/the-stack | train |
85cdf09ea0a5963be24b9353 | train | function | def hadamard(n, normalized=False, increasing_stride=True) -> Butterfly:
""" Construct an nn.Module based on Butterfly that exactly performs the Hadamard transform.
Parameters:
n: size of the Hadamard transform. Must be a power of 2.
normalized: if True, corresponds to the orthogonal Hadamard tra... | def hadamard(n, normalized=False, increasing_stride=True) -> Butterfly:
| """ Construct an nn.Module based on Butterfly that exactly performs the Hadamard transform.
Parameters:
n: size of the Hadamard transform. Must be a power of 2.
normalized: if True, corresponds to the orthogonal Hadamard transform
(i.e. multiplied by 1/sqrt(n))
increa... | _size = m
b[2].out_size = n
else:
if not complex:
b[1].in_size = m
b[1].out_size = n
else:
b.in_size = m
b.out_size = n
return b
def hadamard(n, normalized=False, increasing_stride=True) -> Butterfly:
| 79 | 79 | 266 | 16 | 62 | skn123/butterfly | torch_butterfly/special.py | Python | hadamard | hadamard | 345 | 361 | 345 | 345 | 17c16c5aa4b28d4d395e021eb75764943d106db0 | bigcode/the-stack | train |
6222d5f3f0bb6de4d9811cf5 | train | function | def conv1d_circular_multichannel(n, weight) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs nn.Conv1d
with multiple in/out channels, with circular padding.
The output of nn.Conv1d must have the same size as the input (i.e. kernel size must be 2k + 1,
and padding k for s... | def conv1d_circular_multichannel(n, weight) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs nn.Conv1d
with multiple in/out channels, with circular padding.
The output of nn.Conv1d must have the same size as the input (i.e. kernel size must be 2k + 1,
and padding k for some integer k).
Parameters:
n: size of the inp... | 1) // 2
col = F.pad(weight.flip([-1]), (0, n - kernel_size)).roll(-padding, dims=-1)
return circulant(col.squeeze(1).squeeze(0), separate_diagonal=separate_diagonal)
# We write this as an nn.Module just to use nn.Sequential
class DiagonalMultiplySum(nn.Module):
def __init__(self, diagonal_init):
"... | 210 | 210 | 702 | 16 | 194 | skn123/butterfly | torch_butterfly/special.py | Python | conv1d_circular_multichannel | conv1d_circular_multichannel | 437 | 484 | 437 | 437 | 2d683bb01d5ba1a2241ee18cec613ce5842204a1 | bigcode/the-stack | train |
23c61aae546c0956d4895d58 | train | function | def dst(n: int, type: int = 2, normalized: bool = False) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the DST.
Parameters:
n: size of the DST. Must be a power of 2.
type: either 2 or 4. These are the only types supported. See scipy.fft.dst's notes.
no... | def dst(n: int, type: int = 2, normalized: bool = False) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the DST.
Parameters:
n: size of the DST. Must be a power of 2.
type: either 2 or 4. These are the only types supported. See scipy.fft.dst's notes.
normalized: if True, corresponds to the orthogonal DST (see scipy.fft.dst... | (perm[br]), Real2Complex(), b, Complex2Real())
else:
assert type == 3
b = ifft(n, normalized=normalized, br_first=False, with_br_perm=False)
postprocess_diag[0] /= 2.0
if normalized:
postprocess_diag[1:] /= math.sqrt(2)
else:
# We want iFFT with the sc... | 185 | 186 | 623 | 23 | 162 | skn123/butterfly | torch_butterfly/special.py | Python | dst | dst | 210 | 245 | 210 | 210 | b0e5b055a05ab705f02191931a677255dee27e0c | bigcode/the-stack | train |
ebc0519792dc34cc67441e0c | train | function | def ifft(n, normalized=False, br_first=True, with_br_perm=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the inverse FFT.
Parameters:
n: size of the iFFT. Must be a power of 2.
normalized: if True, corresponds to unitary iFFT (i.e. multiplied by 1/sqrt(n)... | def ifft(n, normalized=False, br_first=True, with_br_perm=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the inverse FFT.
Parameters:
n: size of the iFFT. Must be a power of 2.
normalized: if True, corresponds to unitary iFFT (i.e. multiplied by 1/sqrt(n), not 1/n)
br_first: which decomposition of iFFT. True corresponds to ... | .stack(factors, dim=0).unsqueeze(0).unsqueeze(0)
if not br_first:
twiddle = twiddle.flip([2])
b = ButterflyUnitary(n, n, bias=False, increasing_stride=br_first)
with torch.no_grad():
b.twiddle.copy_(twiddle)
if with_br_perm:
br_perm = FixedPermutation(bitreversal_permutation(n, p... | 140 | 140 | 467 | 21 | 118 | skn123/butterfly | torch_butterfly/special.py | Python | ifft | ifft | 90 | 122 | 90 | 90 | db3d8d85f814fb3a31bbb890a244804a8aada1ed | bigcode/the-stack | train |
feaf17f2607c77adc4b1a3c7 | train | function | def hadamard_diagonal(diagonals: torch.Tensor, normalized: bool = False,
increasing_stride: bool = True, separate_diagonal: bool = True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that performs multiplication by H D H D ... H D,
where H is the Hadamard matrix and D is a di... | def hadamard_diagonal(diagonals: torch.Tensor, normalized: bool = False,
increasing_stride: bool = True, separate_diagonal: bool = True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that performs multiplication by H D H D ... H D,
where H is the Hadamard matrix and D is a diagonal matrix
Parameters:
diagonals: (k, n), where k is the number of diagonal matrices and n is the dimension of the
Hadamard transform.
nor... | , 1, 1, 1, 2, 2).expand((1, 1, log_n, n // 2, 2, 2))
b = Butterfly(n, n, bias=False, increasing_stride=increasing_stride, init=twiddle)
return b
def hadamard_diagonal(diagonals: torch.Tensor, normalized: bool = False,
increasing_stride: bool = True, separate_diagonal: bool = True) -> nn.Mo... | 102 | 102 | 340 | 39 | 62 | skn123/butterfly | torch_butterfly/special.py | Python | hadamard_diagonal | hadamard_diagonal | 364 | 391 | 364 | 365 | aca6d7584f66b42c0d16af3cd368ad56730c4db6 | bigcode/the-stack | train |
92922b3e2fd58c819b7eec7c | train | function | def ifft_unitary(n, br_first=True, with_br_perm=True) -> nn.Module:
""" Construct an nn.Module based on ButterflyUnitary that exactly performs the iFFT.
Since it's unitary, it corresponds to normalized=True.
Parameters:
n: size of the iFFT. Must be a power of 2.
br_first: which decomposition... | def ifft_unitary(n, br_first=True, with_br_perm=True) -> nn.Module:
| """ Construct an nn.Module based on ButterflyUnitary that exactly performs the iFFT.
Since it's unitary, it corresponds to normalized=True.
Parameters:
n: size of the iFFT. Must be a power of 2.
br_first: which decomposition of iFFT. br_first=True corresponds to decimation-in-time.
... | by sqrt(n) by dividing each factor by n^(1/2 log_n) = sqrt(2)
if normalized:
twiddle /= math.sqrt(2)
else:
twiddle /= 2
b = Butterfly(n, n, bias=False, complex=True, increasing_stride=br_first, init=twiddle)
if with_br_perm:
br_perm = FixedPermutation(bitreversal_permutation(n, ... | 141 | 141 | 470 | 20 | 120 | skn123/butterfly | torch_butterfly/special.py | Python | ifft_unitary | ifft_unitary | 125 | 161 | 125 | 125 | 513dccb2ed8c19a57f17dc23587bbe653176da83 | bigcode/the-stack | train |
cf061c1efa05c1bf5227ce8f | train | function | def fft_unitary(n, br_first=True, with_br_perm=True) -> nn.Module:
""" Construct an nn.Module based on ButterflyUnitary that exactly performs the FFT.
Since it's unitary, it corresponds to normalized=True.
Parameters:
n: size of the FFT. Must be a power of 2.
br_first: which decomposition of... | def fft_unitary(n, br_first=True, with_br_perm=True) -> nn.Module:
| """ Construct an nn.Module based on ButterflyUnitary that exactly performs the FFT.
Since it's unitary, it corresponds to normalized=True.
Parameters:
n: size of the FFT. Must be a power of 2.
br_first: which decomposition of FFT. br_first=True corresponds to decimation-in-time.
... | flip([2])
# Divide the whole transform by sqrt(n) by dividing each factor by n^(1/2 log_n) = sqrt(2)
if normalized:
twiddle /= math.sqrt(2)
b = Butterfly(n, n, bias=False, complex=True, increasing_stride=br_first, init=twiddle)
if with_br_perm:
br_perm = FixedPermutation(bitreversal_perm... | 140 | 140 | 467 | 19 | 120 | skn123/butterfly | torch_butterfly/special.py | Python | fft_unitary | fft_unitary | 52 | 88 | 52 | 52 | e9acdea272a700084c5a5807a5d05319b3846411 | bigcode/the-stack | train |
8852bebdb9dd11b4f73f8eab | train | function | def dct(n: int, type: int = 2, normalized: bool = False) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs the DCT.
Parameters:
n: size of the DCT. Must be a power of 2.
type: either 2, 3, or 4. These are the only types supported. See scipy.fft.dct's notes.
... | def dct(n: int, type: int = 2, normalized: bool = False) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs the DCT.
Parameters:
n: size of the DCT. Must be a power of 2.
type: either 2, 3, or 4. These are the only types supported. See scipy.fft.dct's notes.
normalized: if True, corresponds to the orthogonal DCT (see scipy.ff... | the flip later.
chi = -angle / 2 - math.pi / 2
twiddle_factor = torch.stack([phi, alpha, psi, chi], dim=-1)
factors.append(twiddle_factor.repeat(n // size, 1))
twiddle = torch.stack(factors, dim=0).unsqueeze(0).unsqueeze(0)
if not br_first:
twiddle = twiddle.flip([2])
b ... | 202 | 202 | 676 | 24 | 177 | skn123/butterfly | torch_butterfly/special.py | Python | dct | dct | 164 | 207 | 164 | 164 | 244e4e853888d1eff5e1dff8c58900be1b093447 | bigcode/the-stack | train |
4dc5510870c933fe6b930c3b | train | function | def conv1d_circular_singlechannel(n, weight, separate_diagonal=True) -> nn.Module:
""" Construct an nn.Module based on Butterfly that exactly performs nn.Conv1d
with a single in-channel and single out-channel, with circular padding.
The output of nn.Conv1d must have the same size as the input (i.e. kernel s... | def conv1d_circular_singlechannel(n, weight, separate_diagonal=True) -> nn.Module:
| """ Construct an nn.Module based on Butterfly that exactly performs nn.Conv1d
with a single in-channel and single out-channel, with circular padding.
The output of nn.Conv1d must have the same size as the input (i.e. kernel size must be 2k + 1,
and padding k for some integer k).
Parameters:
... | modules = []
for i, diagonal in enumerate(diagonals.unbind()):
modules.append(Diagonal(diagonal_init=diagonal))
cur_increasing_stride = increasing_stride != (i % 2 == 1)
h = hadamard(n, normalized, cur_increasing_stride)
modules.append(h)
return nn... | 96 | 96 | 323 | 21 | 75 | skn123/butterfly | torch_butterfly/special.py | Python | conv1d_circular_singlechannel | conv1d_circular_singlechannel | 394 | 413 | 394 | 394 | 897fdc1b2cf84d8b73c297a216f83fcf977bc21b | bigcode/the-stack | train |
163073d4a0fb29506db76b42 | train | function | def ifft2d_unitary(n1: int, n2: int, br_first: bool = True,
with_br_perm: bool = True) -> nn.Module:
""" Construct an nn.Module based on ButterflyUnitary that exactly performs the 2D iFFT.
Corresponds to normalized=True.
Does not support flatten for now.
Parameters:
n1: size o... | def ifft2d_unitary(n1: int, n2: int, br_first: bool = True,
with_br_perm: bool = True) -> nn.Module:
| """ Construct an nn.Module based on ButterflyUnitary that exactly performs the 2D iFFT.
Corresponds to normalized=True.
Does not support flatten for now.
Parameters:
n1: size of the iFFT on the last input dimension. Must be a power of 2.
n2: size of the iFFT on the second to last input d... | =-2), b, br_perm,
nn.Unflatten(-1, (n2, n1))))
else:
return b if not flatten else nn.Sequential(nn.Flatten(start_dim=-2), b,
nn.Unflatten(-1, (n2, n1)))
def ifft2d_unitary(n1: int, n2: int, br_first: bool =... | 95 | 96 | 320 | 37 | 58 | skn123/butterfly | torch_butterfly/special.py | Python | ifft2d_unitary | ifft2d_unitary | 573 | 594 | 573 | 574 | 264b3012f6c1daab81fa52545d327aa7c97e2327 | bigcode/the-stack | train |
2b11eddd663150b54a742e23 | train | class | class QNetwork(BasePolicy):
"""
Action-Value (Q-Value) network for DQN
:param observation_space: Observation space
:param action_space: Action space
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activation function
:param normalize_images: Whethe... | class QNetwork(BasePolicy):
| """
Action-Value (Q-Value) network for DQN
:param observation_space: Observation space
:param action_space: Action space
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activation function
:param normalize_images: Whether to normalize images or not... | from typing import Any, Dict, List, Optional, Type
import gym
import torch as th
from torch import nn
from stable_baselines3.common.last_mlp import LastMLP
from stable_baselines3.common.policies import BasePolicy, register_policy
from stable_baselines3.common.torch_layers import (
BaseFeaturesExtractor,
Combi... | 107 | 164 | 547 | 6 | 100 | saodem74/Transfer-Learning-in-Reinforcement-Learning | stable_baselines3/dqn/policies.py | Python | QNetwork | QNetwork | 19 | 95 | 19 | 19 | 4fe8476383bab6a3704a70f32da3ba033b308cc1 | bigcode/the-stack | train |
351f89e155779e54e654fd86 | train | class | class CnnPolicy(DQNPolicy):
"""
Policy class for DQN when using images as input.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
... | class CnnPolicy(DQNPolicy):
| """
Policy class for DQN when using images as input.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activa... | _kwargs,
)
)
return data
def set_training_mode(self, mode: bool) -> None:
"""
Put the policy in either training or evaluation mode.
This affects certain modules, such as batch normalisation and dropout.
:param mode: if true, set to training mode, else s... | 103 | 103 | 345 | 8 | 94 | saodem74/Transfer-Learning-in-Reinforcement-Learning | stable_baselines3/dqn/policies.py | Python | CnnPolicy | CnnPolicy | 221 | 263 | 221 | 221 | d7893cb35cdd231dd819aff1c547d2c564c76e45 | bigcode/the-stack | train |
80a552f10a713a0a41d51373 | train | class | class DQNPolicy(BasePolicy):
"""
Policy class with Q-Value Net and target net for DQN
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.... | class DQNPolicy(BasePolicy):
| """
Policy class with Q-Value Net and target net for DQN
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Ac... | .q_net = LastMLP(q_net)
def forward(self, obs: th.Tensor, last = False) -> th.Tensor:
"""
Predict the q-values.
:param obs: Observation
:return: The estimated Q-Value for each action.
"""
return self.q_net(self.extract_features(obs), last)
def _predict(self, ob... | 256 | 256 | 959 | 7 | 248 | saodem74/Transfer-Learning-in-Reinforcement-Learning | stable_baselines3/dqn/policies.py | Python | DQNPolicy | DQNPolicy | 98 | 215 | 98 | 98 | 2f9890ab05fa72914958a35be024387105be46fc | bigcode/the-stack | train |
9a2beba78ee293af766c92b7 | train | class | class MultiInputPolicy(DQNPolicy):
"""
Policy class for DQN when using dict observations as input.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and va... | class MultiInputPolicy(DQNPolicy):
| """
Policy class for DQN when using dict observations as input.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation... | normalize_images: bool = True,
optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,
optimizer_kwargs: Optional[Dict[str, Any]] = None,
):
super(CnnPolicy, self).__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
... | 104 | 104 | 347 | 8 | 96 | saodem74/Transfer-Learning-in-Reinforcement-Learning | stable_baselines3/dqn/policies.py | Python | MultiInputPolicy | MultiInputPolicy | 266 | 308 | 266 | 266 | 1f02aaaaa563e4f85f0b16c0d1f8295b6c0a3d32 | bigcode/the-stack | train |
92022d58bf6bdde57dad1eab | train | class | class Command(BaseCommand):
help = 'Cleans RequestTrack objects'
def add_arguments(self, parser):
parser.add_argument(
'--type',
type=int,
help='1: last day & exception-added | 2: last day | 3: exception-added | 4: all',
)
def handle(self, *args, **kwarg... | class Command(BaseCommand):
| help = 'Cleans RequestTrack objects'
def add_arguments(self, parser):
parser.add_argument(
'--type',
type=int,
help='1: last day & exception-added | 2: last day | 3: exception-added | 4: all',
)
def handle(self, *args, **kwargs):
delete_type = kw... | from datetime import timedelta
from django.utils import timezone
from avishan.models import RequestTrack
from django.core.management.base import BaseCommand
class Command(BaseCommand):
| 34 | 64 | 166 | 5 | 28 | Afshari9978/django-avishan | avishan/management/commands/avishan_clean_request_tracks.py | Python | Command | Command | 9 | 32 | 9 | 9 | 7f716b583a6c4c651afe09d702a726819816c339 | bigcode/the-stack | train |
e52decad3b31fd6b0a975de5 | train | class | class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
- computeValueFromQValues
- computeActionFromQValues
- getQValue
- getAction
- update
Instance variables you have access to
- self.epsilon (exploration pro... | class QLearningAgent(ReinforcementAgent):
| """
Q-Learning Agent
Functions you should fill in:
- computeValueFromQValues
- computeActionFromQValues
- getQValue
- getAction
- update
Instance variables you have access to
- self.epsilon (exploration prob)
- self.alpha (learning rate)
... | # qlearningAgents.py
# ------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.be... | 200 | 256 | 858 | 9 | 190 | patrick-vieira/berkeleyRL3 | src/qlearningAgents.py | Python | QLearningAgent | QLearningAgent | 22 | 135 | 22 | 22 | 3880a6c5bc3b83dca052955358f64063aaa2bd9e | bigcode/the-stack | train |
572253398a383c00a0ff01f9 | train | class | class ApproximateQAgent(PacmanQAgent):
"""
ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is.
"""
def __init__(self, extractor='IdentityExtractor', **args):
self.featExtractor = util.lo... | class ApproximateQAgent(PacmanQAgent):
| """
ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is.
"""
def __init__(self, extractor='IdentityExtractor', **args):
self.featExtractor = util.lookup(extractor, globals())()
Pa... | '] = numTraining
self.index = 0 # This is always Pacman
QLearningAgent.__init__(self, **args)
def getAction(self, state):
"""
Simply calls the getAction method of QLearningAgent and then
informs parent of action for Pacman. Do not change or remove this
method.
... | 111 | 111 | 370 | 11 | 99 | patrick-vieira/berkeleyRL3 | src/qlearningAgents.py | Python | ApproximateQAgent | ApproximateQAgent | 170 | 221 | 170 | 170 | 8c9e77a7b3d4ec5ab9ae59ed0e99a8b35ca407bc | bigcode/the-stack | train |
70cc08dce776c3d7e5ff4ca0 | train | class | class PacmanQAgent(QLearningAgent):
"Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to chang... | class PacmanQAgent(QLearningAgent):
| "Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to change the exploration rate, try:
... | next_value = self.getValue(nextState)
self.values[(state, action)] = (1 - alpha) * qvalue + alpha * (reward + discount * next_value)
def getPolicy(self, state):
return self.computeActionFromQValues(state)
def getValue(self, state):
return self.computeValueFromQValues(state)
class Pac... | 83 | 83 | 279 | 10 | 73 | patrick-vieira/berkeleyRL3 | src/qlearningAgents.py | Python | PacmanQAgent | PacmanQAgent | 138 | 167 | 138 | 138 | ccde3491af1ea1837053fe201b33a881f63afd47 | bigcode/the-stack | train |
f8eb466f08675bc37e20c041 | train | class | class EquipmentChassisFsm(ManagedObject):
"""This is EquipmentChassisFsm class."""
consts = EquipmentChassisFsmConsts()
naming_props = set([])
mo_meta = MoMeta("EquipmentChassisFsm", "equipmentChassisFsm", "fsm", VersionMeta.Version211a, "OutputOnly", 0xf, [], [""], [u'equipmentChassis'], [u'equipment... | class EquipmentChassisFsm(ManagedObject):
| """This is EquipmentChassisFsm class."""
consts = EquipmentChassisFsmConsts()
naming_props = set([])
mo_meta = MoMeta("EquipmentChassisFsm", "equipmentChassisFsm", "fsm", VersionMeta.Version211a, "OutputOnly", 0xf, [], [""], [u'equipmentChassis'], [u'equipmentChassisFsmStage'], [None])
prop_meta ... | _CHANNEL = "ERR-set-port-channel"
RMT_ERR_CODE_ERR_STORE_PRE_LOGIN_BANNER_MSG = "ERR-store-pre-login-banner-msg"
RMT_ERR_CODE_ERR_TACACS_ENABLE_ERROR = "ERR-tacacs-enable-error"
RMT_ERR_CODE_ERR_TACACS_GLOBAL_SET_ERROR = "ERR-tacacs-global-set-error"
RMT_ERR_CODE_ERR_TACACS_GROUP_SET_ERROR = "ERR-tacacs... | 256 | 256 | 2,635 | 10 | 246 | anoop1984/python_sdk | ucsmsdk/mometa/equipment/EquipmentChassisFsm.py | Python | EquipmentChassisFsm | EquipmentChassisFsm | 155 | 212 | 155 | 155 | 49651242d2ab7e45d111b5ed23f183730e845235 | bigcode/the-stack | train |
07c88ae01edb98e3b584764c | train | class | class EquipmentChassisFsmConsts():
COMPLETION_TIME_ = ""
CURRENT_FSM_DYNAMIC_REALLOCATION = "DynamicReallocation"
CURRENT_FSM_OOB_STORAGE_ADMIN_CFG = "OobStorageAdminCfg"
CURRENT_FSM_POWER_CAP = "PowerCap"
CURRENT_FSM_PSU_POLICY_CONFIG = "PsuPolicyConfig"
CURRENT_FSM_REMOVE_CHASSIS = "RemoveChas... | class EquipmentChassisFsmConsts():
| COMPLETION_TIME_ = ""
CURRENT_FSM_DYNAMIC_REALLOCATION = "DynamicReallocation"
CURRENT_FSM_OOB_STORAGE_ADMIN_CFG = "OobStorageAdminCfg"
CURRENT_FSM_POWER_CAP = "PowerCap"
CURRENT_FSM_PSU_POLICY_CONFIG = "PsuPolicyConfig"
CURRENT_FSM_REMOVE_CHASSIS = "RemoveChassis"
CURRENT_FSM_NOP = "nop"
... | """This module contains the general information for EquipmentChassisFsm ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class EquipmentChassisFsmConsts():
| 62 | 256 | 2,715 | 8 | 53 | anoop1984/python_sdk | ucsmsdk/mometa/equipment/EquipmentChassisFsm.py | Python | EquipmentChassisFsmConsts | EquipmentChassisFsmConsts | 9 | 152 | 9 | 9 | 10bcebc8a8cbd3636286eba67abde500f05ae9d7 | bigcode/the-stack | train |
c3a190f1f1e92b70010a789e | train | class | class SSDMobileNetV2KerasFeatureExtractor(
ssd_meta_arch.SSDKerasFeatureExtractor):
"""SSD Feature Extractor using MobilenetV2 features."""
def __init__(self,
is_training,
depth_multiplier,
min_depth,
pad_to_multiple,
conv_hyperparams,
... | class SSDMobileNetV2KerasFeatureExtractor(
ssd_meta_arch.SSDKerasFeatureExtractor):
| """SSD Feature Extractor using MobilenetV2 features."""
def __init__(self,
is_training,
depth_multiplier,
min_depth,
pad_to_multiple,
conv_hyperparams,
freeze_batchnorm,
inplace_batchnorm_update,
... | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 226 | 256 | 1,269 | 22 | 203 | dav1nci/models | research/object_detection/models/ssd_mobilenet_v2_keras_feature_extractor.py | Python | SSDMobileNetV2KerasFeatureExtractor | SSDMobileNetV2KerasFeatureExtractor | 27 | 163 | 27 | 28 | 7298249ccdcf1eb101ba672d3ba063d9f25a28de | bigcode/the-stack | train |
f0dce76550f28db680443ea6 | train | function | def run_cli():
parser = argparse.ArgumentParser(
prog="Nonvex",
conflict_handler="resolve",
formatter_class=CustomHelpFormatter,
)
subparsers = parser.add_subparsers(dest="command", required=True)
def add_subparser(fn, name=None):
description, _ = _parse_doc(fn)... | def run_cli():
| parser = argparse.ArgumentParser(
prog="Nonvex",
conflict_handler="resolve",
formatter_class=CustomHelpFormatter,
)
subparsers = parser.add_subparsers(dest="command", required=True)
def add_subparser(fn, name=None):
description, _ = _parse_doc(fn)
subpar... | import argparse
from inspect import signature
from hermes.typeo.typeo import CustomHelpFormatter, _parse_doc, make_parser
def run_cli():
| 31 | 99 | 332 | 4 | 26 | alecgunny/nonvex | nonvex/__init__.py | Python | run_cli | run_cli | 7 | 58 | 7 | 7 | ec82cc4e900cfc36f5075bac6a80fab2bb644900 | bigcode/the-stack | train |
e55abd694a5d4c1d8dd655e5 | train | function | @blueprint.route('/user_login',methods=['POST'])
def user_login_post():
username = request.form.get('username','0')
password = request.form.get('password','0')
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
login_user(user,True)
re... | @blueprint.route('/user_login',methods=['POST'])
def user_login_post():
| username = request.form.get('username','0')
password = request.form.get('password','0')
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
login_user(user,True)
return redirect(url_for(request.args.get('next')) or url_for('public.home'... | url_for('public.home'))
except Exception as e:
# logger.error(e)
executor.submit(send_email,f'500错误{e}')
flash(f'登录错误:{e}')
abort(401)
@blueprint.route('/user_login',methods=['POST'])
def user_login_post():
| 63 | 64 | 114 | 17 | 46 | anngle/mall | mall/auth/views.py | Python | user_login_post | user_login_post | 93 | 104 | 93 | 94 | c7d92fb6e79a656618ceab24d356c2a33b386a7e | bigcode/the-stack | train |
0c62bf03ce9fe3845229b885 | train | function | @blueprint.before_app_request
def before_request():
if current_user.is_authenticated:
current_user.ping()
| @blueprint.before_app_request
def before_request():
| if current_user.is_authenticated:
current_user.ping()
| next'))
@blueprint.route('/logout/')
@login_required
def logout():
"""Logout."""
logout_user()
flash('您已退出.', 'info')
return redirect(url_for('public.home'))
#每次登陆更新最后访问时间
@blueprint.before_app_request
def before_request():
| 64 | 64 | 24 | 11 | 52 | anngle/mall | mall/auth/views.py | Python | before_request | before_request | 126 | 129 | 126 | 127 | fc4b86787efb639f043b26137f96d9b96031201c | bigcode/the-stack | train |
8b4b4fd53a7b2170480b0422 | train | function | @blueprint.route('/autologin/<string:name>')
@blueprint.route('/autologin')
@oauth(scope='snsapi_base')
def autologin(name=''):
try:
if name:
user = User.query.filter_by(username=name).first()
login_user(user,True) if user else abort(404)
return redirect(request.args.get(... | @blueprint.route('/autologin/<string:name>')
@blueprint.route('/autologin')
@oauth(scope='snsapi_base')
def autologin(name=''):
| try:
if name:
user = User.query.filter_by(username=name).first()
login_user(user,True) if user else abort(404)
return redirect(request.args.get('next') or url_for('public.home'))
wechat_id = session.get('wechat_user_id','')
if wechat_id:
user ... | wechat_id=wechat_id,
)
login_user(user,True)
return user
else:
autoregister()
@blueprint.route('/autologin/<string:name>')
@blueprint.route('/autologin')
@oauth(scope='snsapi_base')
def autologin(name=''):
| 64 | 64 | 205 | 36 | 28 | anngle/mall | mall/auth/views.py | Python | autologin | autologin | 61 | 87 | 61 | 64 | 77c1cd9477682c059d14caaed71bfa665630a089 | bigcode/the-stack | train |
8dfa6bf37822039b1a876790 | train | function | @blueprint.route('/logout/')
@login_required
def logout():
"""Logout."""
logout_user()
flash('您已退出.', 'info')
return redirect(url_for('public.home'))
| @blueprint.route('/logout/')
@login_required
def logout():
| """Logout."""
logout_user()
flash('您已退出.', 'info')
return redirect(url_for('public.home'))
| flash('信息输入错误,没有该用户。')
return redirect(url_for('.user_login',next=request.endpoint))
@blueprint.route('/user_login')
@templated()
def user_login():
return dict(next=request.args.get('next'))
@blueprint.route('/logout/')
@login_required
def logout():
| 63 | 64 | 40 | 13 | 50 | anngle/mall | mall/auth/views.py | Python | logout | logout | 116 | 122 | 116 | 118 | 76602c05882f120adb7420535e3296358c2252ee | bigcode/the-stack | train |
9be9daacef7674a83a2bfeb4 | train | function | @blueprint.route('/user_login')
@templated()
def user_login():
return dict(next=request.args.get('next'))
| @blueprint.route('/user_login')
@templated()
def user_login():
| return dict(next=request.args.get('next'))
| True)
return redirect(url_for(request.args.get('next')) or url_for('public.home'))
else:
flash('信息输入错误,没有该用户。')
return redirect(url_for('.user_login',next=request.endpoint))
@blueprint.route('/user_login')
@templated()
def user_login():
| 63 | 64 | 26 | 16 | 47 | anngle/mall | mall/auth/views.py | Python | user_login | user_login | 108 | 111 | 108 | 110 | 1e5cc583dce4a6c508397b4b489a80199ce5de78 | bigcode/the-stack | train |
3761880bf5d872c3f28966cd | train | function | def autoregister(wechat_id=''):
choice_str = 'ABCDEFGHJKLNMPQRSTUVWSXYZ'
username_str = ''
password_str = ''
str_time = time.time()
username_str = 'AU'
username_str += str(int(int(str_time)*1.301))
for i in range(2):
username_str += random.choice(choice_str)
for i in range... | def autoregister(wechat_id=''):
| choice_str = 'ABCDEFGHJKLNMPQRSTUVWSXYZ'
username_str = ''
password_str = ''
str_time = time.time()
username_str = 'AU'
username_str += str(int(int(str_time)*1.301))
for i in range(2):
username_str += random.choice(choice_str)
for i in range(6):
password_str += random.c... | login_required,login_user,current_user,logout_user
from mall.utils import send_email
from log import logger
from mall.extensions import executor
from mall.user.models import User
from . import blueprint
from mall.utils import templated
#自动注册
# @blueprint.route('/autoregister')
def autoregister(wechat_id=''):
... | 73 | 73 | 245 | 10 | 63 | anngle/mall | mall/auth/views.py | Python | autoregister | autoregister | 20 | 58 | 20 | 21 | 31070ba4394d30e27d10134d8f6a4f0adb11358e | bigcode/the-stack | train |
1c60581b3a6d049226356335 | train | function | def zigzag(input):
#initializing the variables
#----------------------------------
h = 0
v = 0
vmin = 0
hmin = 0
vmax = input.shape[0]
hmax = input.shape[1]
#print(vmax ,hmax )
i = 0
output = np.zeros(( vmax * hmax))
#----------------------------------
while ((v < vmax) and (h < hm... | def zigzag(input):
#initializing the variables
#----------------------------------
| h = 0
v = 0
vmin = 0
hmin = 0
vmax = input.shape[0]
hmax = input.shape[1]
#print(vmax ,hmax )
i = 0
output = np.zeros(( vmax * hmax))
#----------------------------------
while ((v < vmax) and (h < hmax)):
if ((h + v) % 2) == 0: # going up
if (v == vmin):
... | # Zigzag scan of a matrix
# Argument is a two-dimensional matrix of any size,
# not strictly a square one.
# Function returns a 1-by-(m*n) array,
# where m and n are sizes of an input matrix,
# consisting of its items scanned by a zigzag method.
#
# Matlab Code:
# Alexey S. Sokolov a.k.a. nICKEL, Moscow, Russia... | 123 | 171 | 571 | 17 | 105 | MasonEdgar/DCT-Image-Steganography | zigzag.py | Python | zigzag | zigzag | 15 | 98 | 15 | 17 | e69db101f305de820de2fe33acd4cc9796ebf3c2 | bigcode/the-stack | train |
bcc26bcf99f2409e380f7e0c | train | function | def inverse_zigzag(input, vmax, hmax):
#print input.shape
# initializing the variables
#----------------------------------
h = 0
v = 0
vmin = 0
hmin = 0
output = np.zeros((vmax, hmax))
i = 0
#----------------------------------
while ((v < vmax) and (h < hmax)):
#print ('v:',v,', h:'... | def inverse_zigzag(input, vmax, hmax):
#print input.shape
# initializing the variables
#----------------------------------
| h = 0
v = 0
vmin = 0
hmin = 0
output = np.zeros((vmax, hmax))
i = 0
#----------------------------------
while ((v < vmax) and (h < hmax)):
#print ('v:',v,', h:',h,', i:',i)
if ((h + v) % 2) == 0: # going up
if (v == vmin):
#print(1)
output[v, h] = input[i] ... | #print(7)
output[i] = input[v, h]
break
#print ('v:',v,', h:',h,', i:',i)
return output
# Inverse zigzag scan of a matrix
# Arguments are: a 1-by-m*n array,
# where m & n are vertical & horizontal sizes of an output matrix.
# Function returns a two-dimensional matrix of defined sizes,
# cons... | 165 | 165 | 553 | 28 | 136 | MasonEdgar/DCT-Image-Steganography | zigzag.py | Python | inverse_zigzag | inverse_zigzag | 115 | 194 | 115 | 120 | 6c967c855a61fbbb819ec1b5e450eb731a913305 | bigcode/the-stack | train |
d0366bba5759d3d99e0168bc | train | function | def run_tests():
doctest.testmod(verbose=True)
| def run_tests():
| doctest.testmod(verbose=True)
| >>> fizzbuzz(7)
7
>>> fizzbuzz(10)
Buzz
>>> fizzbuzz(12)
Fizz
>>> fizzbuzz(30)
FizzBuzz
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
| 64 | 64 | 12 | 4 | 59 | JBurns7/p02.1 | fizzbuzz.py | Python | run_tests | run_tests | 29 | 30 | 29 | 29 | 3103366e752a16deee51ad705994fefc39bc2fda | bigcode/the-stack | train |
d549858f4e14862e492288ba | train | function | def fizzbuzz(n):
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
| def fizzbuzz(n):
| if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
| Buzz
>>> fizzbuzz(12)
Fizz
>>> fizzbuzz(30)
FizzBuzz
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this function
def fizzbuzz(n):
| 64 | 64 | 66 | 5 | 58 | JBurns7/p02.1 | fizzbuzz.py | Python | fizzbuzz | fizzbuzz | 34 | 46 | 34 | 35 | 0f2e55423ba27d2855dcf77f642f7724f01fdb6f | bigcode/the-stack | train |
41694b693fc9b59c16d0d30c | train | function | def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards
| def make_hit(card, cards, deck):
| """
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards
| make_deal(cards=[]):
"""
Deals 2 cards to player and 2 cards to dealer
"""
if cards:
return cards
for _ in range(4):
cards.append(random.randint(2, 11))
return cards
def make_hit(card, cards, deck):
| 64 | 64 | 41 | 9 | 54 | House-Rulez/black_jack | notebooks/make_test_data.py | Python | make_hit | make_hit | 34 | 41 | 34 | 34 | d891a1c3707b2bd9a05eee6bfbd79d5bae94ca4a | bigcode/the-stack | train |
a885e460293558f15f166ec2 | train | function | def make_deck(hands):
"""
Creates a 52 card deck
"""
points = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cards = []
for point in points:
for _ in range(4):
if point not in hands:
cards.append(point)
else:
hands.remove(point)
return cards
| def make_deck(hands):
| """
Creates a 52 card deck
"""
points = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cards = []
for point in points:
for _ in range(4):
if point not in hands:
cards.append(point)
else:
hands.remove(point)
return cards
| import csv
import random
def make_deck(hands):
| 13 | 64 | 103 | 7 | 5 | House-Rulez/black_jack | notebooks/make_test_data.py | Python | make_deck | make_deck | 5 | 18 | 5 | 5 | 3752fabe9a0ff0ccfc27c7fee8b1ae0b2d91febc | bigcode/the-stack | train |
2cf5147f17bed2e3b23fefcc | train | function | def make_file(contents, filename):
"""
Writes deck and hand to csv files for graphing
"""
with open(filename, mode="w") as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
if filename == 'notebooks/deck.csv':
csv_writer.writerow(['Points'])
... | def make_file(contents, filename):
| """
Writes deck and hand to csv files for graphing
"""
with open(filename, mode="w") as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
if filename == 'notebooks/deck.csv':
csv_writer.writerow(['Points'])
elif filename == 'notebooks/hand.c... | ):
cards.append(random.randint(2, 11))
return cards
def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards
def make_file(contents, filename):
| 64 | 64 | 110 | 7 | 56 | House-Rulez/black_jack | notebooks/make_test_data.py | Python | make_file | make_file | 44 | 58 | 44 | 44 | b0fee04c4d8560fb595c453b0ed2f713ad1a4368 | bigcode/the-stack | train |
d60f2b067dc1ce54806026f7 | train | function | def make_deal(cards=[]):
"""
Deals 2 cards to player and 2 cards to dealer
"""
if cards:
return cards
for _ in range(4):
cards.append(random.randint(2, 11))
return cards
| def make_deal(cards=[]):
| """
Deals 2 cards to player and 2 cards to dealer
"""
if cards:
return cards
for _ in range(4):
cards.append(random.randint(2, 11))
return cards
| 10, 10, 10, 10, 11]
cards = []
for point in points:
for _ in range(4):
if point not in hands:
cards.append(point)
else:
hands.remove(point)
return cards
def make_deal(cards=[]):
| 64 | 64 | 56 | 7 | 56 | House-Rulez/black_jack | notebooks/make_test_data.py | Python | make_deal | make_deal | 21 | 31 | 21 | 21 | 8ae5c95c0c7914177ef213281730803a5e0ab310 | bigcode/the-stack | train |
b3f45ca4765b8aa56f8ad9c5 | train | function | def pattern_pos(pattern, chromosome):
result = ""
pattern_len = len(pattern)
for i in range(len(chromosome) - pattern_len + 1):
if chromosome[i:i + pattern_len] == pattern:
if result != "":
result += " "
result += str(i)
return result
| def pattern_pos(pattern, chromosome):
| result = ""
pattern_len = len(pattern)
for i in range(len(chromosome) - pattern_len + 1):
if chromosome[i:i + pattern_len] == pattern:
if result != "":
result += " "
result += str(i)
return result
| import sys
from fs_helpers import *
def show_usage():
print("Usage:")
print("python pattern_count.py <dataset_file>")
def pattern_pos(pattern, chromosome):
| 35 | 64 | 67 | 7 | 29 | uskovboris/coursera_bioinformatics | pattern_pos.py | Python | pattern_pos | pattern_pos | 10 | 18 | 10 | 10 | c09275be0d45c786e0d69b2998a7a140a396cca5 | bigcode/the-stack | train |
5312004e2722b1feee442c75 | train | function | def show_usage():
print("Usage:")
print("python pattern_count.py <dataset_file>")
| def show_usage():
| print("Usage:")
print("python pattern_count.py <dataset_file>")
| import sys
from fs_helpers import *
def show_usage():
| 12 | 64 | 20 | 4 | 8 | uskovboris/coursera_bioinformatics | pattern_pos.py | Python | show_usage | show_usage | 5 | 7 | 5 | 5 | 180e3dec09562e38e09ee74132d8f0970bdbab15 | bigcode/the-stack | train |
f4d29ec783af62d9bc71460e | train | function | def main():
if len(sys.argv) != 2:
dataset_file = input("Dataset file:")
else:
dataset_file = sys.argv[1]
dataset = read_lines(dataset_file)
if len(dataset) != 2:
print('Dataset should contains 2 lines')
sys.exit(1)
chromosome = dataset[1].strip()
pattern = dat... | def main():
| if len(sys.argv) != 2:
dataset_file = input("Dataset file:")
else:
dataset_file = sys.argv[1]
dataset = read_lines(dataset_file)
if len(dataset) != 2:
print('Dataset should contains 2 lines')
sys.exit(1)
chromosome = dataset[1].strip()
pattern = dataset[0].stri... | AGTGCATAGAGGAAGCGAGCAAAGGTGGTTTCTTTCGCTTTATCCAGCGCGTTAACCACGTTCTGTGCCGACTTT"))
assert("0 2 4" == pattern_pos("ATA", "ATATATA"))
def main():
| 63 | 64 | 142 | 3 | 60 | uskovboris/coursera_bioinformatics | pattern_pos.py | Python | main | main | 28 | 49 | 28 | 28 | 9ecb1137edd052b839a0f235cfe3425682d141e3 | bigcode/the-stack | train |
207052e030000a7f3989d251 | train | function | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--subsystem-test", help="deploy in subsystem mode", action="store_true")
deploy_options = deployment_options.load_deployment_options(parser)
utils.set_profile(deploy_options.target, deploy_options.profile)
dst_file = os.path.join... | def main():
| parser = argparse.ArgumentParser()
parser.add_argument("--subsystem-test", help="deploy in subsystem mode", action="store_true")
deploy_options = deployment_options.load_deployment_options(parser)
utils.set_profile(deploy_options.target, deploy_options.profile)
dst_file = os.path.join(os.getcwd(),... | import argparse
import os
import utils
import deployment_options
UI_REPOSITORY = "https://github.com/openshift-metal3/facet"
log = utils.get_logger('deploy_ui')
def main():
| 43 | 139 | 464 | 3 | 40 | RazRegev/assisted-service | tools/deploy_ui.py | Python | main | main | 11 | 59 | 11 | 12 | ce74fb91e42c6682bd2bb77ba3a5f8de71f96e05 | bigcode/the-stack | train |
2b33e9b0e66d0f665723dbdd | train | class | class QNet_duelingdqn(BaseQNet):
def __init__(self, dim_state, dim_action, dim_hidden=64, activation=nn.LeakyReLU):
super().__init__(dim_state, dim_action, dim_hidden)
self.advantage = nn.Sequential(nn.Linear(self.dim_state, self.dim_hidden),
activation(),
... | class QNet_duelingdqn(BaseQNet):
| def __init__(self, dim_state, dim_action, dim_hidden=64, activation=nn.LeakyReLU):
super().__init__(dim_state, dim_action, dim_hidden)
self.advantage = nn.Sequential(nn.Linear(self.dim_state, self.dim_hidden),
activation(),
... | import torch.nn as nn
from models.BaseQNet import BaseQNet
def init_weight(m):
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight)
nn.init.constant_(m.bias, 0.0)
class QNet_duelingdqn(BaseQNet):
| 63 | 109 | 364 | 11 | 52 | victorkich/MA-GRID | models/QNet_duelingdqn.py | Python | QNet_duelingdqn | QNet_duelingdqn | 11 | 48 | 11 | 11 | 6e72d0c0dc2e3329770f102383972e4af4cab426 | bigcode/the-stack | train |
67279f81434da2e5ef60c665 | train | function | def init_weight(m):
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight)
nn.init.constant_(m.bias, 0.0)
| def init_weight(m):
| if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight)
nn.init.constant_(m.bias, 0.0)
| import torch.nn as nn
from models.BaseQNet import BaseQNet
def init_weight(m):
| 21 | 64 | 36 | 5 | 15 | victorkich/MA-GRID | models/QNet_duelingdqn.py | Python | init_weight | init_weight | 5 | 8 | 5 | 5 | 66cc175aac33584853dbb05a8f1742b8e66d41bc | bigcode/the-stack | train |
19979f6e4dcb3b124b97648e | train | class | class PosePipePanel(Panel):
bl_label = "PosePipe - Camera MoCap"
bl_category = "PosePipe"
bl_idname = "VIEW3D_PT_Pose"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
def draw(self, context):
settings = context.scene.settings
layout = self.layout
box = layout.... | class PosePipePanel(Panel):
| bl_label = "PosePipe - Camera MoCap"
bl_category = "PosePipe"
bl_idname = "VIEW3D_PT_Pose"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
def draw(self, context):
settings = context.scene.settings
layout = self.layout
box = layout.box()
column_flow = ... | 17 left pinky', '18 right pinky', '19 left index',
'20 right index', '21 left thumb', '22 right thumb']
for tracker in hide_trackers:
bpy.data.objects[tracker].hide_set(True)
face_trackers = ['01 left eye (inner)', '02 left eye', '03 left eye (outer)',
... | 148 | 148 | 496 | 7 | 141 | SpectralVectors/PosePipe | PosePipe.py | Python | PosePipePanel | PosePipePanel | 1,235 | 1,283 | 1,235 | 1,235 | 36a0d6c99cffd7f60a235bce429c0988a02e3e38 | bigcode/the-stack | train |
ebd7733ff6a5b4649f661713 | train | class | class SkeletonBuilder(bpy.types.Operator):
"""Builds an armature to use with the mocap data"""
bl_idname = "pose.skeleton_builder"
bl_label = "Skeleton Builder"
def execute(self, context):
settings = bpy.context.scene.settings
bpy.ops.object.armature_add(radius=0.1)
PosePipe_... | class SkeletonBuilder(bpy.types.Operator):
| """Builds an armature to use with the mocap data"""
bl_idname = "pose.skeleton_builder"
bl_label = "Skeleton Builder"
def execute(self, context):
settings = bpy.context.scene.settings
bpy.ops.object.armature_add(radius=0.1)
PosePipe_BodyBones = bpy.context.object
Pose... | body_tracking: bpy.props.BoolProperty(default=True)
camera_number: bpy.props.IntProperty(default=0,
soft_min=0,
soft_max=10,
description="If you have more than one camera, you can choo... | 256 | 256 | 11,525 | 8 | 248 | SpectralVectors/PosePipe | PosePipe.py | Python | SkeletonBuilder | SkeletonBuilder | 543 | 1,233 | 543 | 543 | 16a9f7a49ea329958ca7836bb59ae30f02c19e27 | bigcode/the-stack | train |
90de0749dbaaa14e26975ec1 | train | function | def run_full(file_path):
try:
import cv2
import mediapipe as mp
except Exception as e:
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
install()
import cv2
import mediapipe as mp
settings = bpy.context.scene.settings
mp_drawing = mp.solutions.... | def run_full(file_path):
| try:
import cv2
import mediapipe as mp
except Exception as e:
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
install()
import cv2
import mediapipe as mp
settings = bpy.context.scene.settings
mp_drawing = mp.solutions.drawing_utils
mp_holi... | :
if not len(bpy.context.scene.objects["Face"].children) == 0:
bpy.data.objects[c.name].select_set(True)
bpy.ops.object.delete()
bpy.data.objects["Face"].select_set(True)
bpy.ops.object.delete()
def hands_delete():
""" Deletes all objects associated with ... | 256 | 256 | 1,821 | 6 | 250 | SpectralVectors/PosePipe | PosePipe.py | Python | run_full | run_full | 266 | 441 | 266 | 266 | 06480b0683236e81b0c9c81be20da63e9e6f0459 | bigcode/the-stack | train |
5faf3f4a85962907c31343dc | train | function | def install():
""" Install MediaPipe and dependencies behind the scenes """
import subprocess
import sys
subprocess.check_call([
sys.executable,
"-m", "ensurepip"])
subprocess.check_call([
sys.executable,
"-m", "pip", "install", "--upgrade", "pip"])
subproces... | def install():
| """ Install MediaPipe and dependencies behind the scenes """
import subprocess
import sys
subprocess.check_call([
sys.executable,
"-m", "ensurepip"])
subprocess.check_call([
sys.executable,
"-m", "pip", "install", "--upgrade", "pip"])
subprocess.check_call([
... | left thumb",
"22 right thumb",
"23 left hip",
"24 right hip",
"25 left knee",
"26 right knee",
"27 left ankle",
"28 right ankle",
"29 left heel",
"30 right heel",
"31 left foot index",
"32 right foot index",
]
def install():
| 64 | 64 | 177 | 3 | 61 | SpectralVectors/PosePipe | PosePipe.py | Python | install | install | 65 | 88 | 65 | 65 | c63f19a11c83cd6a8b23336a3a349f1d2c0de5b4 | bigcode/the-stack | train |
a9c67a85c41042fccbc05976 | train | function | def face_delete():
""" Deletes all objects associated with face capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Face" in scene_objects:
for c in bpy.context.scene.objects["Face"].children:
if not len(bpy.context... | def face_delete():
| """ Deletes all objects associated with face capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Face" in scene_objects:
for c in bpy.context.scene.objects["Face"].children:
if not len(bpy.context.scene.objects["Fac... | .scene.objects["Body"].children:
if not len(bpy.context.scene.objects["Body"].children) == 0:
bpy.data.objects[c.name].select_set(True)
bpy.ops.object.delete()
bpy.data.objects["Body"].select_set(True)
bpy.ops.object.delete()
def face_delete():
| 64 | 64 | 114 | 4 | 60 | SpectralVectors/PosePipe | PosePipe.py | Python | face_delete | face_delete | 233 | 244 | 233 | 233 | 00a5ccdced5bb6bd6ce9dc5ebc1d3f078d033146 | bigcode/the-stack | train |
e2c2854786da8c256df6b00d | train | class | class RunFileSelector(Operator, ImportHelper):
bl_idname = "something.identifier_selector"
bl_label = "Select Video File"
filename_ext = ""
def execute(self, context):
file_dir = self.properties.filepath
run_full(file_dir)
return{'FINISHED'}
| class RunFileSelector(Operator, ImportHelper):
| bl_idname = "something.identifier_selector"
bl_label = "Select Video File"
filename_ext = ""
def execute(self, context):
file_dir = self.properties.filepath
run_full(file_dir)
return{'FINISHED'}
|
scn = context.scene
col = layout.column()
row = col.row(align=True)
row.prop(scn.settings, 'file_path', text='directory:')
row.operator("something.identifier_selector", icon="FILE_FOLDER", text="")
class RunFileSelector(Operator, ImportHelper):
| 63 | 64 | 62 | 10 | 54 | SpectralVectors/PosePipe | PosePipe.py | Python | RunFileSelector | RunFileSelector | 490 | 498 | 490 | 490 | 421dd583b97b6b8c48741bebc8b0b73be4ffd676 | bigcode/the-stack | train |
4046c4b5049e070410e0dc84 | train | function | def body_setup():
""" Setup tracking boxes for body tracking """
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.color_type = 'OBJECT'
scene_objects = [n for n in ... | def body_setup():
| """ Setup tracking boxes for body tracking """
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
if space.type == 'VIEW_3D':
space.shading.color_type = 'OBJECT'
scene_objects = [n for n in bpy.context.scene.... | ender 2.93\\2.93\\python\\lib",
"opencv-python"])
subprocess.check_call([
sys.executable,
"-m", "pip", "install",
"--target=C:\\Program Files\\Blender Foundation\\Blender 2.93\\2.93\\python\\lib",
"mediapipe"])
def body_setup():
| 79 | 80 | 267 | 4 | 75 | SpectralVectors/PosePipe | PosePipe.py | Python | body_setup | body_setup | 91 | 125 | 91 | 91 | 19ba6c1ed01a0eb625a8e4099f8ac8d9c1f30675 | bigcode/the-stack | train |
967cba1ff59a0c510bff134f | train | function | def register():
for c in _classes: register_class(c)
bpy.types.Scene.settings = bpy.props.PointerProperty(type=Settings)
| def register():
| for c in _classes: register_class(c)
bpy.types.Scene.settings = bpy.props.PointerProperty(type=Settings)
| Armature:", icon='BONE_DATA')
column.operator(SkeletonBuilder.bl_idname, text="Generate Bones", icon='ARMATURE_DATA')
_classes = [
Settings,
PosePipePanel,
RunOperator,
RunFileSelector,
SkeletonBuilder,
RetimeAnimation,
]
def register():
| 64 | 64 | 28 | 3 | 61 | SpectralVectors/PosePipe | PosePipe.py | Python | register | register | 1,297 | 1,299 | 1,297 | 1,297 | 725be2b2f177b688ac16d9dc0d4d229b8cfb94e3 | bigcode/the-stack | train |
b74cb1f1c6fcae01e3885296 | train | class | class Settings(PropertyGroup):
# Capture only body pose if True, otherwise capture hands, face and body
face_tracking: bpy.props.BoolProperty(default=False)
hand_tracking: bpy.props.BoolProperty(default=False)
body_tracking: bpy.props.BoolProperty(default=True)
camera_number: bpy.props.IntPrope... | class Settings(PropertyGroup):
# Capture only body pose if True, otherwise capture hands, face and body
| face_tracking: bpy.props.BoolProperty(default=False)
hand_tracking: bpy.props.BoolProperty(default=False)
body_tracking: bpy.props.BoolProperty(default=True)
camera_number: bpy.props.IntProperty(default=0,
soft_min=0,
... | path
run_full(file_dir)
return{'FINISHED'}
class RunOperator(Operator):
"""Tooltip"""
bl_idname = "object.run_body_operator"
bl_label = "Run Body Operator"
def execute(self, context):
run_full("None")
return {'FINISHED'}
class Settings(PropertyGroup):
# Capture onl... | 86 | 87 | 292 | 22 | 64 | SpectralVectors/PosePipe | PosePipe.py | Python | Settings | Settings | 511 | 541 | 511 | 512 | 94b80e01a262275df1e47705a9c7bf9e1ed34a7b | bigcode/the-stack | train |
9d9a3610b76582da6f976039 | train | function | def hands_delete():
""" Deletes all objects associated with hands capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Hand Left" in scene_objects:
for c in bpy.context.scene.objects["Hand Left"].children:
if not len(... | def hands_delete():
| """ Deletes all objects associated with hands capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Hand Left" in scene_objects:
for c in bpy.context.scene.objects["Hand Left"].children:
if not len(bpy.context.scene.ob... | .context.scene.objects["Face"].children:
if not len(bpy.context.scene.objects["Face"].children) == 0:
bpy.data.objects[c.name].select_set(True)
bpy.ops.object.delete()
bpy.data.objects["Face"].select_set(True)
bpy.ops.object.delete()
def hands_delete():
| 64 | 64 | 197 | 4 | 60 | SpectralVectors/PosePipe | PosePipe.py | Python | hands_delete | hands_delete | 246 | 264 | 246 | 246 | ec88446fdae583328fac888c09ecc21c5d644bb9 | bigcode/the-stack | train |
189e1d09b5a6823c381fdea7 | train | function | def hands_setup():
""" Setup tracking boxes for hand tracking """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
setup = "Pose" in scene_objects
if not setup:
bpy.ops.object.add(radius=0.1, type='EMPTY')
pose = bpy.context.active_object
pose.name = "Pose"
... | def hands_setup():
| """ Setup tracking boxes for hand tracking """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
setup = "Pose" in scene_objects
if not setup:
bpy.ops.object.add(radius=0.1, type='EMPTY')
pose = bpy.context.active_object
pose.name = "Pose"
pose.scale = (-1,1... | )
pose = bpy.context.scene.objects["Pose"]
bpy.ops.object.add(radius=0.1, type='EMPTY')
body = bpy.context.active_object
body.name = "Body"
body.parent = pose
for k in range(33):
bpy.ops.mesh.primitive_cube_add()
box = bpy.context.active_object
box.name = body_names[k]... | 136 | 136 | 454 | 4 | 131 | SpectralVectors/PosePipe | PosePipe.py | Python | hands_setup | hands_setup | 128 | 179 | 128 | 128 | f7f9dc1ad6949fe140790ef6b70058fc4d24f933 | bigcode/the-stack | train |
813b3236eb761d6a60357872 | train | class | class RetimeAnimation(bpy.types.Operator):
"""Builds an armature to use with the mocap data"""
bl_idname = "posepipe.retime_animation"
bl_label = "Retime Animation"
def execute(self, context):
# Retime animation
#bpy.data.objects['Pose'].select_set(True)
scene_objects = [n for ... | class RetimeAnimation(bpy.types.Operator):
| """Builds an armature to use with the mocap data"""
bl_idname = "posepipe.retime_animation"
bl_label = "Retime Animation"
def execute(self, context):
# Retime animation
#bpy.data.objects['Pose'].select_set(True)
scene_objects = [n for n in bpy.context.scene.objects.keys()]
... | Location'].target = bpy.data.objects['Pose']
bpy.data.objects['Hand Left'].constraints["Copy Location"].use_y = False
bpy.ops.object.constraint_add(type='COPY_LOCATION')
bpy.data.objects['Hand Left'].constraints['Copy Location.001'].target = bpy.data.objects['15 left wrist']
bpy.data.ob... | 113 | 113 | 378 | 9 | 103 | SpectralVectors/PosePipe | PosePipe.py | Python | RetimeAnimation | RetimeAnimation | 444 | 477 | 444 | 444 | e371e26591b4d350a86c3abfbd4eba24d30f6625 | bigcode/the-stack | train |
8333a33bf4dc48599b66e364 | train | function | def face_setup():
""" Setup tracking boxes for face tracking """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
setup = "Pose" in scene_objects
if not setup:
bpy.ops.object.add(radius=0.1, type='EMPTY')
pose = bpy.context.active_object
pose.name = "Pose"
... | def face_setup():
| """ Setup tracking boxes for face tracking """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
setup = "Pose" in scene_objects
if not setup:
bpy.ops.object.add(radius=0.1, type='EMPTY')
pose = bpy.context.active_object
pose.name = "Pose"
pose.scale = (-1,1... | "
box.scale = (0.005, 0.005, 0.005)
box.parent = hand_right
box.color = (255,0,0,255)
hand_left = bpy.context.scene.objects["Hand Left"]
hand_right = bpy.context.scene.objects["Hand Right"]
pose.scale = (-1,1,1)
return hand_left, hand_right
def face_setup():
| 88 | 88 | 296 | 4 | 83 | SpectralVectors/PosePipe | PosePipe.py | Python | face_setup | face_setup | 182 | 218 | 182 | 182 | b30954438564bcb37ce69f3cb3c02fc0504ef925 | bigcode/the-stack | train |
4ca00140f326689250af5a91 | train | class | class RunOperator(Operator):
"""Tooltip"""
bl_idname = "object.run_body_operator"
bl_label = "Run Body Operator"
def execute(self, context):
run_full("None")
return {'FINISHED'}
| class RunOperator(Operator):
| """Tooltip"""
bl_idname = "object.run_body_operator"
bl_label = "Run Body Operator"
def execute(self, context):
run_full("None")
return {'FINISHED'}
| Operator, ImportHelper):
bl_idname = "something.identifier_selector"
bl_label = "Select Video File"
filename_ext = ""
def execute(self, context):
file_dir = self.properties.filepath
run_full(file_dir)
return{'FINISHED'}
class RunOperator(Operator):
| 63 | 64 | 49 | 6 | 57 | SpectralVectors/PosePipe | PosePipe.py | Python | RunOperator | RunOperator | 501 | 508 | 501 | 501 | 356fdf9395bdae82be5842e8b9157da8b51eab8d | bigcode/the-stack | train |
b469ee65df5025f7e19440e3 | train | function | def body_delete():
""" Deletes all objects associated with body capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Body" in scene_objects:
for c in bpy.context.scene.objects["Body"].children:
if not len(bpy.context... | def body_delete():
| """ Deletes all objects associated with body capture """
scene_objects = [n for n in bpy.context.scene.objects.keys()]
pose = bpy.context.scene.objects["Pose"]
if "Body" in scene_objects:
for c in bpy.context.scene.objects["Body"].children:
if not len(bpy.context.scene.objects["Bod... | = (0.002, 0.002, 0.002)
box.parent = face
box.color = (255,0,255,255)
face = bpy.context.scene.objects["Face"]
pose.scale = (-1,1,1)
return face
def body_delete():
| 64 | 64 | 114 | 4 | 59 | SpectralVectors/PosePipe | PosePipe.py | Python | body_delete | body_delete | 220 | 231 | 220 | 220 | 1eedce9526963e2fb661d1a94014166f0ca557dc | bigcode/the-stack | train |
514fcdb52cf85e4fdae78e5d | train | function | def unregister():
for c in _classes: unregister_class(c)
del bpy.types.Scene.settings
| def unregister():
| for c in _classes: unregister_class(c)
del bpy.types.Scene.settings
| _DATA')
_classes = [
Settings,
PosePipePanel,
RunOperator,
RunFileSelector,
SkeletonBuilder,
RetimeAnimation,
]
def register():
for c in _classes: register_class(c)
bpy.types.Scene.settings = bpy.props.PointerProperty(type=Settings)
def unregister():
| 64 | 64 | 21 | 3 | 61 | SpectralVectors/PosePipe | PosePipe.py | Python | unregister | unregister | 1,302 | 1,304 | 1,302 | 1,302 | 813808193ee26499ebc34344df00f34d6056a5c5 | bigcode/the-stack | train |
048eb2652beef73e40cd63a7 | train | function | def draw_file_opener(self, context):
layout = self.layout
scn = context.scene
col = layout.column()
row = col.row(align=True)
row.prop(scn.settings, 'file_path', text='directory:')
row.operator("something.identifier_selector", icon="FILE_FOLDER", text="")
| def draw_file_opener(self, context):
| layout = self.layout
scn = context.scene
col = layout.column()
row = col.row(align=True)
row.prop(scn.settings, 'file_path', text='directory:')
row.operator("something.identifier_selector", icon="FILE_FOLDER", text="")
| _SCALE', value=(timescale, 0, 0, 0))
#bpy.context.area.type = bpy.data.screens['Layout'].areas[-1].type
context.area.type = 'VIEW_3D'
return{'FINISHED'}
def draw_file_opener(self, context):
| 63 | 64 | 67 | 9 | 54 | SpectralVectors/PosePipe | PosePipe.py | Python | draw_file_opener | draw_file_opener | 481 | 487 | 481 | 481 | 6dd876ea7ececa94982b5cca5c8576795cf7d9c1 | bigcode/the-stack | train |
e08533f32b47902422ffc848 | train | function | def setup(bot):
bot.add_cog(Admin(bot))
| def setup(bot):
| bot.add_cog(Admin(bot))
| 369170939965)
json_files = [filename for filename in os.listdir(self.master_path + "/data")if filename.endswith(".json")]
my_files = [discord.File(f'{self.master_path}/data/{i}')for i in json_files]
await channel.send(files=my_files)
def setup(bot):
| 64 | 64 | 12 | 4 | 60 | disneyresidents/Satsuki | cogs/admin_cog.py | Python | setup | setup | 115 | 116 | 115 | 115 | ed0750b4c0598c281ab2d10a7a1d0a7498447d9f | bigcode/the-stack | train |
bfb3ef90e3618a0079cc3418 | train | class | class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.master_path = os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))
if not self.bot.loop.is_running():
self.auto_backup.start()
async def cog_check(self, ctx):
return ctx.guil... | class Admin(commands.Cog):
| def __init__(self, bot):
self.bot = bot
self.master_path = os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))
if not self.bot.loop.is_running():
self.auto_backup.start()
async def cog_check(self, ctx):
return ctx.guild and await self.bot.is_own... | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import time
import traceback
import typing
from datetime import datetime
import discord
import discosnow as ds
from discord.ext import commands, tasks
class Admin(commands.Cog):
| 58 | 253 | 844 | 6 | 51 | disneyresidents/Satsuki | cogs/admin_cog.py | Python | Admin | Admin | 16 | 112 | 16 | 16 | 0fcee6cad34cb68fc93bd8bb0638383abf544674 | bigcode/the-stack | train |
6f9bec1b8992f330a3c180ab | train | class | class NovaProxyRequestHandlerBase(object):
def address_string(self):
# NOTE(rpodolyaka): override the superclass implementation here and
# explicitly disable the reverse DNS lookup, which might fail on some
# deployments due to DNS configuration and break VNC access completely
return... | class NovaProxyRequestHandlerBase(object):
| def address_string(self):
# NOTE(rpodolyaka): override the superclass implementation here and
# explicitly disable the reverse DNS lookup, which might fail on some
# deployments due to DNS configuration and break VNC access completely
return str(self.client_address[0])
def verif... | under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed un... | 256 | 256 | 1,159 | 8 | 247 | j-griffith/nova | nova/console/websocketproxy.py | Python | NovaProxyRequestHandlerBase | NovaProxyRequestHandlerBase | 41 | 168 | 41 | 41 | 4b9d2feb17fb7df0825348e8fce531629f1faa9b | bigcode/the-stack | train |
cbd3261b2e0067b9093ec2e2 | train | class | class NovaProxyRequestHandler(NovaProxyRequestHandlerBase,
websockify.ProxyRequestHandler):
def __init__(self, *args, **kwargs):
websockify.ProxyRequestHandler.__init__(self, *args, **kwargs)
def socket(self, *args, **kwargs):
return websockify.WebSocketServer.sock... | class NovaProxyRequestHandler(NovaProxyRequestHandlerBase,
websockify.ProxyRequestHandler):
| def __init__(self, *args, **kwargs):
websockify.ProxyRequestHandler.__init__(self, *args, **kwargs)
def socket(self, *args, **kwargs):
return websockify.WebSocketServer.socket(*args, **kwargs)
| tsock.close()
self.vmsg(_("%(host)s:%(port)s: "
"Websocket client or target closed") %
{'host': host, 'port': port})
raise
class NovaProxyRequestHandler(NovaProxyRequestHandlerBase,
websockify.P... | 64 | 64 | 77 | 20 | 43 | j-griffith/nova | nova/console/websocketproxy.py | Python | NovaProxyRequestHandler | NovaProxyRequestHandler | 171 | 177 | 171 | 172 | 97c8ec3811919819c01d5fd4ffc98c15743cc2d4 | bigcode/the-stack | train |
7d1258dab6ed4d47955212e2 | train | class | class NovaWebSocketProxy(websockify.WebSocketProxy):
@staticmethod
def get_logger():
return LOG
| class NovaWebSocketProxy(websockify.WebSocketProxy):
@staticmethod
| def get_logger():
return LOG
| , **kwargs):
websockify.ProxyRequestHandler.__init__(self, *args, **kwargs)
def socket(self, *args, **kwargs):
return websockify.WebSocketServer.socket(*args, **kwargs)
class NovaWebSocketProxy(websockify.WebSocketProxy):
@staticmethod
| 64 | 64 | 25 | 16 | 48 | j-griffith/nova | nova/console/websocketproxy.py | Python | NovaWebSocketProxy | NovaWebSocketProxy | 180 | 183 | 180 | 181 | 2fb77bb9cca856fbd5cb57968273589d5e3e082f | bigcode/the-stack | train |
32d96bd48bd24bb621ef5250 | train | class | class Solution:
def get_weight(self, p_1, p_2):
if p_1[0] == p_2[0]:
return None
m = Decimal(p_2[1] - p_1[1]) / Decimal(p_2[0] - p_1[0])
return m
def maxPoints(self, points: List[List[int]]) -> int:
max_points = 0
n = len(points)
counter = Counter([(... | class Solution:
| def get_weight(self, p_1, p_2):
if p_1[0] == p_2[0]:
return None
m = Decimal(p_2[1] - p_1[1]) / Decimal(p_2[0] - p_1[0])
return m
def maxPoints(self, points: List[List[int]]) -> int:
max_points = 0
n = len(points)
counter = Counter([(x[0], x[1]) for x... | from typing import List
from collections import Counter
from decimal import Decimal
class Solution:
| 18 | 68 | 227 | 3 | 14 | thomasgassmann/leetcode | problems/max-points-on-a-line/solution.py | Python | Solution | Solution | 5 | 30 | 5 | 6 | f3c9920ab440d47953ea17c74c875b6e19bb2ce1 | bigcode/the-stack | train |
7fa934aa8392089a6e011b1f | train | function | @ndb.tasklet
def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, me... | @ndb.tasklet
def memoizing_fibonacci(n):
| """A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, memo.value)
raise ndb.Return(memo.value... | (n)
a, b = yield fibonacci(n-1),fibonacci(n-2)
raise ndb.Return(a + b)
class FibonacciMemo(ndb.Model):
arg = ndb.IntegerProperty()
value = ndb.IntegerProperty()
@ndb.tasklet
def memoizing_fibonacci(n):
| 64 | 64 | 201 | 13 | 51 | wmv/appengine-ndb-experiment | demo/fibo.py | Python | memoizing_fibonacci | memoizing_fibonacci | 29 | 47 | 29 | 30 | 2e6d0e20a5f3172a0d33a8335b05fdcc254d1b40 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.