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 | astropy__astropy | astropy/uncertainty/tests/test_functions.py | {
"start": 489,
"end": 901
} | class ____:
@classmethod
def setup_class(cls):
cls.a = (
np.array([[[0.0]], [[10.0]]])
+ np.array([[0.0], [1.0], [2.0]])
+ np.arange(4.0) / 10.0
)
cls.b = -(np.arange(3.0, 6.0)[:, np.newaxis] + np.arange(4.0) / 10.0)
cls.da = Distribution(cls.a... | ArraySetup |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 4665,
"end": 4890
} | class ____(models.Model):
pass
def prevent_deletes(sender, instance, **kwargs):
raise models.ProtectedError("Not allowed to delete.", [instance])
models.signals.pre_delete.connect(prevent_deletes, sender=Node)
| Related |
python | sqlalchemy__sqlalchemy | test/sql/test_compiler.py | {
"start": 281493,
"end": 289608
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
"""test the _omit_from_statements parameter.
this somewhat awkward parameter was added to suit the case of
"insert_sentinel" columns that would try very hard not to be noticed
when not needed, by being omitted from any SQL statement that does not
r... | OmitFromStatementsTest |
python | kamyu104__LeetCode-Solutions | Python/number-of-subsequences-with-odd-sum.py | {
"start": 66,
"end": 377
} | class ____(object):
def subsequenceCount(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MOD = 10**9+7
# 2^(odd-1)*2^even = 2^(len(nums)-1)
return pow(2, len(nums)-1, MOD) if any(x%2 for x in nums) else 0
# Time: O(n)
# Space: O(1)
# dp
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 54647,
"end": 55890
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
username: str,
jdbc_url: str,
password: Optional[str] = None,
jdbc_url_params: Optional[str] = None,
):
"""Airbyte Source for Jdbc.
Documentation can be found at https:... | JdbcSource |
python | pytest-dev__pytest | testing/test_cacheprovider.py | {
"start": 478,
"end": 9385
} | class ____:
def test_config_cache_mkdir(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]")
config = pytester.parseconfigure()
assert config.cache is not None
with pytest.raises(ValueError):
config.cache.mkdir("key/name")
p = config.cache.mkdir("name"... | TestNewAPI |
python | huggingface__transformers | src/transformers/models/clvp/tokenization_clvp.py | {
"start": 2298,
"end": 12960
} | class ____(PreTrainedTokenizer):
"""
Construct a CLVP tokenizer. Based on byte-level Byte-Pair-Encoding.
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without spac... | ClvpTokenizer |
python | huggingface__transformers | tests/models/bit/test_modeling_bit.py | {
"start": 5463,
"end": 9358
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as Bit does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (BitModel, BitForImageClassification, BitBackbone) if i... | BitModelTest |
python | ray-project__ray | python/ray/air/config.py | {
"start": 21131,
"end": 28893
} | class ____:
"""Runtime configuration for training and tuning runs.
Upon resuming from a training or tuning run checkpoint,
Ray Train/Tune will automatically apply the RunConfig from
the previously checkpointed run.
Args:
name: Name of the trial or experiment. If not provided, will be deduc... | RunConfig |
python | pdm-project__pdm | src/pdm/models/repositories/lock.py | {
"start": 917,
"end": 1093
} | class ____:
candidate: Candidate
dependencies: list[str] | None = None
summary: str = ""
marker: BaseMarker = dataclasses.field(default_factory=AnyMarker)
| Package |
python | joerick__pyinstrument | pyinstrument/low_level/stat_profile_python.py | {
"start": 366,
"end": 4761
} | class ____:
await_stack: list[str]
timing_thread_subscription: int | None = None
def __init__(
self,
target: Callable[[types.FrameType, str, Any], Any],
interval: float,
context_var: contextvars.ContextVar[object | None] | None,
timer_type: TimerType,
timer_f... | PythonStatProfiler |
python | miyuchina__mistletoe | mistletoe/block_token.py | {
"start": 28789,
"end": 29321
} | class ____(BlockToken):
"""
Table cell token.
This is a leaf block token. Its children are inline (span) tokens.
Should only be called by TableRow.__init__().
Attributes:
align (bool): align option for current cell (default to None).
"""
repr_attributes = BlockToken.repr_attributes... | TableCell |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_member_details.py | {
"start": 51260,
"end": 57189
} | class ____(APITestCase):
def setUp(self) -> None:
self.owner = self.create_user()
self.org = self.create_organization(owner=self.owner)
self.member = self.create_user()
self.member_om = self.create_member(
organization=self.org, user=self.member, role="member", teams=[]
... | ResetOrganizationMember2faTest |
python | martinblech__xmltodict | xmltodict.py | {
"start": 314,
"end": 19480
} | class ____:
def __init__(
self,
item_depth=0,
item_callback=lambda *args: True,
xml_attribs=True,
attr_prefix="@",
cdata_key="#text",
force_cdata=False,
cdata_separator="",
postprocessor=None,
dict_constructor=dict,
strip_whites... | _DictSAXHandler |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_heapq.py | {
"start": 17323,
"end": 17449
} | class ____(_TestErrorHandling, __TestCase):
module = py_heapq
@skipUnless(c_heapq, 'requires _heapq')
| TestErrorHandlingPython |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 2883,
"end": 2906
} | class ____(H2, H1): ...
| H |
python | pydata__xarray | xarray/tests/test_parallelcompat.py | {
"start": 1502,
"end": 4388
} | class ____(ChunkManagerEntrypoint):
"""Mock-up of ChunkManager class for DummyChunkedArray"""
def __init__(self):
self.array_cls = DummyChunkedArray
def is_chunked_array(self, data: Any) -> bool:
return isinstance(data, DummyChunkedArray)
def chunks(self, data: DummyChunkedArray) -> T... | DummyChunkManager |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/prepare_image_stage.py | {
"start": 638,
"end": 5197
} | class ____:
"""Adapted from vllm.connections.HTTPConnection.
Helper class to send HTTP requests.
"""
def __init__(self, *, reuse_client: bool = True) -> None:
super().__init__()
self.reuse_client = reuse_client
self._sync_client: Optional[requests.Session] = None
self.... | HTTPConnection |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 23925,
"end": 26984
} | class ____(Initializer):
"""Initializer that generates tensors without scaling variance.
When initializing a deep network, it is in principle advantageous to keep
the scale of the input variance constant, so it does not explode or diminish
by reaching the final layer. If the input is `x` and the operation `x *... | UniformUnitScaling |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 71393,
"end": 72195
} | class ____(BiffRecord):
"""
This record specifies the default height and default flags
for rows that do not have a corresponding ROW record.
Record DEFAULTROWHEIGHT, BIFF3-BIFF8:
Offset Size Contents
0 2 Option flags:
Bit Mask Contents
... | DefaultRowHeightRecord |
python | ray-project__ray | python/ray/_private/event/export_event_logger.py | {
"start": 3006,
"end": 9091
} | class ____:
def __init__(self, log_type: EventLogType, logger: logging.Logger):
"""Adapter for the Python logger that's used to emit export events."""
self.logger = logger
self.log_type = log_type
def send_event(self, event_data: ExportEventDataType):
# NOTE: Python logger is th... | ExportEventLoggerAdapter |
python | kubernetes-client__python | kubernetes/client/models/v1_api_service_condition.py | {
"start": 383,
"end": 7405
} | 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... | V1APIServiceCondition |
python | pytorch__pytorch | torch/_dynamo/output_graph.py | {
"start": 121009,
"end": 121419
} | class ____:
def __init__(
self,
tracer: "SubgraphTracer",
fn: Callable[P, R],
*args: P.args,
**kwargs: P.kwargs,
) -> None:
self.tracer = tracer
# pyrefly: ignore [invalid-type-var]
self.fn = fn
self.args = args
self.kwargs = kwargs... | LazyProxy |
python | apache__airflow | devel-common/src/sphinx_exts/removemarktransform.py | {
"start": 1225,
"end": 2707
} | class ____(SphinxTransform):
"""
Trim doc marker like ``# [START howto_concept]` from python code-blocks.
Based on:
https://github.com/sphinx-doc/sphinx/blob/master/sphinx/transforms/post_transforms/code.py
class TrimDoctestFlagsTransform
"""
default_priority = TrimDoctestFlagsTransform.de... | TrimDocMarkerFlagsTransform |
python | getsentry__sentry | src/sentry/discover/endpoints/discover_saved_queries.py | {
"start": 1547,
"end": 7560
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.DATA_BROWSING
permission_classes = (DiscoverSavedQueryPermission,)
def has_feature(self, organization, request):
return features.has(
... | DiscoverSavedQueriesEndpoint |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/definition/assets_definition.py | {
"start": 3676,
"end": 92949
} | class ____(ResourceAddable, IHasInternalInit):
"""Defines a set of assets that are produced by the same op or graph.
AssetsDefinitions are typically not instantiated directly, but rather produced using the
:py:func:`@asset <asset>` or :py:func:`@multi_asset <multi_asset>` decorators.
"""
# Constru... | AssetsDefinition |
python | getsentry__sentry | src/sentry/integrations/perforce/integration.py | {
"start": 10756,
"end": 11242
} | class ____:
"""
Installation view for Perforce configuration.
This is a simple pass-through view. The actual configuration
happens in the Settings tab after installation via get_organization_config().
"""
def dispatch(self, request, pipeline):
"""
Handle installation request.
... | PerforceInstallationView |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/provider.py | {
"start": 1550,
"end": 35037
} | class ____(SpyderCompletionProvider):
"""Language Server Protocol manager."""
COMPLETION_PROVIDER_NAME = 'lsp'
DEFAULT_ORDER = 1
SLOW = True
CONF_DEFAULTS = [
('enable_hover_hints', True),
('show_lsp_down_warning', True),
('code_completion', True),
# ('code_snippets',... | LanguageServerProvider |
python | doocs__leetcode | solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution2.py | {
"start": 192,
"end": 620
} | class ____:
def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
def dfs(root, d):
if root is None:
return
if len(arr) <= d:
arr.append(0)
arr[d] += root.val
dfs(root.left, d + 1)
dfs(root.right, d ... | Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_ecs.py | {
"start": 32834,
"end": 36141
} | class ____(EcsBaseTestCase):
@pytest.mark.parametrize(("waiter_delay", "waiter_max_attempts"), WAITERS_TEST_CASES)
def test_execute_with_waiter(self, patch_hook_waiters, waiter_delay, waiter_max_attempts):
mocked_waiters = mock.MagicMock(name="MockedHookWaitersMethod")
patch_hook_waiters.return_... | TestEcsCreateClusterOperator |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 137597,
"end": 140046
} | class ____(nn.Module):
def __init__(self, config: Qwen2_5OmniDiTConfig):
super().__init__()
self.config = config
self.dim = config.hidden_size
self.heads = config.num_attention_heads
self.inner_dim = config.head_dim * config.num_attention_heads
self.dropout = config.... | DiTAttention |
python | doocs__leetcode | solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution.py | {
"start": 0,
"end": 444
} | class ____:
def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums2)
f = [[inf] * (1 << n) for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(nums1, 1):
for j in range(1 << n):
for k in range(n):
if j >> ... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format09.py | {
"start": 315,
"end": 1314
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with conditional formatting."""
... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/parakeet/modular_parakeet.py | {
"start": 4592,
"end": 4796
} | class ____(FastSpeech2ConformerConvolutionModule):
def __init__(self, config: ParakeetEncoderConfig, module_config=None):
super().__init__(config, module_config)
| ParakeetEncoderConvolutionModule |
python | automl__auto-sklearn | autosklearn/pipeline/components/regression/mlp.py | {
"start": 650,
"end": 11159
} | class ____(IterativeComponent, AutoSklearnRegressionAlgorithm):
def __init__(
self,
hidden_layer_depth,
num_nodes_per_layer,
activation,
alpha,
learning_rate_init,
early_stopping,
solver,
batch_size,
n_iter_no_change,
tol,
... | MLPRegressor |
python | airbytehq__airbyte | airbyte-integrations/bases/base-normalization/normalization/transform_catalog/dbt_macro.py | {
"start": 101,
"end": 438
} | class ____(ABC):
"https://docs.getdbt.com/docs/building-a-dbt-project/jinja-macros"
@abstractmethod
def __str__(self):
pass
def __repr__(self):
return str(self)
def __add__(self, other):
return str(self) + str(other)
def __radd__(self, other):
return str(other... | Macro |
python | mlflow__mlflow | mlflow/johnsnowlabs/__init__.py | {
"start": 33789,
"end": 34821
} | class ____:
"""
Wrapper around NLUPipeline providing interface for scoring pandas DataFrame.
"""
def __init__(
self,
spark_model,
spark=None,
):
# we have this `or`, so we support _PyFuncModelWrapper(nlu_ref)
self.spark = spark or _get_or_create_sparksession(... | _PyFuncModelWrapper |
python | doocs__leetcode | solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.py | {
"start": 0,
"end": 179
} | class ____:
def queryString(self, s: str, n: int) -> bool:
if n > 1000:
return False
return all(bin(i)[2:] in s for i in range(n, n // 2, -1))
| Solution |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 6235,
"end": 8797
} | class ____(nn.Module):
def __init__(self, config: MobileViTConfig, hidden_size: int) -> None:
super().__init__()
if hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size {hidden_size} is not a multiple of the number of attention "
... | MobileViTSelfAttention |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 11636,
"end": 11981
} | class ____(RawDataMixin, IncrementalAppsflyerStream):
cursor_field = "install_time"
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
return f"raw-data/export/app/{self.app_id}/organic_installs... | OrganicInstalls |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/np_test.py | {
"start": 139528,
"end": 141166
} | class ____(jtu.TestCase):
@named_parameters(itertools.chain.from_iterable(
jtu.cases_from_list(
{"testcase_name": jtu.format_test_name_suffix(
rec.name, shapes, itertools.repeat(dtype)),
"op": rec.op, "rng_factory": rec.rng_factory, "shapes": shapes, "dtype": dtype,
"order"... | NumpyGradTests |
python | ray-project__ray | python/ray/tests/test_runtime_env_strong_type.py | {
"start": 261,
"end": 1715
} | class ____:
field1: List[ValueType]
field2: str
def test_convert_from_and_to_dataclass():
runtime_env = RuntimeEnv()
test_plugin = TestPlugin(
field1=[
ValueType(nfield1=["a", "b", "c"], nfield2=False),
ValueType(nfield1=["d", "e"], nfield2=True),
],
fie... | TestPlugin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/misplaced_bare_raise.py | {
"start": 340,
"end": 1090
} | class ____:
def __enter__(self):
return self
def __exit__(self, *args):
raise
try:
raise # [misplaced-bare-raise]
except Exception:
pass
def f():
try:
raise # [misplaced-bare-raise]
except Exception:
pass
def g():
raise # [misplaced-bare-raise]
def h():
... | ContextManager |
python | django__django | tests/backends/base/test_base.py | {
"start": 10775,
"end": 17875
} | class ____(SimpleTestCase):
databases = {"default"}
def setUp(self):
# All test cases here need newly configured and created connections.
# Use the default db connection for convenience.
connection.close()
self.addCleanup(connection.close)
def patch_settings_dict(self, conn... | ConnectionHealthChecksTests |
python | mlflow__mlflow | mlflow/genai/scorers/builtin_scorers.py | {
"start": 61064,
"end": 63604
} | class ____(BuiltInSessionLevelScorer):
"""
ConversationCompleteness evaluates whether an AI assistant fully addresses all user requests
by the end of the conversation.
For evaluating the completeness of a single user prompt, use the Completeness scorer instead.
This scorer analyzes a complete conv... | ConversationCompleteness |
python | fastapi__sqlmodel | docs_src/tutorial/indexes/tutorial001_py310.py | {
"start": 71,
"end": 1184
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, ec... | Hero |
python | pennersr__django-allauth | allauth/socialaccount/providers/jupyterhub/provider.py | {
"start": 280,
"end": 661
} | class ____(OAuth2Provider):
id = "jupyterhub"
name = "JupyterHub"
account_class = JupyterHubAccount
oauth2_adapter_class = JupyterHubOAuth2Adapter
def extract_uid(self, data):
return str(data.get("name"))
def extract_common_fields(self, data):
return dict(name=data.get("name", ... | JupyterHubProvider |
python | google__pytype | pytype/abstract/abstract_utils.py | {
"start": 3114,
"end": 3327
} | class ____(Exception):
"""The error for user-defined generic types."""
def __init__(self, annot, error) -> None:
super().__init__(annot, error)
self.annot = annot
self.error = error
| GenericTypeError |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 154403,
"end": 165389
} | class ____(TestCase):
@parameterized.named_parameters(
("f32", jnp.float32, 256),
("f16", jnp.float16, 256),
("f16_small", jnp.float16, 128),
)
def test_store_untiled_splat(self, jax_dtype, size):
mlir_dtype = utils.dtype_to_ir_type(jax_dtype)
def kernel(ctx, out, _):
del ctx
... | LayoutTest |
python | langchain-ai__langchain | libs/core/langchain_core/messages/content.py | {
"start": 13237,
"end": 13907
} | class ____(TypedDict):
"""Result of a server-side tool call."""
type: Literal["server_tool_result"]
"""Used for discrimination."""
id: NotRequired[str]
"""An identifier associated with the server tool result."""
tool_call_id: str
"""ID of the corresponding server tool call."""
status... | ServerToolResult |
python | has2k1__plotnine | plotnine/stats/stat_function.py | {
"start": 402,
"end": 3211
} | class ____(stat):
"""
Superimpose a function onto a plot
{usage}
Parameters
----------
{common_parameters}
fun : callable
Function to evaluate.
n : int, default=101
Number of points at which to evaluate the function.
xlim : tuple, default=None
`x` limits for... | stat_function |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/globus/tests.py | {
"start": 288,
"end": 1034
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = GlobusProvider.id
@override_settings(SOCIALACCOUNT_QUERY_EMAIL=True)
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"identity_provider_display_name": "University of Gozorpaz... | GlobusTests |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modular_lfm2_moe.py | {
"start": 5863,
"end": 5913
} | class ____(Lfm2ShortConv):
pass
| Lfm2MoeShortConv |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 5310,
"end": 5877
} | class ____(TestRss2Feed):
def get_object(self, request, entry_id):
return Entry.objects.get(pk=entry_id)
def items(self, obj):
return Article.objects.filter(entry=obj)
def item_link(self, item):
return "%sarticle/%s/" % (item.entry.get_absolute_url(), item.pk)
def item_comment... | TestGetObjectFeed |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py | {
"start": 4584,
"end": 4720
} | class ____(NamedTuple):
reduce_scatter_input: torch.Tensor
event: Optional[torch.Event] # reduce-scatter event
| ReduceScatterState |
python | kamyu104__LeetCode-Solutions | Python/number-of-bit-changes-to-make-two-integers-equal.py | {
"start": 51,
"end": 357
} | class ____(object):
def minChanges(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def popcount(x):
return bin(x).count('1')
return popcount(n^k) if n&k == k else -1
# Time: O(logn)
# Space: O(1)
# bit manipulation
| Solution |
python | tensorflow__tensorflow | tensorflow/python/data/ops/load_op.py | {
"start": 7087,
"end": 7619
} | class ____(dataset_ops.DatasetSource):
"""A dataset for one chunk file from a tf.data distributed snapshot."""
def __init__(self, chunk_file: str, element_spec: Any, compression: str):
self._chunk_file = chunk_file
self._element_spec = element_spec
variant_tensor = ged_ops.snapshot_chunk_dataset(
... | _SnapshotChunkDataset |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call15.py | {
"start": 1211,
"end": 1441
} | class ____[T]:
def __init__(self, value: T) -> None:
self._value: T = value
def update(self, value: T = 0, /) -> "A[T]":
return A(value)
a = A("")
a.update("")
# This should generate an error.
a.update()
| A |
python | matplotlib__matplotlib | lib/matplotlib/hatch.py | {
"start": 2827,
"end": 3507
} | class ____(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int(
(hatch.count('\\') + hatch.count('x') + hatch.count('X'))
* density)
if self.num_lines:
self.num_vertices = (self.num_lines + 1) * 2
else:
self.num_vertices... | SouthEastHatch |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 172264,
"end": 172985
} | class ____(Operation):
def call(self, x):
return backend.numpy.ravel(x)
def compute_output_spec(self, x):
if None in x.shape:
output_shape = [
None,
]
else:
output_shape = [int(np.prod(x.shape))]
return KerasTensor(output_shape... | Ravel |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_publish_request.py | {
"start": 1393,
"end": 5643
} | class ____(SentryAppBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
def has_ui_component(self, sentry_app):
"""Determine if the sentry app supports issue linking or stack trace linking."""
elements = (sentry_app.schema or {}).g... | SentryAppPublishRequestEndpoint |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 16475,
"end": 19322
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = ElectraAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
... | ElectraLayer |
python | keras-team__keras | keras/src/dtype_policies/dtype_policy.py | {
"start": 10487,
"end": 16005
} | class ____(QuantizedDTypePolicy):
"""Quantized dtype policy for GPTQ quantization.
This policy helps propagate quantization settings for GPTQ
when loading a GPTQ quantized model in Keras format.
Args:
mode: The quantization mode. This should be a string in the format
`"gptq/<weight... | GPTQDTypePolicy |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 892,
"end": 1124
} | class ____:
def test_beat_lazy_func(self):
def add(a, b):
return a + b
result = BeatLazyFunc(add, 1, 2)
assert add(1, 2) == result()
assert add(1, 2) == result.delay()
| test_BeatLazyFunc |
python | pytorch__pytorch | test/dynamo/test_recompile_ux.py | {
"start": 446,
"end": 11336
} | class ____(torch._dynamo.test_case.TestCase):
# TODO(whc) dynamo actually recompiles one more time than the cache limit
cache_limit = 1
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._exit_stack.enter_context(
torch._dynamo.config.patch("recompile_limit", cls.cac... | RecompileUxTests |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_dataplex.py | {
"start": 11989,
"end": 13103
} | class ____:
@pytest.mark.db_test
def test_get_link(self, create_task_instance_of_operator, session, mock_supervisor_comms):
expected_url = EXPECTED_DATAPLEX_CATALOG_ASPECT_TYPE_LINK
link = DataplexCatalogAspectTypeLink()
ti = create_task_instance_of_operator(
DataplexCatalogG... | TestDataplexCatalogAspectTypeLink |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_device_class_configuration.py | {
"start": 383,
"end": 3547
} | 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... | V1beta1DeviceClassConfiguration |
python | huggingface__transformers | tests/models/perception_lm/test_video_processing_perception_lm.py | {
"start": 3274,
"end": 4957
} | class ____(VideoProcessingTestMixin, unittest.TestCase):
fast_video_processing_class = PerceptionLMVideoProcessor if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.video_processor_tester = PerceptionLMVideoProcessingTester(self)
@property
def video_processor... | PerceptionLMVideoProcessingTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType5.py | {
"start": 677,
"end": 1039
} | class ____(Generic[_KT, _VT]):
@classmethod
def method1(cls, i: Iterable[_T], v: _S) -> "A[_T, _S]": ...
def func1(__x: A[int, _X] | A[str, _X] | A[str | int, _X]) -> A[int, _X]: ...
v3 = func1(A.method1("a", "b"))
reveal_type(v3, expected_text="A[int, str]")
v4 = str.maketrans(dict.fromkeys("a", "b"))
rev... | A |
python | joke2k__faker | faker/providers/automotive/en_CA/__init__.py | {
"start": 48,
"end": 919
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``en_CA`` locale.
Sources:
- https://www.revolvy.com/main/index.php?s=Canadian%20licence%20plate%20designs%20and%20serial%20formats
"""
license_formats = (
# Alberta
"???-####",
# BC
"??# ##?",
... | Provider |
python | openai__openai-python | src/openai/resources/fine_tuning/jobs/jobs.py | {
"start": 36093,
"end": 37033
} | class ____:
def __init__(self, jobs: AsyncJobs) -> None:
self._jobs = jobs
self.create = async_to_streamed_response_wrapper(
jobs.create,
)
self.retrieve = async_to_streamed_response_wrapper(
jobs.retrieve,
)
self.list = async_to_streamed_resp... | AsyncJobsWithStreamingResponse |
python | cython__cython | Cython/Plex/Regexps.py | {
"start": 6789,
"end": 7411
} | class ____(RE):
"""
SpecialSymbol(sym) is an RE which matches the special input
symbol |sym|, which is one of BOL, EOL or EOF.
"""
nullable = 0
match_nl = 0
sym = None
def __init__(self, sym):
self.sym = sym
def build_machine(self, m, initial_state, final_state, match_bol, ... | SpecialSymbol |
python | walkccc__LeetCode | solutions/2241. Design an ATM Machine/2241.py | {
"start": 0,
"end": 555
} | class ____:
def __init__(self):
self.banknotes = [20, 50, 100, 200, 500]
self.bank = [0] * 5
def deposit(self, banknotesCount: list[int]) -> None:
for i in range(5):
self.bank[i] += banknotesCount[i]
def withdraw(self, amount: int) -> list[int]:
withdrew = [0] * 5
for i in reversed(ra... | ATM |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_types.py | {
"start": 1049,
"end": 5031
} | class ____:
async def test_create_block_type(self, client):
response = await client.post(
"/block_types/",
json=BlockTypeCreate(
name="x",
slug="x",
logo_url="http://example.com/logo.png",
documentation_url="http://examp... | TestCreateBlockType |
python | scipy__scipy | scipy/stats/tests/test_odds_ratio.py | {
"start": 250,
"end": 6727
} | class ____:
@pytest.mark.parametrize('parameters, rresult', data)
def test_results_from_r(self, parameters, rresult):
alternative = parameters.alternative.replace('.', '-')
result = odds_ratio(parameters.table)
# The results computed by R are not very accurate.
if result.statist... | TestOddsRatio |
python | apache__airflow | providers/ydb/tests/unit/ydb/hooks/test_ydb.py | {
"start": 1268,
"end": 1332
} | class ____:
def wait(*args, **kwargs):
pass
| FakeDriver |
python | numba__llvmlite | llvmlite/binding/ffi.py | {
"start": 4029,
"end": 6664
} | class ____(object):
"""Wrap libllvmlite with a lock such that only one thread may access it at
a time.
This class duck-types a CDLL.
"""
__slots__ = ['_lib_handle', '_fntab', '_lock']
def __init__(self):
self._lib_handle = None
self._fntab = {}
self._lock = _LLVMLock()
... | _lib_wrapper |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/partialmethod.py | {
"start": 38,
"end": 421
} | class ____:
"""An example for partialmethod.
refs: https://docs.python.org/3/library/functools.html#functools.partialmethod
"""
def set_state(self, state):
"""Update state of cell to *state*."""
#: Make a cell alive.
set_alive = partialmethod(set_state, True)
# a partialmethod wi... | Cell |
python | tensorflow__tensorflow | tensorflow/compiler/tests/searchsorted_op_test.py | {
"start": 901,
"end": 2836
} | class ____(xla_test.XLATestCase):
def test1D(self):
# Test against NumPy implementation (which is 1D only).
np.random.seed(1)
for side in ['left', 'right']:
for dtype in [np.float32, np.int32]:
values = np.random.uniform(
low=-1000, high=1000, size=(10,)).astype(dtype)
u... | SearchSorteddOpTest |
python | kamyu104__LeetCode-Solutions | Python/create-target-array-in-the-given-order.py | {
"start": 536,
"end": 842
} | class ____(object):
def createTargetArray(self, nums, index):
"""
:type nums: List[int]
:type index: List[int]
:rtype: List[int]
"""
result = []
for i, x in itertools.izip(index, nums):
result.insert(i, x)
return result
| Solution2 |
python | TheAlgorithms__Python | graphs/minimum_spanning_tree_kruskal2.py | {
"start": 1395,
"end": 4059
} | class ____[T]:
def __init__(self) -> None:
# connections: map from the node to the neighbouring nodes (with weights)
self.connections: dict[T, dict[T, int]] = {}
def add_node(self, node: T) -> None:
# add a node ONLY if its not present in the graph
if node not in self.connection... | GraphUndirectedWeighted |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/never2.py | {
"start": 366,
"end": 522
} | class ____(Generic[T]):
pass
def func2(x: U) -> ClassB[U]:
# This should generate an error because T is invariant.
return ClassB[Never]()
| ClassB |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_measurements_meta.py | {
"start": 249,
"end": 5190
} | class ____(MetricsEnhancedPerformanceTestCase):
endpoint = "sentry-api-0-organization-measurements-meta"
METRIC_STRINGS = [
"d:transactions/measurements.something_custom@millisecond",
]
features = {"organizations:discover-basic": True}
def setUp(self) -> None:
super().setUp()
... | OrganizationMeasurementsMetaEndpoint |
python | readthedocs__readthedocs.org | readthedocs/search/api/v2/views.py | {
"start": 6942,
"end": 7008
} | class ____(PageSearchAPIView):
pass
| BaseProxiedPageSearchAPIView |
python | pytorch__pytorch | torch/_inductor/standalone_compile.py | {
"start": 9864,
"end": 16664
} | class ____(CompiledArtifact):
"""
Similar to CompiledArtifact, but the object is a single, bundled precompiled function.
This object is always a serializable callable function.
This object is essentially a wrapper for BundledAOTAutogradSerializableCallable, which
is used by torch._dynamo.aot_compil... | AOTCompiledArtifact |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 59109,
"end": 59313
} | class ____(themeable):
"""
Layout items in the legend
Parameters
----------
theme_element : Literal["vertical", "horizontal"]
Vertically or horizontally
"""
| legend_direction |
python | kamyu104__LeetCode-Solutions | Python/squares-of-a-sorted-array.py | {
"start": 45,
"end": 576
} | class ____(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
right = bisect.bisect_left(A, 0)
left = right-1
result = []
while 0 <= left or right < len(A):
if right == len(A) or \
(0 <= left an... | Solution |
python | scikit-learn__scikit-learn | sklearn/utils/_testing.py | {
"start": 39220,
"end": 40953
} | class ____(contextlib.AbstractContextManager):
# see raises() for parameters
def __init__(self, expected_exc_type, match, may_pass, err_msg):
self.expected_exc_types = (
expected_exc_type
if isinstance(expected_exc_type, Iterable)
else [expected_exc_type]
)
... | _Raises |
python | getsentry__sentry | src/sentry/plugins/base/binding_manager.py | {
"start": 805,
"end": 1241
} | class ____:
BINDINGS = {
"repository.provider": RepositoryProviderManager,
"integration-repository.provider": IntegrationRepositoryProviderManager,
}
def __init__(self):
self._bindings = {k: v() for k, v in self.BINDINGS.items()}
def add(self, name, binding, **kwargs):
... | BindingManager |
python | scipy__scipy | benchmarks/benchmarks/test_functions.py | {
"start": 5494,
"end": 6299
} | class ____:
# note: this function is not smooth at the origin. the gradient will never
# converge in the minimizer
target_E = 0.
solution = [0., 0.]
xmin = np.array([-5, -5])
xmax = np.array([5, 5])
def fun(self, x):
E = (-20. * exp(-0.2 * sqrt(0.5 * (x[0]**2 + x[1]**2))) + 20. + n... | Ackley |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_transforms.py | {
"start": 563,
"end": 17873
} | class ____:
single_point = [1.0, 1.0]
multiple_points = [[0.0, 2.0], [3.0, 3.0], [4.0, 0.0]]
pivot = single_point
def test_init(self):
Affine2D([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], int))
Affine2D(np.array([[1, 2, 3], [4, 5, 6], ... | TestAffine2D |
python | ray-project__ray | rllib/models/torch/fcnet.py | {
"start": 482,
"end": 5903
} | class ____(TorchModelV2, nn.Module):
"""Generic fully connected network."""
def __init__(
self,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
num_outputs: int,
model_config: ModelConfigDict,
name: str,
):
TorchModelV2.__init__(
... | FullyConnectedNetwork |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/attrs/test_pretty.py | {
"start": 1897,
"end": 2243
} | class ____:
x: int
y: int = attrs.field(init=False)
def test_does_not_include_no_init_fields_in_attrs_printing():
record = AttrsClassWithNoInitField(x=1)
assert pretty.pretty(record) == "AttrsClassWithNoInitField(x=1)"
record.y = 1
assert pretty.pretty(record) == "AttrsClassWithNoInitField(x=1... | AttrsClassWithNoInitField |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/source_recharge/streams.py | {
"start": 592,
"end": 668
} | class ____(Enum):
DEPRECATED = "2021-01"
MODERN = "2021-11"
| ApiVersion |
python | pytorch__pytorch | torch/testing/_internal/optests/generate_tests.py | {
"start": 29458,
"end": 31762
} | class ____:
def __init__(self, path: str, data: FailuresDictData):
self.path = path
self.data = data
@staticmethod
def load(path, *, create_file=False) -> "FailuresDict":
if create_file and not os.path.exists(path):
result = FailuresDict(path, {})
FailuresDic... | FailuresDict |
python | scikit-learn__scikit-learn | sklearn/ensemble/tests/test_bagging.py | {
"start": 24067,
"end": 24387
} | class ____(BaseEstimator):
"""Fake estimator accepting sample_weight"""
def fit(self, X, y, sample_weight=None):
"""Record values passed during fit"""
self.X_ = X
self.y_ = y
self.sample_weight_ = sample_weight
def predict(self, X):
pass
| EstimatorAcceptingSampleWeight |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_optim_state.py | {
"start": 3921,
"end": 9959
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.block0 = BlockB(5, 3)
self.block1 = BlockB(3, 7)
self.bias = torch.nn.Parameter(torch.randn((5,)))
self.block2 = torch.nn.Sequential(
BlockA(7, 9),
BlockA(9, 9),
... | NestedModel |
python | Farama-Foundation__Gymnasium | tests/test_core.py | {
"start": 4106,
"end": 4338
} | class ____(ObservationWrapper):
"""Example observation wrapper for testing."""
def observation(self, observation: ObsType) -> ObsType:
"""Observation function."""
return np.array([1])
| ExampleObservationWrapper |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 3572,
"end": 5554
} | class ____(QueryTest):
run_create_tables = None
run_inserts = None
def test_with_session(self):
User = self.classes.User
s1 = fixture_session()
s2 = fixture_session()
q1 = s1.query(User)
q2 = q1.with_session(s2)
assert q2.session is s2
assert q1.sessi... | MiscTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self2.py | {
"start": 993,
"end": 1165
} | class ____(Shape1): ...
x1 = Shape1().set_scale(3.4)
reveal_type(x1, expected_text="Shape1")
x2 = Circle1().set_scale(3.4)
reveal_type(x2, expected_text="Circle1")
| Circle1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.