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
django__django
tests/ordering/models.py
{ "start": 1579, "end": 1733 }
class ____(models.Model): article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE) class Meta: ordering = ("article",)
Reference
python
gevent__gevent
src/greentest/3.11/test_ftplib.py
{ "start": 32263, "end": 33789 }
class ____(TestCase): def setUp(self): self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6, encoding=DEFAULT_ENCODING) self.server.start() self.client = ftplib.FTP(timeout=TIMEOUT, encoding=DEFAULT_ENCODING) ...
TestIPv6Environment
python
django-compressor__django-compressor
compressor/parser/__init__.py
{ "start": 451, "end": 1149 }
class ____(LazyObject): options = ( # TODO: make lxml.html parser first again (html.parser.__name__, HtmlParser), # fast and part of the Python stdlib ("lxml.html", LxmlParser), # lxml, extremely fast ) def __init__(self, content): self._wrapped = None self._setup(...
AutoSelectParser
python
pytorch__pytorch
test/profiler/test_memory_profiler.py
{ "start": 3399, "end": 11851 }
class ____(TestCase): def gradient_detected( self, prof: torch.profiler.profile, ctx: _EventType, grad_tensor: torch.Tensor, parameter: Optional[torch.Tensor] = None, ) -> None: # This is not an exhaustive check, but for the purpose of unit testing # it is...
TestIdentifyGradients
python
pytorch__pytorch
test/functorch/test_eager_transforms.py
{ "start": 2627, "end": 3560 }
class ____: def tearDown(self): # Ensure that in the case of a test failure, the next test won't fail # because of a previous call to _vmap_increment_nesting that wasn't undone # i.e. test_vmap_free_tensor fails when PYTORCH_TEST_WITH_DYNAMO=1 # and the call to increment nesting is n...
VmapTearDownMixin
python
celery__celery
celery/security/certificate.py
{ "start": 1079, "end": 2765 }
class ____: """X.509 certificate.""" def __init__(self, cert: str) -> None: with reraise_errors( 'Invalid certificate: {0!r}', errors=(ValueError,) ): self._cert = load_pem_x509_certificate( ensure_bytes(cert), backend=default_backend()) if n...
Certificate
python
django__django
tests/model_fields/test_mixins.py
{ "start": 283, "end": 1760 }
class ____(SimpleTestCase): def setUp(self): self.instance = Foo() self.field = Example() def test_cache_name_not_implemented(self): with self.assertRaises(NotImplementedError): FieldCacheMixin().cache_name def test_cache_name(self): result = Example().cache_nam...
FieldCacheMixinTests
python
redis__redis-py
redis/connection.py
{ "start": 85376, "end": 101205 }
class ____(MaintNotificationsAbstractConnectionPool, ConnectionPoolInterface): """ Create a connection pool. ``If max_connections`` is set, then this object raises :py:class:`~redis.exceptions.ConnectionError` when the pool's limit is reached. By default, TCP connections are created unless ``connec...
ConnectionPool
python
encode__django-rest-framework
tests/authentication/test_authentication.py
{ "start": 10376, "end": 14588 }
class ____: """Token authentication""" model = None path = None header_prefix = 'Token ' def setUp(self): self.csrf_client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user =...
BaseTokenAuthTests
python
spack__spack
lib/spack/spack/vendor/jsonschema/exceptions.py
{ "start": 4605, "end": 5394 }
class ____(Exception): """ A validator was asked to validate an instance against an unknown type. """ def __init__(self, type, instance, schema): self.type = type self.instance = instance self.schema = schema def __unicode__(self): pschema = pprint.pformat(self.sche...
UnknownType
python
walkccc__LeetCode
solutions/2466. Count Ways To Build Good Strings/2466.py
{ "start": 0, "end": 444 }
class ____: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: MOD = 1_000_000_007 ans = 0 # dp[i] := the number of good strings with length i dp = [1] + [0] * high for i in range(1, high + 1): if i >= zero: dp[i] = (dp[i] + dp[i - zero]) % MOD if i >...
Solution
python
davidhalter__parso
parso/utils.py
{ "start": 696, "end": 4628 }
class ____(NamedTuple): major: int minor: int micro: int def split_lines(string: str, keepends: bool = False) -> Sequence[str]: r""" Intended for Python code. In contrast to Python's :py:meth:`str.splitlines`, looks at form feeds and other special characters as normal text. Just splits ``\...
Version
python
getsentry__sentry
tests/sentry/integrations/msteams/test_client.py
{ "start": 7378, "end": 11056 }
class ____(TestCase): def setUp(self) -> None: self.expires_at = 1594768808 self.organization = self.create_organization(owner=self.user) self.integration = self.create_integration( organization=self.organization, provider="msteams", external_id="foobar", ...
MsTeamsProxyApiClientTest
python
huggingface__transformers
tests/models/sam3_tracker/test_modeling_sam3_tracker.py
{ "start": 1505, "end": 2571 }
class ____: def __init__( self, hidden_size=32, input_image_size=128, patch_size=16, mask_input_channels=8, num_point_embeddings=4, hidden_act="gelu", ): self.hidden_size = hidden_size self.input_image_size = input_image_size self.p...
Sam3TrackerPromptEncoderTester
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 9182, "end": 9576 }
class ____(resource.Resource): """Return a response with headers set from the JSON request body""" def render(self, request): body = json.loads(request.content.read().decode()) for header_name, header_value in body.items(): request.responseHeaders.addRawHeader(header_name, header_va...
ResponseHeadersResource
python
kamyu104__LeetCode-Solutions
Python/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.py
{ "start": 39, "end": 524 }
class ____(object): def minOperations(self, k): """ :type k: int :rtype: int """ # reference: https://stackoverflow.com/questions/15390807/integer-square-root-in-python def isqrt(n): a, b = n, (n+1)//2 while b < a: a, b = b, (b+...
Solution
python
Pylons__pyramid
tests/test_view.py
{ "start": 32030, "end": 39721 }
class ____(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def _makeOne(self, environ=None): from pyramid.decorator import reify from pyramid.view import ViewMethodsMixin if environ is None: envi...
TestViewMethodsMixin
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/up_to_date/steps.py
{ "start": 4463, "end": 8066 }
class ____(Step): SYFT_DOCKER_IMAGE = "anchore/syft:v1.6.0" context: ConnectorContext title: str = "Get dependency updates" def get_syft_container(self) -> dagger.Container: home_dir = os.path.expanduser("~") config_path = os.path.join(home_dir, ".docker", "config.json") config_...
GetDependencyUpdates
python
huggingface__transformers
src/transformers/models/dbrx/modeling_dbrx.py
{ "start": 2050, "end": 8392 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: DbrxConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.co...
DbrxRotaryEmbedding
python
kubernetes-client__python
kubernetes/client/models/v1_cluster_trust_bundle_projection.py
{ "start": 383, "end": 8041 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ClusterTrustBundleProjection
python
pandas-dev__pandas
asv_bench/benchmarks/groupby.py
{ "start": 9887, "end": 10739 }
class ____: def setup_cache(self): N = 10**5 key1 = np.tile(np.arange(100, dtype=object), 1000) key2 = key1.copy() np.random.shuffle(key1) np.random.shuffle(key2) df = DataFrame( { "key1": key1, "key2": key2, ...
MultiColumn
python
scipy__scipy
scipy/interpolate/tests/test_rbfinterp.py
{ "start": 3307, "end": 17159 }
class ____: @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT)) def test_scale_invariance_1d(self, kernel, xp): # Verify that the functions in _SCALE_INVARIANT are insensitive to the # shape parameter (when smoothing == 0) in 1d. seq = Halton(1, scramble=False, seed=np.random.Ra...
_TestRBFInterpolator
python
apache__airflow
providers/standard/src/airflow/providers/standard/decorators/external_python.py
{ "start": 1211, "end": 2724 }
class ____(_PythonDecoratedOperator, ExternalPythonOperator): """Wraps a Python callable and captures args/kwargs when called for execution.""" template_fields = ExternalPythonOperator.template_fields custom_operator_name: str = "@task.external_python" def external_python_task( python: str | None = N...
_PythonExternalDecoratedOperator
python
fluentpython__example-code-2e
05-data-classes/class/coordinates.py
{ "start": 221, "end": 340 }
class ____: def __init__(self, lat, lon): self.lat = lat self.lon = lon # end::COORDINATE[]
Coordinate
python
bokeh__bokeh
src/bokeh/core/property/numeric.py
{ "start": 5048, "end": 5936 }
class ____(Float): """ Accept non-negative numeric values. Args: default (float, optional) : A default value for attributes created from this property to have. help (str or None, optional) : A documentation string for this property. (default: None) Example: ...
Size
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator_test.py
{ "start": 2755, "end": 4301 }
class ____(object): def __init__(self, between_graph=False, should_init=None, should_checkpoint=None, should_save_summary=None): self.extended = MockExtended(between_graph, should_init, should_checkpoint, should_save_sum...
MockStrategy
python
python-openxml__python-docx
src/docx/oxml/table.py
{ "start": 8904, "end": 9378 }
class ____(BaseOxmlElement): """`w:gridCol` element, child of `w:tblGrid`, defines a table column.""" w: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "w:w", ST_TwipsMeasure ) @property def gridCol_idx(self) -> int: """Index of this `w:gridCol` element...
CT_TblGridCol
python
PrefectHQ__prefect
src/integrations/prefect-dbt/tests/core/test_tracker.py
{ "start": 6889, "end": 7705 }
class ____: """Test dependency management functionality.""" @pytest.mark.parametrize( "dependencies", [ ["dep1", "dep2", "dep3"], [], ], ) def test_node_dependencies_set_and_get(self, sample_node_id, dependencies): """Test that set_node_dependenci...
TestNodeTaskTrackerDependencies
python
getsentry__sentry
src/sentry/utils/sdk_crashes/path_replacer.py
{ "start": 499, "end": 1409 }
class ____(PathReplacer): """ Replaces the path with the part of the path after the first pattern match. For example, if the pattern is `/sentry/.*` and the path is `/Users/sentry/myfile.js` then the path will be replaced with `/sentry/myfile.js`. :param patterns: A set of regular expressions. :pa...
KeepAfterPatternMatchPathReplacer
python
numpy__numpy
numpy/lib/tests/test_arraypad.py
{ "start": 30650, "end": 36257 }
class ____: def test_check_simple(self): a = np.arange(100) a = np.pad(a, (25, 20), 'reflect') b = np.array( [25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
TestReflect
python
fsspec__filesystem_spec
fsspec/implementations/jupyter.py
{ "start": 3643, "end": 4002 }
class ____(fsspec.spec.AbstractBufferedFile): def _upload_chunk(self, final=False): """Never uploads a chunk until file is done Not suitable for large files """ if final is False: return False self.buffer.seek(0) data = self.buffer.read() self.fs....
SimpleFileWriter
python
apache__airflow
providers/standard/src/airflow/providers/standard/decorators/python.py
{ "start": 1150, "end": 3243 }
class ____(DecoratedOperator, PythonOperator): """ Wraps a Python callable and captures args/kwargs when called for execution. :param python_callable: A reference to an object that is callable :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function (templated...
_PythonDecoratedOperator
python
PyCQA__pylint
tests/functional/u/unused/unused_import_class_def_keyword.py
{ "start": 610, "end": 715 }
class ____: CONF = "Hello World" SCHEMA = A(arg=CONF) # Test normal instantiation A(arg=DOMAIN_3)
B
python
pyca__cryptography
tests/hazmat/primitives/test_pbkdf2hmac.py
{ "start": 482, "end": 3394 }
class ____: def test_already_finalized(self, backend): kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) kdf.derive(b"password") with pytest.raises(AlreadyFinalized): kdf.derive(b"password2") kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend) key =...
TestPBKDF2HMAC
python
getsentry__sentry
tests/sentry/auth/services/test_model.py
{ "start": 898, "end": 1351 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization() def test_serializes_correct_fields(self) -> None: key = ApiKey.objects.create( organization_id=self.create_organization().id, scope_list=["org:read"] )...
TestRpcApiKey
python
doocs__leetcode
solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py
{ "start": 0, "end": 722 }
class ____: __slots__ = ["children"] def __init__(self): self.children = [None] * 2 def insert(self, x: int): node = self for i in range(30, -1, -1): v = x >> i & 1 if node.children[v] is None: node.children[v] = Trie() node = nod...
Trie
python
huggingface__transformers
src/transformers/models/instructblipvideo/modular_instructblipvideo.py
{ "start": 1616, "end": 6543 }
class ____(PreTrainedConfig): r""" [`InstructBlipVideoConfig`] is the configuration class to store the configuration of a [`InstructBlipVideoForConditionalGeneration`]. It is used to instantiate a Instructblipvideo model according to the specified arguments, defining the vision model, Q-Former model and...
InstructBlipVideoConfig
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 38974, "end": 39749 }
class ____(BaseModel): model_config = ConfigDict( extra="forbid", ) action: Annotated[ Literal["update"], Field(description="The action to be performed on the entities.", title="Action") ] entities: Annotated[ list[ConnectionBody], Field(description="A list of entities to be ...
BulkUpdateActionConnectionBody
python
pandas-dev__pandas
pandas/tests/arithmetic/test_datetime64.py
{ "start": 912, "end": 4957 }
class ____: # Comparison tests for datetime64 vectors fully parametrized over # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison # tests will eventually end up here. def test_compare_zerodim(self, tz_naive_fixture, box_with_array): # Test comparison with zero-dimensional ...
TestDatetime64ArrayLikeComparisons
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/app_testing/tutorial001/main.py
{ "start": 403, "end": 442 }
class ____(HeroBase): pass
HeroCreate
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/single_string_slots.py
{ "start": 191, "end": 299 }
class ____: __slots__: str = f"bar" def __init__(self, bar): self.bar = bar # Non-errors.
Foo
python
sqlalchemy__sqlalchemy
test/sql/test_external_traversal.py
{ "start": 47629, "end": 54805 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" @classmethod def setup_test_class(cls): global t1, t2 t1 = table( "table1", column("col1"), column("col2"), column("col3"), column("col4"), ) ...
ColumnAdapterTest
python
apache__airflow
providers/pinecone/src/airflow/providers/pinecone/operators/pinecone.py
{ "start": 3312, "end": 5977 }
class ____(BaseOperator): """ Create a pod based index in Pinecone. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CreatePodIndexOperator` :param conn_id: The connection id to use when connecting to Pinecone. :param ind...
CreatePodIndexOperator
python
aimacode__aima-python
logic4e.py
{ "start": 32561, "end": 43293 }
class ____(Agent): """An agent for the wumpus world that does logical inference. [Figure 7.20]""" def __init__(self, dimentions): self.dimrow = dimentions self.kb = WumpusKB(self.dimrow) self.t = 0 self.plan = list() self.current_position = WumpusPosition(1, 1, 'UP') ...
HybridWumpusAgent
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 23318, "end": 23980 }
class ____(nn.Module): def __init__(self, config: FunnelConfig, block_index: int) -> None: super().__init__() self.attention = FunnelRelMultiheadAttention(config, block_index) self.ffn = FunnelPositionwiseFFN(config) def forward( self, query: torch.Tensor, key: t...
FunnelLayer
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/tracing_compilation_test.py
{ "start": 72410, "end": 74754 }
class ____(test.TestCase, parameterized.TestCase): @test_util.run_in_graph_and_eager_modes def testMultipleDeviceCheck(self): def f(): with ops.device('cpu'): return test_ops.device_placement_op() func = compiled_fn(f) with ops.device('cpu:0'): output = self.evaluate(func()) ...
DevicePlacementTest
python
zarr-developers__zarr-python
src/zarr/errors.py
{ "start": 2979, "end": 3135 }
class ____(ZarrFutureWarning): """ A warning raised to indicate that a feature is outside the Zarr specification. """
UnstableSpecificationWarning
python
numba__numba
numba/cuda/testing.py
{ "start": 390, "end": 1614 }
class ____(SerialMixin, TestCase): """ For tests that use a CUDA device. Test methods in a CUDATestCase must not be run out of module order, because the ContextResettingTestCase may reset the context and destroy resources used by a normal CUDATestCase if any of its tests are run between tests from a...
CUDATestCase
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 47686, "end": 48855 }
class ____(util.MdCase): """Test custom formatter that is broken and causes a failure.""" extension = ['pymdownx.superfences'] extension_configs = { 'pymdownx.superfences': { 'custom_fences': [ { 'name': 'test', 'class': 'test', ...
TestSuperFencesCustomBrokenFail
python
eriklindernoren__ML-From-Scratch
mlfromscratch/unsupervised_learning/k_means.py
{ "start": 186, "end": 3530 }
class ____(): """A simple clustering method that forms k clusters by iteratively reassigning samples to the closest centroids and after that moves the centroids to the center of the new formed clusters. Parameters: ----------- k: int The number of clusters the algorithm will form. ...
KMeans
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 18259, "end": 19487 }
class ____(Reduce): """Computes the (weighted) mean of the given values. For example, if values is [1, 3, 5, 7] then the mean is 4. If the weights were specified as [1, 1, 0, 0] then the mean would be 2. This metric creates two variables, `total` and `count` that are used to compute the average of `values`....
Mean
python
euske__pdfminer
pdfminer/pdfdocument.py
{ "start": 1452, "end": 1755 }
class ____: debug = False def get_trailer(self): raise NotImplementedError def get_objids(self): return [] # Must return # (strmid, index, genno) # or (None, pos, genno) def get_pos(self, objid): raise KeyError(objid) ## PDFXRef ##
PDFBaseXRef
python
django-haystack__django-haystack
haystack/management/commands/haystack_info.py
{ "start": 133, "end": 766 }
class ____(BaseCommand): help = "Provides feedback about the current Haystack setup." # noqa A003 def handle(self, **options): """Provides feedback about the current Haystack setup.""" unified_index = connections[DEFAULT_ALIAS].get_unified_index() indexed = unified_index.get_indexed_m...
Command
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 25381, "end": 26477 }
class ____(Num): """ A decimal. Attributes ---------- value : decimal.Decimal Value of the node, represented as a Decimal object. """ __slots__ = () def __init__(self, parent: Optional["VyperNode"] = None, **kwargs: dict): super().__init__(parent, **kwargs) if ...
Decimal
python
tensorflow__tensorflow
tensorflow/compiler/tests/xla_dump_to_test.py
{ "start": 957, "end": 1732 }
class ____(xla_test.XLATestCase): """Test that ensures --XLA_FLAGS=--dump_to_xla=<dir> produces output.""" def _compute(self): with self.session() as sess, self.device_scope(): data = np.array([0], dtype=np.float32) indices = np.array([0], dtype=np.int32) d = array_ops.placeholder(data.dtype,...
XlaDumpToDirTest
python
google__pytype
pytype/state_test.py
{ "start": 2348, "end": 2750 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self._program = cfg.Program() self._node = self._program.NewCFGNode("test") def check_binding(self, expected, binding, **varnames): self.assertEqual(len(binding.origins), 1) self.assertEqual(self._node, binding.origins[0].where) ...
ConditionTestBase
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/provider.py
{ "start": 319, "end": 720 }
class ____(ProviderAccount): def get_brand(self): ret = super(OpenIDAccount, self).get_brand() domain = urlparse(self.account.uid).netloc provider_map = {} for d, p in provider_map.items(): if domain.lower().find(d) >= 0: ret = p break ...
OpenIDAccount
python
PyCQA__pylint
doc/data/messages/n/notimplemented-raised/bad.py
{ "start": 0, "end": 88 }
class ____: def bore(self): raise NotImplemented # [notimplemented-raised]
Worm
python
facebook__pyre-check
client/command_arguments.py
{ "start": 995, "end": 1498 }
class ____(enum.Enum): _value_: str TRACE_EVENT = "trace_event" COLD_START_PHASES = "cold_start_phases" INCREMENTAL_UPDATES = "incremental_updates" TAINT = "taint" INDIVIDUAL_TABLE_SIZES = "individual_table_sizes" TOTAL_SHARED_MEMORY_SIZE_OVER_TIME = "total_shared_memory_size_over_time" ...
ProfileOutput
python
getsentry__sentry
src/sentry/api/endpoints/organization_on_demand_metrics_estimation_stats.py
{ "start": 1170, "end": 1828 }
class ____(Enum): """ Enum to represent the quality of the stats estimation """ NO_DATA = "no-data" # no data available (not even metrics) NO_INDEXED_DATA = "no-indexed-data" # no indexed data available POOR_INDEXED_DATA = ( "poor-indexed-data" # indexed data available but missing mo...
StatsQualityEstimation
python
pydata__xarray
xarray/tests/test_treenode.py
{ "start": 6057, "end": 8465 }
class ____: def test_set_child_node(self) -> None: john: TreeNode = TreeNode() mary: TreeNode = TreeNode() john._set_item("Mary", mary) assert john.children["Mary"] is mary assert isinstance(mary, TreeNode) assert mary.children == {} assert mary.parent is joh...
TestSetNodes
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin_ini/custom_constructor.py
{ "start": 33, "end": 370 }
class ____(BaseModel): id: int name: str birth_year: int def __init__(self, id: int) -> None: # MYPY: note: "Person" defined here super().__init__(id=id, name='Patrick', birth_year=1991) Person(1) Person(id=1) Person(name='Patrick') # MYPY: error: Unexpected keyword argument "name" for "Perso...
Person
python
wandb__wandb
tests/unit_tests/test_launch/test_runner/test_kubernetes.py
{ "start": 7158, "end": 8551 }
class ____: def __init__(self): self.pods = dict() self.secrets = [] self.calls = {"delete": 0} self.namespaces = [] async def list_namespaced_pod( self, label_selector=None, namespace="default", field_selector=None ): ret = [] for _, pod in self.pods...
MockCoreV1Api
python
lepture__authlib
authlib/integrations/django_oauth1/authorization_server.py
{ "start": 2627, "end": 4560 }
class ____(BaseServer): def __init__(self, client_model, token_model, token_generator=None): super().__init__(client_model, token_model, token_generator) self._temporary_expires_in = self._config.get( "temporary_credential_expires_in", 86400 ) self._temporary_credential_k...
CacheAuthorizationServer
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 12270, "end": 13610 }
class ____(NetworkError): """ Raised when the network with the given name was not found. """ def __init__( self, network: str, ecosystem: Optional[str] = None, options: Optional[Collection[str]] = None, ): self.network = network options = options or [...
NetworkNotFoundError
python
huggingface__transformers
src/transformers/models/vilt/image_processing_vilt_fast.py
{ "start": 1336, "end": 9075 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = IMAGENET_STANDARD_MEAN image_std = IMAGENET_STANDARD_STD size = {"shortest_edge": 384} do_resize = True do_rescale = True do_normalize = True size_divisor = 32 do_pad = True default_to_square =...
ViltImageProcessorFast
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 70682, "end": 70964 }
class ____(_PrintableStructure): _fields_ = [ ('isGridLicenseSupported', c_int), ('licensableFeaturesCount', c_uint), ('gridLicensableFeatures', c_nvmlGridLicensableFeature_v2_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT), ]
c_nvmlGridLicensableFeatures_v2_t
python
ray-project__ray
python/ray/train/tensorflow/tensorflow_predictor.py
{ "start": 603, "end": 9625 }
class ____(DLPredictor): """A predictor for TensorFlow models. Args: model: A Tensorflow Keras model to use for predictions. preprocessor: A preprocessor used to transform data batches prior to prediction. model_weights: List of weights to use for the model. use_gpu:...
TensorflowPredictor
python
has2k1__plotnine
plotnine/guides/guide_colorbar.py
{ "start": 13533, "end": 16280 }
class ____(GuideElements): """ Access & calculate theming for the colobar """ @cached_property def text(self): size = self.theme.getp(("legend_text_colorbar", "size")) ha = self.theme.getp(("legend_text_colorbar", "ha")) va = self.theme.getp(("legend_text_colorbar", "va")) ...
GuideElementsColorbar
python
kamyu104__LeetCode-Solutions
Python/divide-nodes-into-the-maximum-number-of-groups.py
{ "start": 1663, "end": 3324 }
class ____(object): def magnificentSets(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ def bfs(u): group = [] q = [u] lookup[u] = True while q: new_q = [] f...
Solution2
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator.py
{ "start": 1497, "end": 2131 }
class ____(object): """Specify how distribute coordinator runs.""" # The default mode where distribute coordinator will run as a standalone # client and connects to remote servers for training. Each remote server can # use the distribute coordinator binary with task_type set correctly which # will then turn ...
CoordinatorMode
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 13988, "end": 17229 }
class ____(AbstractSource): def check_connection(self, logger, config) -> Tuple[bool, any]: try: timezone = config.get("timezone", "UTC") if timezone not in pendulum.timezones: return False, "The supplied timezone is invalid." app_id = config["app_id"] ...
SourceAppsflyer
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_aliases.py
{ "start": 8024, "end": 10356 }
class ____(GenerationBase): """ Test the ``generate_aliases`` signal handler behaviour. """ def get_signal_handler(self): return signal_handlers.generate_aliases def test_empty(self): """ Thumbnails are not generated if there isn't anything to generate... """ ...
GenerationTest
python
davidhalter__jedi
jedi/inference/compiled/__init__.py
{ "start": 729, "end": 2651 }
class ____(LazyValueWrapper): """ This class represents exact values, that makes operations like additions and exact boolean values possible, while still being a "normal" stub. """ def __init__(self, compiled_value): self.inference_state = compiled_value.inference_state self._compile...
ExactValue
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
{ "start": 27861, "end": 32610 }
class ____: """Represent a rendezvous join operation.""" def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action: state = ctx.state # A closed rendezvous means that it no longer accepts new nodes. if state.closed: if ctx.node in state.redundancy_list: ...
_RendezvousJoinOp
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 41673, "end": 41902 }
class ____(Callback): def on_validation_epoch_end(self, trainer, pl_module): if not trainer.sanity_checking and trainer.current_epoch == 1: raise RuntimeError("Trouble!")
TroubledCallbackOnValidationEpochEnd
python
walkccc__LeetCode
solutions/1019. Next Greater Node In Linked List/1019.py
{ "start": 0, "end": 359 }
class ____: def nextLargerNodes(self, head: ListNode) -> list[int]: ans = [] stack = [] while head: while stack and head.val > ans[stack[-1]]: index = stack.pop() ans[index] = head.val stack.append(len(ans)) ans.append(head.val) head = head.next for i in stack...
Solution
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 68353, "end": 70838 }
class ____(Locator): """ Place ticks at every integer multiple of a base plus an offset. """ def __init__(self, base=1.0, offset=0.0): """ Parameters ---------- base : float > 0, default: 1.0 Interval between ticks. offset : float, default: 0.0 ...
MultipleLocator
python
aimacode__aima-python
logic.py
{ "start": 50240, "end": 66401 }
class ____(Agent): """ [Figure 7.20] An agent for the wumpus world that does logical inference. """ def __init__(self, dimentions): self.dimrow = dimentions self.kb = WumpusKB(self.dimrow) self.t = 0 self.plan = list() self.current_position = WumpusPosition(1...
HybridWumpusAgent
python
xlwings__xlwings
xlwings/constants.py
{ "start": 52083, "end": 52488 }
class ____: xlDataLabelsShowBubbleSizes = 6 # from enum XlDataLabelsType xlDataLabelsShowLabel = 4 # from enum XlDataLabelsType xlDataLabelsShowLabelAndPercent = 5 # from enum XlDataLabelsType xlDataLabelsShowNone = -4142 # from enum XlDataLabelsType xlDataLabelsShowPercent = 3 # from enum XlDa...
DataLabelsType
python
tox-dev__tox
src/tox/tox_env/python/pip/req/args.py
{ "start": 2829, "end": 3322 }
class ____(Action): def __call__( self, parser: ArgumentParser, # noqa: ARG002 namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None, # noqa: ARG002 ) -> None: if getattr(namespace, self.dest, None) is None: setat...
AddSortedUniqueAction
python
pypa__warehouse
tests/unit/macaroons/test_models.py
{ "start": 225, "end": 1364 }
class ____: @pytest.mark.parametrize( ("value", "expected"), [ ( [ caveats.ProjectName(normalized_names=["example"]), caveats.Expiration(expires_at=1705876828, not_before=1705875828), ], [[1, ["exampl...
TestCaveats
python
getsentry__sentry
src/sentry/integrations/bitbucket/webhook.py
{ "start": 2616, "end": 3922 }
class ____(SCMWebhook, ABC): @property def provider(self) -> str: return IntegrationProviderSlug.BITBUCKET.value def update_repo_data(self, repo: Repository, event: Mapping[str, Any]) -> None: """ Given a webhook payload, update stored repo data if needed. NB: Assumes event...
BitbucketWebhook
python
walkccc__LeetCode
solutions/1776. Car Fleet II/1776.py
{ "start": 0, "end": 817 }
class ____: def getCollisionTimes(self, cars: list[list[int]]) -> list[float]: ans = [] stack = [] # (pos, speed, collisionTime) def getCollisionTime( car: tuple[int, int, int], pos: int, speed: int) -> float: return (car[0] - pos) / (speed - car[1]) for pos, speed in ...
Solution
python
GoogleCloudPlatform__python-docs-samples
healthcare/api-client/v1beta1/fhir/fhir_resources_test.py
{ "start": 1265, "end": 9498 }
class ____(Exception): """Operation is not yet complete""" @retry.Retry(predicate=retry.if_exception_type(OperationNotComplete)) def wait_for_operation(operation_name: str): operation = ( client.projects() .locations() .datasets() .operations() .get(name=operation_name)...
OperationNotComplete
python
walkccc__LeetCode
solutions/263. Ugly Number/263.py
{ "start": 0, "end": 180 }
class ____: def isUgly(self, n: int) -> bool: if n == 0: return False for prime in 2, 3, 5: while n % prime == 0: n //= prime return n == 1
Solution
python
getsentry__sentry
src/sentry/integrations/types.py
{ "start": 637, "end": 1061 }
class ____(StrEnum): SLACK = "slack" DISCORD = "discord" MSTEAMS = "msteams" JIRA = "jira" JIRA_SERVER = "jira_server" AZURE_DEVOPS = "vsts" GITHUB = "github" GITHUB_ENTERPRISE = "github_enterprise" GITLAB = "gitlab" BITBUCKET = "bitbucket" BITBUCKET_SERVER = "bitbucket_serve...
IntegrationProviderSlug
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 35973, "end": 36198 }
class ____(Rank): """Subtraction of two ranks""" left: Rank right: Rank def to_dict(self) -> Dict[str, Any]: return {"$sub": {"left": self.left.to_dict(), "right": self.right.to_dict()}} @dataclass
Sub
python
lepture__authlib
authlib/oauth2/rfc6749/errors.py
{ "start": 4987, "end": 5307 }
class ____(OAuth2Error): """The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. https://tools.ietf.org/html/rfc6749#section-5.2 """ error = "invalid_scope" description = "The requested scope is invalid, unknown, or malformed."
InvalidScopeError
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/definition/time_window.py
{ "start": 1901, "end": 47507 }
class ____(PartitionsDefinition, IHaveNew): r"""A set of partitions where each partition corresponds to a time window. The provided cron_schedule determines the bounds of the time windows. E.g. a cron_schedule of "0 0 \\* \\* \\*" will result in daily partitions that start at midnight and end at midnight o...
TimeWindowPartitionsDefinition
python
great-expectations__great_expectations
tests/core/test_expectation_suite.py
{ "start": 7592, "end": 27423 }
class ____: """Tests related to the 1.0 CRUD API.""" expectation_suite_name = "test-suite" @pytest.fixture def expectation(self) -> gxe.ExpectColumnValuesToBeInSet: return gxe.ExpectColumnValuesToBeInSet( column="a", value_set=[1, 2, 3], result_format="BASIC...
TestCRUDMethods
python
mlflow__mlflow
examples/paddle/train_high_level_api.py
{ "start": 180, "end": 965 }
class ____(paddle.nn.Layer): def __init__(self): super().__init__() self.fc_ = paddle.nn.Linear(13, 1, None) def forward(self, inputs): pred = self.fc_(inputs) return pred model = paddle.Model(UCIHousing()) optim = paddle.optimizer.Adam(learning_rate=0.01, parameters=model.par...
UCIHousing
python
mwaskom__seaborn
tests/_core/test_plot.py
{ "start": 49835, "end": 59087 }
class ____: def check_pair_grid(self, p, x, y): xys = itertools.product(y, x) for (y_i, x_j), subplot in zip(xys, p._subplots): ax = subplot["ax"] assert ax.get_xlabel() == "" if x_j is None else x_j assert ax.get_ylabel() == "" if y_i is None else y_i ...
TestPairInterface
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/execution.py
{ "start": 280, "end": 424 }
class ____( NamedTuple("_ScheduledExecutionSkipped", []), ScheduledExecutionResult ): pass @whitelist_for_serdes
ScheduledExecutionSkipped
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/ternary_test.py
{ "start": 704, "end": 1391 }
class ____(op_bench.TorchBenchmarkBase): def init(self, M, N, device, dtype, op_func): self.inputs = { "input_": torch.rand((M, N), device=device).to(dtype=dtype), "tensor1": torch.rand((M, N), device=device).to(dtype=dtype), "tensor2": torch.rand((M, N), device=device).t...
TernaryOpBenchmark
python
python-poetry__poetry
tests/types.py
{ "start": 3884, "end": 3983 }
class ____(Protocol): def __call__(self, name: str) -> Path | None: ...
PackageDistributionLookup
python
MongoEngine__mongoengine
tests/fields/test_uuid_field.py
{ "start": 176, "end": 1880 }
class ____(MongoDBTestCase): def test_storage(self): uid = uuid.uuid4() person = Person(api_key=uid).save() assert get_as_pymongo(person) == {"_id": person.id, "api_key": str(uid)} def test_field_string(self): """Test UUID fields storing as String""" Person.drop_collecti...
TestUUIDField
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/slots1.py
{ "start": 393, "end": 616 }
class ____: # Only lists and tuples of simple strings are supported, so this # will be treated as though there are no slots. __slots__ = ("aaa", f"test{3 + 4}") def __init__(self): self.x = 1
NoSlots3
python
doocs__leetcode
solution/3600-3699/3696.Maximum Distance Between Unequal Words in Array I/Solution.py
{ "start": 0, "end": 304 }
class ____: def maxDistance(self, words: List[str]) -> int: n = len(words) ans = 0 for i in range(n): if words[i] != words[0]: ans = max(ans, i + 1) if words[i] != words[-1]: ans = max(ans, n - i) return ans
Solution
python
optuna__optuna
optuna/storages/_grpc/client.py
{ "start": 16521, "end": 16728 }
class ____: def __init__(self) -> None: self.trials: dict[int, FrozenTrial] = {} self.unfinished_trial_ids: set[int] = set() self.last_finished_trial_id: int = -1
GrpcClientCacheEntry