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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bc5897c95f80a7a513abd1a4 | train | class | class Cosmology(metaclass=abc.ABCMeta):
"""Base-class for all Cosmologies.
Parameters
----------
*args
Arguments into the cosmology; used by subclasses, not this base class.
name : str or None (optional, keyword-only)
The name of the cosmology.
meta : dict or None (optional, key... | class Cosmology(metaclass=abc.ABCMeta):
| """Base-class for all Cosmologies.
Parameters
----------
*args
Arguments into the cosmology; used by subclasses, not this base class.
name : str or None (optional, keyword-only)
The name of the cosmology.
meta : dict or None (optional, keyword-only)
Metadata for the cosm... | style license - see LICENSE.rst
import abc
import inspect
import numpy as np
from astropy.io.registry import UnifiedReadWriteMethod
from astropy.utils.decorators import classproperty
from astropy.utils.metadata import MetaData
from .connect import CosmologyFromFormat, CosmologyRead, CosmologyToFormat, CosmologyWri... | 256 | 256 | 2,854 | 12 | 243 | lmichel/astropy | astropy/cosmology/core.py | Python | Cosmology | Cosmology | 34 | 366 | 34 | 34 | cc3817ba36d3fdd612d6b844940ac032181db0e4 | bigcode/the-stack | train |
99f3b8d55c3752fa946c2e08 | train | function | def __getattr__(attr):
from . import flrw
if hasattr(flrw, attr) and attr not in ("__path__", ):
import warnings
from astropy.utils.exceptions import AstropyDeprecationWarning
warnings.warn(
f"`astropy.cosmology.core.{attr}` has been moved (since v5.0) and "
f"... | def __getattr__(attr):
| from . import flrw
if hasattr(flrw, attr) and attr not in ("__path__", ):
import warnings
from astropy.utils.exceptions import AstropyDeprecationWarning
warnings.warn(
f"`astropy.cosmology.core.{attr}` has been moved (since v5.0) and "
f"should be imported as `... | flat (for the a specific set of parameter values),
but ``FlatLambdaCDM`` **will** be flat.
"""
@property
def is_flat(self):
"""Return `True`, the cosmology is flat."""
return True
# -----------------------------------------------------------------------------
def __getattr__(attr):
| 63 | 64 | 150 | 7 | 56 | lmichel/astropy | astropy/cosmology/core.py | Python | __getattr__ | __getattr__ | 387 | 404 | 387 | 387 | cd02a559254b86f5b4d5570245c8dd78418db5dd | bigcode/the-stack | train |
07ae6aae53a1d738cb898f69 | train | class | class CosmologyError(Exception):
pass
| class CosmologyError(Exception):
| pass
| Cosmology", "CosmologyError", "FlatCosmologyMixin"]
__doctest_requires__ = {} # needed until __getattr__ removed
# registry of cosmology classes with {key=name : value=class}
_COSMOLOGY_CLASSES = dict()
class CosmologyError(Exception):
| 64 | 64 | 9 | 6 | 58 | lmichel/astropy | astropy/cosmology/core.py | Python | CosmologyError | CosmologyError | 30 | 31 | 30 | 30 | 56acb967616d8ee0f1f32114532fd877f067ea98 | bigcode/the-stack | train |
6805ec2abcafbbb6022d649a | train | class | class FlatCosmologyMixin(metaclass=abc.ABCMeta):
"""
Mixin class for flat cosmologies. Do NOT instantiate directly.
Note that all instances of ``FlatCosmologyMixin`` are flat, but not all
flat cosmologies are instances of ``FlatCosmologyMixin``. As example,
``LambdaCDM`` **may** be flat (for the a s... | class FlatCosmologyMixin(metaclass=abc.ABCMeta):
| """
Mixin class for flat cosmologies. Do NOT instantiate directly.
Note that all instances of ``FlatCosmologyMixin`` are flat, but not all
flat cosmologies are instances of ``FlatCosmologyMixin``. As example,
``LambdaCDM`` **may** be flat (for the a specific set of parameter values),
but ``FlatL... | ")`` for allowed kwargs.
Returns
-------
`astropy.table.Table` or subclass instance
Instance of type ``cls``.
"""
return self.to_format("astropy.table", cls=cls, **kwargs)
class FlatCosmologyMixin(metaclass=abc.ABCMeta):
| 64 | 64 | 132 | 15 | 49 | lmichel/astropy | astropy/cosmology/core.py | Python | FlatCosmologyMixin | FlatCosmologyMixin | 369 | 381 | 369 | 369 | 77d39447abf144f72d549c3a0804c755d92ed489 | bigcode/the-stack | train |
c7f58c6ebe69929cb57189bf | train | function | def detect(filename):
curr = os.path.dirname(os.path.abspath(__file__))
classpath = ".:%s/zxing.jar:%s" % (curr, curr)
output = subprocess.check_output(["java", "-classpath", classpath, "SimpleQRDetector", filename])
return output
| def detect(filename):
| curr = os.path.dirname(os.path.abspath(__file__))
classpath = ".:%s/zxing.jar:%s" % (curr, curr)
output = subprocess.check_output(["java", "-classpath", classpath, "SimpleQRDetector", filename])
return output
| import os
import subprocess
def detect(filename):
| 10 | 64 | 61 | 4 | 5 | blukat29/qrdecode | img/__init__.py | Python | detect | detect | 4 | 8 | 4 | 4 | f850f6b0df8e35d5acc0f31181e0e9682b5cc2c7 | bigcode/the-stack | train |
b02f15dd6b4d7e91e946704b | train | function | def adjust_learning_rate(optimizer, cur_epoch, base_lr, lr_schedule):
"""
Sets the learning rate
"""
lr = 0
for i, e in enumerate(lr_schedule):
if cur_epoch < e:
lr = base_lr * (0.1 ** i)
break
if lr == 0:
lr = base_lr
for param_group in optimizer.par... | def adjust_learning_rate(optimizer, cur_epoch, base_lr, lr_schedule):
| """
Sets the learning rate
"""
lr = 0
for i, e in enumerate(lr_schedule):
if cur_epoch < e:
lr = base_lr * (0.1 ** i)
break
if lr == 0:
lr = base_lr
for param_group in optimizer.param_groups:
param_group["lr"] = lr
return lr
| _tuple_for_ctc(T_length, lengths):
input_lengths = []
target_lengths = []
for ch in lengths:
input_lengths.append(T_length)
target_lengths.append(ch)
return tuple(input_lengths), tuple(target_lengths)
def adjust_learning_rate(optimizer, cur_epoch, base_lr, lr_schedule):
| 64 | 64 | 101 | 16 | 48 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | adjust_learning_rate | adjust_learning_rate | 36 | 51 | 36 | 36 | 09aa6682d9a5a54c195904802cf3869bd6739c9d | bigcode/the-stack | train |
f37ce4b622baf386b253cc52 | train | function | def get_parser():
parser = argparse.ArgumentParser(description="parameters to train net")
parser.add_argument("--max_epoch", default=200, help="epoch to train the network")
parser.add_argument("--img_size", default=(94, 24), help="the image size")
parser.add_argument(
"--train_img_dirs", default... | def get_parser():
| parser = argparse.ArgumentParser(description="parameters to train net")
parser.add_argument("--max_epoch", default=200, help="epoch to train the network")
parser.add_argument("--img_size", default=(94, 24), help="the image size")
parser.add_argument(
"--train_img_dirs", default="./images/train",... | nn
import numpy as np
import argparse
import torch
import time
import os
def sparse_tuple_for_ctc(T_length, lengths):
input_lengths = []
target_lengths = []
for ch in lengths:
input_lengths.append(T_length)
target_lengths.append(ch)
return tuple(input_lengths), tuple(target_lengths)... | 174 | 174 | 583 | 4 | 169 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | get_parser | get_parser | 54 | 115 | 54 | 54 | 4dd95ca93fbffa82dd67725756a169119ae62c54 | bigcode/the-stack | train |
a856187a87839e9022e18d02 | train | function | def collate_fn(batch):
imgs = []
labels = []
lengths = []
filenames = []
for _, sample in enumerate(batch):
img, label, length, filename = sample
imgs.append(torch.from_numpy(img))
labels.extend(label)
lengths.append(length)
filenames.append(filename)
labe... | def collate_fn(batch):
| imgs = []
labels = []
lengths = []
filenames = []
for _, sample in enumerate(batch):
img, label, length, filename = sample
imgs.append(torch.from_numpy(img))
labels.extend(label)
lengths.append(length)
filenames.append(filename)
labels = np.asarray(labels)... | # parser.add_argument('--pretrained_model', default='./weights/Final_LPRNet_model.pth', help='pretrained base model')
parser.add_argument("--pretrained_model", default="", help="pretrained base model")
args = parser.parse_args()
return args
def collate_fn(batch):
| 64 | 64 | 97 | 6 | 57 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | collate_fn | collate_fn | 118 | 131 | 118 | 118 | 880dd755202e06a62254e79b535eb24315acb2a6 | bigcode/the-stack | train |
46e1cc8429af2ce3f5b2ee1a | train | function | def sparse_tuple_for_ctc(T_length, lengths):
input_lengths = []
target_lengths = []
for ch in lengths:
input_lengths.append(T_length)
target_lengths.append(ch)
return tuple(input_lengths), tuple(target_lengths)
| def sparse_tuple_for_ctc(T_length, lengths):
| input_lengths = []
target_lengths = []
for ch in lengths:
input_lengths.append(T_length)
target_lengths.append(ch)
return tuple(input_lengths), tuple(target_lengths)
| nn as cudnn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.utils.data import *
from torch import optim
import torch.nn as nn
import numpy as np
import argparse
import torch
import time
import os
def sparse_tuple_for_ctc(T_length, lengths):
| 64 | 64 | 50 | 11 | 52 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | sparse_tuple_for_ctc | sparse_tuple_for_ctc | 25 | 33 | 25 | 25 | e844dcd50869f1bdcd2343e82a43b160d025d219 | bigcode/the-stack | train |
ecd19e4b57d9fa2fc83423f3 | train | function | def get_size(imgpath):
shapeslist = []
for img in os.listdir(imgpath):
try:
im = Image.open(imgpath + "/" + img)
shapeslist.append(im.size)
except:
pass
a = np.array(shapeslist)
heights = a.T[0]
widths = a.T[1]
heights.sort()
widths.sort()
... | def get_size(imgpath):
| shapeslist = []
for img in os.listdir(imgpath):
try:
im = Image.open(imgpath + "/" + img)
shapeslist.append(im.size)
except:
pass
a = np.array(shapeslist)
heights = a.T[0]
widths = a.T[1]
heights.sort()
widths.sort()
img_h = int(np.medi... | sample
imgs.append(torch.from_numpy(img))
labels.extend(label)
lengths.append(length)
filenames.append(filename)
labels = np.asarray(labels).flatten().astype(np.int)
return (torch.stack(imgs, 0), torch.from_numpy(labels), lengths, filenames)
def get_size(imgpath):
| 64 | 64 | 113 | 6 | 58 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | get_size | get_size | 134 | 149 | 134 | 134 | 30b238163d8258d7ef1c570a326714db1e0ea0c7 | bigcode/the-stack | train |
e628368c35a4f13216ab8cad | train | function | def train():
GLOBAL_LOSS = np.inf
args = get_parser()
T_length = 18 # args.lpr_max_len
epoch = 0 + args.resume_epoch
loss_val = 0
if not os.path.exists(args.save_folder):
os.mkdir(args.save_folder)
lprnet = build_lprnet(
lpr_max_len=args.lpr_max_len,
phase=args.ph... | def train():
| GLOBAL_LOSS = np.inf
args = get_parser()
T_length = 18 # args.lpr_max_len
epoch = 0 + args.resume_epoch
loss_val = 0
if not os.path.exists(args.save_folder):
os.mkdir(args.save_folder)
lprnet = build_lprnet(
lpr_max_len=args.lpr_max_len,
phase=args.phase_train,
... | _LPRNet_model.pth', help='pretrained base model')
parser.add_argument("--pretrained_model", default="", help="pretrained base model")
args = parser.parse_args()
return args
def collate_fn(batch):
imgs = []
labels = []
lengths = []
filenames = []
for _, sample in enumerate(batch):
... | 256 | 256 | 1,471 | 3 | 253 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | train | train | 152 | 335 | 152 | 152 | 9b89b753d1e48c1d5a4162df6c4d9e56defe317f | bigcode/the-stack | train |
6acd5d11faf2aede0475a955 | train | function | def Greedy_Decode_Eval(Net, datasets, args):
# TestNet = Net.eval()
epoch_size = len(datasets) // args.test_batch_size
batch_iterator = iter(
DataLoader(
datasets,
args.test_batch_size,
shuffle=True,
num_workers=args.num_workers,
collate_fn... | def Greedy_Decode_Eval(Net, datasets, args):
# TestNet = Net.eval()
| epoch_size = len(datasets) // args.test_batch_size
batch_iterator = iter(
DataLoader(
datasets,
args.test_batch_size,
shuffle=True,
num_workers=args.num_workers,
collate_fn=collate_fn,
)
)
Tp = 0
Tn_1 = 0
Tn_2 = 0
t... | " || Loss: %.4f||" % (loss.item())
+ "Batch time: %.4f sec. ||" % (end_time - start_time)
+ "LR: %.8f" % (lr)
)
if loss.item() < GLOBAL_LOSS:
GLOBAL_LOSS = loss.item()
# torch.save(lprnet.state_dict(), args.save_folder+f"Min_loss({round(loss.... | 256 | 256 | 882 | 21 | 235 | sanchit2843/Indian_LPR | src/License_Plate_Recognition/train_LPRNet.py | Python | Greedy_Decode_Eval | Greedy_Decode_Eval | 338 | 436 | 338 | 339 | 57b178914054f3b5f6a9821d0f362fe888253087 | bigcode/the-stack | train |
3e5878498231a330f9da46d0 | train | class | class LitModule(pl.LightningModule):
"""
Control the loops for training, evaluation, and prediction. This module is independent of
the model definition. This class inherits from the Pytorch Lightning's LightningModule:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html
"... | class LitModule(pl.LightningModule):
| """
Control the loops for training, evaluation, and prediction. This module is independent of
the model definition. This class inherits from the Pytorch Lightning's LightningModule:
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html
"""
def __init__(
sel... | import logging
import torch
from torch import nn
import torch.nn.functional as F
import pytorch_lightning as pl
from .utils import (
get_optimizer,
get_lr_scheduler,
apply_two_stages_lr,
apply_layerwise_lr_decay,
apply_single_lr,
)
from ..constants import LOGITS, WEIGHT
from typing import Union, Opt... | 121 | 256 | 2,476 | 8 | 113 | sgdread/autogluon | text/src/autogluon/text/automm/optimization/lit_module.py | Python | LitModule | LitModule | 22 | 315 | 22 | 22 | e93dd4758f6af65d06f3cb9e12c450d373f60a19 | bigcode/the-stack | train |
d51837def1632a57d6302486 | train | function | def test_leading_newlines():
src = """
def fn(): pass
"""
co = compile(src, 'mymod', 'exec')
firstlineno = co.co_firstlineno
assert firstlineno == 2
| def test_leading_newlines():
| src = """
def fn(): pass
"""
co = compile(src, 'mymod', 'exec')
firstlineno = co.co_firstlineno
assert firstlineno == 2
| compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)
tree = compile(co2, '<ast>', 'eval')
assert compile(co2, '<ast>', 'eval', _ast.PyCF_ONLY_AST) is co2
def test_leading_newlines():
| 64 | 64 | 51 | 7 | 56 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_leading_newlines | test_leading_newlines | 78 | 84 | 78 | 78 | ce8a14f157cc371c3829f2fe68f8d07a768c5738 | bigcode/the-stack | train |
1d1eac29416d848656ec69c3 | train | function | def test_build_class():
"""Test error message bad __prepare__"""
class BadMeta(type):
@classmethod
def __prepare__(*args):
return None
def func():
class Foo(metaclass=BadMeta):
pass
excinfo = raises(TypeError, func)
assert str(excinfo.value) == (
... | def test_build_class():
| """Test error message bad __prepare__"""
class BadMeta(type):
@classmethod
def __prepare__(*args):
return None
def func():
class Foo(metaclass=BadMeta):
pass
excinfo = raises(TypeError, func)
assert str(excinfo.value) == (
r"BadMeta.__prepar... | strings are gone from the bytecode and not just
# inaccessible.
marshalled = str(marshal.dumps(compiled))
assert 'module_doc' not in marshalled
assert 'func_doc' not in marshalled
assert 'class_doc' not in marshalled
def test_build_class():
| 64 | 64 | 92 | 5 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_build_class | test_build_class | 183 | 198 | 183 | 183 | b7fa0561bf459d8930e436461de89da0826afa72 | bigcode/the-stack | train |
3443db1d1303dbd434199b59 | train | function | def test_docstring_remove():
"""Test removal of docstrings with optimize=2."""
import ast
import marshal
code = """
'module_doc'
def f():
'func_doc'
class C:
'class_doc'
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec",... | def test_docstring_remove():
| """Test removal of docstrings with optimize=2."""
import ast
import marshal
code = """
'module_doc'
def f():
'func_doc'
class C:
'class_doc'
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec", optimize=2)
ns = {}... | ():
assert False
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec", optimize=1)
ns = {}
exec(compiled, ns)
ns['f']()
def test_docstring_remove():
| 64 | 64 | 195 | 6 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_docstring_remove | test_docstring_remove | 152 | 181 | 152 | 152 | 7a2acf5a4afe49672201432b2655e664b2a4149a | bigcode/the-stack | train |
3da07b362aba9e57f2e226ef | train | function | def test_recompile_ast():
import _ast
# raise exception when node type doesn't match with compile mode
co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
raises(TypeError, compile, co1, '<ast>', 'eval')
co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)
tree = compile(co... | def test_recompile_ast():
| import _ast
# raise exception when node type doesn't match with compile mode
co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
raises(TypeError, compile, co1, '<ast>', 'eval')
co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)
tree = compile(co2, '<ast>', 'eval')
as... | co = compile(m, 'baz', 'eval')
assert eval(co) == 3
assert eval(m) == 3
ns = {}
exec(memoryview(b'r = 2 + 1'), ns)
assert ns['r'] == 3
def test_recompile_ast():
| 64 | 64 | 125 | 6 | 57 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_recompile_ast | test_recompile_ast | 69 | 76 | 69 | 69 | e588d67e65e3533791a818b9064d04d57d99d524 | bigcode/the-stack | train |
2a5d8a8a8014009cbe391ca3 | train | function | def test_null_bytes():
raises(ValueError, compile, '\x00', 'mymod', 'exec', 0)
src = "#abc\x00def\n"
raises(ValueError, compile, src, 'mymod', 'exec')
raises(ValueError, compile, src, 'mymod', 'exec', 0)
| def test_null_bytes():
| raises(ValueError, compile, '\x00', 'mymod', 'exec', 0)
src = "#abc\x00def\n"
raises(ValueError, compile, src, 'mymod', 'exec')
raises(ValueError, compile, src, 'mymod', 'exec', 0)
| CF_ONLY_AST) is co2
def test_leading_newlines():
src = """
def fn(): pass
"""
co = compile(src, 'mymod', 'exec')
firstlineno = co.co_firstlineno
assert firstlineno == 2
def test_null_bytes():
| 64 | 64 | 74 | 5 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_null_bytes | test_null_bytes | 86 | 90 | 86 | 86 | 33b1629ecd064942214d00e753eb5d0613a85688 | bigcode/the-stack | train |
70d3cb44eb3da5bf781db19d | train | function | def test_error_message():
compile('# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
exc = raises(SyntaxError, compile,
b'# -*- coding: fake -*-\n', 'dummy', 'exec')
assert 'fake' ... | def test_error_message():
| compile('# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
exc = raises(SyntaxError, compile,
b'# -*- coding: fake -*-\n', 'dummy', 'exec')
assert 'fake' in str(exc.value)
exc ... | '?', 'eval')
raises(ValueError, compile, '1+2', '?', 'maybenot')
raises(ValueError, compile, "\n", "<string>", "exec", 0xff)
raises(TypeError, compile, '1+2', 12, 34)
def test_error_message():
| 67 | 67 | 225 | 5 | 62 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_error_message | test_error_message | 18 | 32 | 18 | 18 | 3b66f7f43a9dbf886e197bf028d8ec24eff2df78 | bigcode/the-stack | train |
faab37539f4723c189255942 | train | function | def test_make_sure_namespace_in_class_is_moduledict():
import __pypy__
class A:
assert __pypy__.strategy(locals()) == "ModuleDictStrategy"
| def test_make_sure_namespace_in_class_is_moduledict():
| import __pypy__
class A:
assert __pypy__.strategy(locals()) == "ModuleDictStrategy"
| Foo(metaclass=BadMeta):
pass
excinfo = raises(TypeError, func)
assert str(excinfo.value) == (
r"BadMeta.__prepare__() must return a mapping, not NoneType"
)
def test_make_sure_namespace_in_class_is_moduledict():
| 64 | 64 | 40 | 14 | 50 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_make_sure_namespace_in_class_is_moduledict | test_make_sure_namespace_in_class_is_moduledict | 200 | 203 | 200 | 200 | f596940798c8eec26c3b3bda21376259a346e290 | bigcode/the-stack | train |
8eb4c8dd24d396f30c5711e8 | train | function | def test_memoryview():
m = memoryview(b'2 + 1')
co = compile(m, 'baz', 'eval')
assert eval(co) == 3
assert eval(m) == 3
ns = {}
exec(memoryview(b'r = 2 + 1'), ns)
assert ns['r'] == 3
| def test_memoryview():
| m = memoryview(b'2 + 1')
co = compile(m, 'baz', 'eval')
assert eval(co) == 3
assert eval(m) == 3
ns = {}
exec(memoryview(b'r = 2 + 1'), ns)
assert ns['r'] == 3
| \nfoo = 'caf\xe9'\n", "<string>", "exec")
ns = {}
exec(c, ns)
assert ns['foo'] == 'café'
assert eval(b"# coding: latin1\n'caf\xe9'\n") == 'café'
def test_memoryview():
| 64 | 64 | 76 | 5 | 59 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_memoryview | test_memoryview | 60 | 67 | 60 | 60 | 8d08b93facdefcf7c592ba06c242a02bbcad389b | bigcode/the-stack | train |
f4ef6a2979a42236ea5ddeaa | train | function | def test_simple():
co = compile('1+2', '?', 'eval')
assert eval(co) == 3
co = compile(memoryview(b'1+2'), '?', 'eval')
assert eval(co) == 3
exc = raises(ValueError, compile, chr(0), '?', 'eval')
assert str(exc.value) == "source code string cannot contain null bytes"
compile("from __future__ ... | def test_simple():
| co = compile('1+2', '?', 'eval')
assert eval(co) == 3
co = compile(memoryview(b'1+2'), '?', 'eval')
assert eval(co) == 3
exc = raises(ValueError, compile, chr(0), '?', 'eval')
assert str(exc.value) == "source code string cannot contain null bytes"
compile("from __future__ import with_stateme... | from pytest import raises, skip
import sys
def test_simple():
| 14 | 64 | 192 | 4 | 9 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_simple | test_simple | 4 | 16 | 4 | 4 | 4cb4828fe7dc4ac119c786975907c7779babb866 | bigcode/the-stack | train |
ee836eb2597671ebf2f493a1 | train | function | def test_unicode():
try:
compile(u'-', '?', 'eval')
except SyntaxError as e:
assert e.lineno == 1
| def test_unicode():
| try:
compile(u'-', '?', 'eval')
except SyntaxError as e:
assert e.lineno == 1
| ' in str(exc.value)
exc = raises(SyntaxError, compile,
b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
assert 'fake' in str(exc.value)
assert 'BOM' in str(exc.value)
def test_unicode():
| 64 | 64 | 33 | 4 | 60 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_unicode | test_unicode | 34 | 38 | 34 | 34 | aea9fd09427d8884c8c7452ea9a77c07c2333b1e | bigcode/the-stack | train |
3a87e3c15e4bcdcb81364e04 | train | function | def test_compile_feature_version():
co = compile('1+2', '?', 'eval', _feature_version=-1)
assert eval(co) == 3
co = compile('1+2', '?', 'eval', _feature_version=8)
assert eval(co) == 3
| def test_compile_feature_version():
| co = compile('1+2', '?', 'eval', _feature_version=-1)
assert eval(co) == 3
co = compile('1+2', '?', 'eval', _feature_version=8)
assert eval(co) == 3
| "BadMeta.__prepare__() must return a mapping, not NoneType"
)
def test_make_sure_namespace_in_class_is_moduledict():
import __pypy__
class A:
assert __pypy__.strategy(locals()) == "ModuleDictStrategy"
def test_compile_feature_version():
| 64 | 64 | 64 | 6 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_compile_feature_version | test_compile_feature_version | 205 | 210 | 205 | 205 | 4a04b7a85d2bdbc1d7d122a30ddf6cb1728e1945 | bigcode/the-stack | train |
d3802d6405d1c258cc134c4e | train | function | def test_incorrect_escape_deprecation_bytes():
import warnings
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always', category=DeprecationWarning)
compile(r"b'\}'", '', 'exec')
assert len(l) == 1
| def test_incorrect_escape_deprecation_bytes():
| import warnings
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always', category=DeprecationWarning)
compile(r"b'\}'", '', 'exec')
assert len(l) == 1
| ')
assert 'fake' in str(exc.value)
assert 'BOM' in str(exc.value)
def test_unicode():
try:
compile(u'-', '?', 'eval')
except SyntaxError as e:
assert e.lineno == 1
def test_incorrect_escape_deprecation_bytes():
| 64 | 64 | 60 | 9 | 54 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_incorrect_escape_deprecation_bytes | test_incorrect_escape_deprecation_bytes | 40 | 45 | 40 | 40 | 7b14e909655e770174957c7f4835e15bddcac036 | bigcode/the-stack | train |
adba0d2ca3d98ddab52c063c | train | function | def test_compile_regression():
"""Clone of the part of the original test that was failing."""
import ast
codestr = '''def f():
"""doc"""
try:
assert False
except AssertionError:
return (True, f.__doc__, __debug__)
else:
return (False, f.__doc__, __debug__)
'''
... | def test_compile_regression():
| """Clone of the part of the original test that was failing."""
import ast
codestr = '''def f():
"""doc"""
try:
assert False
except AssertionError:
return (True, f.__doc__, __debug__)
else:
return (False, f.__doc__, __debug__)
'''
def f():
"""doc"""
... | only (requires _ast.PyCF_ACCEPT_NULL_BYTES)')
raises(SyntaxError, compile, '\x00', 'mymod', 'exec',
PyCF_ACCEPT_NULL_BYTES)
src = "#abc\x00def\n"
compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works
def test_compile_regression():
| 77 | 77 | 259 | 6 | 70 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_compile_regression | test_compile_regression | 102 | 136 | 102 | 102 | e6d63abcaa8a4f22812ac003ee9268d6482db2d0 | bigcode/the-stack | train |
25210acc75283bb121eba024 | train | function | def test_bytes():
code = b"# -*- coding: utf-8 -*-\npass\n"
compile(code, "tmp", "exec")
c = compile(b"# coding: latin1\nfoo = 'caf\xe9'\n", "<string>", "exec")
ns = {}
exec(c, ns)
assert ns['foo'] == 'café'
assert eval(b"# coding: latin1\n'caf\xe9'\n") == 'café'
| def test_bytes():
| code = b"# -*- coding: utf-8 -*-\npass\n"
compile(code, "tmp", "exec")
c = compile(b"# coding: latin1\nfoo = 'caf\xe9'\n", "<string>", "exec")
ns = {}
exec(c, ns)
assert ns['foo'] == 'café'
assert eval(b"# coding: latin1\n'caf\xe9'\n") == 'café'
| ', category=DeprecationWarning)
compile(r"b'\}'", '', 'exec')
assert len(l) == 1
def test_unicode_encoding():
code = "# -*- coding: utf-8 -*-\npass\n"
compile(code, "tmp", "exec")
def test_bytes():
| 64 | 64 | 100 | 4 | 60 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_bytes | test_bytes | 51 | 58 | 51 | 51 | 288474c9c87f76bb4f8d35e5c16efa2b5b167bb2 | bigcode/the-stack | train |
d0436952400d9fa1a06c3cb6 | train | function | def test_assert_remove():
"""Test removal of the asserts with optimize=1."""
import ast
code = """def f():
assert False
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec", optimize=1)
ns = {}
exec(compiled, ns)
... | def test_assert_remove():
| """Test removal of the asserts with optimize=1."""
import ast
code = """def f():
assert False
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec", optimize=1)
ns = {}
exec(compiled, ns)
ns['f']()
| test>", "exec", optimize=optval))
for i, code in enumerate(codeobjs):
print(optval, *expected, i)
ns = {}
exec(code, ns)
rv = ns['f']()
print(rv)
assert rv == tuple(expected)
def test_assert_remove():
| 64 | 64 | 85 | 5 | 59 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_assert_remove | test_assert_remove | 138 | 150 | 138 | 138 | 124b6bb46cf8acf65d71d7be1643cc04d90b5e21 | bigcode/the-stack | train |
36b54a8c71adeffe454a5be3 | train | function | def test_unicode_encoding():
code = "# -*- coding: utf-8 -*-\npass\n"
compile(code, "tmp", "exec")
| def test_unicode_encoding():
| code = "# -*- coding: utf-8 -*-\npass\n"
compile(code, "tmp", "exec")
| test_incorrect_escape_deprecation_bytes():
import warnings
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always', category=DeprecationWarning)
compile(r"b'\}'", '', 'exec')
assert len(l) == 1
def test_unicode_encoding():
| 64 | 64 | 31 | 5 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_unicode_encoding | test_unicode_encoding | 47 | 49 | 47 | 47 | f16b5a927879e925c055c52d458c6a132fd0c3aa | bigcode/the-stack | train |
027bc52b300cf7a10fad0d0f | train | function | def test_null_bytes_flag():
try:
from _ast import PyCF_ACCEPT_NULL_BYTES
except ImportError:
skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)')
raises(SyntaxError, compile, '\x00', 'mymod', 'exec',
PyCF_ACCEPT_NULL_BYTES)
src = "#abc\x00def\n"
compile(src, 'mymod', ... | def test_null_bytes_flag():
| try:
from _ast import PyCF_ACCEPT_NULL_BYTES
except ImportError:
skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)')
raises(SyntaxError, compile, '\x00', 'mymod', 'exec',
PyCF_ACCEPT_NULL_BYTES)
src = "#abc\x00def\n"
compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYT... | 'mymod', 'exec', 0)
src = "#abc\x00def\n"
raises(ValueError, compile, src, 'mymod', 'exec')
raises(ValueError, compile, src, 'mymod', 'exec', 0)
def test_null_bytes_flag():
| 64 | 64 | 101 | 6 | 58 | hollmmax/zig | pypy/module/__builtin__/test/apptest_compile.py | Python | test_null_bytes_flag | test_null_bytes_flag | 92 | 100 | 92 | 92 | c52f40d42a74aaba336457f9b30363a906a1a024 | bigcode/the-stack | train |
5bf3cc35f824e1c77c96ef41 | train | class | class LiteralValuePacket:
def __init__(self, version: int, raw_data: str) -> None:
"""Construct a new LiteralValuePacket"""
self.version = version
self.literal, self.length = self._read_data(raw_data)
def _read_data(self, binary_string: str) -> Tuple[int, int]:
"""Read the raw d... | class LiteralValuePacket:
| def __init__(self, version: int, raw_data: str) -> None:
"""Construct a new LiteralValuePacket"""
self.version = version
self.literal, self.length = self._read_data(raw_data)
def _read_data(self, binary_string: str) -> Tuple[int, int]:
"""Read the raw data given by `binary_strin... | type"""
return (int(binary_string[:3], 2), int(binary_string[3:6], 2))
def is_literal_value_packet(type: int) -> bool:
"""Check if the `type` corresponds to a literal value packet"""
return type == 4
class LiteralValuePacket:
| 64 | 64 | 163 | 5 | 58 | xphade/aoc2021 | 16_packet-decoder.py | Python | LiteralValuePacket | LiteralValuePacket | 43 | 60 | 43 | 43 | 34551cc2ba4dd10aeb1df19433d40974317bd62a | bigcode/the-stack | train |
d402837778a551f7976b9845 | train | function | def read_packet_header(binary_string: str) -> Tuple[int, int]:
"""Read the header of the `binary_string`, returning packet version and type"""
return (int(binary_string[:3], 2), int(binary_string[3:6], 2))
| def read_packet_header(binary_string: str) -> Tuple[int, int]:
| """Read the header of the `binary_string`, returning packet version and type"""
return (int(binary_string[:3], 2), int(binary_string[3:6], 2))
| (hex_number, 16))
binary = binary[2:]
mod = len(binary) % 4
if mod != 0:
binary = binary.zfill(len(binary) + (4 - mod))
return binary
def read_packet_header(binary_string: str) -> Tuple[int, int]:
| 64 | 64 | 55 | 15 | 48 | xphade/aoc2021 | 16_packet-decoder.py | Python | read_packet_header | read_packet_header | 33 | 35 | 33 | 33 | 77e97360eaa8f021311a2226a2edaa68398187b0 | bigcode/the-stack | train |
9b955c40df5ffbeb0aeec628 | train | function | def is_literal_value_packet(type: int) -> bool:
"""Check if the `type` corresponds to a literal value packet"""
return type == 4
| def is_literal_value_packet(type: int) -> bool:
| """Check if the `type` corresponds to a literal value packet"""
return type == 4
| _header(binary_string: str) -> Tuple[int, int]:
"""Read the header of the `binary_string`, returning packet version and type"""
return (int(binary_string[:3], 2), int(binary_string[3:6], 2))
def is_literal_value_packet(type: int) -> bool:
| 64 | 64 | 34 | 12 | 52 | xphade/aoc2021 | 16_packet-decoder.py | Python | is_literal_value_packet | is_literal_value_packet | 38 | 40 | 38 | 38 | f63969e07afe0f5660c3ac46e3062fa6de1de7b0 | bigcode/the-stack | train |
6296eadf0cc782ca462418c4 | train | function | def bin_from_hex(hex_number: str) -> str:
"""Calculate the binary representation of the given `hex_number`"""
binary = bin(int(hex_number, 16))
binary = binary[2:]
mod = len(binary) % 4
if mod != 0:
binary = binary.zfill(len(binary) + (4 - mod))
return binary
| def bin_from_hex(hex_number: str) -> str:
| """Calculate the binary representation of the given `hex_number`"""
binary = bin(int(hex_number, 16))
binary = binary[2:]
mod = len(binary) % 4
if mod != 0:
binary = binary.zfill(len(binary) + (4 - mod))
return binary
| ] else 0,
6: lambda l: 1 if l[0] < l[1] else 0,
7: lambda l: 1 if l[0] == l[1] else 0,
}
def bin_from_hex(hex_number: str) -> str:
| 64 | 64 | 80 | 12 | 52 | xphade/aoc2021 | 16_packet-decoder.py | Python | bin_from_hex | bin_from_hex | 21 | 30 | 21 | 21 | 0d7027a2b909c34f0f70969141b991a5eeaf48f2 | bigcode/the-stack | train |
955dca5329816d6371cd9ed5 | train | class | class OperatorPacket:
def __init__(self, version: int, type: int, raw_data: str) -> None:
"""Construct a new OperatorPacket"""
self.version = version
assert type in TYPE_FUNCTIONS
self.packet_function = TYPE_FUNCTIONS[type]
self.literal_packets: List[LiteralValuePacket] = [... | class OperatorPacket:
| def __init__(self, version: int, type: int, raw_data: str) -> None:
"""Construct a new OperatorPacket"""
self.version = version
assert type in TYPE_FUNCTIONS
self.packet_function = TYPE_FUNCTIONS[type]
self.literal_packets: List[LiteralValuePacket] = []
self.operato... | the `type` corresponds to a literal value packet"""
return type == 4
class LiteralValuePacket:
def __init__(self, version: int, raw_data: str) -> None:
"""Construct a new LiteralValuePacket"""
self.version = version
self.literal, self.length = self._read_data(raw_data)
def _read_... | 185 | 185 | 617 | 4 | 181 | xphade/aoc2021 | 16_packet-decoder.py | Python | OperatorPacket | OperatorPacket | 63 | 132 | 63 | 63 | 51217175d8a72f54e9fe3bb64ed0329a952db0ff | bigcode/the-stack | train |
cd43cf138c182c818755cdb3 | train | function | def main():
data_path = get_input_path("Day 16: Packet Decoder")
with open(data_path, "r") as file:
transmission = file.readline()
start = timer()
binary_string = bin_from_hex(transmission)
version, type = read_packet_header(binary_string)
assert not is_literal_value_packet(type)
p... | def main():
| data_path = get_input_path("Day 16: Packet Decoder")
with open(data_path, "r") as file:
transmission = file.readline()
start = timer()
binary_string = bin_from_hex(transmission)
version, type = read_packet_header(binary_string)
assert not is_literal_value_packet(type)
packet = Oper... | in self.operator_packets])
return version_sum
def result(self) -> int:
"""Calculate the result of the packet"""
values = [lp.literal for lp in self.literal_packets]
values += [op.result() for op in self.operator_packets]
return self.packet_function(values)
def main():
| 64 | 64 | 139 | 3 | 61 | xphade/aoc2021 | 16_packet-decoder.py | Python | main | main | 135 | 154 | 135 | 135 | c5cf60108885748db5623f0d126e479db9d5d8b7 | bigcode/the-stack | train |
50dc0fe9cd7cfc693b6a40bc | train | class | class NoFilter(object):
def __init__(self):
pass
def __call__(self, x, update=True):
return np.asarray(x)
| class NoFilter(object):
| def __init__(self):
pass
def __call__(self, x, update=True):
return np.asarray(x)
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class NoFilter(object):
| 33 | 64 | 33 | 5 | 27 | cbfinn/ray | examples/policy_gradient/reinforce/filter.py | Python | NoFilter | NoFilter | 8 | 13 | 8 | 8 | f98997dcfe93c878c0e5bdf139a3a78d0698c5b9 | bigcode/the-stack | train |
2964ef2601a4de4f52fa2ee0 | train | function | def test_running_stat():
for shp in ((), (3,), (3, 4)):
li = []
rs = RunningStat(shp)
for _ in range(5):
val = np.random.randn(*shp)
rs.push(val)
li.append(val)
m = np.mean(li, axis=0)
assert np.allclose(rs.mean, m)
v = np.square(m) if (len(li) == 1) else np.var(li, ddo... | def test_running_stat():
| for shp in ((), (3,), (3, 4)):
li = []
rs = RunningStat(shp)
for _ in range(5):
val = np.random.randn(*shp)
rs.push(val)
li.append(val)
m = np.mean(li, axis=0)
assert np.allclose(rs.mean, m)
v = np.square(m) if (len(li) == 1) else np.var(li, ddof=1, axis=0)
assert... | 8)
if self.clip:
if np.amin(x) < -self.clip or np.amax(x) > self.clip:
print("Clipping value to " + str(self.clip))
x = np.clip(x, -self.clip, self.clip)
return x
def test_running_stat():
| 64 | 64 | 121 | 5 | 58 | cbfinn/ray | examples/policy_gradient/reinforce/filter.py | Python | test_running_stat | test_running_stat | 100 | 111 | 100 | 100 | e54dc3648f380ce48d96c0c52f84a71a30012162 | bigcode/the-stack | train |
a2d43867080518971f453f0b | train | function | def test_combining_stat():
for shape in [(), (3,), (3, 4)]:
li = []
rs1 = RunningStat(shape)
rs2 = RunningStat(shape)
rs = RunningStat(shape)
for _ in range(5):
val = np.random.randn(*shape)
rs1.push(val)
rs.push(val)
li.append(val)
for _ in range(9):
rs2.push(val... | def test_combining_stat():
| for shape in [(), (3,), (3, 4)]:
li = []
rs1 = RunningStat(shape)
rs2 = RunningStat(shape)
rs = RunningStat(shape)
for _ in range(5):
val = np.random.randn(*shape)
rs1.push(val)
rs.push(val)
li.append(val)
for _ in range(9):
rs2.push(val)
rs.push(val)
... | np.mean(li, axis=0)
assert np.allclose(rs.mean, m)
v = np.square(m) if (len(li) == 1) else np.var(li, ddof=1, axis=0)
assert np.allclose(rs.var, v)
def test_combining_stat():
| 64 | 64 | 137 | 6 | 58 | cbfinn/ray | examples/policy_gradient/reinforce/filter.py | Python | test_combining_stat | test_combining_stat | 114 | 131 | 114 | 114 | 1d5665e6b34520274d03d5b003138131bbf8d7d8 | bigcode/the-stack | train |
e647b3760723635ba34ab362 | train | class | class RunningStat(object):
def __init__(self, shape=None):
self._n = 0
self._M = np.zeros(shape)
self._S = np.zeros(shape)
def push(self, x):
x = np.asarray(x)
# Unvectorized update of the running statistics.
assert x.shape == self._M.shape, ("x.shape = {}, self.shape = {}"
... | class RunningStat(object):
| def __init__(self, shape=None):
self._n = 0
self._M = np.zeros(shape)
self._S = np.zeros(shape)
def push(self, x):
x = np.asarray(x)
# Unvectorized update of the running statistics.
assert x.shape == self._M.shape, ("x.shape = {}, self.shape = {}"
.form... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class NoFilter(object):
def __init__(self):
pass
def __call__(self, x, update=True):
return np.asarray(x)
# http://www.johndcook.com/blog/standard_deviation/
class RunningSta... | 81 | 115 | 385 | 5 | 76 | cbfinn/ray | examples/policy_gradient/reinforce/filter.py | Python | RunningStat | RunningStat | 17 | 68 | 17 | 18 | b600ca1ccba6c654af6c993d2adca7f525490d7d | bigcode/the-stack | train |
94688dadfe1130833e03e3ef | train | class | class MeanStdFilter(object):
def __init__(self, shape, demean=True, destd=True, clip=10.0):
self.demean = demean
self.destd = destd
self.clip = clip
self.rs = RunningStat(shape)
def __call__(self, x, update=True):
x = np.asarray(x)
if update:
if len(x.shape) == len(self.rs.shape) + 1... | class MeanStdFilter(object):
| def __init__(self, shape, demean=True, destd=True, clip=10.0):
self.demean = demean
self.destd = destd
self.clip = clip
self.rs = RunningStat(shape)
def __call__(self, x, update=True):
x = np.asarray(x)
if update:
if len(x.shape) == len(self.rs.shape) + 1:
# The vectorized ca... | var(self):
return self._S / (self._n - 1) if self._n > 1 else np.square(self._M)
@property
def std(self):
return np.sqrt(self.var)
@property
def shape(self):
return self._M.shape
class MeanStdFilter(object):
| 69 | 69 | 233 | 6 | 62 | cbfinn/ray | examples/policy_gradient/reinforce/filter.py | Python | MeanStdFilter | MeanStdFilter | 71 | 97 | 71 | 71 | a2792157d610a21c5ee7445bf4aa2319846ab0b8 | bigcode/the-stack | train |
226bb90217502c8ef233bce2 | train | function | def thread_code():
# get thread name
thread_name = threading.currentThread().getName()
# get logger
evlog = OcsLogger('Events', thread_name)
evlog.logger.info('{0:s} thread starting up'.format(thread_name))
# connect to SAL
mgr = SAL_camera()
if not mgr:
return False
evlog... | def thread_code():
# get thread name
| thread_name = threading.currentThread().getName()
# get logger
evlog = OcsLogger('Events', thread_name)
evlog.logger.info('{0:s} thread starting up'.format(thread_name))
# connect to SAL
mgr = SAL_camera()
if not mgr:
return False
evlog.logger.info('{0:s} thread connected to SA... | __email__ = "pdaly@lsst.org"
__file__ = "logevent_camera.py"
__history__ = __date__ + ": " + "original version (" + __email__ + ")"
__version__ = "0.1.0"
# +
# function: thread_code()
# -
def thread_code():
# get thread name
| 75 | 75 | 253 | 10 | 65 | lsst-ts/ts_ocs_sequencer | bin/logevent_camera.py | Python | thread_code | thread_code | 35 | 72 | 35 | 37 | b6bf390e1a7900b85e527810ad49e7b24a83f7a6 | bigcode/the-stack | train |
d133a09dfe6ab88d11a6da75 | train | function | def event_response(name='', event=None):
if not isinstance(name, str) or name == '' or not event:
return ''
if name == 'ccsConfigured':
return ''
elif name == 'endInitializeGuider':
return ''
elif name == 'endInitializeImage':
return ''
elif name == 'endLoadFilter':
... | def event_response(name='', event=None):
| if not isinstance(name, str) or name == '' or not event:
return ''
if name == 'ccsConfigured':
return ''
elif name == 'endInitializeGuider':
return ''
elif name == 'endInitializeImage':
return ''
elif name == 'endLoadFilter':
return ''
elif name == 'endRea... | .getEvent_startSetFilter(event)
elif name == 'startShutterClose':
return mgr.getEvent_startShutterClose(event)
elif name == 'startShutterOpen':
return mgr.getEvent_startShutterOpen(event)
elif name == 'startUnloadFilter':
return mgr.getEvent_startUnloadFilter(event)
else:
... | 95 | 95 | 319 | 8 | 87 | lsst-ts/ts_ocs_sequencer | bin/logevent_camera.py | Python | event_response | event_response | 190 | 238 | 190 | 190 | fe5a152f9952a14118bf02403816bc889b9bd6f9 | bigcode/the-stack | train |
2f4e548d64451c448ea58aca | train | function | def get_event_retval(name='', mgr=None, event=None):
if not isinstance(name, str) or name == '' or not mgr or not event:
return -1
if name == 'ccsConfigured':
return mgr.getEvent_ccsConfigured(event)
elif name == 'endInitializeGuider':
return mgr.getEvent_endInitializeGuider(event)
... | def get_event_retval(name='', mgr=None, event=None):
| if not isinstance(name, str) or name == '' or not mgr or not event:
return -1
if name == 'ccsConfigured':
return mgr.getEvent_ccsConfigured(event)
elif name == 'endInitializeGuider':
return mgr.getEvent_endInitializeGuider(event)
elif name == 'endInitializeImage':
return ... | out':
return camera_logevent_startReadoutC()
elif name == 'startRotateCarousel':
return camera_logevent_startRotateCarouselC()
elif name == 'startSetFilter':
return camera_logevent_startSetFilterC()
elif name == 'startShutterClose':
return camera_logevent_startShutterCloseC()... | 143 | 143 | 479 | 13 | 130 | lsst-ts/ts_ocs_sequencer | bin/logevent_camera.py | Python | get_event_retval | get_event_retval | 136 | 184 | 136 | 136 | 3a17fd8515b442fd4d6e4218b86a7fa0d730473d | bigcode/the-stack | train |
637ab6d6b23f2f9590564d56 | train | function | def get_event_container(name=''):
if not isinstance(name, str) or name == '':
return None
if name == 'ccsConfigured':
return camera_logevent_ccsConfiguredC()
elif name == 'endInitializeGuider':
return camera_logevent_endInitializeGuiderC()
elif name == 'endInitializeImage':
... | def get_event_container(name=''):
| if not isinstance(name, str) or name == '':
return None
if name == 'ccsConfigured':
return camera_logevent_ccsConfiguredC()
elif name == 'endInitializeGuider':
return camera_logevent_endInitializeGuiderC()
elif name == 'endInitializeImage':
return camera_logevent_endIniti... | format(thread_name))
# loop forever
while True:
retval = get_event_retval(thread_name, mgr, event)
if retval != 0:
return False
else:
evlog.logger.info('{0:s} thread event received'.format(thread_name))
msg = event_response(event)
if msg ... | 139 | 139 | 464 | 7 | 132 | lsst-ts/ts_ocs_sequencer | bin/logevent_camera.py | Python | get_event_container | get_event_container | 82 | 130 | 82 | 82 | cec15b21c35c3f05645ab0ea42d8a3a9166c8417 | bigcode/the-stack | train |
b30e6c816ef0153b783bcaac | train | function | def probe():
print("pls typ the url you want to probe")
print("ex: www.google.com")
url1 = input("~:")
url2 = "https://" + url1
print(f"{url2} has compiled")
print("running scans")
ip = socket.gethostbyname(url1)
print(ip)
print(f"{ip} is {url1} ip address")
open = urllib.request.urlopen(url2)
red... | def probe():
| print("pls typ the url you want to probe")
print("ex: www.google.com")
url1 = input("~:")
url2 = "https://" + url1
print(f"{url2} has compiled")
print("running scans")
ip = socket.gethostbyname(url1)
print(ip)
print(f"{ip} is {url1} ip address")
open = urllib.request.urlopen(url2)
red = open.read(... |
import socket
import urllib.request
def probe():
| 11 | 64 | 193 | 3 | 7 | aztecboy/probe | Probe.py | Python | probe | probe | 4 | 30 | 4 | 4 | 13c3cea29b8d596b877c554f7a8fa41f090f6752 | bigcode/the-stack | train |
b9188b9f107865eade15c3ad | train | class | class AssetTest(MyntTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [['-assetindex'], ['-assetindex'], ['-assetindex']]
def activate_assets(self):
self.log.info("Generating MYNT for node[0] and activating assets...")
... | class AssetTest(MyntTestFramework):
| def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [['-assetindex'], ['-assetindex'], ['-assetindex']]
def activate_assets(self):
self.log.info("Generating MYNT for node[0] and activating assets...")
n0, n1, n2 = self.nodes[0], ... | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Copyright (c) 2017-2018 The Mynt Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Testing asset use cases
"""
from test_framework.test_fra... | 99 | 256 | 4,204 | 8 | 90 | silence48/mynt | test/functional/feature_assets.py | Python | AssetTest | AssetTest | 15 | 380 | 15 | 15 | cff147a51cd8cd0fdadcf119d8afe24bbcd70257 | bigcode/the-stack | train |
ff3c083db100b1233ee792af | train | function | def pairwise_word_embedding_distance(topics, topk=20):
"""
:param topk: how many most likely words to consider in the evaluation
:return: topic coherence computed on the word embeddings similarities
"""
if topk > len(topics[0]):
raise Exception('Words in topics are less than topk')
else:... | def pairwise_word_embedding_distance(topics, topk=20):
| """
:param topk: how many most likely words to consider in the evaluation
:return: topic coherence computed on the word embeddings similarities
"""
if topk > len(topics[0]):
raise Exception('Words in topics are less than topk')
else:
sum_dist = 0
for topic in topics:
... | collection.find_one({ "word": word2 })
print(f'w1={w1}, w1={w2}')
def f(x): return float(x)
return list(map(f, w1)), list(map(f, w2))
def pairwise_word_embedding_distance(topics, topk=20):
| 64 | 64 | 165 | 14 | 50 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | pairwise_word_embedding_distance | pairwise_word_embedding_distance | 109 | 125 | 109 | 109 | 050065ca1f950ca15fca9362687b2ffe193ae7cb | bigcode/the-stack | train |
d06c76b16299be5788f2eabb | train | function | def filter_tokens_by_frequencies(documents, min_df=1, max_df=1.0):
vectorizer = CountVectorizer(min_df=min_df, max_df=max_df)
vectorizer.fit_transform(documents)
return [[word for word in document if word not in vectorizer.stop_words_] for document in documents]
| def filter_tokens_by_frequencies(documents, min_df=1, max_df=1.0):
| vectorizer = CountVectorizer(min_df=min_df, max_df=max_df)
vectorizer.fit_transform(documents)
return [[word for word in document if word not in vectorizer.stop_words_] for document in documents]
|
Returns:
dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset
"""
dictionary = Dictionary(documents)
dictionary.compactify()
return dictionary
def filter_tokens_by_frequencies(documents, min_df=1, max_df=1.0):
| 64 | 64 | 69 | 21 | 42 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | filter_tokens_by_frequencies | filter_tokens_by_frequencies | 90 | 94 | 90 | 90 | 7a3da3f00f93660735cd995e22a8ae9cf8bbcab7 | bigcode/the-stack | train |
164334417b89e4cccbf82ebc | train | function | def get_coherence_score(topics, documents, dictionary, coherence, no_of_words=20):
"""Calculates topic coherence using gensim's coherence pipeline.
Parameters:
topics (list of str list): topic words for each topic
documents (list of str): set of documents
dictionary (gensim.corpora.Dictionar... | def get_coherence_score(topics, documents, dictionary, coherence, no_of_words=20):
| """Calculates topic coherence using gensim's coherence pipeline.
Parameters:
topics (list of str list): topic words for each topic
documents (list of str): set of documents
dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset
coherence (str): coherence type. Ca... | scipy.spatial import distance
from itertools import combinations
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.word_embeddings_300d
collection = db.embeddings
def get_coherence_score(topics, documents, dictionary, coherence, no_of_words=20):
| 64 | 64 | 175 | 20 | 43 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | get_coherence_score | get_coherence_score | 16 | 42 | 16 | 16 | 5d6c482c54622909159854b17ea56365c15e57b2 | bigcode/the-stack | train |
8a0dd9dff62589c637e9b42a | train | function | def create_dictionary(documents):
"""Creates word dictionary for given corpus.
Parameters:
documents (list of str): set of documents
Returns:
dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset
"""
dictionary = Dictionary(documents)
dictionary.compactif... | def create_dictionary(documents):
| """Creates word dictionary for given corpus.
Parameters:
documents (list of str): set of documents
Returns:
dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset
"""
dictionary = Dictionary(documents)
dictionary.compactify()
return dictionary
| ):
topic_diversity = topic_diversity + 1
topic_diversity_scores.append(Decimal(topic_diversity) / Decimal(no_of_words))
return float(Decimal(sum(topic_diversity_scores)) / Decimal(len(topic_diversity_scores)))
def create_dictionary(documents):
| 63 | 64 | 72 | 6 | 57 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | create_dictionary | create_dictionary | 73 | 87 | 73 | 73 | 44fb77f3dc02a1610aaf5eb76c8645b88ccd5f5d | bigcode/the-stack | train |
a12c56105ddc9af7e5acd26b | train | function | def get_words_from_db(word1, word2):
print(f'word1={word1}, word2={word2}')
w1 = collection.find_one({ "word": word1 })
w2 = collection.find_one({ "word": word2 })
print(f'w1={w1}, w1={w2}')
def f(x): return float(x)
return list(map(f, w1)), list(map(f, w2))
| def get_words_from_db(word1, word2):
| print(f'word1={word1}, word2={word2}')
w1 = collection.find_one({ "word": word1 })
w2 = collection.find_one({ "word": word2 })
print(f'w1={w1}, w1={w2}')
def f(x): return float(x)
return list(map(f, w1)), list(map(f, w2))
| =1.0):
vectorizer = CountVectorizer(min_df=min_df, max_df=max_df)
vectorizer.fit_transform(documents)
return [[word for word in document if word not in vectorizer.stop_words_] for document in documents]
def get_words_from_db(word1, word2):
| 64 | 64 | 95 | 11 | 53 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | get_words_from_db | get_words_from_db | 97 | 106 | 97 | 97 | 98e781ddd0cf394095dc3e46d14f9cc3339b7624 | bigcode/the-stack | train |
497bb294f9d2c8f6255e1ee9 | train | function | def get_topic_word_matrix(topic_word_mtx, k, idx2token):
topics = []
for i in range(k):
words_dists = list(topic_word_mtx[i].cpu().numpy())
component_words = [idx2token[idx]
for idx, _ in enumerate(words_dists)]
topics.append(component_words)
return topics... | def get_topic_word_matrix(topic_word_mtx, k, idx2token):
| topics = []
for i in range(k):
words_dists = list(topic_word_mtx[i].cpu().numpy())
component_words = [idx2token[idx]
for idx, _ in enumerate(words_dists)]
topics.append(component_words)
return topics
| :
w1, w2 = get_words_from_db(word1, word2)
dist += distance.cosine(w1, w2)
sum_dist += dist / topk
return sum_dist / len(topics)
def get_topic_word_matrix(topic_word_mtx, k, idx2token):
| 64 | 64 | 74 | 16 | 48 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | get_topic_word_matrix | get_topic_word_matrix | 128 | 135 | 128 | 128 | dc374ba69b61b5e5b4eb99c580d014030381f339 | bigcode/the-stack | train |
9b57dd73c606a8edeaa761df | train | function | def get_topic_diversity(topics, no_of_words=20):
"""Calculates topic diversity for given topics. Topic diversity is defined as
the frequency in which words are associated with a single topic
Parameters:
topics (list of str list): topic words for each topic
Returns:
float: diversity score
... | def get_topic_diversity(topics, no_of_words=20):
| """Calculates topic diversity for given topics. Topic diversity is defined as
the frequency in which words are associated with a single topic
Parameters:
topics (list of str list): topic words for each topic
Returns:
float: diversity score
"""
word_frequencies_per_topic = [Counter(t... | : coherence score
"""
coherence_model = CoherenceModel(
topics=topics,
texts=documents,
dictionary=dictionary,
coherence=coherence,
processes=0,
topn=no_of_words
)
return coherence_model.get_coherence()
d... | 75 | 75 | 253 | 15 | 60 | lffloyd/reddit-topic-modelling | training/utils/metrics.py | Python | get_topic_diversity | get_topic_diversity | 45 | 70 | 45 | 45 | 3b57a978cf3ef8047a886d3b541b6baf1c8c4604 | bigcode/the-stack | train |
e489ae258ba471510ecd690d | train | function | @pytest.mark.user_report
def test_cast_popularity(client):
result = most_active_commenters()
assert len(result) == 20
| @pytest.mark.user_report
def test_cast_popularity(client):
| result = most_active_commenters()
assert len(result) == 20
| """
Test file for database methods written in db.py
All test methods must receive client as an argument,
otherwise the database variable won't be configured correctly
"""
from mflix.db import most_active_commenters
import pytest
@pytest.mark.user_report
def test_cast_popularity(client):
| 56 | 64 | 29 | 12 | 43 | helpthx/MongoDB-University- | M220P: MongoDB for Python Developers/mflix-python/tests/test_user_report.py | Python | test_cast_popularity | test_cast_popularity | 11 | 14 | 11 | 12 | a6cec655b0ed810df0103051f3145da158db6553 | bigcode/the-stack | train |
bd4ef1359c48391586bbcdaa | train | function | @pytest.mark.user_report
def test_check_report(client):
result = most_active_commenters()
assert {'_id': 'roger_ashton-griffiths@gameofthron.es', 'count': 909} in result
| @pytest.mark.user_report
def test_check_report(client):
| result = most_active_commenters()
assert {'_id': 'roger_ashton-griffiths@gameofthron.es', 'count': 909} in result
| ,
otherwise the database variable won't be configured correctly
"""
from mflix.db import most_active_commenters
import pytest
@pytest.mark.user_report
def test_cast_popularity(client):
result = most_active_commenters()
assert len(result) == 20
@pytest.mark.user_report
def test_check_report(client):
| 64 | 64 | 49 | 11 | 52 | helpthx/MongoDB-University- | M220P: MongoDB for Python Developers/mflix-python/tests/test_user_report.py | Python | test_check_report | test_check_report | 17 | 20 | 17 | 18 | 335b6e7ddfcf55293682c2c905bcaa023c851479 | bigcode/the-stack | train |
e7c992aa76c3016aa0b39a24 | train | class | class Timer(object):
"""
Easy to use timer to keep track of long during operations.
"""
def __init__(self, start_time=None, resumable=False):
"""
Remember the time when the :class:`Timer` was created.
:param start_time: The start time (a float, defaults to the current time).
... | class Timer(object):
| """
Easy to use timer to keep track of long during operations.
"""
def __init__(self, start_time=None, resumable=False):
"""
Remember the time when the :class:`Timer` was created.
:param start_time: The start time (a float, defaults to the current time).
:param resumabl... | an example of its usage:
>>> from os import environ
>>> from os.path import join
>>> vimrc = join(environ['HOME'], '.vimrc')
>>> vimrc
'/home/peter/.vimrc'
>>> from humanfriendly import format_path
>>> format_path(vimrc)
'~/.vimrc'
"""
pathname = os.path.abspath(pathname)
h... | 245 | 246 | 820 | 4 | 241 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | Timer | Timer | 640 | 740 | 640 | 641 | 80b7ebd4d4c4e7cc3e16d0133cbfcd00827bde27 | bigcode/the-stack | train |
f964e2274fb21e424b1b4345 | train | function | def coerce_seconds(value):
"""
Coerce a value to the number of seconds.
:param value: An :class:`int`, :class:`float` or
:class:`datetime.timedelta` object.
:returns: An :class:`int` or :class:`float` value.
When `value` is a :class:`datetime.timedelta` object the
:meth:`~dat... | def coerce_seconds(value):
| """
Coerce a value to the number of seconds.
:param value: An :class:`int`, :class:`float` or
:class:`datetime.timedelta` object.
:returns: An :class:`int` or :class:`float` value.
When `value` is a :class:`datetime.timedelta` object the
:meth:`~datetime.timedelta.total_secon... | )
else:
empty_pattern = re.compile('')
pattern_type = type(empty_pattern)
if not isinstance(value, pattern_type):
msg = "Failed to coerce value to compiled regular expression! (%r)"
raise ValueError(format(msg, value))
return value
def coerce_seconds(value):
| 64 | 64 | 149 | 6 | 57 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | coerce_seconds | coerce_seconds | 141 | 157 | 141 | 141 | a6de59d5afb785f916b0acdc7f938b190d7dabeb | bigcode/the-stack | train |
e805746f8e34b5f0e3dae5e4 | train | function | def format_size(num_bytes, keep_width=False, binary=False):
"""
Format a byte count as a human readable file size.
:param num_bytes: The size to format in bytes (an integer).
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be st... | def format_size(num_bytes, keep_width=False, binary=False):
| """
Format a byte count as a human readable file size.
:param num_bytes: The size to format in bytes (an integer).
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be stripped.
:param binary: :data:`True` to use binary multip... | :class:`int` or :class:`float` value.
When `value` is a :class:`datetime.timedelta` object the
:meth:`~datetime.timedelta.total_seconds()` method is called.
"""
if isinstance(value, datetime.timedelta):
return value.total_seconds()
if not isinstance(value, numbers.Number):
msg = "F... | 111 | 111 | 372 | 13 | 97 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | format_size | format_size | 160 | 195 | 160 | 160 | 62b3add3cf9a0384e9894333362765e58de4e50d | bigcode/the-stack | train |
a4d5aa282ab8fa3f54459b44 | train | function | def format_path(pathname):
"""
Shorten a pathname to make it more human friendly.
:param pathname: An absolute pathname (a string).
:returns: The pathname with the user's home directory abbreviated.
Given an absolute pathname, this function abbreviates the user's home
directory to ``~/`` in or... | def format_path(pathname):
| """
Shorten a pathname to make it more human friendly.
:param pathname: An absolute pathname (a string).
:returns: The pathname with the user's home directory abbreviated.
Given an absolute pathname, this function abbreviates the user's home
directory to ``~/`` in order to shorten the pathname... | return (year, month, day, 0, 0, 0)
except Exception:
msg = "Invalid date! (expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' but got: %r)"
raise InvalidDate(format(msg, datestring))
def format_path(pathname):
| 69 | 69 | 232 | 6 | 63 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | format_path | format_path | 594 | 623 | 594 | 594 | 81d405c4aa77d992ad056a6a4a6d0015d17a9100 | bigcode/the-stack | train |
11d42b9fa41c2937100a4a42 | train | function | def parse_size(size, binary=False):
"""
Parse a human readable data size and return the number of bytes.
:param size: The human readable file size to parse (a string).
:param binary: :data:`True` to use binary multiples of bytes (base-2) for
ambiguous unit symbols and names, :data:`F... | def parse_size(size, binary=False):
| """
Parse a human readable data size and return the number of bytes.
:param size: The human readable file size to parse (a string).
:param binary: :data:`True` to use binary multiples of bytes (base-2) for
ambiguous unit symbols and names, :data:`False` to use
deci... | _size(0)
'0 bytes'
>>> format_size(1)
'1 byte'
>>> format_size(5)
'5 bytes'
> format_size(1000)
'1 KB'
> format_size(1024, binary=True)
'1 KiB'
>>> format_size(1000 ** 3 * 4)
'4 GB'
"""
for unit in reversed(disk_size_units):
if num_bytes >= unit.binary.divider... | 211 | 211 | 705 | 8 | 203 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | parse_size | parse_size | 198 | 259 | 198 | 198 | 5900f6352fc9faac198b4212328a7ea83a061fef | bigcode/the-stack | train |
643ac182ff682a660fc8c240 | train | class | class InvalidSize(Exception):
"""
Raised when a string cannot be parsed into a file size.
For example:
>>> from humanfriendly import parse_size
>>> parse_size('5 Z')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 267, in parse_size
raise InvalidSize(fo... | class InvalidSize(Exception):
| """
Raised when a string cannot be parsed into a file size.
For example:
>>> from humanfriendly import parse_size
>>> parse_size('5 Z')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 267, in parse_size
raise InvalidSize(format(msg, size, tokens))
hu... | line 206, in parse_date
raise InvalidDate(format(msg, datestring))
humanfriendly.InvalidDate: Invalid date! (expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' but got: '2013-06-XY')
"""
class InvalidSize(Exception):
| 63 | 64 | 108 | 5 | 58 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | InvalidSize | InvalidSize | 759 | 772 | 759 | 760 | 5c28829c2cad94656bf67e867d811e3dcda0046a | bigcode/the-stack | train |
dc729a2936e2ede996e62a0d | train | function | def parse_timespan(timespan):
"""
Parse a "human friendly" timespan into the number of seconds.
:param value: A string like ``5h`` (5 hours), ``10m`` (10 minutes) or
``42s`` (42 seconds).
:returns: The number of seconds as a floating point number.
:raises: :exc:`InvalidTimespan` w... | def parse_timespan(timespan):
| """
Parse a "human friendly" timespan into the number of seconds.
:param value: A string like ``5h`` (5 hours), ``10m`` (10 minutes) or
``42s`` (42 seconds).
:returns: The number of seconds as a floating point number.
:raises: :exc:`InvalidTimespan` when the input can't be parsed.... | if unit != relevant_units[-1]:
# Integer rounding for all but the smallest unit.
count = int(count)
else:
# Floating point rounding for the smallest unit.
count = round_number(count)
# Only include relevant units in the ... | 161 | 161 | 538 | 7 | 154 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | parse_timespan | parse_timespan | 466 | 520 | 466 | 466 | aabb3ec7d939e459985060f691e1736b95deeb50 | bigcode/the-stack | train |
55d56056f6cf33a83cad6735 | train | function | def format_number(number, num_decimals=2):
"""
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no... | def format_number(number, num_decimals=2):
| """
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no
decimal places ar... | 1]):
normalized_unit = tokens[1].lower()
# Try to match the first letter of the unit.
for unit in length_size_units:
if normalized_unit.startswith(unit['prefix']):
return tokens[0] * unit['divider']
# We failed to parse the length specification... | 104 | 104 | 348 | 11 | 93 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | format_number | format_number | 331 | 368 | 331 | 331 | db923ac61f48a1b124a0a4a970376b879b434e6a | bigcode/the-stack | train |
ea645d1940723d480a247b74 | train | function | def round_number(count, keep_width=False):
"""
Round a floating point number to two decimal places in a human friendly format.
:param count: The number to format.
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be stripped.
... | def round_number(count, keep_width=False):
| """
Round a floating point number to two decimal places in a human friendly format.
:param count: The number to format.
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be stripped.
:returns: The formatted number as a string.... | _number = ''.join(reversed(','.join(parts)))
decimals_to_add = decimal_part[:num_decimals].rstrip('0')
if decimals_to_add:
formatted_number += '.' + decimals_to_add
if negative_sign:
formatted_number = '-' + formatted_number
return formatted_number
def round_number(count, keep_width=Fals... | 71 | 71 | 237 | 9 | 61 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | round_number | round_number | 371 | 399 | 371 | 371 | 5470df638f07c019266d0e32868eb2c04477392c | bigcode/the-stack | train |
1772e17919898d71cd227740 | train | class | class InvalidDate(Exception):
"""
Raised when a string cannot be parsed into a date.
For example:
>>> from humanfriendly import parse_date
>>> parse_date('2013-06-XY')
Traceback (most recent call last):
File "humanfriendly.py", line 206, in parse_date
raise InvalidDate(format(ms... | class InvalidDate(Exception):
| """
Raised when a string cannot be parsed into a date.
For example:
>>> from humanfriendly import parse_date
>>> parse_date('2013-06-XY')
Traceback (most recent call last):
File "humanfriendly.py", line 206, in parse_date
raise InvalidDate(format(msg, datestring))
humanfriend... | rounded(self):
"""Human readable timespan rounded to seconds (a string)."""
return format_timespan(round(self.elapsed_time))
def __str__(self):
"""Show the elapsed time since the :class:`Timer` was created."""
return format_timespan(self.elapsed_time)
class InvalidDate(Exception):
... | 64 | 64 | 118 | 5 | 59 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | InvalidDate | InvalidDate | 743 | 756 | 743 | 744 | c239fd15d66fa482adfcb4f7bc0a69507f72bf11 | bigcode/the-stack | train |
d25a39d7f5f5866a1a0bc9ca | train | class | class InvalidTimespan(Exception):
"""
Raised when a string cannot be parsed into a timespan.
For example:
>>> from humanfriendly import parse_timespan
>>> parse_timespan('1 age')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 419, in parse_timespan
rai... | class InvalidTimespan(Exception):
| """
Raised when a string cannot be parsed into a timespan.
For example:
>>> from humanfriendly import parse_timespan
>>> parse_timespan('1 age')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 419, in parse_timespan
raise InvalidTimespan(format(msg, time... | File "humanfriendly/__init__.py", line 267, in parse_length
raise InvalidLength(format(msg, length, tokens))
humanfriendly.InvalidLength: Failed to parse length! (input '5 Z' was tokenized as [5, 'Z'])
"""
class InvalidTimespan(Exception):
| 63 | 64 | 116 | 6 | 57 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | InvalidTimespan | InvalidTimespan | 791 | 804 | 791 | 792 | 36b2e19ff7e71c499ab0f76debbbcb444eb239df | bigcode/the-stack | train |
4c76dbb581709ec214443b37 | train | function | def parse_length(length):
"""
Parse a human readable length and return the number of metres.
:param length: The human readable length to parse (a string).
:returns: The corresponding length in metres (a float).
:raises: :exc:`InvalidLength` when the input can't be parsed.
Some examples:
>... | def parse_length(length):
| """
Parse a human readable length and return the number of metres.
:param length: The human readable length to parse (a string).
:returns: The corresponding length in metres (a float).
:raises: :exc:`InvalidLength` when the input can't be parsed.
Some examples:
>>> from humanfriendly impo... | '1 km'
>>> format_length(0.004)
'4 mm'
"""
for unit in reversed(length_size_units):
if num_metres >= unit['divider']:
number = round_number(float(num_metres) / unit['divider'], keep_width=keep_width)
return pluralize(number, unit['singular'], unit['plural'])
return p... | 92 | 92 | 308 | 5 | 87 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | parse_length | parse_length | 294 | 328 | 294 | 294 | cd9d8a93a6ecbf4eb0ef9c609fb50dd1a76e707a | bigcode/the-stack | train |
59acb8584c430016e78db4a2 | train | class | class InvalidLength(Exception):
"""
Raised when a string cannot be parsed into a length.
For example:
>>> from humanfriendly import parse_length
>>> parse_length('5 Z')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 267, in parse_length
raise InvalidLe... | class InvalidLength(Exception):
| """
Raised when a string cannot be parsed into a length.
For example:
>>> from humanfriendly import parse_length
>>> parse_length('5 Z')
Traceback (most recent call last):
File "humanfriendly/__init__.py", line 267, in parse_length
raise InvalidLength(format(msg, length, tokens))... | File "humanfriendly/__init__.py", line 267, in parse_size
raise InvalidSize(format(msg, size, tokens))
humanfriendly.InvalidSize: Failed to parse size! (input '5 Z' was tokenized as [5, 'Z'])
"""
class InvalidLength(Exception):
| 63 | 64 | 107 | 5 | 58 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | InvalidLength | InvalidLength | 775 | 788 | 775 | 776 | 97b0224f4d7637a59ef5c75321fcc17ef458c13b | bigcode/the-stack | train |
f3111fca1c5c1f230ad48825 | train | function | def parse_date(datestring):
"""
Parse a date/time string into a tuple of integers.
:param datestring: The date/time string to parse.
:returns: A tuple with the numbers ``(year, month, day, hour, minute,
second)`` (all numbers are integers).
:raises: :exc:`InvalidDate` when the date ca... | def parse_date(datestring):
| """
Parse a date/time string into a tuple of integers.
:param datestring: The date/time string to parse.
:returns: A tuple with the numbers ``(year, month, day, hour, minute,
second)`` (all numbers are integers).
:raises: :exc:`InvalidDate` when the date cannot be parsed.
Support... | parse_timespan('1h')
3600.0
>>> parse_timespan('1d')
86400.0
"""
tokens = tokenize(timespan)
if tokens and isinstance(tokens[0], numbers.Number):
# If the input contains only a number, it's assumed to be the number of seconds.
if len(tokens) == 1:
return float(tokens... | 231 | 231 | 772 | 7 | 224 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | parse_date | parse_date | 523 | 591 | 523 | 523 | 0ef59c1ea73083b433aa8d5bed7e67575fb442e1 | bigcode/the-stack | train |
b91239d1a5f92ff46ad7ddb1 | train | function | def format_timespan(num_seconds, detailed=False, max_units=3):
"""
Format a timespan in seconds as a human readable string.
:param num_seconds: Any value accepted by :func:`coerce_seconds()`.
:param detailed: If :data:`True` milliseconds are represented separately
instead of being ... | def format_timespan(num_seconds, detailed=False, max_units=3):
| """
Format a timespan in seconds as a human readable string.
:param num_seconds: Any value accepted by :func:`coerce_seconds()`.
:param detailed: If :data:`True` milliseconds are represented separately
instead of being represented as fractional seconds
(default... | number, they will be omitted.
The main purpose of this function is to be used by functions like
:func:`format_length()`, :func:`format_size()` and
:func:`format_timespan()`.
Here are some examples:
>>> from humanfriendly import round_number
>>> round_number(1)
'1'
>>> round_number(ma... | 162 | 162 | 542 | 15 | 146 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | format_timespan | format_timespan | 402 | 463 | 402 | 402 | a55822b81953d74af8748abad85704e29cf1b225 | bigcode/the-stack | train |
00d61ea50d3c6e7665362c91 | train | function | def format_length(num_metres, keep_width=False):
"""
Format a metre count as a human readable length.
:param num_metres: The length to format in metres (float / integer).
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be stripp... | def format_length(num_metres, keep_width=False):
| """
Format a metre count as a human readable length.
:param num_metres: The length to format in metres (float / integer).
:param keep_width: :data:`True` if trailing zeros should not be stripped,
:data:`False` if they can be stripped.
:returns: The corresponding human readabl... | int(tokens[0] * (unit.binary.divider if binary else unit.decimal.divider))
# We failed to parse the size specification.
msg = "Failed to parse size! (input %r was tokenized as %r)"
raise InvalidSize(format(msg, size, tokens))
def format_length(num_metres, keep_width=False):
| 72 | 72 | 243 | 11 | 61 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | format_length | format_length | 262 | 291 | 262 | 262 | 36aa3503ea3cc7a397923d0c18dd02f0dd32d018 | bigcode/the-stack | train |
d47ba17bf4406d79b0cd4cd3 | train | function | def coerce_boolean(value):
"""
Coerce any value to a boolean.
:param value: Any Python value. If the value is a string:
- The strings '1', 'yes', 'true' and 'on' are coerced to :data:`True`.
- The strings '0', 'no', 'false' and 'off' are coerced to :data:`False`.
... | def coerce_boolean(value):
| """
Coerce any value to a boolean.
:param value: Any Python value. If the value is a string:
- The strings '1', 'yes', 'true' and 'on' are coerced to :data:`True`.
- The strings '0', 'no', 'false' and 'off' are coerced to :data:`False`.
- Other strings... | d']),
dict(divider=60 * 60 * 24 * 7, singular='week', plural='weeks', abbreviations=['w']),
dict(divider=60 * 60 * 24 * 7 * 52, singular='year', plural='years', abbreviations=['y']))
def coerce_boolean(value):
| 69 | 70 | 235 | 6 | 63 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | coerce_boolean | coerce_boolean | 91 | 116 | 91 | 91 | 3f2d27f5d9fbc97ee749c6996e90bb529e62e1a1 | bigcode/the-stack | train |
29305dd797ad4234d35f70db | train | function | def parse_path(pathname):
"""
Convert a human friendly pathname to an absolute pathname.
Expands leading tildes using :func:`os.path.expanduser()` and
environment variables using :func:`os.path.expandvars()` and makes the
resulting pathname absolute using :func:`os.path.abspath()`.
:param path... | def parse_path(pathname):
| """
Convert a human friendly pathname to an absolute pathname.
Expands leading tildes using :func:`os.path.expanduser()` and
environment variables using :func:`os.path.expandvars()` and makes the
resulting pathname absolute using :func:`os.path.abspath()`.
:param pathname: A human friendly pat... | pathname = os.path.abspath(pathname)
home = os.environ.get('HOME')
if home:
home = os.path.abspath(home)
if pathname.startswith(home):
pathname = os.path.join('~', os.path.relpath(pathname, home))
return pathname
def parse_path(pathname):
| 64 | 64 | 108 | 6 | 57 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | parse_path | parse_path | 626 | 637 | 626 | 626 | 24e968053288640a8b5b22876010da7a7a496451 | bigcode/the-stack | train |
0767ad49784b89e96f1e9918 | train | function | def coerce_pattern(value, flags=0):
"""
Coerce strings to compiled regular expressions.
:param value: A string containing a regular expression pattern
or a compiled regular expression.
:param flags: The flags used to compile the pattern (an integer).
:returns: A compiled regular e... | def coerce_pattern(value, flags=0):
| """
Coerce strings to compiled regular expressions.
:param value: A string containing a regular expression pattern
or a compiled regular expression.
:param flags: The flags used to compile the pattern (an integer).
:returns: A compiled regular expression.
:raises: :exc:`~excep... | in ('0', 'no', 'false', 'off', ''):
return False
else:
msg = "Failed to coerce string to boolean! (%r)"
raise ValueError(format(msg, value))
else:
return bool(value)
def coerce_pattern(value, flags=0):
| 64 | 64 | 169 | 10 | 54 | melund/python-humanfriendly | humanfriendly/__init__.py | Python | coerce_pattern | coerce_pattern | 119 | 138 | 119 | 119 | eb49113a286fe3fc7d66ac27743421444afe9616 | bigcode/the-stack | train |
d5b54887056065b64c4f3f43 | train | class | class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='TeacherEvent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date', models.... | class Migration(migrations.Migration):
| dependencies = [
]
operations = [
migrations.CreateModel(
name='TeacherEvent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date', models.DateField(help_text=b'Date of this event... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 200 | 668 | 7 | 23 | naderm/farnsworth | legacy/migrations/0001_initial.py | Python | Migration | Migration | 7 | 68 | 7 | 8 | 23aff7cb7eb1621aa212e4197b809ec061cff459 | bigcode/the-stack | train |
7793a52e95fe0c77a0b03f6f | train | class | class Migration(migrations.Migration):
dependencies = [
('workout', '0003_auto_20161024_1632'),
]
operations = [
migrations.AlterField(
model_name='workout',
name='exercises',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.dele... | class Migration(migrations.Migration):
| dependencies = [
('workout', '0003_auto_20161024_1632'),
]
operations = [
migrations.AlterField(
model_name='workout',
name='exercises',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workout.Exercise'),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-24 20:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 61 | 64 | 131 | 7 | 53 | audiolion/py-fitness | py_fitness/py_fitness/workout/migrations/0004_auto_20161024_1634.py | Python | Migration | Migration | 9 | 26 | 9 | 10 | 7079c449b0bfd80ed3a625a85ac5e6a0a3499441 | bigcode/the-stack | train |
f9fff0c1c191936d15552526 | train | function | def sample_user(email='test@donovandev.com', password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
| def sample_user(email='test@donovandev.com', password='testpass'):
| """Create a sample user"""
return get_user_model().objects.create_user(email, password)
| from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@donovandev.com', password='testpass'):
| 39 | 64 | 38 | 18 | 20 | vdonoso007/recipe-app-api | app/core/tests/test_models.py | Python | sample_user | sample_user | 6 | 8 | 6 | 6 | a9bf1dfddb6f8b1d5cdbfe187fa6d9a9eba9ccc5 | bigcode/the-stack | train |
60f0c250cbd64b61469e31a8 | train | class | class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creating new user with an email is successfull"""
email = "test@donovandev.com"
password = "Testcase123"
user = get_user_model().objects.create_user(
email=email,
password=p... | class ModelTests(TestCase):
| def test_create_user_with_email_successful(self):
"""Test creating new user with an email is successfull"""
email = "test@donovandev.com"
password = "Testcase123"
user = get_user_model().objects.create_user(
email=email,
password=password
)
se... | from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='test@donovandev.com', password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
class ModelTests(TestCase):
| 65 | 90 | 302 | 6 | 59 | vdonoso007/recipe-app-api | app/core/tests/test_models.py | Python | ModelTests | ModelTests | 11 | 54 | 11 | 12 | 267876e59bea9a2065a0e50677cc36ed7be527ba | bigcode/the-stack | train |
83011a84229c64c157182abb | train | function | def _get_figure_class(tvar_name, auto_color=True, slice=False, show_xaxis=True):
if 'plotter' in pytplot.data_quants[tvar_name].attrs['plot_options']['extras'] \
and pytplot.data_quants[tvar_name].attrs['plot_options']['extras']['plotter'] in pytplot.bokeh_plotters:
cls = pytplot.bokeh_plotters[... | def _get_figure_class(tvar_name, auto_color=True, slice=False, show_xaxis=True):
| if 'plotter' in pytplot.data_quants[tvar_name].attrs['plot_options']['extras'] \
and pytplot.data_quants[tvar_name].attrs['plot_options']['extras']['plotter'] in pytplot.bokeh_plotters:
cls = pytplot.bokeh_plotters[pytplot.data_quants[tvar_name].attrs['plot_options']['extras']['plotter']]
el... | _type[axis_types[k][0]]][0].x_range
if axis_types[k][1]:
all_plots[k][0].y_range = all_plots[first_type[axis_types[k][0]]][0].y_range
k += 1
return gridplot(all_plots)
def _get_figure_class(tvar_name, auto_color=True, slice=False, show_xaxis=True):
| 87 | 87 | 293 | 22 | 65 | xnchu/PyTplot | pytplot/HTMLPlotter/generate.py | Python | _get_figure_class | _get_figure_class | 127 | 143 | 127 | 127 | 86347546f5262607a31702cb5380d0b93dcc67be | bigcode/the-stack | train |
311fc74b647534940831c067 | train | function | def generate_stack(name,
var_label=None,
auto_color=True,
combine_axes=True,
slice=True,
vert_spacing=25):
doc.curdoc().clear()
num_plots = len(name)
# Name for .html file containing plots
out_name... | def generate_stack(name,
var_label=None,
auto_color=True,
combine_axes=True,
slice=True,
vert_spacing=25):
| doc.curdoc().clear()
num_plots = len(name)
# Name for .html file containing plots
out_name = ""
if isinstance(var_label, int):
var_label = list(pytplot.data_quants.keys())[var_label]
# Vertical Box layout to store plots
all_plots = []
axis_types = []
i = 0
... | # Copyright 2018 Regents of the University of Colorado. All Rights Reserved.
# Released under the MIT license.
# This software was developed at the University of Colorado's Laboratory for Atmospheric and Space Physics.
# Verify current version before use at: https://github.com/MAVENSDC/PyTplot
from __future__ import d... | 148 | 256 | 975 | 33 | 114 | xnchu/PyTplot | pytplot/HTMLPlotter/generate.py | Python | generate_stack | generate_stack | 15 | 124 | 15 | 21 | dffb26e284b20c27c487c6cb2f0deca80a4c9ad3 | bigcode/the-stack | train |
c0b9d9453f7a07ba65d3f806 | train | function | def isorthonormal(R):
"""
Check if R is orthonormal
Parameters
----------
R : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
False or True
"""
_,ncol = R.shape
for i,j in combinations(range(ncol), 2):
if ( R[:,i].dot(R[:,j]) ).simpl... | def isorthonormal(R):
| """
Check if R is orthonormal
Parameters
----------
R : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
False or True
"""
_,ncol = R.shape
for i,j in combinations(range(ncol), 2):
if ( R[:,i].dot(R[:,j]) ).simplify() != 0:
... | atrices.dense.MutableDenseMatrix`
Returns
-------
False or True
"""
nrow,ncol = R.shape
if (nrow == ncol == 3) and isorthonormal(R):
return True
return False
def isorthonormal(R):
| 64 | 64 | 128 | 7 | 56 | iro-upgto/rkd | rkd/didactic/util.py | Python | isorthonormal | isorthonormal | 116 | 138 | 116 | 116 | da8af515fd983196edcee22551735be6249d9f70 | bigcode/the-stack | train |
bc81c52958dbcb5f7dd889f1 | train | function | def issympyobject(obj):
"""
Determine if input (obj) is a sympy object.
Examples
--------
>>> from sympy import symbols
>>> x = symbols("x")
>>> issympyobject(x)
True
"""
if isinstance( obj, tuple(sc.all_classes ) ):
return True
elif isinstance(obj, Basic):
... | def issympyobject(obj):
| """
Determine if input (obj) is a sympy object.
Examples
--------
>>> from sympy import symbols
>>> x = symbols("x")
>>> issympyobject(x)
True
"""
if isinstance( obj, tuple(sc.all_classes ) ):
return True
elif isinstance(obj, Basic):
return True
elif ... | : float, int, symbolic
Returns
-------
theta_deg : symbolic
"""
if evalf:
theta_deg = ( theta*(180/pi) ).evalf()
else:
theta_deg = theta*(180/pi)
return theta_deg
def issympyobject(obj):
| 64 | 64 | 105 | 7 | 56 | iro-upgto/rkd | rkd/didactic/util.py | Python | issympyobject | issympyobject | 66 | 84 | 66 | 66 | ef5a8c98493dd9d65ae6e5c4d95c2aff11097c28 | bigcode/the-stack | train |
03cc5404fc3d4bad516878e9 | train | function | def sympy2float(sympy_object):
"""
Convert a SymPy object to float object
"""
if isinstance(sympy_object, Matrix):
float_object = sympy_matrix_to_numpy_float(sympy_object)
else:
float_object = sympy_object
return float_object
| def sympy2float(sympy_object):
| """
Convert a SymPy object to float object
"""
if isinstance(sympy_object, Matrix):
float_object = sympy_matrix_to_numpy_float(sympy_object)
else:
float_object = sympy_object
return float_object
| array
Parameters
----------
H : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
Hf : array
"""
Hf = np.array(H).astype("float64")
return Hf
def sympy2float(sympy_object):
| 64 | 64 | 62 | 9 | 54 | iro-upgto/rkd | rkd/didactic/util.py | Python | sympy2float | sympy2float | 159 | 167 | 159 | 159 | 1cfa9d364f75dc0bd5c0232369bd408f7a092023 | bigcode/the-stack | train |
31d0ea419c59e44959f576cf | train | function | def ishtm(H):
"""
Is H a homogeneous transformation matrix ?
"""
nrow,ncol = H.shape
if nrow == ncol == 4:
return True
return False
| def ishtm(H):
| """
Is H a homogeneous transformation matrix ?
"""
nrow,ncol = H.shape
if nrow == ncol == 4:
return True
return False
| ympyobject(x)
True
"""
if isinstance( obj, tuple(sc.all_classes ) ):
return True
elif isinstance(obj, Basic):
return True
elif isinstance(obj, sm.MatrixBase):
return True
else:
return False
def ishtm(H):
| 63 | 64 | 46 | 6 | 56 | iro-upgto/rkd | rkd/didactic/util.py | Python | ishtm | ishtm | 87 | 94 | 87 | 87 | 5d3a62a5dbd540ee0572cd5a264b5d7662c26ac9 | bigcode/the-stack | train |
54bda50eeb4c0d5ebf9f9631 | train | function | def deg2rad(theta, evalf=True):
"""
Convert degrees to radians
Parameters
----------
theta : float, int, symbolic
Returns
-------
theta_rad : symbolic
"""
if evalf:
theta_rad = ( theta*(pi/180) ).evalf()
else:
theta_rad = theta*(pi/180)
... | def deg2rad(theta, evalf=True):
| """
Convert degrees to radians
Parameters
----------
theta : float, int, symbolic
Returns
-------
theta_rad : symbolic
"""
if evalf:
theta_rad = ( theta*(pi/180) ).evalf()
else:
theta_rad = theta*(pi/180)
return theta_rad
| [
"deg2rad",
"ishtm",
"isorthonormal",
"isrot",
"rad2deg",
"sympy2float",
"sympy_matrix_to_numpy_float",
"issympyobject"
]
def deg2rad(theta, evalf=True):
| 64 | 64 | 85 | 10 | 54 | iro-upgto/rkd | rkd/didactic/util.py | Python | deg2rad | deg2rad | 24 | 42 | 24 | 24 | 5c4419a9b1c81ae8cc26b2bcf8b99a2ef321307b | bigcode/the-stack | train |
27507d62a4d82233f344f756 | train | function | def sympy_matrix_to_numpy_float(H):
"""
Convert SymPy Matrix (numerical) to NumPy array
Parameters
----------
H : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
Hf : array
"""
Hf = np.array(H).astype("float64")
return Hf
| def sympy_matrix_to_numpy_float(H):
| """
Convert SymPy Matrix (numerical) to NumPy array
Parameters
----------
H : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
Hf : array
"""
Hf = np.array(H).astype("float64")
return Hf
| if ( R[:,i].dot(R[:,j]) ).simplify() != 0:
return False
for i in range(ncol):
if R[:,i].norm().simplify() != 1:
return False
return True
def sympy_matrix_to_numpy_float(H):
| 64 | 64 | 78 | 9 | 54 | iro-upgto/rkd | rkd/didactic/util.py | Python | sympy_matrix_to_numpy_float | sympy_matrix_to_numpy_float | 141 | 157 | 141 | 141 | 44c484d4b1da7e1d8e38587647417338cfa64e9e | bigcode/the-stack | train |
0217ceff0f9b63baa8528193 | train | function | def rad2deg(theta, evalf=True):
"""
Convert radians to degrees
Parameters
----------
theta : float, int, symbolic
Returns
-------
theta_deg : symbolic
"""
if evalf:
theta_deg = ( theta*(180/pi) ).evalf()
else:
theta_deg = theta*(180/pi)
... | def rad2deg(theta, evalf=True):
| """
Convert radians to degrees
Parameters
----------
theta : float, int, symbolic
Returns
-------
theta_deg : symbolic
"""
if evalf:
theta_deg = ( theta*(180/pi) ).evalf()
else:
theta_deg = theta*(180/pi)
return theta_deg
| symbolic
Returns
-------
theta_rad : symbolic
"""
if evalf:
theta_rad = ( theta*(pi/180) ).evalf()
else:
theta_rad = theta*(pi/180)
return theta_rad
def rad2deg(theta, evalf=True):
| 64 | 64 | 83 | 10 | 53 | iro-upgto/rkd | rkd/didactic/util.py | Python | rad2deg | rad2deg | 45 | 63 | 45 | 45 | dc75b66d3ea8679097949cda199e419b1809a70f | bigcode/the-stack | train |
a24585146c5369f4564496e6 | train | function | def isrot(R):
"""
Is R a rotation matrix ?
Parameters
----------
R : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
False or True
"""
nrow,ncol = R.shape
if (nrow == ncol == 3) and isorthonormal(R):
return True
return False
| def isrot(R):
| """
Is R a rotation matrix ?
Parameters
----------
R : `sympy.matrices.dense.MutableDenseMatrix`
Returns
-------
False or True
"""
nrow,ncol = R.shape
if (nrow == ncol == 3) and isorthonormal(R):
return True
return False
| ):
return True
else:
return False
def ishtm(H):
"""
Is H a homogeneous transformation matrix ?
"""
nrow,ncol = H.shape
if nrow == ncol == 4:
return True
return False
def isrot(R):
| 64 | 64 | 85 | 5 | 58 | iro-upgto/rkd | rkd/didactic/util.py | Python | isrot | isrot | 96 | 114 | 96 | 96 | 415d326de35337cfb129a951500928abac44fbff | bigcode/the-stack | train |
0b40ffad531bcff696b02b14 | train | class | class CloudDBConfigGroup(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map ... | class CloudDBConfigGroup(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
clouddb
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CloudDBConfigGroup(object):
| 52 | 256 | 1,094 | 7 | 44 | NaverCloudPlatform/ncloud-sdk-python | lib/services/clouddb/ncloud_clouddb/model/cloud_db_config_group.py | Python | CloudDBConfigGroup | CloudDBConfigGroup | 17 | 167 | 17 | 17 | 290de674a7a896fc789ad43384bf3e8de82ec54b | bigcode/the-stack | train |
f8c809677992bcb847bff921 | train | class | class Initializer(object):
"""Base class for Initializer."""
def __call__(self, name, arr):
"""Override () function to do Initialization
Parameters
----------
name : str
name of corrosponding ndarray
arr : NDArray
ndarray to be Initialized
... | class Initializer(object):
| """Base class for Initializer."""
def __call__(self, name, arr):
"""Override () function to do Initialization
Parameters
----------
name : str
name of corrosponding ndarray
arr : NDArray
ndarray to be Initialized
"""
if not isins... | # coding: utf-8
"""Initialization helper for mxnet"""
from __future__ import absolute_import
import numpy as np
from .base import string_types
from .ndarray import NDArray
from . import random
class Initializer(object):
| 52 | 107 | 359 | 5 | 46 | danielpinero/prueba | python/mxnet/initializer.py | Python | Initializer | Initializer | 10 | 60 | 10 | 10 | 2f7bc938209428559ff57a3f1a468609778558d6 | bigcode/the-stack | train |
9087f21f3f7271d0a4608fb5 | train | class | class Normal(Initializer):
"""Initialize the weight with normal(0, sigma)
Parameters
----------
sigma : float, optional
Standard deviation for gaussian distribution.
"""
def __init__(self, sigma=0.01):
self.sigma = sigma
def _init_weight(self, _, arr):
random.normal... | class Normal(Initializer):
| """Initialize the weight with normal(0, sigma)
Parameters
----------
sigma : float, optional
Standard deviation for gaussian distribution.
"""
def __init__(self, sigma=0.01):
self.sigma = sigma
def _init_weight(self, _, arr):
random.normal(0, self.sigma, out=arr)
| scale : float, optional
The scale of uniform distribution
"""
def __init__(self, scale=0.07):
self.scale = scale
def _init_weight(self, _, arr):
random.uniform(-self.scale, self.scale, out=arr)
class Normal(Initializer):
| 64 | 64 | 82 | 5 | 59 | danielpinero/prueba | python/mxnet/initializer.py | Python | Normal | Normal | 78 | 90 | 78 | 78 | cb9d2b48866929d1d56a20a1a0df7421d7930edf | bigcode/the-stack | train |
90a1306ce880daa37c4d1b8c | train | class | class Xavier(Initializer):
"""Initialize the weight with Xavier initialization scheme."""
def _init_weight(self, _, arr):
shape = arr.shape
fan_in, fan_out = np.prod(shape[1:]), shape[0]
scale = np.sqrt(3. / (fan_in + fan_out))
random.uniform(-scale, scale, out=arr)
| class Xavier(Initializer):
| """Initialize the weight with Xavier initialization scheme."""
def _init_weight(self, _, arr):
shape = arr.shape
fan_in, fan_out = np.prod(shape[1:]), shape[0]
scale = np.sqrt(3. / (fan_in + fan_out))
random.uniform(-scale, scale, out=arr)
| sigma : float, optional
Standard deviation for gaussian distribution.
"""
def __init__(self, sigma=0.01):
self.sigma = sigma
def _init_weight(self, _, arr):
random.normal(0, self.sigma, out=arr)
class Xavier(Initializer):
| 64 | 64 | 77 | 5 | 59 | danielpinero/prueba | python/mxnet/initializer.py | Python | Xavier | Xavier | 93 | 100 | 93 | 93 | 5ee265412b8297574a8e0a3c6c356966fca5a450 | bigcode/the-stack | train |
3373d7a92ad08dbf4b7c2f7d | train | class | class Uniform(Initializer):
"""Initialize the weight with uniform [-scale, scale]
Parameters
----------
scale : float, optional
The scale of uniform distribution
"""
def __init__(self, scale=0.07):
self.scale = scale
def _init_weight(self, _, arr):
random.uniform(-s... | class Uniform(Initializer):
| """Initialize the weight with uniform [-scale, scale]
Parameters
----------
scale : float, optional
The scale of uniform distribution
"""
def __init__(self, scale=0.07):
self.scale = scale
def _init_weight(self, _, arr):
random.uniform(-self.scale, self.scale, out=a... | ):
"""Abstruct method to Initialize weight"""
raise NotImplementedError("Must override it")
def _init_default(self, name, _):
raise ValueError('Unknown initialization pattern for %s' % name)
# pylint: enable=no-self-use, missing-docstring
class Uniform(Initializer):
| 64 | 64 | 81 | 5 | 58 | danielpinero/prueba | python/mxnet/initializer.py | Python | Uniform | Uniform | 63 | 75 | 63 | 63 | 6b64ecdf7287a687c3295920e015076de583d7f1 | bigcode/the-stack | train |
e4e7df7badf74676d0f24012 | train | function | def print_screen():
for j in range(6):
print(''.join(screen[j]))
| def print_screen():
| for j in range(6):
print(''.join(screen[j]))
| = screen[j-1][i]
screen[0][i] = tmp
summ = 0
for i in range(50):
for j in range(6):
if screen[j][i] == '#':
summ += 1
return summ
def print_screen():
| 64 | 64 | 20 | 4 | 59 | madfist/aoc2016 | aoc2016/day08/main.py | Python | print_screen | print_screen | 37 | 39 | 37 | 37 | f124ceb642d7a0c6edc465db730c09cb5638f5c3 | bigcode/the-stack | train |
7f755efff2b9b9503a1152b9 | train | function | def count_pixels(data):
lines = data.split('\n')
for l in lines:
rect_cmd = re.match(r'rect\ (\d+)x(\d+)', l)
rotate_row_cmd = re.match(r'rotate\ row\ y=(\d+)\ by\ (\d+)', l)
rotate_col_cmd = re.match(r'rotate\ column\ x=(\d+)\ by\ (\d+)', l)
if rect_cmd is not None:
... | def count_pixels(data):
| lines = data.split('\n')
for l in lines:
rect_cmd = re.match(r'rect\ (\d+)x(\d+)', l)
rotate_row_cmd = re.match(r'rotate\ row\ y=(\d+)\ by\ (\d+)', l)
rotate_col_cmd = re.match(r'rotate\ column\ x=(\d+)\ by\ (\d+)', l)
if rect_cmd is not None:
for i in range(int(rect_... | import sys
import re
screen = [['_' for i in range(50)] for j in range(6)]
def count_pixels(data):
| 29 | 101 | 338 | 5 | 24 | madfist/aoc2016 | aoc2016/day08/main.py | Python | count_pixels | count_pixels | 6 | 35 | 6 | 6 | 47c88402f4313e85a7297f8d63904628a7ad4db0 | bigcode/the-stack | train |
bc1e435e0f40e9387b9eea76 | train | function | def main():
if (len(sys.argv) < 2):
print("Usage python3 %s <input>" % sys.argv[0])
exit(-1)
with open(sys.argv[1], 'r') as input:
data = input.read()
print("Pixel count:", count_pixels(data))
print_screen()
| def main():
| if (len(sys.argv) < 2):
print("Usage python3 %s <input>" % sys.argv[0])
exit(-1)
with open(sys.argv[1], 'r') as input:
data = input.read()
print("Pixel count:", count_pixels(data))
print_screen()
| summ = 0
for i in range(50):
for j in range(6):
if screen[j][i] == '#':
summ += 1
return summ
def print_screen():
for j in range(6):
print(''.join(screen[j]))
def main():
| 64 | 64 | 70 | 3 | 61 | madfist/aoc2016 | aoc2016/day08/main.py | Python | main | main | 41 | 48 | 41 | 41 | f8c4ef3f0c3598233bd9365b07ecea86051086cc | bigcode/the-stack | train |
62ab2e1ac6527fcea7483536 | train | class | class ReceiptRestServlet(RestServlet):
PATTERNS = client_v2_patterns(
"/rooms/(?P<room_id>[^/]*)"
"/receipt/(?P<receipt_type>[^/]*)"
"/(?P<event_id>[^/]*)$"
)
def __init__(self, hs):
super(ReceiptRestServlet, self).__init__()
self.hs = hs
self.auth = hs.get_a... | class ReceiptRestServlet(RestServlet):
| PATTERNS = client_v2_patterns(
"/rooms/(?P<room_id>[^/]*)"
"/receipt/(?P<receipt_type>[^/]*)"
"/(?P<event_id>[^/]*)$"
)
def __init__(self, hs):
super(ReceiptRestServlet, self).__init__()
self.hs = hs
self.auth = hs.get_auth()
self.receipts_handler = h... | # See the License for the specific language governing permissions and
# limitations under the License.
import logging
from twisted.internet import defer
from synapse.api.errors import SynapseError
from synapse.http.servlet import RestServlet
from ._base import client_v2_patterns
logger = logging.getLogger(__name__... | 71 | 71 | 239 | 7 | 64 | zauguin/synapse | synapse/rest/client/v2_alpha/receipts.py | Python | ReceiptRestServlet | ReceiptRestServlet | 28 | 58 | 28 | 28 | 97ed79b3f6689ffef6da18d16676ff4c180ee509 | bigcode/the-stack | train |
e8dc78dec9bb5fb19b5638f2 | train | function | def register_servlets(hs, http_server):
ReceiptRestServlet(hs).register(http_server)
| def register_servlets(hs, http_server):
| ReceiptRestServlet(hs).register(http_server)
| _presence_active_time(requester.user)
yield self.receipts_handler.received_client_receipt(
room_id,
receipt_type,
user_id=requester.user.to_string(),
event_id=event_id
)
defer.returnValue((200, {}))
def register_servlets(hs, http_server):
| 64 | 64 | 21 | 10 | 54 | zauguin/synapse | synapse/rest/client/v2_alpha/receipts.py | Python | register_servlets | register_servlets | 61 | 62 | 61 | 61 | 472d99436aad10e5456280b09c59c3c23229091e | bigcode/the-stack | train |
671465621cb245f87372ca35 | train | function | def sendSignupConfirmation(etherbase,email,extra):
fromaddr = username
toaddrs = email
msg = 'You have sucesssfully subscribed to the EasyWaltonMiner email alert system. \n \n' \
'You will now recieve email alerts for blocks mined to wallet: ' + etherbase + '.\n \n'
if (extra):
msg = msg + 'You will reci... | def sendSignupConfirmation(etherbase,email,extra):
| fromaddr = username
toaddrs = email
msg = 'You have sucesssfully subscribed to the EasyWaltonMiner email alert system. \n \n' \
'You will now recieve email alerts for blocks mined to wallet: ' + etherbase + '.\n \n'
if (extra):
msg = msg + 'You will recieve alerts only when the extra_data flag of a block... | so that we can address it.'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
return
def sendSignupConfirmation(etherbase,email,extra):
| 64 | 64 | 212 | 11 | 52 | scavicchio/easyWaltonTracker | app/emailService.py | Python | sendSignupConfirmation | sendSignupConfirmation | 50 | 67 | 50 | 50 | 11d8f2a1dc9968167edd2c9f3c96322e26c51730 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.