uid stringlengths 24 24 | category stringclasses 2
values | granularity stringclasses 3
values | prefix stringlengths 189 2.17k | suffix stringlengths 25 21.2k | content stringlengths 48 21.3k | repo stringlengths 9 41 | path stringlengths 8 82 |
|---|---|---|---|---|---|---|---|
c7183a932a431416aa5d0df6 | class | simple | resources
from neutron.services.logapi.common import sg_callback
from neutron.services.logapi.drivers import base as log_driver_base
from neutron.services.logapi.drivers import manager as driver_mgr
from neutron.tests import base
FAKE_DRIVER = None
class FakeDriver(log_driver_base.DriverBase):
@staticmethod
| def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
| class FakeDriver(log_driver_base.DriverBase):
@staticmethod
def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
| congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py |
0cc48661c407ab0595bbb6f3 | class | simple | '],
requires_rpc=True
)
def fake_register():
global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
class TestSecurityGroupRuleCallback(base.Bas... | def setUp(self):
super(TestSecurityGroupRuleCallback, self).setUp()
self.driver_manager = driver_mgr.LoggingServiceDriverManager()
@mock.patch.object(sg_callback.SecurityGroupRuleCallBack, 'handle_event')
def test_handle_event(self, mock_sg_cb):
fake_register()
self.driver_m... | class TestSecurityGroupRuleCallback(base.BaseTestCase):
def setUp(self):
super(TestSecurityGroupRuleCallback, self).setUp()
self.driver_manager = driver_mgr.LoggingServiceDriverManager()
@mock.patch.object(sg_callback.SecurityGroupRuleCallBack, 'handle_event')
def test_handle_event(self, m... | congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py |
d4f4b62d3518c1e2cffd46d8 | function | simple | FAKE_DRIVER = None
class FakeDriver(log_driver_base.DriverBase):
@staticmethod
def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
def fa... | global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
| def fake_register():
global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
| congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py |
672a8b5362b9a1913107606c | class | simple | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.KoubeiMarketingCampaignItemMerchantactivityModifyModel import KoubeiMarketingCampaignItemMerchantactivityModifyModel
class KoubeiMar... | def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._ud... | class KoubeiMarketingCampaignItemMerchantactivityModifyRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
... | snowxmas/alipay-sdk-python-all | alipay/aop/api/request/KoubeiMarketingCampaignItemMerchantactivityModifyRequest.py |
906ed902324ba134fcb362af | function | moderate | _USER": "usr",
"REGISTRY_PW": MOCKED_PASSWORD,
"REGISTRY_SSL": "False",
}
EXPECTED_DYNAMIC_SIDECAR_ENV_VAR_NAMES = {
"REGISTRY_AUTH",
"REGISTRY_PATH",
"REGISTRY_URL",
"REGISTRY_USER",
"REGISTRY_PW",
"REGISTRY_SSL",
}
def test_dynamic_sidecar_env_vars(monkeypatch: MonkeyPatch) -> None:... | for key, value in MOCKED_BASE_REGISTRY_ENV_VARS.items():
monkeypatch.setenv(key, value)
registry_settings = RegistrySettings()
dynamic_sidecar_env_vars = get_dynamic_sidecar_env_vars(registry_settings)
print("dynamic_sidecar_env_vars:", dynamic_sidecar_env_vars)
assert len(dynamic_sidecar... | def test_dynamic_sidecar_env_vars(monkeypatch: MonkeyPatch) -> None:
for key, value in MOCKED_BASE_REGISTRY_ENV_VARS.items():
monkeypatch.setenv(key, value)
registry_settings = RegistrySettings()
dynamic_sidecar_env_vars = get_dynamic_sidecar_env_vars(registry_settings)
print("dynamic_sidecar_... | colinRawlings/osparc-simcore | services/director-v2/tests/unit/test_utils_registry.py |
48b0359be12c2be18730f21e | function | simple | ]
for i in range(n_tmpfiles)
]
(
tmpfile,
tmpfileh,
tmpfileh2,
tmpfilec,
tmpfilec2,
tmpfile0,
tmpfile1,
tmpfile2,
) = tmpfiles
def _remove_tmpfiles():
| """Try to remove defined temporary files by deleting their paths."""
for f in tmpfiles:
try:
os.remove(f)
except OSError:
pass
| def _remove_tmpfiles():
"""Try to remove defined temporary files by deleting their paths."""
for f in tmpfiles:
try:
os.remove(f)
except OSError:
pass
| sadielbartholomew/cf-python | cf/test/test_read_write.py |
88d5845dfe7641ca5c8c189d | class | simple | USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import unittest
import config
import mesh_cop
import thread_cert
from pktverify.consts import MGMT_PENDING_GET_URI, MGMT_PENDING_SET_URI, NM_CHANNEL_TLV, NM_PAN_ID_TLV, NM_NETWORK_NAME_TLV, NM_NETWORK_MESH_LOCAL_PREFIX_TLV, NM_PSKC_TLV, NM... | SUPPORT_NCP = False
TOPOLOGY = {
COMMISSIONER: {
'name': 'COMMISSIONER',
'mode': 'rdn',
'allowlist': [LEADER]
},
LEADER: {
'name': 'LEADER',
'mode': 'rdn',
'allowlist': [COMMISSIONER]
},
}
def test(... | class Cert_9_2_19_PendingDatasetGet(thread_cert.TestCase):
SUPPORT_NCP = False
TOPOLOGY = {
COMMISSIONER: {
'name': 'COMMISSIONER',
'mode': 'rdn',
'allowlist': [LEADER]
},
LEADER: {
'name': 'LEADER',
'mode': 'rdn',
... | sarah-iot/openthread | tests/scripts/thread-cert/Cert_9_2_19_PendingDatasetGet.py |
203cdfc09a85c2a956e5ec19 | function | simple | decorator's arg func..!!****")
# print(num + 1)
# my_decorator(test_in)
@my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
print("***I m decorator's arg func..!!****")
def smart_divide(func):
| def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
| def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
| PranaliRPatil/Python_OOP_Basics | decorators_test.py |
988999e8887e0129f9aeda8e | function | simple | print("End decorator\n*******###*********")
def test_in():
print("***I m decorator's arg func..!!****")
# print(num + 1)
# my_decorator(test_in)
@my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
| print("***I m decorator's arg func..!!****")
| @my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
print("***I m decorator's arg func..!!****")
| PranaliRPatil/Python_OOP_Basics | decorators_test.py |
92db5ecf77e50fd36452954c | class | simple | super().__init__()
def __repr__(self) -> str:
return (
"CustomObjectPagedQueryResponse(count=%r, total=%r, offset=%r, results=%r)"
% (self.count, self.total, self.offset, self.results)
)
class CustomObjectReference(Reference):
| "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectReferenceSchema`."
#: Optional :class:`commercetools.types.CustomObject`
obj: typing.Optional["CustomObject"]
def __init__(
self,
*,
type_id: typing.Optional["ReferenceTypeId"] = None,
id: typ... | class CustomObjectReference(Reference):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectReferenceSchema`."
#: Optional :class:`commercetools.types.CustomObject`
obj: typing.Optional["CustomObject"]
def __init__(
self,
*,
type_id: typing.Optional["R... | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py |
38de8e39e987e4963b446536 | class | simple |
self.version = version
super().__init__()
def __repr__(self) -> str:
return "CustomObjectDraft(container=%r, key=%r, value=%r, version=%r)" % (
self.container,
self.key,
self.value,
self.version,
)
class CustomObjectPagedQueryRespon... | "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectPagedQueryResponseSchema`."
#: :class:`int`
count: typing.Optional[int]
#: Optional :class:`int`
total: typing.Optional[int]
#: :class:`int`
offset: typing.Optional[int]
#: List of :class:`commercetools.types.... | class CustomObjectPagedQueryResponse(_BaseType):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectPagedQueryResponseSchema`."
#: :class:`int`
count: typing.Optional[int]
#: Optional :class:`int`
total: typing.Optional[int]
#: :class:`int`
offset: typing.Optional... | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py |
2fd2bc707b5f305238274e8d | class | simple | # DO NOT EDIT! This file is automatically generated
import datetime
import typing
from commercetools.types._abstract import _BaseType
from commercetools.types._common import BaseResource, Reference, ReferenceTypeId
__all__ = [
"CustomObject",
"CustomObjectDraft",
"CustomObjectPagedQueryResponse",
"Cu... | "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
def __init__(
self,
*,
id:... | class CustomObject(BaseResource):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
def __init__(
... | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py |
6237f3f1baa62866a70c392c | class | simple | _at=%r, last_modified_at=%r, container=%r, key=%r, value=%r)"
% (
self.id,
self.version,
self.created_at,
self.last_modified_at,
self.container,
self.key,
self.value,
)
)
cla... | "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectDraftSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
#: Optional :class:`int`
version: typing.O... | class CustomObjectDraft(_BaseType):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectDraftSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
#: Optiona... | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py |
abcc56f695aa2c9784e172c4 | function | simple | ERS_IMPORT_ERROR)),
("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
("vision", (is_vision_available, VISION_IMPORT_ERROR)),
("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
]
)
def requires_backends(obj, backends):
| if not isinstance(backends, (list, tuple)):
backends = [backends]
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
if not all(BACKENDS_MAPPING[backend][0]() for backend in backends):
raise ImportError("".join([BACKENDS_MAPPING[backend][1].format(name) for backend ... | def requires_backends(obj, backends):
if not isinstance(backends, (list, tuple)):
backends = [backends]
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
if not all(BACKENDS_MAPPING[backend][0]() for backend in backends):
raise ImportError("".join([BACKENDS_MAPPING... | MichalPitr/transformers | src/transformers/file_utils.py |
c0dc29117101bd5011b8ce72 | function | simple | return False
return importlib.util.find_spec("torch_xla.core.xla_model") is not None
def is_datasets_available():
return _datasets_available
def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
def is_py3nvml_available():
| return importlib.util.find_spec("py3nvml") is not None
| def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
95553f892e5f558acb030445 | function | simple | is_protobuf_available():
if importlib.util.find_spec("google") is None:
return False
return importlib.util.find_spec("google.protobuf") is not None
def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
def is_vision_available():
| return importlib.util.find_spec("PIL") is not None
| def is_vision_available():
return importlib.util.find_spec("PIL") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
354221589fb308c21d68e553 | function | simple | ODE_PID" in os.environ:
raise ImportError("vscode")
return importlib.util.find_spec("IPython") is not None
except (AttributeError, ImportError, KeyError):
return False
def is_scatter_available():
return _scatter_available
def is_pandas_available():
| return importlib.util.find_spec("pandas") is not None
| def is_pandas_available():
return importlib.util.find_spec("pandas") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
7131ea6b7951f9c68abed206 | function | simple | f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, current docstring is:\n{docstrings}"
)
fn.__doc__ = docstrings
return fn
return docstring_decorator
def is_remote_url(url_or_filename):
| parsed = urlparse(url_or_filename)
return parsed.scheme in ("http", "https")
| def is_remote_url(url_or_filename):
parsed = urlparse(url_or_filename)
return parsed.scheme in ("http", "https")
| MichalPitr/transformers | src/transformers/file_utils.py |
1909346ac296c20976e0627c | function | simple | This is the version of torch required to run torch.fx features.
TORCH_FX_REQUIRED_VERSION = version.parse("1.8")
_is_offline_mode = True if os.environ.get("TRANSFORMERS_OFFLINE", "0").upper() in ENV_VARS_TRUE_VALUES else False
def is_offline_mode():
| return _is_offline_mode
| def is_offline_mode():
return _is_offline_mode
| MichalPitr/transformers | src/transformers/file_utils.py |
4a6cfa1e4d02cef39d51bc09 | function | simple | 3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
return importlib.util.find_spec("apex") is not None
def is_faiss_available():
return _faiss_available
def is_scipy_available():
| return importlib.util.find_spec("scipy") is not None
| def is_scipy_available():
return importlib.util.find_spec("scipy") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
77fdd81937ee922d78bd1fe9 | function | simple | ():
return _timm_available
def is_torchaudio_available():
return _torchaudio_available
def is_speech_available():
# For now this depends on torchaudio but the exact dependency might evolve in the future.
return _torchaudio_available
def torch_only_method(fn):
| def wrapper(*args, **kwargs):
if not _torch_available:
raise ImportError(
"You need to install pytorch to use this method or class, "
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
)
else:
return fn(*args, **k... | def torch_only_method(fn):
def wrapper(*args, **kwargs):
if not _torch_available:
raise ImportError(
"You need to install pytorch to use this method or class, "
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
)
else:
... | MichalPitr/transformers | src/transformers/file_utils.py |
ccebc3ba9765725823169245 | function | simple | _is_offline_mode = True if os.environ.get("TRANSFORMERS_OFFLINE", "0").upper() in ENV_VARS_TRUE_VALUES else False
def is_offline_mode():
return _is_offline_mode
def is_torch_available():
return _torch_available
def is_torch_cuda_available():
| if is_torch_available():
import torch
return torch.cuda.is_available()
else:
return False
| def is_torch_cuda_available():
if is_torch_available():
import torch
return torch.cuda.is_available()
else:
return False
| MichalPitr/transformers | src/transformers/file_utils.py |
17b33f290e3402b90f4f8cc0 | function | simple | _docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
def add_start_docstrings_to_model_forward(*docstr):
| def docstring_decorator(fn):
class_name = f":class:`~transformers.{fn.__qualname__.split('.')[0]}`"
intro = f" The {class_name} forward method, overrides the :func:`__call__` special method."
note = r"""
.. note::
Although the recipe for forward pass needs to be defined within... | def add_start_docstrings_to_model_forward(*docstr):
def docstring_decorator(fn):
class_name = f":class:`~transformers.{fn.__qualname__.split('.')[0]}`"
intro = f" The {class_name} forward method, overrides the :func:`__call__` special method."
note = r"""
.. note::
Although th... | MichalPitr/transformers | src/transformers/file_utils.py |
130bf754440381a3e00a1778 | function | simple | _mpi_enabled", False):
return False
except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_training_run_on_sagemaker():
| return "SAGEMAKER_JOB_NAME" in os.environ
| def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
| MichalPitr/transformers | src/transformers/file_utils.py |
3d674ed696f538aece200322 | function | simple | = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
def is_local_clone(repo_path, repo_url):
| """
Checks if the folder in `repo_path` is a local clone of `repo_url`.
"""
# First double-check that `repo_path` is a git repo
if not os.path.exists(os.path.join(repo_path, ".git")):
return False
test_git = subprocess.run("git branch".split(), cwd=repo_path)
if test_git.returncode !... | def is_local_clone(repo_path, repo_url):
"""
Checks if the folder in `repo_path` is a local clone of `repo_url`.
"""
# First double-check that `repo_path` is a git repo
if not os.path.exists(os.path.join(repo_path, ".git")):
return False
test_git = subprocess.run("git branch".split(), cw... | MichalPitr/transformers | src/transformers/file_utils.py |
e169eaab5624d010e0b2f5f8 | function | simple | else:
return f"{endpoint}/{model_id}/{filename}"
if revision is None:
revision = "main"
return HUGGINGFACE_CO_PREFIX.format(model_id=model_id, revision=revision, filename=filename)
def url_to_filename(url: str, etag: Optional[str] = None) -> str:
| """
Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,
delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
identify it as a HDF5 file (see
https://github.com/tensorflow/tensorflow/... | def url_to_filename(url: str, etag: Optional[str] = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,
delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
identify it... | MichalPitr/transformers | src/transformers/file_utils.py |
f53baf9aef8e89059fbb37cf | function | simple | None else ""
built_doc = code_sample.format(**doc_kwargs)
fn.__doc__ = (fn.__doc__ or "") + "".join(docstr) + output_doc + built_doc
return fn
return docstring_decorator
def replace_return_docstrings(output_type=None, config_class=None):
| def docstring_decorator(fn):
docstrings = fn.__doc__
lines = docstrings.split("\n")
i = 0
while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
i += 1
if i < len(lines):
lines[i] = _prepare_output_docstrings(output_type, config_cl... | def replace_return_docstrings(output_type=None, config_class=None):
def docstring_decorator(fn):
docstrings = fn.__doc__
lines = docstrings.split("\n")
i = 0
while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
i += 1
if i < len(lines):
... | MichalPitr/transformers | src/transformers/file_utils.py |
d85b2b0bde97505bfb67e440 | function | simple | return importlib.util.find_spec("scipy") is not None
def is_sklearn_available():
if importlib.util.find_spec("sklearn") is None:
return False
return is_scipy_available() and importlib.util.find_spec("sklearn.metrics")
def is_sentencepiece_available():
| return importlib.util.find_spec("sentencepiece") is not None
| def is_sentencepiece_available():
return importlib.util.find_spec("sentencepiece") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
d9ad2c822d02b1309cf3ce3c | function | simple | lib_metadata.version("torch"))
_torch_fx_available = (torch_version.major, torch_version.minor) == (
TORCH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
| return _tf_available
| def is_tf_available():
return _tf_available
| MichalPitr/transformers | src/transformers/file_utils.py |
2a1dcdae6c1462617be8d608 | function | simple | .util.find_spec("psutil") is not None
def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
return importlib.util.find_spec("apex") is not None
def is_faiss_available():
| return _faiss_available
| def is_faiss_available():
return _faiss_available
| MichalPitr/transformers | src/transformers/file_utils.py |
875d025d95a9b13baeeb634d | class | simple | Returns a copy of a function f."""
# Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
... | """
A Mixin containing the functionality to push a model or tokenizer to the hub.
"""
def push_to_hub(
self,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
use_temp_dir: bool = False,
commit_message: Optional[str] = None,
organiz... | class PushToHubMixin:
"""
A Mixin containing the functionality to push a model or tokenizer to the hub.
"""
def push_to_hub(
self,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
use_temp_dir: bool = False,
commit_message: Optional[str] =... | MichalPitr/transformers | src/transformers/file_utils.py |
0e39dfd11810ab12692f1fac | function | simple |
return importlib.util.find_spec("google.protobuf") is not None
def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
def is_vision_available():
return importlib.util.find_spec("PIL") is not None
def is_in_notebook():
| try:
# Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
get_ipython = sys.modules["IPython"].get_ipython
if "IPKernelApp" not in get_ipython().config:
raise ImportError("console")
if "VSCODE_PID" in os.environ:
... | def is_in_notebook():
try:
# Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
get_ipython = sys.modules["IPython"].get_ipython
if "IPKernelApp" not in get_ipython().config:
raise ImportError("console")
if "VSCODE_PID" in o... | MichalPitr/transformers | src/transformers/file_utils.py |
5f58c1a6c56b5daf4fae0420 | function | simple | sm_distributed_training": runs_distributed_training,
"sm_deep_learning_container": dlc_container_used,
"sm_deep_learning_container_tag": dlc_tag,
"sm_account_id": account_id,
}
return sagemaker_object
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
| """
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{_torch_version}"
if is_tf_available():
ua += f"; tensorflow/{_tf_version}"
... | def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
"""
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{_torch_version}"
... | MichalPitr/transformers | src/transformers/file_utils.py |
eae3d4d3c5ff399270521e3c | function | simple | module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
def is_soundfile_availble():
return _soundfile_available
def is_timm_available():
| return _timm_available
| def is_timm_available():
return _timm_available
| MichalPitr/transformers | src/transformers/file_utils.py |
ce4d74c9b6bad4164ad19fc4 | function | simple | full_output_type}` or a tuple of
:obj:`tf.Tensor` (if ``return_dict=False`` is passed or when ``config.return_dict=False``) comprising various
elements depending on the configuration (:class:`~transformers.{config_class}`) and inputs.
"""
def _get_indent(t):
| """Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
| def _get_indent(t):
"""Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
| MichalPitr/transformers | src/transformers/file_utils.py |
4616a685f4604b33500ff5cd | function | simple | tracted)
zip_file.close()
elif tarfile.is_tarfile(output_path):
tar_file = tarfile.open(output_path)
tar_file.extractall(output_path_extracted)
tar_file.close()
else:
raise EnvironmentError(f"Archive format of {o... | try:
instance_data = requests.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
dlc_container_used = instance_data["Image"]
dlc_tag = instance_data["Image"].split(":")[1]
except Exception:
dlc_container_used = None
dlc_tag = None
sagemaker_params = json.loads(os.g... | def define_sagemaker_information():
try:
instance_data = requests.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
dlc_container_used = instance_data["Image"]
dlc_tag = instance_data["Image"].split(":")[1]
except Exception:
dlc_container_used = None
dlc_tag = None
... | MichalPitr/transformers | src/transformers/file_utils.py |
02e98f9566049dd57213105d | function | simple | json"
if not os.path.exists(meta_path):
raise EnvironmentError(f"file {meta_path} not found")
with open(meta_path, encoding="utf-8") as meta_file:
metadata = json.load(meta_file)
url = metadata["url"]
etag = metadata["etag"]
return url, etag
def get_cached_models(cache_dir: Union... | """
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape
:obj:`(model_url, etag, size_MB)`. Filenames in :obj:`cache_dir` are use to get the metadata for each model, only
urls ending with `.bin` are added.
Args:
cache_dir (:obj:`Union[str, Path]... | def get_cached_models(cache_dir: Union[str, Path] = None) -> List[Tuple]:
"""
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape
:obj:`(model_url, etag, size_MB)`. Filenames in :obj:`cache_dir` are use to get the metadata for each model, only
urls ending w... | MichalPitr/transformers | src/transformers/file_utils.py |
43cdae2150a3f1fa5e72b4c5 | function | simple | isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
def to_py_obj(obj):
| """
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_py_obj(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_py_obj(o) for o in obj]
elif is_tf_available() ... | def to_py_obj(obj):
"""
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_py_obj(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_py_obj(o) for o in obj]
eli... | MichalPitr/transformers | src/transformers/file_utils.py |
b03996bb3a24187f2f03982e | function | simple | CH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
return _tf_available
def is_onnx_available():
return _onnx_available
def is_flax_available():
| return _flax_available
| def is_flax_available():
return _flax_available
| MichalPitr/transformers | src/transformers/file_utils.py |
341b9e600c2ecc6c008f3816 | class | simple | torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
... | """
Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like
a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a regular
python dictionary.
.. warning::
You can't unpack a :obj:... | class ModelOutput(OrderedDict):
"""
Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like
a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a regular
python dictionary.
.. warning::
... | MichalPitr/transformers | src/transformers/file_utils.py |
b6916b62102df3a459cf0916 | function | simple | def is_datasets_available():
return _datasets_available
def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
| return importlib.util.find_spec("apex") is not None
| def is_apex_available():
return importlib.util.find_spec("apex") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
eace067f09cf2d5c0477c602 | function | simple |
processing steps while the latter silently ignores them.
"""
fn.__doc__ = intro + note + "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
def add_end_docstrings(*docstr):
| def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + "".join(docstr)
return fn
return docstring_decorator
| def add_end_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + "".join(docstr)
return fn
return docstring_decorator
| MichalPitr/transformers | src/transformers/file_utils.py |
1fa060f9ce61513419e36ac9 | function | moderate | List[Tuple]: List of tuples each with shape :obj:`(model_url, etag, size_MB)`
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
elif isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cached_models = []
for file in os.listdir(cache_dir):
if file.endswith(".json"... | """
Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file
and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and
then return the path
Args:
cache_dir: specify a cache direc... | def cached_path(
url_or_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
extract_compressed_file=False,
force_extract=False,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> ... | MichalPitr/transformers | src/transformers/file_utils.py |
fd9bc5ca156139375d21fcca | class | simple | "creating metadata file for {cache_path}")
meta = {"url": url, "etag": etag}
meta_path = cache_path + ".json"
with open(meta_path, "w") as meta_file:
json.dump(meta, meta_file)
return cache_path
class cached_property(property):
| """
Descriptor that mimics @property but caches output in member variable.
From tensorflow_datasets
Built-in in functools from Python 3.8.
"""
def __get__(self, obj, objtype=None):
# See docs.python.org/3/howto/descriptor.html#properties
if obj is None:
return self... | class cached_property(property):
"""
Descriptor that mimics @property but caches output in member variable.
From tensorflow_datasets
Built-in in functools from Python 3.8.
"""
def __get__(self, obj, objtype=None):
# See docs.python.org/3/howto/descriptor.html#properties
if obj... | MichalPitr/transformers | src/transformers/file_utils.py |
55df9da53319cbd6180ce00b | class | simple | avoid recursion errors
super().__setattr__(key, value)
def to_tuple(self) -> Tuple[Any]:
"""
Convert self to a tuple containing all the attributes/keys that are not ``None``.
"""
return tuple(self[k] for k in self.keys())
class ExplicitEnum(Enum):
| """
Enum with more explicit error message for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
| class ExplicitEnum(Enum):
"""
Enum with more explicit error message for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
| MichalPitr/transformers | src/transformers/file_utils.py |
02c2ed2e32b25ec8c61037ef | function | complex | ble up errors.
"""
headers = copy.deepcopy(headers)
if resume_size > 0:
headers["Range"] = f"bytes={resume_size}-"
r = requests.get(url, stream=True, proxies=proxies, headers=headers)
r.raise_for_status()
content_length = r.headers.get("Content-Length")
total = resume_size + int(cont... | """
Given a URL, look for the corresponding file in the local cache. If it's not there, download it. Then return the
path to the cached file.
Return:
Local path (string) of file or if networking is off, last version of file cached on disk.
Raises:
In case of non-recoverable file (n... | def get_from_cache(
url: str,
cache_dir=None,
force_download=False,
proxies=None,
etag_timeout=10,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> Optional[str]:
"""
Given a URL, loo... | MichalPitr/transformers | src/transformers/file_utils.py |
0d01c2f42aaee0b63eed8bb1 | function | simple | _torch(x):
import torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
| import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
| def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
| MichalPitr/transformers | src/transformers/file_utils.py |
5d1b8a3849217bc6e8034ebd | function | simple | or,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
return _tf_available
def is_onnx_available():
return _onnx_available
def is_flax_available():
return _flax_available
def is_torch_tpu_available():
| if not _torch_available:
return False
# This test is probably enough, but just in case, we unpack a bit.
if importlib.util.find_spec("torch_xla") is None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return importlib.util.find_spec("torch_x... | def is_torch_tpu_available():
if not _torch_available:
return False
# This test is probably enough, but just in case, we unpack a bit.
if importlib.util.find_spec("torch_xla") is None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return imp... | MichalPitr/transformers | src/transformers/file_utils.py |
92cd82a9a652a66fd38576fa | function | simple | hexdigest()
if etag:
etag_bytes = etag.encode("utf-8")
filename += "." + sha256(etag_bytes).hexdigest()
if url.endswith(".h5"):
filename += ".h5"
return filename
def filename_to_url(filename, cache_dir=None):
| """
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or
its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
if isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cache_... | def filename_to_url(filename, cache_dir=None):
"""
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or
its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
if isinstance(cache_dir, Path):... | MichalPitr/transformers | src/transformers/file_utils.py |
724e0a27ffab39463d8616f9 | class | simple | DO_NOT_PAD = "do_not_pad"
class TensorType(ExplicitEnum):
"""
Possible values for the ``return_tensors`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for
tab-completion in an IDE.
"""
PYTORCH = "pt"
TENSORFLOW = "tf"
NUMPY = "np"
JAX = "jax"
class _BaseLazyModule(Mo... | """
Module class that surfaces all objects but only performs associated imports when the objects are requested.
"""
# Very heavily inspired by optuna.integration._IntegrationModule
# https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
def __init__(self, name, import_stru... | class _BaseLazyModule(ModuleType):
"""
Module class that surfaces all objects but only performs associated imports when the objects are requested.
"""
# Very heavily inspired by optuna.integration._IntegrationModule
# https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
d... | MichalPitr/transformers | src/transformers/file_utils.py |
642c49d5f6e815efe7a27321 | class | simple | proj_y = np.minimum(self.proj_H - 1, proj_y)
proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1]
self.proj_y = np.copy(proj_y) # stope a copy in original order
# copy of depth in original order
self.unproj_range = np.copy(depth)
# order in decreasing depth
i... | """Class that contains LaserScan with x,y,z,r,sem_label,sem_color_label,inst_label,inst_color_label"""
EXTENSIONS_LABEL = [".label"]
def __init__(
self,
sem_color_dict=None,
sem_labels_dict=None,
project=False,
H=64,
W=1024,
fov_up=3.0,
fov_d... | class SemLaserScan(LaserScan):
"""Class that contains LaserScan with x,y,z,r,sem_label,sem_color_label,inst_label,inst_color_label"""
EXTENSIONS_LABEL = [".label"]
def __init__(
self,
sem_color_dict=None,
sem_labels_dict=None,
project=False,
H=64,
W=1024,
... | rayonnant14/PointCloudSegmentation | visualization/laserscan.py |
90b1d1948681256e4b2664a5 | class | simple | import tensorflow as tf
from tensorflow.keras.layers import BatchNormalization, Dropout, Flatten, Dense, Layer
from tensorflow.keras.backend import l2_normalize, clip, epsilon, softmax
from tensorflow.keras.regularizers import l2, get
from tensorflow.keras.applications import VGG16, ResNet50
import os
class ArcFace(L... | def __init__(
self, n_classes=10, enhance=64.0, penalty=0.50, regularizer=None, **kwargs
):
super(ArcFace, self).__init__(**kwargs)
self.n_classes = n_classes
self.s = enhance
self.m = penalty
self.regularizer = get(regularizer)
def build(self, input_shape):
... | class ArcFace(Layer):
def __init__(
self, n_classes=10, enhance=64.0, penalty=0.50, regularizer=None, **kwargs
):
super(ArcFace, self).__init__(**kwargs)
self.n_classes = n_classes
self.s = enhance
self.m = penalty
self.regularizer = get(regularizer)
def buil... | note-nota/ML_models | ArcFace/model/archs.py |
0706fa6e1b9921559a7ac3bf | class | simple | # coding: utf-8
"""
ThingsBoard REST API
ThingsBoard Professional Edition IoT platform REST API documentation. # noqa: E501
OpenAPI spec version: 3.3.3PAAS-RC1
Contact: info@thingsboard.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F40... | """NOTE: This class is auto generated by the swagger code generator program.
from tb_rest_client.api_client import ApiClient
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
at... | class AdminSettings(object):
"""NOTE: This class is auto generated by the swagger code generator program.
from tb_rest_client.api_client import ApiClient
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the valu... | samson0v/python_tb_rest_client | tb_rest_client/models/models_pe/admin_settings.py |
73a80134234f6c7c896d156c | class | simple | ',
on_delete=models.CASCADE)
def __str__(self):
return self.tweet.text
class Comment(Tweet):
parent = models.ForeignKey('Tweet',
related_name='comments',
on_delete=models.CASCADE)
def __str__(s... | user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE)
target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user)+"->"+str(self.t... | class Follow(models.Model):
user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE)
target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return s... | abhishekzgithub/tweet-django | tweetme/core/models.py |
3085da516fceea8d7eec50a5 | class | simple | .Model):
tweet = models.ForeignKey('Tweet',
related_name='like',
on_delete=models.CASCADE)
author = models.ForeignKey('auth.User',
related_name='author',
on_delete=models.CASCADE)
... | parent = models.ForeignKey('Tweet',
related_name='comments',
on_delete=models.CASCADE)
def __str__(self):
return self.text
| class Comment(Tweet):
parent = models.ForeignKey('Tweet',
related_name='comments',
on_delete=models.CASCADE)
def __str__(self):
return self.text
| abhishekzgithub/tweet-django | tweetme/core/models.py |
636676a7f74632b11893d152 | class | simple | , blank=False, editable=False)
likes_count = models.IntegerField(default=0, null=False, blank=False, editable=False)
comments_count = models.IntegerField(default=0, null=False, blank=False, editable=False)
def __str__(self):
return self.text
class Like(models.Model):
| tweet = models.ForeignKey('Tweet',
related_name='like',
on_delete=models.CASCADE)
author = models.ForeignKey('auth.User',
related_name='author',
on_delete=models.CASCADE)
def __s... | class Like(models.Model):
tweet = models.ForeignKey('Tweet',
related_name='like',
on_delete=models.CASCADE)
author = models.ForeignKey('auth.User',
related_name='author',
on_delete=mod... | abhishekzgithub/tweet-django | tweetme/core/models.py |
ae5426bd9e8fcbd37d11f2df | class | simple | # class PublicTimeLine(models.Model):
# username=models.ForeignKey('auth.User',related_name='public_timeline',on_delete=models.CASCADE)
# public_tweet = models.ForeignKey('Tweet',
# related_name='public_tweet',
# on_delete=models.CASCADE)
class ... | username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE)
followers = models.ManyToManyField('auth.User', related_name='followed_by')
date=models.DateTimeField(auto_now_add=True)
count=models.IntegerField(default=1)
def __str__(self):
return str(self.... | class UserFollower(models.Model):
username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE)
followers = models.ManyToManyField('auth.User', related_name='followed_by')
date=models.DateTimeField(auto_now_add=True)
count=models.IntegerField(default=1)
def __str... | abhishekzgithub/tweet-django | tweetme/core/models.py |
b7cd9ea75bde465a7c4701f1 | class | simple | ='followed_by')
date=models.DateTimeField(auto_now_add=True)
count=models.IntegerField(default=1)
def __str__(self):
return str(self.username)+"->"+str(self.followers)
class Meta:
db_table='user_follower'
class HashTag(Tweet):
| name=models.CharField(max_length=10,unique=True)
tweet=models.ManyToManyField(Tweet,related_name='hastag')
def __str__(self):
return self.name
class Meta:
db_table='hashtag'
| class HashTag(Tweet):
name=models.CharField(max_length=10,unique=True)
tweet=models.ManyToManyField(Tweet,related_name='hastag')
def __str__(self):
return self.name
class Meta:
db_table='hashtag'
| abhishekzgithub/tweet-django | tweetme/core/models.py |
2001d5980fdaab195b1a65d7 | class | simple | # coding: utf-8
"""
Lightly API
Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@lightly... | """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = ap... | class SamplingsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
... | Tekrific/lightly | lightly/openapi_generated/swagger_client/api/samplings_api.py |
f6757eda7b6c374d8ca1cf7b | class | simple | .exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.get_request import GetRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.relation.relation_command import RelationCommand
from pyopenproject.model impo... | def __init__(self, connection, relation):
super().__init__(connection)
self.relation = relation
def execute(self):
try:
json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute()
return rel.Relation(json_obj)
except RequestErro... | class Find(RelationCommand):
def __init__(self, connection, relation):
super().__init__(connection)
self.relation = relation
def execute(self):
try:
json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute()
return rel.Relation(json_o... | webu/pyopenproject | pyopenproject/business/services/command/relation/find.py |
ecd2b4088f3c3489d120c29f | class | simple |
from aiokafka.structs import TopicPartition
from aiokafka.abc import ConsumerRebalanceListener
# All test coroutines will be treated as marked.
pytestmark = pytest.mark.asyncio
@pytest.fixture
async def subscription_state():
return SubscriptionState()
class MockListener(ConsumerRebalanceListener):
| def on_partitions_revoked(self, revoked):
pass
def on_partitions_assigned(self, assigned):
pass
| class MockListener(ConsumerRebalanceListener):
def on_partitions_revoked(self, revoked):
pass
def on_partitions_assigned(self, assigned):
pass
| hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 169