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 | pytorch__pytorch | test/dynamo/test_repros.py | {
"start": 24347,
"end": 26402
} | class ____:
attn_layers = ["local", "lsh", "local", "lsh", "local", "lsh"]
lsh_attn_chunk_length = 64
local_attn_chunk_length = 64
def _get_min_chunk_len(config):
"""from hf_Reformer"""
attn_types = config.attn_layers
attn_types_set = set(attn_types)
if len(attn_types_set) == 1 and attn_ty... | DummyConfig |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 3315,
"end": 3796
} | class ____(_Union):
as_name: Annotated[str, 10]
as_float: Annotated[float, 20]
# In most cases we will use the "as_name" field to store arguments which are
# SymBools.
# The "as_bool" field is used in the case where we have a list containing a mix
# of SymBool and bools (ex. [True, i0, ...]). We will serializ... | SymFloatArgument |
python | django__django | django/db/models/sql/where.py | {
"start": 466,
"end": 11689
} | class ____(tree.Node):
"""
An SQL WHERE clause.
The class is tied to the Query class that created it (in order to create
the correct SQL).
A child is usually an expression producing boolean values. Most likely the
expression is a Lookup instance.
However, a child could also be any class w... | WhereNode |
python | graphql-python__graphene | graphene/relay/id_type.py | {
"start": 539,
"end": 1315
} | class ____(BaseGlobalIDType):
"""
Default global ID type: base64 encoded version of "<node type name>: <node id>".
"""
graphene_type = ID
@classmethod
def resolve_global_id(cls, info, global_id):
try:
_type, _id = from_global_id(global_id)
if not _type:
... | DefaultGlobalIDType |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/triggers/databricks.py | {
"start": 1100,
"end": 4550
} | class ____(BaseTrigger):
"""
The trigger handles the logic of async communication with DataBricks API.
:param run_id: id of the run
:param databricks_conn_id: Reference to the :ref:`Databricks connection <howto/connection:databricks>`.
:param polling_period_seconds: Controls the rate of the poll fo... | DatabricksExecutionTrigger |
python | keras-team__keras | keras/src/trainers/trainer_test.py | {
"start": 2631,
"end": 3210
} | class ____(Trainer, layers.Layer):
def __init__(self, units):
layers.Layer.__init__(self)
Trainer.__init__(self)
self.dense_1 = layers.Dense(
units,
use_bias=False,
kernel_initializer=initializers.Ones(),
)
self.dense_2 = layers.Dense(
... | StructModel |
python | Textualize__textual | src/textual/drivers/win32.py | {
"start": 3149,
"end": 6208
} | class ____(Structure):
"""https://docs.microsoft.com/en-us/windows/console/input-record-str"""
_fields_ = [("EventType", wintypes.WORD), ("Event", InputEvent)]
def set_console_mode(file: IO, mode: int) -> bool:
"""Set the console mode for a given file (stdout or stdin).
Args:
file: A file li... | INPUT_RECORD |
python | getsentry__sentry | src/sentry/analytics/events/sentry_app_installation_token_deleted.py | {
"start": 94,
"end": 306
} | class ____(analytics.Event):
user_id: int
organization_id: int
sentry_app_installation_id: int
sentry_app: str
analytics.register(SentryAppInstallationTokenDeleted)
| SentryAppInstallationTokenDeleted |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/exceptions.py | {
"start": 871,
"end": 999
} | class ____(AirflowException):
"""Raised when exception happens during Pod Mutation Hook execution."""
| PodMutationHookException |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 19446,
"end": 90758
} | class ____(ComparesTables, OneConnectionTablesTest):
run_inserts = run_deletes = None
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
cls.define_reflected_tables(metadata, None)
if testing.requires.schemas.enabled:
cls.define_reflected_tables... | ComponentReflectionTest |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/object_identity.py | {
"start": 3135,
"end": 4092
} | class ____(collections.abc.MutableMapping):
"""A mutable mapping data structure which compares using "is".
This is necessary because we have trackable objects (_ListWrapper) which
have behavior identical to built-in Python lists (including being unhashable
and comparing based on the equality of their contents ... | ObjectIdentityDictionary |
python | django__django | tests/settings_tests/tests.py | {
"start": 3478,
"end": 4394
} | class ____(ClassDecoratedTestCaseSuper):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.foo = getattr(settings, "TEST", "BUG")
def test_override(self):
self.assertEqual(settings.TEST, "override")
def test_setupclass_override(self):
"""Settings are overridden... | ClassDecoratedTestCase |
python | huggingface__transformers | tests/models/glm4v_moe/test_modeling_glm4v_moe.py | {
"start": 11234,
"end": 17740
} | class ____(unittest.TestCase):
model = None
@classmethod
def get_model(cls):
if cls.model is None:
cls.model = Glm4vMoeForConditionalGeneration.from_pretrained(
"zai-org/GLM-4.5V", dtype="auto", device_map="auto"
)
return cls.model
@classmethod
... | Glm4vMoeIntegrationTest |
python | mkdocs__mkdocs | mkdocs/utils/__init__.py | {
"start": 10963,
"end": 11543
} | class ____(logging.NullHandler):
"""Counts all logged messages >= level."""
def __init__(self, **kwargs) -> None:
self.counts: dict[int, int] = defaultdict(int)
super().__init__(**kwargs)
def handle(self, record):
rv = self.filter(record)
if rv:
# Use levelno fo... | CountHandler |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 294,
"end": 513
} | class ____(analytics.Event):
organization_id: int
status: str
resolve_type: str | None = None
user_id: int | None = None
@analytics.eventclass("integrations.slack.notification_sent")
| SlackIntegrationStatus |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/code_locations/component_component_deps_custom_component/defs/depends_on_my_python_defs/custom_component.py | {
"start": 130,
"end": 587
} | class ____(dg.Component):
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions:
assets_from_my_python_defs = context.component_tree.build_defs(
MY_PYTHON_DEFS_COMPONENT_PATH
).resolve_all_asset_keys()
@dg.asset(deps=assets_from_my_python_defs)
def dow... | MyCustomComponent |
python | pydata__xarray | xarray/core/groupby.py | {
"start": 5528,
"end": 8539
} | class ____(Generic[T_Xarray]):
"""Class for keeping track of grouped dimensions without coordinates.
Should not be user visible.
"""
__slots__ = ("coords", "dataarray", "name", "size")
def __init__(self, obj: T_Xarray, name: Hashable, coords) -> None:
self.name = name
self.coords ... | _DummyGroup |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/redshift_cluster.py | {
"start": 952,
"end": 7952
} | class ____(AwsBaseHook):
"""
Interact with Amazon Redshift.
This is a thin wrapper around
:external+boto3:py:class:`boto3.client("redshift") <Redshift.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
... | RedshiftHook |
python | doocs__leetcode | solution/3300-3399/3346.Maximum Frequency of an Element After Performing Operations I/Solution.py | {
"start": 0,
"end": 437
} | class ____:
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
cnt = defaultdict(int)
d = defaultdict(int)
for x in nums:
cnt[x] += 1
d[x] += 0
d[x - k] += 1
d[x + k + 1] -= 1
ans = s = 0
for x, t in sor... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py | {
"start": 37395,
"end": 38475
} | class ____(BatchedSubStream, BulkSalesforceStream):
def stream_slices(
self, sync_mode: SyncMode, cursor_field: Optional[List[str]] = None, stream_state: Optional[Mapping[str, Any]] = None
) -> Iterable[Optional[Mapping[str, Any]]]:
self._instantiate_declarative_stream(
BulkParentStr... | BulkSalesforceSubStream |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 48291,
"end": 57353
} | class ____(_ConvTransposeNd):
__doc__ = (
r"""Applies a 3D transposed convolution operator over an input image composed of several input
planes.
The transposed convolution operator multiplies each input value element-wise by a learnable kernel,
and sums over the outputs from all input feature pl... | ConvTranspose3d |
python | pandas-dev__pandas | pandas/tests/arrays/test_datetimes.py | {
"start": 416,
"end": 9130
} | class ____:
@pytest.fixture(params=["s", "ms", "us"])
def unit(self, request):
"""Fixture returning parametrized time units"""
return request.param
@pytest.fixture
def dtype(self, unit, tz_naive_fixture):
tz = tz_naive_fixture
if tz is None:
return np.dtype(f... | TestNonNano |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/cdxgen.py | {
"start": 12682,
"end": 13021
} | class ____:
python_version: str | None
target_path: Path
@abstractmethod
def produce(self, output: Output | None, port: int, github_token: str | None) -> tuple[int, str]:
raise NotImplementedError
@abstractmethod
def get_job_name(self) -> str:
raise NotImplementedError
@datac... | SbomApplicationJob |
python | ray-project__ray | rllib/utils/tests/test_check_multi_agent.py | {
"start": 113,
"end": 2638
} | class ____(unittest.TestCase):
def test_multi_agent_invalid_args(self):
self.assertRaisesRegex(
TypeError,
"got an unexpected keyword argument 'wrong_key'",
lambda: (
PPOConfig().multi_agent(
policies={"p0"}, policies_to_train=["p0"], w... | TestCheckMultiAgent |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/file_search.py | {
"start": 2119,
"end": 12773
} | class ____(AgentMiddleware):
"""Provides Glob and Grep search over filesystem files.
This middleware adds two tools that search through local filesystem:
- Glob: Fast file pattern matching by file path
- Grep: Fast content search using ripgrep or Python fallback
Example:
```python
... | FilesystemFileSearchMiddleware |
python | pytorch__pytorch | torch/_dynamo/variables/lists.py | {
"start": 61353,
"end": 63806
} | class ____(IteratorVariable):
_nonvar_fields = {
"index",
*IteratorVariable._nonvar_fields,
}
def __init__(
self, items: list[VariableTracker], index: int = 0, **kwargs: Any
) -> None:
super().__init__(**kwargs)
assert isinstance(items, list)
# Removing t... | ListIteratorVariable |
python | walkccc__LeetCode | solutions/1032. Stream of Characters/1032.py | {
"start": 108,
"end": 707
} | class ____:
def __init__(self, words: list[str]):
self.root = TrieNode()
self.letters = []
for word in words:
self._insert(word)
def query(self, letter: str) -> bool:
self.letters.append(letter)
node = self.root
for c in reversed(self.letters):
if c not in node.children:
... | StreamChecker |
python | imageio__imageio | imageio/plugins/lytro.py | {
"start": 18393,
"end": 25309
} | class ____(LytroFormat):
"""This is the Lytro Illum LFP format.
The lfp is a image and meta data container format as used by the
Lytro F01 light field camera.
The format will read the specified lfp file.
This format does not support writing.
Parameters for reading
----------------------
... | LytroLfpFormat |
python | spack__spack | lib/spack/spack/database.py | {
"start": 10464,
"end": 13355
} | class ____:
"""Manages acquiring and releasing read or write locks on concrete specs."""
def __init__(self, lock_path: Union[str, pathlib.Path], default_timeout: Optional[float]):
self.lock_path = pathlib.Path(lock_path)
self.default_timeout = default_timeout
# Maps (spec.dag_hash(), s... | SpecLocker |
python | run-llama__llama_index | llama-index-core/tests/output_parsers/test_pydantic.py | {
"start": 250,
"end": 311
} | class ____(BaseModel):
test_attr: str
foo: int
| AttrDict |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/consts.py | {
"start": 2937,
"end": 3555
} | class ____(Enum):
"""Enum to characterize the current context state, values are used for external representation on GitHub commit checks."""
INITIALIZED = {"github_state": "pending", "description": "Pipelines are being initialized..."}
RUNNING = {"github_state": "pending", "description": "Pipelines are run... | ContextState |
python | lxml__lxml | src/lxml/tests/test_elementpath.py | {
"start": 15107,
"end": 15536
} | class ____(EtreeElementPathTestCase):
import xml.etree.ElementTree as etree
import xml.etree.ElementPath as _elementpath
test_cache = unittest.skip("lxml-only")(EtreeElementPathTestCase.test_cache)
test_tokenizer = unittest.skip("lxml-only")(EtreeElementPathTestCase.test_tokenizer)
test_tokenizer_i... | ElementTreeElementPathTestCase |
python | keras-team__keras | keras/src/dtype_policies/dtype_policy.py | {
"start": 7828,
"end": 9352
} | class ____(DTypePolicy):
def __init__(self, mode, source_name=None):
# Use the global dtype policy if `source_name` is not specified
if source_name is None:
source_name = dtype_policy().name
name = f"{mode}_from_{source_name}"
self._compute_dtype, self._variable_dtype = s... | QuantizedDTypePolicy |
python | instagram__MonkeyType | demo/test_inbox.py | {
"start": 272,
"end": 8655
} | class ____(models.RepoInterface):
def __init__(self, *objs: object) -> None:
self.objs = objs
def get_feed_entries_by_ids(
self, ids: Collection[models.FeedEntryId]
) -> Dict[models.FeedEntryId, Optional[models.FeedEntry]]:
found = {
f.id: f
for f in self.ob... | FakeRepo |
python | doocs__leetcode | lcof/面试题40. 最小的k个数/Solution2.py | {
"start": 0,
"end": 234
} | class ____:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
h = []
for x in arr:
heappush(h, -x)
if len(h) > k:
heappop(h)
return [-x for x in h]
| Solution |
python | getsentry__sentry | src/sentry/backup/findings.py | {
"start": 7224,
"end": 7732
} | class ____(json.JSONEncoder):
"""JSON serializer that handles findings properly."""
def default(self, obj):
if isinstance(obj, Finding):
kind = getattr(obj, "kind", None)
d = obj.to_dict()
d["finding"] = obj.get_finding_name()
if isinstance(kind, FindingK... | FindingJSONEncoder |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 111027,
"end": 117600
} | class ____(fixtures.DeclarativeMappedTest):
"""because subqueryloader relies upon the .subquery() method, this means
if the original Query has a from_self() present, it needs to create
.subquery() in terms of the Query class as a from_self() selectable
doesn't work correctly with the future select. So... | FromSubqTest |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 96265,
"end": 98132
} | class ____(Response):
"""
Response of tasks.completed endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "completed"
_version = "2.9"
_schema = {
... | CompletedResponse |
python | huggingface__transformers | tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py | {
"start": 1655,
"end": 4958
} | class ____:
def __init__(
self,
parent,
batch_size=13,
num_channels=3,
image_size=32,
depth_multiplier=0.25,
min_depth=8,
tf_padding=True,
last_hidden_size=1024,
output_stride=32,
hidden_act="relu6",
classifier_dropout_p... | MobileNetV1ModelTester |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/base_layer.py | {
"start": 123419,
"end": 128548
} | class ____(Layer):
"""Wraps a TensorFlow Operation in a Layer.
This class is used internally by the Functional API. When a user
uses a raw TensorFlow Operation on symbolic tensors originating
from an `Input` Layer, the resultant operation will be wrapped
with this Layer object in order to make the operation ... | TensorFlowOpLayer |
python | celery__celery | t/unit/tasks/test_stamping.py | {
"start": 2492,
"end": 4291
} | class ____(StampingVisitor):
def on_signature(self, actual_sig: Signature, **headers) -> dict:
return {
"on_signature": ["ListStampingVisitor: on_signature-item1", "ListStampingVisitor: on_signature-item2"]
}
def on_group_start(self, actual_sig: Signature, **headers) -> dict:
... | ListStampingVisitor |
python | kamyu104__LeetCode-Solutions | Python/replace-elements-in-an-array.py | {
"start": 72,
"end": 515
} | class ____(object):
def arrayChange(self, nums, operations):
"""
:type nums: List[int]
:type operations: List[List[int]]
:rtype: List[int]
"""
lookup = {x:i for i, x in enumerate(nums)}
for x, y in operations:
lookup[y] = lookup.pop(x)
for ... | Solution |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 159322,
"end": 163108
} | class ____(Qwen3OmniMoePreTrainedModel):
_can_record_outputs = {
"hidden_states": Qwen3OmniMoeCode2WavTransformerLayer,
"attentions": Qwen3OmniMoeCode2WavAttention,
}
def __init__(self, config: Qwen3OmniMoeCode2WavConfig):
super().__init__(config)
self.layers = nn.ModuleList... | Qwen3OmniMoeCode2WavTransformerModel |
python | pydata__xarray | asv_bench/benchmarks/indexing.py | {
"start": 3773,
"end": 4253
} | class ____(Base):
@parameterized(["key"], [list(basic_indexes.keys())])
def time_indexing_basic(self, key):
self.ds.isel(**basic_indexes[key])
@parameterized(["key"], [list(outer_indexes.keys())])
def time_indexing_outer(self, key):
self.ds.isel(**outer_indexes[key])
@parameterized... | IndexingOnly |
python | pytorch__pytorch | test/test_autograd.py | {
"start": 423108,
"end": 464098
} | class ____(TestCase):
def test_min_max_median_backprops_to_all_values(self, device):
for f in [torch.min, torch.max, torch.median, torch.nanmedian]:
x1 = torch.tensor(
[1.0, 0.0, 1.0, 0.0, 1.0, 0.0], device=device, requires_grad=True
)
x2 = torch.tensor(
... | TestAutogradDeviceType |
python | spack__spack | lib/spack/spack/compilers/libraries.py | {
"start": 12985,
"end": 13415
} | class ____:
"""Base class for compiler output cache. Default implementation does not cache anything."""
def value(self, compiler: spack.spec.Spec) -> Dict[str, Optional[str]]:
return {"c_compiler_output": CompilerPropertyDetector(compiler)._compile_dummy_c_source()}
def get(self, compiler: spack.s... | CompilerCache |
python | scipy__scipy | scipy/fft/tests/test_helper.py | {
"start": 17814,
"end": 18682
} | class ____:
def test_definition(self, xp):
x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64)
x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64)
# default dtype varies across backends
y = 9 * fft.fftfreq(9, xp=xp)
xp_assert_close(y, x, che... | TestFFTFreq |
python | chroma-core__chroma | chromadb/execution/executor/local.py | {
"start": 1356,
"end": 7520
} | class ____(Executor):
_manager: LocalSegmentManager
def __init__(self, system: System):
super().__init__(system)
self._manager = self.require(LocalSegmentManager)
@overrides
def count(self, plan: CountPlan) -> int:
return self._metadata_segment(plan.scan.collection).count(plan.... | LocalExecutor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-posthog/source_posthog/components.py | {
"start": 500,
"end": 2122
} | class ____(SimpleRetriever):
def __post_init__(self, parameters: Mapping[str, Any]):
super().__post_init__(parameters)
self.cursor = self.stream_slicer if isinstance(self.stream_slicer, Cursor) else None
def request_params(
self,
stream_state: StreamSlice,
stream_slice: ... | EventsSimpleRetriever |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 16814,
"end": 18834
} | class ____(SingleContinuousDistribution):
_argnames = ('alpha', 'left', 'right')
@property
def set(self):
return Interval(self.left, self.right)
@staticmethod
def check(alpha, left, right):
_value_check (alpha.is_positive, "Shape must be positive.")
_value_check (left.is_po... | BoundedParetoDistribution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_run_launcher.py | {
"start": 10669,
"end": 13609
} | class ____(BaseTestSuite):
def test_launch_multiple_runs_success_and_failure(
self, graphql_context: WorkspaceRequestContext
):
launchSuccessExecutionParams = [
{
"selector": {
"repositoryLocationName": "test_location",
"reposit... | TestSuccessAndFailureMultipleLaunch |
python | mlflow__mlflow | mlflow/gateway/schemas/completions.py | {
"start": 2023,
"end": 2287
} | class ____(ResponseModel):
id: str | None = None
object: str = "text_completion_chunk"
created: int
model: str
choices: list[StreamChoice]
model_config = ConfigDict(json_schema_extra=_STREAM_RESPONSE_PAYLOAD_EXTRA_SCHEMA)
| StreamResponsePayload |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session_test.py | {
"start": 24023,
"end": 24358
} | class ____(monitored_session._WrappedSession):
"""A wrapped session that stops at the N-th call to _check_stop."""
def __init__(self, sess, n):
super(StopAtNSession, self).__init__(sess)
self._count = n
def _check_stop(self):
if self._count == 0:
return True
self._count -= 1
return Fal... | StopAtNSession |
python | walkccc__LeetCode | solutions/1652. Defuse the Bomb/1652.py | {
"start": 0,
"end": 500
} | class ____:
def decrypt(self, code: list[int], k: int) -> list[int]:
n = len(code)
ans = [0] * n
if k == 0:
return ans
summ = 0
start = 1 if k > 0 else n + k # the start of the next k numbers
end = k if k > 0 else n - 1 # the end of the next k numbers
for i in range(start, end + ... | Solution |
python | wandb__wandb | wandb/automations/scopes.py | {
"start": 518,
"end": 683
} | class ____(LenientStrEnum):
"""The kind of scope that triggers an automation."""
PROJECT = "PROJECT"
ARTIFACT_COLLECTION = "ARTIFACT_COLLECTION"
| ScopeType |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 9798,
"end": 10557
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_delete_dlp_job(self, mock_hook):
mock_hook.return_value.delete_dlp_job.return_value = mock.MagicMock()
operator = CloudDLPDeleteDLPJobOperator(dlp_job_id=DLP_JOB_ID, project_id=PROJECT_ID, task_id="id")... | TestCloudDLPDeleteDlpJobOperator |
python | pandas-dev__pandas | pandas/tests/reshape/test_melt.py | {
"start": 943,
"end": 19650
} | class ____:
def test_top_level_method(self, df):
result = melt(df)
assert result.columns.tolist() == ["variable", "value"]
def test_method_signatures(self, df, df1, var_name, value_name):
tm.assert_frame_equal(df.melt(), melt(df))
tm.assert_frame_equal(
df.melt(id_v... | TestMelt |
python | getsentry__sentry | src/sentry/models/orgauthtoken.py | {
"start": 1452,
"end": 6887
} | class ____(ReplicatedControlModel):
__relocation_scope__ = RelocationScope.Organization
category = OutboxCategory.ORG_AUTH_TOKEN_UPDATE
organization_id = HybridCloudForeignKey("sentry.Organization", null=False, on_delete="CASCADE")
# The JWT token in hashed form
token_hashed = models.TextField(uniq... | OrgAuthToken |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 493,
"end": 756
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {
"$ref": create_definition_ref(
"io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta/properties/labels"
)
},
}
| Labels |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 23040,
"end": 24328
} | class ____:
__slots__ = ("client",)
def __init__(self, client: Client):
self.client = client
def get(
self,
name: str | None = None,
uri: str | None = None,
alias_name: str | None = None,
after: datetime | None = None,
before: datetime | None = None,... | AssetEventOperations |
python | pdm-project__pdm | src/pdm/pytest.py | {
"start": 3711,
"end": 5042
} | class ____:
def __init__(self, pypi_json: Path) -> None:
self.pypi_data = self.load_fixtures(pypi_json)
@staticmethod
def load_fixtures(pypi_json: Path) -> dict[str, Any]:
return json.loads(pypi_json.read_text())
def add_candidate(self, name: str, version: str, requires_python: str = "... | RepositoryData |
python | run-llama__llama_index | llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py | {
"start": 2804,
"end": 8137
} | class ____:
"""Test BaseAgentCoreMemory methods using AgentCoreMemory instance."""
def test_create_event_success(self, memory):
"""Test successful event creation."""
messages = [ChatMessage(role=MessageRole.USER, content="Hello")]
memory.create_event(
memory_id="test-memory... | TestBaseAgentCoreMemoryMethods |
python | fluentpython__example-code | 07-closure-deco/clockdeco_cls.py | {
"start": 365,
"end": 989
} | class ____:
def __init__(self, fmt=DEFAULT_FMT):
self.fmt = fmt
def __call__(self, func):
def clocked(*_args):
t0 = time.time()
_result = func(*_args)
elapsed = time.time() - t0
name = func.__name__
args = ', '.join(repr(arg) for arg ... | clock |
python | getsentry__sentry | src/sentry/taskworker/retry.py | {
"start": 517,
"end": 735
} | class ____(RetryTaskError):
"""
Exception that is raised by retry helper methods to signal to tasks that
the current attempt is terminal and there won't be any further retries.
"""
| NoRetriesRemainingError |
python | numba__numba | numba/cuda/tests/cudadrv/test_array_attr.py | {
"start": 115,
"end": 5300
} | class ____(CUDATestCase):
def test_contigous_2d(self):
ary = np.arange(10)
cary = ary.reshape(2, 5)
fary = np.asfortranarray(cary)
dcary = cuda.to_device(cary)
dfary = cuda.to_device(fary)
self.assertTrue(dcary.is_c_contiguous())
self.assertTrue(not dfary.is... | TestArrayAttr |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 208097,
"end": 208287
} | class ____(VegaLiteSchema):
"""Color schema wrapper."""
_schema = {"$ref": "#/definitions/Color"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| Color |
python | ipython__ipython | IPython/lib/display.py | {
"start": 463,
"end": 9136
} | class ____(DisplayObject):
"""Create an audio object.
When this object is returned by an input cell or passed to the
display function, it will result in Audio controls being displayed
in the frontend (only works in the notebook).
Parameters
----------
data : numpy array, list, unicode, str... | Audio |
python | scipy__scipy | scipy/stats/_survival.py | {
"start": 413,
"end": 7924
} | class ____:
"""An empirical distribution function produced by `scipy.stats.ecdf`
Attributes
----------
quantiles : ndarray
The unique values of the sample from which the
`EmpiricalDistributionFunction` was estimated.
probabilities : ndarray
The point estimates of the cumulat... | EmpiricalDistributionFunction |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 40301,
"end": 40407
} | class ____:
__slots__ = ["x", "y"]
x: int
y: int
@dataclass
| ClassThatUsesBuildInstructionAllSlots |
python | pennersr__django-allauth | allauth/usersessions/middleware.py | {
"start": 100,
"end": 613
} | class ____:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if (
app_settings.TRACK_ACTIVITY
and hasattr(request, "session")
and request.session.session_key
and hasattr(request, "user")
a... | UserSessionsMiddleware |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 12358,
"end": 13406
} | class ____(ChoicesParser):
"""Composite argument parser which accepts any input value."""
def __init__(self, nothing: bool = False, no_match_message: t.Optional[str] = None) -> None:
self.no_match_message = no_match_message
conditions = MatchConditions.ANY
if nothing:
cond... | AnyParser |
python | tornadoweb__tornado | maint/test/websocket/server.py | {
"start": 213,
"end": 607
} | class ____(WebSocketHandler):
def on_message(self, message):
self.write_message(message, binary=isinstance(message, bytes))
def get_compression_options(self):
return {}
if __name__ == '__main__':
parse_command_line()
app = Application([
('/', EchoHandler),
])
app.liste... | EchoHandler |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/main_widget.py | {
"start": 2764,
"end": 2894
} | class ____:
TodoList = "todo_list_menu"
WarningErrorList = "warning_error_list_menu"
EOL = "eol_menu"
| EditorWidgetMenus |
python | joke2k__faker | faker/providers/address/es_AR/__init__.py | {
"start": 115,
"end": 6530
} | class ____(AddressProvider):
provinces = {
"CABA": "Ciudad Autónoma de Buenos Aires",
"BA": "Buenos Aires",
"CA": "Catamarca",
"CH": "Chaco",
"CT": "Chubut",
"CB": "Córdoba",
"CR": "Corrientes",
"ER": "Entre Ríos",
"FO": "Formosa",
"JY"... | Provider |
python | Pylons__pyramid | tests/test_config/test_views.py | {
"start": 148667,
"end": 149035
} | class ____:
def __init__(self, getval=None):
self.related = []
self.introspectables = []
self.getval = getval
def add(self, introspectable):
self.introspectables.append(introspectable)
def get(self, name, discrim):
return self.getval
def relate(self, a, b):
... | DummyIntrospector |
python | walkccc__LeetCode | solutions/2599. Make the Prefix Sum Non-negative/2599.py | {
"start": 0,
"end": 315
} | class ____:
def makePrefSumNonNegative(self, nums: list[int]) -> int:
ans = 0
prefix = 0
minHeap = []
for num in nums:
prefix += num
if num < 0:
heapq.heappush(minHeap, num)
while prefix < 0:
prefix -= heapq.heappop(minHeap)
ans += 1
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 565745,
"end": 566129
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("Deployment", graphql_name... | DeploymentEdge |
python | numpy__numpy | benchmarks/benchmarks/bench_reduce.py | {
"start": 340,
"end": 607
} | class ____(Benchmark):
params = [[0, 1], TYPES1]
param_names = ['axis', 'type']
def setup(self, axis, typename):
self.a = get_squares()[typename]
def time_reduce(self, axis, typename):
np.add.reduce(self.a, axis=axis)
| AddReduceSeparate |
python | Pylons__pyramid | tests/test_threadlocal.py | {
"start": 2420,
"end": 2748
} | class ____(unittest.TestCase):
def _callFUT(self):
from pyramid.threadlocal import get_current_registry
return get_current_registry()
def test_it(self):
from pyramid.registry import global_registry
self.assertEqual(self._callFUT(), global_registry)
| GetCurrentRegistryWithoutTestingRegistry |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_scheduler.py | {
"start": 38402,
"end": 39030
} | class ____:
"""Tests scheduler network policy."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"networkPolicies": {"enabled": True},
"scheduler": {
"labels": {"test_label": "test_label_value"},
... | TestSchedulerNetworkPolicy |
python | getsentry__sentry | tests/sentry/utils/test_sdk.py | {
"start": 17599,
"end": 21548
} | class ____(TestCase):
def _make_orgs(self, n: int) -> list[Organization]:
return [self.create_organization() for _ in range(n)]
def test_simple(self) -> None:
orgs = self._make_orgs(3)
with patch_isolation_scope() as mock_scope:
bind_ambiguous_org_context(orgs, "integration... | BindAmbiguousOrgContextTest |
python | astropy__astropy | astropy/table/tests/test_masked.py | {
"start": 15638,
"end": 26961
} | class ____:
def test_add_masked_row_to_masked_table_iterable(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name="a", data=[1], mask=[0]))
t.add_column(MaskedColumn(name="b", data=[4], mask=[1]))
t.add_row([2, 5], mask=[1, 0])
t.add_row([3, 6], mask=[0, 1])
a... | TestAddRow |
python | bokeh__bokeh | src/bokeh/core/property/enum.py | {
"start": 1474,
"end": 5169
} | class ____(Either):
""" Accept values from enumerations.
The first value in enumeration is used as the default value, unless the
``default`` keyword argument is used.
See :ref:`bokeh.core.enums` for more information.
"""
_enum: enums.Enumeration
@overload
def __init__(self, enum: en... | Enum |
python | pandas-dev__pandas | pandas/core/groupby/ops.py | {
"start": 2563,
"end": 18522
} | class ____:
"""
Dispatch logic for functions defined in _libs.groupby
Parameters
----------
kind: str
Whether the operation is an aggregate or transform.
how: str
Operation name, e.g. "mean".
has_dropped_na: bool
True precisely when dropna=True and the grouper contai... | WrappedCythonOp |
python | gevent__gevent | src/gevent/_abstract_linkable.py | {
"start": 1389,
"end": 1926
} | class ____(object):
__slots__ = (
'pending',
)
def __init__(self):
self.pending = False
def get_roots_and_hubs():
from gevent.hub import Hub # delay import
return {
x.parent: x
for x in get_objects()
# Make sure to only find hubs that have a loop
# a... | _FakeNotifier |
python | scrapy__scrapy | scrapy/utils/serialize.py | {
"start": 192,
"end": 1117
} | class ____(json.JSONEncoder):
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"
def default(self, o: Any) -> Any:
if isinstance(o, set):
return list(o)
if isinstance(o, datetime.datetime):
return o.strftime(f"{self.DATE_FORMAT} {self.TIME_FORMAT}")
if isinsta... | ScrapyJSONEncoder |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 20371,
"end": 20718
} | class ____(GeomOutputGeoFunc):
def __init__(self, expression, srid, **extra):
expressions = [
expression,
self._handle_param(srid, "srid", int),
]
if "output_field" not in extra:
extra["output_field"] = GeometryField(srid=srid)
super().__init__(*ex... | Transform |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 52731,
"end": 52896
} | class ____(Interface):
def __call__(value, info):
"""
Create a a :class:`.IPredicate` instance for a specific value.
"""
| IPredicateFactory |
python | django__django | django/db/models/deletion.py | {
"start": 3406,
"end": 22130
} | class ____:
def __init__(self, using, origin=None, force_collection=False):
self.using = using
# A Model or QuerySet object.
self.origin = origin
# Force collecting objects for deletion on the Python-level.
self.force_collection = force_collection
# Initially, {model:... | Collector |
python | huggingface__transformers | tests/models/blip_2/test_modeling_blip_2.py | {
"start": 45959,
"end": 49172
} | class ____:
def __init__(self, parent, vision_kwargs=None, qformer_kwargs=None, is_training=True):
if vision_kwargs is None:
vision_kwargs = {}
if qformer_kwargs is None:
qformer_kwargs = {"use_qformer_text_input": True}
self.parent = parent
self.vision_model... | Blip2VisionModelWithProjectionTester |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 86516,
"end": 90122
} | class ____:
@staticmethod
def pq(
bit_compression: Optional[bool] = None,
centroids: Optional[int] = None,
encoder_distribution: Optional[PQEncoderDistribution] = None,
encoder_type: Optional[PQEncoderType] = None,
segments: Optional[int] = None,
training_limit: O... | _VectorIndexQuantizerUpdate |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 224977,
"end": 230665
} | class ____(Request):
"""
Add or update task hyper parameters
:param task: Task ID
:type task: str
:param hyperparams: Task hyper parameters. The new ones will be added and the
already existing ones will be updated
:type hyperparams: Sequence[ParamsItem]
:param replace_hyperparams: C... | EditHyperParamsRequest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/implementation/utils.py | {
"start": 20074,
"end": 21752
} | class ____(Exception):
# The `error` arg here should be a Graphene type implementing the interface `GrapheneError`, but
# this is not trackable by the Python type system.
def __init__(self, error: Any):
self.error = error
message = "[{cls}] {message}".format(
cls=error.__class__.... | UserFacingGraphQLError |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/ag_ctx.py | {
"start": 1700,
"end": 1774
} | class ____(enum.Enum):
UNSPECIFIED = 0
ENABLED = 1
DISABLED = 2
| Status |
python | scipy__scipy | scipy/optimize/_optimize.py | {
"start": 4132,
"end": 5748
} | class ____(_RichResult):
"""
Represents the optimization result.
Attributes
----------
x : ndarray
The solution of the optimization.
success : bool
Whether or not the optimizer exited successfully.
status : int
Termination status of the optimizer. Its value depends o... | OptimizeResult |
python | jazzband__django-model-utils | model_utils/models.py | {
"start": 4350,
"end": 5915
} | class ____(models.Model):
"""
An abstract base class model with a ``is_removed`` field that
marks entries that are not going to be used anymore, but are
kept in db for any reason.
Default manager returns only not-removed entries.
"""
is_removed = models.BooleanField(default=False)
class... | SoftDeletableModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_events.py | {
"start": 2706,
"end": 9876
} | class ____(TestCase):
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
_a_request().with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(),
_a_response().with_record(_a_record()).w... | FullRefreshTest |
python | realpython__materials | python-313/typing/readonly.py | {
"start": 896,
"end": 1439
} | class ____(TypedDict):
version: str
release_year: ReadOnly[int]
# %% Work with Version and PythonVersion
#
def get_version_info(ver: Version) -> str:
if "release_year" in ver:
return f"Version {ver['version']} released in {ver['release_year']}"
else:
return f"Version {ver['version']}"
... | PythonVersion |
python | django__django | tests/model_forms/tests.py | {
"start": 132701,
"end": 132891
} | class ____(ModelFormMetaclass):
def __new__(cls, name, bases, attrs):
new = super().__new__(cls, name, bases, attrs)
new.base_fields = {}
return new
| CustomMetaclass |
python | walkccc__LeetCode | solutions/826. Most Profit Assigning Work/826.py | {
"start": 0,
"end": 435
} | class ____:
def maxProfitAssignment(
self,
difficulty: list[int],
profit: list[int],
worker: list[int],
) -> int:
ans = 0
jobs = sorted(zip(difficulty, profit))
worker.sort(reverse=1)
i = 0
maxProfit = 0
for w in sorted(worker):
while i < len(jobs) and w >= jo... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.