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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5efd45e81677301a082bb9f7 | train | function | def reorder_items_atscope(
items: Dict[nodes.Item, None],
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
scope: Scope,
) -> Dict[nodes.Item, None]:
if scope is Scope.Function or len(items) < 3:
return items
i... | def reorder_items_atscope(
items: Dict[nodes.Item, None],
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
scope: Scope,
) -> Dict[nodes.Item, None]:
| if scope is Scope.Function or len(items) < 3:
return items
ignore: Set[Optional[_Key]] = set()
items_deque = deque(items)
items_done: Dict[nodes.Item, None] = {}
scoped_items_by_argkey = items_by_argkey[scope]
scoped_argkeys_cache = argkeys_cache[scope]
while items_deque:
no_... | Scope, Dict[_Key, "Deque[nodes.Item]"]],
) -> None:
for scope in HIGH_SCOPES:
for key in argkeys_cache[scope].get(item, []):
items_by_argkey[scope][key].appendleft(item)
def reorder_items_atscope(
items: Dict[nodes.Item, None],
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]... | 128 | 128 | 428 | 73 | 55 | sgaist/pytest | src/_pytest/fixtures.py | Python | reorder_items_atscope | reorder_items_atscope | 311 | 354 | 311 | 316 | 74e74bba880f32ed060057a7fbd6bd09b600c756 | bigcode/the-stack | train |
9b832bdf913ba795ff165193 | train | function | def get_direct_param_fixture_func(request):
return request.param
| def get_direct_param_fixture_func(request):
| return request.param
| fm.session._setupstate.setup(function)
request._fillfixtures()
# Prune out funcargs for jstests.
function.funcargs = {name: function.funcargs[name] for name in fi.argnames}
else:
request._fillfixtures()
def get_direct_param_fixture_func(request):
| 64 | 64 | 13 | 8 | 56 | sgaist/pytest | src/_pytest/fixtures.py | Python | get_direct_param_fixture_func | get_direct_param_fixture_func | 392 | 393 | 392 | 392 | f34b361d7ff50a88cbd6b63b66e30e50c0505a57 | bigcode/the-stack | train |
a4032acb54d39e56680ef3e0 | train | function | def get_scope_node(
node: nodes.Node, scope: Scope
) -> Optional[Union[nodes.Item, nodes.Collector]]:
import _pytest.python
if scope is Scope.Function:
return node.getparent(nodes.Item)
elif scope is Scope.Class:
return node.getparent(_pytest.python.Class)
elif scope is Scope.Module... | def get_scope_node(
node: nodes.Node, scope: Scope
) -> Optional[Union[nodes.Item, nodes.Collector]]:
| import _pytest.python
if scope is Scope.Function:
return node.getparent(nodes.Item)
elif scope is Scope.Class:
return node.getparent(_pytest.python.Class)
elif scope is Scope.Module:
return node.getparent(_pytest.python.Module)
elif scope is Scope.Package:
return nod... | ) is not cls or fixture_package_name != current.nodeid
):
current = current.parent
if current is None:
return node.session
return current
def get_scope_node(
node: nodes.Node, scope: Scope
) -> Optional[Union[nodes.Item, nodes.Collector]]:
| 64 | 64 | 126 | 28 | 35 | sgaist/pytest | src/_pytest/fixtures.py | Python | get_scope_node | get_scope_node | 134 | 150 | 134 | 136 | 7fe0677107405e9725ab19c91b81a8ed880b961e | bigcode/the-stack | train |
f04342f7dc7d58293aefbd91 | train | function | def fix_cache_order(
item: nodes.Item,
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
) -> None:
for scope in HIGH_SCOPES:
for key in argkeys_cache[scope].get(item, []):
items_by_argkey[scope][key].append... | def fix_cache_order(
item: nodes.Item,
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
) -> None:
| for scope in HIGH_SCOPES:
for key in argkeys_cache[scope].get(item, []):
items_by_argkey[scope][key].appendleft(item)
| key, Scope.Session)
)
def fix_cache_order(
item: nodes.Item,
argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[_Key, None]]],
items_by_argkey: Dict[Scope, Dict[_Key, "Deque[nodes.Item]"]],
) -> None:
| 64 | 64 | 95 | 57 | 7 | sgaist/pytest | src/_pytest/fixtures.py | Python | fix_cache_order | fix_cache_order | 301 | 308 | 301 | 305 | 7f4331021033163eb2854250d68e3a6cac81358a | bigcode/the-stack | train |
5711ed6fe7a42873b9f660b6 | train | function | def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
fs, lineno = getfslineno(fixturefunc)
location = f"{fs}:{lineno + 1}"
source = _pytest._code.Source(fixturefunc)
fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
| def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
| fs, lineno = getfslineno(fixturefunc)
location = f"{fs}:{lineno + 1}"
source = _pytest._code.Source(fixturefunc)
fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
| "{FormattedExcinfo.flow_marker} {line.strip()}",
red=True,
)
tw.line()
tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))
def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
| 64 | 64 | 82 | 17 | 47 | sgaist/pytest | src/_pytest/fixtures.py | Python | fail_fixturefunc | fail_fixturefunc | 908 | 912 | 908 | 908 | 6bc9b9cdea523a561a4786b5948b5246ac7fb2ae | bigcode/the-stack | train |
97e9af206a0ea0fb3ea04958 | train | class | @attr.s(slots=True)
class FuncFixtureInfo:
# Original function argument names.
argnames = attr.ib(type=Tuple[str, ...])
# Argnames that function immediately requires. These include argnames +
# fixture names specified via usefixtures and via autouse=True in fixture
# definitions.
initialnames = ... | @attr.s(slots=True)
class FuncFixtureInfo:
# Original function argument names.
| argnames = attr.ib(type=Tuple[str, ...])
# Argnames that function immediately requires. These include argnames +
# fixture names specified via usefixtures and via autouse=True in fixture
# definitions.
initialnames = attr.ib(type=Tuple[str, ...])
names_closure = attr.ib(type=List[str])
name2... | , function.obj, None)
function._fixtureinfo = fi
request = function._request = FixtureRequest(function, _ispytest=True)
fm.session._setupstate.setup(function)
request._fillfixtures()
# Prune out funcargs for jstests.
function.funcargs = {name: function.funcargs[name] for ... | 118 | 118 | 396 | 19 | 98 | sgaist/pytest | src/_pytest/fixtures.py | Python | FuncFixtureInfo | FuncFixtureInfo | 396 | 432 | 396 | 398 | b33d596e804d7d5a38e223641bee8006d0b1f08c | bigcode/the-stack | train |
13d514af1e43dc51d7c4e067 | train | function | def resolve_fixture_function(
fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
) -> "_FixtureFunc[FixtureValue]":
"""Get the actual callable that can be called to obtain the fixture
value, dealing with unittest-specific instances and bound methods."""
fixturefunc = fixturedef.func
if fi... | def resolve_fixture_function(
fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
) -> "_FixtureFunc[FixtureValue]":
| """Get the actual callable that can be called to obtain the fixture
value, dealing with unittest-specific instances and bound methods."""
fixturefunc = fixturedef.func
if fixturedef.unittest:
if request.instance is not None:
# Bind the unbound method to the TestCase instance.
... | hasattr(request, "param") else request.param
def __repr__(self) -> str:
return "<FixtureDef argname={!r} scope={!r} baseid={!r}>".format(
self.argname, self.scope, self.baseid
)
def resolve_fixture_function(
fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
) -> "_Fixtu... | 86 | 86 | 288 | 30 | 56 | sgaist/pytest | src/_pytest/fixtures.py | Python | resolve_fixture_function | resolve_fixture_function | 1,087 | 1,111 | 1,087 | 1,089 | eadc1788c0d44b45855937096d07b9d6f529be34 | bigcode/the-stack | train |
7776e4ff800862e43727bf17 | train | function | def wrap_function_to_error_out_if_called_directly(
function: FixtureFunction,
fixture_marker: "FixtureFunctionMarker",
) -> FixtureFunction:
"""Wrap the given fixture function so we can raise an error about it being called directly,
instead of used as an argument in a test function."""
message = (
... | def wrap_function_to_error_out_if_called_directly(
function: FixtureFunction,
fixture_marker: "FixtureFunctionMarker",
) -> FixtureFunction:
| """Wrap the given fixture function so we can raise an error about it being called directly,
instead of used as an argument in a test function."""
message = (
'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n'
"but are created automatically when test functions... | ):
return ids
return tuple(ids)
def _params_converter(
params: Optional[Iterable[object]],
) -> Optional[Tuple[object, ...]]:
return tuple(params) if params is not None else None
def wrap_function_to_error_out_if_called_directly(
function: FixtureFunction,
fixture_marker: "FixtureFunctionM... | 78 | 78 | 263 | 31 | 46 | sgaist/pytest | src/_pytest/fixtures.py | Python | wrap_function_to_error_out_if_called_directly | wrap_function_to_error_out_if_called_directly | 1,165 | 1,186 | 1,165 | 1,168 | 404d23cfff8dd29f71c7def6dc7a4feb74c0b57b | bigcode/the-stack | train |
18a770add92223b442c57650 | train | function | @overload
def fixture(
fixture_function: FixtureFunction,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
C... | @overload
def fixture(
fixture_function: FixtureFunction,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
C... | ...
| @overload
def fixture(
fixture_function: FixtureFunction,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
C... | 112 | 64 | 114 | 112 | 0 | sgaist/pytest | src/_pytest/fixtures.py | Python | fixture | fixture | 1,230 | 1,245 | 1,230 | 1,244 | eb1354e2d9b8ab9ba89610a2a98d0f5d193ea0af | bigcode/the-stack | train |
37dd95c8ebebde71e32b334e | train | class | @final
@attr.s(frozen=True)
class FixtureFunctionMarker:
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = attr.ib()
params: Optional[Tuple[object, ...]] = attr.ib(converter=_params_converter)
autouse: bool = attr.ib(default=False)
ids: Union[
Tuple[Union[None, str, float, int, b... | @final
@attr.s(frozen=True)
class FixtureFunctionMarker:
| scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = attr.ib()
params: Optional[Tuple[object, ...]] = attr.ib(converter=_params_converter)
autouse: bool = attr.ib(default=False)
ids: Union[
Tuple[Union[None, str, float, int, bool], ...],
Callable[[Any], Optional[object]],
... | , **kwargs):
fail(message, pytrace=False)
# Keep reference to the original function in our own custom attribute so we don't unwrap
# further than this point and lose useful wrappings like @mock.patch (#3774).
result.__pytest_wrapped__ = _PytestWrapper(function) # type: ignore[attr-defined]
re... | 95 | 95 | 317 | 15 | 80 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureFunctionMarker | FixtureFunctionMarker | 1,189 | 1,227 | 1,189 | 1,191 | 56da36a3b5107fafe13cbdb9f7fb78101f327a6f | bigcode/the-stack | train |
3f4416f452faa37ff850eacf | train | class | @final
class FixtureDef(Generic[FixtureValue]):
"""A container for a factory definition."""
def __init__(
self,
fixturemanager: "FixtureManager",
baseid: Optional[str],
argname: str,
func: "_FixtureFunc[FixtureValue]",
scope: Union[Scope, "_ScopeName", Callable[[... | @final
class FixtureDef(Generic[FixtureValue]):
| """A container for a factory definition."""
def __init__(
self,
fixturemanager: "FixtureManager",
baseid: Optional[str],
argname: str,
func: "_FixtureFunc[FixtureValue]",
scope: Union[Scope, "_ScopeName", Callable[[str, Config], "_ScopeName"], None],
para... | more than one yield in the function)."""
try:
next(it)
except StopIteration:
pass
else:
fail_fixturefunc(fixturefunc, "fixture function has more than one 'yield'")
def _eval_scope_callable(
scope_callable: "Callable[[str, Config], _ScopeName]",
fixture_name: str,
confi... | 256 | 256 | 965 | 11 | 244 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureDef | FixtureDef | 972 | 1,084 | 972 | 973 | 74f65d983f5c5a58f4b691fda3284a99ae9ca0af | bigcode/the-stack | train |
b395d3d40386be438f1c511c | train | function | def get_parametrized_fixture_keys(item: nodes.Item, scope: Scope) -> Iterator[_Key]:
"""Return list of keys for all parametrized arguments which match
the specified scope."""
assert scope is not Scope.Function
try:
callspec = item.callspec # type: ignore[attr-defined]
except AttributeError:... | def get_parametrized_fixture_keys(item: nodes.Item, scope: Scope) -> Iterator[_Key]:
| """Return list of keys for all parametrized arguments which match
the specified scope."""
assert scope is not Scope.Function
try:
callspec = item.callspec # type: ignore[attr-defined]
except AttributeError:
pass
else:
cs: CallSpec2 = callspec
# cs.indices.items()... | _OUTCOME:
# some objects raise errors like request (from flask import request)
# we don't expect them to be fixture functions
return None
return fixturemarker
# Parametrized fixture key, helper alias for code below.
_Key = Tuple[object, ...]
def get_parametrized_fixture_keys(item: nodes.It... | 79 | 79 | 266 | 21 | 58 | sgaist/pytest | src/_pytest/fixtures.py | Python | get_parametrized_fixture_keys | get_parametrized_fixture_keys | 245 | 272 | 245 | 245 | cf3c7409e05d2c1c2150b86fe97e03dec23c5059 | bigcode/the-stack | train |
60655bca80ca59146908393d | train | function | def get_scope_package(node, fixturedef: "FixtureDef[object]"):
import pytest
cls = pytest.Package
current = node
fixture_package_name = "{}/{}".format(fixturedef.baseid, "__init__.py")
while current and (
type(current) is not cls or fixture_package_name != current.nodeid
):
curr... | def get_scope_package(node, fixturedef: "FixtureDef[object]"):
| import pytest
cls = pytest.Package
current = node
fixture_package_name = "{}/{}".format(fixturedef.baseid, "__init__.py")
while current and (
type(current) is not cls or fixture_package_name != current.nodeid
):
current = current.parent
if current is None:
return nod... | seudoFixtureDef(Generic[FixtureValue]):
cached_result: "_FixtureCachedResult[FixtureValue]"
_scope: Scope
def pytest_sessionstart(session: "Session") -> None:
session._fixturemanager = FixtureManager(session)
def get_scope_package(node, fixturedef: "FixtureDef[object]"):
| 64 | 64 | 95 | 16 | 48 | sgaist/pytest | src/_pytest/fixtures.py | Python | get_scope_package | get_scope_package | 119 | 131 | 119 | 119 | 5486ccb98904910d39ee7bdbf8c54b28135bc7cd | bigcode/the-stack | train |
299b7a0ed2d772b3bf0dab07 | train | function | def pytest_addoption(parser: Parser) -> None:
parser.addini(
"usefixtures",
type="args",
default=[],
help="list of default fixtures to be used with this project",
)
| def pytest_addoption(parser: Parser) -> None:
| parser.addini(
"usefixtures",
type="args",
default=[],
help="list of default fixtures to be used with this project",
)
| """Session-scoped fixture that returns the session's :class:`pytest.Config`
object.
Example::
def test_foo(pytestconfig):
if pytestconfig.getoption("verbose") > 0:
...
"""
return request.config
def pytest_addoption(parser: Parser) -> None:
| 64 | 64 | 46 | 11 | 52 | sgaist/pytest | src/_pytest/fixtures.py | Python | pytest_addoption | pytest_addoption | 1,386 | 1,392 | 1,386 | 1,386 | 337b3dc5e06c5b3b90c8d702a3a54f1a11452456 | bigcode/the-stack | train |
5e2e2a7af67483b148e22010 | train | class | class FixtureLookupErrorRepr(TerminalRepr):
def __init__(
self,
filename: Union[str, "os.PathLike[str]"],
firstlineno: int,
tblines: Sequence[str],
errorstring: str,
argname: Optional[str],
) -> None:
self.tblines = tblines
self.errorstring = error... | class FixtureLookupErrorRepr(TerminalRepr):
| def __init__(
self,
filename: Union[str, "os.PathLike[str]"],
firstlineno: int,
tblines: Sequence[str],
errorstring: str,
argname: Optional[str],
) -> None:
self.tblines = tblines
self.errorstring = errorstring
self.filename = filename
... | self.argname}' not found"
msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
msg += "\n use 'pytest --fixtures [testpath]' for help on them."
return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
class FixtureLookupErrorRepr(TerminalRepr):
| 77 | 77 | 259 | 12 | 65 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureLookupErrorRepr | FixtureLookupErrorRepr | 874 | 905 | 874 | 874 | 954382bfe3cbf1326c74a5713757e1107700e37d | bigcode/the-stack | train |
f9bace22da2ccb9e778a0bc4 | train | class | @final
class FixtureLookupError(LookupError):
"""Could not return a requested fixture (missing or invalid)."""
def __init__(
self, argname: Optional[str], request: FixtureRequest, msg: Optional[str] = None
) -> None:
self.argname = argname
self.request = request
self.fixture... | @final
class FixtureLookupError(LookupError):
| """Could not return a requested fixture (missing or invalid)."""
def __init__(
self, argname: Optional[str], request: FixtureRequest, msg: Optional[str] = None
) -> None:
self.argname = argname
self.request = request
self.fixturestack = request._get_fixturestack()
se... | within the requesting test context finished execution."""
self._fixturedef.addfinalizer(finalizer)
def _schedule_finalizers(
self, fixturedef: "FixtureDef[object]", subrequest: "SubRequest"
) -> None:
# If the executing fixturedef was not explicitly requested in the argument list (via
... | 152 | 152 | 508 | 12 | 140 | sgaist/pytest | src/_pytest/fixtures.py | Python | FixtureLookupError | FixtureLookupError | 817 | 871 | 817 | 818 | f45e2439d74fec3e134cdec338e4fe5311da5859 | bigcode/the-stack | train |
f8a75b1544af7a56e34bd51f | train | function | def _fill_fixtures_impl(function: "Function") -> None:
"""Internal implementation to fill fixtures on the given function object."""
try:
request = function._request
except AttributeError:
# XXX this special code path is only expected to execute
# with the oejskit plugin. It uses cla... | def _fill_fixtures_impl(function: "Function") -> None:
| """Internal implementation to fill fixtures on the given function object."""
try:
request = function._request
except AttributeError:
# XXX this special code path is only expected to execute
# with the oejskit plugin. It uses classes with funcargs
# and we thus have to work a... | :
"""Fill missing fixtures for a test function (deprecated)."""
warnings.warn(
FILLFUNCARGS.format(name="_pytest.fixtures.fillfixtures()"), stacklevel=2
)
_fill_fixtures_impl(function)
def _fill_fixtures_impl(function: "Function") -> None:
| 64 | 64 | 200 | 15 | 49 | sgaist/pytest | src/_pytest/fixtures.py | Python | _fill_fixtures_impl | _fill_fixtures_impl | 371 | 389 | 371 | 371 | b22bb95696c061c139239af36748f2c524bbc7fc | bigcode/the-stack | train |
215b506e12cf16246b90d7a4 | train | function | def _fillfuncargs(function: "Function") -> None:
"""Fill missing fixtures for a test function, old public API (deprecated)."""
warnings.warn(FILLFUNCARGS.format(name="pytest._fillfuncargs()"), stacklevel=2)
_fill_fixtures_impl(function)
| def _fillfuncargs(function: "Function") -> None:
| """Fill missing fixtures for a test function, old public API (deprecated)."""
warnings.warn(FILLFUNCARGS.format(name="pytest._fillfuncargs()"), stacklevel=2)
_fill_fixtures_impl(function)
| no_argkey_group, argkeys_cache, items_by_argkey, scope.next_lower()
)
for item in no_argkey_group:
items_done[item] = None
ignore.add(slicing_argkey)
return items_done
def _fillfuncargs(function: "Function") -> None:
| 64 | 64 | 61 | 13 | 50 | sgaist/pytest | src/_pytest/fixtures.py | Python | _fillfuncargs | _fillfuncargs | 357 | 360 | 357 | 357 | cdac360b848d635d6d341fe60862ea86b9b12951 | bigcode/the-stack | train |
5ac166ee37e92092a9a248b3 | train | function | @fixture(scope="session")
def pytestconfig(request: FixtureRequest) -> Config:
"""Session-scoped fixture that returns the session's :class:`pytest.Config`
object.
Example::
def test_foo(pytestconfig):
if pytestconfig.getoption("verbose") > 0:
...
"""
return req... | @fixture(scope="session")
def pytestconfig(request: FixtureRequest) -> Config:
| """Session-scoped fixture that returns the session's :class:`pytest.Config`
object.
Example::
def test_foo(pytestconfig):
if pytestconfig.getoption("verbose") > 0:
...
"""
return request.config
| _FIXTURE, stacklevel=2)
return fixture(
fixture_function,
*args,
scope=scope,
params=params,
autouse=autouse,
ids=ids,
name=name,
)
@fixture(scope="session")
def pytestconfig(request: FixtureRequest) -> Config:
| 64 | 64 | 71 | 17 | 47 | sgaist/pytest | src/_pytest/fixtures.py | Python | pytestconfig | pytestconfig | 1,371 | 1,383 | 1,371 | 1,372 | 5793aa7541e91c452cd35a31595069cc96ff02f7 | bigcode/the-stack | train |
4150e6e70b6c122b03f72b37 | train | function | def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
"""Return fixturemarker or None if it doesn't exist or raised
exceptions."""
try:
fixturemarker: Optional[FixtureFunctionMarker] = getattr(
obj, "_pytestfixturefunction", None
)
except TEST_OUTCOME:
... | def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
| """Return fixturemarker or None if it doesn't exist or raised
exceptions."""
try:
fixturemarker: Optional[FixtureFunctionMarker] = getattr(
obj, "_pytestfixturefunction", None
)
except TEST_OUTCOME:
# some objects raise errors like request (from flask import request)
... | =False,
ids=None,
)
arg2fixturedefs[argname] = [fixturedef]
if name2pseudofixturedef is not None:
name2pseudofixturedef[argname] = fixturedef
def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
| 64 | 64 | 100 | 15 | 48 | sgaist/pytest | src/_pytest/fixtures.py | Python | getfixturemarker | getfixturemarker | 227 | 238 | 227 | 227 | 7036533bdc4ea36e9da71ba7d346420caa10b4a6 | bigcode/the-stack | train |
f8cfbc808fa74c619449fa8e | train | class | @final
class SubRequest(FixtureRequest):
"""A sub request for handling getting a fixture from a test function/fixture."""
def __init__(
self,
request: "FixtureRequest",
scope: Scope,
param: Any,
param_index: int,
fixturedef: "FixtureDef[object]",
*,
... | @final
class SubRequest(FixtureRequest):
| """A sub request for handling getting a fixture from a test function/fixture."""
def __init__(
self,
request: "FixtureRequest",
scope: Scope,
param: Any,
param_index: int,
fixturedef: "FixtureDef[object]",
*,
_ispytest: bool = False,
) -> None... | fixturedef) # type: ignore[attr-defined]
else:
node = get_scope_node(self._pyfuncitem, scope)
if node is None and scope is Scope.Class:
# Fallback to function item itself.
node = self._pyfuncitem
assert node, 'Could not obtain a node for scope "{}" for functi... | 127 | 127 | 425 | 10 | 117 | sgaist/pytest | src/_pytest/fixtures.py | Python | SubRequest | SubRequest | 768 | 814 | 768 | 769 | 0c1093fe96c914437cda9a88849d64be7ac115b0 | bigcode/the-stack | train |
b16187a61be41779615cb84c | train | function | def add_funcarg_pseudo_fixture_def(
collector: nodes.Collector, metafunc: "Metafunc", fixturemanager: "FixtureManager"
) -> None:
# This function will transform all collected calls to functions
# if they use direct funcargs (i.e. direct parametrization)
# because we want later test execution to be able ... | def add_funcarg_pseudo_fixture_def(
collector: nodes.Collector, metafunc: "Metafunc", fixturemanager: "FixtureManager"
) -> None:
# This function will transform all collected calls to functions
# if they use direct funcargs (i.e. direct parametrization)
# because we want later test execution to be able ... | if not metafunc._calls[0].funcargs:
# This function call does not have direct parametrization.
return
# Collect funcargs of all callspecs into a list of values.
arg2params: Dict[str, List[object]] = {}
arg2scope: Dict[str, Scope] = {}
for callspec in metafunc._calls:
for argn... | elif scope is Scope.Module:
return node.getparent(_pytest.python.Module)
elif scope is Scope.Package:
return node.getparent(_pytest.python.Package)
elif scope is Scope.Session:
return node.getparent(_pytest.main.Session)
else:
assert_never(scope)
# Used for storing arti... | 215 | 215 | 717 | 120 | 95 | sgaist/pytest | src/_pytest/fixtures.py | Python | add_funcarg_pseudo_fixture_def | add_funcarg_pseudo_fixture_def | 157 | 224 | 157 | 165 | 809e8032fc36687a5dc28c7504f3ddd1b94bde9d | bigcode/the-stack | train |
f17f8790d368fecaadf51acf | train | function | def fillfixtures(function: "Function") -> None:
"""Fill missing fixtures for a test function (deprecated)."""
warnings.warn(
FILLFUNCARGS.format(name="_pytest.fixtures.fillfixtures()"), stacklevel=2
)
_fill_fixtures_impl(function)
| def fillfixtures(function: "Function") -> None:
| """Fill missing fixtures for a test function (deprecated)."""
warnings.warn(
FILLFUNCARGS.format(name="_pytest.fixtures.fillfixtures()"), stacklevel=2
)
_fill_fixtures_impl(function)
| Function") -> None:
"""Fill missing fixtures for a test function, old public API (deprecated)."""
warnings.warn(FILLFUNCARGS.format(name="pytest._fillfuncargs()"), stacklevel=2)
_fill_fixtures_impl(function)
def fillfixtures(function: "Function") -> None:
| 64 | 64 | 59 | 11 | 53 | sgaist/pytest | src/_pytest/fixtures.py | Python | fillfixtures | fillfixtures | 363 | 368 | 363 | 363 | b2460e0472c68779df9829ff11246c8b612d14d5 | bigcode/the-stack | train |
6290030cdd4388cf51ae6f57 | train | function | def _eval_scope_callable(
scope_callable: "Callable[[str, Config], _ScopeName]",
fixture_name: str,
config: Config,
) -> "_ScopeName":
try:
# Type ignored because there is no typing mechanism to specify
# keyword arguments, currently.
result = scope_callable(fixture_name=fixture_... | def _eval_scope_callable(
scope_callable: "Callable[[str, Config], _ScopeName]",
fixture_name: str,
config: Config,
) -> "_ScopeName":
| try:
# Type ignored because there is no typing mechanism to specify
# keyword arguments, currently.
result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
except Exception as e:
raise TypeError(
"Error evaluating {} while defining ... | :
pass
else:
fail_fixturefunc(fixturefunc, "fixture function has more than one 'yield'")
def _eval_scope_callable(
scope_callable: "Callable[[str, Config], _ScopeName]",
fixture_name: str,
config: Config,
) -> "_ScopeName":
| 63 | 64 | 199 | 38 | 26 | sgaist/pytest | src/_pytest/fixtures.py | Python | _eval_scope_callable | _eval_scope_callable | 947 | 969 | 947 | 951 | a1cc00cda2c4e6a661e2728bbe481b4e29c64836 | bigcode/the-stack | train |
0c37b7c5f090102087dbcb6d | train | function | def _ensure_immutable_ids(
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callable[[Any], Optional[object]],
]
],
) -> Optional[
Union[
Tuple[Union[None, str, float, int, bool], ...],
Callable[[Any], Optional[object]],
]
]:
... | def _ensure_immutable_ids(
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callable[[Any], Optional[object]],
]
],
) -> Optional[
Union[
Tuple[Union[None, str, float, int, bool], ...],
Callable[[Any], Optional[object]],
]
]:
| if ids is None:
return None
if callable(ids):
return ids
return tuple(ids)
| def _ensure_immutable_ids(
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callable[[Any], Optional[object]],
]
],
) -> Optional[
Union[
Tuple[Union[None, str, float, int, bool], ...],
Callable[[Any], Optional[object]],
]
]:
| 79 | 64 | 103 | 79 | 0 | sgaist/pytest | src/_pytest/fixtures.py | Python | _ensure_immutable_ids | _ensure_immutable_ids | 1,139 | 1,156 | 1,139 | 1,151 | 1f553687a5406987cffe466f3c2d25e13c1593a6 | bigcode/the-stack | train |
3570856276eee67c0f8f42e8 | train | function | @overload
def fixture(
fixture_function: None = ...,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callab... | @overload
def fixture(
fixture_function: None = ...,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callab... | ...
| @overload
def fixture(
fixture_function: None = ...,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callab... | 114 | 64 | 116 | 114 | 0 | sgaist/pytest | src/_pytest/fixtures.py | Python | fixture | fixture | 1,248 | 1,263 | 1,248 | 1,262 | 2e0634c9142680437cb8355fc473af32509faf51 | bigcode/the-stack | train |
50dd70cf735b3e7757177cda | train | function | def call_fixture_func(
fixturefunc: "_FixtureFunc[FixtureValue]", request: FixtureRequest, kwargs
) -> FixtureValue:
if is_generator(fixturefunc):
fixturefunc = cast(
Callable[..., Generator[FixtureValue, None, None]], fixturefunc
)
generator = fixturefunc(**kwargs)
t... | def call_fixture_func(
fixturefunc: "_FixtureFunc[FixtureValue]", request: FixtureRequest, kwargs
) -> FixtureValue:
| if is_generator(fixturefunc):
fixturefunc = cast(
Callable[..., Generator[FixtureValue, None, None]], fixturefunc
)
generator = fixturefunc(**kwargs)
try:
fixture_result = next(generator)
except StopIteration:
raise ValueError(f"{request.fi... | = _pytest._code.Source(fixturefunc)
fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
def call_fixture_func(
fixturefunc: "_FixtureFunc[FixtureValue]", request: FixtureRequest, kwargs
) -> FixtureValue:
| 64 | 64 | 160 | 28 | 36 | sgaist/pytest | src/_pytest/fixtures.py | Python | call_fixture_func | call_fixture_func | 915 | 932 | 915 | 917 | 550cfca6fa603ec1002712dcfecba6b720735096 | bigcode/the-stack | train |
44d793ad47e230b6bfc2c0a8 | train | function | def _teardown_yield_fixture(fixturefunc, it) -> None:
"""Execute the teardown of a fixture function by advancing the iterator
after the yield and ensure the iteration ends (if not it means there is
more than one yield in the function)."""
try:
next(it)
except StopIteration:
pass
... | def _teardown_yield_fixture(fixturefunc, it) -> None:
| """Execute the teardown of a fixture function by advancing the iterator
after the yield and ensure the iteration ends (if not it means there is
more than one yield in the function)."""
try:
next(it)
except StopIteration:
pass
else:
fail_fixturefunc(fixturefunc, "fixture f... | _yield_fixture, fixturefunc, generator)
request.addfinalizer(finalizer)
else:
fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)
fixture_result = fixturefunc(**kwargs)
return fixture_result
def _teardown_yield_fixture(fixturefunc, it) -> None:
| 64 | 64 | 93 | 16 | 47 | sgaist/pytest | src/_pytest/fixtures.py | Python | _teardown_yield_fixture | _teardown_yield_fixture | 935 | 944 | 935 | 935 | 509c228fdd92e16dd67cdaafcfe213beb8166802 | bigcode/the-stack | train |
19447889f1d8b25ffe91511f | train | function | def fixture(
fixture_function: Optional[FixtureFunction] = None,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
params: Optional[Iterable[object]] = None,
autouse: bool = False,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool... | def fixture(
fixture_function: Optional[FixtureFunction] = None,
*,
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
params: Optional[Iterable[object]] = None,
autouse: bool = False,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool... | """Decorator to mark a fixture factory function.
This decorator can be used, with or without parameters, to define a
fixture function.
The name of the fixture function can later be referenced to cause its
invocation ahead of running tests: test modules or classes can use the
``pytest.mark.usef... | ]]" = ...,
params: Optional[Iterable[object]] = ...,
autouse: bool = ...,
ids: Optional[
Union[
Iterable[Union[None, str, float, int, bool]],
Callable[[Any], Optional[object]],
]
] = ...,
name: Optional[str] = None,
) -> FixtureFunctionMarker:
...
def fixt... | 201 | 201 | 670 | 120 | 81 | sgaist/pytest | src/_pytest/fixtures.py | Python | fixture | fixture | 1,266 | 1,342 | 1,266 | 1,279 | 0f4a558e5cf9acca32d57454c84a7e4aed7c3a02 | bigcode/the-stack | train |
5299099e151fa66efbf65c16 | train | function | def recover_ray(x: int) -> list[int]:
ray = recover_ray11(x)
if 0 < x < 5:
return ray
return ray[2:]
| def recover_ray(x: int) -> list[int]:
| ray = recover_ray11(x)
if 0 < x < 5:
return ray
return ray[2:]
| ^ k
b = bcjk ^ c ^ j ^ k
a = acik ^ c ^ i ^ k
return [a, b, c, d, e, f, g, h, i, j, k]
def recover_ray(x: int) -> list[int]:
| 63 | 64 | 40 | 11 | 52 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | recover_ray | recover_ray | 101 | 105 | 101 | 101 | 2acd00e4cd0863c53714f3bc97244b50b69b3336 | bigcode/the-stack | train |
02660b30f06a720245fe5a81 | train | function | def option(n):
io.sendlineafter('>> ', str(n))
| def option(n):
| io.sendlineafter('>> ', str(n))
| from pwn import remote, context
from ast import literal_eval
from functools import reduce
from operator import xor
def option(n):
| 28 | 64 | 15 | 4 | 23 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | option | option | 6 | 7 | 6 | 6 | 6ff6ceec4b10b5be32f5434a7a8d9142060551b4 | bigcode/the-stack | train |
1a2e84f68371cdf6e22ce36c | train | function | def recover_ray11(indir: int) -> list:
for _ in range(5):
oracle(indir)
acik = oracle(indir)
bcjk = oracle(indir)
ck = oracle(indir)
defghijk = oracle(indir)
egik = oracle(indir)
fgjk = oracle(indir)
gk = oracle(indir)
hijk = oracle(indir)
ik = oracle(indir)
... | def recover_ray11(indir: int) -> list:
| for _ in range(5):
oracle(indir)
acik = oracle(indir)
bcjk = oracle(indir)
ck = oracle(indir)
defghijk = oracle(indir)
egik = oracle(indir)
fgjk = oracle(indir)
gk = oracle(indir)
hijk = oracle(indir)
ik = oracle(indir)
jk = oracle(indir)
k = oracle(... | i+1)][1]] = ray
else:
path = SHOOT_DIC[indir]
for x, y in path:
ray ^= self.state[x][y]
self.state[x][y] = ray
if verbose:
print(self.state)
return ray
def recover_ray11(indir: int) -> list:
| 74 | 74 | 247 | 12 | 61 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | recover_ray11 | recover_ray11 | 71 | 98 | 71 | 71 | c122befca5be63141c002d448b343c0f0fa13305 | bigcode/the-stack | train |
c9fb85b829469aa4afaf87a7 | train | function | def oracle(x: int) -> int:
option(1)
io.sendlineafter('>> ', str((x, 0)))
io.recvuntil('comes: ')
return int(io.recvline())
| def oracle(x: int) -> int:
| option(1)
io.sendlineafter('>> ', str((x, 0)))
io.recvuntil('comes: ')
return int(io.recvline())
| from pwn import remote, context
from ast import literal_eval
from functools import reduce
from operator import xor
def option(n):
io.sendlineafter('>> ', str(n))
def oracle(x: int) -> int:
| 48 | 64 | 44 | 9 | 39 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | oracle | oracle | 9 | 13 | 9 | 9 | 1a89e782e8f41cefa50177273ed07c8e77ba24b9 | bigcode/the-stack | train |
e24651e30fe1eefb006b964d | train | function | def read_tuple() -> tuple[int, int]:
return literal_eval(io.recvline(False)[1:].strip().decode())
| def read_tuple() -> tuple[int, int]:
| return literal_eval(io.recvline(False)[1:].strip().decode())
| .sendlineafter('>> ', str(n))
def oracle(x: int) -> int:
option(1)
io.sendlineafter('>> ', str((x, 0)))
io.recvuntil('comes: ')
return int(io.recvline())
def read_tuple() -> tuple[int, int]:
| 63 | 64 | 25 | 10 | 53 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | read_tuple | read_tuple | 15 | 16 | 15 | 15 | ed622de952e617b8467e4c4fe500af320775ea84 | bigcode/the-stack | train |
9579f12a8d1fd1ed6a47d332 | train | function | def recover_flag(comb: PandorasComb):
print('='*200)
dirs = [read_tuple() for _ in range(57)]
flag = []
for indir, res in dirs:
path = SHOOT_DIC[indir]
f = res ^ reduce(xor, [comb.state[x][y] for x, y in path])
print(chr(f), end='')
flag.append(f)
c... | def recover_flag(comb: PandorasComb):
| print('='*200)
dirs = [read_tuple() for _ in range(57)]
flag = []
for indir, res in dirs:
path = SHOOT_DIC[indir]
f = res ^ reduce(xor, [comb.state[x][y] for x, y in path])
print(chr(f), end='')
flag.append(f)
comb.shoot(indir, f)
print()
... | 0 < x < 5:
return ray
return ray[2:]
def recover_comb() -> PandorasComb:
key = []
for x in range(6):
key.extend(recover_ray(x))
return PandorasComb(key)
def recover_flag(comb: PandorasComb):
| 64 | 64 | 111 | 10 | 54 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | recover_flag | recover_flag | 113 | 129 | 113 | 113 | f323bcfa0a5fe789c9b02c83d3a7ae35862d3ff1 | bigcode/the-stack | train |
077fe180c98b7c813dbf270e | train | class | class PandorasComb:
def __init__(self,key_62):
if type(key_62) == str:
key_62 = bytes.fromhex(key_62)
self.key = list(key_62)
self.state = [
[' '] + self.key[:9] + [' '],
self.key[9:20],
self.key[20:31],
self.key[31:42],
... | class PandorasComb:
| def __init__(self,key_62):
if type(key_62) == str:
key_62 = bytes.fromhex(key_62)
self.key = list(key_62)
self.state = [
[' '] + self.key[:9] + [' '],
self.key[9:20],
self.key[20:31],
self.key[31:42],
self.key... | 8],[2,7],[3,7],[3,6],[4,6],[4,5],[5,5],[5,4]],
15 : [[1,10],[2,10],[2,9],[3,9],[3,8],[4,8],[4,7],[5,7],[5,6]]
}
class PandorasComb:
| 78 | 78 | 262 | 5 | 73 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | PandorasComb | PandorasComb | 37 | 69 | 37 | 37 | c2abee2d32d61188a88a939a8c9b738f28b0fa3d | bigcode/the-stack | train |
40fe41bf0c63e5fbedee21e7 | train | function | def recover_comb() -> PandorasComb:
key = []
for x in range(6):
key.extend(recover_ray(x))
return PandorasComb(key)
| def recover_comb() -> PandorasComb:
| key = []
for x in range(6):
key.extend(recover_ray(x))
return PandorasComb(key)
| e, f, g, h, i, j, k]
def recover_ray(x: int) -> list[int]:
ray = recover_ray11(x)
if 0 < x < 5:
return ray
return ray[2:]
def recover_comb() -> PandorasComb:
| 63 | 64 | 36 | 9 | 54 | AZ-0/Writeups | k3rn3l-ctf-2021/cozzmic-discovery/solve.py | Python | recover_comb | recover_comb | 107 | 111 | 107 | 107 | 9719588b8387bbbb50a530962a7cf9ad0b62d1df | bigcode/the-stack | train |
07982a967ca32f61d5629f83 | train | class | class Poller:
def __init__(self):
self._poll = uselect.poll()
self._events = {}
def register(self, fd, callback, flags=uselect.POLLIN):
"""
callback must take Poller and fd as arguments
"""
self._events[fd.fileno()] = callback
self._poll.register(fd, fla... | class Poller:
| def __init__(self):
self._poll = uselect.poll()
self._events = {}
def register(self, fd, callback, flags=uselect.POLLIN):
"""
callback must take Poller and fd as arguments
"""
self._events[fd.fileno()] = callback
self._poll.register(fd, flags)
def un... | # Copyright: 2021, Diez B. Roggisch, Berlin . All rights reserved.
import uselect
import gc
import wifi
import webserver
import buttons
import sensors
import machine
class Poller:
| 48 | 64 | 148 | 4 | 43 | deets/beehive-monitor | py/src/main.py | Python | Poller | Poller | 10 | 31 | 10 | 11 | 4d1c39e493312fe412824deb2b618519b1c5d12a | bigcode/the-stack | train |
a6746ee535410e467d913d81 | train | class | class ResNet(nn.Module):
def __init__(self, num_blocks, num_classes = 1000):
super(ResNet, self).__init__()
self.in_ch = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 3, bias = False) # 112x112x64, 1층
self.bn = nn.BatchNorm2d(64)
self.maxpoo... | class ResNet(nn.Module):
| def __init__(self, num_blocks, num_classes = 1000):
super(ResNet, self).__init__()
self.in_ch = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 3, bias = False) # 112x112x64, 1층
self.bn = nn.BatchNorm2d(64)
self.maxpool = nn.MaxPool2d(kernel_s... | _ch, kernel_size=3, stride=1, padding=1, bias=False)
if (stride == 2): #BasicBlock의 shortcut 사용 조건
self.shortcut = conv_bn(in_ch, out_ch, kernel_size=1, stride=stride, bias=False)
def forward(self, x):
out = self.conv1(x)
out = F.relu(out)
print(" ... | 155 | 155 | 519 | 6 | 148 | YuYoHy/resnet | 4_resnet18-34.py | Python | ResNet | ResNet | 33 | 76 | 33 | 33 | d896fcc76e29cccd2e70e8e2ab0bc70cc99fd539 | bigcode/the-stack | train |
1cf712bf75ab3936b6410141 | train | function | def conv_bn(in_ch,out_ch, *args, **kwargs):
return nn.Sequential(
nn.Conv2d(in_ch, out_ch, *args, **kwargs),
nn.BatchNorm2d(out_ch),
)
| def conv_bn(in_ch,out_ch, *args, **kwargs):
| return nn.Sequential(
nn.Conv2d(in_ch, out_ch, *args, **kwargs),
nn.BatchNorm2d(out_ch),
)
| import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn(in_ch,out_ch, *args, **kwargs):
| 30 | 64 | 47 | 14 | 15 | YuYoHy/resnet | 4_resnet18-34.py | Python | conv_bn | conv_bn | 6 | 10 | 6 | 6 | d5b48690cfc9354a5035bd6827fb95be2ae4275c | bigcode/the-stack | train |
046f2d46715d5c3cc3262e38 | train | function | def ResNet18():
return ResNet(num_blocks = [2, 2, 2, 2], num_classes=1000)
| def ResNet18():
| return ResNet(num_blocks = [2, 2, 2, 2], num_classes=1000)
| self.layer(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
print("Flatten:",out.shape)
out = self.linear(out)
print("[layer FC]:",out.shape)
return out
def ResNet18():
| 64 | 64 | 30 | 5 | 58 | YuYoHy/resnet | 4_resnet18-34.py | Python | ResNet18 | ResNet18 | 78 | 79 | 78 | 78 | f827d2c2acc8eb58193b07575261fc4ae967dd3a | bigcode/the-stack | train |
856bdc5c7f07c2582cec1799 | train | function | def ResNet34():
return ResNet(num_blocks = [3, 4, 6, 3], num_classes=1000)
| def ResNet34():
| return ResNet(num_blocks = [3, 4, 6, 3], num_classes=1000)
| print("Flatten:",out.shape)
out = self.linear(out)
print("[layer FC]:",out.shape)
return out
def ResNet18():
return ResNet(num_blocks = [2, 2, 2, 2], num_classes=1000)
def ResNet34():
| 64 | 64 | 30 | 5 | 59 | YuYoHy/resnet | 4_resnet18-34.py | Python | ResNet34 | ResNet34 | 81 | 82 | 81 | 81 | fa180d23603287efa000447dc849bddd8386f964 | bigcode/the-stack | train |
9f534c4c4df0ba18144d5049 | train | class | class BasicBlock(nn.Module):
def __init__(self, in_ch, out_ch, stride):
super().__init__()
self.conv1= conv_bn(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False)
self.conv2= conv_bn(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False)
if (stride ... | class BasicBlock(nn.Module):
| def __init__(self, in_ch, out_ch, stride):
super().__init__()
self.conv1= conv_bn(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False)
self.conv2= conv_bn(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False)
if (stride == 2): #BasicBlock의 shortcut ... | torch.nn as nn
import torch.nn.functional as F
def conv_bn(in_ch,out_ch, *args, **kwargs):
return nn.Sequential(
nn.Conv2d(in_ch, out_ch, *args, **kwargs),
nn.BatchNorm2d(out_ch),
)
class BasicBlock(nn.Module):
| 65 | 65 | 217 | 6 | 59 | YuYoHy/resnet | 4_resnet18-34.py | Python | BasicBlock | BasicBlock | 12 | 31 | 12 | 12 | 458e50ea979acac9610f61c74626325c4bf8682a | bigcode/the-stack | train |
86e67ee7f31445133dabbe48 | train | class | class RoomForm(ModelForm):
class Meta:
model = Room
fields = '__all__'
exclude = ['host', 'participants']
| class RoomForm(ModelForm):
| class Meta:
model = Room
fields = '__all__'
exclude = ['host', 'participants']
| import Room, User
from django.contrib.auth.forms import UserCreationForm
# from django.contrib.auth.models import User
class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class RoomForm(ModelForm):
| 64 | 64 | 31 | 6 | 58 | engineer237/Coders-Hub- | hub/forms.py | Python | RoomForm | RoomForm | 13 | 17 | 13 | 13 | bf08b02037403bec960075556be7e8ad4b1c162a | bigcode/the-stack | train |
3266b1b43a89693e19295407 | train | class | class UserForm(ModelForm):
class Meta:
model = User
fields = ['avatar','name','username', 'email', 'bio']
| class UserForm(ModelForm):
| class Meta:
model = User
fields = ['avatar','name','username', 'email', 'bio']
| ):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class RoomForm(ModelForm):
class Meta:
model = Room
fields = '__all__'
exclude = ['host', 'participants']
class UserForm(ModelForm):
| 64 | 64 | 31 | 6 | 58 | engineer237/Coders-Hub- | hub/forms.py | Python | UserForm | UserForm | 19 | 22 | 19 | 19 | 9bdb3612a12a6921f92865cf4e35a782731e4b5b | bigcode/the-stack | train |
2a504f8f42ac86f0005f027b | train | class | class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
| class UserCreationForm(UserCreationForm):
| class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
| from dataclasses import fields
from django.forms import ModelForm
from hub.models import Room, User
from django.contrib.auth.forms import UserCreationForm
# from django.contrib.auth.models import User
class UserCreationForm(UserCreationForm):
| 48 | 64 | 34 | 8 | 39 | engineer237/Coders-Hub- | hub/forms.py | Python | UserCreationForm | UserCreationForm | 8 | 11 | 8 | 8 | 264ea7540eee906c78c5b23543db9eebe37399ca | bigcode/the-stack | train |
308c91a4cec72712de0fcad9 | train | class | class TestStorage:
def test_version_check(self):
from gaphor.storage.storage import version_lower_than
assert version_lower_than("0.3.0", (0, 15, 0))
assert version_lower_than("0", (0, 15, 0))
assert version_lower_than("0.14", (0, 15, 0))
assert version_lower_than("0.14.1111... | class TestStorage:
| def test_version_check(self):
from gaphor.storage.storage import version_lower_than
assert version_lower_than("0.3.0", (0, 15, 0))
assert version_lower_than("0", (0, 15, 0))
assert version_lower_than("0.14", (0, 15, 0))
assert version_lower_than("0.14.1111", (0, 15, 0))
... | """Unittest the storage and parser modules."""
import re
from io import StringIO
import pytest
from gaphor import UML
from gaphor.core.modeling import StyleSheet
from gaphor.diagram.general import CommentItem
from gaphor.storage import storage
from gaphor.storage.xmlwriter import XMLWriter
from gaphor.UML.classes im... | 127 | 256 | 2,302 | 4 | 122 | mrmonkington/gaphor | gaphor/storage/tests/test_storage.py | Python | TestStorage | TestStorage | 27 | 272 | 27 | 27 | ba9daacab61a934a5c3c796786af1301d95c709e | bigcode/the-stack | train |
1551613108a7956f980b778a | train | class | class PseudoFile:
def __init__(self):
self.data = ""
def write(self, data):
self.data += data
def close(self):
pass
| class PseudoFile:
| def __init__(self):
self.data = ""
def write(self, data):
self.data += data
def close(self):
pass
| UML
from gaphor.core.modeling import StyleSheet
from gaphor.diagram.general import CommentItem
from gaphor.storage import storage
from gaphor.storage.xmlwriter import XMLWriter
from gaphor.UML.classes import AssociationItem, ClassItem, InterfaceItem
class PseudoFile:
| 64 | 64 | 38 | 5 | 58 | mrmonkington/gaphor | gaphor/storage/tests/test_storage.py | Python | PseudoFile | PseudoFile | 16 | 24 | 16 | 16 | 72f6ed414e85b085a708a830618976e5159e9016 | bigcode/the-stack | train |
532393083fc58acf2ebc3b03 | train | function | def check_cols(board):
"""
Check board by column
:param board: list
:return: 1, 2, or None
"""
for i in range(0, len(board)):
temp = set()
for row in board:
temp.add(row[i])
if len(temp) == 1:
return temp.pop()
return None
| def check_cols(board):
| """
Check board by column
:param board: list
:return: 1, 2, or None
"""
for i in range(0, len(board)):
temp = set()
for row in board:
temp.add(row[i])
if len(temp) == 1:
return temp.pop()
return None
| += 1
if len(temp) == 1:
return temp.pop()
i = 2
temp = set()
for row in board:
temp.add(row[i])
i -= 1
if len(temp) == 1:
return temp.pop()
return None
def check_cols(board):
| 64 | 64 | 76 | 5 | 58 | ikostan/codewars | kyu_5/tic_tac_toe_checker/checker.py | Python | check_cols | check_cols | 64 | 79 | 64 | 64 | df5edff1b61b3753e7fb54b518beb08da7f42ebc | bigcode/the-stack | train |
7f4f04b15dffe1075dee5d7c | train | function | def check_diagonals(board):
"""
Check board by diagonal
:param board: list
:return: 1, 2, or None
"""
i = 0
temp = set()
for row in board:
temp.add(row[i])
i += 1
if len(temp) == 1:
return temp.pop()
i = 2
temp = set()
for row in board:
temp.add(row[i])
i -= 1
if len(temp) == 1:
return temp... | def check_diagonals(board):
| """
Check board by diagonal
:param board: list
:return: 1, 2, or None
"""
i = 0
temp = set()
for row in board:
temp.add(row[i])
i += 1
if len(temp) == 1:
return temp.pop()
i = 2
temp = set()
for row in board:
temp.add(row[i])
i -= 1
if len(temp) == 1:
return temp.pop()
return None
| rows
cols = check_cols(board)
if cols:
return cols
diagonals = check_diagonals(board)
if diagonals:
return diagonals
for row in board:
if 0 in row:
return -1
return 0
def check_diagonals(board):
| 64 | 64 | 115 | 7 | 56 | ikostan/codewars | kyu_5/tic_tac_toe_checker/checker.py | Python | check_diagonals | check_diagonals | 36 | 61 | 36 | 36 | 46a324d3fc15818cf6138cbc9d5488baf4d1040a | bigcode/the-stack | train |
f015de30b711dab281cec7de | train | function | def is_solved(board):
"""
Checks whether the board's current state is solved:
-1 if the board is not yet finished (there are empty spots),
1 if "X" won,
2 if "O" won,
0 if it's a cat's game (i.e. a draw).
:param board: list
:return: -1, 0, 1, or 2
"""
rows = check_rows(board)
if rows:
return rows
co... | def is_solved(board):
| """
Checks whether the board's current state is solved:
-1 if the board is not yet finished (there are empty spots),
1 if "X" won,
2 if "O" won,
0 if it's a cat's game (i.e. a draw).
:param board: list
:return: -1, 0, 1, or 2
"""
rows = check_rows(board)
if rows:
return rows
cols = check_cols(board)... | # Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def is_solved(board):
| 47 | 64 | 162 | 6 | 41 | ikostan/codewars | kyu_5/tic_tac_toe_checker/checker.py | Python | is_solved | is_solved | 6 | 33 | 6 | 6 | 2159030cf01b352a2dbab63375a6186747b18c36 | bigcode/the-stack | train |
409f212ffba1f6585f5704eb | train | function | def check_rows(board: list):
"""
Check board by row
:param board: list
:return: 1, 2, or None
"""
for row in board:
if len(set(row)) == 1:
return row[0]
return None
| def check_rows(board: list):
| """
Check board by row
:param board: list
:return: 1, 2, or None
"""
for row in board:
if len(set(row)) == 1:
return row[0]
return None
| :return: 1, 2, or None
"""
for i in range(0, len(board)):
temp = set()
for row in board:
temp.add(row[i])
if len(temp) == 1:
return temp.pop()
return None
def check_rows(board: list):
| 64 | 64 | 58 | 7 | 56 | ikostan/codewars | kyu_5/tic_tac_toe_checker/checker.py | Python | check_rows | check_rows | 82 | 92 | 82 | 82 | d72881eb680a3243eae213b89802af7d144d55e0 | bigcode/the-stack | train |
434a436126b018cda1e868ca | train | function | def test_layer_flatten(system_dict):
forward = True;
test = "test_layer_flatten";
system_dict["total_tests"] += 1;
print_start(test, system_dict["total_tests"])
if(forward):
try:
gtf = prototype(verbose=0);
gtf.Prototype("sample-project-1", "sample-experiment-1");
... | def test_layer_flatten(system_dict):
| forward = True;
test = "test_layer_flatten";
system_dict["total_tests"] += 1;
print_start(test, system_dict["total_tests"])
if(forward):
try:
gtf = prototype(verbose=0);
gtf.Prototype("sample-project-1", "sample-experiment-1");
network = [];
... | monk.compare_prototype import compare
from monk.pip_unit_tests.gluon.common import print_start
from monk.pip_unit_tests.gluon.common import print_status
import mxnet as mx
import numpy as np
from monk.gluon.losses.return_loss import load_loss
def test_layer_flatten(system_dict):
| 67 | 67 | 226 | 8 | 58 | take2rohit/monk_v1 | monk/pip_unit_tests/gluon/test_layer_flatten.py | Python | test_layer_flatten | test_layer_flatten | 16 | 48 | 16 | 16 | 4afd60616a3f57eacbab3553028c5c095642dc8b | bigcode/the-stack | train |
5978f3f635a90c8943ae64f5 | train | class | @uvicore.model()
class Role(Model['Role'], metaclass=ModelMetaclass):
"""Auth Role Model"""
__tableclass__ = table.Roles
id: Optional[int] = Field('id',
primary=True,
description='Role ID',
)
name: str = Field('name',
description='Role Name',
required=True,
)
... | @uvicore.model()
class Role(Model['Role'], metaclass=ModelMetaclass):
| """Auth Role Model"""
__tableclass__ = table.Roles
id: Optional[int] = Field('id',
primary=True,
description='Role ID',
)
name: str = Field('name',
description='Role Name',
required=True,
)
# superadmin: bool = Field('superadmin',
# default=False,
... | dd, dump
from uvicore.auth.models.permission import Permission
from uvicore.auth.database.tables import roles as table
from uvicore.orm import Model, ModelMetaclass, Field, BelongsToMany
@uvicore.model()
class Role(Model['Role'], metaclass=ModelMetaclass):
| 64 | 64 | 177 | 19 | 44 | coboyoshi/uvicore | uvicore/auth/models/role.py | Python | Role | Role | 10 | 35 | 10 | 11 | 2c424d8415661c62703f9efd00e8d8c12ab7c8a5 | bigcode/the-stack | train |
3be10b014682d8656d4605c1 | train | class | class Reduce(NAry):
"Reduce binary modules over multiple inputs"
# def __init__(self, binary_module, left_in, right_in, outp, **kwds):
# super(Reduce, self).__init__(**kwds)
# self._binary_module = binary_module
# self._left_in = left_in
# self._right_in = right_in
# self... | class Reduce(NAry):
| "Reduce binary modules over multiple inputs"
# def __init__(self, binary_module, left_in, right_in, outp, **kwds):
# super(Reduce, self).__init__(**kwds)
# self._binary_module = binary_module
# self._left_in = left_in
# self._right_in = right_in
# self._outp = outp
# ... |
from .nary import NAry
from progressivis import Scheduler
class Reduce(NAry):
| 22 | 157 | 526 | 6 | 15 | jdfekete/progressivis | progressivis/table/reduce.py | Python | Reduce | Reduce | 6 | 56 | 6 | 6 | d1ad999f31fe95d6172b955439aabcdfaad803d7 | bigcode/the-stack | train |
8b733f95b2f43f8b957c47a9 | train | class | class Migration(migrations.Migration):
dependencies = [
('trade', '0005_auto_20180821_2249'),
]
operations = [
migrations.AlterField(
model_name='paymentlogs',
name='goods_order',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='t... | class Migration(migrations.Migration):
| dependencies = [
('trade', '0005_auto_20180821_2249'),
]
operations = [
migrations.AlterField(
model_name='paymentlogs',
name='goods_order',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='trade.GoodsOrder', verbose_name='关联订单'),
... | # Generated by Django 2.0.3 on 2018-08-23 22:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 83 | 7 | 37 | dryprojects/MyBlog | apps/trade/migrations/0006_auto_20180823_2238.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 33c11905b29e81611e65f33f2b05901b821c4c87 | bigcode/the-stack | train |
a31ced97794098830351bec8 | train | class | class DbContext(object):
pass
| class DbContext(object):
| pass
|
import zigg, osmapi
class DbContext(object):
| 13 | 64 | 8 | 5 | 7 | TimSC/ZiggDb | osmfunctest.py | Python | DbContext | DbContext | 4 | 5 | 4 | 4 | 95c3fe54662fe305fd794561562315aecbf57d6d | bigcode/the-stack | train |
b93c8f4f0cae70d23d1df611 | train | class | class Splice_Mish(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(Splice_Mish, self).__init__()
self.mul = P.Mul()
self.tanh = P.Tanh()
self.softplus = P.Softplus()
def construct(self, input_x):
"""Forward Mish."""
res1 = self.softplus(inpu... | class Splice_Mish(nn.Cell):
| """Mish activation method."""
def __init__(self):
super(Splice_Mish, self).__init__()
self.mul = P.Mul()
self.tanh = P.Tanh()
self.softplus = P.Softplus()
def construct(self, input_x):
"""Forward Mish."""
res1 = self.softplus(input_x)
tanh = self.tan... | Mish net definition."""
def __init__(self):
super(Init_Mish, self).__init__()
self.mish = P.Mish()
def construct(self, x):
"""Forward Mish."""
out = self.mish(x)
return out
class Splice_Mish(nn.Cell):
| 64 | 64 | 109 | 8 | 55 | zjzh/vega | vega/op_search/davinci_op_impl/test.py | Python | Splice_Mish | Splice_Mish | 79 | 93 | 79 | 79 | aba9f54f3daa6268dfb473e0306b57ca7b56f33f | bigcode/the-stack | train |
e554adb3a836fb300757e465 | train | class | class Init_Mish(nn.Cell):
"""Mish net definition."""
def __init__(self):
super(Init_Mish, self).__init__()
self.mish = P.Mish()
def construct(self, x):
"""Forward Mish."""
out = self.mish(x)
return out
| class Init_Mish(nn.Cell):
| """Mish net definition."""
def __init__(self):
super(Init_Mish, self).__init__()
self.mish = P.Mish()
def construct(self, x):
"""Forward Mish."""
out = self.mish(x)
return out
| init__()
self.exp1 = Exp1()
self.pow = P.Pow()
def construct(self, x):
"""Forward Mish."""
return x * (1 - 2 / (self.pow(1 + self.exp1(x), 2) + 1))
class Init_Mish(nn.Cell):
| 64 | 64 | 65 | 7 | 57 | zjzh/vega | vega/op_search/davinci_op_impl/test.py | Python | Init_Mish | Init_Mish | 66 | 76 | 66 | 66 | e943db9c18a7e00995cbe42c6db4c160ef18e815 | bigcode/the-stack | train |
8fb1c3c9c9d27d23ef064629 | train | class | class My_exp(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(My_exp, self).__init__()
self.exp1 = Exp1()
def construct(self, x):
"""Forward Mish."""
return self.exp1(x)
| class My_exp(nn.Cell):
| """Mish activation method."""
def __init__(self):
super(My_exp, self).__init__()
self.exp1 = Exp1()
def construct(self, x):
"""Forward Mish."""
return self.exp1(x)
| as np
import mindspore.nn as nn
import mindspore.context as context
from mindspore import Tensor
from exp1 import Exp1
from mindspore.ops import operations as P
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
class My_exp(nn.Cell):
| 64 | 64 | 56 | 6 | 58 | zjzh/vega | vega/op_search/davinci_op_impl/test.py | Python | My_exp | My_exp | 29 | 38 | 29 | 29 | 337396b3704af3193830beacab393a531be8728c | bigcode/the-stack | train |
1cc9304eb84290c4a3c838e5 | train | class | class My_Mish(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(My_Mish, self).__init__()
self.exp1 = Exp1()
self.pow = P.Pow()
def construct(self, x):
"""Forward Mish."""
return x * (1 - 2 / (self.pow(1 + self.exp1(x), 2) + 1))
| class My_Mish(nn.Cell):
| """Mish activation method."""
def __init__(self):
super(My_Mish, self).__init__()
self.exp1 = Exp1()
self.pow = P.Pow()
def construct(self, x):
"""Forward Mish."""
return x * (1 - 2 / (self.pow(1 + self.exp1(x), 2) + 1))
| (x)
class Init_exp(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(Init_exp, self).__init__()
self.exp = P.Exp()
def construct(self, x):
"""Forward Mish."""
return self.exp(x)
class My_Mish(nn.Cell):
| 64 | 64 | 86 | 7 | 57 | zjzh/vega | vega/op_search/davinci_op_impl/test.py | Python | My_Mish | My_Mish | 53 | 63 | 53 | 53 | e73ba81601adfd3f1fc4d732a9c4533dde6deeaf | bigcode/the-stack | train |
9055cc4070bff71571729c77 | train | class | class Init_exp(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(Init_exp, self).__init__()
self.exp = P.Exp()
def construct(self, x):
"""Forward Mish."""
return self.exp(x)
| class Init_exp(nn.Cell):
| """Mish activation method."""
def __init__(self):
super(Init_exp, self).__init__()
self.exp = P.Exp()
def construct(self, x):
"""Forward Mish."""
return self.exp(x)
| end")
class My_exp(nn.Cell):
"""Mish activation method."""
def __init__(self):
super(My_exp, self).__init__()
self.exp1 = Exp1()
def construct(self, x):
"""Forward Mish."""
return self.exp1(x)
class Init_exp(nn.Cell):
| 64 | 64 | 55 | 6 | 58 | zjzh/vega | vega/op_search/davinci_op_impl/test.py | Python | Init_exp | Init_exp | 41 | 50 | 41 | 41 | 891a84fed575d2a83a12041a3f24d928e4ceebd0 | bigcode/the-stack | train |
10e16317460cf16f06988446 | train | function | def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this w... | def get_activation(activation_string):
| """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_str... | """
PI = 3.141592653589793238462
cdf = 0.5 * (1.0 + tf.tanh(
(tf.sqrt(2 / PI) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def get_activation(activation_string):
| 74 | 74 | 247 | 7 | 66 | Mistobaan/electra | model/modeling.py | Python | get_activation | get_activation | 300 | 334 | 300 | 300 | 94be316efce2243cf21f51907034027aa2abc603 | bigcode/the-stack | train |
83ef43ab158c38a7e749c165 | train | function | def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""):
"""Compute the union of the current variables and checkpoint variables."""
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(... | def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""):
| """Compute the union of the current variables and checkpoint variables."""
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to_variable[name] = var
initialized_variable_names = {}
as... | return tf.nn.relu
elif act == "gelu":
return gelu
elif act == "tanh":
return tf.tanh
else:
raise ValueError("Unsupported activation: %s" % act)
def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""):
| 64 | 64 | 188 | 15 | 49 | Mistobaan/electra | model/modeling.py | Python | get_assignment_map_from_checkpoint | get_assignment_map_from_checkpoint | 337 | 357 | 337 | 337 | f5a9a142dcbda3dbd0a6fb9738081eed0f052d6e | bigcode/the-stack | train |
80da7e5da601775ca9886bb5 | train | function | def embedding_postprocessor(input_tensor,
use_token_type=False,
token_type_ids=None,
token_type_vocab_size=16,
token_type_embedding_name="token_type_embeddings",
use_position_embed... | def embedding_postprocessor(input_tensor,
use_token_type=False,
token_type_ids=None,
token_type_vocab_size=16,
token_type_embedding_name="token_type_embeddings",
use_position_embed... | """Performs various post-processing on a word embedding tensor.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length,
embedding_size].
use_token_type: bool. Whether to add embeddings for `token_type_ids`.
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
... | izer_range))
if original_dims == 3:
input_shape = get_shape_list(input_ids)
tf.reshape(input_ids, [-1, input_shape[-1]])
output = tf.matmul(input_ids, embedding_table)
output = tf.reshape(output,
[input_shape[0], input_shape[1], embedding_size])
else:
if use_one_hot_embe... | 256 | 256 | 912 | 74 | 181 | Mistobaan/electra | model/modeling.py | Python | embedding_postprocessor | embedding_postprocessor | 453 | 546 | 453 | 462 | b03c28e0a8acd1776b174d874d51855080f509df | bigcode/the-stack | train |
731d647bd0d5ca38b6d6dbb2 | train | function | def attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attenti... | def attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attenti... | """Performs multi-headed attention from `from_tensor` to `to_tensor`.
This is an implementation of multi-headed attention based on "Attention
is all you Need". If `from_tensor` and `to_tensor` are the same, then
this is self-attention. Each timestep in `from_tensor` attends to the
corresponding sequence in `... | =2)
to_seq_length = to_shape[1]
to_mask = tf.cast(
tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)
# We don't assume that `from_tensor` is a mask (although it could be). We
# don't actually care if we attend *from* padding tokens (only *to* padding)
# tokens so we create a tensor of a... | 256 | 256 | 1,984 | 88 | 167 | Mistobaan/electra | model/modeling.py | Python | attention_layer | attention_layer | 583 | 776 | 583 | 596 | 456e4ef18e92a499ec9fdbfa82b01541babb2788 | bigcode/the-stack | train |
b36792a92b188688c8a6eed1 | train | function | def reshape_to_matrix(input_tensor):
"""Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
ndims = input_tensor.shape.ndims
if ndims < 2:
raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor... | def reshape_to_matrix(input_tensor):
| """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
ndims = input_tensor.shape.ndims
if ndims < 2:
raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor
width = input_tensor.shape[-1]
... | enumerate(shape):
if dim is None:
non_static_indexes.append(index)
if not non_static_indexes:
return shape
dyn_shape = tf.shape(tensor)
for index in non_static_indexes:
shape[index] = dyn_shape[index]
return shape
def reshape_to_matrix(input_tensor):
| 64 | 64 | 118 | 7 | 56 | Mistobaan/electra | model/modeling.py | Python | reshape_to_matrix | reshape_to_matrix | 961 | 972 | 961 | 961 | 4b942d5b989831537346e247dffdb8e733272b70 | bigcode/the-stack | train |
e6aabb4c62db038e2266ef77 | train | function | def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, ... | def create_attention_mask_from_input_mask(from_tensor, to_mask):
| """Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_length, to_seq_length].
"""
from_shape = get_shape_l... | the batch size.
position_broadcast_shape = []
for _ in range(num_dims - 2):
position_broadcast_shape.append(1)
position_broadcast_shape.extend([seq_length, width])
position_embeddings = tf.reshape(position_embeddings,
position_broadcast_shape)
... | 93 | 93 | 312 | 13 | 79 | Mistobaan/electra | model/modeling.py | Python | create_attention_mask_from_input_mask | create_attention_mask_from_input_mask | 549 | 580 | 549 | 549 | 7b1181d98e98cc7f3aea99c382a648811bef55d5 | bigcode/the-stack | train |
4193dcb390258fed9c14f53e | train | function | def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
| def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
| """Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
|
def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor."""
return contrib_layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
| 64 | 64 | 50 | 14 | 50 | Mistobaan/electra | model/modeling.py | Python | layer_norm_and_dropout | layer_norm_and_dropout | 384 | 388 | 384 | 384 | 49bd787c5858042f8c490802a7f88876c29ab5f4 | bigcode/the-stack | train |
aefdc1862ef576fffd79296f | train | function | def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(o... | def reshape_from_matrix(output_tensor, orig_shape_list):
| """Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
| Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor
width = input_tensor.shape[-1]
output_tensor = tf.reshape(input_tensor, [-1, width])
return output_tensor
def reshape_from_matrix(output_tensor, orig_shape_list):
| 64 | 64 | 90 | 11 | 52 | Mistobaan/electra | model/modeling.py | Python | reshape_from_matrix | reshape_from_matrix | 975 | 985 | 975 | 975 | f1d063773d294b36bdecbce6de5a82d60a662b2b | bigcode/the-stack | train |
3c54ff8e4ba7e561f79fe2b4 | train | function | def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor.
Args:
... | def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
| """Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
ids.
vocab_size: int. Size of the embedding vocabulary.
embedding_size: int. Width of the word embeddings.
initializer_range: float. Embedding initialization range.
... | inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_t... | 147 | 147 | 490 | 39 | 108 | Mistobaan/electra | model/modeling.py | Python | embedding_lookup | embedding_lookup | 396 | 450 | 396 | 401 | 27efc58af137c49fb4e33bedbe7b85dd3142f589 | bigcode/the-stack | train |
cd60378fa82c18a97d1099ff | train | function | def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
... | def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
... | """Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transforme... | 3])
# `context_layer` = [B, N, F, H]
context_layer = tf.matmul(attention_probs, value_layer)
# `context_layer` = [B, F, N, H]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
if do_return_2d_tensor:
# `context_layer` = [B*F, N*H]
context_layer = tf.reshape(
context_layer,
[... | 256 | 256 | 1,220 | 80 | 175 | Mistobaan/electra | model/modeling.py | Python | transformer_model | transformer_model | 779 | 913 | 779 | 789 | 5587b105092902d4893aaa26a228f7847f2765ef | bigcode/the-stack | train |
3c97a197d7eeb66c9f16deea | train | class | class BertConfig(object):
"""Configuration for `BertModel` (ELECTRA uses the same model as BERT)."""
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden... | class BertConfig(object):
| """Configuration for `BertModel` (ELECTRA uses the same model as BERT)."""
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
... | Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS I... | 202 | 202 | 675 | 5 | 196 | Mistobaan/electra | model/modeling.py | Python | BertConfig | BertConfig | 36 | 109 | 36 | 36 | bf5e649a53865cb8beff6ddf9562b1cc7f856334 | bigcode/the-stack | train |
b5cec8b640ce3bfc6469f13e | train | function | def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
PI = 3.141592653589793238462
cdf = 0.5 * (1.0 + tf.tanh(
(tf.... | def gelu(x):
| """Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
PI = 3.141592653589793238462
cdf = 0.5 * (1.0 + tf.tanh(
(tf.sqrt(2 / PI) ... | output of the embedding layer, after summing the word
embeddings with the positional embeddings and the token type embeddings,
then performing layer normalization. This is the input to the transformer.
"""
return self.embedding_output
def get_embedding_table(self):
return self.embedding_tabl... | 64 | 64 | 134 | 5 | 58 | Mistobaan/electra | model/modeling.py | Python | gelu | gelu | 286 | 298 | 286 | 286 | a0a4546aef41c72ca97f269bc1644c281eda1ea8 | bigcode/the-stack | train |
6c55c628fa48ad39db8b3663 | train | function | def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different... | def get_shape_list(tensor, expected_rank=None, name=None):
| """Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different rank, and exception will be
thrown.
name: Option... | (prev_output + attention_output)
all_layer_outputs.append(prev_output)
attn_maps = tf.stack(attn_maps, 0)
if do_return_all_layers:
return tf.stack([reshape_from_matrix(layer, input_shape)
for layer in all_layer_outputs], 0), attn_maps
else:
return reshape_from_matrix(prev_out... | 95 | 95 | 317 | 14 | 80 | Mistobaan/electra | model/modeling.py | Python | get_shape_list | get_shape_list | 916 | 958 | 916 | 916 | 89a2980803d5c09f8c9796a2e0a0a0aaa7f63ffd | bigcode/the-stack | train |
68d467d7501989156cf77b29 | train | function | def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:... | def assert_rank(tensor, expected_rank, name=None):
| """Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:
ValueError: If the expected shape doesn't matc... | ."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
def assert_rank(tensor, expected_rank, name=None):
| 72 | 72 | 241 | 12 | 60 | Mistobaan/electra | model/modeling.py | Python | assert_rank | assert_rank | 988 | 1,015 | 988 | 988 | 7f49d2d2a27c4aeeb8ace9097c78c1eba12c5c8e | bigcode/the-stack | train |
33c6bfa3c82035590070e63c | train | function | def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor."""
return contrib_layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
| def layer_norm(input_tensor, name=None):
| """Run layer normalization on the last dimension of the tensor."""
return contrib_layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
| A version of `input_tensor` with dropout applied.
"""
if dropout_prob is None or dropout_prob == 0.0:
return input_tensor
output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
return output
def layer_norm(input_tensor, name=None):
| 64 | 64 | 49 | 9 | 54 | Mistobaan/electra | model/modeling.py | Python | layer_norm | layer_norm | 378 | 381 | 378 | 378 | 8ce0896e88061a74ce5edade2f56997abb349911 | bigcode/the-stack | train |
44e25bfffec51effb6efd3f0 | train | function | def dropout(input_tensor, dropout_prob):
"""Perform dropout.
Args:
input_tensor: float Tensor.
dropout_prob: Python float. The probability of dropping out a value (NOT of
*keeping* a dimension as in `tf.nn.dropout`).
Returns:
A version of `input_tensor` with dropout applied.
"""
if dropout... | def dropout(input_tensor, dropout_prob):
| """Perform dropout.
Args:
input_tensor: float Tensor.
dropout_prob: Python float. The probability of dropping out a value (NOT of
*keeping* a dimension as in `tf.nn.dropout`).
Returns:
A version of `input_tensor` with dropout applied.
"""
if dropout_prob is None or dropout_prob == 0.0:
... | if prefix + name not in name_to_variable:
continue
assignment_map[name] = prefix + name
initialized_variable_names[name] = 1
initialized_variable_names[name + ":0"] = 1
return assignment_map, initialized_variable_names
def dropout(input_tensor, dropout_prob):
| 64 | 64 | 113 | 8 | 55 | Mistobaan/electra | model/modeling.py | Python | dropout | dropout | 360 | 375 | 360 | 360 | f2327fa7e67d9aacb151cdf5a63cb52904083efa | bigcode/the-stack | train |
27e404dfbe1aa737f78c0888 | train | class | class BertModel(object):
"""BERT model. Although the training algorithm is different, the transformer
model for ELECTRA is the same as BERT's.
Example usage:
```python
# Already been converted into WordPiece token ids
input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
input_mask = tf.constant([[1, 1, 1... | class BertModel(object):
| """BERT model. Although the training algorithm is different, the transformer
model for ELECTRA is the same as BERT's.
Example usage:
```python
# Already been converted into WordPiece token ids
input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
token_ty... |
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
@classmethod
def from_dict(cls, json_object):... | 256 | 256 | 1,490 | 5 | 251 | Mistobaan/electra | model/modeling.py | Python | BertModel | BertModel | 112 | 283 | 112 | 112 | e68eefe922a3278a5ef74020e1e2f4776b48eed9 | bigcode/the-stack | train |
177efdf3d2b59e6e7e0f732a | train | function | def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range)
| def create_initializer(initializer_range=0.02):
| """Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range)
| scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
def create_initializer(initializer_range=0.02):
| 64 | 64 | 39 | 11 | 52 | Mistobaan/electra | model/modeling.py | Python | create_initializer | create_initializer | 391 | 393 | 391 | 391 | 3956b75d9142b716062aba6859e51c11518be31b | bigcode/the-stack | train |
05f82ad10bb0cea57a04da2b | train | function | def CommonChecks(input_api, output_api):
output = []
def join(*args):
return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
gae_sdk_path = FindAppEngineSDK(input_api)
if not gae_sdk_path:
output.append(output_api.PresubmitError('Couldn\'t find AppEngine SDK.'))
return output
impor... | def CommonChecks(input_api, output_api):
| output = []
def join(*args):
return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
gae_sdk_path = FindAppEngineSDK(input_api)
if not gae_sdk_path:
output.append(output_api.PresubmitError('Couldn\'t find AppEngine SDK.'))
return output
import sys
old_sys_path = sys.path
try:
... | ' to sys.path to be able to import gae_sdk_utils.
components_dir = input_api.os_path.join(
input_api.PresubmitLocalPath(), '..', 'components')
sys.path = [components_dir] + sys.path
# pylint: disable=F0401
from support import gae_sdk_utils
return gae_sdk_utils.find_gae_sdk()
finally:
s... | 100 | 100 | 334 | 9 | 90 | pombreda/swarming | appengine/auth_service/PRESUBMIT.py | Python | CommonChecks | CommonChecks | 28 | 70 | 28 | 28 | b14c2d5f2d8b56e9884101821475163e0c8d62f2 | bigcode/the-stack | train |
52fb1838713f1570a635e226 | train | function | def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
| def CheckChangeOnUpload(input_api, output_api):
| return CommonChecks(input_api, output_api)
| = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api,
join('tests'),
whitelist=[r'.+_test\.py$'])
output.extend(input_api.RunTests(tests, parallel=True))
return output
def CheckChangeOnUpload(input_api, output_api):
| 64 | 64 | 21 | 11 | 52 | pombreda/swarming | appengine/auth_service/PRESUBMIT.py | Python | CheckChangeOnUpload | CheckChangeOnUpload | 73 | 74 | 73 | 73 | 04c84b758feb323bb8f59d78878563ee41ed0115 | bigcode/the-stack | train |
e608f5eb8f8930105ebb3975 | train | function | def FindAppEngineSDK(input_api):
"""Returns an absolute path to AppEngine SDK (or None if not found)."""
import sys
old_sys_path = sys.path
try:
# Add 'components' to sys.path to be able to import gae_sdk_utils.
components_dir = input_api.os_path.join(
input_api.PresubmitLocalPath(), '..', 'comp... | def FindAppEngineSDK(input_api):
| """Returns an absolute path to AppEngine SDK (or None if not found)."""
import sys
old_sys_path = sys.path
try:
# Add 'components' to sys.path to be able to import gae_sdk_utils.
components_dir = input_api.os_path.join(
input_api.PresubmitLocalPath(), '..', 'components')
sys.path = [componen... | that can be
# found in the LICENSE file.
"""Top-level presubmit script for auth server.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
def FindAppEngineSDK(input_api):
| 64 | 64 | 137 | 8 | 56 | pombreda/swarming | appengine/auth_service/PRESUBMIT.py | Python | FindAppEngineSDK | FindAppEngineSDK | 12 | 25 | 12 | 12 | 5c4ef37cdd23a9bbf1dd3b23a314d3b0b7dd70f8 | bigcode/the-stack | train |
273902ab09a34185f6092d57 | train | function | def CheckChangeOnCommit(input_api, output_api):
return CommonChecks(input_api, output_api)
| def CheckChangeOnCommit(input_api, output_api):
| return CommonChecks(input_api, output_api)
| ('tests'),
whitelist=[r'.+_test\.py$'])
output.extend(input_api.RunTests(tests, parallel=True))
return output
def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
| 64 | 64 | 21 | 11 | 53 | pombreda/swarming | appengine/auth_service/PRESUBMIT.py | Python | CheckChangeOnCommit | CheckChangeOnCommit | 77 | 78 | 77 | 77 | 4bcf7a1c58df5ee7bbeaccd1c8507cb0b82580aa | bigcode/the-stack | train |
bb870094d8f931b5834d5aa1 | train | function | def _set_units(cube, units):
"""Set units in compliance with cf_unit."""
special = {'psu': 1.e-3, 'Sv': '1e6 m3 s-1'}
if units in list(special.keys()):
cube.units = special[units]
else:
cube.units = Unit(units)
return cube
| def _set_units(cube, units):
| """Set units in compliance with cf_unit."""
special = {'psu': 1.e-3, 'Sv': '1e6 m3 s-1'}
if units in list(special.keys()):
cube.units = special[units]
else:
cube.units = Unit(units)
return cube
| attributes['positive'] = 'up'
return cube
def _roll_cube_data(cube, shift, axis):
"""Roll a cube data on specified axis."""
cube.data = da.roll(cube.core_data(), shift, axis=axis)
return cube
def _set_units(cube, units):
| 64 | 64 | 77 | 9 | 54 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | _set_units | _set_units | 294 | 301 | 294 | 294 | e1e3b4e3aa558e9852a6fbb422cda98045508c83 | bigcode/the-stack | train |
db903b28d1f63d481469ee15 | train | function | def flip_dim_coord(cube, coord_name):
"""Flip (reverse) dimensional coordinate of cube."""
logger.info("Flipping dimensional coordinate %s...", coord_name)
coord = cube.coord(coord_name, dim_coords=True)
coord_idx = cube.coord_dims(coord)[0]
coord.points = np.flip(coord.points)
if coord.bounds i... | def flip_dim_coord(cube, coord_name):
| """Flip (reverse) dimensional coordinate of cube."""
logger.info("Flipping dimensional coordinate %s...", coord_name)
coord = cube.coord(coord_name, dim_coords=True)
coord_idx = cube.coord_dims(coord)[0]
coord.points = np.flip(coord.points)
if coord.bounds is not None:
coord.bounds = np.... | cube.standard_name = None
else:
cube.standard_name = var_info.standard_name
cube.var_name = var_info.short_name
cube.long_name = var_info.long_name
_set_units(cube, var_info.units)
return cube
def flip_dim_coord(cube, coord_name):
| 64 | 64 | 104 | 10 | 53 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | flip_dim_coord | flip_dim_coord | 131 | 139 | 131 | 131 | a928ea4a4bea74ad270e107ca0d1911cbaae2360 | bigcode/the-stack | train |
799eb2bf91289ceb22f16d70 | train | function | def _fix_dim_coordnames(cube):
"""Perform a check on dim coordinate names."""
# first check for CMOR standard coord;
for coord in cube.coords():
# guess the CMOR-standard x, y, z and t axes if not there
coord_type = iris.util.guess_coord_axis(coord)
if coord_type == 'T':
... | def _fix_dim_coordnames(cube):
| """Perform a check on dim coordinate names."""
# first check for CMOR standard coord;
for coord in cube.coords():
# guess the CMOR-standard x, y, z and t axes if not there
coord_type = iris.util.guess_coord_axis(coord)
if coord_type == 'T':
cube.coord(axis=coord_type).va... | iris.Constraint(cube_func=lambda c: c.var_name == var_name)
def _fix_bounds(cube, dim_coord):
"""Reset and fix all bounds."""
if len(cube.coord(dim_coord).points) > 1:
if cube.coord(dim_coord).has_bounds():
cube.coord(dim_coord).bounds = None
cube.coord(dim_coord).guess_bounds()
... | 125 | 125 | 417 | 9 | 115 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | _fix_dim_coordnames | _fix_dim_coordnames | 247 | 285 | 247 | 247 | 6a59725ab9d850cd3da2290ca9f0d0ebf5ad0784 | bigcode/the-stack | train |
16fc540b5a57d090955d1b7b | train | function | def read_cmor_config(dataset):
"""Read the associated dataset-specific config file."""
reg_path = os.path.join(os.path.dirname(__file__), 'cmor_config',
dataset + '.yml')
with open(reg_path, 'r') as file:
cfg = yaml.safe_load(file)
cfg['cmor_table'] = \
CMOR_T... | def read_cmor_config(dataset):
| """Read the associated dataset-specific config file."""
reg_path = os.path.join(os.path.dirname(__file__), 'cmor_config',
dataset + '.yml')
with open(reg_path, 'r') as file:
cfg = yaml.safe_load(file)
cfg['cmor_table'] = \
CMOR_TABLES[cfg['attributes']['projec... | coord_idx = cube.coord_dims(coord)[0]
coord.points = np.flip(coord.points)
if coord.bounds is not None:
coord.bounds = np.flip(coord.bounds, axis=0)
cube.data = da.flip(cube.core_data(), axis=coord_idx)
def read_cmor_config(dataset):
| 64 | 64 | 106 | 7 | 57 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | read_cmor_config | read_cmor_config | 142 | 152 | 142 | 142 | 288a71536dfbd482ac4036290eca798a5103ae2c | bigcode/the-stack | train |
082d154e6acf1da7a4d163ad | train | function | def fix_coords(cube):
"""Fix the time units and values to CMOR standards."""
# first fix any completely missing coord var names
_fix_dim_coordnames(cube)
# fix individual coords
for cube_coord in cube.coords():
# fix time
if cube_coord.var_name == 'time':
logger.info("Fix... | def fix_coords(cube):
| """Fix the time units and values to CMOR standards."""
# first fix any completely missing coord var names
_fix_dim_coordnames(cube)
# fix individual coords
for cube_coord in cube.coords():
# fix time
if cube_coord.var_name == 'time':
logger.info("Fixing time...")
... | convert_units(cube, source_units, target_units):
"""Convert units."""
source_units = Unit(source_units)
target_units = Unit(target_units)
try:
source_units.convert(1.0, target_units)
except ValueError:
logger.warning("Cannot convert units from '%s' to '%s'", source_units,
... | 121 | 121 | 405 | 6 | 115 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | fix_coords | fix_coords | 71 | 116 | 71 | 71 | dcecd8e6a7fb58b96e3a7747cb4549cd76e2f56b | bigcode/the-stack | train |
e0e3f9942b16e9bc04755a44 | train | function | def var_name_constraint(var_name):
""":mod:`iris.Constraint` using `var_name` of an :mod:`iris.cube.Cube`."""
return iris.Constraint(cube_func=lambda c: c.var_name == var_name)
| def var_name_constraint(var_name):
| """:mod:`iris.Constraint` using `var_name` of an :mod:`iris.cube.Cube`."""
return iris.Constraint(cube_func=lambda c: c.var_name == var_name)
| datasets need the global attributes 'dataset_id', "
"'version', 'tier', 'source', 'reference', 'comment' and "
"'project_id' specified in the configuration file")
# Additional attributes
glob_dict.update(attrs)
cube.attributes = glob_dict
def var_name_constraint(var_name):
| 64 | 64 | 49 | 7 | 56 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | var_name_constraint | var_name_constraint | 229 | 231 | 229 | 229 | 2ff8154ba71356a87c60e6117273a13c26ca234a | bigcode/the-stack | train |
6538cc4da30d3254f7c443d6 | train | function | def set_global_atts(cube, attrs):
"""Complete the cmorized file with global metadata."""
logger.info("Setting global metadata...")
attrs = dict(attrs)
cube.attributes.clear()
timestamp = datetime.datetime.utcnow()
timestamp_format = "%Y-%m-%d %H:%M:%S"
now_time = timestamp.strftime(timestamp... | def set_global_atts(cube, attrs):
| """Complete the cmorized file with global metadata."""
logger.info("Setting global metadata...")
attrs = dict(attrs)
cube.attributes.clear()
timestamp = datetime.datetime.utcnow()
timestamp_format = "%Y-%m-%d %H:%M:%S"
now_time = timestamp.strftime(timestamp_format)
# Necessary attribut... | + '.nc'
file_path = os.path.join(outdir, file_name)
logger.info('Saving: %s', file_path)
status = 'lazy' if cube.has_lazy_data() else 'realized'
logger.info('Cube has %s data [lazy is preferred]', status)
iris.save(cube, file_path, fill_value=1e20, **kwargs)
def set_global_atts(cube, attrs):
| 91 | 91 | 305 | 10 | 81 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | set_global_atts | set_global_atts | 185 | 226 | 185 | 185 | 8b6a2cfe82c63f3c0bcd6392b25d4914a118cc39 | bigcode/the-stack | train |
7edbf834c13cac8d637b07be | train | function | def fix_var_metadata(cube, var_info):
"""Fix var metadata from CMOR table."""
if var_info.standard_name == '':
cube.standard_name = None
else:
cube.standard_name = var_info.standard_name
cube.var_name = var_info.short_name
cube.long_name = var_info.long_name
_set_units(cube, var_... | def fix_var_metadata(cube, var_info):
| """Fix var metadata from CMOR table."""
if var_info.standard_name == '':
cube.standard_name = None
else:
cube.standard_name = var_info.standard_name
cube.var_name = var_info.short_name
cube.long_name = var_info.long_name
_set_units(cube, var_info.units)
return cube
| ':
logger.info("Fixing air pressure...")
_fix_bounds(cube, cube.coord('air_pressure'))
# remove CS
cube.coord('latitude').coord_system = None
cube.coord('longitude').coord_system = None
return cube
def fix_var_metadata(cube, var_info):
| 64 | 64 | 83 | 10 | 53 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | fix_var_metadata | fix_var_metadata | 119 | 128 | 119 | 119 | a2621950062805f5b9dd5ce0a7270d17d8ae066b | bigcode/the-stack | train |
0c76b56ddc8631c911d69f52 | train | function | def save_variable(cube, var, outdir, attrs, **kwargs):
"""Saver function."""
# CMOR standard
cube_time = cube.coord('time')
reftime = Unit(cube_time.units.origin, cube_time.units.calendar)
dates = reftime.num2date(cube_time.points[[0, -1]])
if len(cube_time.points) == 1:
year = str(dates... | def save_variable(cube, var, outdir, attrs, **kwargs):
| """Saver function."""
# CMOR standard
cube_time = cube.coord('time')
reftime = Unit(cube_time.units.origin, cube_time.units.calendar)
dates = reftime.num2date(cube_time.points[[0, -1]])
if len(cube_time.points) == 1:
year = str(dates[0].year)
time_suffix = '-'.join([year + '01', ... | or_config',
dataset + '.yml')
with open(reg_path, 'r') as file:
cfg = yaml.safe_load(file)
cfg['cmor_table'] = \
CMOR_TABLES[cfg['attributes']['project_id']]
if 'comment' not in cfg:
cfg['attributes']['comment'] = ''
return cfg
def save_variable(cube, ... | 90 | 90 | 303 | 16 | 73 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | save_variable | save_variable | 155 | 182 | 155 | 155 | 26839626beb12ff7d783f0a5143a325f79cfb3b1 | bigcode/the-stack | train |
0131b1bcb4f863180f5e5615 | train | function | def add_height2m(cube):
"""Add scalar coordinate 'height' with value of 2m."""
logger.info("Adding height coordinate (2m)")
height_coord = iris.coords.AuxCoord(2.0,
var_name='height',
standard_name='height',
... | def add_height2m(cube):
| """Add scalar coordinate 'height' with value of 2m."""
logger.info("Adding height coordinate (2m)")
height_coord = iris.coords.AuxCoord(2.0,
var_name='height',
standard_name='height',
long... | cf_units import Unit
from dask import array as da
from esmvalcore._config import get_tag_value
from esmvalcore.cmor.table import CMOR_TABLES
from esmvaltool import __version__ as version
logger = logging.getLogger(__name__)
def add_height2m(cube):
| 64 | 64 | 90 | 8 | 56 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | add_height2m | add_height2m | 20 | 29 | 20 | 20 | 214dd81c2cdf3ad110a832fe271d625cf9239405 | bigcode/the-stack | train |
7556b7ca8c16057fa6518257 | train | function | def convert_units(cube, source_units, target_units):
"""Convert units."""
source_units = Unit(source_units)
target_units = Unit(target_units)
try:
source_units.convert(1.0, target_units)
except ValueError:
logger.warning("Cannot convert units from '%s' to '%s'", source_units,
... | def convert_units(cube, source_units, target_units):
| """Convert units."""
source_units = Unit(source_units)
target_units = Unit(target_units)
try:
source_units.convert(1.0, target_units)
except ValueError:
logger.warning("Cannot convert units from '%s' to '%s'", source_units,
target_units)
return
logg... | 1':
real_unit = 'days since 1950-1-1 00:00:00'
else:
real_unit = cube.coord('time').units
cube.coord('time').units = real_unit
return cube
def convert_units(cube, source_units, target_units):
| 64 | 64 | 116 | 12 | 51 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | convert_units | convert_units | 55 | 68 | 55 | 55 | 070c2d0ef43dbf31a25ec301748045b15e895289 | bigcode/the-stack | train |
f088bcab0776efc730b03ce3 | train | function | def _roll_cube_data(cube, shift, axis):
"""Roll a cube data on specified axis."""
cube.data = da.roll(cube.core_data(), shift, axis=axis)
return cube
| def _roll_cube_data(cube, shift, axis):
| """Roll a cube data on specified axis."""
cube.data = da.roll(cube.core_data(), shift, axis=axis)
return cube
| air_pressure'
cube.coord(axis=coord_type).long_name = 'pressure'
cube.coord(axis=coord_type).var_name = 'air_pressure'
cube.coord(axis=coord_type).attributes['positive'] = 'up'
return cube
def _roll_cube_data(cube, shift, axis):
| 64 | 64 | 43 | 12 | 51 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | _roll_cube_data | _roll_cube_data | 288 | 291 | 288 | 288 | 72693cb671165d4d974e851df9e1fdd3788063f8 | bigcode/the-stack | train |
11ba8102b6c43a4d94f01bcc | train | function | @contextmanager
def constant_metadata(cube):
"""Do cube math without modifying units etc."""
metadata = cube.metadata
yield metadata
cube.metadata = metadata
| @contextmanager
def constant_metadata(cube):
| """Do cube math without modifying units etc."""
metadata = cube.metadata
yield metadata
cube.metadata = metadata
| = iris.coords.AuxCoord(2.0,
var_name='height',
standard_name='height',
long_name='height',
units=Unit('m'),
attributes=... | 63 | 64 | 36 | 10 | 53 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | constant_metadata | constant_metadata | 32 | 37 | 32 | 33 | 6301b133484f151bdb81648d5d874f6e3b0b04eb | bigcode/the-stack | train |
1ff6bfd772c9b9e89e35ca29 | train | function | def convert_timeunits(cube, start_year):
"""Convert time axis from malformed Year 0."""
# TODO any more weird cases?
if cube.coord('time').units == 'months since 0000-01-01 00:00:00':
real_unit = 'months since {}-01-01 00:00:00'.format(str(start_year))
elif cube.coord('time').units == 'days sinc... | def convert_timeunits(cube, start_year):
| """Convert time axis from malformed Year 0."""
# TODO any more weird cases?
if cube.coord('time').units == 'months since 0000-01-01 00:00:00':
real_unit = 'months since {}-01-01 00:00:00'.format(str(start_year))
elif cube.coord('time').units == 'days since 0000-01-01 00:00:00':
real_unit... | attributes={'positive': 'up'})
cube.add_aux_coord(height_coord, ())
@contextmanager
def constant_metadata(cube):
"""Do cube math without modifying units etc."""
metadata = cube.metadata
yield metadata
cube.metadata = metadata
def convert_timeunits(cube, star... | 64 | 64 | 199 | 10 | 53 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | convert_timeunits | convert_timeunits | 40 | 52 | 40 | 40 | 645d084e77dd44f8b93fadbcae364544040921e5 | bigcode/the-stack | train |
d859666123fc34e63a6e2743 | train | function | def _fix_bounds(cube, dim_coord):
"""Reset and fix all bounds."""
if len(cube.coord(dim_coord).points) > 1:
if cube.coord(dim_coord).has_bounds():
cube.coord(dim_coord).bounds = None
cube.coord(dim_coord).guess_bounds()
if cube.coord(dim_coord).has_bounds():
cube.coord(d... | def _fix_bounds(cube, dim_coord):
| """Reset and fix all bounds."""
if len(cube.coord(dim_coord).points) > 1:
if cube.coord(dim_coord).has_bounds():
cube.coord(dim_coord).bounds = None
cube.coord(dim_coord).guess_bounds()
if cube.coord(dim_coord).has_bounds():
cube.coord(dim_coord).bounds = da.array(
... | .attributes = glob_dict
def var_name_constraint(var_name):
""":mod:`iris.Constraint` using `var_name` of an :mod:`iris.cube.Cube`."""
return iris.Constraint(cube_func=lambda c: c.var_name == var_name)
def _fix_bounds(cube, dim_coord):
| 64 | 64 | 101 | 10 | 54 | znicholls/ESMValTool | esmvaltool/cmorizers/obs/utilities.py | Python | _fix_bounds | _fix_bounds | 234 | 244 | 234 | 234 | 0cb4137c743fa31fc9f1e11fe24154e773dcbb1d | bigcode/the-stack | train |
27062a2e35474521a531b90d | train | function | def test_board():
assert True
| def test_board():
| assert True
| def test_board():
| 4 | 64 | 8 | 4 | 0 | arzano/blackqueen | tests/test_board.py | Python | test_board | test_board | 1 | 2 | 1 | 1 | 2872931853362e5442110ad185b38793db0d3ce4 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.