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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8abb002178400d795e344f1c | train | class | class Loop:
attr: Final['Loop']
| class Loop:
| attr: Final['Loop']
| float
class B(A):
x: ClassVar[Optional['B']] = None
y: int
b: int
class CSub(B):
z: ClassVar['CSub'] = B()
class G(Generic[T]):
lst: ClassVar[List[T]] = []
class Loop:
| 64 | 64 | 10 | 3 | 61 | Visva92/cpython | Lib/test/test_typing.py | Python | Loop | Loop | 2,982 | 2,983 | 2,982 | 2,982 | 32ea874e16230dc2dfcc49abd5ab50c1f006bf73 | bigcode/the-stack | train |
844e385d57fb4bad59ba759e | train | class | class OtherABCTests(BaseTestCase):
def test_contextmanager(self):
@contextlib.contextmanager
def manager():
yield 42
cm = manager()
self.assertIsInstance(cm, typing.ContextManager)
self.assertNotIsInstance(42, typing.ContextManager)
@skipUnless(ASYNCIO, 'Py... | class OtherABCTests(BaseTestCase):
| def test_contextmanager(self):
@contextlib.contextmanager
def manager():
yield 42
cm = manager()
self.assertIsInstance(cm, typing.ContextManager)
self.assertNotIsInstance(42, typing.ContextManager)
@skipUnless(ASYNCIO, 'Python 3.5 required')
def test_asy... | .abc.Iterable): ...
self.assertIsSubclass(I, typing.Iterable)
class A(collections.abc.Mapping, metaclass=abc.ABCMeta): ...
class B: ...
A.register(B)
self.assertIsSubclass(B, typing.Mapping)
class OtherABCTests(BaseTestCase):
| 64 | 64 | 211 | 9 | 55 | Visva92/cpython | Lib/test/test_typing.py | Python | OtherABCTests | OtherABCTests | 3,810 | 3,837 | 3,810 | 3,811 | 5c8c18826bddf5d83cc42c11a24d4ec511486e5b | bigcode/the-stack | train |
4cebeed0a90cd8b67477296a | train | class | class TypeTests(BaseTestCase):
def test_type_basic(self):
class User: pass
class BasicUser(User): pass
class ProUser(User): pass
def new_user(user_class: Type[User]) -> User:
return user_class()
new_user(BasicUser)
def test_type_typevar(self):
cl... | class TypeTests(BaseTestCase):
| def test_type_basic(self):
class User: pass
class BasicUser(User): pass
class ProUser(User): pass
def new_user(user_class: Type[User]) -> User:
return user_class()
new_user(BasicUser)
def test_type_typevar(self):
class User: pass
class Bas... | .AsyncContextManager)
self.assertEqual(typing.AsyncContextManager[int].__args__, (int,))
with self.assertRaises(TypeError):
isinstance(42, typing.AsyncContextManager[int])
with self.assertRaises(TypeError):
typing.AsyncContextManager[int, str]
class TypeTests(BaseTestCase... | 64 | 64 | 196 | 7 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | TypeTests | TypeTests | 3,840 | 3,876 | 3,840 | 3,841 | cc3c683fda3999d100271340748fdb324fa62b43 | bigcode/the-stack | train |
23f03485d1d3f5dc86bd5482 | train | class | class ConcatenateTests(BaseTestCase):
def test_basics(self):
P = ParamSpec('P')
class MyClass: ...
c = Concatenate[MyClass, P]
self.assertNotEqual(c, Concatenate)
def test_valid_uses(self):
P = ParamSpec('P')
T = TypeVar('T')
C1 = Callable[Concatenate[int... | class ConcatenateTests(BaseTestCase):
| def test_basics(self):
P = ParamSpec('P')
class MyClass: ...
c = Concatenate[MyClass, P]
self.assertNotEqual(c, Concatenate)
def test_valid_uses(self):
P = ParamSpec('P')
T = TypeVar('T')
C1 = Callable[Concatenate[int, P], int]
self.assertEqual(C1... | 1 = Callable[P, T]
G1 = List[C1]
G2 = list[C1]
G3 = list[C1] | int
self.assertEqual(G1.__parameters__, (P, T))
self.assertEqual(G2.__parameters__, (P, T))
self.assertEqual(G3.__parameters__, (P, T))
class ConcatenateTests(BaseTestCase):
| 84 | 84 | 280 | 8 | 76 | Visva92/cpython | Lib/test/test_typing.py | Python | ConcatenateTests | ConcatenateTests | 4,745 | 4,768 | 4,745 | 4,745 | f84449a354260df9fee03a3382b0412746c01363 | bigcode/the-stack | train |
4fde3a0908ecb1cb7ab60ba2 | train | class | class YAxis(Protocol):
y: int
| class YAxis(Protocol):
| y: int
| ):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
label: str
class MyPoint:
x: int
y: int
label: str
class XAxis(Protocol):
x: int
class YAxis(Protocol):
| 64 | 64 | 11 | 6 | 57 | Visva92/cpython | Lib/test/test_typing.py | Python | YAxis | YAxis | 792 | 793 | 792 | 792 | ec5ae070c7d9c55112b0f068db377d18fe178210 | bigcode/the-stack | train |
53e7a39224d63302c6c18f07 | train | class | class ForRefExample:
@ann_module.dec
def func(self: 'ForRefExample'):
pass
@ann_module.dec
@ann_module.dec
def nested(self: 'ForRefExample'):
pass
| class ForRefExample:
@ann_module.dec
| def func(self: 'ForRefExample'):
pass
@ann_module.dec
@ann_module.dec
def nested(self: 'ForRefExample'):
pass
| x: int
async with am as x:
return x
try:
g_with(ACM()).send(None)
except StopIteration as e:
assert e.args[0] == 42
gth = get_type_hints
class ForRefExample:
@ann_module.dec
| 64 | 64 | 49 | 11 | 52 | Visva92/cpython | Lib/test/test_typing.py | Python | ForRefExample | ForRefExample | 3,041 | 3,049 | 3,041 | 3,042 | 5ca414716ff59092ef01e76520e2c225c4299444 | bigcode/the-stack | train |
21d1200edd2a63531ae936fc | train | class | class Options(TypedDict, total=False):
log_level: int
log_path: str
| class Options(TypedDict, total=False):
| log_level: int
log_path: str
| ('Label', [('label', str)])
class Point2D(TypedDict):
x: int
y: int
class Bar(_typed_dict_helper.Foo, total=False):
b: int
class LabelPoint2D(Point2D, Label): ...
class Options(TypedDict, total=False):
| 64 | 64 | 21 | 9 | 55 | Visva92/cpython | Lib/test/test_typing.py | Python | Options | Options | 3,021 | 3,023 | 3,021 | 3,021 | de1f5859ced97889ee521f1b17baa3bd20630a13 | bigcode/the-stack | train |
641f2fd9ac0e11ff428739a7 | train | class | @runtime_checkable
class Proto(Protocol):
attr: int
def meth(self, arg: str) -> int:
...
| @runtime_checkable
class Proto(Protocol):
| attr: int
def meth(self, arg: str) -> int:
...
| x: int
y: int
label: str
class XAxis(Protocol):
x: int
class YAxis(Protocol):
y: int
@runtime_checkable
class Position(XAxis, YAxis, Protocol):
pass
@runtime_checkable
class Proto(Protocol):
| 64 | 64 | 29 | 10 | 53 | Visva92/cpython | Lib/test/test_typing.py | Python | Proto | Proto | 799 | 803 | 799 | 800 | 98eecbb3e52b2c59bc8477f7c78ec6d86a0a1fc7 | bigcode/the-stack | train |
e7a4892a881facef1983c454 | train | class | class RETests(BaseTestCase):
# Much of this is really testing _TypeAlias.
def test_basics(self):
pat = re.compile('[a-z]+', re.I)
self.assertIsSubclass(pat.__class__, Pattern)
self.assertIsSubclass(type(pat), Pattern)
self.assertIsInstance(pat, Pattern)
mat = pat.search... | class RETests(BaseTestCase):
# Much of this is really testing _TypeAlias.
| def test_basics(self):
pat = re.compile('[a-z]+', re.I)
self.assertIsSubclass(pat.__class__, Pattern)
self.assertIsSubclass(type(pat), Pattern)
self.assertIsInstance(pat, Pattern)
mat = pat.search('12345abcde.....')
self.assertIsSubclass(mat.__class__, Match)
... | __['a']
self.assertEqual(a.__parameters__, ())
def test_io_submodule(self):
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("default", category=DeprecationWarning)
from typing.io import IO, TextIO, BinaryIO, __all__, __name__
self.assertIs... | 158 | 158 | 527 | 19 | 139 | Visva92/cpython | Lib/test/test_typing.py | Python | RETests | RETests | 4,336 | 4,396 | 4,336 | 4,338 | a565884dce9def60c2ff631f9e293c8807d8a3a2 | bigcode/the-stack | train |
6a8b6b35397f3aab0681809c | train | class | class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = '%r is not a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failure... | class BaseTestCase(TestCase):
| def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = '%r is not a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def ass... | import import_helper
from test import mod_generics_cache
from test import _typed_dict_helper
py_typing = import_helper.import_fresh_module('typing', blocked=['_typing'])
c_typing = import_helper.import_fresh_module('typing', fresh=['_typing'])
class BaseTestCase(TestCase):
| 63 | 64 | 173 | 7 | 56 | Visva92/cpython | Lib/test/test_typing.py | Python | BaseTestCase | BaseTestCase | 45 | 63 | 45 | 46 | a2e212afc65f1dc934bee01d38b9aece9882f45b | bigcode/the-stack | train |
374d20c12072a78d47db12d3 | train | class | class LabelPoint2D(Point2D, Label): ...
| class LabelPoint2D(Point2D, Label): | ...
| return 0
Label = TypedDict('Label', [('label', str)])
class Point2D(TypedDict):
x: int
y: int
class Bar(_typed_dict_helper.Foo, total=False):
b: int
class LabelPoint2D(Point2D, Label): | 64 | 64 | 12 | 12 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | LabelPoint2D | LabelPoint2D | 3,019 | 3,019 | 3,019 | 3,019 | 696da0a88d146139bac806b19c361c8b7bb62ccc | bigcode/the-stack | train |
b56127f64a21eabaf9b6215f | train | class | class GenericTests(BaseTestCase):
def test_basics(self):
X = SimpleMapping[str, Any]
self.assertEqual(X.__parameters__, ())
with self.assertRaises(TypeError):
X[str]
with self.assertRaises(TypeError):
X[str, str]
Y = SimpleMapping[XK, str]
sel... | class GenericTests(BaseTestCase):
| def test_basics(self):
X = SimpleMapping[str, Any]
self.assertEqual(X.__parameters__, ())
with self.assertRaises(TypeError):
X[str]
with self.assertRaises(TypeError):
X[str, str]
Y = SimpleMapping[XK, str]
self.assertEqual(Y.__parameters__, (XK... | sIndex)
def test_bundled_protocol_instance_works(self):
self.assertIsInstance(0, typing.SupportsAbs)
class C1(typing.SupportsInt):
def __int__(self) -> int:
return 42
class C2(C1):
pass
c = C2()
self.assertIsInstance(c, C1)
def te... | 256 | 256 | 6,842 | 7 | 249 | Visva92/cpython | Lib/test/test_typing.py | Python | GenericTests | GenericTests | 1,614 | 2,442 | 1,614 | 1,615 | 23bb213e5be6a4b9d92ad0919ba12100283280a6 | bigcode/the-stack | train |
80bd0a8548dde2392a801fc8 | train | class | class TypeAliasTests(BaseTestCase):
def test_canonical_usage_with_variable_annotation(self):
Alias: TypeAlias = Employee
def test_canonical_usage_with_type_comment(self):
Alias = Employee # type: TypeAlias
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
... | class TypeAliasTests(BaseTestCase):
| def test_canonical_usage_with_variable_annotation(self):
Alias: TypeAlias = Employee
def test_canonical_usage_with_type_comment(self):
Alias = Employee # type: TypeAlias
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
TypeAlias()
def test_no_... | None]
LI = L[int]
with self.assertRaises(TypeError):
LI[None]
def test_annotated_in_other_types(self):
X = List[Annotated[T, 5]]
self.assertEqual(X[int], List[Annotated[int, 5]])
class TypeAliasTests(BaseTestCase):
| 66 | 67 | 225 | 8 | 58 | Visva92/cpython | Lib/test/test_typing.py | Python | TypeAliasTests | TypeAliasTests | 4,572 | 4,608 | 4,572 | 4,572 | e8e1c67142d1f6c52f822f58c805eaa46c926e65 | bigcode/the-stack | train |
2a211c3c5bc7cb34c42238a6 | train | class | class NamedTupleTests(BaseTestCase):
class NestedEmployee(NamedTuple):
name: str
cool: int
def test_basics(self):
Emp = NamedTuple('Emp', [('name', str), ('id', int)])
self.assertIsSubclass(Emp, tuple)
joe = Emp('Joe', 42)
jim = Emp(name='Jim', id=1)
self... | class NamedTupleTests(BaseTestCase):
| class NestedEmployee(NamedTuple):
name: str
cool: int
def test_basics(self):
Emp = NamedTuple('Emp', [('name', str), ('id', int)])
self.assertIsSubclass(Emp, tuple)
joe = Emp('Joe', 42)
jim = Emp(name='Jim', id=1)
self.assertIsInstance(joe, Emp)
s... | UserId')
self.assertEqual(repr(self.UserName),
f'{__name__}.{self.__class__.__qualname__}.UserName')
def test_pickle(self):
UserAge = self.module.NewType('UserAge', float)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
... | 256 | 256 | 1,358 | 8 | 247 | Visva92/cpython | Lib/test/test_typing.py | Python | NamedTupleTests | NamedTupleTests | 3,984 | 4,124 | 3,984 | 3,984 | 68cdc7c47372fd0bc60dd494d49278d2b6e280a1 | bigcode/the-stack | train |
6da3005ca135f7fee1100147 | train | class | class GetTypeHintTests(BaseTestCase):
def test_get_type_hints_from_various_objects(self):
# For invalid objects should fail with TypeError (not AttributeError etc).
with self.assertRaises(TypeError):
gth(123)
with self.assertRaises(TypeError):
gth('abc')
with ... | class GetTypeHintTests(BaseTestCase):
| def test_get_type_hints_from_various_objects(self):
# For invalid objects should fail with TypeError (not AttributeError etc).
with self.assertRaises(TypeError):
gth(123)
with self.assertRaises(TypeError):
gth('abc')
with self.assertRaises(TypeError):
... | self.x} -> {self.y}'
def __add__(self, other):
return 0
Label = TypedDict('Label', [('label', str)])
class Point2D(TypedDict):
x: int
y: int
class Bar(_typed_dict_helper.Foo, total=False):
b: int
class LabelPoint2D(Point2D, Label): ...
class Options(TypedDict, total=False):
log_level: i... | 256 | 256 | 2,147 | 9 | 246 | Visva92/cpython | Lib/test/test_typing.py | Python | GetTypeHintTests | GetTypeHintTests | 3,052 | 3,267 | 3,052 | 3,052 | 112e5195e0f7b0a9dfb7f9600cfcbbc04ecb63dc | bigcode/the-stack | train |
532735e2df8e07783b0ec00a | train | class | @skipUnless(c_typing, 'requires _typing')
class NewTypeCTests(NewTypeTests, BaseTestCase):
module = c_typing
| @skipUnless(c_typing, 'requires _typing')
class NewTypeCTests(NewTypeTests, BaseTestCase):
| module = c_typing
| = typing.NewType('NT', int)\n"
)
exec(code, {})
class NewTypePythonTests(NewTypeTests, BaseTestCase):
module = py_typing
@skipUnless(c_typing, 'requires _typing')
class NewTypeCTests(NewTypeTests, BaseTestCase):
| 64 | 64 | 32 | 25 | 38 | Visva92/cpython | Lib/test/test_typing.py | Python | NewTypeCTests | NewTypeCTests | 3,979 | 3,981 | 3,979 | 3,980 | b83b870f46c4932e56ccfdae15b6a57efb877572 | bigcode/the-stack | train |
22c854787756e8a89582b1ad | train | class | class Other:
attr: int = 1
def meth(self, arg: str) -> int:
if arg == 'this':
return 1
return 0
| class Other:
| attr: int = 1
def meth(self, arg: str) -> int:
if arg == 'this':
return 1
return 0
| ):
y: int
@runtime_checkable
class Position(XAxis, YAxis, Protocol):
pass
@runtime_checkable
class Proto(Protocol):
attr: int
def meth(self, arg: str) -> int:
...
class Concrete(Proto):
pass
class Other:
| 64 | 64 | 40 | 3 | 60 | Visva92/cpython | Lib/test/test_typing.py | Python | Other | Other | 808 | 813 | 808 | 808 | e8de7d5a08659896b158888080083f80074533f1 | bigcode/the-stack | train |
292d0f2fefa3fa96728909b7 | train | class | @runtime_checkable
class Point(Coordinate, Protocol):
label: str
| @runtime_checkable
class Point(Coordinate, Protocol):
| label: str
| self.store[key] = value
def get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
return default
class Coordinate(Protocol):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
| 64 | 64 | 17 | 12 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | Point | Point | 780 | 782 | 780 | 781 | 4bc857a633004eaecc5c99f670fed810b2c74fca | bigcode/the-stack | train |
d193042dc195f7f54307f789 | train | class | class ClassVarTests(BaseTestCase):
def test_basics(self):
with self.assertRaises(TypeError):
ClassVar[1]
with self.assertRaises(TypeError):
ClassVar[int, str]
with self.assertRaises(TypeError):
ClassVar[int][str]
def test_repr(self):
self.ass... | class ClassVarTests(BaseTestCase):
| def test_basics(self):
with self.assertRaises(TypeError):
ClassVar[1]
with self.assertRaises(TypeError):
ClassVar[int, str]
with self.assertRaises(TypeError):
ClassVar[int][str]
def test_repr(self):
self.assertEqual(repr(ClassVar), 'typing.Cla... | ],
Literal[1, 2],
Concatenate[int, ParamSpec("P")],
TypeGuard[int],
):
with self.subTest(msg=obj):
with self.assertRaisesRegex(
TypeError, f'^{re.escape(f"Cannot subclass {obj!r}")}$'
):
c... | 80 | 80 | 267 | 8 | 71 | Visva92/cpython | Lib/test/test_typing.py | Python | ClassVarTests | ClassVarTests | 2,444 | 2,481 | 2,444 | 2,445 | 9fc095389848382e04ea1fdcdc6bf81b121cd3ca | bigcode/the-stack | train |
5905f9ca93bb805ff8e7bcec | train | class | class Bar(_typed_dict_helper.Foo, total=False):
b: int
| class Bar(_typed_dict_helper.Foo, total=False):
| b: int
| self.x} -> {self.y}'
def __add__(self, other):
return 0
Label = TypedDict('Label', [('label', str)])
class Point2D(TypedDict):
x: int
y: int
class Bar(_typed_dict_helper.Foo, total=False):
| 64 | 64 | 17 | 12 | 51 | Visva92/cpython | Lib/test/test_typing.py | Python | Bar | Bar | 3,016 | 3,017 | 3,016 | 3,016 | 1032dc49c86a5a6c879859f342cdd7b944275e87 | bigcode/the-stack | train |
b73e5a4d528d9b6efedfc577 | train | class | class A:
y: float
| class A:
| y: float
| ImportError:
ASYNCIO = False # multithreading is not enabled
else:
ASYNCIO = True
# Definitions needed for features introduced in Python 3.6
from test import ann_module, ann_module2, ann_module3
from typing import AsyncContextManager
class A:
| 64 | 64 | 8 | 3 | 60 | Visva92/cpython | Lib/test/test_typing.py | Python | A | A | 2,971 | 2,972 | 2,971 | 2,971 | 49c8e1a853a1f76891555445489af4b1e22225ed | bigcode/the-stack | train |
51837510a45e80680a3550db | train | class | class ThriftParser(object):
""" Extracts struct, service, enum, and typedef definitions from thrift files.
Call parse to extract a ThriftParseResult object.
The parser works by taking the following steps:
1. Parse all dependencies and inherit their results
2. Match file content with regexs and con... | class ThriftParser(object):
| """ Extracts struct, service, enum, and typedef definitions from thrift files.
Call parse to extract a ThriftParseResult object.
The parser works by taking the following steps:
1. Parse all dependencies and inherit their results
2. Match file content with regexs and consolidate the following in a ... | # Copyright Notice:
# Copyright 2017, Fitbit, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | 190 | 256 | 4,729 | 6 | 183 | m-racine/thriftcli | thriftcli/thrift_parser.py | Python | ThriftParser | ThriftParser | 23 | 507 | 23 | 23 | ed89ed98e5fd5b6094d262fcfbe56a25b647fd98 | bigcode/the-stack | train |
9ad3682282878be3cda2415f | train | function | @pytest.fixture()
def query():
return ["language__iexact", "ru"]
| @pytest.fixture()
def query():
| return ["language__iexact", "ru"]
| _data):
form_data.update(
{
"title": "Test title",
"form-0-field": "language",
"form-0-operator": "iexact",
"form-0-value": "ru",
}
)
return form_data
@pytest.fixture()
def query():
| 64 | 64 | 17 | 6 | 57 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | query | query | 59 | 61 | 59 | 60 | c482cfc99356150c6f468812c9000371bcd55237 | bigcode/the-stack | train |
6a2c2f493a5edca69327cc84 | train | function | def test_create_form_validation(user, client, form_data):
user.user_permissions.add(Permission.objects.get(codename="change_client"))
res = client.post(URL_CLIENT_CHANGELIST, data=form_data)
assert res.status_code == 200
form = res.context_data["advanced_filters"]
assert "title" in form.errors
a... | def test_create_form_validation(user, client, form_data):
| user.user_permissions.add(Permission.objects.get(codename="change_client"))
res = client.post(URL_CLIENT_CHANGELIST, data=form_data)
assert res.status_code == 200
form = res.context_data["advanced_filters"]
assert "title" in form.errors
assert "__all__" in form.errors
assert form.errors["tit... | + fields:
assert part in response_content
@pytest.fixture
def form_data():
return {
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 0,
"action": "advanced_filters",
}
def test_create_form_validation(user, client, form_data):
| 64 | 64 | 112 | 12 | 52 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | test_create_form_validation | test_create_form_validation | 35 | 43 | 35 | 35 | 59fa3c0cdf51f58f7855a19a4da68be3e68b2c0f | bigcode/the-stack | train |
eb222d3e80619e8a539f8f21 | train | function | def test_changelist_includes_form(user, settings, client):
user.user_permissions.add(Permission.objects.get(codename="change_client"))
settings.ADVANCED_FILTER_EDIT_BY_USER = False
res = client.get(URL_CLIENT_CHANGELIST)
assert res.status_code == 200
title = ["Create advanced filter"]
fields = [... | def test_changelist_includes_form(user, settings, client):
| user.user_permissions.add(Permission.objects.get(codename="change_client"))
settings.ADVANCED_FILTER_EDIT_BY_USER = False
res = client.get(URL_CLIENT_CHANGELIST)
assert res.status_code == 200
title = ["Create advanced filter"]
fields = ["First name", "Language", "Sales Rep"]
response_content... | from django.urls import reverse_lazy
except ImportError: # Django < 2.0
from django.core.urlresolvers import reverse_lazy
URL_CLIENT_CHANGELIST = reverse_lazy("admin:customers_client_changelist")
def test_changelist_includes_form(user, settings, client):
| 64 | 64 | 112 | 14 | 50 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | test_changelist_includes_form | test_changelist_includes_form | 14 | 23 | 14 | 14 | 53b0092d85c88d14dc282bcf57e1cc2cf57b7892 | bigcode/the-stack | train |
fea54861acfe05b776d4d9d7 | train | function | @pytest.fixture
def form_data():
return {
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 0,
"action": "advanced_filters",
}
| @pytest.fixture
def form_data():
| return {
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 0,
"action": "advanced_filters",
}
| assert res.status_code == 200
title = ["Create advanced filter"]
fields = ["First name", "Language", "Sales Rep"]
response_content = res.content.decode("utf-8")
for part in title + fields:
assert part in response_content
@pytest.fixture
def form_data():
| 64 | 64 | 42 | 7 | 56 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | form_data | form_data | 26 | 32 | 26 | 27 | b068b0e2add678cf4d6432c92cbdb3e6904a9edd | bigcode/the-stack | train |
bcb7df893a0d2265bc824c1e | train | function | def test_create_form_valid(user, client, good_data, query):
assert AdvancedFilter.objects.count() == 0
user.user_permissions.add(Permission.objects.get(codename="change_client"))
res = client.post(URL_CLIENT_CHANGELIST, data=good_data)
assert res.status_code == 200
form = res.context_data["advanced_... | def test_create_form_valid(user, client, good_data, query):
| assert AdvancedFilter.objects.count() == 0
user.user_permissions.add(Permission.objects.get(codename="change_client"))
res = client.post(URL_CLIENT_CHANGELIST, data=good_data)
assert res.status_code == 200
form = res.context_data["advanced_filters"]
assert form.is_valid()
assert AdvancedFilt... | ",
"form-0-field": "language",
"form-0-operator": "iexact",
"form-0-value": "ru",
}
)
return form_data
@pytest.fixture()
def query():
return ["language__iexact", "ru"]
def test_create_form_valid(user, client, good_data, query):
| 73 | 74 | 248 | 14 | 59 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | test_create_form_valid | test_create_form_valid | 64 | 88 | 64 | 64 | 248acd265f59c4152bfd6a18196d31e6f1c14723 | bigcode/the-stack | train |
07c937cb87b712f7ef5d47be | train | function | @pytest.fixture()
def good_data(form_data):
form_data.update(
{
"title": "Test title",
"form-0-field": "language",
"form-0-operator": "iexact",
"form-0-value": "ru",
}
)
return form_data
| @pytest.fixture()
def good_data(form_data):
| form_data.update(
{
"title": "Test title",
"form-0-field": "language",
"form-0-operator": "iexact",
"form-0-value": "ru",
}
)
return form_data
| _data["advanced_filters"]
assert "title" in form.errors
assert "__all__" in form.errors
assert form.errors["title"] == ["This field is required."]
assert form.errors["__all__"] == ["Error validating filter forms"]
@pytest.fixture()
def good_data(form_data):
| 63 | 64 | 65 | 9 | 54 | cagerber/django-advanced-filters | advanced_filters/tests/test_creation.py | Python | good_data | good_data | 46 | 56 | 46 | 47 | 93362b6191d8902d6262cfcd9650c7e0c04ca85a | bigcode/the-stack | train |
01697b4712906c69c3cfe098 | train | function | def loadObjectClass(filename):
"""Load object class lookup table."""
model = ObjectClass
with createApp().app_context():
sess = GlobalDB.db().session
# for object class, delete and replace values
sess.query(model).delete()
data = pd.read_csv(filename, dtype=str)
dat... | def loadObjectClass(filename):
| """Load object class lookup table."""
model = ObjectClass
with createApp().app_context():
sess = GlobalDB.db().session
# for object class, delete and replace values
sess.query(model).delete()
data = pd.read_csv(filename, dtype=str)
data = LoaderUtils.cleanData(
... | =['cgac_code'], inplace=True)
# insert to db
table_name = model.__table__.name
num = LoaderUtils.insertDataframe(data, table_name, sess.connection())
sess.commit()
logger.info('{} records inserted to {}'.format(num, table_name))
def loadObjectClass(filename):
| 64 | 64 | 177 | 6 | 58 | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | dataactvalidator/scripts/loadFile.py | Python | loadObjectClass | loadObjectClass | 45 | 69 | 45 | 45 | fe2d8133d7e526f44239d0d870fb23ce59be5610 | bigcode/the-stack | train |
e63e90f0a8f271ebeb1c23d2 | train | function | def loadProgramActivity(filename):
"""Load program activity lookup table."""
model = ProgramActivity
with createApp().app_context():
sess = GlobalDB.db().session
# for program activity, delete and replace values??
sess.query(model).delete()
data = pd.read_csv(filename, dty... | def loadProgramActivity(filename):
| """Load program activity lookup table."""
model = ProgramActivity
with createApp().app_context():
sess = GlobalDB.db().session
# for program activity, delete and replace values??
sess.query(model).delete()
data = pd.read_csv(filename, dtype=str)
data = LoaderUtils.... | _object_class_name": "object_class_name"},
{}
)
# de-dupe
data.drop_duplicates(subset=['object_class_code'], inplace=True)
# insert to db
table_name = model.__table__.name
num = LoaderUtils.insertDataframe(data, table_name, sess.connection())
sess.comm... | 89 | 89 | 297 | 6 | 83 | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | dataactvalidator/scripts/loadFile.py | Python | loadProgramActivity | loadProgramActivity | 72 | 107 | 72 | 72 | f67afe0682231c1df9601c0eb0efa8d3fc7e26b9 | bigcode/the-stack | train |
86b8fee59fb9f94f0af9770c | train | function | def loadCgac(filename):
"""Load CGAC (high-level agency names) lookup table."""
model = CGAC
with createApp().app_context():
sess = GlobalDB.db().session
# for CGAC, delete and replace values
sess.query(model).delete()
# read CGAC values from csv
data = pd.read_csv... | def loadCgac(filename):
| """Load CGAC (high-level agency names) lookup table."""
model = CGAC
with createApp().app_context():
sess = GlobalDB.db().session
# for CGAC, delete and replace values
sess.query(model).delete()
# read CGAC values from csv
data = pd.read_csv(filename, dtype=str)
... | Utils import LoaderUtils
from dataactcore.interfaces.db import GlobalDB
from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity
from dataactcore.config import CONFIG_BROKER
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def loadCgac(filename):
| 64 | 64 | 203 | 6 | 58 | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | dataactvalidator/scripts/loadFile.py | Python | loadCgac | loadCgac | 16 | 42 | 16 | 16 | 98254724eca6d273fd58f00ccd3515e8bb87ef3b | bigcode/the-stack | train |
c31ecb06ccf8ae25da87ed25 | train | function | def loadDomainValues(basePath, localProgramActivity = None):
"""Load all domain value files.
Parameters
----------
basePath : directory that contains the domain values files.
localProgramActivity : optional location of the program activity file (None = use basePath)
"""
logger.info... | def loadDomainValues(basePath, localProgramActivity = None):
| """Load all domain value files.
Parameters
----------
basePath : directory that contains the domain values files.
localProgramActivity : optional location of the program activity file (None = use basePath)
"""
logger.info('Loading CGAC')
loadCgac(os.path.join(basePath,"cgac.csv... | )
# insert to db
table_name = model.__table__.name
num = LoaderUtils.insertDataframe(data, table_name, sess.connection())
sess.commit()
logger.info('{} records inserted to {}'.format(num, table_name))
def loadDomainValues(basePath, localProgramActivity = None):
| 64 | 64 | 146 | 13 | 51 | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | dataactvalidator/scripts/loadFile.py | Python | loadDomainValues | loadDomainValues | 110 | 128 | 110 | 110 | dad717a48aed9444ffb01619abe8cd945da2befe | bigcode/the-stack | train |
ba6108ca533fcaa305773be6 | train | class | class Schedule(db.Model):
__tablename__ = 'schedules'
id = db.Column(db.Integer, primary_key=True)
day = db.Column(db.String(45))
start = db.Column(db.Float)
end = db.Column(db.Float)
| class Schedule(db.Model):
| __tablename__ = 'schedules'
id = db.Column(db.Integer, primary_key=True)
day = db.Column(db.String(45))
start = db.Column(db.Float)
end = db.Column(db.Float)
| = db.Column(db.String)
ethnicity = db.Column(db.String(45))
gender = db.Column(db.String(45))
numvisits = db.Column(db.String(45))
rank = db.Column(db.String(45))
gradcode = db.Column(db.String(45))
class Schedule(db.Model):
| 64 | 64 | 52 | 5 | 59 | sara/Assemble-the-Minions | minions/models.py | Python | Schedule | Schedule | 16 | 21 | 16 | 16 | d8fbda755dc35875da1c187511d21f57e9f8c6bc | bigcode/the-stack | train |
1a5c808e2f36b868d39eb489 | train | class | class Ambassador(db.Model):
__tablename__ = 'ambassadors'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
phone = db.Column(db.String)
ethnicity = db.Column(db.String(45))
gender = db.Column(db.String(45))
numvisits = db.Column(db.String(45))
rank = db.Column... | class Ambassador(db.Model):
| __tablename__ = 'ambassadors'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(45))
phone = db.Column(db.String)
ethnicity = db.Column(db.String(45))
gender = db.Column(db.String(45))
numvisits = db.Column(db.String(45))
rank = db.Column(db.String(45))
gradcode... | #!venv/bin/python
from minions import db
from flask.ext.login import UserMixin
class Ambassador(db.Model):
| 25 | 64 | 97 | 5 | 19 | sara/Assemble-the-Minions | minions/models.py | Python | Ambassador | Ambassador | 5 | 14 | 5 | 5 | f66a8493b657da0bc1f3ead6518f2a7d4f59f2fe | bigcode/the-stack | train |
18560be3a90788fd65940018 | train | class | class NuoDBBasicTest(unittest.TestCase):
def test_toByteString(self):
self.assertEqual(pynuodb.crypt.toSignedByteString(1), '\x01')
self.assertEqual(pynuodb.crypt.toSignedByteString(127), '\x7f')
self.assertEqual(pynuodb.crypt.toSignedByteString(254), '\x00\xfe')
self.assertEqual(pyn... | class NuoDBBasicTest(unittest.TestCase):
| def test_toByteString(self):
self.assertEqual(pynuodb.crypt.toSignedByteString(1), '\x01')
self.assertEqual(pynuodb.crypt.toSignedByteString(127), '\x7f')
self.assertEqual(pynuodb.crypt.toSignedByteString(254), '\x00\xfe')
self.assertEqual(pynuodb.crypt.toSignedByteString(255), '\x00... | #!/usr/bin/env python
import unittest
import pynuodb
class NuoDBBasicTest(unittest.TestCase):
| 24 | 139 | 464 | 10 | 13 | nuodb/nuodb-python | tests/nuodb_crypt_test.py | Python | NuoDBBasicTest | NuoDBBasicTest | 7 | 31 | 7 | 7 | cf51b89b827d2b5c12008899556fe2ae4304ade6 | bigcode/the-stack | train |
c4f953354024b676825dbac1 | train | class | class TestDysymTabCommand(unittest.TestCase):
def setUp(self):
with open('./binaries/executable.i386', 'rb') as f1:
self.executable_i386 = f1.read()
with open('./binaries/object.o.i386', 'rb') as f2:
self.object_i386 = f2.read()
with open('./binaries/executable.x86_64... | class TestDysymTabCommand(unittest.TestCase):
| def setUp(self):
with open('./binaries/executable.i386', 'rb') as f1:
self.executable_i386 = f1.read()
with open('./binaries/object.o.i386', 'rb') as f2:
self.object_i386 = f2.read()
with open('./binaries/executable.x86_64', 'rb') as f3:
self.executable_x8... | import unittest
from mach_o.headers.dysymtab_command import DysymtabCommand
from mach_o.headers.load_command import LoadCommandCommand
class TestDysymTabCommand(unittest.TestCase):
| 40 | 256 | 1,178 | 11 | 28 | hkkwok/MachOTool | tests/test_dysymtab_command.py | Python | TestDysymTabCommand | TestDysymTabCommand | 6 | 124 | 6 | 6 | 12970212cade0ae8b617e8740c1c09dca1a2e1f3 | bigcode/the-stack | train |
3ef97e5074c1b0e9c036923f | train | function | def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument('--build-path', type=str,
help='non default build path', default="./build")
parser.add_argument(
'--branch',
type=str,
help='branch that is being merged against',
default="... | def parse_commandline():
| parser = argparse.ArgumentParser()
parser.add_argument('--build-path', type=str,
help='non default build path', default="./build")
parser.add_argument(
'--branch',
type=str,
help='branch that is being merged against',
default="develop")
parser.add_... | if '.hpp' in filename:
print_warning(
"\nWARNING: Failed to find a file dependent on {}".format(
filename))
filenames_to_remove.append(filename)
for filename in filenames_to_remove:
changed_files_fullpath.remove(filename)
return changed_file... | 64 | 64 | 93 | 5 | 58 | fetchai/ledger-archive | scripts/quickly_fix_style.py | Python | parse_commandline | parse_commandline | 138 | 149 | 138 | 138 | ea73ca6e64ef8920b1012d579387417b17d2bc50 | bigcode/the-stack | train |
fe76cc4479ac7cbff71f2176 | train | function | def main():
args = parse_commandline()
compare_branch = args.branch
build_path = args.build_path
# Firstly, check license headers
print("Checking license headers")
sys.argv = ['_', '--fix']
check_license_header.main()
changed_files = []
# Stack overflow 34279322
proc = subpro... | def main():
| args = parse_commandline()
compare_branch = args.branch
build_path = args.build_path
# Firstly, check license headers
print("Checking license headers")
sys.argv = ['_', '--fix']
check_license_header.main()
changed_files = []
# Stack overflow 34279322
proc = subprocess.Popen(
... | for filename in filenames_to_remove:
changed_files_fullpath.remove(filename)
return changed_files_fullpath
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument('--build-path', type=str,
help='non default build path', default="./build")
pa... | 119 | 119 | 397 | 3 | 116 | fetchai/ledger-archive | scripts/quickly_fix_style.py | Python | main | main | 152 | 207 | 152 | 153 | fc6eff74484fd280f066c1e8bdbb724ecb869365 | bigcode/the-stack | train |
ab8e2ee64f82e3d5867a0b80 | train | function | def convert_to_dependencies(
changed_files_fullpath: set, build_path, verbose=False):
"""For each changed hpp file, find a cpp file that depends on it (clang-tidy requires cpp files only) and replace it in the set.
To do this, find cmake generated depend.make files
Example depend.make format:
l... | def convert_to_dependencies(
changed_files_fullpath: set, build_path, verbose=False):
| """For each changed hpp file, find a cpp file that depends on it (clang-tidy requires cpp files only) and replace it in the set.
To do this, find cmake generated depend.make files
Example depend.make format:
libs/metrics/CMakeFiles/fetch-metrics.dir/src/metrics.cpp.o: ../libs/vectorise/include/vectoris... | ER
#
# This script is used to run the apply_style.py and run-statis-analysis.py tools
# after trying to determine the files that actually need changing (NOT GUARANTEED)
# IT WILL AUTOMATICALLY TRY TO FIX which may break the code. Commit your changes first.
#
# *** Requires you to have build the targets in your build di... | 225 | 225 | 750 | 19 | 206 | fetchai/ledger-archive | scripts/quickly_fix_style.py | Python | convert_to_dependencies | convert_to_dependencies | 40 | 135 | 40 | 41 | 74f9953dd6004c3abbb096aa3cf139ac5486bb33 | bigcode/the-stack | train |
15b3a7723d215529baae3b7c | train | function | def print_warning(warning):
try:
from colors import red, green, blue
print(red(warning))
except:
print("*** " + warning)
| def print_warning(warning):
| try:
from colors import red, green, blue
print(red(warning))
except:
print("*** " + warning)
| ask git for the changes between this commit and the last common commit to [develop]
# to determine the files that need changing.
import run_static_analysis
import apply_style
import check_license_header
import subprocess
import sys
import os
import argparse
import glob
import re
def print_warning(warning):
| 64 | 64 | 35 | 6 | 57 | fetchai/ledger-archive | scripts/quickly_fix_style.py | Python | print_warning | print_warning | 32 | 37 | 32 | 32 | 7b8cb19a49a3725241f059d78ffda782e53e1b34 | bigcode/the-stack | train |
a20961a9df24ae82b7053a71 | train | class | class Document(ModelBase):
__tablename__ = "document"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(Integer)
doc_name = Column(String(45))
text = Column(Text)
created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime, default=datetime.now, on... | class Document(ModelBase):
| __tablename__ = "document"
id = Column(Integer, primary_key=True, autoincrement=True)
uid = Column(Integer)
doc_name = Column(String(45))
text = Column(Text)
created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
@... | # coding=utf-8
from sqlalchemy.exc import IntegrityError
from sqlalchemy import Integer, Column, Text, DateTime, String
from . import ModelBase, session
from sqlalchemy.orm.exc import NoResultFound
from ..exceptions import Error
from datetime import datetime
class Document(ModelBase):
| 60 | 90 | 302 | 5 | 54 | docloud/docmanage | docmanage/docmanage/models/doc.py | Python | Document | Document | 11 | 57 | 11 | 11 | c96913ec8a10ec1624e6ae90a5a8723cc5c92c3d | bigcode/the-stack | train |
33148950992e35399a7017d9 | train | class | class nop(object):
"""
Nop class to handle misc optional imports
Shamelessly ripped off
from http://stackoverflow.com/questions/24946321/how-do-i-write-a-no-op-or-dummy-class-in-python
"""
def __init__(self, name=''):
self.name_ = name
def __get__(self, *args):
return MayBeC... | class nop(object):
| """
Nop class to handle misc optional imports
Shamelessly ripped off
from http://stackoverflow.com/questions/24946321/how-do-i-write-a-no-op-or-dummy-class-in-python
"""
def __init__(self, name=''):
self.name_ = name
def __get__(self, *args):
return MayBeCalled()
def __... | _PYBOT_MARSHALLING_CHOICES))
print('Using {} marshalling backend.'.format(color_green(_PYBOT_MARSHALLING_BACKEND)))
# ===============================================================================
class MayBeCalled(object):
def __call__(self, *args, **kwargs):
return None
class nop(object):
| 64 | 64 | 147 | 4 | 59 | spillai/pybot | pybot/externals/__init__.py | Python | nop | nop | 64 | 82 | 64 | 64 | a8e03fa5482cb88c77757f66f85a46cf69791681 | bigcode/the-stack | train |
18df7b258b5c9c21cbee8193 | train | function | def marshalling_backend():
return _PYBOT_MARSHALLING_BACKEND
| def marshalling_backend():
| return _PYBOT_MARSHALLING_BACKEND
| default='zmq',
choices=_PYBOT_MARSHALLING_CHOICES)
def vis_backend():
return _PYBOT_VIS_BACKEND
def set_vis_backend(value):
assert(value in set(_PYBOT_VIS_CHOICES))
_PYBOT_VIS_BACKEND = value
def marshalling_backend():
| 64 | 64 | 18 | 5 | 58 | spillai/pybot | pybot/externals/__init__.py | Python | marshalling_backend | marshalling_backend | 23 | 24 | 23 | 23 | c083eff4dad1c609fdb70eaa9db385d062558e07 | bigcode/the-stack | train |
8bb819a467380883344648a7 | train | class | class MayBeCalled(object):
def __call__(self, *args, **kwargs):
return None
| class MayBeCalled(object):
| def __call__(self, *args, **kwargs):
return None
| '''
'''choices are {}'''.format(_PYBOT_MARSHALLING_BACKEND,
_PYBOT_MARSHALLING_CHOICES))
print('Using {} marshalling backend.'.format(color_green(_PYBOT_MARSHALLING_BACKEND)))
# ========================================================================... | 63 | 64 | 23 | 6 | 57 | spillai/pybot | pybot/externals/__init__.py | Python | MayBeCalled | MayBeCalled | 60 | 62 | 60 | 60 | fdb4695d6c4460884036b9b821784b80e2c72515 | bigcode/the-stack | train |
c33884ee4992f71346be1505 | train | function | def set_vis_backend(value):
assert(value in set(_PYBOT_VIS_CHOICES))
_PYBOT_VIS_BACKEND = value
| def set_vis_backend(value):
| assert(value in set(_PYBOT_VIS_CHOICES))
_PYBOT_VIS_BACKEND = value
| q']
_PYBOT_MARSHALLING_BACKEND = get_environment('PYBOT_MARSHALLING_BACKEND',
default='zmq',
choices=_PYBOT_MARSHALLING_CHOICES)
def vis_backend():
return _PYBOT_VIS_BACKEND
def set_vis_backend(value):
| 64 | 64 | 28 | 6 | 57 | spillai/pybot | pybot/externals/__init__.py | Python | set_vis_backend | set_vis_backend | 19 | 21 | 19 | 19 | ba3e6dee81d62644ec07852651ecb24751bf003e | bigcode/the-stack | train |
57e2e65dcf4ee39e891e617f | train | function | def vis_backend():
return _PYBOT_VIS_BACKEND
| def vis_backend():
| return _PYBOT_VIS_BACKEND
| BOT_MARSHALLING_CHOICES = ['lcm', 'zmq']
_PYBOT_MARSHALLING_BACKEND = get_environment('PYBOT_MARSHALLING_BACKEND',
default='zmq',
choices=_PYBOT_MARSHALLING_CHOICES)
def vis_backend():
| 64 | 64 | 13 | 4 | 60 | spillai/pybot | pybot/externals/__init__.py | Python | vis_backend | vis_backend | 16 | 17 | 16 | 16 | aa8d3c41ce608a6bf33f6d5952b1f58ad4aa48a5 | bigcode/the-stack | train |
34c8c62134957baf3da5b050 | train | function | def set_marshalling_backend(value):
assert(value in set(_PYBOT_MARSHALLING_CHOICES))
_PYBOT_MARSHALLING_BACKEND = value
| def set_marshalling_backend(value):
| assert(value in set(_PYBOT_MARSHALLING_CHOICES))
_PYBOT_MARSHALLING_BACKEND = value
| _backend():
return _PYBOT_VIS_BACKEND
def set_vis_backend(value):
assert(value in set(_PYBOT_VIS_CHOICES))
_PYBOT_VIS_BACKEND = value
def marshalling_backend():
return _PYBOT_MARSHALLING_BACKEND
def set_marshalling_backend(value):
| 64 | 64 | 37 | 7 | 56 | spillai/pybot | pybot/externals/__init__.py | Python | set_marshalling_backend | set_marshalling_backend | 26 | 28 | 26 | 26 | 5f86874d3db966db33b1f6371d77ad93de042a3a | bigcode/the-stack | train |
381fe940797d9158382a1145 | train | function | def _impl(ctx):
if not ctx.attr.deps:
fail("closure_js_binary rules can not have an empty 'deps' list")
for flag in ctx.attr.defs:
if not flag.startswith("--") or (" " in flag and "=" not in flag):
fail("Please use --flag=value syntax for defs")
if ctx.attr.language not in JS_LAN... | def _impl(ctx):
| if not ctx.attr.deps:
fail("closure_js_binary rules can not have an empty 'deps' list")
for flag in ctx.attr.defs:
if not flag.startswith("--") or (" " in flag and "=" not in flag):
fail("Please use --flag=value syntax for defs")
if ctx.attr.language not in JS_LANGUAGES.to_list()... | Copyright 2016 The Closure Rules Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | 256 | 256 | 2,126 | 5 | 251 | vrana/rules_closure | closure/compiler/closure_js_binary.bzl | Python | _impl | _impl | 36 | 262 | 36 | 36 | a32a46a4e802d1ed5eaa391014027649a989e630 | bigcode/the-stack | train |
0319f729986b585c106cd53e | train | function | def _validate_css_graph(ctx, js):
if ctx.attr.css:
missing = difference(js.stylesheets, ctx.attr.css.closure_css_binary.labels)
if missing:
fail("Dependent JS libraries depend on CSS libraries that weren't " +
"compiled into the referenced CSS binary: " +
... | def _validate_css_graph(ctx, js):
| if ctx.attr.css:
missing = difference(js.stylesheets, ctx.attr.css.closure_css_binary.labels)
if missing:
fail("Dependent JS libraries depend on CSS libraries that weren't " +
"compiled into the referenced CSS binary: " +
", ".join(missing))
elif js.... | ,
),
runfiles = ctx.runfiles(
files = files + ctx.files.data,
transitive_files = (collect_runfiles(deps) |
collect_runfiles([ctx.attr.css]) |
collect_runfiles(ctx.attr.data)),
),
)
def _validate_css_graph... | 64 | 64 | 117 | 9 | 55 | vrana/rules_closure | closure/compiler/closure_js_binary.bzl | Python | _validate_css_graph | _validate_css_graph | 264 | 274 | 264 | 264 | a528109023e55c85018d0dd412397c45a74df3fa | bigcode/the-stack | train |
f1d240d98367d3aacb66fe4e | train | class | class FacilityTests(TestCase):
def test_create_facility(self):
"""
Ensure that we can create a medical facility
"""
User.objects.create_superuser(
username='john', email='john@doe.com', password='myAwesomePassword1')
self.client.login(username='john',
... | class FacilityTests(TestCase):
| def test_create_facility(self):
"""
Ensure that we can create a medical facility
"""
User.objects.create_superuser(
username='john', email='john@doe.com', password='myAwesomePassword1')
self.client.login(username='john',
password='myAweso... | from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from .models import MedicalFacility
class FacilityTests(TestCase):
| 49 | 100 | 335 | 6 | 42 | BuildForSDG/team-271-backend | med_facility/tests.py | Python | FacilityTests | FacilityTests | 9 | 50 | 9 | 10 | 2a2179798ba52bb7e963c5011057121cc61ccfd7 | bigcode/the-stack | train |
e630c2dbab431d409ff3b146 | train | function | def parsedata(jsonfile):
data = {}
if os.path.isfile(jsonfile):
with open('data.json') as f:
try:
data = json.load(f)
except ValueError:
#Ignore
pass
return data
| def parsedata(jsonfile):
| data = {}
if os.path.isfile(jsonfile):
with open('data.json') as f:
try:
data = json.load(f)
except ValueError:
#Ignore
pass
return data
| = json.load(data_file)
#pprint(authdata)
auth = OAuthHandler(authdata['consumer_key'], authdata['consumer_secret'])
auth.set_access_token(authdata['access_token'], authdata['access_token_secret'])
api = API(auth)
return api
def parsedata(jsonfile):
| 64 | 64 | 54 | 6 | 57 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | parsedata | parsedata | 24 | 33 | 24 | 24 | e1a572307a2d26910432a8a38845b4a261bc1ded | bigcode/the-stack | train |
4e5c7bfdeb3e5f66688db909 | train | function | def work():
pin = 17
wiringpi.pinMode(pin,wiringpi.GPIO.OUTPUT)
try:
for i in range (0,3):
wiringpi.digitalWrite(pin,wiringpi.GPIO.HIGH)
wiringpi.delay(500)
wiringpi.digitalWrite(pin,wiringpi.GPIO.LOW)
wiringpi.delay(500)
finally:
wiringpi.digitalWrite(pin,wiringpi.GPIO.LOW)
| def work():
| pin = 17
wiringpi.pinMode(pin,wiringpi.GPIO.OUTPUT)
try:
for i in range (0,3):
wiringpi.digitalWrite(pin,wiringpi.GPIO.HIGH)
wiringpi.delay(500)
wiringpi.digitalWrite(pin,wiringpi.GPIO.LOW)
wiringpi.delay(500)
finally:
wiringpi.digitalWrite(pin,wiringpi.GPIO.LOW)
| w') as f:
json.dump(d, f)
def filter_for_author(twt):
return twt.sender_screen_name == 'hrishikesh_date'
def nFilter(filters, tuples):
for f in filters:
tuples = ifilter(f, tuples)
return tuples
def work():
| 64 | 64 | 91 | 3 | 60 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | work | work | 47 | 57 | 47 | 47 | bcf2aec90dc6c0ad85644bfa673f1504e647ec02 | bigcode/the-stack | train |
ef2a184c9a101e155e351c17 | train | function | def getTwitterAPIHandle():
with open('api_secret_token.json') as data_file:
authdata = json.load(data_file)
#pprint(authdata)
auth = OAuthHandler(authdata['consumer_key'], authdata['consumer_secret'])
auth.set_access_token(authdata['access_token'], authdata['access_token_secret'])
api = API(auth)
r... | def getTwitterAPIHandle():
| with open('api_secret_token.json') as data_file:
authdata = json.load(data_file)
#pprint(authdata)
auth = OAuthHandler(authdata['consumer_key'], authdata['consumer_secret'])
auth.set_access_token(authdata['access_token'], authdata['access_token_secret'])
api = API(auth)
return api
| __ import absolute_import, print_function
import json
import os
from pprint import pprint
from tweepy import OAuthHandler
from tweepy import API
from itertools import ifilter
import wiringpi
wiringpi.wiringPiSetupGpio() # For GPIO pin numbering
def getTwitterAPIHandle():
| 64 | 64 | 81 | 6 | 57 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | getTwitterAPIHandle | getTwitterAPIHandle | 13 | 21 | 13 | 13 | 723edf4d0c108995ec489e8f5a949f373c82e247 | bigcode/the-stack | train |
f3dfbd6ab6f761cc95ef8ae5 | train | function | def filter_for_author(twt):
return twt.sender_screen_name == 'hrishikesh_date'
| def filter_for_author(twt):
| return twt.sender_screen_name == 'hrishikesh_date'
| .json') as f:
try:
data = json.load(f)
except ValueError:
#Ignore
pass
return data
def savedata(jsonfile,d):
with open(jsonfile, 'w') as f:
json.dump(d, f)
def filter_for_author(twt):
| 64 | 64 | 22 | 7 | 57 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | filter_for_author | filter_for_author | 39 | 40 | 39 | 39 | 5d07bd91b9aae3d68615c69d331a57d396db5c3c | bigcode/the-stack | train |
7364c23e76e65eb8c152b25e | train | function | def savedata(jsonfile,d):
with open(jsonfile, 'w') as f:
json.dump(d, f)
| def savedata(jsonfile,d):
| with open(jsonfile, 'w') as f:
json.dump(d, f)
| return api
def parsedata(jsonfile):
data = {}
if os.path.isfile(jsonfile):
with open('data.json') as f:
try:
data = json.load(f)
except ValueError:
#Ignore
pass
return data
def savedata(jsonfile,d):
| 64 | 64 | 26 | 7 | 56 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | savedata | savedata | 35 | 37 | 35 | 35 | dcc23ded1fd3e5c60427f5b49ca25825a8a8aff0 | bigcode/the-stack | train |
4c16014ac908b6d21e035cca | train | function | def nFilter(filters, tuples):
for f in filters:
tuples = ifilter(f, tuples)
return tuples
| def nFilter(filters, tuples):
| for f in filters:
tuples = ifilter(f, tuples)
return tuples
|
pass
return data
def savedata(jsonfile,d):
with open(jsonfile, 'w') as f:
json.dump(d, f)
def filter_for_author(twt):
return twt.sender_screen_name == 'hrishikesh_date'
def nFilter(filters, tuples):
| 63 | 64 | 26 | 7 | 56 | fuzzyhandle/pihangout | homeautomation/listner_blinkled/listner_blinkled.py | Python | nFilter | nFilter | 42 | 45 | 42 | 42 | bb3d5838c53c5395b3032e7f6661a3a70a0d94cf | bigcode/the-stack | train |
6776b6e2d08500083a01e382 | train | function | def main():
# """
# Main function of test python module
# """
# random.seed(os.urandom(345634)) # initialize random generator
# t = np.linspace(0.0, 24.0, 96.0) # define the time axis of a day, here we use 96 values every quarter of an hour
# # standard load profile -- input
# q = extra.read_slp(t,
# ... | def main():
# """
# Main function of test python module
# """
# random.seed(os.urandom(345634)) # initialize random generator
# t = np.linspace(0.0, 24.0, 96.0) # define the time axis of a day, here we use 96 values every quarter of an hour
# # standard load profile -- input
# q = extra.read_slp(t,
# ... | """
New function for synthetic in repeated time
"""
t = np.linspace(0.0, 24.0, 96.0)
load_profile = extra.read_slp(t, 'Profielen-Elektriciteit-2015-versie-1.00 Folder/profielen Elektriciteit 2015 versie 1.00.csv')
slp = synthetic.create_synthetic_load(load_profile, 5.0, 5)
plt.step(range(len(slp)), slp)
plt.sho... | def main():
# """
# Main function of test python module
# """
# random.seed(os.urandom(345634)) # initialize random generator
# t = np.linspace(0.0, 24.0, 96.0) # define the time axis of a day, here we use 96 values every quarter of an hour
# # standard load profile -- input
# q = extra.read_slp(t,
# ... | 952 | 256 | 1,058 | 952 | 0 | GiorgosMethe/SLP-Demand_Decomposition_Tool | test.py | Python | main | main | 11 | 87 | 11 | 79 | c5228a0413c7c4970cd9c449fce13b04a13a8c98 | bigcode/the-stack | train |
6cac12bdee1dfc1e8737bc18 | train | class | class ParentSerializer(serializers.ModelSerializer):
class Meta:
model = Parent
fields = (
'id',
'firstname',
'lastname'
) | class ParentSerializer(serializers.ModelSerializer):
| class Meta:
model = Parent
fields = (
'id',
'firstname',
'lastname'
) | from rest_framework import serializers
from parents.models import Parent
class ParentSerializer(serializers.ModelSerializer):
| 19 | 64 | 34 | 7 | 11 | FR98/uvg-web | babiesManagerDjango/parents/serializers.py | Python | ParentSerializer | ParentSerializer | 6 | 13 | 6 | 6 | c0dea7c0e469eb5b5226d25eb982ca7261f2b55f | bigcode/the-stack | train |
7206cc1ebf176cb594edb4b4 | train | function | def preprocess(image_file, label_file):
images = read_file(image_file)
labels = read_file(label_file)
if (len(labels) > 10000):
labels = labels[:10000]
images = images[:10000]
flag_array = images > 128
images.setflags(write=1)
images[flag_array]=1
images[~flag_array]=0
... | def preprocess(image_file, label_file):
| images = read_file(image_file)
labels = read_file(label_file)
if (len(labels) > 10000):
labels = labels[:10000]
images = images[:10000]
flag_array = images > 128
images.setflags(write=1)
images[flag_array]=1
images[~flag_array]=0
images = images.reshape( (10000, 784)... | >HBB', fp.read(4))
shape = tuple(struct.unpack('>I', fp.read(4))[0] for d in range(dims))
np_array = np.frombuffer(fp.read(), dtype=np.uint8).reshape(shape)
return np_array
def preprocess(image_file, label_file):
| 64 | 64 | 134 | 8 | 55 | mohiitgupta/mnist_digit_recognize | util.py | Python | preprocess | preprocess | 12 | 28 | 12 | 12 | d76b4b2b631907284bd4e1ff21cc46f98385b674 | bigcode/the-stack | train |
8a44200755abe57d7165283b | train | function | def inference(test_data, weights):
data_size = len(test_data)
bias = np.ones((data_size,1))
examples, labels = get_features_labels(test_data, bias)
prediction = np.ones(data_size, dtype = int)
correct = 0
for i, example in enumerate(examples):
activation_values = np.sum(weights*example, ... | def inference(test_data, weights):
| data_size = len(test_data)
bias = np.ones((data_size,1))
examples, labels = get_features_labels(test_data, bias)
prediction = np.ones(data_size, dtype = int)
correct = 0
for i, example in enumerate(examples):
activation_values = np.sum(weights*example, axis = 1)
prediction[i] = n... | on_type:
return 1
return -1
def get_features_labels(data, bias):
examples = data[:,:-1]
labels = data[:,-1]
examples = np.append(examples, bias, 1)
return examples, labels
def inference(test_data, weights):
| 64 | 64 | 127 | 7 | 56 | mohiitgupta/mnist_digit_recognize | util.py | Python | inference | inference | 41 | 53 | 41 | 41 | daea961f97a2116780a6113053066e85d6de5624 | bigcode/the-stack | train |
293e4595d22c8e54d0ea3b7d | train | function | def read_file(filename):
with open(filename,'rb') as fp:
zero, data_type, dims = struct.unpack('>HBB', fp.read(4))
shape = tuple(struct.unpack('>I', fp.read(4))[0] for d in range(dims))
np_array = np.frombuffer(fp.read(), dtype=np.uint8).reshape(shape)
return np_array
| def read_file(filename):
| with open(filename,'rb') as fp:
zero, data_type, dims = struct.unpack('>HBB', fp.read(4))
shape = tuple(struct.unpack('>I', fp.read(4))[0] for d in range(dims))
np_array = np.frombuffer(fp.read(), dtype=np.uint8).reshape(shape)
return np_array
| import numpy as np
import struct
from f1_macro import calculate_macro_f1_score
def read_file(filename):
| 24 | 64 | 82 | 5 | 18 | mohiitgupta/mnist_digit_recognize | util.py | Python | read_file | read_file | 5 | 10 | 5 | 5 | 6a4eadb63f6f5230f13d9de34f1298edba59d29a | bigcode/the-stack | train |
1629f3137da63577fc628dad | train | function | def get_f1_score(test_data, weights):
prediction, true_labels = inference(test_data, weights)
f1_score = calculate_macro_f1_score(prediction, true_labels)
return f1_score | def get_f1_score(test_data, weights):
| prediction, true_labels = inference(test_data, weights)
f1_score = calculate_macro_f1_score(prediction, true_labels)
return f1_score | (weights*example, axis = 1)
prediction[i] = np.argmax(activation_values)
if prediction[i] == labels[i]:
correct += 1
# print correct*1.0/data_size*100
return prediction, labels
def get_f1_score(test_data, weights):
| 64 | 64 | 43 | 10 | 53 | mohiitgupta/mnist_digit_recognize | util.py | Python | get_f1_score | get_f1_score | 55 | 58 | 55 | 55 | 5ae96aaa87cd6fae073c0ae84b332e6c73a44235 | bigcode/the-stack | train |
8d73ebf57eb0c31c718176a2 | train | function | def get_true_label(digit, perceptron_type):
if digit == perceptron_type:
return 1
return -1
| def get_true_label(digit, perceptron_type):
| if digit == perceptron_type:
return 1
return -1
| _array]=0
images = images.reshape( (10000, 784))
labels = labels.reshape(-1,1)
data = np.concatenate((images, labels), axis=1)
# np.random.shuffle(data)
return data
def get_true_label(digit, perceptron_type):
| 64 | 64 | 31 | 12 | 51 | mohiitgupta/mnist_digit_recognize | util.py | Python | get_true_label | get_true_label | 30 | 33 | 30 | 30 | f78e218c748f5a66f54ecf101e6e7e610498364f | bigcode/the-stack | train |
5d5723bfc8395cf8fbe1d218 | train | function | def get_features_labels(data, bias):
examples = data[:,:-1]
labels = data[:,-1]
examples = np.append(examples, bias, 1)
return examples, labels
| def get_features_labels(data, bias):
| examples = data[:,:-1]
labels = data[:,-1]
examples = np.append(examples, bias, 1)
return examples, labels
| data = np.concatenate((images, labels), axis=1)
# np.random.shuffle(data)
return data
def get_true_label(digit, perceptron_type):
if digit == perceptron_type:
return 1
return -1
def get_features_labels(data, bias):
| 64 | 64 | 44 | 8 | 55 | mohiitgupta/mnist_digit_recognize | util.py | Python | get_features_labels | get_features_labels | 35 | 39 | 35 | 35 | 6e9f3a07cc792f581628d667d2ea1c0a8ed9174c | bigcode/the-stack | train |
fc5a996f52b9b3e2923992bc | train | function | def test_fillna_feature_generator(generator_helper, data_helper):
# Given
input_data = data_helper.generate_multi_feature_full()
expected_output_data = input_data.fillna(
{
'int': np.nan,
'float': np.nan,
'obj': '',
'cat': np.nan,
'datetime... | def test_fillna_feature_generator(generator_helper, data_helper):
# Given
| input_data = data_helper.generate_multi_feature_full()
expected_output_data = input_data.fillna(
{
'int': np.nan,
'float': np.nan,
'obj': '',
'cat': np.nan,
'datetime': np.nan,
'text': '',
'datetime_as_object': ''
... | import copy
import numpy as np
from autogluon.tabular.features import FillNaFeatureGenerator
# TODO: Consider adding test of loading from csv
def test_fillna_feature_generator(generator_helper, data_helper):
# Given
| 49 | 76 | 254 | 16 | 32 | RuohanW/autogluon | tabular/tests/unittests/features/generators/test_fillna.py | Python | test_fillna_feature_generator | test_fillna_feature_generator | 9 | 47 | 9 | 10 | e84ca5f48b8f5e3b18dc4e0f2d34ec1cb826a062 | bigcode/the-stack | train |
631c6bbfa6c7f72ffa081acb | train | function | def test_fillna_object_edgecase_feature_generator(generator_helper, data_helper):
# Given
input_data = data_helper.generate_int_feature().to_frame('int_as_object')
input_data = input_data.astype('object')
edge_case_input = copy.deepcopy(input_data)
input_data.loc[0] = np.nan
expected_output_data... | def test_fillna_object_edgecase_feature_generator(generator_helper, data_helper):
# Given
| input_data = data_helper.generate_int_feature().to_frame('int_as_object')
input_data = input_data.astype('object')
edge_case_input = copy.deepcopy(input_data)
input_data.loc[0] = np.nan
expected_output_data = copy.deepcopy(input_data)
expected_output_data.loc[0] = ''
generator = FillNaFeatu... | _data)
# Edge case when input is all integers but is of object type without NaN values. Without downcast=False, it will be converted to int type.
# This test confirms that this unwanted conversion does not happen.
def test_fillna_object_edgecase_feature_generator(generator_helper, data_helper):
# Given
| 64 | 64 | 209 | 19 | 45 | RuohanW/autogluon | tabular/tests/unittests/features/generators/test_fillna.py | Python | test_fillna_object_edgecase_feature_generator | test_fillna_object_edgecase_feature_generator | 52 | 80 | 52 | 53 | 3a9e0298f6046e4150967570d6f3ab9645c24519 | bigcode/the-stack | train |
6d43d75410719b28cc9a20a6 | train | class | class UsecaseTests(WebTest):
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.user = mommy.make(
UserProfile,
username="user",
password="pbkdf2_sha256$12000$uH9Cc7pBkaxQ$XLVGZKTbCyuDlgFQB65Mn5SAm6v/2kjpCTct1td2VTo=")
mommy.make(UserProfile, username="noname")
mo... | class UsecaseTests(WebTest):
| extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.user = mommy.make(
UserProfile,
username="user",
password="pbkdf2_sha256$12000$uH9Cc7pBkaxQ$XLVGZKTbCyuDlgFQB65Mn5SAm6v/2kjpCTct1td2VTo=")
mommy.make(UserProfile, username="noname")
mommy.make(UserProfile, usernam... | from django.conf import settings
from django.contrib.auth.models import Group
from django.test.utils import override_settings
from django.urls import reverse
from django_webtest import WebTest
from guardian.shortcuts import assign_perm
from guardian.utils import get_anonymous_user
from model_mommy import mommy
from _... | 86 | 256 | 1,280 | 7 | 78 | felixrindt/1327 | _1327/user_management/tests.py | Python | UsecaseTests | UsecaseTests | 15 | 141 | 15 | 15 | a4c4d161df00cb4ec59be800c36862b3ac745e33 | bigcode/the-stack | train |
958592a6e1b512c5b9cd0e9f | train | class | class _1327AuthenticationBackendTests(WebTest):
csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.document = mommy.make(InformationDocument)
cls.user = mommy.make(UserProfile)
def test_anonymous_fallback_if_user_has_no_permissions(self):
anonymous_... | class _1327AuthenticationBackendTests(WebTest):
| csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.document = mommy.make(InformationDocument)
cls.user = mommy.make(UserProfile)
def test_anonymous_fallback_if_user_has_no_permissions(self):
anonymous_user = get_anonymous_user()
anonymous_groups = ... | = UserProfile.objects.get(username='test')
response = self.app.post('/hijack/{email}/'.format(email=user.email), user=self.user, expect_errors=True)
self.assertEqual(response.status_code, 400)
response = self.app.post('/hijack/{username}/'.format(username=user.username), user=self.user, expect_errors=True)
s... | 95 | 95 | 319 | 10 | 85 | felixrindt/1327 | _1327/user_management/tests.py | Python | _1327AuthenticationBackendTests | _1327AuthenticationBackendTests | 198 | 232 | 198 | 199 | 2b9d413161e0c84605233bbaf08c8ebd6ccde836 | bigcode/the-stack | train |
fac31d1f96c7cdc90d236197 | train | class | class UserImpersonationTests(WebTest):
csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.user = mommy.make(UserProfile, is_superuser=True)
mommy.make(UserProfile, username='test')
def test_view_impersonation_page(self):
response = self.app.get(rever... | class UserImpersonationTests(WebTest):
| csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.user = mommy.make(UserProfile, is_superuser=True)
mommy.make(UserProfile, username='test')
def test_view_impersonation_page(self):
response = self.app.get(reverse('view_as'), user=self.user)
self.a... | (username='nolastname')
self.assertEqual(user.get_full_name(), 'First')
self.assertEqual(user.get_short_name(), 'First')
user = UserProfile.objects.get(username='admin')
self.assertEqual(user.get_full_name(), 'Admin User')
self.assertEqual(user.get_short_name(), 'Admin')
def test_default_group(self):
use... | 152 | 152 | 509 | 9 | 143 | felixrindt/1327 | _1327/user_management/tests.py | Python | UserImpersonationTests | UserImpersonationTests | 144 | 195 | 144 | 144 | 76cddbace2959718fc21f6928d8bf8f18d854471 | bigcode/the-stack | train |
632014567cc7587a9b89e2b4 | train | class | @override_settings(ANONYMOUS_IP_RANGE_GROUPS={'8.0.0.0/8': 'university_group'})
class _1327AuthenticationBackendUniversityNetworkTests(WebTest):
csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.document = mommy.make(InformationDocument)
cls.university... | @override_settings(ANONYMOUS_IP_RANGE_GROUPS={'8.0.0.0/8': 'university_group'})
class _1327AuthenticationBackendUniversityNetworkTests(WebTest):
| csrf_checks = False
extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}
@classmethod
def setUpTestData(cls):
cls.document = mommy.make(InformationDocument)
cls.university_group = mommy.make(Group, name='university_group')
def test_university_network_fallback_no_access(self):
# check that user is not allowed to ... | Equal(response.status_code, 403)
def test_anonymous_fallback_not_used_if_user_has_permission(self):
group = mommy.make(Group)
self.user.groups.add(group)
self.user.save()
assign_perm(self.document.view_permission_name, group, self.document)
response = self.app.get(reverse(self.document.get_view_url_name()... | 131 | 131 | 439 | 40 | 91 | felixrindt/1327 | _1327/user_management/tests.py | Python | _1327AuthenticationBackendUniversityNetworkTests | _1327AuthenticationBackendUniversityNetworkTests | 235 | 273 | 235 | 237 | 71624e7b3d2e8b1c443cf7c5dcb60e61fe8432d8 | bigcode/the-stack | train |
93d8d5875922a72a1b29af45 | train | class | class ATRIndicator(Indicator):
"""
Average True Range indicator
Also update the last ATR stop-loss for the two directions.
Compute need at least N candles plus one.
- distance entre le haut du jour et le bas du jour.
- distance entre la clôture de la veille et le haut du jour
- ... | class ATRIndicator(Indicator):
| """
Average True Range indicator
Also update the last ATR stop-loss for the two directions.
Compute need at least N candles plus one.
- distance entre le haut du jour et le bas du jour.
- distance entre la clôture de la veille et le haut du jour
- distance entre la clôture de la... | # @date 2019-02-13
# @author Frederic Scherma, All rights reserved without prejudices.
# @license Copyright (c) 2019 Dream Overflow
# Average True Range indicator
from strategy.indicator.indicator import Indicator
# from strategy.indicator.utils import down_sample, MM_n
from talib import ATR as ta_ATR # , SMA as ta_S... | 97 | 256 | 1,029 | 6 | 90 | firebird631/siis | strategy/indicator/atr/atr.py | Python | ATRIndicator | ATRIndicator | 13 | 137 | 13 | 13 | 4ed300e8b51ab847ec4c41516d24b13d2c1a81df | bigcode/the-stack | train |
62e244d268ab3d1f9e2eda23 | train | class | class BaseBlock(BaseModule):
""" Base class for all blocks. """
def __init__(self, channel_in, channel_out, activation_fn, use_bn=True, use_bias=True):
# type: (int, int, Module, bool, bool) -> None
"""
Class constructor.
:param channel_in: number of input channels.
:par... | class BaseBlock(BaseModule):
| """ Base class for all blocks. """
def __init__(self, channel_in, channel_out, activation_fn, use_bn=True, use_bias=True):
# type: (int, int, Module, bool, bool) -> None
"""
Class constructor.
:param channel_in: number of input channels.
:param channel_out: number of out... | )
if bn2 is not None:
ha = bn2(ha)
# B-branch
hb = x
if f3 is not None:
hb = f3(hb)
if bn3 is not None:
hb = bn3(hb)
# Residual connection
out = ha + hb
return activation_fn(out)
class BaseBlock(BaseModule):
| 85 | 85 | 286 | 6 | 79 | BotanAtomic/anomaly-detection | models/blocks_3d.py | Python | BaseBlock | BaseBlock | 54 | 89 | 54 | 54 | d14a12af1208e3f32525fea61be8a5364c3b929f | bigcode/the-stack | train |
2c04678216d689f3fe951c8b | train | class | class DownsampleBlock(BaseBlock):
""" Implements a Downsampling block for videos (Fig. 1ii). """
def __init__(self, channel_in, channel_out, activation_fn, stride, use_bn=True, use_bias=False):
# type: (int, int, Module, Tuple[int, int, int], bool, bool) -> None
"""
Class constructor.
... | class DownsampleBlock(BaseBlock):
| """ Implements a Downsampling block for videos (Fig. 1ii). """
def __init__(self, channel_in, channel_out, activation_fn, stride, use_bn=True, use_bias=False):
# type: (int, int, Module, Tuple[int, int, int], bool, bool) -> None
"""
Class constructor.
:param channel_in: number o... | .'
self._channel_in = channel_in
self._channel_out = channel_out
self._activation_fn = activation_fn
self._use_bn = use_bn
self._bias = use_bias
def get_bn(self):
# type: () -> Optional[Module]
"""
Returns batch norm layers, if needed.
:retur... | 138 | 138 | 460 | 7 | 130 | BotanAtomic/anomaly-detection | models/blocks_3d.py | Python | DownsampleBlock | DownsampleBlock | 92 | 134 | 92 | 92 | 9fe0ddd22d2115137ce0d902c160f25929651605 | bigcode/the-stack | train |
f6646763b013ef16ee8c0033 | train | class | class UpsampleBlock(BaseBlock):
""" Implements a Upsampling block for videos (Fig. 1ii). """
def __init__(self, channel_in, channel_out, activation_fn, stride, output_padding, use_bn=True, use_bias=False):
# type: (int, int, Module, Tuple[int, int, int], Tuple[int, int, int], bool, bool) -> None
... | class UpsampleBlock(BaseBlock):
| """ Implements a Upsampling block for videos (Fig. 1ii). """
def __init__(self, channel_in, channel_out, activation_fn, stride, output_padding, use_bn=True, use_bias=False):
# type: (int, int, Module, Tuple[int, int, int], Tuple[int, int, int], bool, bool) -> None
"""
Class constructor.
... | bias=use_bias)
# Batch Normalization layers
self.bn1a = self.get_bn()
self.bn1b = self.get_bn()
self.bn2a = self.get_bn()
def forward(self, x):
# type: (torch.Tensor) -> torch.Tensor
"""
Forward propagation.
:param x: the input tensor
:retur... | 148 | 148 | 494 | 7 | 141 | BotanAtomic/anomaly-detection | models/blocks_3d.py | Python | UpsampleBlock | UpsampleBlock | 137 | 181 | 137 | 137 | 99ba5f89011e8a81914d5a528ef2be172cd93e81 | bigcode/the-stack | train |
3204bf44b16b5e8a87417c66 | train | function | def residual_op(x, functions, bns, activation_fn):
# type: (torch.Tensor, List[Module, Module, Module], List[Module, Module, Module], Module) -> torch.Tensor
"""
Implements a global residual operation.
:param x: the input tensor.
:param functions: a list of functions (nn.Modules).
:param bns: a... | def residual_op(x, functions, bns, activation_fn):
# type: (torch.Tensor, List[Module, Module, Module], List[Module, Module, Module], Module) -> torch.Tensor
| """
Implements a global residual operation.
:param x: the input tensor.
:param functions: a list of functions (nn.Modules).
:param bns: a list of optional batch-norm layers.
:param activation_fn: the activation to be applied.
:return: the output of the residual operation.
"""
f1, f2... | typing import List
from typing import Optional
from typing import Tuple
import torch
import torch.nn as nn
from torch.nn import Module
from models.base import BaseModule
from models.layers.mconv3d import MaskedConv3d
def residual_op(x, functions, bns, activation_fn):
# type: (torch.Tensor, List[Module, Module, M... | 93 | 93 | 312 | 43 | 49 | BotanAtomic/anomaly-detection | models/blocks_3d.py | Python | residual_op | residual_op | 13 | 51 | 13 | 14 | ff4bd8026554529d2319a6405942edae8ecaa47f | bigcode/the-stack | train |
772da24859d8c1a00ea3f138 | train | function | def sweep(privkeys, network: 'Network', config: 'SimpleConfig', recipient, fee=None, imax=100,
*, locktime=None, tx_version=None):
inputs, keypairs = sweep_preparations(privkeys, network, imax)
total = sum(i.get('value') for i in inputs)
if fee is None:
outputs = [TxOutput(TYPE_ADDRESS, re... | def sweep(privkeys, network: 'Network', config: 'SimpleConfig', recipient, fee=None, imax=100,
*, locktime=None, tx_version=None):
| inputs, keypairs = sweep_preparations(privkeys, network, imax)
total = sum(i.get('value') for i in inputs)
if fee is None:
outputs = [TxOutput(TYPE_ADDRESS, recipient, total)]
tx = Transaction.from_io(inputs, outputs)
fee = config.estimate_fee(tx.estimated_size())
if total - fee ... | that inputs need to be confirmed)'))
# FIXME actually inputs need not be confirmed now, see https://github.com/kyuupichan/electrumx/issues/365
return inputs, keypairs
def sweep(privkeys, network: 'Network', config: 'SimpleConfig', recipient, fee=None, imax=100,
*, locktime=None, tx_version=None):... | 81 | 81 | 270 | 36 | 44 | zumbrunn/electrumfair | electrum/wallet.py | Python | sweep | sweep | 130 | 150 | 130 | 131 | f9be9b6f4137432ce46a9a93e10c6cecc85e7f59 | bigcode/the-stack | train |
f00bab8a0a6851280204bee0 | train | function | def append_utxos_to_inputs(inputs, network: 'Network', pubkey, txin_type, imax):
if txin_type != 'p2pk':
address = bitcoin.pubkey_to_address(txin_type, pubkey)
scripthash = bitcoin.address_to_scripthash(address)
else:
script = bitcoin.public_key_to_p2pk_script(pubkey)
scripthash ... | def append_utxos_to_inputs(inputs, network: 'Network', pubkey, txin_type, imax):
| if txin_type != 'p2pk':
address = bitcoin.pubkey_to_address(txin_type, pubkey)
scripthash = bitcoin.address_to_scripthash(address)
else:
script = bitcoin.public_key_to_p2pk_script(pubkey)
scripthash = bitcoin.script_to_scripthash(script)
address = '(pubkey)'
u = netw... |
if TYPE_CHECKING:
from .network import Network
from .simple_config import SimpleConfig
TX_STATUS = [
_('Unconfirmed'),
_('Unconfirmed parent'),
_('Not Verified'),
_('Local'),
]
def append_utxos_to_inputs(inputs, network: 'Network', pubkey, txin_type, imax):
| 71 | 71 | 239 | 24 | 47 | zumbrunn/electrumfair | electrum/wallet.py | Python | append_utxos_to_inputs | append_utxos_to_inputs | 81 | 102 | 81 | 81 | 7601c2057dd810b4b7f550b071bcf07d97fc2c37 | bigcode/the-stack | train |
1cf5a3bb7596ea1829fbf8ee | train | function | def create_new_wallet(*, path, passphrase=None, password=None, encrypt_file=True, segwit=True):
"""Create a new wallet"""
storage = WalletStorage(path)
if storage.file_exists():
raise Exception("Remove the existing wallet first!")
seed_type = 'segwit' if segwit else 'standard'
seed = Mnemon... | def create_new_wallet(*, path, passphrase=None, password=None, encrypt_file=True, segwit=True):
| """Create a new wallet"""
storage = WalletStorage(path)
if storage.file_exists():
raise Exception("Remove the existing wallet first!")
seed_type = 'segwit' if segwit else 'standard'
seed = Mnemonic('en').make_seed(seed_type)
k = keystore.from_seed(seed, passphrase)
storage.put('keys... | return Multisig_Wallet
if wallet_type in wallet_constructors:
return wallet_constructors[wallet_type]
raise WalletFileException("Unknown wallet type: " + str(wallet_type))
def create_new_wallet(*, path, passphrase=None, password=None, encrypt_file=True, segwit=True):
| 64 | 64 | 192 | 23 | 41 | zumbrunn/electrumfair | electrum/wallet.py | Python | create_new_wallet | create_new_wallet | 1,851 | 1,868 | 1,851 | 1,851 | 9783441dd8dadff925b71546ecb5d5f2308d1556 | bigcode/the-stack | train |
ae5c4a445aab99aedff06413 | train | class | class Deterministic_Wallet(Abstract_Wallet):
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
self.gap_limit = storage.get('gap_limit', 20)
# generate addresses now. note that without libsecp this might block
# for a few seconds!
self.synchronize()
d... | class Deterministic_Wallet(Abstract_Wallet):
| def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
self.gap_limit = storage.get('gap_limit', 20)
# generate addresses now. note that without libsecp this might block
# for a few seconds!
self.synchronize()
def has_seed(self):
return self.keystor... | = d['redeem_script']
return redeem_script
def get_txin_type(self, address):
return self.db.get_imported_address(address).get('type', 'address')
def add_input_sig_info(self, txin, address):
if self.is_watching_only():
x_pubkey = 'fd' + address_to_script(address)
... | 256 | 256 | 1,062 | 10 | 245 | zumbrunn/electrumfair | electrum/wallet.py | Python | Deterministic_Wallet | Deterministic_Wallet | 1,524 | 1,662 | 1,524 | 1,525 | ee3f07ac8ef6bc85135f015f441ae2505105476c | bigcode/the-stack | train |
d1c452309a6a2689666490bd | train | class | class InternalAddressCorruption(Exception):
def __str__(self):
return _("Wallet file corruption detected. "
"Please restore your wallet from seed, and compare the addresses in both files")
| class InternalAddressCorruption(Exception):
| def __str__(self):
return _("Wallet file corruption detected. "
"Please restore your wallet from seed, and compare the addresses in both files")
| offline/multisig/coinjoin/...)
if random.randint(0, 9) == 0:
locktime = max(0, locktime - random.randint(0, 99))
return locktime
class CannotBumpFee(Exception): pass
class InternalAddressCorruption(Exception):
| 64 | 64 | 40 | 7 | 56 | zumbrunn/electrumfair | electrum/wallet.py | Python | InternalAddressCorruption | InternalAddressCorruption | 177 | 180 | 177 | 177 | be03ee1f4e09b9cd421f3fe152f9b51b4d271c4a | bigcode/the-stack | train |
03e924712214be11506e55ac | train | function | def get_locktime_for_new_transaction(network: 'Network') -> int:
# if no network or not up to date, just set locktime to zero
if not network:
return 0
chain = network.blockchain()
header = chain.header_at_tip()
if not header:
return 0
STALE_DELAY = 8 * 60 * 60 # in seconds
i... | def get_locktime_for_new_transaction(network: 'Network') -> int:
# if no network or not up to date, just set locktime to zero
| if not network:
return 0
chain = network.blockchain()
header = chain.header_at_tip()
if not header:
return 0
STALE_DELAY = 8 * 60 * 60 # in seconds
if header['timestamp'] + STALE_DELAY < time.time():
return 0
# discourage "fee sniping"
locktime = chain.height()
... | , outputs, locktime=locktime, version=tx_version)
tx.set_rbf(True)
tx.sign(keypairs)
return tx
def get_locktime_for_new_transaction(network: 'Network') -> int:
# if no network or not up to date, just set locktime to zero
| 64 | 64 | 192 | 33 | 30 | zumbrunn/electrumfair | electrum/wallet.py | Python | get_locktime_for_new_transaction | get_locktime_for_new_transaction | 153 | 170 | 153 | 154 | 99438e0cb541177efce43fc06a21addb9b18acee | bigcode/the-stack | train |
08aab27b431ae0bcccaa53b9 | train | class | class Standard_Wallet(Simple_Deterministic_Wallet):
wallet_type = 'standard'
def pubkeys_to_address(self, pubkey):
return bitcoin.pubkey_to_address(self.txin_type, pubkey)
| class Standard_Wallet(Simple_Deterministic_Wallet):
| wallet_type = 'standard'
def pubkeys_to_address(self, pubkey):
return bitcoin.pubkey_to_address(self.txin_type, pubkey)
| txin['num_sig'] = 1
def get_master_public_key(self):
return self.keystore.get_master_public_key()
def derive_pubkeys(self, c, i):
return self.keystore.derive_pubkey(c, i)
class Standard_Wallet(Simple_Deterministic_Wallet):
| 63 | 64 | 44 | 11 | 52 | zumbrunn/electrumfair | electrum/wallet.py | Python | Standard_Wallet | Standard_Wallet | 1,706 | 1,710 | 1,706 | 1,706 | 1c7c18b32d1c3eb8c41ce9b1038e8b52e20fcf53 | bigcode/the-stack | train |
f7bf5dd31d6a736a10452a7d | train | function | def sweep_preparations(privkeys, network: 'Network', imax=100):
def find_utxos_for_privkey(txin_type, privkey, compressed):
pubkey = ecc.ECPrivkey(privkey).get_public_key_hex(compressed=compressed)
append_utxos_to_inputs(inputs, network, pubkey, txin_type, imax)
keypairs[pubkey] = privkey, ... | def sweep_preparations(privkeys, network: 'Network', imax=100):
| def find_utxos_for_privkey(txin_type, privkey, compressed):
pubkey = ecc.ECPrivkey(privkey).get_public_key_hex(compressed=compressed)
append_utxos_to_inputs(inputs, network, pubkey, txin_type, imax)
keypairs[pubkey] = privkey, compressed
inputs = []
keypairs = {}
for sec in privk... | _type
item['prevout_hash'] = item['tx_hash']
item['prevout_n'] = int(item['tx_pos'])
item['pubkeys'] = [pubkey]
item['x_pubkeys'] = [pubkey]
item['signatures'] = [None]
item['num_sig'] = 1
inputs.append(item)
def sweep_preparations(privkeys, network: 'Network', im... | 95 | 95 | 319 | 18 | 77 | zumbrunn/electrumfair | electrum/wallet.py | Python | sweep_preparations | sweep_preparations | 104 | 127 | 104 | 105 | f47c09c69ed0f3aed48608e47986a3bba2b163f5 | bigcode/the-stack | train |
e0e95ab812a4faf7ad40966e | train | class | class Simple_Deterministic_Wallet(Simple_Wallet, Deterministic_Wallet):
""" Deterministic Wallet with a single pubkey per address """
def __init__(self, storage):
Deterministic_Wallet.__init__(self, storage)
def get_public_key(self, address):
sequence = self.get_address_index(address)
... | class Simple_Deterministic_Wallet(Simple_Wallet, Deterministic_Wallet):
| """ Deterministic Wallet with a single pubkey per address """
def __init__(self, storage):
Deterministic_Wallet.__init__(self, storage)
def get_public_key(self, address):
sequence = self.get_address_index(address)
pubkey = self.get_pubkey(*sequence)
return pubkey
def l... | return True
def get_address_index(self, address):
return self.db.get_address_index(address)
def get_master_public_keys(self):
return [self.get_master_public_key()]
def get_fingerprint(self):
return self.get_master_public_key()
def get_txin_type(self, address):
return... | 88 | 88 | 295 | 17 | 70 | zumbrunn/electrumfair | electrum/wallet.py | Python | Simple_Deterministic_Wallet | Simple_Deterministic_Wallet | 1,665 | 1,699 | 1,665 | 1,666 | 823e4ff60e70743d30204496f3a59435462bef4a | bigcode/the-stack | train |
ec8c823a6b72c94f7eb19933 | train | class | class Wallet(object):
"""The main wallet "entry point".
This class is actually a factory that will return a wallet of the correct
type when passed a WalletStorage instance."""
def __new__(self, storage):
wallet_type = storage.get('wallet_type')
WalletClass = Wallet.wallet_class(wallet_t... | class Wallet(object):
| """The main wallet "entry point".
This class is actually a factory that will return a wallet of the correct
type when passed a WalletStorage instance."""
def __new__(self, storage):
wallet_type = storage.get('wallet_type')
WalletClass = Wallet.wallet_class(wallet_type)
wallet = ... | {
'standard': Standard_Wallet,
'old': Standard_Wallet,
'xpub': Standard_Wallet,
'imported': Imported_Wallet
}
def register_constructor(wallet_type, constructor):
wallet_constructors[wallet_type] = constructor
# former WalletFactory
class Wallet(object):
| 64 | 64 | 139 | 4 | 59 | zumbrunn/electrumfair | electrum/wallet.py | Python | Wallet | Wallet | 1,831 | 1,848 | 1,831 | 1,831 | 0891433db3d4664a541cb5f2e09410cca63f1228 | bigcode/the-stack | train |
08f3ffdf06ecfb4cf34a5c2b | train | class | class Multisig_Wallet(Deterministic_Wallet):
# generic m of n
gap_limit = 20
def __init__(self, storage):
self.wallet_type = storage.get('wallet_type')
self.m, self.n = multisig_type(self.wallet_type)
Deterministic_Wallet.__init__(self, storage)
def get_pubkeys(self, c, i):
... | class Multisig_Wallet(Deterministic_Wallet):
# generic m of n
| gap_limit = 20
def __init__(self, storage):
self.wallet_type = storage.get('wallet_type')
self.m, self.n = multisig_type(self.wallet_type)
Deterministic_Wallet.__init__(self, storage)
def get_pubkeys(self, c, i):
return self.derive_pubkeys(c, i)
def get_public_keys(sel... | , 'keystore')
try:
xtype = bip32.xpub_type(self.keystore.xpub)
except:
xtype = 'standard'
self.txin_type = 'p2pkh' if xtype == 'standard' else xtype
def get_pubkey(self, c, i):
return self.derive_pubkeys(c, i)
def add_input_sig_info(self, txin, address):... | 256 | 256 | 929 | 20 | 236 | zumbrunn/electrumfair | electrum/wallet.py | Python | Multisig_Wallet | Multisig_Wallet | 1,713 | 1,812 | 1,713 | 1,714 | b0193a8ecbd696f8a2eb2560f2257bab7ae7e53b | bigcode/the-stack | train |
684de840c2288d71a1096fb0 | train | function | def register_constructor(wallet_type, constructor):
wallet_constructors[wallet_type] = constructor
| def register_constructor(wallet_type, constructor):
| wallet_constructors[wallet_type] = constructor
| 'imported']
def register_wallet_type(category):
wallet_types.append(category)
wallet_constructors = {
'standard': Standard_Wallet,
'old': Standard_Wallet,
'xpub': Standard_Wallet,
'imported': Imported_Wallet
}
def register_constructor(wallet_type, constructor):
| 64 | 64 | 19 | 8 | 56 | zumbrunn/electrumfair | electrum/wallet.py | Python | register_constructor | register_constructor | 1,827 | 1,828 | 1,827 | 1,827 | 2ec1278f794c8b0d2b6507f5327923c97ca29262 | bigcode/the-stack | train |
bf9b925597a1ecfda18f7a3b | train | function | def register_wallet_type(category):
wallet_types.append(category)
| def register_wallet_type(category):
| wallet_types.append(category)
| txin['pubkeys'] = None
# we need n place holders
txin['signatures'] = [None] * self.n
txin['num_sig'] = self.m
wallet_types = ['standard', 'multisig', 'imported']
def register_wallet_type(category):
| 64 | 64 | 12 | 6 | 58 | zumbrunn/electrumfair | electrum/wallet.py | Python | register_wallet_type | register_wallet_type | 1,817 | 1,818 | 1,817 | 1,817 | e88a6566f22069710cf07678ef75f628c9da2d0c | bigcode/the-stack | train |
750a0a13ccbbca27991750d1 | train | class | class Abstract_Wallet(AddressSynchronizer):
"""
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
max_change_outputs = 3
gap_limit_for_change = 6
verbosity_filter = 'w'
... | class Abstract_Wallet(AddressSynchronizer):
| """
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
max_change_outputs = 3
gap_limit_for_change = 6
verbosity_filter = 'w'
def __init__(self, storage: WalletStorage)... | pairs)
return tx
def get_locktime_for_new_transaction(network: 'Network') -> int:
# if no network or not up to date, just set locktime to zero
if not network:
return 0
chain = network.blockchain()
header = chain.header_at_tip()
if not header:
return 0
STALE_DELAY = 8 * 60 *... | 255 | 256 | 9,953 | 8 | 247 | zumbrunn/electrumfair | electrum/wallet.py | Python | Abstract_Wallet | Abstract_Wallet | 184 | 1,305 | 184 | 184 | 4b5db817c2411a1b5eac22ca414358093919dfe3 | bigcode/the-stack | train |
a6029aff51133e2f4a25ccf5 | train | class | class Simple_Wallet(Abstract_Wallet):
# wallet with a single keystore
def get_keystore(self):
return self.keystore
def get_keystores(self):
return [self.keystore]
def is_watching_only(self):
return self.keystore.is_watching_only()
def _update_password_for_keystore(self, o... | class Simple_Wallet(Abstract_Wallet):
# wallet with a single keystore
| def get_keystore(self):
return self.keystore
def get_keystores(self):
return [self.keystore]
def is_watching_only(self):
return self.keystore.is_watching_only()
def _update_password_for_keystore(self, old_pw, new_pw):
if self.keystore and self.keystore.may_have_passwor... | txin_value/Decimal(COIN)
def is_billing_address(self, addr):
# overloaded for TrustedCoin wallets
return False
def is_watching_only(self) -> bool:
raise NotImplementedError()
class Simple_Wallet(Abstract_Wallet):
# wallet with a single keystore
| 64 | 64 | 131 | 17 | 47 | zumbrunn/electrumfair | electrum/wallet.py | Python | Simple_Wallet | Simple_Wallet | 1,308 | 1,326 | 1,308 | 1,310 | 3da2c75814b07ed3a3fc5b3218786e628e4eba68 | bigcode/the-stack | train |
febe60f36a0a4a12de11c946 | train | class | class Imported_Wallet(Simple_Wallet):
# wallet made of imported addresses
wallet_type = 'imported'
txin_type = 'address'
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
def is_watching_only(self):
return self.keystore is None
def get_keystores(self):
... | class Imported_Wallet(Simple_Wallet):
# wallet made of imported addresses
| wallet_type = 'imported'
txin_type = 'address'
def __init__(self, storage):
Abstract_Wallet.__init__(self, storage)
def is_watching_only(self):
return self.keystore is None
def get_keystores(self):
return [self.keystore] if self.keystore else []
def can_import_privkey... | [cache_key] = result
return result
else:
fiat_value = self.get_fiat_value(txid, ccy)
if fiat_value is not None:
return fiat_value
else:
p = self.price_at_timestamp(txid, price_func)
return p * txin_value/Decimal(COIN... | 256 | 256 | 1,564 | 16 | 240 | zumbrunn/electrumfair | electrum/wallet.py | Python | Imported_Wallet | Imported_Wallet | 1,329 | 1,522 | 1,329 | 1,331 | 0ad7ce4a4de5b9e9a31f0bf70762cec7626a6217 | bigcode/the-stack | train |
ea1998a8711336c679fb23ff | train | class | class CannotBumpFee(Exception): pass
| class CannotBumpFee(Exception): | pass
| # of setups that need more time (offline/multisig/coinjoin/...)
if random.randint(0, 9) == 0:
locktime = max(0, locktime - random.randint(0, 99))
return locktime
class CannotBumpFee(Exception): | 64 | 64 | 9 | 8 | 55 | zumbrunn/electrumfair | electrum/wallet.py | Python | CannotBumpFee | CannotBumpFee | 174 | 174 | 174 | 174 | 0ed3649dd9e4fb471fe71ee8b482931061409dff | bigcode/the-stack | train |
cca4043336608f4cbba120e9 | train | function | def restore_wallet_from_text(text, *, path, network, passphrase=None, password=None, encrypt_file=True):
"""Restore a wallet from text. Text can be a seed phrase, a master
public key, a master private key, a list of bitcoin addresses
or bitcoin private keys."""
storage = WalletStorage(path)
if stora... | def restore_wallet_from_text(text, *, path, network, passphrase=None, password=None, encrypt_file=True):
| """Restore a wallet from text. Text can be a seed phrase, a master
public key, a master private key, a list of bitcoin addresses
or bitcoin private keys."""
storage = WalletStorage(path)
if storage.file_exists():
raise Exception("Remove the existing wallet first!")
text = text.strip()
... | segwit else 'standard'
seed = Mnemonic('en').make_seed(seed_type)
k = keystore.from_seed(seed, passphrase)
storage.put('keystore', k.dump())
storage.put('wallet_type', 'standard')
wallet = Wallet(storage)
wallet.update_password(old_pw=None, new_pw=password, encrypt_storage=encrypt_file)
wal... | 153 | 153 | 510 | 23 | 130 | zumbrunn/electrumfair | electrum/wallet.py | Python | restore_wallet_from_text | restore_wallet_from_text | 1,871 | 1,923 | 1,871 | 1,871 | eb84807acc9e3a881fa613be89e938d802430f0c | bigcode/the-stack | train |
f2d09e2d0dc46d6df812aa75 | train | function | def make_xml(num_fields):
return ''.join((
HEADER.format(num_fields),
FIELD0, ''.join(FIELDS.format(i) for i in range(1, num_fields)),
''.join(VALUES.format(i) for i in range(num_fields)),
''.join(CHECKS.format(i) for i in range(num_fields)),
FOOTER
))
| def make_xml(num_fields):
| return ''.join((
HEADER.format(num_fields),
FIELD0, ''.join(FIELDS.format(i) for i in range(1, num_fields)),
''.join(VALUES.format(i) for i in range(num_fields)),
''.join(CHECKS.format(i) for i in range(num_fields)),
FOOTER
))
| struct/record like variable.
Attribute/field names can be specified in the tab 'Fields'.
For each non-empty field a parameter with type raw is shown.
Value access via the dot operator, e.g. "variable_struct_0.field0"
</doc>
</block>
"""
def make_xml(num_fields):
| 64 | 64 | 76 | 6 | 58 | v1259397/cosmic-gnuradio | gnuradio-3.7.13.4/grc/blocks/variable_struct.xml.py | Python | make_xml | make_xml | 77 | 84 | 77 | 77 | 37e3b608783262c198f78383ba38182c0dcdfd16 | bigcode/the-stack | train |
6366962d2623cd3ad4cc76de | train | class | class Features( ml_pipeline.ML_Features.Features ):
OVERRIDE_KWARGS = {
}
def __init__( self, Input_File_inst, **supplemental_kwargs ):
kwargs = ps.merge_dicts( Features.OVERRIDE_KWARGS, supplemental_kwargs )
ml_pipeline.ML_Features.Features.__init__( self, Input_File_inst, **kwargs )
| class Features( ml_pipeline.ML_Features.Features ):
| OVERRIDE_KWARGS = {
}
def __init__( self, Input_File_inst, **supplemental_kwargs ):
kwargs = ps.merge_dicts( Features.OVERRIDE_KWARGS, supplemental_kwargs )
ml_pipeline.ML_Features.Features.__init__( self, Input_File_inst, **kwargs )
| ### import from ml_pipeline
import ml_pipeline
import py_starter as ps
class Features( ml_pipeline.ML_Features.Features ):
| 29 | 64 | 80 | 12 | 16 | jameskabbes/ml_pipeline | src/ml_pipeline/Templates/main_class_templates/Features.py | Python | Features | Features | 6 | 14 | 6 | 7 | 097bbb2719c2d24a3b8d4150db32564c90b404ed | bigcode/the-stack | train |
776cf14d1f26d7f698aff912 | train | function | @pytest.mark.version('>=2.5.2')
def test_1(act_1: Action):
act_1.expected_stdout = expected_stdout_1
act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_expected_stderr == act_1.clean_stderr
assert act_1.clean_expected_stdout == act_1.clean_stdout
| @pytest.mark.version('>=2.5.2')
def test_1(act_1: Action):
| act_1.expected_stdout = expected_stdout_1
act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_expected_stderr == act_1.clean_stderr
assert act_1.clean_expected_stdout == act_1.clean_stdout
| = 1)
Statement : update test set f01 = ? where id = ?
Data source : Firebird::localhost:
-At block line: 3, col: 9
"""
@pytest.mark.version('>=2.5.2')
def test_1(act_1: Action):
| 64 | 64 | 85 | 21 | 43 | reevespaul/firebird-qa | tests/bugs/core_3610_test.py | Python | test_1 | test_1 | 92 | 98 | 92 | 93 | e13ffdab412ef0cf18db419a6fee925fe2494c86 | bigcode/the-stack | train |
082976af08ef20773208fc97 | train | class | class TestNetUtilsTestCase(test.NoDBTestCase):
def test_get_cached_vifs_with_vlan_no_nw_info(self):
# Make sure that an empty dictionary will be returned when
# nw_info is None
self.assertEqual({}, netutils.get_cached_vifs_with_vlan(None))
def test_get_cached_vifs_with_vlan_with_no_vlan... | class TestNetUtilsTestCase(test.NoDBTestCase):
| def test_get_cached_vifs_with_vlan_no_nw_info(self):
# Make sure that an empty dictionary will be returned when
# nw_info is None
self.assertEqual({}, netutils.get_cached_vifs_with_vlan(None))
def test_get_cached_vifs_with_vlan_with_no_vlan_details(self):
network_info = fake_net... | , software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.network import model as network_model
fr... | 98 | 98 | 328 | 12 | 85 | zjzh/nova | nova/tests/unit/virt/test_netutils.py | Python | TestNetUtilsTestCase | TestNetUtilsTestCase | 19 | 41 | 19 | 19 | c1bd74fdb67939de859335291aac8625ac63c4b2 | bigcode/the-stack | train |
5324f6383a23f3ff29191ea0 | train | class | class TestEquals:
def test_dataframe_not_equal(self):
# see GH#28839
df1 = DataFrame({"a": [1, 2], "b": ["s", "d"]})
df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})
assert df1.equals(df2) is False
def test_equals_different_blocks(self):
# GH#9330
df0 = DataFrame(... | class TestEquals:
| def test_dataframe_not_equal(self):
# see GH#28839
df1 = DataFrame({"a": [1, 2], "b": ["s", "d"]})
df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})
assert df1.equals(df2) is False
def test_equals_different_blocks(self):
# GH#9330
df0 = DataFrame({"A": ["x", "y"], ... | import numpy as np
from pandas import DataFrame, date_range
import pandas._testing as tm
class TestEquals:
| 25 | 223 | 744 | 4 | 20 | CJL89/pandas | pandas/tests/frame/methods/test_equals.py | Python | TestEquals | TestEquals | 7 | 78 | 7 | 7 | 797ac581a5ef65a4c761244d9c28d8ad40e86620 | bigcode/the-stack | train |
74b92cda8da51c2c0905ef56 | train | class | class TCN(layers.Layer):
"""
The TCN-layer consisting of TCN-residual-blocks.
The dilation-rate grows exponentially with each residual block.
:param filters: number of conv filters per residual block
:param kernel_size: size of the conv kernels
:param return_sequence: flag if the last sequence ... | class TCN(layers.Layer):
| """
The TCN-layer consisting of TCN-residual-blocks.
The dilation-rate grows exponentially with each residual block.
:param filters: number of conv filters per residual block
:param kernel_size: size of the conv kernels
:param return_sequence: flag if the last sequence should be returned or onl... | (inputs)
x = self.causal_conv_1(inputs)
x = self.weight_norm_1(x)
x = self.activation_1(x)
x = self.dropout_1(x, training=training)
x = self.causal_conv_2(x)
x = self.weight_norm_2(x)
x = self.activation_2(x)
x = self.dropout_2(x, training=training)
... | 110 | 110 | 367 | 7 | 102 | 1044197988/TF.Keras-Commonly-used-models | Others/tcn.py | Python | TCN | TCN | 82 | 133 | 82 | 82 | 128f6bad66388e58a4bff9a2159229ff7a0a6189 | bigcode/the-stack | train |
de8f6424921416c80ec91a68 | train | function | def build_model(sequence_length: int,
channels: int,
filters: List[int],
num_classes:int,
kernel_size: int,
return_sequence:bool = False):
"""
Builds a simple TCN model for a classification task
:param sequence_length: lenght o... | def build_model(sequence_length: int,
channels: int,
filters: List[int],
num_classes:int,
kernel_size: int,
return_sequence:bool = False):
| """
Builds a simple TCN model for a classification task
:param sequence_length: lenght of the input sequence
:param channels: number of channels of the input sequence
:param filters: number of conv filters per residual block
:param num_classes: number of output classes
:param kernel_size: s... | .depth)
def receptive_field_size(kernel_size, depth):
return 1 + 2 * (kernel_size - 1) * (2 ** depth - 1)
def build_model(sequence_length: int,
channels: int,
filters: List[int],
num_classes:int,
kernel_size: int,
return_sequence:bool... | 73 | 73 | 245 | 38 | 35 | 1044197988/TF.Keras-Commonly-used-models | Others/tcn.py | Python | build_model | build_model | 140 | 170 | 140 | 145 | 95b3151ae75d6fcacba6eefa0ebf199e4c7b8b60 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.