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 | matplotlib__matplotlib | tools/stubtest.py | {
"start": 183,
"end": 4459
} | class ____(ast.NodeVisitor):
def __init__(self, filepath, output, existing_allowed):
self.filepath = filepath
self.context = list(filepath.with_suffix("").relative_to(lib).parts)
self.output = output
self.existing_allowed = existing_allowed
def _is_already_allowed(self, parts):
... | Visitor |
python | networkx__networkx | networkx/classes/reportviews.py | {
"start": 38504,
"end": 41643
} | class ____(OutEdgeView):
"""A EdgeView class for edges of a Graph
This densely packed View allows iteration over edges, data lookup
like a dict and set operations on edges represented by node-tuples.
In addition, edge data can be controlled by calling this object
possibly creating an EdgeDataView. ... | EdgeView |
python | encode__django-rest-framework | tests/test_negotiation.py | {
"start": 3218,
"end": 3680
} | class ____(TestCase):
def setUp(self):
self.negotiator = BaseContentNegotiation()
def test_raise_error_for_abstract_select_parser_method(self):
with pytest.raises(NotImplementedError):
self.negotiator.select_parser(None, None)
def test_raise_error_for_abstract_select_renderer_... | BaseContentNegotiationTests |
python | catalyst-team__catalyst | tests/catalyst/callbacks/test_control_flow.py | {
"start": 155,
"end": 284
} | class ____:
def __init__(self, loader_key, epoch):
self.loader_key = loader_key
self.epoch_step = epoch
| _Runner |
python | gevent__gevent | src/gevent/testing/flaky.py | {
"start": 1662,
"end": 1795
} | class ____(FlakyTest):
"""
Use this when the flaky test is definitely caused by a race condition.
"""
| FlakyTestRaceCondition |
python | coleifer__peewee | tests/cockroachdb.py | {
"start": 879,
"end": 11800
} | class ____(ModelTestCase):
@requires_models(KV)
def test_retry_transaction_ok(self):
@self.database.retry_transaction()
def succeeds(db):
k1 = KV.create(k='k1', v=1)
k2 = KV.create(k='k2', v=2)
return [k1.id, k2.id]
id_list = succeeds()
self.a... | TestCockroachDatabase |
python | pypa__setuptools | setuptools/_vendor/zipp/__init__.py | {
"start": 1412,
"end": 1832
} | class ____:
"""
Mix-in to save the initialization state for pickling.
"""
def __init__(self, *args, **kwargs):
self.__args = args
self.__kwargs = kwargs
super().__init__(*args, **kwargs)
def __getstate__(self):
return self.__args, self.__kwargs
def __setstate__... | InitializedState |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/asset_health.py | {
"start": 5572,
"end": 5757
} | class ____(graphene.ObjectType):
lastMaterializedTimestamp = graphene.Field(graphene.Float)
class Meta:
name = "AssetHealthFreshnessMeta"
| GrapheneAssetHealthFreshnessMeta |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/serialization_test.py | {
"start": 1456,
"end": 2162
} | class ____(serialization.Serializable):
def __init__(self, *elements):
self.elements = elements
@classmethod
def experimental_type_proto(cls):
return serialization_test_pb2.MyCompositeRepresentation
@classmethod
def experimental_from_proto(cls, proto):
return MyCompositeClass(
*[seriali... | MyCompositeClass |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 6695,
"end": 6794
} | class ____(BaseModel):
my_field: str = Field(alias='my_alias')
m4 = Model4(my_alias='foo')
| Model4 |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/rds.py | {
"start": 24776,
"end": 29639
} | class ____(RdsBaseOperator):
"""
Creates an RDS DB instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:RdsCreateDbInstanceOperator`
:param db_instance_identifier: The DB instance identifier, must start with a letter an... | RdsCreateDbInstanceOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 42289,
"end": 42894
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, docker_username: str):
"""Airbyte Source for Dockerhub.
Documentation can be found at https://docs.airbyte.com/integrations/sources/dockerhub
Args:
name (str): The name of the destination.
... | DockerhubSource |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_event_frequency_handlers.py | {
"start": 11059,
"end": 11495
} | class ____(TestEventFrequencyCountCondition):
def setUp(self) -> None:
super().setUp()
self.condition = Condition.EVENT_UNIQUE_USER_FREQUENCY_COUNT
self.payload: dict[str, str | int | float] = {
"interval": "1h",
"id": EventUniqueUserFrequencyCondition.id,
... | TestEventUniqueUserFrequencyCountCondition |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_insert.py | {
"start": 783,
"end": 2573
} | class ____(fixtures.TablesTest):
run_deletes = "each"
__backend__ = True
__requires__ = "implements_get_lastrowid", "autoincrement_insert"
@classmethod
def define_tables(cls, metadata):
Table(
"autoinc_pk",
metadata,
Column(
"id", Intege... | LastrowidTest |
python | wandb__wandb | wandb/sdk/interface/summary_record.py | {
"start": 157,
"end": 1044
} | class ____:
"""Encodes a diff -- analogous to the SummaryRecord protobuf message."""
update: t.List["SummaryItem"]
remove: t.List["SummaryItem"]
def __init__(self):
self.update = []
self.remove = []
def __str__(self):
s = "SummaryRecord:\n Update:\n "
s += "\n ... | SummaryRecord |
python | huggingface__transformers | src/transformers/models/omdet_turbo/modeling_omdet_turbo.py | {
"start": 19357,
"end": 20260
} | class ____(nn.Module):
"""
RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
"""
def __init__(self, config: OmDetTurboConfig):
super().__init__()
activation = config.csp_activation
hidden_channels = int(config.encoder_hidden_dim *... | OmDetTurboRepVggBlock |
python | huggingface__transformers | tests/models/mllama/test_processing_mllama.py | {
"start": 957,
"end": 17671
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = MllamaProcessor
model_id = "hf-internal-testing/mllama-11b"
@classmethod
def _setup_test_attributes(cls, processor):
cls.image1 = Image.new("RGB", (224, 220))
cls.image2 = Image.new("RGB", (512, 128))
cls.ima... | MllamaProcessorTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 22109,
"end": 22417
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"GIST",
"ISSUE",
"ORGANIZATION",
"PROJECT",
"PULL_REQUEST",
"REPOSITORY",
"TEAM",
"USER",
)
| PinnableItemType |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/common/parameters.py | {
"start": 4954,
"end": 5345
} | class ____(BaseParam[bool]):
"""Filter on is_stale."""
def to_orm(self, select: Select) -> Select:
if self.value and self.skip_none:
return select.where(DagModel.is_stale != self.value)
return select
@classmethod
def depends(cls, exclude_stale: bool = True) -> _ExcludeStale... | _ExcludeStaleFilter |
python | kamyu104__LeetCode-Solutions | Python/twisted-mirror-path-count.py | {
"start": 46,
"end": 718
} | class ____(object):
def uniquePaths(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
MOD = 10**9+7
def get(r, c):
return grid[r][c] if len(grid) > len(grid[0]) else grid[c][r]
dp = [[0]*2 for _ in xrange(min(len(grid), len(grid[0]))+1)... | Solution |
python | ray-project__ray | rllib/algorithms/algorithm_config.py | {
"start": 3578,
"end": 310942
} | class ____(_Config):
"""A RLlib AlgorithmConfig builds an RLlib Algorithm from a given configuration.
.. testcode::
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.algorithms.callbacks import MemoryTrackingCallbacks
# Construct a generic config object, specifying values w... | AlgorithmConfig |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 530358,
"end": 530975
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ProjectViewEdge"), graphql_name="edges"
)
nodes = sgqlc.t... | ProjectViewConnection |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/tests/test_couchbase_query_vector_store.py | {
"start": 8024,
"end": 25639
} | class ____:
@classmethod
def setup_class(cls) -> None:
"""Set up test class with vector index creation."""
cls.cluster = get_cluster()
# Create scope and collection if they don't exist
create_scope_and_collection(
cls.cluster, BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME... | TestCouchbaseQueryVectorStore |
python | huggingface__transformers | tests/models/parakeet/test_modeling_parakeet.py | {
"start": 1329,
"end": 5977
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=1024,
is_training=True,
hidden_size=64,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=256,
hidden_act="silu",
dropout=0, # so gradient checkpoint... | ParakeetEncoderModelTester |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session.py | {
"start": 52440,
"end": 54903
} | class ____(_WrappedSession):
"""A wrapped session that works with a `tf.Coordinator`.
Calls to `run()` are delegated to the wrapped session. If a call
raises an exception, the exception is reported to the coordinator.
In addition, after each call to `run()` this session ask the coordinator if
the session s... | _CoordinatedSession |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_all.py | {
"start": 1163,
"end": 2279
} | class ____(Callback):
def on_train_batch_start(self, trainer, pl_module, batch, *_):
_device_check_helper(batch.device, pl_module.device)
def on_train_batch_end(self, trainer, pl_module, outputs, batch, *_):
_device_check_helper(batch.device, pl_module.device)
def on_validation_batch_start... | BatchHookObserverCallback |
python | falconry__falcon | tests/test_headers.py | {
"start": 4676,
"end": 5447
} | class ____:
def __init__(self):
self._links = []
def add_link(self, *args, **kwargs):
self._links.append(('add_link', args, kwargs))
def append_link(self, *args, **kwargs):
self._links.append(('append_link', args, kwargs))
def on_get(self, req, resp):
resp.text = '{}'
... | LinkHeaderResource |
python | pdm-project__pdm | src/pdm/models/backends.py | {
"start": 1024,
"end": 1249
} | class ____(BuildBackend):
@classmethod
def build_system(cls) -> BuildSystem:
return {
"requires": ["setuptools>=61"],
"build-backend": "setuptools.build_meta",
}
| SetuptoolsBackend |
python | jazzband__django-polymorphic | example/pexp/management/commands/polymorphic_create_test_data.py | {
"start": 157,
"end": 561
} | class ____(BaseCommand):
help = ""
def handle_noargs(self, **options):
Project.objects.all().delete()
o = Project.objects.create(topic="John's gathering")
o = ArtProject.objects.create(topic="Sculpting with Tim", artist="T. Turner")
o = ResearchProject.objects.create(topic="Swal... | Command |
python | scipy__scipy | scipy/odr/_models.py | {
"start": 1738,
"end": 4599
} | class ____(Model):
r"""
Arbitrary-dimensional linear model
This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i`
Examples
--------
We can calculate orthogonal distance regression with an arbitrary
dimensional linear model:
>>> from scipy import odr
>>> import numpy... | _MultilinearModel |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 50284,
"end": 62445
} | class ____:
def __init__(self, vals, rows, cols, shape):
"""
Create a sparse matrix in COO format.
*vals*: arrays of values of non-null entries of the matrix
*rows*: int arrays of rows of non-null entries of the matrix
*cols*: int arrays of cols of non-null entries of the mat... | _Sparse_Matrix_coo |
python | pytorch__pytorch | test/test_cuda.py | {
"start": 3217,
"end": 159240
} | class ____(TestCase):
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = True
FIFTY_MIL_CYCLES = 50000000
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
@property
def expandable_segments(self):
return EXPANDABLE_SEGMENTS
d... | TestCuda |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 40677,
"end": 41123
} | class ____(SetitemCastingEquivalents):
@pytest.fixture
def obj(self):
return Series([1, 2, 3], dtype=np.int8)
@pytest.fixture
def key(self):
return 1
@pytest.fixture
def expected(self):
return Series([1, 512, 3], dtype=np.int16)
@pytest.fixture
def raises(self)... | TestSetitemIntoIntegerSeriesNeedsUpcast |
python | eventlet__eventlet | tests/pools_test.py | {
"start": 6532,
"end": 6614
} | class ____(pools.Pool):
def create(self):
raise RuntimeError()
| RaisePool |
python | sqlalchemy__sqlalchemy | test/sql/test_compare.py | {
"start": 4798,
"end": 5064
} | class ____(HasCacheKey):
def __init__(self, name, element):
self.name = name
self.element = element
_cache_key_traversal = [
("name", InternalTraversal.dp_string),
("element", InternalTraversal.dp_clauseelement),
]
| MyEntity |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 9133,
"end": 9215
} | class ____(ProxyModelBase):
field1 = models.CharField(max_length=30)
| ProxyModelA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass6.py | {
"start": 244,
"end": 641
} | class ____(ABC):
@abstractmethod
def method1(self, x: int) -> int:
pass
def func1(base_cls: Type[Base]):
base_cls()
def func2():
# This should generate an error.
Base()
def func3(base_cls: type[Base]):
base_cls()
T = TypeVar("T")
def create_instance(cls: Type[T]) -> T:
retu... | Base |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/common/parameters.py | {
"start": 3466,
"end": 3832
} | class ____(BaseParam[NonNegativeInt]):
"""Filter on offset."""
def to_orm(self, select: Select) -> Select:
if self.value is None and self.skip_none:
return select
return select.offset(self.value)
@classmethod
def depends(cls, offset: NonNegativeInt = 0) -> OffsetFilter:
... | OffsetFilter |
python | wandb__wandb | wandb/vendor/pygments/lexers/automation.py | {
"start": 10167,
"end": 19648
} | class ____(RegexLexer):
"""
For `AutoIt <http://www.autoitscript.com/site/autoit/>`_ files.
AutoIt is a freeware BASIC-like scripting language
designed for automating the Windows GUI and general scripting
.. versionadded:: 1.6
"""
name = 'AutoIt'
aliases = ['autoit']
filenames = ['... | AutoItLexer |
python | doocs__leetcode | solution/1000-1099/1085.Sum of Digits in the Minimum Number/Solution.py | {
"start": 0,
"end": 190
} | class ____:
def sumOfDigits(self, nums: List[int]) -> int:
x = min(nums)
s = 0
while x:
s += x % 10
x //= 10
return s & 1 ^ 1
| Solution |
python | plotly__plotly.py | plotly/graph_objs/contour/_contours.py | {
"start": 233,
"end": 14525
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contour"
_path_str = "contour.contours"
_valid_props = {
"coloring",
"end",
"labelfont",
"labelformat",
"operation",
"showlabels",
"showlines",
"size",
"start",
"type",
... | Contours |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 1935,
"end": 1988
} | class ____(BasicEntity):
__hash__ = None
| FooWNoHash |
python | jazzband__django-oauth-toolkit | oauth2_provider/exceptions.py | {
"start": 1012,
"end": 1169
} | class ____(InvalidRequestFatalError):
description = "Mismatch between the Client ID of the ID Token and the Client ID that was provided."
| ClientIdMissmatch |
python | apache__airflow | providers/apache/beam/tests/unit/apache/beam/hooks/test_beam.py | {
"start": 16621,
"end": 17553
} | class ____:
@pytest.mark.parametrize(
("options", "expected_args"),
[
({"key": "val"}, ["--key=val"]),
({"key": None}, []),
({"key": True}, ["--key"]),
({"key": False}, []),
({"key": ["a", "b", "c"]}, ["--key=a", "--key=b", "--key=c"]),
... | TestBeamOptionsToArgs |
python | django__django | tests/cache/tests.py | {
"start": 64060,
"end": 65361
} | class ____(BaseMemcachedTests, TestCase):
base_params = PyMemcacheCache_params
@property
def incr_decr_type_error(self):
return cache._lib.exceptions.MemcacheClientError
def test_pymemcache_highest_pickle_version(self):
self.assertEqual(
cache._cache.default_kwargs["serde"]... | PyMemcacheCacheTests |
python | jazzband__django-polymorphic | src/polymorphic/formsets/models.py | {
"start": 12826,
"end": 15213
} | class ____(BaseInlineFormSet, BasePolymorphicModelFormSet):
"""
Polymorphic formset variation for inline formsets
"""
def _construct_form(self, i, **kwargs):
return super()._construct_form(i, **kwargs)
def polymorphic_inlineformset_factory(
parent_model,
model,
formset_children,
... | BasePolymorphicInlineFormSet |
python | scikit-learn__scikit-learn | sklearn/utils/_set_output.py | {
"start": 4528,
"end": 5629
} | class ____:
container_lib = "polars"
def create_container(self, X_output, X_original, columns, inplace=True):
pl = check_library_installed("polars")
columns = get_columns(columns)
columns = columns.tolist() if isinstance(columns, np.ndarray) else columns
if not inplace or not i... | PolarsAdapter |
python | numba__numba | numba/cuda/cudamath.py | {
"start": 2463,
"end": 2677
} | class ____(ConcreteTemplate):
cases = [
signature(types.float32, types.float32, types.float32),
signature(types.float64, types.float64, types.float64),
]
@infer_global(math.pow)
| Math_remainder |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 1014,
"end": 1069
} | class ____: # [invalid-slots]
__slots__ = 1
| SecondBad |
python | graphql-python__graphene | graphene/tests/issues/test_720.py | {
"start": 258,
"end": 694
} | class ____(graphene.InputObjectType):
@classmethod
def __init_subclass_with_meta__(
cls, container=None, _meta=None, fields=None, **options
):
if _meta is None:
_meta = graphene.types.inputobjecttype.InputObjectTypeOptions(cls)
_meta.fields = fields
super(MyInputC... | MyInputClass |
python | kamyu104__LeetCode-Solutions | Python/find-the-k-sum-of-an-array.py | {
"start": 72,
"end": 726
} | class ____(object):
def kSum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
total = sum(x for x in nums if x > 0)
sorted_vals = sorted(abs(x) for x in nums)
max_heap = [(-total, 0)]
for _ in xrange(k):
result... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/response_builder/helpers.py | {
"start": 305,
"end": 961
} | class ____(HttpResponseBuilder):
def __init__(
self,
template: List[Any],
records_path: Optional[Union[FieldPath, NestedPath]] = None,
pagination_strategy: Optional[PaginationStrategy] = None,
):
self._response = template
self._records: List[RecordBuilder] = []
... | RootHttpResponseBuilder |
python | ray-project__ray | python/ray/tests/test_runtime_env_standalone.py | {
"start": 4385,
"end": 5936
} | class ____(RuntimeEnvPlugin):
name = RT_ENV_AGENT_SLOW_STARTUP_PLUGIN_NAME
def __init__(self):
# This happens in Runtime Env Agent start up process. Make it slow.
time.sleep(5)
print("starting...")
@pytest.mark.parametrize(
"set_runtime_env_plugins",
[
'[{"class":"' +... | RtEnvAgentSlowStartupPlugin |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 30522,
"end": 32731
} | class ____(SimpleTestCase):
"""
Tests for AnonymousUser delegating to backend.
"""
def setUp(self):
self.user1 = AnonymousUser()
def test_has_perm(self):
self.assertIs(self.user1.has_perm("perm", TestObj()), False)
self.assertIs(self.user1.has_perm("anon", TestObj()), True)... | AnonymousUserBackendTest |
python | numba__numba | numba/tests/support.py | {
"start": 32259,
"end": 32469
} | class ____(object):
"""Mixin to enable the NRT statistics counters."""
def setUp(self):
_nrt.memsys_enable_stats()
def tearDown(self):
_nrt.memsys_disable_stats()
| EnableNRTStatsMixin |
python | huggingface__transformers | src/transformers/models/apertus/modular_apertus.py | {
"start": 11500,
"end": 13182
} | class ____(LlamaDecoderLayer):
def __init__(self, config: ApertusConfig, layer_idx: int):
super().__init__(config, layer_idx)
self.attention_layernorm = ApertusRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.feedforward_layernorm = ApertusRMSNorm(config.hidden_size, eps=config.rms_... | ApertusDecoderLayer |
python | huggingface__transformers | src/transformers/models/llava_next_video/video_processing_llava_next_video.py | {
"start": 817,
"end": 1348
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
size = {"shortest_edge": 224}
default_to_square = False
crop_size = {"height": 224, "width": 224}
do_resize = True
do_center_crop = True
do_rescale = True
... | LlavaNextVideoVideoProcessor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 70099,
"end": 71585
} | class ____(GithubStream):
"""
API docs: https://docs.github.com/en/rest/teams/members?apiVersion=2022-11-28#list-team-members
"""
use_cache = True
primary_key = ["id", "team_slug"]
def __init__(self, parent: Teams, **kwargs):
super().__init__(**kwargs)
self.parent = parent
... | TeamMembers |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/control_flow/scan_ops_test.py | {
"start": 2117,
"end": 7077
} | class ____(test.TestCase):
valid_dtypes = [
np.int32,
np.int64,
np.float16,
np.float32,
np.float64,
np.complex64,
np.complex128,
dtypes.bfloat16.as_numpy_dtype,
]
def _compare(self, x, axis, exclusive, reverse):
np_out = handle_options(np.cumsum, x, axis, excl... | CumsumTest |
python | numba__numba | numba/tests/test_array_exprs.py | {
"start": 2081,
"end": 3063
} | class ____(Compiler):
@classmethod
def mk_pipeline(cls, args, return_type=None, flags=None, locals=None,
library=None, typing_context=None, target_context=None):
if locals is None:
locals = {}
if not flags:
flags = Flags()
flags.nrt = True
... | RewritesTester |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-singlestore/llama_index/readers/singlestore/base.py | {
"start": 208,
"end": 2284
} | class ____(BaseReader):
"""
SingleStore reader.
Args:
scheme (str): Database Scheme.
host (str): Database Host.
port (str): Database Port.
user (str): Database User.
password (str): Database Password.
dbname (str): Database Name.
table_name (str): Tab... | SingleStoreReader |
python | altair-viz__altair | sphinxext/code_ref.py | {
"start": 9136,
"end": 9407
} | class ____(SphinxDirective):
"""Placeholder for non-theme related directive."""
has_content: ClassVar[bool] = False
option_spec = {"packages": directives.unchanged}
def run(self) -> Sequence[nodes.Node]:
raise NotImplementedError
| PyScriptDirective |
python | marshmallow-code__apispec | tests/test_ext_marshmallow.py | {
"start": 53286,
"end": 53821
} | class ____:
def test_timedelta_x_unit(self, spec):
class SchemaWithTimeDelta(Schema):
sec = TimeDelta("seconds")
day = TimeDelta("days")
spec.components.schema("SchemaWithTimeDelta", schema=SchemaWithTimeDelta)
assert (
get_schemas(spec)["SchemaWithTimeD... | TestTimeDelta |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/openai_functions_agent/agent_token_buffer_memory.py | {
"start": 450,
"end": 3650
} | class ____(BaseChatMemory):
"""Memory used to save agent output AND intermediate steps.
Args:
human_prefix: Prefix for human messages.
ai_prefix: Prefix for AI messages.
llm: Language model.
memory_key: Key to save memory under.
max_token_limit: Maximum number of tokens ... | AgentTokenBufferMemory |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 19103,
"end": 20860
} | class ____(WebTestCase):
def get_handlers(self):
return [("/group/(.*)", EchoHandler), ("/slashes/([^/]*)/([^/]*)", EchoHandler)]
def fetch_json(self, path):
return json_decode(self.fetch(path).body)
def test_group_question_mark(self):
# Ensure that url-encoded question marks are h... | RequestEncodingTest |
python | apache__airflow | providers/exasol/tests/unit/exasol/hooks/test_sql.py | {
"start": 1204,
"end": 9901
} | class ____(ExasolHook):
conn_name_attr = "exasol_conn_id"
get_conn = MagicMock(name="conn")
@pytest.fixture(autouse=True)
def create_connection(create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_ID,
conn_type="exasol",
... | ExasolHookForTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib.py | {
"start": 56861,
"end": 59428
} | class ____(type_spec.TypeSpec):
"""Type specification for `_SingleWorkerOwnedDatasetIterator`."""
__slots__ = [
"_worker", "_devices", "_element_spec", "_options",
"_canonicalize_devices"
]
def __init__(self, worker, devices, element_spec, options,
canonicalize_devices=True):
se... | _SingleWorkerDatasetIteratorSpec |
python | python__mypy | mypy/server/update.py | {
"start": 22602,
"end": 53491
} | class ____(NamedTuple):
module: str
path: str
remaining: list[tuple[str, str]]
messages: list[str]
UpdateResult: _TypeAlias = NormalUpdate | BlockedUpdate
def update_module_isolated(
module: str,
path: str,
manager: BuildManager,
previous_modules: dict[str, str],
graph: Graph,
... | BlockedUpdate |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/request_builders/__init__.py | {
"start": 71,
"end": 159
} | class ____:
@abc.abstractmethod
def build(self):
pass
| AbstractRequestBuilder |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 22347,
"end": 22424
} | class ____(MarkdownBlock):
"""A table head Markdown block."""
| MarkdownTHead |
python | Pylons__pyramid | tests/test_events.py | {
"start": 3473,
"end": 4223
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.events import ContextFound
return ContextFound
def _makeOne(self, request=None):
if request is None:
request = DummyRequest()
return self._getTargetClass()(request)
def test_class_conforms_t... | ContextFoundEventTests |
python | astropy__astropy | astropy/coordinates/builtin_frames/galactic.py | {
"start": 1865,
"end": 4082
} | class ____(BaseCoordinateFrame):
"""
A coordinate or frame in the Galactic coordinate system.
This frame is used in a variety of Galactic contexts because it has as its
x-y plane the plane of the Milky Way. The positive x direction (i.e., the
l=0, b=0 direction) points to the center of the Milky W... | Galactic |
python | matplotlib__matplotlib | lib/matplotlib/_enums.py | {
"start": 4000,
"end": 6175
} | class ____(str, Enum):
r"""
Define how the two endpoints (caps) of an unclosed line are drawn.
How to draw the start and end points of lines that represent a closed curve
(i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's
`JoinStyle`. For all other lines, how the start and end... | CapStyle |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_constructors.py | {
"start": 3503,
"end": 23528
} | class ____:
def test_from_ordinals(self):
Period(ordinal=-1000, freq="Y")
Period(ordinal=0, freq="Y")
idx1 = PeriodIndex.from_ordinals(ordinals=[-1, 0, 1], freq="Y")
idx2 = PeriodIndex.from_ordinals(ordinals=np.array([-1, 0, 1]), freq="Y")
tm.assert_index_equal(idx1, idx2)
... | TestPeriodIndex |
python | lxml__lxml | src/lxml/doctestcompare.py | {
"start": 15073,
"end": 17731
} | class ____:
def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func,
del_module):
self.dt_self = dt_self
self.checker = old_checker
self.checker._temp_call_super_check_output = self.call_super
self.checker._temp_override_self = new_checker
... | _RestoreChecker |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/sql_component/sql_component.py | {
"start": 900,
"end": 2548
} | class ____(ExecutableComponent, ABC):
"""Base component which executes templated SQL. Subclasses
implement instructions on where to load the SQL content from.
"""
# Necessary to allow connection to be a SQLClient, which is an ABC
model_config = ConfigDict(arbitrary_types_allowed=True)
connecti... | SqlComponent |
python | doocs__leetcode | solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/Solution.py | {
"start": 0,
"end": 197
} | class ____:
def subtractProductAndSum(self, n: int) -> int:
x, y = 1, 0
while n:
n, v = divmod(n, 10)
x *= v
y += v
return x - y
| Solution |
python | great-expectations__great_expectations | great_expectations/render/renderer/profiling_results_overview_section_renderer.py | {
"start": 454,
"end": 13669
} | class ____(Renderer):
@classmethod
def render(cls, evrs, section_name=None):
content_blocks = []
# NOTE: I don't love the way this builds content_blocks as a side effect.
# The top-level API is clean and scannable, but the function internals are counterintutitive and hard to test. # noq... | ProfilingResultsOverviewSectionRenderer |
python | great-expectations__great_expectations | great_expectations/render/renderer/site_builder.py | {
"start": 20655,
"end": 41063
} | class ____:
def __init__( # noqa: PLR0913 # FIXME CoP
self,
name,
site_name,
data_context: AbstractDataContext,
target_store,
site_section_builders_config,
custom_styles_directory=None,
custom_views_directory=None,
show_how_to_buttons=True,
... | DefaultSiteIndexBuilder |
python | celery__celery | t/unit/utils/test_text.py | {
"start": 665,
"end": 1935
} | class ____:
def test_textindent(self):
assert indent(RANDTEXT, 4) == RANDTEXT_RES
def test_format_queues(self, app):
app.amqp.queues = app.amqp.Queues(QUEUES)
assert (sorted(app.amqp.queues.format().split('\n')) ==
sorted([QUEUE_FORMAT1, QUEUE_FORMAT2]))
def test_e... | test_Info |
python | django__django | tests/utils_tests/test_connection.py | {
"start": 99,
"end": 565
} | class ____(SimpleTestCase):
def test_create_connection(self):
handler = BaseConnectionHandler()
msg = "Subclasses must implement create_connection()."
with self.assertRaisesMessage(NotImplementedError, msg):
handler.create_connection(None)
def test_all_initialized_only(self)... | BaseConnectionHandlerTests |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_wx.py | {
"start": 47911,
"end": 48118
} | class ____(backend_tools.ConfigureSubplotsBase):
def trigger(self, *args):
NavigationToolbar2Wx.configure_subplots(self)
@backend_tools._register_tool_class(_FigureCanvasWxBase)
| ConfigureSubplotsWx |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/daemon.py | {
"start": 2145,
"end": 8282
} | class ____(AbstractContextManager, ABC, Generic[TContext]):
_logger: logging.Logger
_last_heartbeat_time: Optional[datetime.datetime]
def __init__(self):
self._logger = get_default_daemon_logger(type(self).__name__)
self._last_heartbeat_time = None
self._last_log_time = None
... | DagsterDaemon |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 49668,
"end": 51062
} | class ____:
def test_simple(self):
arr = np.arange(24).reshape(4, 6)
result = np.pad(arr, [(2, 3), (3, 1)], mode="empty")
assert result.shape == (9, 10)
assert_equal(arr, result[2:-3, 3:-1])
def test_pad_empty_dimension(self):
arr = np.zeros((3, 0, 2))
result = n... | TestEmpty |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 11361,
"end": 12027
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | NystromformerIntermediate |
python | python-attrs__attrs | tests/test_functional.py | {
"start": 477,
"end": 595
} | class ____:
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
foo = None
@attr.s()
| C1Slots |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/GraphicsScene.py | {
"start": 145,
"end": 1161
} | class ____(QtWidgets.QGraphicsObject):
def __init__(self):
QtWidgets.QGraphicsObject.__init__(self)
def paint(self, p, *args):
p.setPen(pg.mkPen(200,200,200))
p.drawRect(self.boundingRect())
def boundingRect(self):
return QtCore.QRectF(0, 0, 20, 20)
... | Obj |
python | pypa__pip | src/pip/_vendor/pygments/lexer.py | {
"start": 12247,
"end": 12446
} | class ____:
"""
Indicates the a state should inherit from its superclass.
"""
def __repr__(self):
return 'inherit'
inherit = _inherit() # pylint: disable=invalid-name
| _inherit |
python | getsentry__sentry | tests/sentry/integrations/slack/tasks/test_send_notifications_on_activity.py | {
"start": 2238,
"end": 3505
} | class ____(TestCase):
def setUp(self) -> None:
mock_slack_service = mock.MagicMock()
mock_default_method = mock.MagicMock(return_value=mock_slack_service)
mock_notify_all_threads_for_activity = mock.MagicMock()
mock_slack_service.default = mock_default_method
mock_slack_servi... | TestSendActivityNotifications |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 16684,
"end": 19874
} | class ____(Widget):
"""Renders a Markdown table."""
DEFAULT_CSS = """
MarkdownTableContent {
width: 1fr;
height: auto;
layout: grid;
grid-columns: auto;
grid-rows: auto;
grid-gutter: 1 1;
& > .cell {
margin: 0 0;
height: auto;... | MarkdownTableContent |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 14903,
"end": 15406
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "PartitionKeysNotFoundError"
partition_keys = non_null_list(graphene.String)
def __init__(self, partition_keys: set[str]):
super().__init__()
self.partition_keys = check.list_param(
... | GraphenePartitionKeysNotFoundError |
python | django__django | tests/delete/models.py | {
"start": 2095,
"end": 3951
} | class ____(models.Model):
name = models.CharField(max_length=30)
auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set")
auto_nullable = models.ForeignKey(
R, models.CASCADE, null=True, related_name="auto_nullable_set"
)
setvalue = models.ForeignKey(R, models.SET(get_default_r)... | A |
python | huggingface__transformers | tests/models/owlv2/test_image_processing_owlv2.py | {
"start": 1106,
"end": 2895
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.48145466, 0.4578275, 0.40821073],
im... | Owlv2ImageProcessingTester |
python | ansible__ansible | test/units/modules/test_unarchive.py | {
"start": 3293,
"end": 4037
} | class ____:
def test_no_tar_binary(self, mocker, fake_ansible_module):
mocker.patch("ansible.modules.unarchive.get_bin_path", side_effect=ValueError)
fake_ansible_module.params = {
"extra_opts": "",
"exclude": "",
"include": "",
"io_buffer_size": 65536... | TestCaseTgzArchive |
python | readthedocs__readthedocs.org | readthedocs/oauth/services/__init__.py | {
"start": 579,
"end": 727
} | class ____(SettingsOverrideObject):
_default_class = bitbucket.BitbucketService
_override_setting = "OAUTH_BITBUCKET_SERVICE"
| BitbucketService |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/types.py | {
"start": 4060,
"end": 4982
} | class ____:
"""Represents a user-defined Airbyte source.
Args:
name (str): The display name of the source.
source_type (str): The type of the source, from Airbyte's list
of sources https://docs.airbyte.com/integrations/sources/.
source_configuration (Mapping[str, Any]): The ... | AirbyteSource |
python | django-import-export__django-import-export | tests/core/tests/test_base_formats.py | {
"start": 2741,
"end": 5625
} | class ____(TestCase):
def setUp(self):
self.format = base_formats.XLSX()
self.filename = os.path.join(
os.path.dirname(__file__), os.path.pardir, "exports", "books.xlsx"
)
def test_binary_format(self):
self.assertTrue(self.format.is_binary())
@ignore_utcnow_depr... | XLSXTest |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_context.py | {
"start": 11504,
"end": 12968
} | class ____:
def test_current_context_roundtrip(self):
example_context = {"Hello": "World"}
with set_current_context(example_context):
assert get_current_context() == example_context
def test_context_removed_after_exit(self):
example_context = {"Hello": "World"}
wit... | TestCurrentContext |
python | ansible__ansible | test/units/module_utils/test_api.py | {
"start": 459,
"end": 674
} | class ____:
def test_ratelimit(self):
@rate_limit(rate=1, rate_limit=1)
def login_database():
return "success"
r = login_database()
assert r == 'success'
| TestRateLimit |
python | tensorflow__tensorflow | tensorflow/python/distribute/strategy_test_lib.py | {
"start": 6025,
"end": 20077
} | class ____(test.TestCase):
"""Some tests that should work with any DistributionStrategy."""
def _test_minimize_loss_eager(self, d):
with d.scope():
kernel = create_variable_like_keras_layer(
name="kernel", shape=(1, 1), dtype=dtypes.float32)
def loss(x):
y = array_ops.reshape(
... | DistributionTestBase |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.