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 | apache__airflow | dev/breeze/src/airflow_breeze/utils/projects_google_spreadsheet.py | {
"start": 1395,
"end": 9678
} | class ____(Enum):
KNOWN_REPUTABLE_FOUNDATIONS = auto()
KNOWN_STRONG_COMMUNITIES = auto()
KNOWN_COMPANIES = auto()
KNOWN_STABLE_PROJECTS = auto()
KNOWN_LOW_IMPORTANCE_PROJECTS = auto()
KNOWN_MEDIUM_IMPORTANCE_PROJECTS = auto()
KNOWN_HIGH_IMPORTANCE_PROJECTS = auto()
RELATIONSHIP_PROJECTS ... | MetadataFromSpreadsheet |
python | mlflow__mlflow | dev/clint/tests/rules/test_redundant_test_docstring.py | {
"start": 2262,
"end": 2637
} | class ____:
"""Test."""
pass
'''
config = Config(select={RedundantTestDocstring.name})
violations = lint_file(Path("regular_module.py"), code, config, index_path)
assert len(violations) == 0
def test_supports_test_suffix_files(index_path: Path) -> None:
code = '''
def test_feature_implementat... | TestFeature |
python | huggingface__transformers | src/transformers/models/plbart/modular_plbart.py | {
"start": 1818,
"end": 1863
} | class ____(BartEncoder):
pass
| PLBartEncoder |
python | realpython__materials | python-dict-attribute/salary.py | {
"start": 0,
"end": 371
} | class ____:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def give_raise(self, amount):
self.salery = self.salary + amount # Typo here: self.salery
john = Employee("John", "Engineering", 70000)
john.give_raise... | Employee |
python | getsentry__sentry | src/sentry/plugins/sentry_webhooks/client.py | {
"start": 46,
"end": 541
} | class ____(ApiClient):
plugin_name = "webhook"
allow_redirects = False
metrics_prefix = "integrations.webhook"
def __init__(self, data):
self.data = data
super().__init__(verify_ssl=False)
def request(self, url):
return self._request(
path=url,
metho... | WebhookApiClient |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 7006,
"end": 7335
} | class ____(graphene.ObjectType):
experiment_id = graphene.String()
name = graphene.String()
artifact_location = graphene.String()
lifecycle_stage = graphene.String()
last_update_time = LongString()
creation_time = LongString()
tags = graphene.List(graphene.NonNull(MlflowExperimentTag))
| MlflowExperiment |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 615059,
"end": 616090
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"advisory",
"first_patched_version",
"package",
"severity",
"updated_at",
"vulnerable_version_range",
)
advisory = sgqlc.types... | SecurityVulnerability |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/contextmanager.py | {
"start": 2506,
"end": 2914
} | class ____(Generic[T], metaclass=ContextStackMeta):
_context: deque[T]
@classmethod
def push(cls, obj: T):
cls._context.appendleft(obj)
@classmethod
def pop(cls) -> T | None:
return cls._context.popleft()
@classmethod
def get_current(cls) -> T | None:
try:
... | ContextStack |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 1475,
"end": 1631
} | class ____(Form):
first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"}))
last_name = CharField()
birthday = DateField()
| PersonNew |
python | huggingface__transformers | src/transformers/models/llava_onevision/image_processing_llava_onevision.py | {
"start": 3866,
"end": 38631
} | class ____(BaseImageProcessor):
r"""
Constructs a LLaVa-Onevision image processor. Based on [`SiglipImageProcessor`] with incorporation of processing each video frame.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to t... | LlavaOnevisionImageProcessor |
python | pytorch__pytorch | torch/distributed/algorithms/join.py | {
"start": 1396,
"end": 2842
} | class ____(ABC):
r"""
This defines an abstract base class for joinable classes.
A joinable class
(inheriting from :class:`Joinable`) should implement :meth:`join_hook`,
which returns a :class:`JoinHook` instance, in addition to
:meth:`join_device` and :meth:`join_process_group` that return devi... | Joinable |
python | joke2k__faker | faker/providers/internet/ar_AA/__init__.py | {
"start": 46,
"end": 1047
} | class ____(InternetProvider):
replacements = (
("س", "s"),
("ق", "q"),
("ب", "b"),
("خ", "x"),
("ش", "$"),
("َ", "a"),
("ئ", "}"),
("إ", "<"),
("ل", "l"),
("ٰ", "`"),
("ف", "f"),
("و", "w"),
("ض", "D"),
(... | Provider |
python | walkccc__LeetCode | solutions/173. Binary Search Tree Iterator/173-2.py | {
"start": 0,
"end": 420
} | class ____:
def __init__(self, root: TreeNode | None):
self.stack = []
self._pushLeftsUntilNull(root)
def next(self) -> int:
root = self.stack.pop()
self._pushLeftsUntilNull(root.right)
return root.val
def hasNext(self) -> bool:
return self.stack
def _pushLeftsUntilNull(self, root: Tr... | BSTIterator |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/advanced_models.py | {
"start": 5426,
"end": 6262
} | class ____(LightningModule):
def __init__(self):
super().__init__()
self.rnn = nn.LSTM(10, 20, batch_first=True)
self.linear_out = nn.Linear(in_features=20, out_features=5)
self.example_input_array = torch.rand(2, 3, 10)
self._loss = [] # needed for checking if the loss is t... | ParityModuleRNN |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 76579,
"end": 82109
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "account_performance_report_hourly"
report_file = "account_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "account_performance_report_hourly_incremental"
repor... | TestAccountPerformanceReportHourlyStream |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/attrs/test_inference.py | {
"start": 3942,
"end": 4164
} | class ____:
x: int = attr.ib(alias="crazyname")
@pytest.mark.parametrize("s", [st.just(42)])
def test_aliased_attribute(s):
check_can_generate_examples(st.builds(HasAliasedAttribute, crazyname=s))
| HasAliasedAttribute |
python | GoogleCloudPlatform__python-docs-samples | healthcare/api-client/v1/fhir/fhir_resources_test.py | {
"start": 2240,
"end": 12015
} | class ____(Exception):
"""Operation is not yet complete"""
pass
@retry.Retry(predicate=retry.if_exception_type(OperationNotComplete))
def wait_for_operation(operation_name: str):
operation = (
client.projects()
.locations()
.datasets()
.operations()
.get(name=opera... | OperationNotComplete |
python | fluentpython__example-code-2e | 10-dp-1class-func/untyped/strategy_param2.py | {
"start": 2316,
"end": 2616
} | class ____(Promotion):
"""discount for each LineItem with 20 or more units"""
def __call__(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * self.percent / 100
return discount
| BulkItemPromo |
python | dask__dask | dask/tests/test_tokenize.py | {
"start": 26556,
"end": 41373
} | class ____:
def __init__(self, val) -> None:
self.val = val
def test_local_objects():
class LocalType:
foo = "bar"
class LocalReducible:
def __reduce__(self):
return LocalReducible, ()
class LocalDaskTokenize:
def __dask_tokenize__(self):
retur... | GlobalClass |
python | spyder-ide__spyder | spyder/api/widgets/comboboxes.py | {
"start": 11966,
"end": 13053
} | class ____(_SpyderComboBoxMixin, QFontComboBox):
def __init__(self, parent=None):
QFontComboBox.__init__(self, parent)
_SpyderComboBoxMixin.__init__(self)
# Avoid font name eliding because it confuses users.
# Fixes spyder-ide/spyder#22683
self.setItemDelegate(
... | SpyderFontComboBox |
python | wandb__wandb | wandb/vendor/pygments/lexers/python.py | {
"start": 805,
"end": 11159
} | class ____(RegexLexer):
"""
For `Python <http://www.python.org>`_ source code.
"""
name = 'Python'
aliases = ['python', 'py', 'sage']
filenames = ['*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac', '*.sage']
mimetypes = ['text/x-python', 'application/x-python']
def innerstri... | PythonLexer |
python | ansible__ansible | test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py | {
"start": 361,
"end": 1209
} | class ____(ConnectionBase):
transport = 'ns.name.dummy'
def __init__(self, *args, **kwargs):
self._cmds_run = 0
super().__init__(*args, **kwargs)
@property
def connected(self):
return True
def _connect(self):
return
def exec_command(self, cmd, in_data=None, s... | Connection |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 509,
"end": 742
} | class ____(SocialAuthBaseException):
"""Stop pipeline process exception.
Raise this exception to stop the rest of the pipeline process.
"""
def __str__(self) -> str:
return gettext("Stop pipeline")
| StopPipeline |
python | numpy__numpy | numpy/polynomial/tests/test_legendre.py | {
"start": 16132,
"end": 16539
} | class ____:
def test_raises(self):
assert_raises(ValueError, leg.legcompanion, [])
assert_raises(ValueError, leg.legcompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0] * i + [1]
assert_(leg.legcompanion(coef).shape == (i, i))
def tes... | TestCompanion |
python | getsentry__sentry | src/sentry/debug/utils/exception_reporter_filter.py | {
"start": 121,
"end": 260
} | class ____(SafeExceptionReporterFilter):
def get_safe_settings(self) -> dict[str, Any]:
return {}
| NoSettingsExceptionReporterFilter |
python | kubernetes-client__python | kubernetes/client/api/events_v1_api.py | {
"start": 543,
"end": 120463
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | EventsV1Api |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py | {
"start": 135,
"end": 1364
} | class ____(Benchmark):
r"""
Hansen objective function.
This class defines the Hansen [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Hansen}}(x) = \left[ \sum_{i=0}^4(i+1)\cos(ix_1+i+1)\right ]
\left[\sum_{j=0}^4(... | Hansen |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 21975,
"end": 22149
} | class ____(models.Model):
history = HistoricalRecords(inherit=True, custom_model_name=lambda x: f"Audit{x}")
class Meta:
abstract = True
| AbstractModelCallable1 |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 26962,
"end": 29371
} | class ____(AggregateFnV2[SupportsRichComparisonType, SupportsRichComparisonType]):
"""Defines absolute max aggregation.
Example:
.. testcode::
import ray
from ray.data.aggregate import AbsMax
ds = ray.data.range(100)
# Schema: {'id': int64}
... | AbsMax |
python | django__django | tests/db_functions/text/test_left.py | {
"start": 164,
"end": 1313
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(name_part=Left("name", 5))
self.assertQuerySetEqual(
a... | LeftTests |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 21296,
"end": 21428
} | class ____(models.Model):
greeting = models.CharField(max_length=100)
history = HistoricalRecords()
| CharFieldChangeReasonModel |
python | pytorch__pytorch | torch/_higher_order_ops/foreach_map.py | {
"start": 200,
"end": 690
} | class ____(BaseHOP):
def __init__(self):
super().__init__("foreach_map")
def __call__(self, fn, *operands, **kwargs): # type: ignore[override]
fn = FunctionWithNoFreeVars(fn)
return super().__call__(fn, *operands, **kwargs)
_foreach_map = ForeachMap()
def foreach_map(op: Callable, ... | ForeachMap |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-surveymonkey/source_surveymonkey/streams.py | {
"start": 4495,
"end": 5974
} | class ____(SurveymonkeyStream, CheckpointMixin, ABC):
state_checkpoint_interval = 1000
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._state = None
@property
@abstractmethod
def cursor_field(self) -> str:
pass
@property
def state(self) -> MutableMapp... | IncrementalSurveymonkeyStream |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 2236,
"end": 2270
} | class ____(Co[Co[T_co]]): ...
| CoToCo |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 65785,
"end": 66218
} | class ____(_PrintableStructure):
_fields_ = [
('processName', c_char * NVML_VGPU_NAME_BUFFER_SIZE),
('timeStamp', c_ulonglong),
('vgpuInstance', _nvmlVgpuInstance_t),
('pid', c_uint),
('smUtil', c_uint),
('memUtil', c_uint),
('encUtil', c_uint),
('decU... | c_nvmlVgpuProcessUtilizationInfo_v1_t |
python | tox-dev__tox | src/tox/report.py | {
"start": 2980,
"end": 3111
} | class ____(BytesIO):
def __init__(self, name: str) -> None:
super().__init__()
self.name: str = name
| NamedBytesIO |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/project_preprod_artifact_download.py | {
"start": 1654,
"end": 6414
} | class ____(PreprodArtifactEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"HEAD": ApiPublishStatus.PRIVATE,
}
authentication_classes = (
LaunchpadRpcSignatureAuthentication,
SessionAuthentication,
UserAuthTokenAuthentic... | ProjectPreprodArtifactDownloadEndpoint |
python | allegroai__clearml | examples/distributed/pytorch_distributed_example.py | {
"start": 1527,
"end": 6655
} | class ____(object):
def __init__(self, data, sizes=(0.7, 0.2, 0.1), seed=1234):
self.data = data
self.partitions = []
rng = Random()
rng.seed(seed)
data_len = len(data)
indexes = [x for x in range(0, data_len)]
rng.shuffle(indexes)
for frac in sizes:
... | DataPartitioner |
python | wandb__wandb | wandb/apis/importers/internals/protocols.py | {
"start": 327,
"end": 2885
} | class ____(Protocol):
def run_id(self) -> str: ... # pragma: no cover
def entity(self) -> str: ... # pragma: no cover
def project(self) -> str: ... # pragma: no cover
def config(self) -> Dict[str, Any]: ... # pragma: no cover
def summary(self) -> Dict[str, float]: ... # pragma: no cover
... | ImporterRun |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 26645,
"end": 26758
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Pop'
strategy_class = FileStrategy
| PopHostname |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/unary_test.py | {
"start": 483,
"end": 4237
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, device, op_func):
self.inputs = {"input": torch.rand(M, N, device=device)}
self.op_func = op_func
def forward(self, input):
return self.op_func(input)
def bernoulli_(input):
return input.bernoulli_()
def cauchy_(input... | UnaryOpBenchmark |
python | getsentry__sentry-python | tests/integrations/grpc/test_grpc_aio.py | {
"start": 8911,
"end": 10019
} | class ____(gRPCTestServiceServicer):
class TestException(Exception):
__test__ = False
def __init__(self):
super().__init__("test")
@classmethod
async def TestServe(cls, request, context): # noqa: N802
with start_span(
op="test",
name="test",
... | TestService |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 30116,
"end": 40000
} | class ____(WhisperPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`WhisperDecoderLayer`]
Args:
config: WhisperConfig
"""
main_input_name = "input_ids"
def __init__(self, config: WhisperConfig):
super().__init__(config)
... | WhisperDecoder |
python | apache__thrift | tutorial/php/runserver.py | {
"start": 976,
"end": 1124
} | class ____(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ['/php']
BaseHTTPServer.HTTPServer(('', 8080), Handler).serve_forever()
| Handler |
python | Pylons__pyramid | src/pyramid/authorization.py | {
"start": 2665,
"end": 8419
} | class ____:
"""A helper for use with constructing a :term:`security policy` which
consults an :term:`ACL` object attached to a :term:`context` to determine
authorization information about a :term:`principal` or multiple principals.
If the context is part of a :term:`lineage`, the context's parents are
... | ACLHelper |
python | PrefectHQ__prefect | src/prefect/cli/transfer/_migratable_resources/work_pools.py | {
"start": 709,
"end": 5691
} | class ____(MigratableResource[WorkPool]):
_instances: dict[uuid.UUID, Self] = {}
def __init__(self, work_pool: WorkPool, default_queue: WorkQueue):
self.source_work_pool = work_pool
self.source_default_queue = default_queue
self.destination_work_pool: WorkPool | None = None
self... | MigratableWorkPool |
python | mozilla__bleach | bleach/_vendor/html5lib/html5parser.py | {
"start": 2675,
"end": 117091
} | class ____(object):
"""HTML parser
Generates a tree structure from a stream of (possibly malformed) HTML.
"""
def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False):
"""
:arg tree: a treebuilder class controlling the type of tree that will be
... | HTMLParser |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_decorators_1.py | {
"start": 454,
"end": 489
} | class ____:
x: array
@dataclass
| D |
python | spyder-ide__spyder | spyder/api/plugins/enum.py | {
"start": 1811,
"end": 1872
} | class ____:
EnvManager = "spyder_env_manager"
| OptionalPlugins |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py | {
"start": 13138,
"end": 13685
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
inputs = constant_op.constant(
np.int8(0), shape=[3, 3, 3, 3], dtype=dtypes.quint8)
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
... | QuantizedReluOpTest |
python | walkccc__LeetCode | solutions/3258. Count Substrings That Satisfy K-Constraint I/3258.py | {
"start": 0,
"end": 288
} | class ____:
def countKConstraintSubstrings(self, s: str, k: int) -> int:
ans = 0
count = [0, 0]
l = 0
for r, c in enumerate(s):
count[int(c)] += 1
while min(count) > k:
count[int(s[l])] -= 1
l += 1
ans += r - l + 1
return ans
| Solution |
python | django__django | tests/raw_query/models.py | {
"start": 31,
"end": 627
} | class ____(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
dob = models.DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Protect against annotations being passed to __init__ --
# this'l... | Author |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 156261,
"end": 158624
} | class ____:
def test_describe(self):
assert self.locale.describe("now", only_distance=True) == "no nettopp"
assert self.locale.describe("now", only_distance=False) == "no nettopp"
def test_plurals(self):
assert self.locale._format_timeframe("now", 0) == "no nettopp"
assert self.... | TestNewNorwegianLocale |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 18767,
"end": 20225
} | class ____(Transform):
r"""
Transform via the mapping :math:`y = x^{\text{exponent}}`.
"""
domain = constraints.positive
codomain = constraints.positive
bijective = True
def __init__(self, exponent: Tensor, cache_size: int = 0) -> None:
super().__init__(cache_size=cache_size)
... | PowerTransform |
python | pytorch__pytorch | torch/testing/_internal/autograd_function_db.py | {
"start": 7644,
"end": 9113
} | class ____(torch.autograd.Function):
generate_vmap_rule = True
@staticmethod
def forward(x, dim):
ind = torch.argsort(x, dim=dim)
ind_inv = torch.argsort(ind, axis=dim)
result = torch.take_along_dim(x, ind, dim=dim)
return result, ind, ind_inv
@staticmethod
def setu... | SortGenVmap |
python | huggingface__transformers | tests/models/dpr/test_modeling_dpr.py | {
"start": 6660,
"end": 9059
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
DPRContextEncoder,
DPRQuestionEncoder,
DPRReader,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = {"feature-extraction": DPRQuestionE... | DPRModelTest |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_legacy_slugs.py | {
"start": 2513,
"end": 3080
} | class ____(util.MdCase):
"""Test GitHub Flavored Markdown style slugs."""
extension = ['markdown.extensions.toc']
extension_configs = {
'markdown.extensions.toc': {
"slugify": slugs.gfm
}
}
def test_slug(self):
"""Test the slug output."""
with pytest.wa... | TestGFM |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/advanced_activations.py | {
"start": 5826,
"end": 6926
} | class ____(Layer):
"""Exponential Linear Unit.
It follows:
```
f(x) = alpha * (exp(x) - 1.) for x < 0
f(x) = x for x >= 0
```
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer i... | ELU |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 1514,
"end": 4912
} | class ____(BaseClient):
def create_artifact(self, artifact: "ArtifactCreate") -> "Artifact":
response = self.request(
"POST",
"/artifacts/",
json=artifact.model_dump(mode="json", exclude_unset=True),
)
from prefect.client.schemas.objects import Artifact
... | ArtifactClient |
python | instagram__MonkeyType | monkeytype/stubs.py | {
"start": 17915,
"end": 19451
} | class ____(Stub):
def __init__(
self,
name: str,
signature: inspect.Signature,
kind: FunctionKind,
strip_modules: Optional[Iterable[str]] = None,
is_async: bool = False,
) -> None:
self.name = name
self.signature = signature
self.kind = kin... | FunctionStub |
python | pandas-dev__pandas | pandas/core/indexes/multi.py | {
"start": 3580,
"end": 3904
} | class ____(libindex.BaseMultiIndexCodesEngine, libindex.UInt8Engine):
"""Manages a MultiIndex by mapping label combinations to positive integers.
The number of possible label combinations must not overflow the 8 bits integers.
"""
_base = libindex.UInt8Engine
_codes_dtype = "uint8"
| MultiIndexUInt8Engine |
python | Lightning-AI__lightning | src/lightning/pytorch/core/mixins/hparams_mixin.py | {
"start": 1466,
"end": 6980
} | class ____:
__jit_unused_properties__: list[str] = ["hparams", "hparams_initial"]
def __init__(self) -> None:
super().__init__()
self._log_hyperparams = False
def save_hyperparameters(
self,
*args: Any,
ignore: Optional[Union[Sequence[str], str]] = None,
fra... | HyperparametersMixin |
python | doocs__leetcode | solution/0600-0699/0650.2 Keys Keyboard/Solution2.py | {
"start": 0,
"end": 318
} | class ____:
def minSteps(self, n: int) -> int:
dp = list(range(n + 1))
dp[1] = 0
for i in range(2, n + 1):
j = 2
while j * j <= i:
if i % j == 0:
dp[i] = min(dp[i], dp[i // j] + j)
j += 1
return dp[-1]
| Solution |
python | doocs__leetcode | lcci/05.02.Binary Number to String/Solution.py | {
"start": 0,
"end": 247
} | class ____:
def printBin(self, num: float) -> str:
ans = '0.'
while len(ans) < 32 and num:
num *= 2
x = int(num)
ans += str(x)
num -= x
return 'ERROR' if num else ans
| Solution |
python | pytorch__pytorch | test/test_multiprocessing_spawn.py | {
"start": 9929,
"end": 10158
} | class ____:
SLEEP_SECS = 5
# Simulate startup overhead such as large imports
time.sleep(SLEEP_SECS)
def __init__(self):
self.config: str = "*" * 1000000
def my_call(self, *args):
pass
| Expensive |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 49618,
"end": 49836
} | class ____(VOTableSpecWarning):
"""
A VOTable cannot have a DATA section without any defined FIELD; DATA will be ignored.
"""
message_template = "No FIELDs are defined; DATA section will be ignored."
| E25 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 1476,
"end": 1719
} | class ____(graphene.ObjectType):
lineage = non_null_list(GrapheneTableColumnLineageEntry)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "TableColumnLineageMetadataEntry"
| GrapheneTableColumnLineageMetadataEntry |
python | getsentry__sentry | tests/sentry/workflow_engine/test_integration.py | {
"start": 20386,
"end": 21651
} | class ____(BaseWorkflowIntegrationTest):
@override_options({"workflow_engine.issue_alert.group.type_id.rollout": [6001]})
@with_feature("organizations:workflow-engine-single-process-workflows")
def test_workflow_engine(self) -> None:
occurrence_data = self.build_occurrence_data(
type=Fee... | TestWorkflowEngineIntegrationFromFeedbackPostProcess |
python | hynek__structlog | src/structlog/twisted.py | {
"start": 3564,
"end": 4224
} | class ____:
"""
Wrap a string and return it as the ``__repr__``.
This is needed for ``twisted.python.log.err`` that calls `repr` on
``_stuff``:
>>> repr("foo")
"'foo'"
>>> repr(ReprWrapper("foo"))
'foo'
Note the extra quotes in the unwrapped example.
"""
def __init__(self... | ReprWrapper |
python | plotly__plotly.py | plotly/graph_objs/splom/_legendgrouptitle.py | {
"start": 233,
"end": 2925
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "splom"
_path_str = "splom.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified a... | Legendgrouptitle |
python | tiangolo__fastapi | fastapi/params.py | {
"start": 10929,
"end": 14078
} | class ____(Param): # type: ignore[misc]
in_ = ParamTypes.header
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Unio... | Header |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/training_status.py | {
"start": 1709,
"end": 4323
} | class ____:
"""
GlobalTrainingStatus class that contains static methods to save global training status and
load it on a resume. These are values that might be needed for the training resume that
cannot/should not be captured in a model checkpoint, such as curriclum lesson.
"""
saved_state: Dict... | GlobalTrainingStatus |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 10696,
"end": 11284
} | class ____(IOMultipleNetCDF):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
requires_dask()
self.make_ds()
self.format = "NETCDF4"
xr.save_mfdataset(self.ds_list, self.filename... | IOReadMultipleNetCDF4 |
python | django__django | tests/queries/tests.py | {
"start": 77630,
"end": 77767
} | class ____(TestCase):
def test_ticket7371(self):
self.assertQuerySetEqual(Related.objects.order_by("custom"), [])
| CustomPkTests |
python | tornadoweb__tornado | tornado/test/curl_httpclient_test.py | {
"start": 2495,
"end": 2671
} | class ____(RequestHandler):
def get(self):
self.set_status(400, "Custom reason")
@unittest.skipIf(pycurl is None, "pycurl module not present")
| CustomFailReasonHandler |
python | sympy__sympy | sympy/stats/joint_rv.py | {
"start": 10602,
"end": 12655
} | class ____(Distribution, NamedArgsMixin):
"""
Represented by the random variables part of the joint distribution.
Contains methods for PDF, CDF, sampling, marginal densities, etc.
"""
_argnames = ('pdf', )
def __new__(cls, *args):
args = list(map(sympify, args))
for i in range(... | JointDistribution |
python | getsentry__sentry | src/sentry/new_migrations/monkey/special.py | {
"start": 94,
"end": 1263
} | class ____(RunSQL):
def __init__(self, *args, use_statement_timeout=True, **kwargs):
super().__init__(*args, **kwargs)
self.use_statement_timeout = use_statement_timeout
def _run_sql(self, schema_editor, sqls):
use_statement_timeout = (
settings.ZERO_DOWNTIME_MIGRATIONS_STAT... | SafeRunSQL |
python | lepture__authlib | authlib/integrations/base_client/sync_app.py | {
"start": 2560,
"end": 3938
} | class ____:
client_cls = None
def __init__(
self,
framework,
name=None,
fetch_token=None,
client_id=None,
client_secret=None,
request_token_url=None,
request_token_params=None,
access_token_url=None,
access_token_params=None,
... | OAuth1Base |
python | fastai__fastai | fastai/learner.py | {
"start": 3426,
"end": 3618
} | class ____():
"Returns a function that returns `o`"
def __init__(self, o): self.o = o
def __call__(self, *args, **kwargs): return self.o
# %% ../nbs/13a_learner.ipynb 22
| _ConstantFunc |
python | PrefectHQ__prefect | tests/cli/transfer/test_work_pools.py | {
"start": 464,
"end": 23380
} | class ____:
async def test_construct_creates_new_instance_and_reads_default_queue(
self, transfer_work_pool: WorkPool
):
"""Test that construct creates a new MigratableWorkPool instance and reads default queue."""
# Clear any existing instances
MigratableWorkPool._instances.clear... | TestMigratableWorkPool |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_kinesis_analytics.py | {
"start": 1416,
"end": 1667
} | class ____:
@pytest.fixture(autouse=True)
def mock_conn(self, monkeypatch):
self.client = boto3.client("kinesisanalyticsv2")
monkeypatch.setattr(KinesisAnalyticsV2Hook, "conn", self.client)
| TestKinesisAnalyticsV2CustomWaitersBase |
python | pytorch__pytorch | torch/_inductor/mkldnn_ir.py | {
"start": 34106,
"end": 38077
} | class ____(ExternKernelAlloc):
def __init__(
self,
layout,
inputs,
constant_args=(),
has_bias=True,
) -> None:
"""
if bias is not None
- inputs = [x, w, x_scale, x_zp, weight_scale, weight_zp, x2, bias]
- const_args is: [o_scale, o_... | QLinearPointwiseBinaryPT2E |
python | pennersr__django-allauth | allauth/socialaccount/providers/telegram/views.py | {
"start": 892,
"end": 2857
} | class ____(View):
def get(self, request):
return render(request, "telegram/callback.html")
def post(self, request):
adapter = get_adapter()
provider = adapter.get_provider(request, TelegramProvider.id)
state_id = request.GET.get("state")
if not state_id:
ret... | CallbackView |
python | skorch-dev__skorch | skorch/llm/classifier.py | {
"start": 9362,
"end": 21564
} | class ____(ClassifierMixin, BaseEstimator):
"""Base class for LLM models
This class handles a few of the checks, as well as the whole prediction
machinery.
Required attributes are:
- model_name
- model
- tokenizer
- prompt
- probas_sum_to_1
- device
- error_low_prob
- ... | _LlmBase |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/ftp_to_s3.py | {
"start": 1171,
"end": 6414
} | class ____(BaseOperator):
"""
Transfer of one or more files from an FTP server to S3.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:FTPToS3Operator`
:param ftp_path: The ftp remote path. For one file it is mandatory to inc... | FTPToS3Operator |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 36381,
"end": 37050
} | class ____(DelegatingLexer):
"""
Subclass of `ErbLexer` which highlights unlexed data with the
`JavascriptLexer`.
"""
name = 'JavaScript+Ruby'
aliases = ['js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+ruby',
... | JavascriptErbLexer |
python | apache__airflow | shared/configuration/tests/configuration/test_parser.py | {
"start": 1217,
"end": 2666
} | class ____(_SharedAirflowConfigParser):
"""Test parser that extends shared parser for testing."""
def __init__(self, default_config: str | None = None, *args, **kwargs):
configuration_description = {
"test": {
"options": {
"key1": {"default": "default_val... | AirflowConfigParser |
python | gevent__gevent | src/gevent/_ffi/watcher.py | {
"start": 15862,
"end": 17143
} | class ____(object):
_watcher_type = 'timer'
def __init__(self, loop, after=0.0, repeat=0.0, ref=True, priority=None):
if repeat < 0.0:
raise ValueError("repeat must be positive or zero: %r" % repeat)
self._after = after
self._repeat = repeat
super(TimerMixin, self)._... | TimerMixin |
python | celery__celery | celery/utils/collections.py | {
"start": 12761,
"end": 20274
} | class ____:
"""Kind-of Set (or priority queue) with limitations.
Good for when you need to test for membership (`a in set`),
but the set should not grow unbounded.
``maxlen`` is enforced at all times, so if the limit is reached
we'll also remove non-expired items.
You can also configure ``min... | LimitedSet |
python | agronholm__apscheduler | src/apscheduler/triggers/cron/fields.py | {
"start": 1030,
"end": 3039
} | class ____:
__slots__ = "expressions", "name"
real: ClassVar[bool] = True
compilers: ClassVar[Any] = (AllExpression, RangeExpression)
def __init_subclass__(cls, real: bool = True, extra_compilers: Sequence = ()):
cls.real = real
if extra_compilers:
cls.compilers += extra_co... | BaseField |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_tabbed.py | {
"start": 16767,
"end": 17905
} | class ____(util.MdCase):
"""Test legacy tab slug separator cases."""
extension = ['pymdownx.tabbed', 'toc']
extension_configs = {'pymdownx.tabbed': {'slugify': slugify(case='lower'), 'separator': '_'}}
MD = """
### Here is some text
=== "Here is some text"
content
=== "Here is so... | TestLegacyTabSlugsSep |
python | pallets__flask | tests/test_json.py | {
"start": 3617,
"end": 8741
} | class ____(datetime.tzinfo):
"""Fixed offset in hours east from UTC.
This is a slight adaptation of the ``FixedOffset`` example found in
https://docs.python.org/2.7/library/datetime.html.
"""
def __init__(self, hours, name):
self.__offset = datetime.timedelta(hours=hours)
self.__na... | FixedOffset |
python | walkccc__LeetCode | solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py | {
"start": 0,
"end": 830
} | class ____:
def connectTwoGroups(self, cost: list[list[int]]) -> int:
# minCosts[j] := the minimum cost of connecting group2's point j
minCosts = [min(col) for col in zip(*cost)]
@functools.lru_cache(None)
def dp(i: int, mask: int) -> int:
"""
Returns the minimum cost to connect group1's ... | Solution |
python | django__django | django/db/migrations/operations/models.py | {
"start": 40703,
"end": 42754
} | class ____(IndexOperation):
category = OperationCategory.ADDITION
option_name = "constraints"
def __init__(self, model_name, constraint):
self.model_name = model_name
self.constraint = constraint
def state_forwards(self, app_label, state):
state.add_constraint(app_label, self.m... | AddConstraint |
python | PrefectHQ__prefect | src/prefect/server/utilities/database.py | {
"start": 2184,
"end": 3473
} | class ____(functions.FunctionElement[uuid.UUID]):
"""
Platform-independent UUID default generator.
Note the actual functionality for this class is specified in the
`compiles`-decorated functions below
"""
name = "uuid_default"
@compiles(GenerateUUID, "postgresql")
def generate_uuid_postgresql... | GenerateUUID |
python | huggingface__transformers | src/transformers/models/longformer/modeling_longformer.py | {
"start": 26290,
"end": 54984
} | class ____(nn.Module):
def __init__(self, config, layer_id):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({con... | LongformerSelfAttention |
python | sqlalchemy__sqlalchemy | test/orm/test_options.py | {
"start": 41430,
"end": 42927
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(30), nullable=False),
)
Table(
"addresses",
met... | PickleTest |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 262714,
"end": 264045
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('entryCount', c_uint),
('entries', POINTER(c_nvmlEccSramUniqueUncorrectedErrorEntry_v1_t))
]
def __init__(self):
super(c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t, self).__init__(version=nvmlEccSramUnique... | c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t |
python | apache__avro | lang/py/avro/schema.py | {
"start": 10288,
"end": 12003
} | class ____(Schema):
"""Named Schemas specified in NAMED_TYPES."""
def __init__(
self,
type_: str,
name: str,
namespace: Optional[str] = None,
names: Optional[Names] = None,
other_props: Optional[Mapping[str, object]] = None,
validate_names: bool = True,
... | NamedSchema |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/align.py | {
"start": 7941,
"end": 10529
} | class ____(JupyterMixin):
"""Vertically aligns a renderable.
Warn:
This class is deprecated and may be removed in a future version. Use Align class with
`vertical="middle"`.
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional sty... | VerticalCenter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.