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 | scipy__scipy | scipy/signal/_czt.py | {
"start": 3259,
"end": 8797
} | class ____:
"""
Create a callable chirp z-transform function.
Transform to compute the frequency response around a spiral.
Objects of this class are callables which can compute the
chirp z-transform on their inputs. This object precalculates the constant
chirps used in the given transform.
... | CZT |
python | sphinx-doc__sphinx | tests/roots/test-root/autodoc_target.py | {
"start": 730,
"end": 1298
} | class ____(CustomDataDescriptor):
"""Descriptor class with custom metaclass docstring."""
__metaclass__ = CustomDataDescriptorMeta
def _funky_classmethod(name, b, c, d, docstring=None):
"""Generates a classmethod for a class from a template by filling out some arguments."""
def template(cls, a, b, c... | CustomDataDescriptor2 |
python | numba__numba | numba/core/byteflow.py | {
"start": 1032,
"end": 1908
} | class ____(object):
"""Kinds of block to make related code safer than just `str`.
"""
_members = frozenset({
'LOOP',
'TRY', 'EXCEPT', 'FINALLY',
'WITH', 'WITH_FINALLY',
})
def __init__(self, value):
assert value in self._members
self._value = value
def _... | BlockKind |
python | ray-project__ray | python/ray/data/datasource/file_datasink.py | {
"start": 6925,
"end": 9136
} | class ____(_FileDatasink):
"""A datasink that writes one row to each file.
Subclasses must implement ``write_row_to_file`` and call the superclass constructor.
Examples:
.. testcode::
import io
from typing import Any, Dict
import pyarrow
from PIL i... | RowBasedFileDatasink |
python | bokeh__bokeh | src/bokeh/models/misc/group_by.py | {
"start": 1749,
"end": 2092
} | class ____(GroupBy):
""" Group models by manually predefined groups. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
groups = Required(List(List(Instance(Model))), help="""
Predefined groups of mode... | GroupByModels |
python | pypa__pip | src/pip/_internal/resolution/base.py | {
"start": 257,
"end": 577
} | class ____:
def resolve(
self, root_reqs: list[InstallRequirement], check_supported_wheels: bool
) -> RequirementSet:
raise NotImplementedError()
def get_installation_order(
self, req_set: RequirementSet
) -> list[InstallRequirement]:
raise NotImplementedError()
| BaseResolver |
python | django__django | tests/m2m_regress/models.py | {
"start": 2462,
"end": 2624
} | class ____(models.Model):
primary_lines = models.ManyToManyField(Line, related_name="+")
secondary_lines = models.ManyToManyField(Line, related_name="+")
| Post |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/distributed_save_test.py | {
"start": 1520,
"end": 15652
} | class ____(
data_service_test_base.TestBase,
parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(num_workers=[1, 3], num_elements=[0, 10, 1000])))
def testSaveLoad(self, num_workers, num_elements):
cl... | DistributedSaveTest |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 2907,
"end": 3016
} | class ____(TypedDict):
"""A range of partition keys."""
start: str
end: str
| PipesPartitionKeyRange |
python | huggingface__transformers | src/transformers/models/gemma3/modeling_gemma3.py | {
"start": 31093,
"end": 37419
} | class ____(nn.Module):
def __init__(self, config: Gemma3Config):
super().__init__()
self.mm_input_projection_weight = nn.Parameter(
torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
)
self.mm_soft_emb_norm = Gemma3RMSNorm(
config.... | Gemma3MultiModalProjector |
python | redis__redis-py | tests/test_data_structure.py | {
"start": 154,
"end": 2662
} | class ____:
def test_add_items(self):
wlist = WeightedList()
wlist.add("item1", 3.0)
wlist.add("item2", 2.0)
wlist.add("item3", 4.0)
wlist.add("item4", 4.0)
assert wlist.get_top_n(4) == [
("item3", 4.0),
("item4", 4.0),
("item1", ... | TestWeightedList |
python | google__jax | jax/_src/core.py | {
"start": 140240,
"end": 140691
} | class ____(NamedTuple):
print_shapes: bool = True
source_info: bool = False
name_stack: bool = False
custom_pp_eqn_rules: bool = True
print_effects: bool = False
def _encode_digits_alphabetic(n: int) -> str:
if n == -1:
return '*'
s = ''
while len(s) == 0 or n:
n, i = n // 26, n % 26
s = ch... | JaxprPpSettings |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 1397,
"end": 2593
} | class ____(nn.Module):
"""Image to Patch Embedding"""
def __init__(self, config):
super().__init__()
image_size = config.image_size
patch_size = config.patch_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
... | TimesformerPatchEmbeddings |
python | hyperopt__hyperopt | hyperopt/rdists.py | {
"start": 7005,
"end": 8674
} | class ____:
"""Stats for Y = q * round(exp(X) / q) where X ~ N(mu, sigma)"""
def __init__(self, mu, sigma, q):
self.mu, self.sigma = list(map(float, (mu, sigma)))
self.q = q
# -- distfn for using the CDF
self._norm_cdf = scipy.stats.norm(loc=mu, scale=sigma).cdf
def in_doma... | qlognormal_gen |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 50954,
"end": 51224
} | class ____(BaseModel):
healing_threshold: Optional[float] = Field(
default=0.3,
description="Enable HNSW healing if the ratio of missing points is no more than this value. To disable healing completely, set this value to `0.0`.",
)
| HnswGlobalConfig |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/marker/_colorbar.py | {
"start": 233,
"end": 61749
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.marker"
_path_str = "scattersmith.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
... | ColorBar |
python | tensorflow__tensorflow | tensorflow/python/training/session_manager_test.py | {
"start": 28319,
"end": 34338
} | class ____(test.TestCase):
@classmethod
def setUpClass(cls):
super(ObsoleteSessionManagerTest, cls).setUpClass()
resource_variables_toggle.disable_resource_variables()
def testPrepareSessionSucceeds(self):
with ops.Graph().as_default():
v = variable_v1.VariableV1([1.0, 2.0, 3.0], name="v")
... | ObsoleteSessionManagerTest |
python | giampaolo__psutil | tests/test_testutils.py | {
"start": 6358,
"end": 8697
} | class ____(PsutilTestCase):
def test_reap_children(self):
subp = self.spawn_subproc()
p = psutil.Process(subp.pid)
assert p.is_running()
reap_children()
assert not p.is_running()
assert not tests._pids_started
assert not tests._subprocesses_started
def te... | TestProcessUtils |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/data_time.py | {
"start": 1966,
"end": 22895
} | class ____:
_instance_queryer: CachingInstanceQueryer
_asset_graph: BaseAssetGraph
def __init__(self, instance_queryer: CachingInstanceQueryer):
self._instance_queryer = instance_queryer
@property
def instance_queryer(self) -> CachingInstanceQueryer:
return self._instance_queryer
... | CachingDataTimeResolver |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 1977,
"end": 3044
} | class ____(dict):
def __init__(self, mapping):
super().__init__(mapping)
self.cache = {}
def __setitem__(self, key, value):
super().__setitem__(key, value)
self.cache.clear()
def __delitem__(self, key):
super().__delitem__(key)
self.cache.clear()
_colors_f... | _ColorMapping |
python | pallets__click | examples/complex/complex/cli.py | {
"start": 93,
"end": 666
} | class ____:
def __init__(self):
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Logs a message to stderr."""
if args:
msg %= args
click.echo(msg, file=sys.stderr)
def vlog(self, msg, *args):
"""Logs a message to stderr ... | Environment |
python | huggingface__transformers | src/transformers/models/dia/configuration_dia.py | {
"start": 9904,
"end": 14305
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DiaModel`]. It is used to instantiate a
Dia model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration... | DiaConfig |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 45732,
"end": 52627
} | class ____(nn.Module):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MimiTransformerLayer`]
Args:
config: MimiConfig
"""
def __init__(self, config: MimiConfig):
super().__init__()
self.layers = nn.ModuleList(
[MimiTr... | MimiTransformerModel |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_north_carolina_zip.py | {
"start": 1798,
"end": 4187
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid North Carolina zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
example... | ExpectColumnValuesToBeValidNorthCarolinaZip |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 12851,
"end": 16272
} | class ____(object):
"""Context manager when you are in `update()` or `update_non_slot()`."""
__slots__ = ["_replica_id", "_old_replica_id"]
def __init__(self, replica_id):
self._replica_id = replica_id
self._old_replica_id = None
def __enter__(self):
self._old_replica_id = get_update_replica_id()... | UpdateContext |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_with_reference.py | {
"start": 1014,
"end": 3288
} | class ____(BaseModel):
id: Optional[str] = None
"""
For an item of type (`message` | `function_call` | `function_call_output`) this
field allows the client to assign the unique ID of the item. It is not required
because the server will generate one if not provided.
For an item of type `item_ref... | ConversationItemWithReference |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py | {
"start": 4892,
"end": 18846
} | class ____(
AgentMiddleware[ToolCallLimitState[ResponseT], ContextT],
Generic[ResponseT, ContextT],
):
"""Track tool call counts and enforces limits during agent execution.
This middleware monitors the number of tool calls made and can terminate or
restrict execution when limits are exceeded. It su... | ToolCallLimitMiddleware |
python | doocs__leetcode | solution/2100-2199/2179.Count Good Triplets in an Array/Solution2.py | {
"start": 0,
"end": 128
} | class ____:
__slots__ = ("l", "r", "v")
def __init__(self):
self.l = 0
self.r = 0
self.v = 0
| Node |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 64891,
"end": 69495
} | class ____(SageMakerBaseOperator):
"""
Stops a SageMaker pipeline execution.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerStopPipelineOperator`
:param config: The configuration to start the pipeline execution.
... | SageMakerStopPipelineOperator |
python | walkccc__LeetCode | solutions/2150. Find All Lonely Numbers in the Array/2150.py | {
"start": 0,
"end": 253
} | class ____:
def findLonely(self, nums: list[int]) -> list[int]:
count = collections.Counter(nums)
return [num for num, freq in count.items()
if freq == 1 and
count[num - 1] == 0 and
count[num + 1] == 0]
| Solution |
python | pytorch__pytorch | torch/testing/_internal/common_distributed.py | {
"start": 57469,
"end": 58522
} | class ____(torch._dynamo.test_case.TestCase):
"""
Test harness for single-process dynamo distributed tests,
initializes dist process group.
Prefer this for simple tests, as it's easier to debug.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# _exit_stack is set... | DynamoDistributedSingleProcTestCase |
python | huggingface__transformers | src/transformers/models/umt5/modeling_umt5.py | {
"start": 21047,
"end": 21784
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config: UMT5Config):
super().__init__()
self.dense = nn.Linear(config.d_model, config.d_model)
self.dropout = nn.Dropout(p=config.classifier_dropout)
self.out_proj = nn.Linear(config.d_... | UMT5ClassificationHead |
python | PrefectHQ__prefect | src/prefect/events/filters.py | {
"start": 7120,
"end": 7457
} | class ____(EventDataFilter):
id: Optional[list[UUID]] = Field(
default=None, description="Only include events with one of these IDs"
)
def includes(self, event: Event) -> bool:
if self.id:
if not any(event.id == id for id in self.id):
return False
return... | EventIDFilter |
python | PyCQA__pylint | tests/regrtest_data/max_inferable_limit_for_classes/other_funcs.py | {
"start": 316,
"end": 357
} | class ____(ReturnsRows):
...
| Selectable |
python | great-expectations__great_expectations | great_expectations/core/metric_function_types.py | {
"start": 1294,
"end": 4940
} | class ____(enum.Enum):
"""Enum type, whose members depict the nature of return value of a metric implementation function
(defined for a specified "ExecutionEngine" subclass) that is a (partial)
Callable to be executed once execution plan is complete.
The available types are:
- `MAP_FN` -- metric i... | MetricPartialFunctionTypes |
python | tiangolo__fastapi | docs_src/dataclasses/tutorial002.py | {
"start": 114,
"end": 549
} | class ____:
name: str
price: float
tags: List[str] = field(default_factory=list)
description: Union[str, None] = None
tax: Union[float, None] = None
app = FastAPI()
@app.get("/items/next", response_model=Item)
async def read_next_item():
return {
"name": "Island In The Moon",
... | Item |
python | chroma-core__chroma | chromadb/db/migrations.py | {
"start": 1731,
"end": 1871
} | class ____(Exception):
def __init__(self, alg: str):
super().__init__(f"Invalid hash algorithm specified: {alg}")
| InvalidHashError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 362203,
"end": 362534
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("IssueTimelineItems", graphql_name="node")
| IssueTimelineItemsEdge |
python | openai__openai-python | src/openai/types/audio/speech_create_params.py | {
"start": 282,
"end": 1780
} | class ____(TypedDict, total=False):
input: Required[str]
"""The text to generate audio for. The maximum length is 4096 characters."""
model: Required[Union[str, SpeechModel]]
"""
One of the available [TTS models](https://platform.openai.com/docs/models#tts):
`tts-1`, `tts-1-hd` or `gpt-4o-mini-... | SpeechCreateParams |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-huggingface-optimum-intel/llama_index/embeddings/huggingface_optimum_intel/base.py | {
"start": 425,
"end": 6229
} | class ____(BaseEmbedding):
folder_name: str = Field(description="Folder name to load from.")
max_length: int = Field(description="Maximum length of input.")
pooling: str = Field(description="Pooling strategy. One of ['cls', 'mean'].")
normalize: bool = Field(default=True, description="Normalize embeddin... | IntelEmbedding |
python | huggingface__transformers | src/transformers/models/janus/modular_janus.py | {
"start": 2848,
"end": 7234
} | class ____(SiglipVisionConfig):
r"""
This is the configuration class to store the configuration of a [`JanusVisionModel`]. It is used to instantiate a
`JanusVisionModel` according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and ca... | JanusVisionConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/cards.py | {
"start": 1451,
"end": 1587
} | class ____(CreditCard):
"""
https://developer.paypal.com/braintree/docs/reference/response/samsung-pay-card
"""
| SamsungPayCard |
python | astropy__astropy | astropy/visualization/interval.py | {
"start": 4504,
"end": 6051
} | class ____(BaseInterval):
"""
Interval based on a keeping a specified fraction of pixels (can be
asymmetric).
Parameters
----------
lower_percentile : float or None
The lower percentile below which to ignore pixels. If None, then
defaults to 0.
upper_percentile : float or No... | AsymmetricPercentileInterval |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 4561,
"end": 5309
} | class ____(Opcode):
"""An opcode with one argument.
Attributes:
arg: The integer opcode argument read in from the bytecode
argval: A decoded version of arg, performing the same steps the cpython
interpreter does to convert arg into a python value.
"""
__slots__ = ("arg", "argval")
def __init_... | OpcodeWithArg |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/evaluation_modes.py | {
"start": 117,
"end": 870
} | class ____(Enum):
"""
Tests may be run in "diagnostic" mode or "strict" mode.
When run in "diagnostic" mode, `AssertionError`s won't fail the test, but we will continue to surface
any errors to the test report.
In "strict" mode, tests pass/fail as usual.
In live tests, diagnostic mode is used... | TestEvaluationMode |
python | openai__openai-python | tests/api_resources/responses/test_input_items.py | {
"start": 446,
"end": 2542
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_list(self, client: OpenAI) -> None:
input_item = client.responses.input_items.list(
response_id="response_id",
)
assert_matches... | TestInputItems |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 55103,
"end": 56149
} | class ____(RRuleLocator):
"""
Make ticks on occurrences of each weekday.
"""
def __init__(self, byweekday=1, interval=1, tz=None):
"""
Parameters
----------
byweekday : int or list of int, default: all days
Ticks will be placed on every weekday in *byweekday*... | WeekdayLocator |
python | pandas-dev__pandas | pandas/tests/util/test_deprecate_nonkeyword_arguments.py | {
"start": 3417,
"end": 3965
} | class ____:
@deprecate_nonkeyword_arguments(WARNING_CATEGORY, allowed_args=["self", "bar"])
def baz(self, bar=None, foobar=None): ...
def test_foo_signature():
assert str(inspect.signature(Foo.baz)) == "(self, bar=None, *, foobar=None)"
def test_class():
msg = (
rf"Starting with pandas versi... | Foo |
python | scipy__scipy | scipy/signal/_upfirdn.py | {
"start": 2626,
"end": 7976
} | class ____:
"""Helper for resampling."""
def __init__(self, h, x_dtype, up, down):
h = np.asarray(h)
if h.ndim != 1 or h.size == 0:
raise ValueError('h must be 1-D with non-zero length')
self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
h = np.asarray(... | _UpFIRDn |
python | google__pytype | pytype/overlays/typing_overlay.py | {
"start": 19290,
"end": 19750
} | class ____(abstract.AnnotationClass):
"""Implementation of typing.Optional."""
def _build_value(self, node, inner, ellipses):
self.ctx.errorlog.invalid_ellipses(self.ctx.vm.frames, ellipses, self.name)
if len(inner) != 1:
error = "typing.Optional can only contain one type parameter"
self.ctx.er... | Optional |
python | Lightning-AI__lightning | tests/tests_fabric/strategies/launchers/test_multiprocessing_integration.py | {
"start": 726,
"end": 2331
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.layer = nn.Linear(2, 2)
self.tied_layer = nn.Linear(2, 2)
self.tied_layer.weight = self.layer.weight
self.register_buffer("buffer", torch.ones(3))
@RunIf(skip_windows=True)
@pytest.mark.flaky(reruns=3)
@pyte... | SimpleModel |
python | bokeh__bokeh | src/bokeh/models/scales.py | {
"start": 1475,
"end": 2403
} | class ____(Transform):
''' Base class for ``Scale`` models that represent an invertible
computation to be carried out on the client-side.
JavaScript implementations should implement the following methods:
.. code-block
compute(x: number): number {
# compute and return the transfor... | Scale |
python | pypa__hatch | tests/utils/test_structures.py | {
"start": 121,
"end": 1698
} | class ____:
def test_restoration(self):
num_env_vars = len(os.environ)
with EnvVars():
os.environ.clear()
assert len(os.environ) == num_env_vars
def test_set(self):
env_var = get_random_name()
with EnvVars({env_var: "foo"}):
assert os.environ.ge... | TestEnvVars |
python | tiangolo__fastapi | docs_src/body_nested_models/tutorial002.py | {
"start": 110,
"end": 413
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: List[str] = []
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": item}
return results
| Item |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1214550,
"end": 1215639
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'marked_as_duplicate' event on a given issue or pull
request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "canonical", "created_at", "duplicate", "is_cross_repository")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
... | MarkedAsDuplicateEvent |
python | getsentry__sentry | tests/sentry/digests/test_notifications.py | {
"start": 4303,
"end": 5987
} | class ____(TestCase):
def test_old_style_key(self) -> None:
assert split_key(f"mail:p:{self.project.id}") == (
self.project,
ActionTargetType.ISSUE_OWNERS,
None,
None,
)
def test_new_style_key_no_identifier(self) -> None:
assert split_key(... | SplitKeyTestCase |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 305808,
"end": 308042
} | class ____:
def test_trim_mean(self, xp):
# don't use pre-sorted arrays
idx = np.array([3, 5, 0, 1, 2, 4])
a2 = np.arange(24).reshape(6, 4)[idx, :]
a3 = np.arange(24).reshape(6, 4, order='F')[idx, :]
xp_assert_equal(stats.trim_mean(xp.asarray(a3), 2/6.),
... | TestTrimMean |
python | kamyu104__LeetCode-Solutions | Python/find-k-th-smallest-pair-distance.py | {
"start": 81,
"end": 805
} | class ____(object):
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# Sliding window solution
def possible(guess, nums, k):
count, left = 0, 0
for right, num in enumerate(nums):
... | Solution |
python | ethereum__web3.py | web3/_utils/ens.py | {
"start": 1294,
"end": 2686
} | class ____:
def __init__(self, name_addr_pairs: dict[str, ChecksumAddress]) -> None:
self.registry = dict(name_addr_pairs)
async def address(self, name: str) -> ChecksumAddress:
return self.registry.get(name, None)
@contextmanager
def ens_addresses(
w3: Union["Web3", "AsyncWeb3[Any]"], na... | AsyncStaticENS |
python | wandb__wandb | tests/system_tests/test_artifacts/test_object_references.py | {
"start": 23569,
"end": 35883
} | class ____:
@fixture(
params=[
table.__name__,
image.__name__,
point_cloud.__name__,
bokeh.__name__,
html.__name__,
video.__name__,
joined_table.__name__,
audio_ref_https.__name__,
audio_ref_s3.__name... | TestMediaObjectReferentialEquality |
python | google__pytype | pytype/overlays/flax_overlay.py | {
"start": 709,
"end": 1003
} | class ____(overlay.Overlay):
"""A custom overlay for the 'flax.struct' module."""
def __init__(self, ctx):
member_map = {
"dataclass": Dataclass.make,
}
ast = ctx.loader.import_name("flax.struct")
super().__init__(ctx, "flax.struct", member_map, ast)
| DataclassOverlay |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 22570,
"end": 23146
} | class ____(sgqlc.types.Enum):
"""The possible roles for enterprise membership.
Enumeration Choices:
* `MEMBER`: The user is a member of an organization in the
enterprise.
* `OWNER`: The user is an owner of an organization in the
enterprise.
* `UNAFFILIATED`: The user is not an owner of... | EnterpriseUserAccountMembershipRole |
python | getsentry__sentry | src/sentry/issues/endpoints/project_event_details.py | {
"start": 5396,
"end": 6865
} | class ____(ProjectEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(self, request: Request, project: Project, event_id: str) -> Response:
event = eventstore.backend.get_event_by_id(project.id, event_id)
if not event:
... | EventJsonEndpoint |
python | django-mptt__django-mptt | mptt/querysets.py | {
"start": 55,
"end": 1133
} | class ____(models.query.QuerySet):
def as_manager(cls):
# Address the circular dependency between `Queryset` and `Manager`.
from mptt.managers import TreeManager
manager = TreeManager.from_queryset(cls)()
manager._built_with_as_manager = True
return manager
as_manager.q... | TreeQuerySet |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 12225,
"end": 12469
} | class ____(_GenerativeProvider):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.OLLAMA, frozen=True, exclude=True
)
model: Optional[str]
apiEndpoint: Optional[str]
| _GenerativeOllama |
python | fsspec__filesystem_spec | fsspec/parquet.py | {
"start": 477,
"end": 13775
} | class ____(AbstractBufferedFile):
def _fetch_range(self, start, end):
raise NotImplementedError
def open_parquet_files(
path: list[str],
mode: Literal["rb"] = "rb",
fs: None | fsspec.AbstractFileSystem = None,
metadata=None,
columns: None | list[str] = None,
row_groups: None | list... | AlreadyBufferedFile |
python | astropy__astropy | astropy/io/registry/interface.py | {
"start": 290,
"end": 4232
} | class ____:
"""Base class for the worker object used in unified read() or write() methods.
This lightweight object is created for each `read()` or `write()` call
via ``read`` / ``write`` descriptors on the data object class. The key
driver is to allow complete format-specific documentation of availabl... | UnifiedReadWrite |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc_metastore.py | {
"start": 13784,
"end": 15467
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
@mock.patch(
"airflow.providers.google.cloud.operators.dataproc_metastore"
".DataprocMetastoreRestoreServiceOperator._wait_for_restore_service"
)
def test_assert_valid_hook_call(s... | TestDataprocMetastoreRestoreServiceOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 269342,
"end": 271131
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
pardot_business_unit_id: str,
client_id: str,
client_secret: str,
refresh_token: str,
start_date: Optional[str] = None,
is_sandbox: Optional[bool] = None,
):
"""... | PardotSource |
python | huggingface__transformers | src/transformers/models/glm/modular_glm.py | {
"start": 5011,
"end": 5277
} | class ____(LlamaAttention):
def __init__(self, config: GlmConfig, layer_idx: Optional[int] = None):
super().__init__(config, layer_idx)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
| GlmAttention |
python | python-pillow__Pillow | src/PIL/MspImagePlugin.py | {
"start": 1110,
"end": 1915
} | class ____(ImageFile.ImageFile):
format = "MSP"
format_description = "Windows Paint"
def _open(self) -> None:
# Header
assert self.fp is not None
s = self.fp.read(32)
if not _accept(s):
msg = "not an MSP file"
raise SyntaxError(msg)
# Header... | MspImageFile |
python | getsentry__sentry | src/sentry/utils/kvstore/redis.py | {
"start": 248,
"end": 1015
} | class ____(KVStorage[str, T]):
"""
This class provides a key/value store backed by Redis (either a single node
or cluster.)
"""
def __init__(self, client: StrictRedis[T] | RedisCluster[T]) -> None:
self.client: StrictRedis[T] | RedisCluster[T] = client
def get(self, key: str) -> T | No... | RedisKVStorage |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_georgia_zip.py | {
"start": 1743,
"end": 4078
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Georgia zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidGeorgiaZip |
python | python-visualization__folium | folium/plugins/polyline_text_path.py | {
"start": 161,
"end": 2304
} | class ____(JSCSSMixin, MacroElement):
"""
Shows a text along a PolyLine.
Parameters
----------
polyline: folium.features.PolyLine object
The folium.features.PolyLine object to attach the text to.
text: string
The string to be attached to the polyline.
repeat: bool, default F... | PolyLineTextPath |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes1.py | {
"start": 245,
"end": 271
} | class ____(app.C):
...
| D |
python | gevent__gevent | src/gevent/tests/test__semaphore.py | {
"start": 11152,
"end": 11325
} | class ____(greentest.TestCase):
def test_c_extension(self):
self.assertEqual(Semaphore.__module__,
'gevent._gevent_c_semaphore')
| TestCExt |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/python/tree_utils.py | {
"start": 38,
"end": 179
} | class ____(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
| TreeNode |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 166882,
"end": 167731
} | class ____(TestCase):
def test_basic(self):
iterable = 'abcdefg'
r = 4
for index, expected in enumerate(
combinations_with_replacement(iterable, r)
):
actual = mi.nth_combination_with_replacement(iterable, r, index)
self.assertEqual(actual, expecte... | NthCombinationWithReplacementTests |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/cutlass_python_evt.py | {
"start": 3226,
"end": 4199
} | class ____(DefaultHandler):
def __init__(self, parent_handler: "CutlassEVTCodegen"):
self.parent_handler = parent_handler
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
# Handle op dispatch here
if hasattr(self.parent_handler, name):
fn ... | _AssignmentFormatter |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required.py | {
"start": 655,
"end": 869
} | class ____:
"""Example usage of "For the parameters, see" in init docstring"""
def __init__(self, x, y):
"""docstring foo constructor
For the parameters, see :func:`bla`
"""
| ClassFoo |
python | doocs__leetcode | solution/3300-3399/3379.Transformed Array/Solution.py | {
"start": 0,
"end": 240
} | class ____:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
ans = []
n = len(nums)
for i, x in enumerate(nums):
ans.append(nums[(i + x + n) % n] if x else 0)
return ans
| Solution |
python | coleifer__peewee | tests/regressions.py | {
"start": 66726,
"end": 68101
} | class ____(ModelTestCase):
def test_thread_safe_meta(self):
d1 = get_in_memory_db()
d2 = get_in_memory_db()
class Meta:
database = d1
model_metadata_class = ThreadSafeDatabaseMetadata
attrs = {'Meta': Meta}
for i in range(1, 30):
attrs['f%... | TestThreadSafeMetaRegression |
python | kubernetes-client__python | kubernetes/client/models/v1_flow_schema_spec.py | {
"start": 383,
"end": 7897
} | 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... | V1FlowSchemaSpec |
python | google__jax | tests/pallas/tpu_sparsecore_pallas_test.py | {
"start": 60825,
"end": 61575
} | class ____(PallasSCTest):
def test_basic(self):
self.skip_if_tc_tiling()
num_steps = 16
x = jnp.arange(num_steps * 8).reshape(-1, 8)
@self.vector_subcore_kernel(
out_shape=x,
in_specs=(pl.BlockSpec(memory_space=pltpu.HBM),),
out_specs=pl.BlockSpec(memory_space=pltpu.HBM),
... | PipelineTest |
python | ijl__orjson | test/test_numpy.py | {
"start": 319,
"end": 33844
} | class ____:
def test_numpy_array_d1_uintp(self):
low = numpy.iinfo(numpy.uintp).min
high = numpy.iinfo(numpy.uintp).max
assert orjson.dumps(
numpy.array([low, high], numpy.uintp),
option=orjson.OPT_SERIALIZE_NUMPY,
) == f"[{low},{high}]".encode("ascii")
d... | TestNumpy |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/model_helpers.py | {
"start": 3843,
"end": 5544
} | class ____(classmethod, Generic[_T, _P, _R_co]):
"""Drop-in replacement for @classmethod, but raises an exception when the decorated method is called on an instance
instead of a class type."""
method: Callable[Concatenate[type[_T], _P], _R_co]
def __init__(self, method: Callable[Concatenate[type[_T], ... | _restricted_classmethod_impl |
python | PyCQA__pylint | pylint/extensions/confusing_elif.py | {
"start": 488,
"end": 2049
} | class ____(BaseChecker):
"""Checks if "elif" is used right after an indented block that finishes with "if" or
"elif" itself.
"""
name = "confusing_elif"
msgs = {
"R5601": (
"Consecutive elif with differing indentation level, consider creating a function to separate the inner"
... | ConfusingConsecutiveElifChecker |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/partition_utils.py | {
"start": 443,
"end": 4868
} | class ____(NamedTuple):
partitioning_type: PartitionDefinitionType
partition_keys: Sequence[str]
# Eventually we can add more of these for different partitioning types
additional_info: Optional[TimeWindowPartitioningInformation]
@staticmethod
def from_asset_node_graphql(
asset_nodes: Se... | PartitioningInformation |
python | django__django | django/contrib/sessions/models.py | {
"start": 164,
"end": 1250
} | class ____(AbstractBaseSession):
"""
Django provides full support for anonymous sessions. The session
framework lets you store and retrieve arbitrary data on a
per-site-visitor basis. It stores data on the server side and
abstracts the sending and receiving of cookies. Cookies contain a
session ... | Session |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 1458,
"end": 2727
} | class ____(Benchmark):
r"""
Sargan objective function.
This class defines the Sargan [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Sargan}}(x) = \sum_{i=1}^{n} n \left (x_i^2
+ 0.4 \sum_{i \neq j}^{n} x_ix_j \ri... | Sargan |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py | {
"start": 4979,
"end": 5386
} | class ____(BaseFSHandler):
@web.authenticated
@authorized
async def get(self):
detail_arg = self.get_argument("detail", default="true").lower()
detail = detail_arg == "true"
path = self.get_path_argument("path")
async with self.stream_json() as write_json:
for res... | LsHandler |
python | scrapy__scrapy | scrapy/core/downloader/handlers/file.py | {
"start": 322,
"end": 672
} | class ____:
lazy = False
@defers
def download_request(self, request: Request, spider: Spider) -> Response:
filepath = file_uri_to_path(request.url)
body = Path(filepath).read_bytes()
respcls = responsetypes.from_args(filename=filepath, body=body)
return respcls(url=request.u... | FileDownloadHandler |
python | django__django | tests/dbshell/test_postgresql.py | {
"start": 255,
"end": 6285
} | class ____(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_dict, parameters=None):
if parameters is None:
parameters = []
settings_dict.setdefault("OPTIONS", {})
return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)
def test_basic(self):
... | PostgreSqlDbshellCommandTestCase |
python | django-extensions__django-extensions | tests/collisions/models.py | {
"start": 552,
"end": 777
} | class ____(models.Model):
# name conflict with testapp.Name
real_name = models.CharField(max_length=50)
number_of_users_having_this_name = models.IntegerField()
class Meta:
app_label = "collisions"
| Name |
python | huggingface__transformers | src/transformers/models/pegasus/modeling_pegasus.py | {
"start": 19244,
"end": 26988
} | class ____(PegasusPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`PegasusEncoderLayer`].
Args:
config: PegasusConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: PegasusConf... | PegasusEncoder |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/lkml/liquid_utils.py | {
"start": 471,
"end": 1339
} | class ____(Tag):
"""Defines a custom Liquid tag to match Looker's condition tag,
treats the condition as always true when rendering the output SQL.
https://jg-rp.github.io/liquid/guides/custom-tags#add-a-tag.
"""
name = TAG_CONDITION
end = TAG_ENDCONDITION
def __init__(self, env: Environme... | ConditionTag |
python | django__django | tests/test_utils/test_transactiontestcase.py | {
"start": 2361,
"end": 2727
} | class ____(TransactionTestCase):
available_apps = ["test_utils"]
fixtures = ["person.json"]
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.elvis = Person.objects.get(name="Elvis Presley")
def test_fixture_loaded_during_class_setup(self):
self.assertIsInstance(se... | FixtureAvailableInSetUpClassTest |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_field.py | {
"start": 7118,
"end": 16397
} | class ____(enum.Enum):
"""Enum to indicate what kind of value is being converted.
Used by `_convert_fields` and `_convert_value` and their helper methods.
"""
VALUE = 1 # Converting an ExtensionType field
SPEC = 2 # Converting an ExtensionType.Spec field
DEFAULT = 3 # Converting a default value for __in... | _ConversionContext |
python | nedbat__coveragepy | tests/test_plugins.py | {
"start": 11775,
"end": 23483
} | class ____(FileTracerTest):
"""Tests of file tracer plugin happy paths."""
def test_plugin1(self) -> None:
self.make_file(
"simple.py",
"""\
import try_xyz
a = 1
b = 2
""",
)
self.make_file(
"try_xyz.py"... | GoodFileTracerTest |
python | pytorch__pytorch | torch/distributed/fsdp/_trace_utils.py | {
"start": 1354,
"end": 2296
} | class ____(NamedTuple):
"""
This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
execution information. The ``dict`` maps modules to a list of these
``_ParamUsageInfo`` instances, where each instance represents a group of
parameters used together.
Specifically, for each mod... | _ParamUsageInfo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.