language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_5.py
{ "start": 115, "end": 246 }
class ____: class InnerClass: pass def failing_func(self) -> "InnerClass": return self.InnerClass()
OuterClass
python
pytorch__pytorch
test/test_numa_binding.py
{ "start": 1163, "end": 31605 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self._mock_file_path_to_contents: dict[str, str] = {} self._mock_device_properties: list[MockDeviceProperties] = [] self._mock_num_logical_cpus = 0 self._mock_num_numa_nodes = 0 self._mock_num_sockets = 0...
NumaBindingTest
python
Lightning-AI__lightning
src/lightning/pytorch/_graveyard/tpu.py
{ "start": 2866, "end": 3319 }
class ____(XLAPrecision): """Legacy class. Use :class:`~lightning.pytorch.plugins.precision.xlabf16.XLAPrecision` instead. """ def __init__(self, *args: Any, **kwargs: Any) -> None: rank_zero_deprecation( "The `TPUBf16PrecisionPlugin` class is deprecated. Use" " `light...
TPUBf16PrecisionPlugin
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 39095, "end": 40218 }
class ____: def __init__( self, token: milvus_types.AnalyzerToken, with_hash: bool = False, with_detail: bool = False ): self.dict = {"token": token.token} if with_detail: self.dict["start_offset"] = token.start_offset self.dict["end_offset"] = token.end_offset ...
AnalyzeToken
python
numba__numba
numba/core/rewrites/static_binop.py
{ "start": 132, "end": 1146 }
class ____(Rewrite): """ Detect constant arguments to select binops. """ # Those operators can benefit from a constant-inferred argument rhs_operators = {'**'} def match(self, func_ir, block, typemap, calltypes): self.static_lhs = {} self.static_rhs = {} self.block = bl...
DetectStaticBinops
python
realpython__materials
python-pydantic/pydantic_models.py
{ "start": 211, "end": 317 }
class ____(Enum): HR = "HR" SALES = "SALES" IT = "IT" ENGINEERING = "ENGINEERING"
Department
python
realpython__materials
intro-to-threading/prodcom_queue.py
{ "start": 122, "end": 1855 }
class ____(queue.Queue): def __init__(self): super().__init__(maxsize=10) def get_message(self, name): logging.debug("%s:about to get from queue", name) value = self.get() logging.debug("%s:got %d from queue", name, value) return value def set_message(self, value, n...
Pipeline
python
pennersr__django-allauth
tests/apps/socialaccount/providers/lemonldap/tests.py
{ "start": 246, "end": 725 }
class ____(OAuth2TestsMixin, TestCase): provider_id = LemonLDAPProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "email": "dwho@example.com", "sub": "dwho", "preferred_username": "dw...
LemonLDAPTests
python
scipy__scipy
scipy/_build_utils/tempita/_tempita.py
{ "start": 1414, "end": 1930 }
class ____(Exception): """Exception raised while parsing a template """ def __init__(self, message, position, name=None): Exception.__init__(self, message) self.position = position self.name = name def __str__(self): msg = ' '.join(self.args) if self.position: ...
TemplateError
python
GoogleCloudPlatform__python-docs-samples
dataflow/run-inference/main.py
{ "start": 2067, "end": 4920 }
class ____(beam.PTransform): """Asks an language model a prompt message and gets its responses. Attributes: model_name: HuggingFace model name compatible with AutoModelForSeq2SeqLM. state_dict_path: File path to the model's state_dict, can be in Cloud Storage. max_response_tokens: Maxim...
AskModel
python
Netflix__metaflow
test/core/tests/card_timeout.py
{ "start": 72, "end": 1843 }
class ____(MetaflowTest): """ Test that checks if the card decorator works as intended with the timeout decorator. # This test set an artifact in the steps and also set a timeout to the card argument. # It will assert the artifact to be None. """ PRIORITY = 2 SKIP_GRAPHS = [ "simple...
CardTimeoutTest
python
django__django
tests/model_options/apps.py
{ "start": 224, "end": 346 }
class ____(AppConfig): name = "model_options" default_auto_field = "django.db.models.TextField"
ModelPKNonAutoConfig
python
ray-project__ray
python/ray/train/v2/_internal/execution/worker_group/worker_group.py
{ "start": 2372, "end": 3177 }
class ____: """Context for a worker group. This stores the context that is shared when starting a worker group. Attributes: run_attempt_id: The ID of the run attempt. train_fn_ref: An object store reference to the training function to execute. num_workers: The number of workers in ...
WorkerGroupContext
python
PyCQA__pylint
tests/functional/r/regression/regression_6531_crash_index_error.py
{ "start": 152, "end": 707 }
class ____: def __init__(self): self.balance = 0 def add_cash(self, earned): self.balance += earned def spend_cash(self, spent): self.balance -= spent @pytest.fixture def my_wallet(): '''Returns a Wallet instance with a zero balance''' return Wallet() @pytest.mark.paramet...
Wallet
python
python-poetry__poetry
src/poetry/console/exceptions.py
{ "start": 356, "end": 436 }
class ____(PoetryConsoleError): pass @dataclasses.dataclass
GroupNotFoundError
python
google__jax
jax/_src/source_info_util.py
{ "start": 8502, "end": 9027 }
class ____(contextlib.ContextDecorator): __slots__ = ['name', 'prev'] def __init__(self, name: str): self.name = name def __enter__(self): self.prev = prev = _source_info_context.context name_stack = prev.name_stack.extend(self.name) _source_info_context.context = prev.replace(name_stack=name_st...
ExtendNameStackContextManager
python
huggingface__transformers
src/transformers/data/processors/squad.py
{ "start": 22937, "end": 23045 }
class ____(SquadProcessor): train_file = "train-v1.1.json" dev_file = "dev-v1.1.json"
SquadV1Processor
python
django__django
tests/auth_tests/test_auth_backends.py
{ "start": 1785, "end": 3858 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user("test", "test@example.com", "test") def test_get_user_permissions(self): self.assertEqual(self.user.get_user_permissions(), {"user_perm"}) async def test_aget_user_permissions(self): ...
BaseBackendTest
python
lxml__lxml
src/lxml/html/tests/test_html5parser.py
{ "start": 12527, "end": 12876 }
class ____(ElementMaker): def __init__(self, namespaceHTMLElements=True): initargs = dict(makeelement=html_parser.makeelement) if namespaceHTMLElements: initargs.update(namespace=XHTML_NAMESPACE, nsmap={None: XHTML_NAMESPACE}) ElementMaker.__init__(sel...
HTMLElementMaker
python
huggingface__transformers
src/transformers/utils/quantization_config.py
{ "start": 2507, "end": 6800 }
class ____: """ Mixin class for quantization config """ quant_method: QuantizationMethod @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters. Args: ...
QuantizationConfigMixin
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_low_rank_update_test.py
{ "start": 10951, "end": 11593 }
class ____( BaseLinearOperatorLowRankUpdatetest, linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest): """A = L + UDU^H, D > 0, L > 0 ==> A > 0 and we can use a Cholesky.""" _use_diag_update = True _is_diag_update_positive = True _use_v = True def tearDown(self): config.enable_tens...
LinearOperatorLowRankUpdatetestWithDiagNotSquare
python
ray-project__ray
python/ray/train/v2/_internal/exceptions.py
{ "start": 2803, "end": 3038 }
class ____(RayTrainError): """Exception raised when the worker group fails to start. Example scenario: A worker is scheduled onto a node that dies while the worker actor is initializing. """
WorkerGroupStartupFailedError
python
huggingface__transformers
src/transformers/models/fsmt/tokenization_fsmt.py
{ "start": 3225, "end": 17873 }
class ____(PreTrainedTokenizer): """ Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following: - Moses preprocessing and tokenization. - Normalizing all inputs text. - The arguments `special_tokens` and the function `set_special_tokens`, can...
FSMTTokenizer
python
davidhalter__jedi
jedi/api/helpers.py
{ "start": 2374, "end": 6787 }
class ____(Exception): @property def error_leaf(self): return self.args[0] def _get_code_for_stack(code_lines, leaf, position): # It might happen that we're on whitespace or on a comment. This means # that we would not get the right leaf. if leaf.start_pos >= position: # If we're n...
OnErrorLeaf
python
huggingface__transformers
src/transformers/models/pegasus_x/configuration_pegasus_x.py
{ "start": 798, "end": 7954 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`PegasusXModel`]. It is used to instantiate a PEGASUS-X model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar co...
PegasusXConfig
python
django__django
tests/handlers/test_exception.py
{ "start": 221, "end": 1917 }
class ____(SimpleTestCase): def get_suspicious_environ(self): payload = FakePayload("a=1&a=2&a=3\r\n") return { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, ...
ExceptionHandlerTests
python
getsentry__sentry
tests/acceptance/test_project_release_tracking_settings.py
{ "start": 132, "end": 1248 }
class ____(AcceptanceTestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user("foo@example.com") self.org = self.create_organization(name="Rowdy Tiger", owner=None) self.team = self.create_team(organization=self.org, name="Mariachi Band") ...
ProjectReleaseTrackingSettingsTest
python
google__jax
tests/pallas/pallas_test.py
{ "start": 95935, "end": 97535 }
class ____(PallasBaseTest): def test_pass_weird_tuple_into_pallas_call(self): xt = WeirdTuple(x0=jnp.ones((8, 8)), x1=jnp.zeros((8,))) def kernel(xt_ref, ot_ref): xt = xt_ref[...] ot_ref[...] = xt ot = self.pallas_call(kernel, out_shape=jax.typeof(xt))(xt) self.assertArraysEqual(ot.x0,...
PallasHiJaxTest
python
ApeWorX__ape
tests/functional/conversion/test_address.py
{ "start": 812, "end": 1450 }
class ____: @pytest.fixture(scope="class") def converter(self): return HexAddressConverter() def test_is_convertible_hex_str(self, converter): assert not converter.is_convertible("0x123") def test_is_convertible_address(self, converter, owner): # Is already an address! ...
TestHexAddressConverter
python
huggingface__transformers
src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py
{ "start": 5985, "end": 6098 }
class ____(SamVisionNeck): def __init__(self, config): super().__init__(config)
DeepseekVLSamVisionNeck
python
numba__numba
numba/core/typing/templates.py
{ "start": 612, "end": 8018 }
class ____(object): """ The signature of a function call or operation, i.e. its argument types and return type. """ # XXX Perhaps the signature should be a BoundArguments, instead # of separate args and pysig... __slots__ = '_return_type', '_args', '_recvr', '_pysig' def __init__(self,...
Signature
python
pytorch__pytorch
test/test_utils.py
{ "start": 35230, "end": 35912 }
class ____(TestCase): def test_import_imported(self): self.assertIn("os", sys.modules) os_module = try_import("os") self.assertIs(os_module, os) def test_import_existing(self): self.assertNotIn("imaplib", sys.modules) imaplib_module = try_import("imaplib") self.a...
TestTryImport
python
pydata__xarray
xarray/backends/zarr.py
{ "start": 5929, "end": 20812 }
class ____(BackendArray): __slots__ = ("_array", "dtype", "shape") def __init__(self, zarr_array): # some callers attempt to evaluate an array if an `array` property exists on the object. # we prefix with _ to avoid this inference. # TODO type hint this? self._array = zarr_arra...
ZarrArrayWrapper
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 9086, "end": 17630 }
class ____(object): ''' A Router is an ordered collection of route->target pairs. It is used to efficiently match WSGI requests against a number of routes and return the first target that satisfies the request. The target may be anything, usually a string, ID or callable object. A route cons...
Router
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 13917, "end": 17426 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testSameDynamicShape(self): with self.cached_session(): scalar = constant_op.constant(2.0) scalar1 = array_ops.placeholder(dtype=dtypes.float32) vector = [0.3, 0.4, 0.5] vector1 = array_ops.placeholder(dtype=dtypes.float32, sh...
DynamicShapeTest
python
mlflow__mlflow
mlflow/gateway/app.py
{ "start": 7359, "end": 8762 }
class ____(BaseModel): endpoints: list[Endpoint] next_page_token: str | None = None model_config = ConfigDict( json_schema_extra={ "example": { "endpoints": [ { "name": "openai-chat", "endpoint_type": "l...
ListEndpointsResponse
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/api.py
{ "start": 10966, "end": 13084 }
class ____: """Represent a registry of :py:class:`RendezvousHandler` backends.""" _registry: dict[str, RendezvousHandlerCreator] def __init__(self) -> None: self._registry = {} def register(self, backend: str, creator: RendezvousHandlerCreator) -> None: """Register a new rendezvous ba...
RendezvousHandlerRegistry
python
tensorflow__tensorflow
tensorflow/python/keras/utils/generic_utils.py
{ "start": 8190, "end": 15503 }
class ____(object): """Keeps track of shared object configs when serializing.""" def __enter__(self): if _shared_object_disabled(): return None global SHARED_OBJECT_SAVING # Serialization can happen at a number of layers for a number of reasons. # We may end up with a case where we're openi...
SharedObjectSavingScope
python
pytorch__pytorch
tools/setup_helpers/cmake.py
{ "start": 1554, "end": 19253 }
class ____: "Manages cmake." def __init__(self, build_dir: str = BUILD_DIR) -> None: self._cmake_command = CMake._get_cmake_command() self.build_dir = build_dir @property def _cmake_cache_file(self) -> str: r"""Returns the path to CMakeCache.txt. Returns: str...
CMake
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 225247, "end": 228014 }
class ____(unittest.TestCase): def checkNonblock(self, s, nonblock=True, timeout=0.0): if nonblock: self.assertEqual(s.type, socket.SOCK_STREAM) self.assertEqual(s.gettimeout(), timeout) self.assertTrue( fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_...
NonblockConstantTest
python
numpy__numpy
numpy/ma/core.py
{ "start": 27438, "end": 27838 }
class ____: """ DomainGreaterEqual(v)(x) is True where x < v. """ def __init__(self, critical_value): "DomainGreaterEqual(v)(x) = true where x < v" self.critical_value = critical_value def __call__(self, x): "Executes the call behavior." with np.errstate(invalid='i...
_DomainGreaterEqual
python
scikit-learn__scikit-learn
sklearn/linear_model/_huber.py
{ "start": 4339, "end": 12752 }
class ____(LinearModel, RegressorMixin, BaseEstimator): """L2-regularized linear regression model that is robust to outliers. The Huber Regressor optimizes the squared loss for the samples where ``|(y - Xw - c) / sigma| < epsilon`` and the absolute loss for the samples where ``|(y - Xw - c) / sigma| > ...
HuberRegressor
python
PyCQA__pylint
tests/functional/r/recursion/recursion_error_crash_2683.py
{ "start": 124, "end": 335 }
class ____: def __init__(self): self.count = 5 def method(self): records = [] for _ in []: records += [] records = records[:self.count] records.sort()
Cls
python
django__django
tests/prefetch_related/tests.py
{ "start": 53245, "end": 56435 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.book1 = BookWithYear.objects.create(title="Poems", published_year=2010) cls.book2 = BookWithYear.objects.create(title="More poems", published_year=2011) cls.author1 = AuthorWithAge.objects.create( name="Jane", fir...
MultiTableInheritanceTest
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py
{ "start": 48484, "end": 70347 }
class ____(Qwen3VLMoePreTrainedModel): base_model_prefix = "model" _checkpoint_conversion_mapping = {} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False config: Qwen3VLMoeConfig _no_split_modules = ["Qwen3VLMoeTextDecoderLayer", "Qwen3VLMoeVisionBlock"] def __init__(self, ...
Qwen3VLMoeModel
python
plotly__plotly.py
plotly/callbacks.py
{ "start": 45, "end": 2856 }
class ____: def __init__( self, ctrl=None, alt=None, shift=None, meta=None, button=None, buttons=None, **_ ): self._ctrl = ctrl self._alt = alt self._meta = meta self._shift = shift self._button = button self._buttons = buttons def __repr__(self): ...
InputDeviceState
python
sympy__sympy
sympy/physics/secondquant.py
{ "start": 80582, "end": 86376 }
class ____: def __init__(self, label): self._counterVar = 0 self._label = label def _set_counter(self, value): """ Sets counter to value. """ self._counterVar = value @property def _counter(self): """ What counter is currently at. ...
_SymbolFactory
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 16667, "end": 16878 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("ACTIVE", "PENDING_DELETION", "SUSPENDED")
OauthApplicationCreateAuditEntryState
python
pyqtgraph__pyqtgraph
tests/test_reload.py
{ "start": 299, "end": 2977 }
class ____(pg.QtCore.QObject): sig = pg.QtCore.Signal() # https://www.riverbankcomputing.com/pipermail/pyqt/2024-August/045989.html # @pg.QtCore.Slot() def fn(self): print("{msg}") """ def remove_cache(mod): if os.path.isfile(mod+'c'): os.remove(mod+'c') cachedir = os.path.join...
C
python
rq__rq
tests/test_worker.py
{ "start": 1369, "end": 1406 }
class ____(Queue): pass
CustomQueue
python
getsentry__sentry
tests/apidocs/endpoints/integration_platform/test_sentry_app_external_issues.py
{ "start": 314, "end": 1534 }
class ____(APIDocsTestCase): def setUp(self) -> None: self.org = self.create_organization(owner=self.user, name="Rowdy Tiger") self.project = self.create_project(organization=self.org) self.group = self.create_group(project=self.project) self.sentry_app = self.create_sentry_app( ...
SentryAppDocsTest
python
optuna__optuna
optuna/samplers/_cmaes.py
{ "start": 1314, "end": 27102 }
class ____(BaseSampler): """A sampler using `cmaes <https://github.com/CyberAgentAILab/cmaes>`__ as the backend. Example: Optimize a simple quadratic function by using :class:`~optuna.samplers.CmaEsSampler`. .. code-block:: console $ pip install cmaes .. testcode:: ...
CmaEsSampler
python
arrow-py__arrow
arrow/locales.py
{ "start": 77602, "end": 80895 }
class ____(Locale): names = ["he", "he-il"] past = "לפני {0}" future = "בעוד {0}" and_word = "ו" timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { "now": "הרגע", "second": "שנייה", "seconds": "{0} שניות", "minute": "דקה", "mi...
HebrewLocale
python
huggingface__transformers
src/transformers/utils/dummy_mistral_common_objects.py
{ "start": 129, "end": 309 }
class ____(metaclass=DummyObject): _backends = ["mistral-common"] def __init__(self, *args, **kwargs): requires_backends(self, ["mistral-common"])
MistralCommonBackend
python
langchain-ai__langchain
libs/partners/mistralai/tests/integration_tests/test_chat_models.py
{ "start": 1873, "end": 1935 }
class ____(BaseModel): name: str authors: list[str]
Book
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 69848, "end": 70305 }
class ____(Response, BottleException): def __init__(self, body='', status=None, headers=None, **more_headers): super(HTTPResponse, self).__init__(body, status, headers, **more_headers) def apply(self, response): response._status_code = self._status_code response._status_line = self._sta...
HTTPResponse
python
getsentry__sentry
tests/sentry/auth/test_email.py
{ "start": 235, "end": 2800 }
class ____(TestCase): def setUp(self) -> None: self.user1 = self.create_user() self.user2 = self.create_user() def test_no_match(self) -> None: result = resolve_email_to_user("no_one@example.com") assert result is None def test_single_match(self) -> None: result = r...
EmailResolverTest
python
pandas-dev__pandas
pandas/tests/reductions/test_reductions.py
{ "start": 45200, "end": 47311 }
class ____: # Note: the name TestCategoricalSeriesReductions indicates these tests # were moved from a series-specific test file, _not_ that these tests are # intended long-term to be series-specific @pytest.mark.parametrize("function", ["min", "max"]) def test_min_max_unordered_raises(self, func...
TestCategoricalSeriesReductions
python
wandb__wandb
wandb/sdk/launch/registry/abstract.py
{ "start": 106, "end": 1146 }
class ____(ABC): """Abstract base class for registries.""" uri: str async def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry. Returns: (str, str): The username and password. """ raise NotImplementedError @...
AbstractRegistry
python
pytorch__pytorch
test/inductor/test_aot_inductor.py
{ "start": 279282, "end": 280734 }
class ____(LoggingTestCase): @make_logging_test(dynamic=logging.DEBUG) def test_shape_env_reuse(self, records): # make sure ShapeEnv is only created once and reused afterwards class Foo(torch.nn.Module): def forward(self, x): return x + 2 inputs = (torch.rand...
AOTInductorLoggingTest
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 98201, "end": 99726 }
class ____: def test_unsupported_storage(self): settings = { "FEEDS": { "unsupported://uri": {}, }, } crawler = get_crawler(settings_dict=settings) with pytest.raises(NotConfigured): FeedExporter.from_crawler(crawler) def test_...
TestFeedExportInit
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py
{ "start": 2620, "end": 4028 }
class ____(AwsBaseWaiterTrigger): """ Asynchronously poll the boto3 API and wait for the JobFlow to finish executing. :param job_flow_id: The id of the job flow to wait for. :param waiter_delay: The amount of time in seconds to wait between attempts. :param waiter_max_attempts: The maximum number o...
EmrCreateJobFlowTrigger
python
Lightning-AI__lightning
src/lightning/pytorch/serve/servable_module_validator.py
{ "start": 800, "end": 7264 }
class ____(Callback): """The ServableModuleValidator validates to validate a model correctly implement the ServableModule API. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Arguments: optimization: The format in which the model should be tested while being ser...
ServableModuleValidator
python
pytorch__pytorch
torch/__init__.py
{ "start": 86628, "end": 87574 }
class ____(_TorchCompileInductorWrapper): compiler_name = "aotinductor" def __init__(self, mode, options, dynamic): super().__init__(mode, options, dynamic) self.apply_options({"cpp_wrapper": True}) self.apply_options({"aot_inductor.package": True}) def __call__(self, model_, input...
_TorchCompileAOTInductorWrapper
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/adam.py
{ "start": 1325, "end": 10709 }
class ____(optimizer_v2.OptimizerV2): r"""Optimizer that implements the Adam algorithm. Adam optimization is a stochastic gradient descent method that is based on adaptive estimation of first-order and second-order moments. According to [Kingma et al., 2014](http://arxiv.org/abs/1412.6980), the method is ...
Adam
python
pypa__pip
src/pip/_vendor/urllib3/packages/six.py
{ "start": 14152, "end": 14841 }
class ____(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] ...
Module_six_moves_urllib_error
python
mlflow__mlflow
examples/flower_classifier/train.py
{ "start": 3214, "end": 9361 }
class ____(Callback): """ Keras callback for logging metrics and final model with MLflow. Metrics are logged after every epoch. The logger keeps track of the best model based on the validation metric. At the end of the training, the best model is logged with MLflow. """ def __init__(self, mode...
MlflowLogger
python
huggingface__transformers
src/transformers/pipelines/fill_mask.py
{ "start": 972, "end": 11064 }
class ____(Pipeline): _load_processor = False _load_image_processor = False _load_feature_extractor = False _load_tokenizer = True """ Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling examples](../task_summary#masked-language-modeli...
FillMaskPipeline
python
pypa__hatch
src/hatch/env/plugin/interface.py
{ "start": 662, "end": 36280 }
class ____(ABC): """ Example usage: ```python tab="plugin.py" from hatch.env.plugin.interface import EnvironmentInterface class SpecialEnvironment(EnvironmentInterface): PLUGIN_NAME = "special" ... ``` ```python tab="hooks.py" from hatchling.plugin import hookimpl ...
EnvironmentInterface
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 2317, "end": 9497 }
class ____(AwsBaseOperator[SageMakerHook]): """ This is the base operator for all SageMaker operators. :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and a...
SageMakerBaseOperator
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/utils/asserts.py
{ "start": 2815, "end": 4935 }
class ____(FormatChecker): @staticmethod def check_datetime(value: str) -> bool: valid_format = timestamp_regex.match(value) try: pendulum.parse(value, strict=False) except ValueError: valid_time = False else: valid_time = True return v...
CustomFormatChecker
python
protocolbuffers__protobuf
python/google/protobuf/internal/reflection_test.py
{ "start": 95923, "end": 96397 }
class ____(unittest.TestCase): def testEqualityWithMutualRecursion(self): first_proto = unittest_pb2.TestMutualRecursionA() second_proto = unittest_pb2.TestMutualRecursionA() self.assertEqual(first_proto, second_proto) first_proto.bb.a.bb.optional_int32 = 23 self.assertNotEqual(first_proto, secon...
MutualRecursionEqualityTest
python
Netflix__metaflow
metaflow/plugins/pypi/conda_decorator.py
{ "start": 293, "end": 10418 }
class ____(StepDecorator): """ Specifies the Conda environment for the step. Information in this decorator will augment any attributes set in the `@conda_base` flow-level decorator. Hence, you can use `@conda_base` to set packages required by all steps and use `@conda` to specify step-specific ...
CondaStepDecorator
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 69719, "end": 73286 }
class ____: def __init__( self, naming_authority: NamingAuthority | None, profession_items: Iterable[str], profession_oids: Iterable[ObjectIdentifier] | None, registration_number: str | None, add_profession_info: bytes | None, ) -> None: if naming_authorit...
ProfessionInfo
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py
{ "start": 2608, "end": 2849 }
class ____(TypedDict): a: int td10: TD10 = {"a": 0} n1: TD8 = td10 # This should generate an error because "a" is writable # and required in TD10 but writable and not required in # TD9, which means it can be deleted. n2: TD9 = td10
TD10
python
doocs__leetcode
solution/3600-3699/3607.Power Grid Maintenance/Solution.py
{ "start": 563, "end": 1285 }
class ____: def processQueries( self, c: int, connections: List[List[int]], queries: List[List[int]] ) -> List[int]: uf = UnionFind(c + 1) for u, v in connections: uf.union(u, v) st = [SortedList() for _ in range(c + 1)] for i in range(1, c + 1): s...
Solution
python
pallets__click
src/click/utils.py
{ "start": 5591, "end": 16109 }
class ____: def __init__(self, file: t.IO[t.Any]) -> None: self._file: t.IO[t.Any] = file def __getattr__(self, name: str) -> t.Any: return getattr(self._file, name) def __enter__(self) -> KeepOpenFile: return self def __exit__( self, exc_type: type[BaseExcepti...
KeepOpenFile
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
{ "start": 72372, "end": 78591 }
class ____: def __init__( self, fwd_mask_info: mask_info_lib.MaskInfo, dq_mask_info: mask_info_lib.MaskInfo | None, dkv_mask_info: mask_info_lib.MaskInfo | None, **kwargs, ): self.kwargs = kwargs self.fwd_mask_info = fwd_mask_info self.dq_mask_info = dq_mask_info self....
SplashAttentionKernel
python
getsentry__sentry
src/sentry/integrations/utils/metrics.py
{ "start": 16552, "end": 17331 }
class ____(EventLifecycleMetric): """An instance to be recorded of a integration proxy event.""" interaction_type: IntegrationProxyEventType def get_metrics_domain(self) -> str: return "integration_proxy" def get_interaction_type(self) -> str: return str(self.interaction_type) de...
IntegrationProxyEvent
python
zostera__django-bootstrap4
example/app/forms.py
{ "start": 2732, "end": 2772 }
class ____(TestForm): pass
ContactForm
python
great-expectations__great_expectations
great_expectations/data_context/store/gx_cloud_store_backend.py
{ "start": 1176, "end": 2275 }
class ____(str, Enum): V0 = "V0" V1 = "V1" V2 = "V2" def get_user_friendly_error_message( http_exc: requests.exceptions.HTTPError, log_level: int = logging.WARNING ) -> str: # TODO: define a GeCloud service/client for this & other related behavior support_message = [] response: requests.Re...
EndpointVersion
python
lazyprogrammer__machine_learning_examples
rl3/es_mnist.py
{ "start": 1076, "end": 3695 }
class ____: def __init__(self, D, M, K): self.D = D self.M = M self.K = K def init(self): D, M, K = self.D, self.M, self.K self.W1 = np.random.randn(D, M) / np.sqrt(D) self.b1 = np.zeros(M) self.W2 = np.random.randn(M, K) / np.sqrt(M) self.b2 = np.zeros(K) def forward(self, X): ...
ANN
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/data_version.py
{ "start": 9102, "end": 9219 }
class ____(Enum): MISSING = "MISSING" STALE = "STALE" FRESH = "FRESH" @functools.total_ordering
StaleStatus
python
PyCQA__pylint
tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.py
{ "start": 1309, "end": 1762 }
class ____: """test_ignores_non_property_return_type_numpy Example of a class function trying to use `type` as return documentation in a numpy style docstring """ def foo_method(self): # [missing-return-doc, missing-return-type-doc] """int: docstring ... Raises ------ ...
Foo
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 10459, "end": 10562 }
class ____(torch.nn.Module): def forward(self, x): return (x,) @dataclasses.dataclass
ToTuple
python
tensorflow__tensorflow
configure.py
{ "start": 1651, "end": 49467 }
class ____(Exception): pass def is_windows(): return platform.system() == 'Windows' def is_linux(): return platform.system() == 'Linux' def is_macos(): return platform.system() == 'Darwin' def is_ppc64le(): return platform.machine() == 'ppc64le' def is_s390x(): return platform.machine() == 's390x'...
UserInputError
python
conda__conda
conda/exceptions.py
{ "start": 32131, "end": 32275 }
class ____(CondaError, IndexError): def __init__(self, message: str): msg = f"{message}" super().__init__(msg)
CondaIndexError
python
Textualize__textual
docs/examples/guide/widgets/hello05.py
{ "start": 363, "end": 680 }
class ____(Static): """Display a greeting.""" def on_mount(self) -> None: self.action_next_word() def action_next_word(self) -> None: """Get a new hello and update the content area.""" hello = next(hellos) self.update(f"[@click='next_word']{hello}[/], [b]World[/b]!")
Hello
python
ethereum__web3.py
web3/exceptions.py
{ "start": 7622, "end": 7815 }
class ____(PersistentConnectionError, Web3ValueError): """ Raised when the read buffer limit is reached while reading data from a persistent connection. """
ReadBufferLimitReached
python
walkccc__LeetCode
solutions/3208. Alternating Groups II/3208.py
{ "start": 0, "end": 339 }
class ____: def numberOfAlternatingGroups(self, colors: list[int], k: int) -> int: n = len(colors) ans = 0 alternating = 1 for i in range(n + k - 2): alternating = (1 if colors[i % n] == colors[(i - 1) % n] else alternating + 1) if alternating >= k: ans += 1 ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 28246, "end": 28648 }
class ____(SemiIncrementalMixin, GithubStream): """ API docs: https://docs.github.com/en/rest/issues/events?apiVersion=2022-11-28#list-issue-events-for-a-repository """ cursor_field = "created_at" def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str: return f"repos/{stre...
IssueEvents
python
allegroai__clearml
clearml/backend_api/services/v2_23/dataviews.py
{ "start": 98713, "end": 116770 }
class ____(Response): """ Response of dataviews.get_all endpoint. :param dataviews: List of dataviews :type dataviews: Sequence[Dataview] :param scroll_id: Scroll ID that can be used with the next calls to get_all to retrieve more data :type scroll_id: str """ _service = "datav...
GetAllResponse
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 179237, "end": 180719 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, start_date: str, is_sandbox: bool, client_id: Optional[str] = None, client_secret: Optional[str] = None, refresh_token: Optional[str] = None, ): """Airbyte Source for Pa...
PaypalTransactionSource
python
bokeh__bokeh
src/bokeh/core/has_props.py
{ "start": 27682, "end": 27744 }
class ____(TypedDict): name: str default: Any
OverrideDef
python
huggingface__transformers
src/transformers/models/openai/tokenization_openai.py
{ "start": 1088, "end": 4997 }
class ____(TokenizersBackend): """ Construct a GPT Tokenizer (backed by HuggingFace's *tokenizers* library). Based on Byte-Pair-Encoding with the following peculiarities: - lower case all inputs - uses BERT's BasicTokenizer for pre-BPE tokenization This tokenizer inherits from [`TokenizersBack...
OpenAIGPTTokenizer
python
yandexdataschool__Practical_RL
week06_policy_based/atari_wrappers.py
{ "start": 7128, "end": 7292 }
class ____(RewardWrapper): """Modifes reward to be in {-1, 0, 1} by taking sign of it.""" def reward(self, reward): return np.sign(reward)
ClipReward
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 17036, "end": 18553 }
class ____(BaseModel): names: list[SelfReferencing] # noqa: F821 """ ) SelfReferencing = module.SelfReferencing if sys.version_info >= (3, 10): assert ( repr(SelfReferencing.model_fields['names']) == 'FieldInfo(annotation=list[SelfReferencing], required=True)' ) # test...
SelfReferencing
python
pennersr__django-allauth
allauth/account/forms.py
{ "start": 26382, "end": 26873 }
class ____(forms.Form): password = PasswordField(label=_("Password"), autocomplete="current-password") def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) def clean_password(self): password = self.cleaned_data.get("password") ...
ReauthenticateForm
python
jazzband__django-waffle
waffle/models.py
{ "start": 13579, "end": 15406 }
class ____(BaseModel): """A feature switch. Switches are active, or inactive, globally. """ name = models.CharField( max_length=100, unique=True, help_text=_('The human/computer readable name.'), verbose_name=_('Name'), ) active = models.BooleanField( d...
AbstractBaseSwitch
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called.py
{ "start": 1846, "end": 2071 }
class ____(abc.ABC): def __init__(self, param: int) -> None: self.param = param + 1 def abstract_method(self) -> str: """This needs to be implemented.""" raise NotImplementedError()
AbstractBase