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 | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 21059,
"end": 21358
} | class ____(sgqlc.types.Enum):
"""Properties by which Enterprise Server user account email
connections can be ordered.
Enumeration Choices:
* `EMAIL`: Order emails by email
"""
__schema__ = github_schema
__choices__ = ("EMAIL",)
| EnterpriseServerUserAccountEmailOrderField |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/dag_object_graph.py | {
"start": 1176,
"end": 1515
} | class ____(tf.Module):
def __init__(self):
super(TestModule, self).__init__()
self.child1 = Child()
self.child2 = self.child1
# CHECK: tf_saved_model.global_tensor
# CHECK-SAME: tf_saved_model.exported_names = ["child1.my_variable", "child2.my_variable"]
if __name__ == '__main__':
common.do_test... | TestModule |
python | numba__numba | numba/tests/test_iteration.py | {
"start": 1707,
"end": 6612
} | class ____(MemoryLeakMixin, TestCase):
def run_nullary_func(self, pyfunc, flags):
cfunc = jit((), **flags)(pyfunc)
expected = pyfunc()
self.assertPreciseEqual(cfunc(), expected)
def test_int_tuple_iter(self, flags=force_pyobj_flags):
self.run_nullary_func(int_tuple_iter_usecase... | IterationTest |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 17882,
"end": 18087
} | class ____(ValueWrapper):
def is_bound_method(self):
return True
def get_signatures(self):
return [sig.bind(self) for sig in self._wrapped_value.get_signatures()]
| CompiledBoundMethod |
python | google__jax | tests/custom_api_test.py | {
"start": 44725,
"end": 95538
} | class ____(jtu.JaxTestCase):
def test_basic(self):
@jax.custom_vjp
def f(x):
return jnp.sin(x)
def f_fwd(x):
return f(x), jnp.cos(x)
def f_rev(cos_x, g):
return (2 * cos_x * g,)
f.defvjp(f_fwd, f_rev)
x = 3.
self.assertAllClose(f(x), jnp.sin(x))
self.assertAllClose(... | CustomVJPTest |
python | pypa__setuptools | setuptools/tests/test_manifest.py | {
"start": 3688,
"end": 3967
} | class ____:
def setup_method(self, method):
self.temp_dir = tempfile.mkdtemp()
self.old_cwd = os.getcwd()
os.chdir(self.temp_dir)
def teardown_method(self, method):
os.chdir(self.old_cwd)
shutil.rmtree(self.temp_dir)
| TempDirTestCase |
python | faif__python-patterns | patterns/creational/pool.py | {
"start": 1340,
"end": 2829
} | class ____:
def __init__(self, queue: Queue, auto_get: bool = False) -> None:
self._queue = queue
self.item = self._queue.get() if auto_get else None
def __enter__(self) -> str:
if self.item is None:
self.item = self._queue.get()
return self.item
def __exit__(
... | ObjectPool |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 72003,
"end": 72273
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('type', c_uint),
('value', c_nvmlUUIDValue_t),
]
def __init__(self):
super(c_nvmlUUID_t, self).__init__(version=nvmlUUID_v1)
nvmlPdi_v1 = 0x1000010
| c_nvmlUUID_t |
python | pytorch__pytorch | torch/_subclasses/meta_utils.py | {
"start": 19305,
"end": 19844
} | class ____(Generic[_TensorT]):
@abstractmethod
def apply(
self,
t: _TensorT,
new_base: _TensorT,
symint_visitor_fn: Optional[Callable[[int], int]] = None,
tensor_visitor_fn: Optional[Callable[[torch.Tensor], _TensorT]] = None,
) -> _TensorT: ...
@staticmethod
... | ViewFunc |
python | gevent__gevent | src/gevent/tests/test__monkey_queue.py | {
"start": 9016,
"end": 9565
} | class ____(Queue.Queue):
def __init__(self, *args):
self.fail_next_put = False
self.fail_next_get = False
Queue.Queue.__init__(self, *args)
def _put(self, item):
if self.fail_next_put:
self.fail_next_put = False
raise FailingQueueException("You Lose")
... | FailingQueue |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 15872,
"end": 16013
} | class ____(_TestDSTIVBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 4
self.type = 4
| TestDSTIVFloat |
python | boto__boto3 | boto3/docs/service.py | {
"start": 943,
"end": 8544
} | class ____(BaseServiceDocumenter):
# The path used to find examples
EXAMPLE_PATH = os.path.join(os.path.dirname(boto3.__file__), 'examples')
def __init__(self, service_name, session, root_docs_path):
super().__init__(
service_name=service_name,
# I know that this is an inter... | ServiceDocumenter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 842436,
"end": 843784
} | class ____(sgqlc.types.Type):
"""Project progress stats."""
__schema__ = github_schema
__field_names__ = (
"done_count",
"done_percentage",
"enabled",
"in_progress_count",
"in_progress_percentage",
"todo_count",
"todo_percentage",
)
done_count... | ProjectProgress |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/events/test_link_shared.py | {
"start": 517,
"end": 6106
} | class ____(BaseEventTest):
@pytest.fixture(autouse=True)
def mock_chat_unfurlMessage(self):
with patch(
"slack_sdk.web.client.WebClient.chat_unfurl",
return_value=SlackResponse(
client=None,
http_verb="POST",
api_url="https://slack.... | LinkSharedEventTest |
python | spack__spack | lib/spack/spack/modules/common.py | {
"start": 18932,
"end": 27350
} | class ____(tengine.Context):
"""Provides the base context needed for template rendering.
This class needs to be sub-classed for specific module types. The
following attributes need to be implemented:
- fields
"""
def __init__(self, configuration):
self.conf = configuration
@teng... | BaseContext |
python | kamyu104__LeetCode-Solutions | Python/design-video-sharing-platform.py | {
"start": 388,
"end": 2742
} | class ____(object):
def __init__(self):
self.__avails = []
self.__videos = []
self.__likes = []
self.__dislikes = []
self.__views = []
def upload(self, video):
"""
:type video: str
:rtype: int
"""
if self.__avails:
i =... | VideoSharingPlatform |
python | google__pytype | pytype/tests/test_typeguard.py | {
"start": 6475,
"end": 14313
} | class ____(test_base.BaseTest):
"""Tests for typing.TypeGuard."""
def test_basic(self):
self.Check("""
from typing import TypeGuard
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
def f(val: list[object]):
if is_str_lis... | TypeGuardTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/writeonly.py | {
"start": 14913,
"end": 15912
} | class ____(strategies._AbstractRelationshipLoader, log.Identified):
impl_class = _WriteOnlyAttributeImpl
def init_class_attribute(self, mapper: Mapper[Any]) -> None:
self.is_class_level = True
if not self.uselist or self.parent_property.direction not in (
interfaces.ONETOMANY,
... | _WriteOnlyLoader |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 18520,
"end": 27516
} | class ____(StorageWriter):
"""
Basic implementation of StorageWriter using file IO.
This implementation makes the following assumptions and simplifications:
* The checkpoint path is an empty or non-existing directory.
* File creation is atomic
The checkpoint consist of one file per write requ... | _FileSystemWriter |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 33852,
"end": 40330
} | class ____(DescriptorPoolTestBase,
unittest.TestCase):
def setUp(self):
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb)
self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
... | SecondaryDescriptorFromDescriptorDB |
python | numba__numba | numba/np/random/generator_core.py | {
"start": 1004,
"end": 4712
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('bit_generator', _bit_gen_type),
('meminfo', types.MemInfoPointer(types.voidptr)),
('parent', types.pyobject)
]
super(
NumPyRandomGeneratorTypeModel,
sel... | NumPyRandomGeneratorTypeModel |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/docstore/simple_docstore.py | {
"start": 519,
"end": 3388
} | class ____(KVDocumentStore):
"""
Simple Document (Node) store.
An in-memory store for Document and Node objects.
Args:
simple_kvstore (SimpleKVStore): simple key-value store
namespace (str): namespace for the docstore
"""
def __init__(
self,
simple_kvstore: Op... | SimpleDocumentStore |
python | pytorch__pytorch | test/test_static_runtime.py | {
"start": 566,
"end": 5042
} | class ____(nn.Module):
def __init__(self, hid_dim, n_heads, dropout, device):
super().__init__()
assert hid_dim % n_heads == 0
self.hid_dim = hid_dim
self.n_heads = n_heads
self.head_dim = hid_dim // n_heads
self.fc_q = nn.Linear(hid_dim, hid_dim)
self.fc_k = ... | MultiHeadAttentionLayer |
python | django__django | tests/admin_scripts/app_raising_warning/models.py | {
"start": 62,
"end": 197
} | class ____(models.Model):
@classmethod
def check(self, **kwargs):
return [checks.Warning("A warning")]
| ModelRaisingMessages |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 56771,
"end": 59197
} | class ____(MegatronBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = MegatronBertModel(config, add_pooling_layer=False)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(... | MegatronBertForTokenClassification |
python | django__django | django/contrib/gis/db/models/fields.py | {
"start": 7639,
"end": 11017
} | class ____(BaseSpatialField):
"""
The base Geometry field -- maps to the OpenGIS Specification Geometry type.
"""
description = _(
"The base Geometry field — maps to the OpenGIS Specification Geometry type."
)
form_class = forms.GeometryField
# The OpenGIS Geometry name.
geom_ty... | GeometryField |
python | ray-project__ray | python/ray/train/v2/api/config.py | {
"start": 8296,
"end": 9231
} | class ____(FailureConfigV1):
"""Configuration related to failure handling of each training run.
Args:
max_failures: Tries to recover a run from training worker errors at least this many times.
Will recover from the latest checkpoint if present.
Setting to -1 will lead to infinit... | FailureConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/errors_handlers.py | {
"start": 4829,
"end": 5937
} | class ____(HttpStatusErrorHandler):
"""
This custom error handler is needed for streams based on repository statistics endpoints like ContributorActivity because
when requesting data that hasn't been cached yet when the request is made, you'll receive a 202 response. And these requests
need to retried t... | ContributorActivityErrorHandler |
python | pytorch__pytorch | torch/distributed/_tools/sac_estimator.py | {
"start": 4241,
"end": 4799
} | class ____(NamedTuple):
"""
Represents Memory and Runtime Statistics for an operator/operator group.
Attributes:
func_names (set[str]): Set of operator/operator group names.
op_idx (int): Operator index (group head index in case of operator groups).
memory (int): Memory usage in byt... | MSPS |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 26372,
"end": 26554
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("BOARD_LAYOUT", "TABLE_LAYOUT")
| ProjectV2ViewLayout |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 8971,
"end": 10022
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_HUGGINGFACE, frozen=True, exclude=True
)
model: Optional[str]
passageModel: Optional[str]
queryModel: Optional[str]
endpointURL: Optional[AnyHttpUrl]
waitForModel: ... | _Text2VecHuggingFaceConfig |
python | PyCQA__pylint | tests/functional/d/disable_msg_github_issue_1389.py | {
"start": 301,
"end": 357
} | class ____(NamedTuple):
user: Dict[UserId, Set[Bar]]
| Foo |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_cache_test.py | {
"start": 1662,
"end": 1899
} | class ____(MockGenericType):
def most_specific_common_supertype(self, others):
if all([self._object == other._object for other in others]):
return MockIntGenericType(self._object)
else:
return None
| MockIntGenericType |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 25128,
"end": 27306
} | class ____(RenderedContent):
# NOTE: JPC 20191028 - review these keys to consolidate and group
def __init__( # noqa: PLR0913 # FIXME CoP
self,
sections,
data_asset_name=None,
full_data_asset_identifier=None,
renderer_type=None,
page_title=None,
utm_medium... | RenderedDocumentContent |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 38859,
"end": 41624
} | class ____(ValidationAction):
"""Action that pushes validations results to an SNS topic with a subject of passed or failed.
YAML configuration example:
```yaml
- name: send_sns_notification_on_validation_result
action:
class_name: SNSNotificationAction
# put the act... | SNSNotificationAction |
python | keras-team__keras | keras/src/utils/image_dataset_utils_test.py | {
"start": 304,
"end": 23111
} | class ____(testing.TestCase):
def _get_images(self, count=16, color_mode="rgb"):
width = height = 24
imgs = []
for _ in range(count):
if color_mode == "grayscale":
img = np.random.randint(0, 256, size=(height, width, 1))
elif color_mode == "rgba":
... | ImageDatasetFromDirectoryTest |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_type_test.py | {
"start": 8277,
"end": 19900
} | class ____(test.TestCase, parameterized.TestCase):
args_1_2_3 = {"args": (1, 2, 3), "kwargs": {}}
args_1_2_kwargs_z_3 = {"args": (1, 2), "kwargs": {"z": 3}}
kwargs_x_1_y_2_z_3 = {"args": (), "kwargs": {"x": 1, "y": 2, "z": 3}}
args_1_2 = {"args": (1, 2), "kwargs": {}}
args_1_kwargs_y_2 = {"args": (1,), "kwarg... | CanonicalizationTest |
python | protocolbuffers__protobuf | python/google/protobuf/internal/containers.py | {
"start": 21631,
"end": 23453
} | class ____:
"""UnknownField container"""
# Disallows assignment to other attributes.
__slots__ = ['_values']
def __init__(self):
self._values = []
def __getitem__(self, index):
if self._values is None:
raise ValueError('UnknownFields does not exist. '
'The parent messag... | UnknownFieldSet |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_looker_utils.py | {
"start": 1584,
"end": 3244
} | class ____(LookerComponent):
@cached_property
def looker_resource_cached(self) -> MockLookerResource:
return MockLookerResource(**self.looker_resource.model_dump())
# Store mock data as a class variable to share between methods
_mock_data = None
def write_state_to_path(self, state_path):
... | MockLookerComponent |
python | getsentry__sentry-python | sentry_sdk/integrations/sanic.py | {
"start": 1624,
"end": 3541
} | class ____(Integration):
identifier = "sanic"
origin = f"auto.http.{identifier}"
version = None
def __init__(self, unsampled_statuses=frozenset({404})):
# type: (Optional[Container[int]]) -> None
"""
The unsampled_statuses parameter can be used to specify for which HTTP statuses... | SanicIntegration |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/athena_sql.py | {
"start": 1343,
"end": 7238
} | class ____(AwsBaseHook, DbApiHook):
"""
Interact with Amazon Athena.
Provide wrapper around PyAthena library.
:param athena_conn_id: :ref:`Amazon Athena Connection <howto/connection:athena>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying... | AthenaSQLHook |
python | mlflow__mlflow | dev/clint/src/clint/rules/redundant_test_docstring.py | {
"start": 625,
"end": 5365
} | class ____(Rule):
def __init__(
self,
function_name: str | None = None,
has_class_docstring: bool = False,
is_module_docstring: bool = False,
) -> None:
self.function_name = function_name
self.has_class_docstring = has_class_docstring
self.is_module_docstr... | RedundantTestDocstring |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol13.py | {
"start": 354,
"end": 681
} | class ____:
def watch(self, key: str | None = None, max_time: int | None = None) -> None: ...
# This should not generate an error even though the "keys" and
# "max_time" parameters in Collection.watch are not marked as
# keyword-only parameters and are not in the same order.
col: CollectionProtocol = Collection()... | Collection |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/inferredTypes2.py | {
"start": 129,
"end": 443
} | class ____:
def __init__(self):
self.value = None
def func(self, param: int):
reveal_type(self.value, expected_text="int | None")
if self.value is not None:
reveal_type(self.value, expected_text="int")
self.value.bit_length()
self.value = param
| ClassA |
python | getsentry__sentry | src/sentry/releases/endpoints/organization_release_health_data.py | {
"start": 1023,
"end": 5061
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.TELEMETRY_EXPERIENCE
permission_classes = (OrganizationAndStaffPermission,)
"""
@deprecated This endpoint is not actively maintained
and its usages should be replaced with querie... | OrganizationReleaseHealthDataEndpoint |
python | huggingface__transformers | src/transformers/models/esm/openfold_utils/chunk_utils.py | {
"start": 11214,
"end": 14390
} | class ____:
def __init__(
self,
# Heuristically, runtimes for most of the modules in the network
# plateau earlier than this on all GPUs I've run the model on.
max_chunk_size: int = 512,
):
self.max_chunk_size = max_chunk_size
self.cached_chunk_size: Optional[int]... | ChunkSizeTuner |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 67349,
"end": 70531
} | class ____(RegexLexer):
"""
`Twig <http://twig.sensiolabs.org/>`_ template lexer.
It just highlights Twig code between the preprocessor directives,
other data is left untouched by the lexer.
.. versionadded:: 2.0
"""
name = 'Twig'
aliases = ['twig']
mimetypes = ['application/x-twi... | TwigLexer |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 4215,
"end": 4475
} | class ____(MetaflowException):
headline = "Unhandled artifacts in merge"
def __init__(self, msg, unhandled):
super(UnhandledInMergeArtifactsException, self).__init__(msg)
self.artifact_names = unhandled
| UnhandledInMergeArtifactsException |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 31495,
"end": 31758
} | class ____(AbstractTemplate):
#key = operator.eq
def generic(self, args, kws):
assert not kws
[va, vb] = args
if isinstance(va, types.Array) and va == vb:
return signature(va.copy(dtype=types.boolean), va, vb)
| CmpOpEqArray |
python | django-extensions__django-extensions | tests/management/commands/shell_plus_tests/test_utils.py | {
"start": 175,
"end": 2268
} | class ____(TestCase):
def setUp(self):
super().setUp()
sys.stdout = StringIO()
sys.stderr = StringIO()
self.imported_objects = {} # type: Dict[str, Type]
self.output = ""
def get_all_names_for_class(self, model_to_find_occurrences): # type: (Type) -> Set[str]
"... | AutomaticShellPlusImportsTestCase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py | {
"start": 142,
"end": 217
} | class ____(metaclass=ABCMeta):
@abstractmethod
def foo(self): pass
| A1 |
python | mitmproxy__pdoc | test/testdata/misc.py | {
"start": 5185,
"end": 5325
} | class ____(metaclass=Issue352aMeta):
def __init__(self):
"""Issue352.__init__ should be preferred over Meta.__call__."""
| Issue352a |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_legacy_checkpoints.py | {
"start": 2579,
"end": 5506
} | class ____(Callback):
def __init__(self, nb: int):
self.limit = nb
self._count = 0
def on_train_epoch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None:
self._count += 1
if self._count >= self.limit:
trainer.should_stop = True
@pytest.mark... | LimitNbEpochs |
python | PrefectHQ__prefect | tests/server/models/test_task_runs.py | {
"start": 5122,
"end": 5575
} | class ____:
async def test_read_task_run(self, task_run, session):
read_task_run = await models.task_runs.read_task_run(
session=session, task_run_id=task_run.id
)
assert task_run == read_task_run
async def test_read_task_run_returns_none_if_does_not_exist(self, session):
... | TestReadTaskRun |
python | sqlalchemy__sqlalchemy | test/sql/test_external_traversal.py | {
"start": 95331,
"end": 104484
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
"""Tests the generative capability of Insert, Update"""
__dialect__ = "default"
# fixme: consolidate converage from elsewhere here and expand
@classmethod
def setup_test_class(cls):
global t1, t2
t1 = table("table1", column("col1"... | ValuesBaseTest |
python | spack__spack | lib/spack/spack/concretize.py | {
"start": 8642,
"end": 9279
} | class ____(spack.error.SpackError):
"""Raised when there is no available compiler that satisfies a
compiler spec."""
def __init__(self, compiler_spec: CompilerSpec, arch: Optional[ArchSpec] = None) -> None:
err_msg = f"No compilers with spec {compiler_spec} found"
if arch:
err_m... | UnavailableCompilerVersionError |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 65893,
"end": 67882
} | class ____(SingleContinuousDistribution):
_argnames = ('mu', 's')
set = Interval(-oo, oo)
@staticmethod
def check(mu, s):
_value_check(s > 0, "Scale parameter s must be positive.")
def pdf(self, x):
mu, s = self.mu, self.s
return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))*... | LogisticDistribution |
python | huggingface__transformers | src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py | {
"start": 6102,
"end": 8962
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hi... | GraniteMoeHybridAttention |
python | RaRe-Technologies__gensim | gensim/test/test_similarities.py | {
"start": 77462,
"end": 79806
} | class ____(unittest.TestCase):
def setUp(self):
self.documents = [[u"government", u"denied", u"holiday"], [u"holiday", u"slowing", u"hollingworth"]]
self.dictionary = Dictionary(self.documents)
max_distance = max(len(term) for term in self.dictionary.values())
self.index = Levenshtei... | TestLevenshteinSimilarityIndex |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0090_dont_allow_ips_on_domains.py | {
"start": 189,
"end": 804
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0089_update_help_text"),
]
operations = [
migrations.AlterField(
model_name="domain",
name="domain",
field=models.CharField(
max_length=255,
... | Migration |
python | paramiko__paramiko | tests/test_channelfile.py | {
"start": 995,
"end": 1425
} | class ____:
def test_read_calls_channel_recv_stderr(self):
chan = MagicMock()
cf = ChannelStderrFile(chan)
cf.read(100)
chan.recv_stderr.assert_called_once_with(100)
def test_write_calls_channel_sendall(self):
chan = MagicMock()
cf = ChannelStderrFile(chan, mode=... | TestChannelStderrFile |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/qt5.py | {
"start": 7935,
"end": 8050
} | class ____(Task.Task):
color = 'BLUE'
run_str = '${QT_LRELEASE} ${QT_LRELEASE_FLAGS} ${SRC} -qm ${TGT}'
| ts2qm |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 56753,
"end": 56900
} | class ____(BaseModel):
"""Configuration for string inverted index."""
model_config = {"extra": "forbid"}
pass
| StringInvertedIndexConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/configurable.py | {
"start": 4718,
"end": 8461
} | class ____(ConfigurableDefinition):
"""An interface that makes the `configured` method require a positional `name` argument."""
def configured(
self,
config_or_config_fn: Any,
name: str,
config_schema: Optional[UserConfigSchema] = None,
description: Optional[str] = None,... | NamedConfigurableDefinition |
python | fastapi__sqlmodel | docs_src/tutorial/connect/update/tutorial001_py310.py | {
"start": 214,
"end": 2075
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqlite_url = ... | Hero |
python | gevent__gevent | src/gevent/tests/test__greenletset.py | {
"start": 4932,
"end": 5032
} | class ____(gevent.Greenlet):
pass
if __name__ == '__main__':
greentest.main()
| GreenletSubclass |
python | giampaolo__psutil | tests/__init__.py | {
"start": 8581,
"end": 21249
} | class ____(threading.Thread):
"""A thread task which does nothing expect staying alive."""
def __init__(self):
super().__init__()
self._running = False
self._interval = 0.001
self._flag = threading.Event()
def __repr__(self):
name = self.__class__.__name__
r... | ThreadTask |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_whoosh_backend.py | {
"start": 3345,
"end": 3806
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(model_attr="foo", document=True)
name = indexes.CharField(model_attr="author")
pub_date = indexes.DateTimeField(model_attr="pub_date")
text_auto = indexes.EdgeNgramField(model_attr="foo")
name_auto = indexes.EdgeNgramField(... | WhooshAutocompleteMockModelSearchIndex |
python | has2k1__plotnine | plotnine/geoms/geom_histogram.py | {
"start": 75,
"end": 367
} | class ____(geom_bar):
"""
Histogram
{usage}
Parameters
----------
{common_parameters}
See Also
--------
plotnine.geom_bar : The default `stat` for this `geom`.
"""
DEFAULT_PARAMS = {"stat": "bin", "position": "stack", "na_rm": False}
| geom_histogram |
python | getsentry__sentry | src/sentry/api/endpoints/release_thresholds/release_threshold_index.py | {
"start": 779,
"end": 1135
} | class ____(serializers.Serializer[ReleaseThresholdIndexGETData]):
environment = serializers.ListField(
required=False, allow_empty=True, child=serializers.CharField()
)
project = serializers.ListField(
required=True, allow_empty=False, child=serializers.IntegerField()
)
@region_silo_en... | ReleaseThresholdIndexGETValidator |
python | astral-sh__uv | crates/uv-python/fetch-download-metadata.py | {
"start": 2524,
"end": 3164
} | class ____:
# The architecture family, e.g. "x86_64", "aarch64".
family: str
# The architecture variant, e.g., "v2" in "x86_64_v2"
variant: str | None = None
def key(self) -> str:
return str(self)
def __str__(self) -> str:
return (self.family + "_" + self.variant) if self.varia... | Arch |
python | cherrypy__cherrypy | cherrypy/_cpdispatch.py | {
"start": 7622,
"end": 9467
} | class ____(PageHandler):
"""Page handler callable with delayed request parameters binding.
When passing ``cherrypy.request.params`` to the page handler, we do not
want to capture that dict too early; we want to give tools like the
decoding tool a chance to modify the params dict in-between the lookup
... | LateParamPageHandler |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/config_types.py | {
"start": 7918,
"end": 9765
} | class ____(graphene.ObjectType):
scalar_type = graphene.NonNull(GrapheneConfigType)
non_scalar_type = graphene.NonNull(GrapheneConfigType)
scalar_type_key = graphene.NonNull(graphene.String)
non_scalar_type_key = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneConfigType... | GrapheneScalarUnionConfigType |
python | walkccc__LeetCode | solutions/2806. Account Balance After Rounded Purchase/2806.py | {
"start": 0,
"end": 136
} | class ____:
def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
return 100 - ((purchaseAmount + 5) // 10) * 10
| Solution |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_math_ops.py | {
"start": 1239,
"end": 52629
} | class ____(Partial):
"""
This placement is used for partial vector norm.
For p-norms (where p not inf or -inf), the p-norm over n elements computes
(sum_i x_i^p)^(1/p)
where the sum is from i=1 to n. The reduction op is the p-norm itself.
For example, consider 2 ranks, a (4,) tensor sharded... | _NormPartial |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 7398,
"end": 7496
} | class ____(GISLookup):
lookup_name = "overlaps"
@BaseSpatialField.register_lookup
| OverlapsLookup |
python | doocs__leetcode | solution/0400-0499/0418.Sentence Screen Fitting/Solution.py | {
"start": 0,
"end": 378
} | class ____:
def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
s = " ".join(sentence) + " "
m = len(s)
cur = 0
for _ in range(rows):
cur += cols
if s[cur % m] == " ":
cur += 1
while cur and s[(cur - 1) % m] != ... | Solution |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 18832,
"end": 20695
} | class ____(Instruction):
def __init__(self, parent, ptr, indices, inbounds, name,
source_etype=None):
if source_etype is not None:
typ = ptr.type
self.source_etype = source_etype
# For compatibility with typed pointers. Eventually this should
# probab... | GEPInstr |
python | pytorch__pytorch | benchmarks/tensorexpr/conv.py | {
"start": 26,
"end": 2487
} | class ____(benchmark.Benchmark):
def __init__(self, case, mode, device, dtype, kernel_size, N, iC, H, W, oC):
super().__init__(mode, device, dtype)
self.case = case
self.kernel_size = kernel_size
self.N = N
self.iC = iC
self.H = H
self.W = W
self.oC = ... | ConvImplBench |
python | pypa__build | tests/test_projectbuilder.py | {
"start": 423,
"end": 1173
} | class ____(_importlib.metadata.Distribution):
def locate_file(self, path): # pragma: no cover
return ''
@classmethod
def from_name(cls, name):
if name == 'extras_dep':
return ExtraMockDistribution()
elif name == 'requireless_dep':
return RequirelessMockDistr... | MockDistribution |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 5307,
"end": 27368
} | class ____(fixtures.ORMTest):
def setup_test(self):
global MyTest, MyTest2
class MyTest:
pass
class MyTest2:
pass
def teardown_test(self):
global MyTest, MyTest2
MyTest, MyTest2 = None, None
def test_basic(self):
class User:
... | AttributesTest |
python | pypa__warehouse | tests/unit/admin/views/test_sponsors.py | {
"start": 1265,
"end": 2921
} | class ____(TestCase):
def setUp(self):
self.data = {
"name": "Sponsor",
"link_url": "https://newsponsor.com",
"color_logo_url": "http://domain.com/image.jpg",
}
def test_validate(self):
form = views.SponsorForm(formdata=MultiDict(self.data))
a... | TestSponsorForm |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 60296,
"end": 61223
} | class ____(Request):
"""
Get the number of task entries in the given queue
:param queue: ID of the queue
:type queue: str
"""
_service = "queues"
_action = "get_num_entries"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"queue": {"description": "ID... | GetNumEntriesRequest |
python | ansible__ansible | lib/ansible/cli/config.py | {
"start": 2691,
"end": 28512
} | class ____(CLI):
""" Config command line class """
name = 'ansible-config'
def __init__(self, args, callback=None):
self.config_file = None
self.config = None
super(ConfigCLI, self).__init__(args, callback)
def init_parser(self):
super(ConfigCLI, self).init_parser(
... | ConfigCLI |
python | arrow-py__arrow | tests/test_formatter.py | {
"start": 7682,
"end": 9553
} | class ____:
def test_atom(self):
assert (
self.formatter.format(self.datetime, FORMAT_ATOM)
== "1975-12-25 14:15:16-05:00"
)
def test_cookie(self):
assert (
self.formatter.format(self.datetime, FORMAT_COOKIE)
== "Thursday, 25-Dec-1975 14:1... | TestFormatterBuiltinFormats |
python | huggingface__transformers | src/transformers/models/table_transformer/modeling_table_transformer.py | {
"start": 26437,
"end": 31335
} | class ____(GradientCheckpointingLayer):
# Copied from transformers.models.detr.modeling_detr.DetrDecoderLayer.__init__ with Detr->TableTransformer
def __init__(self, config: TableTransformerConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = TableTransformerAtte... | TableTransformerDecoderLayer |
python | getsentry__sentry | src/sentry/search/events/builder/spans_indexed.py | {
"start": 3607,
"end": 4039
} | class ____(TimeseriesQueryBuilder):
config_class = SpansIndexedDatasetConfig
uuid_fields = SPAN_UUID_FIELDS
span_id_fields = SPAN_ID_FIELDS
duration_fields = DURATION_FIELDS
size_fields = SIZE_FIELDS
@property
def time_column(self) -> SelectType:
return custom_time_processor(
... | TimeseriesSpanIndexedQueryBuilder |
python | ray-project__ray | rllib/offline/mixed_input.py | {
"start": 439,
"end": 2030
} | class ____(InputReader):
"""Mixes input from a number of other input sources.
.. testcode::
:skipif: True
from ray.rllib.offline.io_context import IOContext
from ray.rllib.offline.mixed_input import MixedInput
ioctx = IOContext(...)
MixedInput({
"sampler": 0.... | MixedInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesloft/components.py | {
"start": 274,
"end": 860
} | class ____(DeclarativeSingleUseRefreshTokenOauth2Authenticator):
config: Config
def __post_init__(self):
self._connector_config = self.config
self._token_expiry_date_config_path = "credentials/token_expiry_date"
self.token_refresh_endpoint = "https://accounts.salesloft.com/oauth/token"
... | SingleUseOauth2Authenticator |
python | huggingface__transformers | src/transformers/models/plbart/modeling_plbart.py | {
"start": 58774,
"end": 63507
} | class ____(PLBartPreTrainedModel, GenerationMixin):
_tied_weights_keys = {
"lm_head.weight": "model.decoder.embed_tokens.weight",
}
def __init__(self, config):
config.is_decoder = True
config.is_encoder_decoder = False
super().__init__(config)
self.model = PLBartDeco... | PLBartForCausalLM |
python | sympy__sympy | sympy/polys/domains/gaussiandomains.py | {
"start": 16747,
"end": 22377
} | class ____(GaussianDomain[GaussianRational, MPQ], Field[GaussianRational]):
r"""Field of Gaussian rationals ``QQ_I``
The :ref:`QQ_I` domain represents the `Gaussian rationals`_ `\mathbb{Q}(i)`
as a :py:class:`~.Domain` in the domain system (see
:ref:`polys-domainsintro`).
By default a :py:class:`~... | GaussianRationalField |
python | pdm-project__pdm | src/pdm/cli/commands/cache.py | {
"start": 267,
"end": 2123
} | class ____(BaseCommand):
"""Control the caches of PDM"""
arguments = (verbose_option,)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
subparsers = parser.add_subparsers(title="commands", metavar="")
ClearCommand.register_to(subparsers, "clear")
RemoveCommand.regi... | Command |
python | sqlalchemy__sqlalchemy | test/orm/test_descriptor.py | {
"start": 495,
"end": 953
} | class ____(descriptor_props.DescriptorProperty):
def __init__(
self, cls, key, descriptor=None, doc=None, comparator_factory=None
):
self.parent = cls.__mapper__
self.key = key
self.doc = doc
self.descriptor = descriptor
if comparator_factory:
self._co... | MockDescriptor |
python | cherrypy__cherrypy | cherrypy/_cpserver.py | {
"start": 225,
"end": 8384
} | class ____(ServerAdapter):
"""An adapter for an HTTP server.
You can set attributes (like socket_host and socket_port)
on *this* object (which is probably cherrypy.server), and call
quickstart. For example::
cherrypy.server.socket_port = 80
cherrypy.quickstart()
"""
socket_por... | Server |
python | redis__redis-py | tests/test_parsers/test_errors.py | {
"start": 149,
"end": 4062
} | class ____:
"""Mock socket that simulates Redis protocol responses."""
def __init__(self):
self.sent_data = []
self.closed = False
self.pending_responses = []
def connect(self, address):
pass
def send(self, data):
"""Simulate sending data to Redis."""
i... | MockSocket |
python | psf__black | tests/data/cases/ignore_pyi.py | {
"start": 83,
"end": 190
} | class ____:
... # comment
# whitespace doesn't matter (note the next line has a trailing space and tab)
| y |
python | langchain-ai__langchain | libs/cli/langchain_cli/integration_template/tests/integration_tests/test_vectorstores.py | {
"start": 239,
"end": 759
} | class ____(VectorStoreIntegrationTests):
@pytest.fixture()
def vectorstore(self) -> Generator[VectorStore, None, None]: # type: ignore
"""Get an empty vectorstore for unit tests."""
store = __ModuleName__VectorStore(self.get_embeddings())
# note: store should be EMPTY at this point
... | Test__ModuleName__VectorStore |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_task_command.py | {
"start": 2777,
"end": 16182
} | class ____:
run_id = "TEST_RUN_ID"
dag_id = "example_python_operator"
parser: ArgumentParser
dagbag: DBDagBag
dag: DAG
dag_run: DagRun
@classmethod
def setup_class(cls):
parse_and_sync_to_db(os.devnull, include_examples=True)
cls.parser = cli_parser.get_parser()
... | TestCliTasks |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_v2_test.py | {
"start": 160790,
"end": 162078
} | class ____(lite_v2_test_util.ModelTest):
@test_util.run_v2_only
def testConstantFolding(self):
# Constant folding handles the tf.broadcast_to operation which was not
# supported by the TFLite at the time this test was added.
input_data = tf.constant(
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0... | GrapplerTest |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py | {
"start": 23838,
"end": 23935
} | class ____(CheckSection):
header = "Supported sync modes"
| CheckSupportedSyncModesSectionContent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.