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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62561fdd238c5002c6856c04 | train | function | def find_output(node, txid, amount):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeEr... | def find_output(node, txid, amount):
| """
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not fou... | while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
time.sleep(0.1)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def find_output(node, txid, amount):
| 64 | 64 | 102 | 10 | 54 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | find_output | find_output | 224 | 233 | 224 | 224 | e8fc600f64add7ca3f9b60ca808f598fbb5f0893 | bigcode/the-stack | train |
1526085c8aa0f6ba5816c87d | train | function | def sync_blocks(rpc_connections):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc_connections ]
if counts == [ counts[0] ]*len(counts):
break
time.sleep(1)
| def sync_blocks(rpc_connections):
| """
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc_connections ]
if counts == [ counts[0] ]*len(counts):
break
time.sleep(1)
| = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def sync_blocks(rpc_connections):
| 64 | 64 | 64 | 7 | 57 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | sync_blocks | sync_blocks | 39 | 47 | 39 | 39 | ff2f73f94cb1d705b60cbb682b7a0d8626862551 | bigcode/the-stack | train |
6eca84ba99a6aab86610d902 | train | function | def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >=0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = De... | def gather_inputs(from_node, amount_needed, confirmations_required=1):
| """
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >=0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > ... | (len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
| 63 | 64 | 185 | 14 | 49 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | gather_inputs | gather_inputs | 236 | 251 | 236 | 236 | 9cd0044dec0a53b2b3e722e8eaad85c5493b44d9 | bigcode/the-stack | train |
a788e916b50cb1710e76a877 | train | function | def wait_bitcoinds():
# Wait for all bitcoinds to cleanly exit
for bitcoind in bitcoind_processes.values():
bitcoind.wait()
bitcoind_processes.clear()
| def wait_bitcoinds():
# Wait for all bitcoinds to cleanly exit
| for bitcoind in bitcoind_processes.values():
bitcoind.wait()
bitcoind_processes.clear()
| for node in nodes:
node.stop()
del nodes[:] # Emptying array closes connections as a side effect
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def wait_bitcoinds():
# Wait for all bitcoinds to cleanly exit
| 64 | 64 | 46 | 19 | 45 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | wait_bitcoinds | wait_bitcoinds | 206 | 210 | 206 | 207 | 457c046ac00d52b28087313c155a07a9ac71ce9d | bigcode/the-stack | train |
56e0459db19ddc044d36b3c0 | train | function | def rpc_port(n):
return 12000 + n + os.getpid()%999
| def rpc_port(n):
| return 12000 + n + os.getpid()%999
| _DOWN
import json
import random
import shutil
import subprocess
import time
import re
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def p2p_port(n):
return 11000 + n + os.getpid()%999
def rpc_port(n):
| 64 | 64 | 19 | 5 | 58 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | rpc_port | rpc_port | 29 | 30 | 29 | 29 | a35639752e1a9dad48e6f1040a6f0b083dd4b292 | bigcode/the-stack | train |
a5e471967ed51461e3d74e63 | train | function | def start_node(i, dirname, extra_args=None, rpchost=None):
"""
Start a banderad and return RPC connection to it
"""
datadir = os.path.join(dirname, "node"+str(i))
args = [ os.getenv("BITCOIND", "banderad"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ]
if extra_args is not None: ar... | def start_node(i, dirname, extra_args=None, rpchost=None):
| """
Start a banderad and return RPC connection to it
"""
datadir = os.path.join(dirname, "node"+str(i))
args = [ os.getenv("BITCOIND", "banderad"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ]
if extra_args is not None: args.extend(extra_args)
bitcoind_processes[i] = subproces... | connect.startswith('['): # remove IPv6 [...] wrapping
rpcconnect = rpcconnect[1:-1]
rv = ['-rpcconnect=' + rpcconnect]
if rpcport:
rv += ['-rpcport=' + rpcport]
return rv
def start_node(i, dirname, extra_args=None, rpchost=None):
| 72 | 72 | 242 | 16 | 55 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | start_node | start_node | 164 | 180 | 164 | 164 | 39b379bf1a4bb47f16512a2468befb54dffc3003 | bigcode/the-stack | train |
e10a7d01945bf00189fd6072 | train | function | def sync_mempools(rpc_connections):
"""
Wait until everybody has the same transactions in their memory
pools
"""
while True:
pool = set(rpc_connections[0].getrawmempool())
num_match = 1
for i in range(1, len(rpc_connections)):
if set(rpc_connections[i].getrawmempo... | def sync_mempools(rpc_connections):
| """
Wait until everybody has the same transactions in their memory
pools
"""
while True:
pool = set(rpc_connections[0].getrawmempool())
num_match = 1
for i in range(1, len(rpc_connections)):
if set(rpc_connections[i].getrawmempool()) == pool:
num_m... | Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc_connections ]
if counts == [ counts[0] ]*len(counts):
break
time.sleep(1)
def sync_mempools(rpc_connections):
| 64 | 64 | 113 | 9 | 55 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | sync_mempools | sync_mempools | 49 | 62 | 49 | 49 | 3b19c3fb45fea6c54630126a8a9eefdcad4937a5 | bigcode/the-stack | train |
e2e09c656ec5d07ff38426de | train | function | def assert_raises(exc, fun, *args, **kwds):
try:
fun(*args, **kwds)
except exc:
pass
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
| def assert_raises(exc, fun, *args, **kwds):
| try:
fun(*args, **kwds)
except exc:
pass
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
| (thing1),str(thing2)))
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
| 64 | 64 | 67 | 15 | 49 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | assert_raises | assert_raises | 338 | 346 | 338 | 338 | 1942593327c89a96efaeb3a1ae271295a07650c4 | bigcode/the-stack | train |
99a2af37a4a16a47389f2478 | train | function | def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
... | def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
| """
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount+fee)
outputs = mak... | fee_increment*random.randint(0,fee_variants)
(txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
return (txid, txhex, fee)
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
| 64 | 64 | 175 | 17 | 47 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | random_transaction | random_transaction | 311 | 328 | 311 | 311 | 283bc07de243a1cbecd8c3fb2d93f8d96c0f909c | bigcode/the-stack | train |
163a2150262a45afa14c778b | train | function | def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
| def assert_greater_than(thing1, thing2):
| if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
| )
return (txid, signresult["hex"], fee)
def assert_equal(thing1, thing2):
if thing1 != thing2:
raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
def assert_greater_than(thing1, thing2):
| 64 | 64 | 40 | 12 | 52 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | assert_greater_than | assert_greater_than | 334 | 336 | 334 | 334 | 7337ea857f4666d61d8776610788c9e18d65a782 | bigcode/the-stack | train |
2a95ddc5c2072d1ed520aa5f | train | function | def initialize_chain(test_dir):
"""
Create (or copy from cache) a 200-block-long chain and
4 wallets.
banderad and bandera-cli must be in search path.
"""
if not os.path.isdir(os.path.join("cache", "node0")):
devnull = open("/dev/null", "w+")
# Create cache directories, run band... | def initialize_chain(test_dir):
| """
Create (or copy from cache) a 200-block-long chain and
4 wallets.
banderad and bandera-cli must be in search path.
"""
if not os.path.isdir(os.path.join("cache", "node0")):
devnull = open("/dev/null", "w+")
# Create cache directories, run banderad:
for i in range(4):... | _connections[i].getrawmempool()) == pool:
num_match = num_match+1
if num_match == len(rpc_connections):
break
time.sleep(1)
bitcoind_processes = {}
def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n))
if not os.path.isdir(datadir):
... | 178 | 178 | 594 | 6 | 171 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | initialize_chain | initialize_chain | 78 | 133 | 78 | 78 | 813fe5a82c2e8d59a393e1a4262ff213b8af3c28 | bigcode/the-stack | train |
fc5118cf4891cd16f23951e4 | train | function | def send_zeropri_transaction(from_node, to_node, amount, fee):
"""
Create&broadcast a zero-priority transaction.
Returns (txid, hex-encoded-txdata)
Ensures transaction is zero-priority by first creating a send-to-self,
then using it's output
"""
# Create a send-to-self with confirmed inputs... | def send_zeropri_transaction(from_node, to_node, amount, fee):
| """
Create&broadcast a zero-priority transaction.
Returns (txid, hex-encoded-txdata)
Ensures transaction is zero-priority by first creating a send-to-self,
then using it's output
"""
# Create a send-to-self with confirmed inputs:
self_address = from_node.getnewaddress()
(total_in, i... | address()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return out... | 93 | 93 | 313 | 16 | 76 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | send_zeropri_transaction | send_zeropri_transaction | 270 | 298 | 270 | 270 | 26b52b4818b465d583b5236bfa51bf50c1893dc8 | bigcode/the-stack | train |
6917b10ab93602fd8d94e0e7 | train | function | def log_filename(dirname, n_node, logname):
return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
| def log_filename(dirname, n_node, logname):
| return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
| return RPC connections to them
"""
if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ]
def log_filename(dirname, n_node, logname):
| 64 | 64 | 32 | 11 | 53 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | log_filename | log_filename | 189 | 190 | 189 | 189 | 915b6597e4c4ab74211818ca14285a9635f74d57 | bigcode/the-stack | train |
e3c53467ad0907a7b8c42b98 | train | function | def stop_nodes(nodes):
for node in nodes:
node.stop()
del nodes[:] # Emptying array closes connections as a side effect
| def stop_nodes(nodes):
| for node in nodes:
node.stop()
del nodes[:] # Emptying array closes connections as a side effect
| (dirname, n_node, logname):
return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
def stop_node(node, i):
node.stop()
bitcoind_processes[i].wait()
del bitcoind_processes[i]
def stop_nodes(nodes):
| 64 | 64 | 30 | 5 | 59 | 2ovob4ehko/bandera-coin | qa/rpc-tests/util.py | Python | stop_nodes | stop_nodes | 197 | 200 | 197 | 197 | 15c56328e5dfb09edd9a6f0e264178d9d39b520d | bigcode/the-stack | train |
28b6edcb4aa5ed8b71f3f63a | train | class | class VAEGen(GenBase):
def __init__(self, input_dim=None, verbose=False, model=None, **kwargs):
super().__init__()
if model is None:
self.model = ModelVAE(input_dim=input_dim, verbose=verbose, **kwargs)
else:
self.model = model
self.manifold = None
def fi... | class VAEGen(GenBase):
| def __init__(self, input_dim=None, verbose=False, model=None, **kwargs):
super().__init__()
if model is None:
self.model = ModelVAE(input_dim=input_dim, verbose=verbose, **kwargs)
else:
self.model = model
self.manifold = None
def fit(self, x, epochs=10, b... | import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional
from melime.generators.gen_base import GenBase
class VAEGen(GenBase):
| 40 | 140 | 469 | 8 | 31 | tiagobotari/melime | melime/generators/vae_gen.py | Python | VAEGen | VAEGen | 9 | 55 | 9 | 9 | 6d8b6ab9ab1c6844d9429c8c95e79f526a595aa5 | bigcode/the-stack | train |
49f3485463a5af20a2a220c6 | train | class | class ModelVAE(object):
def __init__(
self, input_dim, nodes_dim=400, n_layers=2, latent_dim=12, device="cpu", batch_size=128, verbose=False
):
self.verbose = verbose
self.latent_dim = latent_dim
self.input_dim = input_dim
self.n_layers = n_layers
self.nodes_dim =... | class ModelVAE(object):
| def __init__(
self, input_dim, nodes_dim=400, n_layers=2, latent_dim=12, device="cpu", batch_size=128, verbose=False
):
self.verbose = verbose
self.latent_dim = latent_dim
self.input_dim = input_dim
self.n_layers = n_layers
self.nodes_dim = nodes_dim
self... | x_exp_tensor = torch.from_numpy(x_exp).to(self.model.device)
mu_p, log_var_p = self.model.model.encode(x_exp_tensor.reshape(-1))
ones = torch.ones(n_samples).to(self.model.device)
mu_m = torch.ger(ones, mu_p)
std_r = torch.exp(0.5 * log_var_p).to(self.model.de... | 231 | 231 | 770 | 6 | 224 | tiagobotari/melime | melime/generators/vae_gen.py | Python | ModelVAE | ModelVAE | 58 | 136 | 58 | 58 | fe5d93a44524837e2e694143a5c83fcaab908e00 | bigcode/the-stack | train |
5961ff7a837416559bfdd7d6 | train | class | class VAE(nn.Module):
def __init__(self, input_dim, nodes_dim=400, n_layers=2, latent_dim=12, device=None):
super().__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.nodes_dim = nodes_dim
self.device = device
self.layers_encoder = nn.ModuleList(... | class VAE(nn.Module):
| def __init__(self, input_dim, nodes_dim=400, n_layers=2, latent_dim=12, device=None):
super().__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.nodes_dim = nodes_dim
self.device = device
self.layers_encoder = nn.ModuleList(self.create_layers(sel... | .input_dim), reduction="sum")
# see Appendix B from VAE paper:
# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
# https://arxiv.org/abs/1312.6114
# 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
kld = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
... | 122 | 122 | 409 | 6 | 115 | tiagobotari/melime | melime/generators/vae_gen.py | Python | VAE | VAE | 139 | 188 | 139 | 139 | f499932ec3dd0f031e51165ef4c72f3a105adda7 | bigcode/the-stack | train |
35da578d5c93fbf1b6729bf1 | train | class | class Command(BaseCommand):
help = "Import Data"
def handle(self, *args, **kwargs):
clean = re.compile('<.*?>')
data = pd.read_json('./data/json/nabucco161021.json')
df_json = pd.json_normalize(data.nodes)
# print(df_json)
for i, row in df_json.iterrows():
m... | class Command(BaseCommand):
| help = "Import Data"
def handle(self, *args, **kwargs):
clean = re.compile('<.*?>')
data = pd.read_json('./data/json/nabucco161021.json')
df_json = pd.json_normalize(data.nodes)
# print(df_json)
for i, row in df_json.iterrows():
museum_id = row['node.Museum ... | from django.core.management.base import BaseCommand
import pandas as pd
import re
class Command(BaseCommand):
| 22 | 123 | 410 | 5 | 16 | acdh-oeaw/nabucco | appcreator/management/commands/import_json_print.py | Python | Command | Command | 7 | 46 | 7 | 7 | d3681c943e6d28ee197f878621365a2a56c4c9f9 | bigcode/the-stack | train |
bbed0ea122a3f09b11837de6 | train | class | @gin.configurable
class TruncatedES(gradient_learner.GradientEstimator):
"""Estimate gradients with truncated evolution strategies.
This gradient estimator performs 2 antithetic unrolls to compute a gradient
estimate.
"""
def __init__(
self,
truncated_step: truncated_step_mod.VectorizedTruncated... | @gin.configurable
class TruncatedES(gradient_learner.GradientEstimator):
| """Estimate gradients with truncated evolution strategies.
This gradient estimator performs 2 antithetic unrolls to compute a gradient
estimate.
"""
def __init__(
self,
truncated_step: truncated_step_mod.VectorizedTruncatedStep,
unroll_length: int = 20,
steps_per_jit: int = 10,
... | list(x.shape[2:]))
p_ys = jax.tree_map(flat_first, tree_utils.tree_zip_jnp(p_yses))
n_ys = jax.tree_map(flat_first, tree_utils.tree_zip_jnp(n_yses))
# mean over the num steps axis.
pos_loss = jnp.sum(p_ys.loss * p_ys.mask, axis=0) / jnp.sum(p_ys.mask, axis=0)
neg_loss = jnp.sum(n_ys.loss * n_ys.mask, axis=... | 256 | 256 | 1,003 | 18 | 237 | Sohl-Dickstein/learned_optimization | learned_optimization/outer_trainers/truncated_es.py | Python | TruncatedES | TruncatedES | 81 | 210 | 81 | 82 | d045ddbf345865b55d06a6ad5522d835ba41eb15 | bigcode/the-stack | train |
699d1d1025f98f95eca16139 | train | function | @functools.partial(jax.jit, static_argnames=("std",))
def compute_es_grad(
p_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
n_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
vec_pos: MetaParams, std: float
) -> Tuple[float, MetaParams, truncated_step_mod.TruncatedUnrollOut, float]:
"""Compu... | @functools.partial(jax.jit, static_argnames=("std",))
def compute_es_grad(
p_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
n_yses: Sequence[truncated_step_mod.TruncatedUnrollOut],
vec_pos: MetaParams, std: float
) -> Tuple[float, MetaParams, truncated_step_mod.TruncatedUnrollOut, float]:
| """Compute the ES gradient estimate from the outputs of many unrolls.
Args:
p_yses: Sequence of ES outputs from the positive perturbation.
n_yses: Sequence of ES outputs from the negative perturbation.
vec_pos: Positive perturbations used to compute the current unroll.
std: Standard deviation of pe... | common
from learned_optimization.outer_trainers import gradient_learner
from learned_optimization.outer_trainers import truncated_step as truncated_step_mod
PRNGKey = jnp.ndarray
MetaParams = Any
UnrollState = Any
@functools.partial(jax.jit, static_argnames=("std",))
def compute_es_grad(
p_yses: Sequence[truncat... | 136 | 136 | 456 | 87 | 48 | Sohl-Dickstein/learned_optimization | learned_optimization/outer_trainers/truncated_es.py | Python | compute_es_grad | compute_es_grad | 41 | 78 | 41 | 46 | 5f828e348e93cc963405f13859a4873ba6083bac | bigcode/the-stack | train |
9db352397a0df9d64ea2ebd1 | train | function | def check_data(loader):
assert loader.has(name, date)
quote = loader.get(name, date)
assert quote.name() == name
assert quote.quote().value() == value
assert quote.asofDate() == date
assert quote.instrumentType() == MarketDatum.InstrumentType_CC_BASIS_SWAP
assert quote.quoteType() == Market... | def check_data(loader):
| assert loader.has(name, date)
quote = loader.get(name, date)
assert quote.name() == name
assert quote.quote().value() == value
assert quote.asofDate() == date
assert quote.instrumentType() == MarketDatum.InstrumentType_CC_BASIS_SWAP
assert quote.quoteType() == MarketDatum.QuoteType_BASIS_SP... | _SPREAD/USD/3M/CHF/3M/4Y"
value = -0.008303
#20150202 EUR-EURIBOR-1W -0.00022
fix_date = Date(2, February, 2015)
fix_name = "EUR-EURIBOR-1W"
fix_value = -0.00022
def check_data(loader):
| 81 | 81 | 271 | 5 | 75 | syalovit/ORE-SWIG | OREAnalytics-SWIG/Python/Examples/loader.py | Python | check_data | check_data | 17 | 44 | 17 | 17 | fde20bfb35d9f4ff4e1587717317487df95552e5 | bigcode/the-stack | train |
f89f5fa554a996691eae8e43 | train | class | class TruncatedNormal(Posterior):
def __init__(self, bounds):
self.bounds = torch.tensor(bounds, dtype=torch.float64, requires_grad=False)
self.norm = torch.distributions.Normal(loc=0.0, scale=1.0)
self.val = None
def sample_epsilon(self, size):
eps_arr = np.random.uniform(low=... | class TruncatedNormal(Posterior):
| def __init__(self, bounds):
self.bounds = torch.tensor(bounds, dtype=torch.float64, requires_grad=False)
self.norm = torch.distributions.Normal(loc=0.0, scale=1.0)
self.val = None
def sample_epsilon(self, size):
eps_arr = np.random.uniform(low=0.0, high=1.0, size=size)
r... | .norm.log_prob((z.log() - alpha) / (sigma + 1e-10))
return torch.sum(log_phi - (sigma + 1e-10).log() - z.log())
def mode(self, alpha, beta):
return torch.exp(alpha - beta.exp() ** 2)
def mean(self, alpha, beta):
return torch.exp(alpha + 0.5 * beta.exp() ** 2)
def median(self, alph... | 217 | 217 | 725 | 8 | 209 | trouleau/pypop | pypop/posteriors.py | Python | TruncatedNormal | TruncatedNormal | 74 | 136 | 74 | 75 | a00564706ae3f5ead1a4a16b3abbdf65a0d3fb3c | bigcode/the-stack | train |
e66611ad9118de719e06c91f | train | class | class Posterior:
def sample_epsilon(self, size):
"""
Sample an array of epsilons from the normal distribution, with size
(n_samples, n_weights, n_params)
"""
raise NotImplementedError('Must be implemented in child class')
def g(self, eps, alpha, beta):
"""
... | class Posterior:
| def sample_epsilon(self, size):
"""
Sample an array of epsilons from the normal distribution, with size
(n_samples, n_weights, n_params)
"""
raise NotImplementedError('Must be implemented in child class')
def g(self, eps, alpha, beta):
"""
Reparamaterizat... | import math
import numpy as np
from scipy.stats import norm, lognorm, truncnorm
import torch
class Posterior:
| 27 | 64 | 132 | 4 | 22 | trouleau/pypop | pypop/posteriors.py | Python | Posterior | Posterior | 8 | 27 | 8 | 9 | 4ef8d58ff4b45b50d4c5e40d55e21dc89a754e86 | bigcode/the-stack | train |
a07330d0f2184502fd016224 | train | class | class LogNormalPosterior(Posterior):
def __init__(self, device='cpu'):
self.norm = torch.distributions.Normal(loc=0.0, scale=1.0)
self.device = 'cuda' if torch.cuda.is_available() and device == 'cuda' else 'cpu'
def sample_epsilon(self, size):
"""
Sample an array of epsilons fr... | class LogNormalPosterior(Posterior):
| def __init__(self, device='cpu'):
self.norm = torch.distributions.Normal(loc=0.0, scale=1.0)
self.device = 'cuda' if torch.cuda.is_available() and device == 'cuda' else 'cpu'
def sample_epsilon(self, size):
"""
Sample an array of epsilons from the normal distribution, with size
... | array of epsilons from the normal distribution, with size
(n_samples, n_weights, n_params)
"""
raise NotImplementedError('Must be implemented in child class')
def g(self, eps, alpha, beta):
"""
Reparamaterization of the approximate log-normal posterior function
"""
... | 123 | 123 | 412 | 9 | 114 | trouleau/pypop | pypop/posteriors.py | Python | LogNormalPosterior | LogNormalPosterior | 30 | 71 | 30 | 31 | c2ab3a71006cee9b97e44d98c9fcbe0671e00c96 | bigcode/the-stack | train |
414235c07aa21b1f07417481 | train | function | def reverse_y_mapper(height, mapper):
"""
Returns a coordinate mapper function for grids with reversed Y coordinates.
:param height: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_y = height - 1
def y_mapper(x, y):
return mapper(x, max_y - y)
... | def reverse_y_mapper(height, mapper):
| """
Returns a coordinate mapper function for grids with reversed Y coordinates.
:param height: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_y = height - 1
def y_mapper(x, y):
return mapper(x, max_y - y)
return y_mapper
| of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_x = width - 1
def x_mapper(x, y):
return mapper(max_x - x, y)
return x_mapper
def reverse_y_mapper(height, mapper):
| 64 | 64 | 85 | 8 | 55 | smysnk/led-controller | src/adafruit_led_animation/grid.py | Python | reverse_y_mapper | reverse_y_mapper | 220 | 233 | 220 | 220 | 04f7de943ad50e6cf9ebf899026081da9972787a | bigcode/the-stack | train |
d50d07bbf60a4390607c629c | train | function | def reverse_x_mapper(width, mapper):
"""
Returns a coordinate mapper function for grids with reversed X coordinates.
:param width: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_x = width - 1
def x_mapper(x, y):
return mapper(max_x - x, y)
... | def reverse_x_mapper(width, mapper):
| """
Returns a coordinate mapper function for grids with reversed X coordinates.
:param width: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_x = width - 1
def x_mapper(x, y):
return mapper(max_x - x, y)
return x_mapper
| pixels.show()
@property
def auto_write(self):
"""
auto_write from the underlying strip.
"""
return self._pixels.auto_write
@auto_write.setter
def auto_write(self, value):
self._pixels.auto_write = value
def reverse_x_mapper(width, mapper):
| 64 | 64 | 85 | 8 | 55 | smysnk/led-controller | src/adafruit_led_animation/grid.py | Python | reverse_x_mapper | reverse_x_mapper | 204 | 217 | 204 | 204 | 0cfe6f4a00d129793471815e7dbf13094cedf36f | bigcode/the-stack | train |
30a07bf08f9359b4c4a843ee | train | class | class PixelGrid:
"""
PixelGrid lets you address a pixel strip with x and y coordinates.
:param strip: An object that implements the Neopixel or Dotstar protocol.
:param width: Grid width.
:param height: Grid height.
:param orientation: Orientation of the strip pixels - HORIZONTAL (default) or V... | class PixelGrid:
| """
PixelGrid lets you address a pixel strip with x and y coordinates.
:param strip: An object that implements the Neopixel or Dotstar protocol.
:param width: Grid width.
:param height: Grid height.
:param orientation: Orientation of the strip pixels - HORIZONTAL (default) or VERTICAL.
:par... | # all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE ... | 256 | 256 | 992 | 4 | 252 | smysnk/led-controller | src/adafruit_led_animation/grid.py | Python | PixelGrid | PixelGrid | 53 | 201 | 53 | 53 | e99115a0da55b46338deda66232d07e6311b2f46 | bigcode/the-stack | train |
1a96b5a294c8778325ab0171 | train | class | class JupyterCommand(PluginCommand):
# noinspection PyUnusedLocal
@command
def do_jupyter(self, args, arguments):
"""
::
Usage:
jupyter lab HOST PORT [DIR]
jupyter tunnel HOST PORT
jupyter stop HOST PORT
jupyter open... | class JupyterCommand(PluginCommand):
# noinspection PyUnusedLocal
@command
| def do_jupyter(self, args, arguments):
"""
::
Usage:
jupyter lab HOST PORT [DIR]
jupyter tunnel HOST PORT
jupyter stop HOST PORT
jupyter open PORT
jupyter info [PORT]
jupyter backup
... | from cloudmesh.shell.command import command
from cloudmesh.shell.command import PluginCommand
from cloudmesh.common.console import Console
from cloudmesh.common.util import path_expand
from cloudmesh.common.util import backup_name
from cloudmesh.common.util import yn_choice
from pprint import pprint
from cloudmesh.comm... | 109 | 153 | 513 | 20 | 88 | cloudmesh/cloudmesh-jupyter | cloudmesh/jupyter/command/jupyter.py | Python | JupyterCommand | JupyterCommand | 13 | 102 | 13 | 16 | 035a01e884cce2ed1d26c07d553fbf13a07a7926 | bigcode/the-stack | train |
99b47981d945fbc3f44844bd | train | class | class Migration(migrations.Migration):
dependencies = [
('playground_backend', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='created_by',
new_name='user',
),
migrations.RenameField(
... | class Migration(migrations.Migration):
| dependencies = [
('playground_backend', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='created_by',
new_name='user',
),
migrations.RenameField(
model_name='comment',
old_na... | # Generated by Django 2.2.7 on 2019-11-09 03:02
from django.db import migrations
class Migration(migrations.Migration):
| 36 | 64 | 85 | 7 | 28 | kkomarocker/playground | playground/playground_backend/migrations/0002_auto_20191109_0302.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 7a3f2a12a447da6a3f97bcd510f4b90f7527da2f | bigcode/the-stack | train |
d2ea4e87f559fbf3025d1140 | train | function | def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to fi... | def load_data(city, month, day):
| """
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day... | import pandas as pd
path = "C:\\Users\\gv01\\Desktop\\googleSync\\LEarning\\Udacity\\Data Scientists Foundation\\python\\Resources\\"
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def load_data(city, month, day):
| 81 | 99 | 333 | 9 | 72 | vaibhavg12/DSFND | Introduction to Python/project/load_filter_dataset.py | Python | load_data | load_data | 9 | 44 | 9 | 9 | 02e880afd89c9021f01c3061eb72e8b0d2d5e55c | bigcode/the-stack | train |
803610f6bafe10a8b501f156 | train | function | def checkdir(dirstring):
if not os.path.isdir(dirstring):
error("Error: no such directory ", dirstring)
else:
return os.path.realpath(dirstring)
| def checkdir(dirstring):
| if not os.path.isdir(dirstring):
error("Error: no such directory ", dirstring)
else:
return os.path.realpath(dirstring)
| value = int(timedelta_string[:-1])
if unit == 's':
return timedelta(seconds=value)
elif unit == 'm':
return timedelta(minutes=value)
elif unit == 'd':
return timedelta(days=value)
else:
return timedelta(weeks=value)
def checkdir(dirstring)... | 64 | 64 | 39 | 6 | 58 | ouroboros8/mc_server_utils | delete_older_than.py | Python | checkdir | checkdir | 29 | 33 | 29 | 29 | 0c462da30b0122ac390a00be499dba54e42e7444 | bigcode/the-stack | train |
255204d7268bbfc5361dc1a1 | train | function | def str_to_timedelta(timedelta_string):
timedelta_string_pattern = re.compile('\d*[smdw]')
if not timedelta_string_pattern.fullmatch(timedelta_string):
error(timedelta_string, " is not a correctly formatted time string.")
sys.exit()
else:
unit = timedelta_string[-1]
value = i... | def str_to_timedelta(timedelta_string):
| timedelta_string_pattern = re.compile('\d*[smdw]')
if not timedelta_string_pattern.fullmatch(timedelta_string):
error(timedelta_string, " is not a correctly formatted time string.")
sys.exit()
else:
unit = timedelta_string[-1]
value = int(timedelta_string[:-1])
if uni... | # Delete all files in a directory older than age.
import sys
import os
import argparse
from datetime import datetime, timedelta
import re
def error(string):
print("Error: ", string, file=sys.stderr)
def str_to_timedelta(timedelta_string):
| 55 | 64 | 124 | 9 | 46 | ouroboros8/mc_server_utils | delete_older_than.py | Python | str_to_timedelta | str_to_timedelta | 12 | 27 | 12 | 12 | f2193f8597c2d8e0c6c32c864fdb9f9e76416f22 | bigcode/the-stack | train |
fa4872aad7352c540175632d | train | function | def error(string):
print("Error: ", string, file=sys.stderr)
| def error(string):
| print("Error: ", string, file=sys.stderr)
| # Delete all files in a directory older than age.
import sys
import os
import argparse
from datetime import datetime, timedelta
import re
def error(string):
| 34 | 64 | 16 | 4 | 29 | ouroboros8/mc_server_utils | delete_older_than.py | Python | error | error | 9 | 10 | 9 | 9 | f325274bb385cd8cbc2cf703000a617c2c1e090f | bigcode/the-stack | train |
1b4f58b1da2b8933a6884352 | train | function | def main():
time_help = '''
an integer followed by a suffix, denoting units. Files created longer than t ago
will be deleted. Suffixes 's', 'm', 'd', 'w' represent seconds, minutes, days,
weeks, respectively.
'''
parser = argparse.ArgumentParser(description='Process command line... | def main():
| time_help = '''
an integer followed by a suffix, denoting units. Files created longer than t ago
will be deleted. Suffixes 's', 'm', 'd', 'w' represent seconds, minutes, days,
weeks, respectively.
'''
parser = argparse.ArgumentParser(description='Process command line options')
... | ':
return timedelta(minutes=value)
elif unit == 'd':
return timedelta(days=value)
else:
return timedelta(weeks=value)
def checkdir(dirstring):
if not os.path.isdir(dirstring):
error("Error: no such directory ", dirstring)
else:
return os.path.... | 72 | 72 | 241 | 3 | 69 | ouroboros8/mc_server_utils | delete_older_than.py | Python | main | main | 35 | 58 | 35 | 35 | 08df14fa366966ee369399cba0ae1ca6906dbe20 | bigcode/the-stack | train |
b1c1ac1714174459ae09528e | train | class | class LoginView(SuccessURLAllowedHostsMixin, FormView):
"""
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = "registration/login.html"
redirect_authenticated_user ... | class LoginView(SuccessURLAllowedHostsMixin, FormView):
| """
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = "registration/login.html"
redirect_authenticated_user = False
extra_context = None
@method_decorator(... | django.utils.decorators import method_decorator
from django.utils.http import (
url_has_allowed_host_and_scheme,
urlsafe_base64_decode,
)
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from djang... | 146 | 146 | 489 | 13 | 133 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | LoginView | LoginView | 48 | 114 | 48 | 48 | ab8a047523709f51b44823ced2e78784599fc56e | bigcode/the-stack | train |
dc49ce88e0aaf263606edce1 | train | function | def logout_then_login(request, login_url=None):
"""
Log out the user if they are logged in. Then redirect to the login page.
"""
login_url = resolve_url(login_url or settings.LOGIN_URL)
return LogoutView.as_view(next_page=login_url)(request)
| def logout_then_login(request, login_url=None):
| """
Log out the user if they are logged in. Then redirect to the login page.
"""
login_url = resolve_url(login_url or settings.LOGIN_URL)
return LogoutView.as_view(next_page=login_url)(request)
| _site = get_current_site(self.request)
context.update(
{
"site": current_site,
"site_name": current_site.name,
"title": _("Logged out"),
**(self.extra_context or {}),
}
)
return context
def logout_then_login(... | 64 | 64 | 59 | 10 | 53 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | logout_then_login | logout_then_login | 180 | 185 | 180 | 180 | 39d2d519cb30fd747919719573745827df4f9277 | bigcode/the-stack | train |
7d0ad1caa6585f6a0aec806a | train | class | class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
"""
Log out the user and display the 'You are logged out' message.
"""
next_page = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = "registration/logged_out.html"
extra_context = None
@method_decorator(never_cac... | class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
| """
Log out the user and display the 'You are logged out' message.
"""
next_page = None
redirect_field_name = REDIRECT_FIELD_NAME
template_name = "registration/logged_out.html"
extra_context = None
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
... | def form_valid(self, form):
"""Security check complete. Log the user in."""
auth_login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
current_site = get... | 132 | 132 | 440 | 13 | 118 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | LogoutView | LogoutView | 117 | 177 | 117 | 117 | c773190d359a2ae3b7e30a5eeba42aeabca273b1 | bigcode/the-stack | train |
f31de505048da5bbca492d68 | train | class | class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
template_name = "registration/password_change_done.html"
title = _("Password change successful")
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
| class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
| template_name = "registration/password_change_done.html"
title = _("Password change successful")
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
| def form_valid(self, form):
form.save()
# Updating the password logs out all other sessions for the user
# except the current one.
update_session_auth_hash(self.request, form.user)
return super().form_valid(form)
class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
| 64 | 64 | 62 | 13 | 51 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordChangeDoneView | PasswordChangeDoneView | 377 | 383 | 377 | 377 | 8c8cb3002ba5ee26ebbd8d274c235473d164a050 | bigcode/the-stack | train |
001ac043be92ef586ab490c9 | train | class | class PasswordResetConfirmView(PasswordContextMixin, FormView):
form_class = SetPasswordForm
post_reset_login = False
post_reset_login_backend = None
reset_url_token = "set-password"
success_url = reverse_lazy("password_reset_complete")
template_name = "registration/password_reset_confirm.html"
... | class PasswordResetConfirmView(PasswordContextMixin, FormView):
| form_class = SetPasswordForm
post_reset_login = False
post_reset_login_backend = None
reset_url_token = "set-password"
success_url = reverse_lazy("password_reset_complete")
template_name = "registration/password_reset_confirm.html"
title = _("Enter new password")
token_generator = defaul... | *args, **kwargs):
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
opts = {
"use_https": self.request.is_secure(),
"token_generator": self.token_generator,
"from_email": self.from_email,
"email_template_name": self.email_template_... | 182 | 182 | 607 | 13 | 169 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordResetConfirmView | PasswordResetConfirmView | 259 | 339 | 259 | 259 | 780fc1b1dc1d4102612ec446c52e484dd63175c9 | bigcode/the-stack | train |
971cb16efaa7417174a8be4d | train | function | def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirect the user to the login page, passing the given 'next' page.
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
... | def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
| """
Redirect the user to the login page, passing the given 'next' page.
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[re... | out the user if they are logged in. Then redirect to the login page.
"""
login_url = resolve_url(login_url or settings.LOGIN_URL)
return LogoutView.as_view(next_page=login_url)(request)
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
| 64 | 64 | 125 | 19 | 45 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | redirect_to_login | redirect_to_login | 188 | 200 | 188 | 188 | d2447472b4e285ccbd701d00dfd1b02ac21c4a72 | bigcode/the-stack | train |
579d72e0fbf5b683a7e46cf8 | train | class | class PasswordResetDoneView(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_done.html"
title = _("Password reset sent")
| class PasswordResetDoneView(PasswordContextMixin, TemplateView):
| template_name = "registration/password_reset_done.html"
title = _("Password reset sent")
| "html_email_template_name": self.html_email_template_name,
"extra_email_context": self.extra_email_context,
}
form.save(**opts)
return super().form_valid(form)
INTERNAL_RESET_SESSION_TOKEN = "_password_reset_token"
class PasswordResetDoneView(PasswordContextMixin, Templ... | 64 | 64 | 32 | 13 | 51 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordResetDoneView | PasswordResetDoneView | 254 | 256 | 254 | 254 | 1ad36cadb1a35baf01f050284ce1dc01625c113c | bigcode/the-stack | train |
0b7b3fd71067d5d541f04b78 | train | class | class PasswordResetView(PasswordContextMixin, FormView):
email_template_name = "registration/password_reset_email.html"
extra_email_context = None
form_class = PasswordResetForm
from_email = None
html_email_template_name = None
subject_template_name = "registration/password_reset_subject.txt"
... | class PasswordResetView(PasswordContextMixin, FormView):
| email_template_name = "registration/password_reset_email.html"
extra_email_context = None
form_class = PasswordResetForm
from_email = None
html_email_template_name = None
subject_template_name = "registration/password_reset_subject.txt"
success_url = reverse_lazy("password_reset_done")
t... | a success message for the above
class PasswordContextMixin:
extra_context = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({"title": self.title, **(self.extra_context or {})})
return context
class PasswordResetView(PasswordConte... | 72 | 72 | 243 | 12 | 59 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordResetView | PasswordResetView | 220 | 248 | 220 | 220 | 8bc3d37b1d0a3e38ab1f63d825dfa3c3eb89d0eb | bigcode/the-stack | train |
f3141a87f8291f395f6959be | train | class | class PasswordChangeView(PasswordContextMixin, FormView):
form_class = PasswordChangeForm
success_url = reverse_lazy("password_change_done")
template_name = "registration/password_change_form.html"
title = _("Password change")
@method_decorator(sensitive_post_parameters())
@method_decorator(csr... | class PasswordChangeView(PasswordContextMixin, FormView):
| form_class = PasswordChangeForm
success_url = reverse_lazy("password_change_done")
template_name = "registration/password_change_form.html"
title = _("Password change")
@method_decorator(sensitive_post_parameters())
@method_decorator(csrf_protect)
@method_decorator(login_required)
def d... | registration/password_reset_complete.html"
title = _("Password reset complete")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["login_url"] = resolve_url(settings.LOGIN_URL)
return context
class PasswordChangeView(PasswordContextMixin, FormVie... | 64 | 64 | 181 | 12 | 51 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordChangeView | PasswordChangeView | 352 | 374 | 352 | 352 | d94af53014edf724c9e1666792db3195859d407e | bigcode/the-stack | train |
1658ec606221cb216d03368c | train | class | class SuccessURLAllowedHostsMixin:
success_url_allowed_hosts = set()
def get_success_url_allowed_hosts(self):
return {self.request.get_host(), *self.success_url_allowed_hosts}
| class SuccessURLAllowedHostsMixin:
| success_url_allowed_hosts = set()
def get_success_url_allowed_hosts(self):
return {self.request.get_host(), *self.success_url_allowed_hosts}
| as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
UserModel = get_user_model()
class Succ... | 64 | 64 | 39 | 7 | 57 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | SuccessURLAllowedHostsMixin | SuccessURLAllowedHostsMixin | 41 | 45 | 41 | 41 | 0b9330361e8a9553224a16afa92fef060663e1d5 | bigcode/the-stack | train |
ea2e3c2632c169f04a9021ca | train | class | class PasswordContextMixin:
extra_context = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({"title": self.title, **(self.extra_context or {})})
return context
| class PasswordContextMixin:
| extra_context = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({"title": self.title, **(self.extra_context or {})})
return context
| # - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
# prompts for a new password
# - PasswordResetCompleteView shows a success message for the above
class PasswordContextMixin:
| 64 | 64 | 53 | 5 | 58 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordContextMixin | PasswordContextMixin | 211 | 217 | 211 | 211 | 5352c95da7dcc9fba2486a76ef6c3d73b1175d4b | bigcode/the-stack | train |
9673666ed26a6d65b28604de | train | class | class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_complete.html"
title = _("Password reset complete")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["login_url"] = resolve_url(setting... | class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
| template_name = "registration/password_reset_complete.html"
title = _("Password reset complete")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["login_url"] = resolve_url(settings.LOGIN_URL)
return context
| .validlink:
context["validlink"] = True
else:
context.update(
{
"form": None,
"title": _("Password reset unsuccessful"),
"validlink": False,
}
)
return context
class PasswordRe... | 64 | 64 | 70 | 13 | 50 | nverbois/TFE21-232 | Thesis@3.9.1/Lib/site-packages/django/contrib/auth/views.py | Python | PasswordResetCompleteView | PasswordResetCompleteView | 342 | 349 | 342 | 342 | 61266db0d7f9185c18aa39babaef8ef49d041a44 | bigcode/the-stack | train |
9dd9ae34507997cab719ea0f | train | function | def test_hub_list_local_with_submodule():
args = set_hub_list_parser().parse_args(['--local-only'])
response = HubIO(args).list()
assert len(response) > 1
| def test_hub_list_local_with_submodule():
| args = set_hub_list_parser().parse_args(['--local-only'])
response = HubIO(args).list()
assert len(response) > 1
| from jina.docker.hubio import HubIO
from jina.parsers.hub import set_hub_list_parser
def test_hub_list_local_with_submodule():
| 33 | 64 | 44 | 10 | 22 | ryan-zheng-teki/jina | tests/unit/docker/test_hub_list.py | Python | test_hub_list_local_with_submodule | test_hub_list_local_with_submodule | 5 | 8 | 5 | 5 | d132e323e34650512e0fb1d5f0cf3df301f873e5 | bigcode/the-stack | train |
ee9c0e5f92c0d2a144a2ef9c | train | function | def test_hub_list_keywords():
args = set_hub_list_parser().parse_args(['--keywords', 'numeric'])
response = HubIO(args).list()
numeric_count = len(response)
assert numeric_count > 1
args = set_hub_list_parser().parse_args(['--keywords', 'numeric', 'randjojd'])
response = HubIO(args).list()
... | def test_hub_list_keywords():
| args = set_hub_list_parser().parse_args(['--keywords', 'numeric'])
response = HubIO(args).list()
numeric_count = len(response)
assert numeric_count > 1
args = set_hub_list_parser().parse_args(['--keywords', 'numeric', 'randjojd'])
response = HubIO(args).list()
combined_count = len(response... |
from jina.parsers.hub import set_hub_list_parser
def test_hub_list_local_with_submodule():
args = set_hub_list_parser().parse_args(['--local-only'])
response = HubIO(args).list()
assert len(response) > 1
def test_hub_list_keywords():
| 64 | 64 | 120 | 7 | 56 | ryan-zheng-teki/jina | tests/unit/docker/test_hub_list.py | Python | test_hub_list_keywords | test_hub_list_keywords | 11 | 25 | 11 | 11 | 14629961e1b070bada5af1947915fd2297f03bdf | bigcode/the-stack | train |
00c01d8944db933fdaf6a151 | train | function | def test_hub_list_nonexisting_kind():
args = set_hub_list_parser().parse_args(['--kind', 'blah'])
response = HubIO(args).list()
assert not response
| def test_hub_list_nonexisting_kind():
| args = set_hub_list_parser().parse_args(['--kind', 'blah'])
response = HubIO(args).list()
assert not response
| numeric', 'randjojd'])
response = HubIO(args).list()
combined_count = len(response)
assert combined_count > 1
# Making sure both arguments are --keywords are considered as `either or`
assert combined_count >= numeric_count
def test_hub_list_nonexisting_kind():
| 64 | 64 | 41 | 9 | 54 | ryan-zheng-teki/jina | tests/unit/docker/test_hub_list.py | Python | test_hub_list_nonexisting_kind | test_hub_list_nonexisting_kind | 28 | 32 | 28 | 28 | 9cbbd6ca6a42d4e937eac1b0f4cdacbedc626d58 | bigcode/the-stack | train |
bd3c477f5e45c14866ccf20f | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='RestaurantData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='RestaurantData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ddoock', models.CharField(max_le... | # Generated by Django 2.2.1 on 2019-10-09 09:53
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 77 | 259 | 7 | 30 | devGW/PostApp | cafeteria/crawler/migrations/0001_initial.py | Python | Migration | Migration | 6 | 38 | 6 | 7 | 5030540b1df5b59290b24a22c4f6e3f6b62aeeca | bigcode/the-stack | train |
c6e4e42225274d562678990b | train | class | @dataclass
class ProjectedGradient(base.IterativeSolverMixin):
"""Projected gradient solver.
This solver is a convenience wrapper around ``ProximalGradient``.
Attributes:
fun: a smooth function of the form ``fun(parameters, *args, **kwargs)``,
where ``parameters`` are the model parameters w.r.t. which... | @dataclass
class ProjectedGradient(base.IterativeSolverMixin):
| """Projected gradient solver.
This solver is a convenience wrapper around ``ProximalGradient``.
Attributes:
fun: a smooth function of the form ``fun(parameters, *args, **kwargs)``,
where ``parameters`` are the model parameters w.r.t. which we minimize
the function and the rest are fixed auxiliar... | # Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 218 | 256 | 860 | 13 | 204 | tachukao/jaxopt | jaxopt/_src/projected_gradient.py | Python | ProjectedGradient | ProjectedGradient | 30 | 126 | 30 | 31 | b9a2552d1cf40f8045b7f36dc187a0946543d0a6 | bigcode/the-stack | train |
96d1addde2086e178bf8a943 | train | class | class BroadbandPulse(Cantilever):
"""Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers
Uses a broadband pulse to excite the cantilever
Parameters
----------
can_params : dict
Parameters for cantilever properties. See Cantilever
force_params : dict
Parameters for forces. Beyond Cantilever, th... | class BroadbandPulse(Cantilever):
| """Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers
Uses a broadband pulse to excite the cantilever
Parameters
----------
can_params : dict
Parameters for cantilever properties. See Cantilever
force_params : dict
Parameters for forces. Beyond Cantilever, the dictionary contains:
es_force... | """simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "Rajiv Giridharagopal"
__copyright__ = "Copyright 2020, Ginger Lab"
__email__ = "rgiri@uw.edu"
__status__ = "Production"
import numpy as np
from scipy.integrate import odeint
from scipy.signal import chirp
from .cantilever ... | 120 | 178 | 594 | 7 | 112 | lindat18/ffta | ffta/simulation/broadband_drive.py | Python | BroadbandPulse | BroadbandPulse | 18 | 105 | 18 | 18 | 34fcfeff3a1047fcdec037426149722aad5fe2e7 | bigcode/the-stack | train |
a16c463de45e1b0f6a214972 | train | class | class NamespaceEntry(Base):
"""Represents a name within a BEL namespace."""
__tablename__ = NAME_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(
String(1023), index=True, nullable=False,
doc='Name that is defined in the corresponding namespace definition file',... | class NamespaceEntry(Base):
| """Represents a name within a BEL namespace."""
__tablename__ = NAME_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(
String(1023), index=True, nullable=False,
doc='Name that is defined in the corresponding namespace definition file',
)
identifier = Col... | = False) -> Mapping[str, str]:
"""Return the most useful entries as a dictionary.
:param include_id: If true, includes the model identifier
"""
result = {
'keyword': self.keyword,
'name': self.name,
'version': self.version,
}
... | 112 | 112 | 374 | 5 | 106 | aman527/pybel | src/pybel/manager/models.py | Python | NamespaceEntry | NamespaceEntry | 150 | 200 | 150 | 150 | 56e4cac5442eeeba4ef4baa00cb399ebf558b42a | bigcode/the-stack | train |
e2294532dd6eb672f5208a65 | train | class | class Namespace(Base):
"""Represents a BEL Namespace."""
__tablename__ = NAMESPACE_TABLE_NAME
id = Column(Integer, primary_key=True)
uploaded = Column(DateTime, nullable=False, default=datetime.datetime.utcnow, doc='The date of upload')
# logically the "namespace"
keyword = Column(
... | class Namespace(Base):
| """Represents a BEL Namespace."""
__tablename__ = NAMESPACE_TABLE_NAME
id = Column(Integer, primary_key=True)
uploaded = Column(DateTime, nullable=False, default=datetime.datetime.utcnow, doc='The date of upload')
# logically the "namespace"
keyword = Column(
String(255), nul... | 'Network',
'Node',
'Author',
'Citation',
'Evidence',
'Edge',
'edge_annotation',
'network_edge',
'network_node',
]
NAME_TABLE_NAME = 'pybel_name'
NAMESPACE_TABLE_NAME = 'pybel_namespace'
NODE_TABLE_NAME = 'pybel_node'
EDGE_TABLE_NAME = 'pybel_edge'
EDGE_ANNOTATION_... | 213 | 213 | 712 | 4 | 209 | aman527/pybel | src/pybel/manager/models.py | Python | Namespace | Namespace | 65 | 147 | 65 | 65 | 874875dae6dff86f51b001ede1aa6c9af3a1803d | bigcode/the-stack | train |
6a2e4af55fd12a720aa9ce01 | train | class | class Edge(Base):
"""Relationships between BEL nodes and their properties, annotations, and provenance."""
__tablename__ = EDGE_TABLE_NAME
id = Column(Integer, primary_key=True)
bel = Column(Text, nullable=False, doc='Valid BEL statement that represents the given edge')
relation = Column(... | class Edge(Base):
| """Relationships between BEL nodes and their properties, annotations, and provenance."""
__tablename__ = EDGE_TABLE_NAME
id = Column(Integer, primary_key=True)
bel = Column(Text, nullable=False, doc='Valid BEL statement that represents the given edge')
relation = Column(String(32), nullabl... | text),
)
def __str__(self):
return '{}:{}:{}'.format(self.citation.db, self.citation.db_id, self.text)
def to_json(self, include_id: bool = False):
"""Create a dictionary that is used to recreate the edge data dictionary for a :class:`BELGraph`.
:param include_id: If tru... | 224 | 224 | 748 | 4 | 220 | aman527/pybel | src/pybel/manager/models.py | Python | Edge | Edge | 523 | 615 | 523 | 523 | 2e5eea4537796289e2117451270e1e0931d5a4d4 | bigcode/the-stack | train |
2b8f62aeea5a81f36dc56a04 | train | class | class Node(Base):
"""Represents a BEL Term."""
__tablename__ = NODE_TABLE_NAME
id = Column(Integer, primary_key=True)
type = Column(String(32), nullable=False, doc='The type of the represented biological entity e.g. Protein or Gene')
bel = Column(String(1023), nullable=False, doc='Canonical... | class Node(Base):
| """Represents a BEL Term."""
__tablename__ = NODE_TABLE_NAME
id = Column(Integer, primary_key=True)
type = Column(String(32), nullable=False, doc='The type of the represented biological entity e.g. Protein or Gene')
bel = Column(String(1023), nullable=False, doc='Canonical BEL term that repr... |
return cls.id.in_(network_ids)
def __repr__(self):
return '{} v{}'.format(self.name, self.version)
def __str__(self):
return repr(self)
def as_bel(self):
"""Get this network and loads it into a :class:`BELGraph`.
:rtype: pybel.BELGraph
"""
... | 130 | 130 | 435 | 4 | 126 | aman527/pybel | src/pybel/manager/models.py | Python | Node | Node | 310 | 365 | 310 | 310 | a930410235f30508f806998e1c55241726f8c45d | bigcode/the-stack | train |
798a267e47cef18c7f7acbe7 | train | class | class Evidence(Base):
"""This table contains the evidence text that proves a specific relationship and refers the source that is cited."""
__tablename__ = EVIDENCE_TABLE_NAME
id = Column(Integer, primary_key=True)
text = Column(Text, nullable=False, doc='Supporting text from a given publication'... | class Evidence(Base):
| """This table contains the evidence text that proves a specific relationship and refers the source that is cited."""
__tablename__ = EVIDENCE_TABLE_NAME
id = Column(Integer, primary_key=True)
text = Column(Text, nullable=False, doc='Supporting text from a given publication')
citation_id = ... | ('%Y-%m-%d')
if self.first:
result[CITATION_FIRST_AUTHOR] = self.first.name
if self.last:
result[CITATION_LAST_AUTHOR] = self.last.name
if self.authors:
result[CITATION_AUTHORS] = sorted(
author.name
for author in ... | 82 | 82 | 276 | 4 | 77 | aman527/pybel | src/pybel/manager/models.py | Python | Evidence | Evidence | 480 | 513 | 480 | 480 | 5f05ae7e60db299d140cc13c98c28c59e8bd97e9 | bigcode/the-stack | train |
3a7154315e2da83317a9af67 | train | class | class Citation(Base):
"""The information about the citations that are used to prove a specific relation are stored in this table."""
__tablename__ = CITATION_TABLE_NAME
id = Column(Integer, primary_key=True)
db = Column(String(16), nullable=False, doc='Type of the stored publication e.g. PubMe... | class Citation(Base):
| """The information about the citations that are used to prove a specific relation are stored in this table."""
__tablename__ = CITATION_TABLE_NAME
id = Column(Integer, primary_key=True)
db = Column(String(16), nullable=False, doc='Type of the stored publication e.g. PubMed')
db_id = Column... | AUTHOR_CITATION_TABLE_NAME, Base.metadata,
Column('author_id', Integer, ForeignKey('{}.id'.format(AUTHOR_TABLE_NAME)), primary_key=True),
Column('citation_id', Integer, ForeignKey('{}.id'.format(CITATION_TABLE_NAME)), primary_key=True),
)
class Author(Base):
"""Contains all author names."""
... | 204 | 204 | 681 | 4 | 199 | aman527/pybel | src/pybel/manager/models.py | Python | Citation | Citation | 397 | 477 | 397 | 397 | 30761adf0f632950ba9d393b96cc7dcc84ac59e4 | bigcode/the-stack | train |
54255a89816ed7bac4d51f3d | train | class | class Author(Base):
"""Contains all author names."""
__tablename__ = AUTHOR_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False, unique=True, index=True)
@classmethod
def name_contains(cls, name_query: str):
"""Build a filter for autho... | class Author(Base):
| """Contains all author names."""
__tablename__ = AUTHOR_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False, unique=True, index=True)
@classmethod
def name_contains(cls, name_query: str):
"""Build a filter for authors whose names contai... | _CITATION_TABLE_NAME, Base.metadata,
Column('author_id', Integer, ForeignKey('{}.id'.format(AUTHOR_TABLE_NAME)), primary_key=True),
Column('citation_id', Integer, ForeignKey('{}.id'.format(CITATION_TABLE_NAME)), primary_key=True),
)
class Author(Base):
| 64 | 64 | 139 | 4 | 60 | aman527/pybel | src/pybel/manager/models.py | Python | Author | Author | 375 | 394 | 375 | 375 | 8cf85a6b8956bdaddebb42d485db97d2770797e7 | bigcode/the-stack | train |
5d576bc437f2fdf82821c333 | train | class | class Network(Base):
"""Represents a collection of edges, specified by a BEL Script."""
__tablename__ = NETWORK_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False, index=True, doc='Name of the given Network (from the BEL file)')
version = Column(Stri... | class Network(Base):
| """Represents a collection of edges, specified by a BEL Script."""
__tablename__ = NETWORK_TABLE_NAME
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False, index=True, doc='Name of the given Network (from the BEL file)')
version = Column(String(255), nullable=Fals... | def name_contains(cls, name_query: str):
"""Make a filter if the name contains a certain substring."""
return cls.name.contains(name_query)
def __str__(self):
return '[{namespace_id}]{namespace_name}:[{identifier}]{name}'.format(
namespace_id=self.namespace.id,
... | 218 | 218 | 729 | 4 | 214 | aman527/pybel | src/pybel/manager/models.py | Python | Network | Network | 216 | 307 | 216 | 216 | 1275e3d101e0d87fb1313a238331cd89787f0e1f | bigcode/the-stack | train |
99a1ea93dd8aff60e1b29adb | train | function | def count_file_lines(file_path):
"""
Counts the number of lines in a file using wc utility.
:param file_path: path to file
:return: int, no of lines
"""
num = subprocess.check_output(['wc', '-l', file_path])
num = num.decode('utf-8').split(' ')
return int(num[0])
| def count_file_lines(file_path):
| """
Counts the number of lines in a file using wc utility.
:param file_path: path to file
:return: int, no of lines
"""
num = subprocess.check_output(['wc', '-l', file_path])
num = num.decode('utf-8').split(' ')
return int(num[0])
| _r = x_tz_matmul.reshape(length, batch_size, heads, -1)
x_tz_matmul_r_t = x_tz_matmul_r.permute(1, 2, 0, 3)
return x_tz_matmul_r_t
def count_file_lines(file_path):
| 64 | 64 | 79 | 7 | 56 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | count_file_lines | count_file_lines | 87 | 95 | 87 | 87 | 2de069fd86dd30ded16915df477657316b6fb106 | bigcode/the-stack | train |
0170962fa20ad0d8cbade2e3 | train | function | def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return (torch.arange(0, max_len, device=lengths.device) # (0 for pad positions)
.type_as(lengths)
.repe... | def sequence_mask(lengths, max_len=None):
| """
Creates a boolean mask from sequence lengths.
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max()
return (torch.arange(0, max_len, device=lengths.device) # (0 for pad positions)
.type_as(lengths)
.repeat(batch_size, 1)
.lt(lengths.... | Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments), \
"Not all arguments have the same value: " + str(args)
def sequence_mask(lengths, max_len=None):
| 64 | 64 | 91 | 10 | 54 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | sequence_mask | sequence_mask | 18 | 27 | 18 | 18 | 87317bc2ba96c00ec6d8b338df2034c1ec888d52 | bigcode/the-stack | train |
bc349c1a59ccf6be02d70486 | train | function | def aeq(*args):
"""
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments), \
"Not all arguments have the same value: " + str(args)
| def aeq(*args):
| """
Assert all arguments have the same value
"""
arguments = (arg for arg in args)
first = next(arguments)
assert all(arg == first for arg in arguments), \
"Not all arguments have the same value: " + str(args)
| # src: https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/utils/misc.py
# -*- coding: utf-8 -*-
import torch
import subprocess
def aeq(*args):
| 45 | 64 | 62 | 6 | 38 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | aeq | aeq | 8 | 15 | 8 | 8 | 76092db06f533f793a5d66b0c4ca85644ccd1fe4 | bigcode/the-stack | train |
25b87b5d7c7a7edd3f561d61 | train | function | def relative_matmul(x, z, transpose):
"""Helper function for relative positions attention."""
batch_size = x.shape[0]
heads = x.shape[1]
length = x.shape[2]
x_t = x.permute(2, 0, 1, 3)
x_t_r = x_t.reshape(length, heads * batch_size, -1)
if transpose:
z_t = z.transpose(1, 2)
... | def relative_matmul(x, z, transpose):
| """Helper function for relative positions attention."""
batch_size = x.shape[0]
heads = x.shape[1]
length = x.shape[2]
x_t = x.permute(2, 0, 1, 3)
x_t_r = x_t.reshape(length, heads * batch_size, -1)
if transpose:
z_t = z.transpose(1, 2)
x_tz_matmul = torch.matmul(x_t_... | )
distance_mat_clipped = torch.clamp(distance_mat,
min=-max_relative_positions,
max=max_relative_positions)
# Shift values to be >= 0
final_mat = distance_mat_clipped + max_relative_positions
return final_mat
def relativ... | 64 | 64 | 195 | 10 | 53 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | relative_matmul | relative_matmul | 70 | 84 | 70 | 70 | 2e61b5165bb1a0fab9647498fbf9b5ddef2be455 | bigcode/the-stack | train |
44fc5509cd428fcf28a889ef | train | function | def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
"""
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(perm).contiguous()
out_size = list(x.size())
out_size[0] *= count
batch = x.size(0)
... | def tile(x, count, dim=0):
| """
Tiles x on dimension dim count times.
"""
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(perm).contiguous()
out_size = list(x.size())
out_size[0] *= count
batch = x.size(0)
x = x.view(batch, -1) \
... | lengths.max()
return (torch.arange(0, max_len, device=lengths.device) # (0 for pad positions)
.type_as(lengths)
.repeat(batch_size, 1)
.lt(lengths.unsqueeze(1)))
def tile(x, count, dim=0):
| 63 | 64 | 171 | 10 | 53 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | tile | tile | 30 | 49 | 30 | 30 | 4f69de1cda9a4c116a33cd096afd8918e17fd581 | bigcode/the-stack | train |
4bc99e3364db791e14d0ef97 | train | function | def generate_relative_positions_matrix(length, max_relative_positions,
cache=False):
"""Generate the clipped relative positions matrix
for a given length and maximum relative positions"""
if cache:
distance_mat = torch.arange(-length + 1, 1, 1).unsqueez... | def generate_relative_positions_matrix(length, max_relative_positions,
cache=False):
| """Generate the clipped relative positions matrix
for a given length and maximum relative positions"""
if cache:
distance_mat = torch.arange(-length + 1, 1, 1).unsqueeze(0)
else:
range_vec = torch.arange(length)
range_mat = range_vec.unsqueeze(-1).expand(-1, length).tran... | 1) \
.transpose(0, 1) \
.contiguous() \
.view(*out_size)
if dim != 0:
x = x.permute(perm).contiguous()
return x
def generate_relative_positions_matrix(length, max_relative_positions,
cache=False):
| 64 | 64 | 164 | 15 | 48 | wasiahmad/PrivacyQA | nqa/utils/misc.py | Python | generate_relative_positions_matrix | generate_relative_positions_matrix | 52 | 67 | 52 | 53 | 0af04ba021a25532ee0756bcc87262ff72d48fd0 | bigcode/the-stack | train |
06a90ae19be62b34d30c69b4 | train | function | def test_stream_invalid_type():
testee = Stream(name="stream1", operator={})
with pytest.raises(PipelineException) as ex:
testee.validate()
assert "is not of type" in str(ex)
| def test_stream_invalid_type():
| testee = Stream(name="stream1", operator={})
with pytest.raises(PipelineException) as ex:
testee.validate()
assert "is not of type" in str(ex)
| import pytest
from pipeline import Stream
from pipeline.exception import PipelineException
from pipeline.operators import (
FileInputOperator,
InputOperator,
InputOutputOperator,
Operator,
)
from pipeline.pipeline import Pipeline
def test_stream_invalid_type():
| 51 | 64 | 47 | 6 | 44 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_stream_invalid_type | test_stream_invalid_type | 13 | 17 | 13 | 13 | 50f29f2de18265b156247980bf1051f19d0b15c4 | bigcode/the-stack | train |
56c72d80565a401024f4268c | train | function | def test_pipeline_invalid3():
pipeline = Pipeline(
Stream("stream1", FileInputOperator(path="/foo")),
Stream("stream1", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "Name of streams in pipeline should be unique." in str(ex)
| def test_pipeline_invalid3():
| pipeline = Pipeline(
Stream("stream1", FileInputOperator(path="/foo")),
Stream("stream1", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "Name of streams in pipeline should be unique." in str(ex)
| = Pipeline(
Stream("stream1", FooInputOutputOperator()),
Stream("stream2", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert f"First stream should be {InputOperator}" in str(ex)
def test_pipeline_invalid3():
| 64 | 64 | 68 | 6 | 58 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_pipeline_invalid3 | test_pipeline_invalid3 | 47 | 54 | 47 | 47 | f1290af6ff00c12cb5d900b7dde3228466d92b12 | bigcode/the-stack | train |
36fc7365aeb007419d89c146 | train | function | def test_pipeline_invalid2():
pipeline = Pipeline(
Stream("stream1", FooInputOutputOperator()),
Stream("stream2", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert f"First stream should be {InputOperator}" in str(ex)
| def test_pipeline_invalid2():
| pipeline = Pipeline(
Stream("stream1", FooInputOutputOperator()),
Stream("stream2", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert f"First stream should be {InputOperator}" in str(ex)
| stream1", FileInputOperator(path="/foo")))
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "At least 2 streams are required to" in str(ex)
class FooInputOutputOperator(InputOutputOperator):
def process(self):
pass
def test_pipeline_invalid2():
| 64 | 64 | 66 | 6 | 57 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_pipeline_invalid2 | test_pipeline_invalid2 | 37 | 44 | 37 | 37 | 47205b00254711dd1e0a9963926fe7a7b431854e | bigcode/the-stack | train |
49d03b0ff953841b6850afe6 | train | function | def test_stream_valid_type():
testee = Stream(name="stream1", operator=FileInputOperator(path="/foo"))
testee.validate()
| def test_stream_valid_type():
| testee = Stream(name="stream1", operator=FileInputOperator(path="/foo"))
testee.validate()
| ,
Operator,
)
from pipeline.pipeline import Pipeline
def test_stream_invalid_type():
testee = Stream(name="stream1", operator={})
with pytest.raises(PipelineException) as ex:
testee.validate()
assert "is not of type" in str(ex)
def test_stream_valid_type():
| 64 | 64 | 30 | 6 | 58 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_stream_valid_type | test_stream_valid_type | 20 | 22 | 20 | 20 | a91cb839f16bfe2243abfbf15b5e8af1628db86d | bigcode/the-stack | train |
c59f55df3d7241fa34c396da | train | class | class FooInputOutputOperator(InputOutputOperator):
def process(self):
pass
| class FooInputOutputOperator(InputOutputOperator):
| def process(self):
pass
| .validate()
def test_pipeline_invalid1():
pipeline = Pipeline(Stream("stream1", FileInputOperator(path="/foo")))
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "At least 2 streams are required to" in str(ex)
class FooInputOutputOperator(InputOutputOperator):
| 64 | 64 | 17 | 9 | 55 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | FooInputOutputOperator | FooInputOutputOperator | 32 | 34 | 32 | 32 | 23dda91fe5d757e147e3bb0b45f17da7c9580fd8 | bigcode/the-stack | train |
ce0bfe359fd30e5ea34d4903 | train | function | def test_pipeline_invalid1():
pipeline = Pipeline(Stream("stream1", FileInputOperator(path="/foo")))
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "At least 2 streams are required to" in str(ex)
| def test_pipeline_invalid1():
| pipeline = Pipeline(Stream("stream1", FileInputOperator(path="/foo")))
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "At least 2 streams are required to" in str(ex)
| with pytest.raises(PipelineException) as ex:
testee.validate()
assert "is not of type" in str(ex)
def test_stream_valid_type():
testee = Stream(name="stream1", operator=FileInputOperator(path="/foo"))
testee.validate()
def test_pipeline_invalid1():
| 64 | 64 | 53 | 6 | 58 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_pipeline_invalid1 | test_pipeline_invalid1 | 25 | 29 | 25 | 25 | 8aca9da97a313ac542e5456399a67b30cc3e371d | bigcode/the-stack | train |
e79aa1e79764f6d28a1159f2 | train | function | def test_pipeline_valid():
pipeline = Pipeline(
Stream("stream1", FileInputOperator(path="/foo")),
Stream("stream2", FooInputOutputOperator()),
Stream("stream3", FooInputOutputOperator()),
)
pipeline.validate()
| def test_pipeline_valid():
| pipeline = Pipeline(
Stream("stream1", FileInputOperator(path="/foo")),
Stream("stream2", FooInputOutputOperator()),
Stream("stream3", FooInputOutputOperator()),
)
pipeline.validate()
| Pipeline(
Stream("stream1", FileInputOperator(path="/foo")),
Stream("stream1", FooInputOutputOperator()),
)
with pytest.raises(PipelineException) as ex:
pipeline.validate()
assert "Name of streams in pipeline should be unique." in str(ex)
def test_pipeline_valid():
| 64 | 64 | 51 | 5 | 59 | prashanthsandela/python-pipeline | tests/test_stream.py | Python | test_pipeline_valid | test_pipeline_valid | 57 | 63 | 57 | 57 | 57950cc05ae1baf693f1203d5d8af2c7bb617319 | bigcode/the-stack | train |
a8aca9b3e987b436afd6e847 | train | function | def build_resolver(uri, environ):
if uri.startswith("http") and uri.endswith(".git"):
return GitDataResolver(uri, environ)
else:
return FileDataResolver(uri)
| def build_resolver(uri, environ):
| if uri.startswith("http") and uri.endswith(".git"):
return GitDataResolver(uri, environ)
else:
return FileDataResolver(uri)
| os.path.abspath(filename)
def get_filecontent(self, name):
filename = self.get_filename(name=name)
with open(filename, mode='rb') as f:
return f.read()
def get_directory(self, name):
return self.get_filename(name=name)
def build_resolver(uri, environ):
| 64 | 64 | 40 | 8 | 56 | rhpvorderman/galaxy | lib/galaxy/tool_util/verify/test_data.py | Python | build_resolver | build_resolver | 56 | 60 | 56 | 56 | 28e8a9a686dad5d897ba6094c121a8c6ef4e2c55 | bigcode/the-stack | train |
273f3f4418e721dab0dace6b | train | class | class GitDataResolver(FileDataResolver):
def __init__(self, repository, environ):
self.repository = repository
self.updated = False
repo_cache = environ.get("GALAXY_TEST_DATA_REPO_CACHE", "test-data-cache")
m = hashlib.md5()
m.update(smart_str(repository))
repo_path ... | class GitDataResolver(FileDataResolver):
| def __init__(self, repository, environ):
self.repository = repository
self.updated = False
repo_cache = environ.get("GALAXY_TEST_DATA_REPO_CACHE", "test-data-cache")
m = hashlib.md5()
m.update(smart_str(repository))
repo_path = os.path.join(repo_cache, m.hexdigest())
... | uri.startswith("http") and uri.endswith(".git"):
return GitDataResolver(uri, environ)
else:
return FileDataResolver(uri)
class FileDataResolver:
def __init__(self, file_dir):
self.file_dir = file_dir
def exists(self, filename):
path = os.path.abspath(self.path(filename))... | 112 | 112 | 376 | 8 | 104 | rhpvorderman/galaxy | lib/galaxy/tool_util/verify/test_data.py | Python | GitDataResolver | GitDataResolver | 76 | 122 | 76 | 77 | 29b0ad1c39d25cbcbf99700f0107ba881bef4d5a | bigcode/the-stack | train |
ff801f82877702fcf1aad0ed | train | class | class TestDataResolver:
def __init__(self, file_dirs=None, env_var='GALAXY_TEST_FILE_DIR', environ=os.environ):
if file_dirs is None:
file_dirs = environ.get(env_var, None)
if file_dirs is None:
file_dirs = "test-data,https://github.com/galaxyproject/galaxy-test-data.git"
... | class TestDataResolver:
| def __init__(self, file_dirs=None, env_var='GALAXY_TEST_FILE_DIR', environ=os.environ):
if file_dirs is None:
file_dirs = environ.get(env_var, None)
if file_dirs is None:
file_dirs = "test-data,https://github.com/galaxyproject/galaxy-test-data.git"
if file_dirs:
... | git-dir $dir/.git merge origin/master"
)
UPDATE_FAILED_TEMPLATE = Template(
"Warning failed to update test repository $dir - "
"update stdout was [$stdout] and stderr was [$stderr]."
)
LIST_SEP = re.compile(r"\s*,\s*")
class TestDataResolver:
| 64 | 64 | 212 | 5 | 59 | rhpvorderman/galaxy | lib/galaxy/tool_util/verify/test_data.py | Python | TestDataResolver | TestDataResolver | 27 | 53 | 27 | 28 | 1b1eb272824e8f7505c754db4807ea615b4e2249 | bigcode/the-stack | train |
5318a004d97a5b3c9229772b | train | class | class FileDataResolver:
def __init__(self, file_dir):
self.file_dir = file_dir
def exists(self, filename):
path = os.path.abspath(self.path(filename))
return os.path.exists(path) and in_directory(path, self.file_dir)
def path(self, filename):
return os.path.join(self.file_... | class FileDataResolver:
| def __init__(self, file_dir):
self.file_dir = file_dir
def exists(self, filename):
path = os.path.abspath(self.path(filename))
return os.path.exists(path) and in_directory(path, self.file_dir)
def path(self, filename):
return os.path.join(self.file_dir, filename)
| f.read()
def get_directory(self, name):
return self.get_filename(name=name)
def build_resolver(uri, environ):
if uri.startswith("http") and uri.endswith(".git"):
return GitDataResolver(uri, environ)
else:
return FileDataResolver(uri)
class FileDataResolver:
| 64 | 64 | 74 | 5 | 59 | rhpvorderman/galaxy | lib/galaxy/tool_util/verify/test_data.py | Python | FileDataResolver | FileDataResolver | 63 | 73 | 63 | 64 | e8008209144fc9adb86c8773023f69af13060b9e | bigcode/the-stack | train |
a6d259fd163df13f5fc2e100 | train | class | class TestPSPassWithBow(unittest.TestCase):
def net(self):
def get_acc(cos_q_nt, cos_q_pt, batch_size):
cond = fluid.layers.less_than(cos_q_nt, cos_q_pt)
cond = fluid.layers.cast(cond, dtype='float64')
cond_3 = fluid.layers.reduce_sum(cond)
acc = fluid.layers.... | class TestPSPassWithBow(unittest.TestCase):
| def net(self):
def get_acc(cos_q_nt, cos_q_pt, batch_size):
cond = fluid.layers.less_than(cos_q_nt, cos_q_pt)
cond = fluid.layers.cast(cond, dtype='float64')
cond_3 = fluid.layers.reduce_sum(cond)
acc = fluid.layers.elementwise_div(
cond_3,
... | .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 under the License is distributed on an "AS IS" BASIS,
... | 256 | 256 | 1,222 | 10 | 245 | licanisme/Paddle | python/paddle/fluid/tests/unittests/test_dist_fleet_ps3.py | Python | TestPSPassWithBow | TestPSPassWithBow | 34 | 170 | 34 | 34 | 177d7aa2e531eef864d403c662d01186162e72db | bigcode/the-stack | train |
ffcd437ad0e9472028b7d9cc | train | class | class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['video4k.to']
self.base_link = 'http://video4k.to'
self.request_link = '/request'
def movie(self, imdb, title, localtitle, aliases, year):
try:
return urllib.ur... | class source:
| def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['video4k.to']
self.base_link = 'http://video4k.to'
self.request_link = '/request'
def movie(self, imdb, title, localtitle, aliases, year):
try:
return urllib.urlencode({'mID'... |
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------... | 143 | 143 | 479 | 3 | 139 | parser4life/tantrumrepo | script.module.placenta/lib/resources/lib/sources/de/video4k.py | Python | source | source | 24 | 82 | 24 | 24 | 9cbf69fb277496eca0f4e3411538813db9bc87e6 | bigcode/the-stack | train |
330afc976e2ee83552cb03f4 | train | class | class PXEPrivateMethodsTestCase(db_base.DbTestCase):
def setUp(self):
super(PXEPrivateMethodsTestCase, self).setUp()
n = {
'driver': 'fake_pxe',
'instance_info': INST_INFO_DICT,
'driver_info': DRV_INFO_DICT,
}
mgr_utils.mock_the_extension_ma... | class PXEPrivateMethodsTestCase(db_base.DbTestCase):
| def setUp(self):
super(PXEPrivateMethodsTestCase, self).setUp()
n = {
'driver': 'fake_pxe',
'instance_info': INST_INFO_DICT,
'driver_info': DRV_INFO_DICT,
}
mgr_utils.mock_the_extension_manager(driver="fake_pxe")
self.dbapi = dbapi.ge... | _driver_info_missing_deploy_kernel(self):
# make sure error is raised when info is missing
info = dict(DRV_INFO_DICT)
del info['pxe_deploy_kernel']
node = obj_utils.create_test_node(self.context, driver_info=info)
self.assertRaises(exception.MissingParameterValue,
... | 255 | 256 | 1,815 | 13 | 242 | hongbin/ironic | ironic/tests/drivers/test_pxe.py | Python | PXEPrivateMethodsTestCase | PXEPrivateMethodsTestCase | 103 | 293 | 103 | 104 | 283d559146429fe22d420a394502e609572f62d5 | bigcode/the-stack | train |
87ea1c21e6a543f61d30d6da | train | class | class PXEDriverTestCase(db_base.DbTestCase):
def setUp(self):
super(PXEDriverTestCase, self).setUp()
self.context = context.get_admin_context()
self.context.auth_token = '4562138218392831'
self.temp_dir = tempfile.mkdtemp()
self.config(tftp_root=self.temp_dir, group='pxe')
... | class PXEDriverTestCase(db_base.DbTestCase):
| def setUp(self):
super(PXEDriverTestCase, self).setUp()
self.context = context.get_admin_context()
self.context.auth_token = '4562138218392831'
self.temp_dir = tempfile.mkdtemp()
self.config(tftp_root=self.temp_dir, group='pxe')
self.temp_dir = tempfile.mkdtemp()
... | ')
fake_pxe_info = {'foo': 'bar'}
expected_path = os.path.join(CONF.pxe.tftp_root, self.node.uuid)
pxe._cache_ramdisk_kernel(self.context, self.node, fake_pxe_info)
mock_ensure_tree.assert_called_with(expected_path)
mock_fetch_image.assert_called_once_with(self.context, mock.ANY... | 256 | 256 | 4,736 | 12 | 244 | hongbin/ironic | ironic/tests/drivers/test_pxe.py | Python | PXEDriverTestCase | PXEDriverTestCase | 296 | 785 | 296 | 297 | 896c55d619317d734b06f974d15e9271e4321339 | bigcode/the-stack | train |
dffb4a5472c0e68a67b537e2 | train | class | class PXEValidateParametersTestCase(base.TestCase):
def setUp(self):
super(PXEValidateParametersTestCase, self).setUp()
self.context = context.get_admin_context()
self.dbapi = dbapi.get_instance()
def test__parse_deploy_info(self):
# make sure we get back the expected things
... | class PXEValidateParametersTestCase(base.TestCase):
| def setUp(self):
super(PXEValidateParametersTestCase, self).setUp()
self.context = context.get_admin_context()
self.dbapi = dbapi.get_instance()
def test__parse_deploy_info(self):
# make sure we get back the expected things
node = obj_utils.create_test_node(self.context,... |
from ironic.drivers.modules import pxe
from ironic.openstack.common import context
from ironic.openstack.common import fileutils
from ironic.openstack.common import jsonutils as json
from ironic.tests import base
from ironic.tests.conductor import utils as mgr_utils
from ironic.tests.db import base as db_base
from iro... | 128 | 128 | 429 | 11 | 117 | hongbin/ironic | ironic/tests/drivers/test_pxe.py | Python | PXEValidateParametersTestCase | PXEValidateParametersTestCase | 55 | 100 | 55 | 56 | d2601bffb5634bed36f41511daae053216a86a53 | bigcode/the-stack | train |
30187b3f97f4285172cc1f0f | train | function | @click.command()
@click.argument("filename")
def main(filename):
filename = Path(filename)
commands = filename.read_text().split("\n")
commands = [cmd.split(" ") for cmd in commands]
horizontal = 0
depth = 0
aim = 0
for cmd, x in commands:
x = int(x)
if cmd == "down":
... | @click.command()
@click.argument("filename")
def main(filename):
| filename = Path(filename)
commands = filename.read_text().split("\n")
commands = [cmd.split(" ") for cmd in commands]
horizontal = 0
depth = 0
aim = 0
for cmd, x in commands:
x = int(x)
if cmd == "down":
aim += x
elif cmd == "up":
aim -= x
... | from pathlib import Path
import click
@click.command()
@click.argument("filename")
def main(filename):
| 20 | 64 | 126 | 12 | 7 | martinsbruveris/advent-of-code | code/day_02b.py | Python | main | main | 6 | 25 | 6 | 8 | 05bf9c5e1b961892ff785610baf5f9c427c145aa | bigcode/the-stack | train |
623332992ff332f54f0e4a09 | train | class | class TemplateCleaner(object):
def __init__(self, text):
self.cleaned_text = text
def cleaner(self, stri):
sents = nltk.tokenize.sent_tokenize(self.cleaned_text)
word_dump = []
for sent in sents:
if stri in sent:
ss = re.split(re.escape(stri), sent)
... | class TemplateCleaner(object):
| def __init__(self, text):
self.cleaned_text = text
def cleaner(self, stri):
sents = nltk.tokenize.sent_tokenize(self.cleaned_text)
word_dump = []
for sent in sents:
if stri in sent:
ss = re.split(re.escape(stri), sent)
word_dump.append... | ceptron_tagger')
nltk.download('wordnet')
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
SPELL = Speller(lang='en')
class TemplateCleaner(object):
| 64 | 64 | 102 | 5 | 59 | varunnathan/NLP | src/preprocessing/text_preprocessing.py | Python | TemplateCleaner | TemplateCleaner | 17 | 30 | 17 | 17 | aa4cfcf4fc81a50abe71829b3a9ed54004c5a3be | bigcode/the-stack | train |
23454dbb71a0c7b3a4e3ff3d | train | function | def regex_cleaning(text):
text = re.sub(r'http\S+', ' ', text)
text = re.sub(r'www\S+\.com', ' ', text)
text = re.sub(r'[!,\#()]', ' ', text)
return text
| def regex_cleaning(text):
| text = re.sub(r'http\S+', ' ', text)
text = re.sub(r'www\S+\.com', ' ', text)
text = re.sub(r'[!,\#()]', ' ', text)
return text
| word_dump = []
for sent in sents:
if stri in sent:
ss = re.split(re.escape(stri), sent)
word_dump.append(ss[0])
else:
word_dump.append(sent)
self.cleaned_text = " ".join(word_dump)
def regex_cleaning(text):
| 64 | 64 | 57 | 6 | 58 | varunnathan/NLP | src/preprocessing/text_preprocessing.py | Python | regex_cleaning | regex_cleaning | 33 | 37 | 33 | 33 | 8dca80fadc6a16d1deafbf939e406498189bd6da | bigcode/the-stack | train |
85efab0da0be707e1a8eee78 | train | function | def preprocess(text):
# pos - keep only nouns and adjectives
text = " ".join(t[0] for t in nltk.pos_tag(nltk.wordpunct_tokenize(text)) if t[1].startswith('N') or t[1].startswith('J'))
# lower casing
text = text.strip().lower()
# contraction
# regex cleaning
# remove numerals
text = r... | def preprocess(text):
# pos - keep only nouns and adjectives
| text = " ".join(t[0] for t in nltk.pos_tag(nltk.wordpunct_tokenize(text)) if t[1].startswith('N') or t[1].startswith('J'))
# lower casing
text = text.strip().lower()
# contraction
# regex cleaning
# remove numerals
text = re.sub(r'[0-9]+', ' ', text)
# spell correction
text = " ... | text = re.sub(r'http\S+', ' ', text)
text = re.sub(r'www\S+\.com', ' ', text)
text = re.sub(r'[!,\#()]', ' ', text)
return text
def preprocess(text):
# pos - keep only nouns and adjectives
| 64 | 64 | 127 | 14 | 49 | varunnathan/NLP | src/preprocessing/text_preprocessing.py | Python | preprocess | preprocess | 40 | 55 | 40 | 41 | 2fc0e607864ef2d9f17cc1aa9f808769ef20a3d6 | bigcode/the-stack | train |
8baac86127c5070b62b07a45 | train | class | class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20181105_1041'),
]
operations = [
migrations.AddField(
model_name='user',
name='title',
field=models.CharField(default=1, max_length=50, unique=True),
preserve_de... | class Migration(migrations.Migration):
| dependencies = [
('accounts', '0002_auto_20181105_1041'),
]
operations = [
migrations.AddField(
model_name='user',
name='title',
field=models.CharField(default=1, max_length=50, unique=True),
preserve_default=False,
),
migratio... | # Generated by Django 2.1.1 on 2018-11-05 10:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 118 | 7 | 37 | nurpeiis/RED | accounts/migrations/0003_auto_20181105_1053.py | Python | Migration | Migration | 7 | 25 | 7 | 8 | 48366e3e9050bef134f15502fbf3cc23791dea42 | bigcode/the-stack | train |
4cd9917c7b6d3c7e1c01fcc4 | train | function | def get_vector(request, size):
img = Image.open(request.FILES['file'])
img.thumbnail(size)
vector = np.array(img).reshape(-1)
vector = vector.tolist()
for i in range(len(vector)):
vector[i] = vector[i] / 255
return str(vector)
| def get_vector(request, size):
| img = Image.open(request.FILES['file'])
img.thumbnail(size)
vector = np.array(img).reshape(-1)
vector = vector.tolist()
for i in range(len(vector)):
vector[i] = vector[i] / 255
return str(vector)
| import numpy as np
from PIL import Image
def get_vector(request, size):
| 17 | 64 | 65 | 7 | 9 | cebanauskes/test_vectors | api/utils.py | Python | get_vector | get_vector | 4 | 11 | 4 | 4 | cb085d7d188ff41a7cd15c610339a9bdff38a608 | bigcode/the-stack | train |
2371fd8652f8511bbedec886 | train | function | def test_rabbit_consumption():
"""
Test the containerized consumers.
1. We create the rabbitmq server and expose its main port.
2. We declare a sample queue `testing` and push a message.
3. The container is built and run. The container connects to the RabbitMQ Server, consumes the message prints th... | def test_rabbit_consumption():
| """
Test the containerized consumers.
1. We create the rabbitmq server and expose its main port.
2. We declare a sample queue `testing` and push a message.
3. The container is built and run. The container connects to the RabbitMQ Server, consumes the message prints the ouput.
4. The test is suc... | = os.getcwd() + dockerfile_path
client.images.build(path=docker_path, tag=tag)
container_consumer = client.containers.run(tag, name='consumer', network_mode='host', detach=True)
time.sleep(12)
return container_consumer
def test_rabbit_consumption():
| 64 | 64 | 203 | 7 | 56 | smartassist-tech/py-consumer-docker | tests/test_rabbitmq.py | Python | test_rabbit_consumption | test_rabbit_consumption | 48 | 73 | 48 | 48 | 280408ef31b427f70fc5e619b0b2ebfd762cbf15 | bigcode/the-stack | train |
10287f9f9b4d1bbe3e000482 | train | function | def _set_consumer_container(dockerfile_path, tag='docker_python_consumer_testimage'):
"""
Run the consumer container and wait for a few messages to be consumed and printed
:param dockerfile_path:
:param tag:
:return:
"""
docker_path = os.getcwd() + dockerfile_path
client.images.build(pa... | def _set_consumer_container(dockerfile_path, tag='docker_python_consumer_testimage'):
| """
Run the consumer container and wait for a few messages to be consumed and printed
:param dockerfile_path:
:param tag:
:return:
"""
docker_path = os.getcwd() + dockerfile_path
client.images.build(path=docker_path, tag=tag)
container_consumer = client.containers.run(tag, name='con... | '))
channel = connection.channel()
channel.queue_declare('testing')
channel.basic_publish(exchange='', routing_key='testing', body='Hello World! From Producer')
connection.close()
return container_rabbit
def _set_consumer_container(dockerfile_path, tag='docker_python_consumer_testimage'):
| 64 | 64 | 117 | 20 | 43 | smartassist-tech/py-consumer-docker | tests/test_rabbitmq.py | Python | _set_consumer_container | _set_consumer_container | 32 | 45 | 32 | 32 | f416ab3a7ba81baa946d57d0823a6947126fe796 | bigcode/the-stack | train |
6963290d060cd7f10f467aff | train | function | def test_example_app_root_rabbit():
container_rabbit = _set_rabbitmq_container()
container_consumer = _set_consumer_container(dockerfile_path='/examples/example_app_root')
logs: str = container_consumer.logs()
logs = logs.decode('utf-8')
assert 'Message Consumed' in logs
assert 'Message Succe... | def test_example_app_root_rabbit():
| container_rabbit = _set_rabbitmq_container()
container_consumer = _set_consumer_container(dockerfile_path='/examples/example_app_root')
logs: str = container_consumer.logs()
logs = logs.decode('utf-8')
assert 'Message Consumed' in logs
assert 'Message Success' in logs or 'Message Failure' in ... | .decode('utf-8')
assert 'Consumer Receives' in logs
assert 'Hello World! From Producer' in logs
container_rabbit.stop()
container_consumer.stop()
container_rabbit.remove(force=True)
container_consumer.remove(force=True)
def test_example_app_root_rabbit():
| 64 | 64 | 110 | 8 | 56 | smartassist-tech/py-consumer-docker | tests/test_rabbitmq.py | Python | test_example_app_root_rabbit | test_example_app_root_rabbit | 76 | 91 | 76 | 76 | f21bcba06bd05a1d8266d9ca9a3f069fa1212fb3 | bigcode/the-stack | train |
48e141f46b2380e5470e2485 | train | function | def _set_rabbitmq_container():
"""
Run a RabbitMQ container and create a queue named `testing`.
:return:
"""
container_rabbit = client.containers.run('rabbitmq:alpine', ports={'5672': '5672'},
name='rabbit', detach=True)
time.sleep(12)
print(conta... | def _set_rabbitmq_container():
| """
Run a RabbitMQ container and create a queue named `testing`.
:return:
"""
container_rabbit = client.containers.run('rabbitmq:alpine', ports={'5672': '5672'},
name='rabbit', detach=True)
time.sleep(12)
print(container_rabbit.logs().decode('utf-... | import os
import time
import docker
import pika
client = docker.from_env()
def _set_rabbitmq_container():
| 26 | 64 | 140 | 8 | 18 | smartassist-tech/py-consumer-docker | tests/test_rabbitmq.py | Python | _set_rabbitmq_container | _set_rabbitmq_container | 10 | 29 | 10 | 10 | f62272c0ca061483ef45e721c5abb69a3585559d | bigcode/the-stack | train |
1a1d5870ce07909a31699d17 | train | class | class ResetInletVelocity(Equation):
def __init__(self, dest, sources, U, V, W):
self.U = U
self.V = V
self.W = W
super(ResetInletVelocity, self).__init__(dest, sources)
def loop(self, d_idx, d_u, d_v, d_w, d_x, d_y, d_z, d_xn, d_yn, d_zn):
d_u[d_idx] = self.U
d_... | class ResetInletVelocity(Equation):
| def __init__(self, dest, sources, U, V, W):
self.U = U
self.V = V
self.W = W
super(ResetInletVelocity, self).__init__(dest, sources)
def loop(self, d_idx, d_u, d_v, d_w, d_x, d_y, d_z, d_xn, d_yn, d_zn):
d_u[d_idx] = self.U
d_v[d_idx] = self.V
d_w[d_idx]... | += WIJ
def post_loop(self, d_idx, d_wij, d_uhat, d_rho):
if d_wij[d_idx] > 1e-14:
d_uhat[d_idx] /= d_wij[d_idx]
class ResetInletVelocity(Equation):
| 64 | 64 | 127 | 8 | 56 | deeptavker/pysph | pysph/examples/flow_past_cylinder_2d.py | Python | ResetInletVelocity | ResetInletVelocity | 57 | 68 | 57 | 57 | f82a325220551012dc46073e32f720eb30c626b4 | bigcode/the-stack | train |
1ef4f072509bb515a7198597 | train | class | class ExtrapolateUhat(Equation):
def initialize(self, d_idx, d_uhat, d_wij):
d_uhat[d_idx] = 0.0
d_wij[d_idx] = 0.0
def loop(self, d_idx, s_idx, d_uhat, s_uhat, d_wij, s_rho,
d_au, d_av, d_aw, WIJ, XIJ):
d_uhat[d_idx] += s_uhat[s_idx]*WIJ
d_wij[d_idx] += WIJ
de... | class ExtrapolateUhat(Equation):
| def initialize(self, d_idx, d_uhat, d_wij):
d_uhat[d_idx] = 0.0
d_wij[d_idx] = 0.0
def loop(self, d_idx, s_idx, d_uhat, s_uhat, d_wij, s_rho,
d_au, d_av, d_aw, WIJ, XIJ):
d_uhat[d_idx] += s_uhat[s_idx]*WIJ
d_wij[d_idx] += WIJ
def post_loop(self, d_idx, d_wij, d... | # Number of outlet layers
n_wall = 5
# Fluid mechanical/numerical parameters
rho = 1000
umax = 1.0
c0 = 10 * umax
p0 = rho * c0 * c0
class ExtrapolateUhat(Equation):
| 64 | 64 | 181 | 9 | 54 | deeptavker/pysph | pysph/examples/flow_past_cylinder_2d.py | Python | ExtrapolateUhat | ExtrapolateUhat | 42 | 54 | 42 | 42 | a69401c97ab6848c47d06861a231eded30d14782 | bigcode/the-stack | train |
2cad473b12062e7711c5c318 | train | class | class WindTunnel(Application):
def add_user_options(self, group):
group.add_argument(
"--re", action="store", type=float, dest="re", default=200,
help="Reynolds number (defaults to 200)."
)
group.add_argument(
"--hdx", action="store", type=float, dest="hdx... | class WindTunnel(Application):
| def add_user_options(self, group):
group.add_argument(
"--re", action="store", type=float, dest="re", default=200,
help="Reynolds number (defaults to 200)."
)
group.add_argument(
"--hdx", action="store", type=float, dest="hdx", default=1.5,
hel... | , d_idx, s_idx, d_uhat, s_uhat, d_wij, s_rho,
d_au, d_av, d_aw, WIJ, XIJ):
d_uhat[d_idx] += s_uhat[s_idx]*WIJ
d_wij[d_idx] += WIJ
def post_loop(self, d_idx, d_wij, d_uhat, d_rho):
if d_wij[d_idx] > 1e-14:
d_uhat[d_idx] /= d_wij[d_idx]
class ResetInletVelocity(Equa... | 256 | 256 | 2,702 | 5 | 250 | deeptavker/pysph | pysph/examples/flow_past_cylinder_2d.py | Python | WindTunnel | WindTunnel | 71 | 354 | 71 | 71 | 1f9fdb8a3f8990e959905cffeede36d0ae8e127d | bigcode/the-stack | train |
8489c4fdf8809014189608eb | train | function | def test_MonitorParameter(plot):
# Get a model and data
my_model, x, y = get_model_and_data()
# Test MonitorParameter
mp = MonitorParameter("Weight")
my_model.fit(x, y, batch_size=5, epochs=10, callbacks=[mp])
assert isinstance(mp.current_epoch, int)
assert mp.current_epoch == 10
asser... | def test_MonitorParameter(plot):
# Get a model and data
| my_model, x, y = get_model_and_data()
# Test MonitorParameter
mp = MonitorParameter("Weight")
my_model.fit(x, y, batch_size=5, epochs=10, callbacks=[mp])
assert isinstance(mp.current_epoch, int)
assert mp.current_epoch == 10
assert isinstance(mp.current_params, np.ndarray)
assert mp.cur... | import matplotlib.pyplot as plt
import numpy as np
from get_model_and_data import get_model_and_data
from probflow.callbacks import MonitorParameter
def test_MonitorParameter(plot):
# Get a model and data
| 45 | 74 | 249 | 15 | 29 | chiragnagpal/probflow | tests/unit/tensorflow/callbacks/test_monitor_parameter.py | Python | test_MonitorParameter | test_MonitorParameter | 8 | 40 | 8 | 10 | d45102bb2caf8d89f9ee0720639c3013182a0507 | bigcode/the-stack | train |
787d9393328e0e6ba305f1a2 | train | class | class ViewMem:
@staticmethod
def get_palette(num_colors: int) -> list:
if num_colors == 1:
return [.45]
if num_colors not in ViewMem.colors:
ViewMem.colors[num_colors] = [ViewMem.color_map(float(idx) / (num_colors - 1)) for idx in range(num_colors)]
return ViewMe... | class ViewMem:
@staticmethod
| def get_palette(num_colors: int) -> list:
if num_colors == 1:
return [.45]
if num_colors not in ViewMem.colors:
ViewMem.colors[num_colors] = [ViewMem.color_map(float(idx) / (num_colors - 1)) for idx in range(num_colors)]
return ViewMem.colors[num_colors]
colors =... | options import TrainOptions, Options
from constants import OUT_DIR
from show.view_utils import view
from custom_types import *
from process_data.mesh_loader import get_loader, AnotherLoaderWrap
from process_data.files_utils import collect, init_folders
import matplotlib.pyplot as plt
class ViewMem:
@staticmethod
| 64 | 64 | 156 | 8 | 55 | anidnerocram/pointgmm | eval_ae.py | Python | ViewMem | ViewMem | 12 | 31 | 12 | 14 | 453f0e81e9cd1977b2a61c1b7f69ce5163bf75c0 | bigcode/the-stack | train |
d3d11e08a6548833914e9f94 | train | function | def save_np_points(points_group, path: str, prefix: str, start_counts:int, trace: ViewMem) -> int :
for i, group in enumerate(zip(*points_group)):
if prefix in trace.save_separate:
saving_path = f'{path}{prefix}_{start_counts + i:03d}.npz'
else:
saving_path = f'{path}{prefix}... | def save_np_points(points_group, path: str, prefix: str, start_counts:int, trace: ViewMem) -> int :
| for i, group in enumerate(zip(*points_group)):
if prefix in trace.save_separate:
saving_path = f'{path}{prefix}_{start_counts + i:03d}.npz'
else:
saving_path = f'{path}{prefix}_{start_counts:03d}_{i:02d}.npz'
np.savez_compressed(saving_path, points=group[0], splits=gr... | , path, prefix: str, start_counts:int, _) -> int:
image.save(f'{path}{prefix}_{start_counts:03d}.png')
return 1
def save_np_points(points_group, path: str, prefix: str, start_counts:int, trace: ViewMem) -> int :
| 64 | 64 | 146 | 27 | 36 | anidnerocram/pointgmm | eval_ae.py | Python | save_np_points | save_np_points | 47 | 56 | 47 | 47 | c160fce8df5792c87216ecd6be18ef5a037d5e5a | bigcode/the-stack | train |
a2656e57c35d2257036dfa5b | train | function | def save_pil_image(image, path, prefix: str, start_counts:int, _) -> int:
image.save(f'{path}{prefix}_{start_counts:03d}.png')
return 1
| def save_pil_image(image, path, prefix: str, start_counts:int, _) -> int:
| image.save(f'{path}{prefix}_{start_counts:03d}.png')
return 1
| (splits: list) -> list:
palette = []
for split in splits:
num_colors = len(split) - 1
palette.append(ViewMem.get_palette(num_colors))
return palette
def save_pil_image(image, path, prefix: str, start_counts:int, _) -> int:
| 64 | 64 | 43 | 21 | 42 | anidnerocram/pointgmm | eval_ae.py | Python | save_pil_image | save_pil_image | 42 | 44 | 42 | 42 | 1ed6e2871e1aa809a3aaef3a9d8079bfb06eea27 | bigcode/the-stack | train |
b61ba2e12280c0099a6dc05f | train | function | def interpolate(encoder, decoder, args: Options, trace: ViewMem):
if trace.memory is None:
msg = '\tPlease choose number of interpolation: from 8 to 20\n\t'
num_interpulate = get_integer((7, 21), msg)
else:
num_interpulate = trace.memory[1]
z = get_z_by_id(encoder, args, 2, trace.las... | def interpolate(encoder, decoder, args: Options, trace: ViewMem):
| if trace.memory is None:
msg = '\tPlease choose number of interpolation: from 8 to 20\n\t'
num_interpulate = get_integer((7, 21), msg)
else:
num_interpulate = trace.memory[1]
z = get_z_by_id(encoder, args, 2, trace.last_idx, trace)
gms = decoder.interpulate(z, num_interpulate)
... | (splits_.squeeze(0).cpu().numpy())
palette = create_palettes(splits)
im, points = view(vs, splits, palette)
return True, (hgmms, ), im, (points, splits, palette)
def interpolate(encoder, decoder, args: Options, trace: ViewMem):
| 69 | 69 | 231 | 16 | 53 | anidnerocram/pointgmm | eval_ae.py | Python | interpolate | interpolate | 161 | 174 | 161 | 161 | 1baa78c9c55895d032aa6043fbe261e624dd1d74 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.