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 | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/daemon.py | {
"start": 1809,
"end": 1938
} | class ____(BaseModel):
useThreads: bool
numWorkers: Optional[int] = None
numSubmitWorkers: Optional[int] = None
| Sensors |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 20055,
"end": 20445
} | class ____(PointEvent):
''' Announce the end of a pan event on a Bokeh plot.
Attributes:
sx (float) : x-coordinate of the event in *screen* space
sy (float) : y-coordinate of the event in *screen* space
x (float) : x-coordinate of the event in *data* space
y (float) : y-coordina... | PanEnd |
python | sphinx-doc__sphinx | sphinx/io.py | {
"start": 2261,
"end": 3429
} | class ____(SphinxBaseReader):
"""A basic document reader for Sphinx."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
warnings.warn(
'sphinx.io.SphinxStandaloneReader is deprecated',
RemovedInSphinx10Warning,
stackle... | SphinxStandaloneReader |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/graph.py | {
"start": 3775,
"end": 4137
} | class ____:
"""Schema for Hexadecimal color codes for different node types.
Args:
default: The default color code.
first: The color code for the first node.
last: The color code for the last node.
"""
default: str = "fill:#f2f0ff,line-height:1.2"
first: str = "fill-opacity:... | NodeStyles |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/unit_tests.py | {
"start": 7788,
"end": 8284
} | class ____(ConfigurableResource): ...
@asset
def asset_requires_service(service: MyServiceResource): ...
@asset
def other_asset_requires_service(service: MyServiceResource): ...
def test_assets_require_service():
# Mock objects can be provided directly.
result = materialize_to_memory(
[asset_requi... | MyServiceResource |
python | ray-project__ray | python/ray/dag/tests/experimental/test_torch_tensor_transport.py | {
"start": 20494,
"end": 21572
} | class ____:
"""Tests worker to driver tensor transport with CPU device."""
def test_src_cpu_tensor(self, ray_start_regular):
actor = Actor.remote()
ref = run_worker_to_driver_dag(actor, "cpu", "cpu")
tensor = ray.get(ref)
assert str(tensor.device) == "cpu"
@pytest.mark.skip... | TestWorkerToDriverDeviceCPU |
python | huggingface__transformers | src/transformers/models/metaclip_2/modular_metaclip_2.py | {
"start": 30322,
"end": 33176
} | class ____(CLIPVisionModelWithProjection):
"""
MetaClip2 vision model with a projection layer on top (a linear layer on top of the pooled output).
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as d... | MetaClip2VisionModelWithProjection |
python | getsentry__sentry | src/sentry/projects/services/project/serial.py | {
"start": 366,
"end": 1482
} | class ____(serializers.Serializer[ProjectUpdateArgs]):
name = serializers.CharField(
help_text="The name for the project",
max_length=200,
required=False,
)
slug = SentrySerializerSlugField(
help_text="Uniquely identifies a project and is used for the interface.",
max... | ProjectUpdateArgsSerializer |
python | pdm-project__pdm | src/pdm/models/repositories/lock.py | {
"start": 1093,
"end": 14124
} | class ____(BaseRepository):
def __init__(
self,
lockfile: Mapping[str, Any],
sources: list[RepositoryConfig],
environment: BaseEnvironment,
env_spec: EnvSpec | None = None,
) -> None:
super().__init__(sources, environment, env_spec=env_spec or environment.spec)
... | LockedRepository |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 30379,
"end": 31240
} | class ____(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer = UnspecInlinableModule()
self.step = 10
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + 1
return self.layer(x) + self.step
def make_test(fn, expected_ops=None):
def test_fn(... | UnspecModuleWithIntAttr |
python | pypa__pip | src/pip/_vendor/rich/layout.py | {
"start": 680,
"end": 883
} | class ____(NamedTuple):
"""An individual layout render."""
region: Region
render: List[List[Segment]]
RegionMap = Dict["Layout", Region]
RenderMap = Dict["Layout", LayoutRender]
| LayoutRender |
python | pypa__build | src/build/env.py | {
"start": 10222,
"end": 14241
} | class ____(_EnvBackend):
def create(self, path: str) -> None:
import venv
self._env_path = path
try:
import uv
self._uv_bin = uv.find_uv_bin()
except (ModuleNotFoundError, FileNotFoundError):
uv_bin = shutil.which('uv')
if uv_bin is ... | _UvBackend |
python | openai__openai-python | src/openai/types/responses/response_output_message.py | {
"start": 527,
"end": 1104
} | class ____(BaseModel):
id: str
"""The unique ID of the output message."""
content: List[Content]
"""The content of the output message."""
role: Literal["assistant"]
"""The role of the output message. Always `assistant`."""
status: Literal["in_progress", "completed", "incomplete"]
"""T... | ResponseOutputMessage |
python | ethereum__web3.py | web3/types.py | {
"start": 6183,
"end": 6284
} | class ____(SubscriptionResponse):
result: Literal[False] | SyncProgress
| SyncingSubscriptionResponse |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-deepinfra/llama_index/llms/deepinfra/base.py | {
"start": 1391,
"end": 16541
} | class ____(FunctionCallingLLM):
"""
DeepInfra LLM.
Examples:
`pip install llama-index-llms-deepinfra`
```python
from llama_index.llms.deepinfra import DeepInfraLLM
llm = DeepInfraLLM(
model="mistralai/Mixtral-8x22B-Instruct-v0.1", # Default model name
... | DeepInfraLLM |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 3068,
"end": 3924
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def active(self):
raise NotImplementedError()
def __call__(self, name_or_index):
raise NotImplementedError()
def __len__(self):
raise NotImplementedError()
def add(self):
ra... | Books |
python | pennersr__django-allauth | allauth/socialaccount/providers/gumroad/provider.py | {
"start": 221,
"end": 343
} | class ____(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("url")
| GumroadAccount |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py | {
"start": 40,
"end": 124
} | class ____:
def __len__(self):
return True # [invalid-length-return]
| Bool |
python | uqfoundation__dill | dill/tests/test_restricted.py | {
"start": 340,
"end": 783
} | class ____:
def __bool__(*args, **kwargs):
raise Exception('Restricted function')
__eq__ = __lt__ = __le__ = __ne__ = __gt__ = __ge__ = __hash__ = __bool__
glob_obj = RestrictedType()
def restricted_func():
a = glob_obj
def test_function_with_restricted_object():
deserialized = dill.loads(di... | RestrictedType |
python | walkccc__LeetCode | solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py | {
"start": 0,
"end": 891
} | class ____:
def maxSelectedElements(self, nums: list[int]) -> int:
ans = 1
prev = -math.inf
# the length of the longest consecutive elements (seq0) ending in the
# previous number
dp0 = 1
# the length of the longest consecutive elements (seq1) ending in the
# previous number + 1
dp1 = ... | Solution |
python | pytorch__pytorch | torch/_ops.py | {
"start": 1394,
"end": 10726
} | class ____:
"""
Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator
(which represents Python-only operators that are unrepresentable in TorchScript).
"""
def __init__(self):
# The dispatch cache precomputes a mapping of dispatch key that the
# dis... | OperatorBase |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_format_returned.py | {
"start": 331,
"end": 463
} | class ____:
"""__format__ returns <type 'str'>"""
def __format__(self, format_spec):
return str(123)
| SecondGoodFormat |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 9130,
"end": 9306
} | class ____(str, Enum):
"""
Enum for DAG Run states when updating a DAG Run.
"""
QUEUED = "queued"
SUCCESS = "success"
FAILED = "failed"
| DAGRunPatchStates |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_index_serialize.py | {
"start": 333,
"end": 2071
} | class ____(unittest.TestCase):
def test_serialize(self):
res = faiss.StandardGpuResources()
d = 32
k = 10
train = make_t(10000, d)
add = make_t(10000, d)
query = make_t(10, d)
# Construct various GPU index types
indexes = []
# Flat
i... | TestGpuSerialize |
python | coleifer__peewee | tests/models.py | {
"start": 145851,
"end": 147623
} | class ____(PGOnConflictTests, ModelTestCase):
database = get_in_memory_db()
@skip_if(IS_SQLITE_24, 'requires sqlite < 3.24')
def test_no_preserve_update_where(self):
# Ensure on SQLite < 3.24 we cannot update or preserve values.
base = Emp.insert(first='foo', last='bar', empno='125')
... | TestUpsertSqlite |
python | numpy__numpy | benchmarks/benchmarks/bench_random.py | {
"start": 955,
"end": 1648
} | class ____(Benchmark):
high = {
'bool': 1,
'uint8': 2**7,
'uint16': 2**15,
'uint32': 2**31,
'uint64': 2**63
}
param_names = ['dtype']
params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64']
def setup(self, name):
from numpy.lib import NumpyVersi... | Randint_dtype |
python | huggingface__transformers | src/transformers/models/gpt_oss/modeling_gpt_oss.py | {
"start": 28162,
"end": 32622
} | class ____(GptOssPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = GptOss... | GptOssForCausalLM |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/workflow_serializer.py | {
"start": 536,
"end": 3652
} | class ____(Serializer):
def get_attrs(
self, item_list: Sequence[Workflow], user, **kwargs
) -> MutableMapping[Workflow, dict[str, Any]]:
attrs: MutableMapping[Workflow, dict[str, Any]] = defaultdict(dict)
trigger_conditions = list(
DataConditionGroup.objects.filter(
... | WorkflowSerializer |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 17958,
"end": 18083
} | class ____(ExampleViewSet):
permission_classes = []
http_method_names = ['get', 'head', 'options']
| MethodLimitedViewSet |
python | getsentry__sentry | src/sentry/notifications/platform/templates/sample.py | {
"start": 4384,
"end": 4679
} | class ____(NotificationData):
source = "deployment-service"
project_name: str
version: str
environment: str
deployer: str
commit_sha: str
commit_message: str
deployment_url: str
rollback_url: str
@template_registry.register(DeploymentData.source)
| DeploymentData |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 229636,
"end": 230226
} | 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("CommitEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.ty... | CommitConnection |
python | pypa__setuptools | setuptools/_distutils/tests/test_build_py.py | {
"start": 299,
"end": 6882
} | class ____(support.TempdirManager):
def test_package_data(self):
sources = self.mkdtemp()
jaraco.path.build(
{
'__init__.py': "# Pretend this is a package.",
'README.txt': 'Info about this package',
},
sources,
)
de... | TestBuildPy |
python | pytorch__pytorch | torch/ao/quantization/fx/_model_report/detector.py | {
"start": 17392,
"end": 34345
} | class ____(DetectorBase):
r"""
Determines whether dynamic or static quantization is more appropriate for a given module.
Takes advantage of the ModelReportObserver that records range information.
Stationary distribution of data are strictly above tolerance level for the comparison statistic:
S... | DynamicStaticDetector |
python | kubernetes-client__python | kubernetes/client/models/v1_capacity_request_policy_range.py | {
"start": 383,
"end": 6167
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1CapacityRequestPolicyRange |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 18450,
"end": 25671
} | class ____(CodegenAST):
"""
Represents a block of code.
Explanation
===========
For now only assignments are supported. This restriction will be lifted in
the future.
Useful attributes on this object are:
``left_hand_sides``:
Tuple of left-hand sides of assignments, in order.... | CodeBlock |
python | automl__auto-sklearn | test/test_pipeline/components/feature_preprocessing/test_fast_ica.py | {
"start": 276,
"end": 1715
} | class ____(PreprocessingTestCase):
def test_default_configuration(self):
transformation, original = _test_preprocessing(FastICA, dataset="diabetes")
self.assertEqual(transformation.shape[0], original.shape[0])
self.assertFalse((transformation == 0).all())
def test_default_configuration_... | FastICAComponentTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/embedding.py | {
"start": 908,
"end": 1311
} | class ____(BaseEvent):
"""
EmbeddingStartEvent.
Args:
model_dict (dict): Model dictionary containing details about the embedding model.
"""
model_config = ConfigDict(protected_namespaces=("pydantic_model_",))
model_dict: dict
@classmethod
def class_name(cls) -> str:
"... | SparseEmbeddingStartEvent |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k.py | {
"start": 116,
"end": 1487
} | class ____(object):
def findMaximumNumber(self, k, x):
"""
:type k: int
:type x: int
:rtype: int
"""
def floor_log2(x):
return x.bit_length()-1
def binary_search_right(left, right, check):
while left <= right:
mid = lef... | Solution |
python | dask__dask | dask/array/random.py | {
"start": 708,
"end": 17670
} | class ____:
"""
Container for the BitGenerators.
``Generator`` exposes a number of methods for generating random
numbers drawn from a variety of probability distributions and serves
as a replacement for ``RandomState``. The main difference between the
two is that ``Generator`` relies on an addi... | Generator |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 12626,
"end": 12829
} | class ____(Stmt):
"""A node that represents the include tag."""
fields = ("template", "with_context", "ignore_missing")
template: "Expr"
with_context: bool
ignore_missing: bool
| Include |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 17265,
"end": 18710
} | class ____(nn.Module):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, embedding_dim=256):
super().__init__()
self.row_embeddings = nn.Embedding(50, embedding_dim)
self.column_embeddings = nn.Embedding(50, embedding_dim)
def f... | DetrLearnedPositionEmbedding |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-azcognitive-search/llama_index/readers/azcognitive_search/base.py | {
"start": 331,
"end": 2070
} | class ____(BaseReader):
"""
General reader for any Azure Cognitive Search index reader.
Args:
service_name (str): the name of azure cognitive search service.
search_key (str): provide azure search access key directly.
index (str): index name
"""
def __init__(self, service_... | AzCognitiveSearchReader |
python | pypa__setuptools | setuptools/_distutils/tests/test_build_ext.py | {
"start": 22341,
"end": 22539
} | class ____(TestBuildExt):
def build_ext(self, *args, **kwargs):
build_ext = super().build_ext(*args, **kwargs)
build_ext.parallel = True
return build_ext
| TestParallelBuildExt |
python | getsentry__sentry | src/sentry/interfaces/contexts.py | {
"start": 6017,
"end": 6178
} | class ____(ContextType):
type = "device"
context_to_tag_mapping = {"": "{model}", "family": "{family}"}
# model_id, arch
@contexttype
| DeviceContextType |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 13108,
"end": 13148
} | class ____:
literal: Literal[1, 2]
| Base |
python | pytest-dev__pytest | testing/test_terminal.py | {
"start": 98743,
"end": 110958
} | class ____:
DEFAULT_FILE_CONTENTS = """
import pytest
@pytest.mark.parametrize("i", range(4))
def test_ok(i):
'''
some docstring
'''
pass
def test_fail():
assert False
"""
... | TestFineGrainedTestCase |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py | {
"start": 45962,
"end": 48046
} | class ____(TestQueuedEventEndpoint):
@pytest.mark.usefixtures("time_freezer")
def test_should_respond_204(self, test_client, session, create_dummy_dag):
dag, _ = create_dummy_dag()
dag_id = dag.dag_id
self.create_assets(session=session, num=1)
asset_id = 1
self._create_as... | TestDeleteDagDatasetQueuedEvents |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 8908,
"end": 9047
} | class ____:
xlAllocateIncrement = 2 # from enum XlAllocationValue
xlAllocateValue = 1 # from enum XlAllocationValue
| AllocationValue |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/np_einsum_test.py | {
"start": 1099,
"end": 9188
} | class ____(tntu.TestCase):
def _check(self, s, *ops):
a = np.einsum(s, *ops)
b = tnp.einsum(s, *ops)
self.assertAllClose(a, b, check_dtypes=True, atol=1e-4, rtol=1e-4)
def test_three_operands_1(self):
r = self.rng()
x = r.randn(3)
y = r.randn(4)
z = r.randn(5)
s = 'i,j,k->ijk'
... | EinsumTest |
python | openai__gym | gym/envs/toy_text/blackjack.py | {
"start": 974,
"end": 10806
} | class ____(gym.Env):
"""
Blackjack is a card game where the goal is to beat the dealer by obtaining cards
that sum to closer to 21 (without going over 21) than the dealers cards.
### Description
Card Values:
- Face cards (Jack, Queen, King) have a point value of 10.
- Aces can either count... | BlackjackEnv |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/widgets/tests/test_remotekernels.py | {
"start": 835,
"end": 3578
} | class ____:
def test_start_stop_kernel(
self, ipyconsole, remote_client, remote_client_id, qtbot
):
"""Starts and stops a kernel on the remote server."""
ipyconsole.get_widget().create_ipyclient_for_server(remote_client_id)
shell = ipyconsole.get_current_shellwidget()
qt... | TestIpythonConsole |
python | spack__spack | var/spack/test_repos/spack_repo/diff/packages/p3/package.py | {
"start": 217,
"end": 291
} | class ____(Package):
version("1.0")
variant("p3var", default=True)
| P3 |
python | allegroai__clearml | clearml/binding/frameworks/fastai_bind.py | {
"start": 463,
"end": 1102
} | class ____(object):
@staticmethod
def update_current_task(task: Any, **_: Any) -> None:
if fastai is None:
return
# noinspection PyBroadException
try:
if Version(fastai.__version__) < Version("2.0.0"):
PatchFastaiV1.update_current_task(task)
... | PatchFastai |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 280303,
"end": 280797
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ReopenDiscussion"""
__schema__ = github_schema
__field_names__ = ("discussion_id", "client_mutation_id")
discussion_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="discussionId")
"""ID of the discussion to be reopened."""
... | ReopenDiscussionInput |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/combine_documents/map_rerank.py | {
"start": 1029,
"end": 9396
} | class ____(BaseCombineDocumentsChain):
r"""Combining documents by mapping a chain over them, then reranking results.
This algorithm calls an LLMChain on each input document. The LLMChain is expected
to have an OutputParser that parses the result into both an answer (`answer_key`)
and a score (`rank_key... | MapRerankDocumentsChain |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 26831,
"end": 27066
} | class ____(TestSimpleHttpsBase):
"""Connect to HTTPS hosts where the certificate are issued to an ip instead of a domain."""
keyfile = "keys/localhost.ip.key"
certfile = "keys/localhost.ip.crt"
| TestHttpsInvalidDNSPatternBase |
python | kamyu104__LeetCode-Solutions | Python/maximum-cost-of-trip-with-k-highways.py | {
"start": 1568,
"end": 2427
} | class ____(object):
def maximumCost(self, n, highways, k):
"""
:type n: int
:type highways: List[List[int]]
:type k: int
:rtype: int
"""
if k+1 > n: # required to optimize, otherwise, TLE or MLE
return -1
adj = [[] for _ in xrange(n)]
... | Solution2 |
python | huggingface__transformers | src/transformers/models/wavlm/modeling_wavlm.py | {
"start": 33095,
"end": 39499
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
# feature dim might need to be down-projected
if config.output_hidden_size != config.hidden_size:
self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
self.proj_layer_norm = nn.Laye... | WavLMAdapter |
python | dask__dask | dask/dataframe/dask_expr/datasets.py | {
"start": 3572,
"end": 6847
} | class ____:
def __init__(self, dtypes, columns, freq, kwargs):
self.dtypes = dtypes
self.columns = columns
self.freq = freq
self.kwargs = kwargs
def __call__(self, start, end, state_data):
dtypes = self.dtypes
columns = self.columns
freq = self.freq
... | MakeTimeseriesPart |
python | openai__openai-python | src/openai/types/beta/assistant_update_params.py | {
"start": 6612,
"end": 6937
} | class ____(TypedDict, total=False):
vector_store_ids: SequenceNotStr[str]
"""
Overrides the
[vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)
attached to this assistant. There can be a maximum of 1 vector store attached to
the assistant.
"""
| ToolResourcesFileSearch |
python | gevent__gevent | src/gevent/tests/test__example_echoserver.py | {
"start": 170,
"end": 1198
} | class ____(util.TestServer):
example = 'echoserver.py'
def _run_all_tests(self):
def test_client(message):
if greentest.PY3:
kwargs = {'buffering': 1}
else:
kwargs = {'bufsize': 1}
kwargs['mode'] = 'rb'
conn = create_connec... | Test |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 41663,
"end": 44089
} | class ____(_InverseTrigonometric1D):
"""
One dimensional ArcTangent model returning values between -pi/2 and
pi/2 only.
Parameters
----------
amplitude : float
Oscillation amplitude for corresponding Tangent
frequency : float
Oscillation frequency for corresponding Tangent
... | ArcTangent1D |
python | walkccc__LeetCode | solutions/429. N-ary Tree Level Order Traversal/429.py | {
"start": 0,
"end": 387
} | class ____:
def levelOrder(self, root: 'Node') -> list[list[int]]:
if not root:
return []
ans = []
q = collections.deque([root])
while q:
currLevel = []
for _ in range(len(q)):
node = q.popleft()
currLevel.append(node.val)
for child in node.children:
... | Solution |
python | scrapy__scrapy | tests/test_command_startproject.py | {
"start": 3911,
"end": 10287
} | class ____:
def test_startproject_template_override(self, tmp_path: Path) -> None:
tmpl = tmp_path / "templates"
tmpl_proj = tmpl / "project"
project_name = "testproject"
copytree(Path(scrapy.__path__[0], "templates"), tmpl)
(tmpl_proj / "root_template").write_bytes(b"")
... | TestStartprojectTemplates |
python | h5py__h5py | h5py/tests/test_vds/test_highlevel_vds.py | {
"start": 15887,
"end": 17852
} | class ____(ut.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self.path = osp.join(self.tmpdir, "resize.h5")
with h5.File(self.path, "w") as f:
source_dset = f.create_dataset(
"source",
data=np.arange(20),
shape=(10, 2... | VDSUnlimitedTestCase |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 3836,
"end": 4975
} | class ____:
params = [np.nan, 0]
param_names = ["fill_value"]
def setup(self, fill_value):
N = 10**6
self.arr1 = self.make_block_array(
length=N, num_blocks=1000, block_size=10, fill_value=fill_value
)
self.arr2 = self.make_block_array(
length=N, num_... | ArithmeticBlock |
python | ray-project__ray | python/ray/data/_internal/datasource/parquet_datasource.py | {
"start": 5724,
"end": 10303
} | class ____:
"""Result of splitting a predicate by column type.
Attributes:
data_predicate: Expression containing only data column predicates
(for PyArrow pushdown), or None if no data predicates exist.
partition_predicate: Expression containing only partition column predicates
... | _SplitPredicateResult |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 750,
"end": 901
} | class ____(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, *args, **kwargs):
pass
| ExampleDetailView |
python | realpython__materials | python-serialize/http-payload/django-rest-api/rest_api/models.py | {
"start": 78,
"end": 272
} | class ____(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=200)
created_at = models.DateTimeField(default=timezone.now)
| User |
python | pytorch__pytorch | torch/_inductor/template_heuristics/decompose_k.py | {
"start": 1265,
"end": 2382
} | class ____(GemmMaxAutotuneTemplateConfigHeuristics):
def _get_template_configs_impl(
self,
kernel_inputs: KernelInputs,
op_name: str,
) -> Generator[dict[str, Any], None, None]:
"""
Get all the valid k_splits for the given m, n, k.
"""
assert isinstance(ke... | DecomposeKConfigHeuristics |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 377148,
"end": 377902
} | class ____(ValueChannelMixin, core.PositionValueDef):
"""
Longitude2Value schema wrapper.
Definition object for a constant value (primitive value or gradient definition) of an
encoding channel.
Parameters
----------
value : dict, float, :class:`ExprRef`, Literal['height', 'width']
... | Longitude2Value |
python | celery__celery | celery/backends/s3.py | {
"start": 299,
"end": 2752
} | class ____(KeyValueStoreBackend):
"""An S3 task result store.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`boto3` is not available,
if the :setting:`aws_access_key_id` or
setting:`aws_secret_access_key` are not set,
or it the :setting:... | S3Backend |
python | pyca__cryptography | tests/hazmat/primitives/test_ec.py | {
"start": 7177,
"end": 8349
} | class ____:
def test_with_numbers(self, backend, subtests):
vectors = itertools.product(
load_vectors_from_file(
os.path.join(
"asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp"
),
load_fips_ecdsa_key_pair_vectors,
)... | TestECWithNumbers |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 9514,
"end": 13494
} | class ____(GoogleCloudBaseOperator):
"""
Export Redis instance data into a Redis RDB format file in Cloud Storage.
Redis will continue serving during this operation.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudMemor... | CloudMemorystoreExportInstanceOperator |
python | nedbat__coveragepy | tests/test_api.py | {
"start": 44641,
"end": 45104
} | class ____(CoverageTest):
"""Check that reporting methods don't permanently change the configuration."""
def test_config_doesnt_change(self) -> None:
self.make_file("simple.py", "a = 1")
cov = coverage.Coverage()
self.start_import_stop(cov, "simple")
assert cov.get_option("repor... | ImmutableConfigTest |
python | Textualize__textual | docs/examples/widgets/progress_bar_gradient.py | {
"start": 166,
"end": 868
} | class ____(App[None]):
"""Progress bar with a rainbow gradient."""
def compose(self) -> ComposeResult:
gradient = Gradient.from_colors(
"#881177",
"#aa3355",
"#cc6666",
"#ee9944",
"#eedd00",
"#99dd55",
"#44dd88",
... | ProgressApp |
python | getsentry__sentry | src/sentry/migrations/0938_rm_eventattachment_fileid_part1.py | {
"start": 239,
"end": 1527
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | django__django | tests/admin_filters/tests.py | {
"start": 7638,
"end": 7744
} | class ____(DecadeFilterBookAdmin):
show_facets = ShowFacets.ALWAYS
| DecadeFilterBookAdminWithAlwaysFacets |
python | doocs__leetcode | solution/3300-3399/3339.Find the Number of K-Even Arrays/Solution.py | {
"start": 0,
"end": 508
} | class ____:
def countOfArrays(self, n: int, m: int, k: int) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if j < 0:
return 0
if i >= n:
return int(j == 0)
return (
cnt1 * dfs(i + 1, j, 1) + cnt0 * dfs(i + 1,... | Solution |
python | conda__conda | conda/core/portability.py | {
"start": 1503,
"end": 16066
} | class ____(Exception):
pass
def _subdir_is_win(subdir: str) -> bool:
"""
Determine if the given `subdir` corresponds to a Windows operating system.
:param subdir: The subdirectory name which may contain an OS identifier.
:return: Returns True if `subdir` indicates a Windows OS; otherwise, False.
... | _PaddingError |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_memorystore.py | {
"start": 9220,
"end": 18661
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
self.hook = CloudMemorystoreHook(gcp_conn_id="test")
@mock.patch("air... | TestCloudMemorystoreWithoutDefaultProjectIdHook |
python | PyCQA__pylint | tests/benchmark/test_baseline_benchmarks.py | {
"start": 1680,
"end": 2424
} | class ____(BaseRawFileChecker):
"""A checker that sleeps, the wall-clock time should reduce as we add workers.
As we apply a roughly constant amount of "work" in this checker any variance is
likely to be caused by the pylint system.
"""
name = "long-sleeper"
msgs = {
"R9999": (
... | SleepingCheckerLong |
python | ipython__ipython | IPython/utils/sentinel.py | {
"start": 157,
"end": 454
} | class ____:
def __init__(self, name: str, module: str, docstring: str | None = None) -> None:
self.name = name
self.module = module
if docstring:
self.__doc__ = docstring
def __repr__(self) -> str:
return str(self.module) + "." + self.name
| Sentinel |
python | jazzband__prettytable | tests/test_json.py | {
"start": 85,
"end": 1693
} | class ____:
def test_json_output(self, helper_table: PrettyTable) -> None:
result = helper_table.get_json_string()
assert (
result.strip()
== """
[
[
"",
"Field 1",
"Field 2",
"Field 3"
],
{
"": 1,
"Field 1": "value ... | TestJSONOutput |
python | geekcomputers__Python | JsonParser.py | {
"start": 14,
"end": 1452
} | class ____:
"""
this class to handle anything related to json file [as implementation of facade pattern]
"""
def convert_json_to_python(self, par_json_file):
"""
this function to convert any json file format to dictionary
args: the json file
return: dictionary contains j... | JsonParser |
python | getsentry__sentry | tests/sentry/grouping/seer_similarity/test_seer_eligibility.py | {
"start": 730,
"end": 12344
} | class ____(TestCase):
def setUp(self) -> None:
self.event_data = {
"title": "FailedToFetchError('Charlie didn't bring the ball back')",
"exception": {
"values": [
{
"type": "FailedToFetchError",
"valu... | ShouldCallSeerTest |
python | jpadilla__pyjwt | jwt/types.py | {
"start": 2524,
"end": 2772
} | class ____(TypedDict):
verify_signature: bool
require: list[str]
strict_aud: bool
verify_aud: bool
verify_exp: bool
verify_iat: bool
verify_iss: bool
verify_jti: bool
verify_nbf: bool
verify_sub: bool
| FullOptions |
python | pytorch__pytorch | torch/_inductor/codegen/multi_kernel.py | {
"start": 5284,
"end": 11316
} | class ____:
"""
This class maintains the compile time state for multi kernels.
Assume we do codegen for a MultiKernel encapsulating kernel1 and kernel2.
The generated definition for the multi-kernel will looks like:
```
multi_kernel_kernel1 = MultiKernelCall(
[kernel1, kernel2], multi_k... | MultiKernel |
python | dask__dask | dask/dataframe/dask_expr/_util.py | {
"start": 3700,
"end": 6503
} | class ____:
"""Helper class to wrap backend data
The primary purpose of this class is to provide
caching outside the ``FromPandas`` class.
"""
def __init__(self, data):
self._data = data
self._division_info = LRU(10)
@functools.cached_property
def _token(self):
fro... | _BackendData |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/resolution_tests/test_resolvable_model.py | {
"start": 287,
"end": 576
} | class ____(BaseModel, dg.Resolvable):
val1_renamed: Annotated[
int,
dg.Resolver(
resolve_val1,
model_field_type=str,
model_field_name="val1",
inject_before_resolve=False,
),
]
val2: Optional[str]
| InnerObject |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 8024,
"end": 8276
} | class ____(WeaviateQueryError):
"""Is raised if a gRPC delete many request to Weaviate fails in any way."""
def __init__(self, message: str):
super().__init__(message, "GRPC delete")
self.message = message
| WeaviateDeleteManyError |
python | Netflix__metaflow | metaflow/plugins/aws/step_functions/step_functions.py | {
"start": 848,
"end": 962
} | class ____(MetaflowException):
headline = "AWS Step Functions scheduling error"
| StepFunctionsSchedulingException |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/prefetch_test.py | {
"start": 5042,
"end": 6652
} | class ____(test_base.DatasetTestBase,
parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 10, 11])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Data... | PrefetchRandomAccessTest |
python | getsentry__sentry | src/sentry/issues/ignored.py | {
"start": 1200,
"end": 5958
} | class ____(TypedDict, total=False):
ignoreCount: int | None
ignoreUntil: datetime | None
ignoreUserCount: int | None
ignoreUserWindow: int | None
ignoreWindow: int | None
actor: User | None
def handle_archived_until_escalating(
group_list: Sequence[Group],
acting_user: RpcUser | User |... | IgnoredStatusDetails |
python | scipy__scipy | scipy/optimize/_root_scalar.py | {
"start": 409,
"end": 20391
} | class ____:
"""Decorator that caches the value and derivative(s) of function each
time it is called.
This is a simplistic memoizer that calls and caches a single value
of ``f(x, *args)``.
It assumes that `args` does not change between invocations.
It supports the use case of a root-finder where... | MemoizeDer |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 873412,
"end": 874696
} | class ____(Geometry):
"""
Polygon schema wrapper.
Polygon geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.6
Parameters
----------
coordinates : Sequence[Sequence[Sequence[float], :class:`Position`]]
type : Literal['Polygon']
Specifies the type of GeoJSON object.
... | Polygon |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 55306,
"end": 55530
} | class ____(ToFrame):
_parameters = ["frame", "index", "name"]
_defaults = {"name": no_default, "index": True}
_keyword_only = ["name", "index"]
operation = M.to_frame
_filter_passthrough = True
| ToFrameIndex |
python | facebook__pyre-check | client/commands/tests/pyre_server_options_test.py | {
"start": 940,
"end": 2220
} | class ____(testslide.TestCase):
def test_create(self) -> None:
language_server_features = features.LanguageServerFeatures()
start_arguments = start.Arguments(
backend_arguments.BaseArguments(
source_paths=backend_arguments.SimpleSourcePath(),
log_path="/lo... | ServerOptionsTest |
python | huggingface__transformers | src/transformers/models/dia/processing_dia.py | {
"start": 1239,
"end": 1843
} | class ____(ProcessingKwargs, total=False):
audio_kwargs: DiaAudioKwargs
_defaults = {
"text_kwargs": {
"padding": True,
"padding_side": "right",
"add_special_tokens": False,
},
"audio_kwargs": {
"eos_token_id": 1024,
"pad_token_... | DiaProcessorKwargs |
python | django__django | tests/servers/tests.py | {
"start": 15214,
"end": 15856
} | class ____(LiveServerBase):
"""If LiveServerTestCase isn't threaded, these tests will hang."""
def test_view_calls_subview(self):
url = "/subview_calling_view/?%s" % urlencode({"url": self.live_server_url})
with self.urlopen(url) as f:
self.assertEqual(f.read(), b"subview calling vi... | LiveServerThreadedTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.