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 | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 10352,
"end": 14843
} | class ____(nn.Module):
"""
This module converts the hidden states reshaped as an image to patch embeddings ready to be passed to the
Transformer block.
"""
def __init__(self, config: ClapAudioConfig):
super().__init__()
img_size = (config.spec_size, config.spec_size) if isinstance(c... | ClapAudioPatchEmbed |
python | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 6769,
"end": 7687
} | class ____(Benchmark):
params = [
['float64', 'int64', 'float32', 'int32', 'int16', 'float16'],
[
('random',),
('ordered',),
('reversed',),
('uniform',),
('sorted_block', 10),
('sorted_block', 100),
('sorted_block', ... | Partition |
python | ansible__ansible | test/integration/targets/connection_delegation/action_plugins/delegation_action.py | {
"start": 84,
"end": 268
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
return {
'remote_password': self._connection.get_option('remote_password'),
}
| ActionModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 826428,
"end": 827166
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for User."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("OrganizationMemberEdge"), graphql_name="edges")
"""A list of edges."""
nodes ... | OrganizationMemberConnection |
python | huggingface__transformers | examples/modular-transformers/modeling_my_new_model2.py | {
"start": 11485,
"end": 11600
} | class ____(GenericForSequenceClassification, MyNewModel2PreTrainedModel):
pass
| MyNewModel2ForSequenceClassification |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/mro3.py | {
"start": 357,
"end": 419
} | class ____(QualifiedObject, SubclassableObject):
pass
| Source |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 96610,
"end": 99890
} | class ____(TypedDict, total=False):
"""
:class:`altair.FormatConfig` ``TypedDict`` wrapper.
Parameters
----------
normalizedNumberFormat
If normalizedNumberFormatType is not specified, D3 number format for axis labels,
text marks, and tooltips of normalized stacked fields (fields wi... | FormatConfigKwds |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 8445,
"end": 10097
} | class ____(
mixins.NodeDetailMixin,
mixins.NodeExecuteMixin,
mixins.NodeUndoMixin,
mixins.NodeReviveMixin,
nodes.Split,
):
"""
Represents a parallel split gateway in a workflow, allowing branching into multiple parallel paths.
Methods:
- `Next(node, case=None, data_source=None)`... | Split |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/module_path_separator/package.py | {
"start": 217,
"end": 887
} | class ____(Package):
homepage = "http://www.spack.llnl.gov"
url = "http://www.spack.llnl.gov/module-path-separator-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
def setup_run_environment(self, env: EnvironmentModifications) -> None:
env.append_path("COLON", "foo")
... | ModulePathSeparator |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 19930,
"end": 20130
} | class ____(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
history = HistoricalRecords(history_id_field=models.UUIDField(default=uuid.uuid4))
| UUIDModel |
python | python-pillow__Pillow | src/PIL/ImageTransform.py | {
"start": 370,
"end": 1058
} | class ____(Image.ImageTransformHandler):
"""Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
method: Image.Transform
def __init__(self, data: Sequence[Any]) -> None:
self.data = data
def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
return self.me... | Transform |
python | ray-project__ray | python/ray/data/_internal/logical/operators/all_to_all_operator.py | {
"start": 2819,
"end": 4217
} | class ____(AbstractAllToAll, LogicalOperatorSupportsPredicatePassThrough):
"""Logical operator for random_shuffle."""
def __init__(
self,
input_op: LogicalOperator,
name: str = "RandomShuffle",
seed: Optional[int] = None,
ray_remote_args: Optional[Dict[str, Any]] = None,... | RandomShuffle |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/__init__.py | {
"start": 3510,
"end": 3622
} | class ____(str): # NoQA: FURB189,SLOT000
"""docstring"""
def __repr__(self):
return self
| StrRepr |
python | huggingface__transformers | src/transformers/models/glm/modeling_glm.py | {
"start": 13651,
"end": 15421
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: GlmConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GlmAttention(config=config, layer_idx=layer_idx)
self.mlp = GlmMLP(config)
self.input_layernorm = GlmRMSN... | GlmDecoderLayer |
python | walkccc__LeetCode | solutions/2702. Minimum Operations to Make Numbers Non-positive/2702.py | {
"start": 0,
"end": 542
} | class ____:
def minOperations(self, nums: list[int], x: int, y: int) -> int:
def isPossible(m: int) -> bool:
"""
Returns True if it's possible to make all `nums` <= 0 using m operations.
"""
# If we want m operations, first decrease all the numbers by y * m. Then
# we have m operatio... | Solution |
python | scipy__scipy | scipy/integrate/tests/test_cubature.py | {
"start": 32601,
"end": 34716
} | class ____:
"""
Tests underlying quadrature rules (ndim == 1).
"""
@pytest.mark.parametrize(("rule", "rule_args"), [
(GaussLegendreQuadrature, (3,)),
(GaussLegendreQuadrature, (5,)),
(GaussLegendreQuadrature, (10,)),
(GaussKronrodQuadrature, (15,)),
(GaussKronrod... | TestRulesQuadrature |
python | python-openxml__python-docx | src/docx/opc/phys_pkg.py | {
"start": 3375,
"end": 4005
} | class ____(PhysPkgWriter):
"""Implements |PhysPkgWriter| interface for a zip file OPC package."""
def __init__(self, pkg_file):
super(_ZipPkgWriter, self).__init__()
self._zipf = ZipFile(pkg_file, "w", compression=ZIP_DEFLATED)
def close(self):
"""Close the zip archive, flushing an... | _ZipPkgWriter |
python | tensorflow__tensorflow | third_party/xla/xla/python_api/xla_literal_test.py | {
"start": 2619,
"end": 9341
} | class ____(absltest.TestCase):
def assertShape(self, shape, expected_dimensions, expected_element_type):
self.assertEqual(shape.element_type, expected_element_type)
self.assertEqual(shape.dimensions, expected_dimensions)
def assertLayout(self, layout, expected_minor_to_major):
self.assertEqual(layout.... | XlaLiteralTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/source.py | {
"start": 4690,
"end": 8517
} | class ____(AbstractSource):
@property
def continue_sync_on_stream_failure(self) -> bool:
return True
@staticmethod
def get_shop_name(config) -> str:
split_pattern = ".myshopify.com"
shop_name = config.get("shop")
return shop_name.split(split_pattern)[0] if split_pattern ... | SourceShopify |
python | kamyu104__LeetCode-Solutions | Python/best-team-with-no-conflicts.py | {
"start": 3185,
"end": 3884
} | class ____(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
players = sorted(zip(ages, scores))
sorted_scores = sorted(set(scores))
lookup = {score:i for i, score in enumerate(sorted_scor... | Solution2 |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 95654,
"end": 98664
} | class ____(Operation):
def __init__(
self, kernel_size, dilation=1, padding=0, stride=1, *, name=None
):
super().__init__(name=name)
self.kernel_size = kernel_size
self.dilation = dilation
self.padding = padding
self.stride = stride
def compute_output_spec(se... | Unfold |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 11152,
"end": 11901
} | class ____:
@make_xp_test_case(is_isomorphic)
@pytest.mark.parametrize("criterion,t",
[("inconsistent", t) for t in hierarchy_test_data.fcluster_inconsistent]
+ [("distance", t) for t in hierarchy_test_data.fcluster_distance]
+ [("maxclust", t) for t in hierarchy_test_data.fcluster_maxc... | TestFclusterData |
python | ApeWorX__ape | src/ape/cli/choices.py | {
"start": 10796,
"end": 13273
} | class ____(click.Choice):
"""
A ``click.Choice`` to provide network choice defaults for the active project.
Optionally provide a list of ecosystem names, network names, or provider names
to filter the results by.
This is used in :meth:`~ape.cli.options.network_option`.
"""
CUSTOM_NETWORK_... | NetworkChoice |
python | chroma-core__chroma | chromadb/logservice/logservice.py | {
"start": 859,
"end": 5870
} | class ____(Producer, Consumer):
"""
Distributed Chroma Log Service
"""
_log_service_stub: LogServiceStub
_request_timeout_seconds: int
_channel: grpc.Channel
_log_service_url: str
_log_service_port: int
def __init__(self, system: System):
self._log_service_url = system.sett... | LogService |
python | mwaskom__seaborn | tests/test_base.py | {
"start": 19667,
"end": 49072
} | class ____:
def test_flat_variables(self, flat_data):
p = VectorPlotter()
p.assign_variables(data=flat_data)
assert p.input_format == "wide"
assert list(p.variables) == ["x", "y"]
assert len(p.plot_data) == len(flat_data)
try:
expected_x = flat_data.ind... | TestVectorPlotter |
python | pytorch__pytorch | torch/_export/db/examples/cond_predicate.py | {
"start": 95,
"end": 663
} | class ____(torch.nn.Module):
"""
The conditional statement (aka predicate) passed to cond() must be one of the following:
- torch.Tensor with a single element
- boolean expression
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
"""
def forward(self, x)... | CondPredicate |
python | celery__celery | celery/worker/consumer/events.py | {
"start": 226,
"end": 2054
} | class ____(bootsteps.StartStopStep):
"""Service used for sending monitoring events."""
requires = (Connection,)
def __init__(self, c,
task_events=True,
without_heartbeat=False,
without_gossip=False,
**kwargs):
self.groups = None i... | Events |
python | Pylons__pyramid | tests/test_router.py | {
"start": 61341,
"end": 61481
} | class ____:
def __init__(self, root):
self.root = root
def __call__(self, environ):
return self.root
| DummyRootFactory |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 46902,
"end": 47879
} | class ____:
"""
Test beta and betaln.
"""
def test_beta(self):
assert_equal(special.beta(1, 1), 1.0)
assert_allclose(special.beta(-100.3, 1e-200), special.gamma(1e-200))
assert_allclose(special.beta(0.0342, 171), 24.070498359873497,
rtol=1e-13, atol=0)
... | TestBeta |
python | pytorch__pytorch | torch/autograd/graph.py | {
"start": 25039,
"end": 27216
} | class ____(TorchDispatchMode):
def __init__(self, ctx: "_AllowMutationOnSavedContext") -> None:
self.ctx = ctx
def __torch_dispatch__(
self,
func: "OpOverload",
types: Iterable[type],
args: tuple[Any, ...] = (),
kwargs: Optional[dict[Any, Any]] = None,
) -> A... | _CloneArgBeforeMutateMode |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 261628,
"end": 264649
} | class ____(Response):
"""
Response of tasks.publish endpoint.
:param committed_versions_results: Committed versions results
:type committed_versions_results: Sequence[dict]
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
... | PublishResponse |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/bedrock/_beta_messages.py | {
"start": 2510,
"end": 2749
} | class ____:
def __init__(self, messages: AsyncMessages) -> None:
self._messages = messages
self.create = _legacy_response.async_to_raw_response_wrapper(
messages.create,
)
| AsyncMessagesWithRawResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 10467,
"end": 11335
} | class ____(Projects, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-projects/#api-rest-api-3-project-post
"""
def path(self, **kwargs) -> str:
return "project"
def generate(self):
for index in range(1, 51):
payload = json.dump... | ProjectsGenerator |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 3647,
"end": 3861
} | class ____(GQLResult):
typename__: Typename[Literal["ArtifactType"]] = "ArtifactType"
id: GQLId
name: str
description: Optional[str]
created_at: str = Field(alias="createdAt")
| ArtifactTypeFragment |
python | pytorch__pytorch | test/dynamo/test_ctx_manager.py | {
"start": 49687,
"end": 66162
} | class ____(torch.nn.Module):
def forward(self, L_y_: "f32[]"):
l_y_ = L_y_
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable('This is not supported'); _saved_tensors_hooks_disable = None
mul: "f32[]" = l_y_ * 2; l_y_ = None
_saved_tensors_hooks_enabl... | GraphModule |
python | pytorch__pytorch | torch/distributed/fsdp/_common_utils.py | {
"start": 3548,
"end": 3778
} | class ____(_FSDPDeviceHandle):
def __init__(self) -> None:
pass
def __getattribute__(self, name: str, /) -> Any:
raise RuntimeError("Trying to use an uninitialized device handle.")
| _UninitializedDeviceHandle |
python | pandas-dev__pandas | pandas/tests/indexes/test_indexing.py | {
"start": 2464,
"end": 5353
} | class ____:
@pytest.mark.parametrize(
"index,val",
[
([0, 1, 2], 2),
([0, 1, "2"], "2"),
([0, 1, 2, np.inf, 4], 4),
([0, 1, 2, np.nan, 4], 4),
([0, 1, 2, np.inf], np.inf),
([0, 1, 2, np.nan], np.nan),
],
)
def te... | TestContains |
python | mlflow__mlflow | examples/demos/mlflow-3/deep_learning.py | {
"start": 1006,
"end": 4573
} | class ____(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = self.fc1(x)
x = self.r... | IrisClassifier |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance16.py | {
"start": 99,
"end": 636
} | class ____:
@classmethod
def bar(cls, other: type):
if issubclass(other, cls):
reveal_type(other, expected_text="type[Self@ClassA]")
if issubclass(other, (int, cls)):
reveal_type(other, expected_text="type[Self@ClassA] | type[int]")
def baz(self, other: object):
... | ClassA |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/http_request_stage.py | {
"start": 6691,
"end": 7103
} | class ____(StatefulStage):
"""
A stage that sends HTTP requests.
"""
fn: Type[StatefulStageUDF] = HttpRequestUDF
def get_required_input_keys(self) -> Dict[str, str]:
"""The required input keys of the stage and their descriptions."""
return {
"payload": "The payload to s... | HttpRequestStage |
python | OmkarPathak__pygorithm | tests/test_data_structure.py | {
"start": 2502,
"end": 3357
} | class ____(unittest.TestCase):
def test_queue(self):
myQueue = queue.Queue() # create a queue with default queue size 10
myQueue.enqueue(2)
myQueue.enqueue(10)
myQueue.enqueue(12)
myQueue.enqueue(3)
self.assertEqual(myQueue.dequeue(), 2)
self.assertEqual(myQ... | TestQueue |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vision.py | {
"start": 14203,
"end": 15105
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook")
def test_minimal_green_path(self, mock_hook):
op = CloudVisionRemoveProductFromProductSetOperator(
location=LOCATION_TEST,
product_set_id=PRODUCTSET_ID_TEST,
product_id=PRODUCT_... | TestCloudVisionRemoveProductFromProductSetOperator |
python | pola-rs__polars | py-polars/src/polars/_typing.py | {
"start": 9588,
"end": 9857
} | class ____(TypedDict):
"""Underlying buffers of a Series."""
values: Series
validity: Series | None
offsets: Series | None
# minimal protocol definitions that can reasonably represent
# an executable connection, cursor, or equivalent object
| SeriesBuffers |
python | doocs__leetcode | solution/3400-3499/3408.Design Task Manager/Solution.py | {
"start": 0,
"end": 1120
} | class ____:
def __init__(self, tasks: List[List[int]]):
self.d = {}
self.st = SortedList()
for task in tasks:
self.add(*task)
def add(self, userId: int, taskId: int, priority: int) -> None:
self.d[taskId] = (userId, priority)
self.st.add((-priority, -taskId))... | TaskManager |
python | dask__distributed | distributed/worker.py | {
"start": 4672,
"end": 4887
} | class ____(ErrorMessage):
op: Literal["task-erred"]
result: object
nbytes: int
type: type
start: float
stop: float
thread: int
actual_exception: BaseException | Exception
| RunTaskFailure |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_analytics_admin.py | {
"start": 7884,
"end": 8843
} | class ____:
@mock.patch(f"{ANALYTICS_PATH}.GoogleAnalyticsAdminHook")
def test_execute(self, hook_mock):
mock_retry, mock_timeout, mock_metadata = (mock.MagicMock() for _ in range(3))
GoogleAnalyticsAdminDeleteDataStreamOperator(
task_id="test_task",
gcp_conn_id=GCP_CONN... | TestGoogleAnalyticsAdminDeleteDataStreamOperator |
python | plotly__plotly.py | plotly/graph_objs/_streamtube.py | {
"start": 215,
"end": 79407
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "streamtube"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"coloraxis",
"colorbar",
"colorscale",
"customdata",
"customdatasrc",
"hoveri... | Streamtube |
python | plotly__plotly.py | plotly/graph_objs/choroplethmapbox/_hoverlabel.py | {
"start": 233,
"end": 11304
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmapbox"
_path_str = "choroplethmapbox.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"... | Hoverlabel |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 2459,
"end": 4140
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
paper](https://huggingface.co/papers/2006.11477).
logits (`t... | UniSpeechSatForPreTrainingOutput |
python | huggingface__transformers | src/transformers/models/bark/modeling_bark.py | {
"start": 37294,
"end": 57216
} | class ____(BarkPreTrainedModel):
base_model_prefix = "fine_acoustics"
config: BarkFineConfig
main_input_name = "codebook_idx"
def __init__(self, config):
# non-causal gpt-like model with one embedding layer and one lm_head for each codebook of Encodec
super().__init__(config)
se... | BarkFineModel |
python | run-llama__llama_index | llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-tablestore/llama_index/storage/chat_store/tablestore/base.py | {
"start": 690,
"end": 9095
} | class ____(BaseChatStore):
"""
Tablestore Chat Store.
Args:
tablestore_client (OTSClient, optional): External tablestore(ots) client.
If this parameter is set, the following endpoint/instance_name/access_key_id/access_key_secret will be ignored.
endpoint (str, optional): Tab... | TablestoreChatStore |
python | aio-libs__aiohttp | aiohttp/abc.py | {
"start": 682,
"end": 1327
} | class ____(ABC):
def __init__(self) -> None:
self._frozen = False
def post_init(self, app: Application) -> None:
"""Post init stage.
Not an abstract method for sake of backward compatibility,
but if the router wants to be aware of the application
it can override this.
... | AbstractRouter |
python | sympy__sympy | sympy/polys/orderings.py | {
"start": 4157,
"end": 8051
} | class ____(MonomialOrder):
"""
The "inverse" of another monomial order.
If O is any monomial order, we can construct another monomial order iO
such that `A >_{iO} B` if and only if `B >_O A`. This is useful for
constructing local orders.
Note that many algorithms only work with *global* orders... | InverseOrder |
python | django__django | django/contrib/admin/utils.py | {
"start": 6214,
"end": 17193
} | class ____(Collector):
def __init__(self, *args, force_collection=True, **kwargs):
super().__init__(*args, force_collection=force_collection, **kwargs)
self.edges = {} # {from_instance: [to_instances]}
self.protected = set()
self.model_objs = defaultdict(set)
def add_edge(self,... | NestedObjects |
python | pallets__click | src/click/_winconsole.py | {
"start": 3671,
"end": 4695
} | class ____(_WindowsConsoleRawIOBase):
def readable(self) -> t.Literal[True]:
return True
def readinto(self, b: Buffer) -> int:
bytes_to_be_read = len(b)
if not bytes_to_be_read:
return 0
elif bytes_to_be_read % 2:
raise ValueError(
"cannot... | _WindowsConsoleReader |
python | crytic__slither | slither/printers/summary/cheatcodes.py | {
"start": 241,
"end": 2593
} | class ____(AbstractPrinter):
ARGUMENT = "cheatcode"
HELP = """
Print the usage of (Foundry) cheatcodes in the code.
For the complete list of Cheatcodes, see https://book.getfoundry.sh/cheatcodes/
"""
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#cheatcode"
... | CheatcodePrinter |
python | fluentpython__example-code-2e | 24-class-metaprog/qualname/models.py | {
"start": 56,
"end": 262
} | class ____(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ['horn_length']
verbose_name_plural = 'oxen'
print(Ox.Meta.__name__)
print(Ox.Meta.__qualname__)
| Ox |
python | kamyu104__LeetCode-Solutions | Python/maximum-width-of-binary-tree.py | {
"start": 29,
"end": 582
} | class ____(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, i, depth, leftmosts):
if not node:
return 0
if depth >= len(leftmosts):
leftmosts.append(i)
return... | Solution |
python | cython__cython | Cython/Debugger/Tests/test_libcython_in_gdb.py | {
"start": 1143,
"end": 2789
} | class ____(unittest.TestCase, metaclass=TraceMethodCallMeta):
"""
Base class for test cases. On teardown it kills the inferior and unsets
all breakpoints.
"""
def __init__(self, name):
super().__init__(name)
self.cy = libcython.cy
self.module = libcython.cy.cython_namespace[... | DebugTestCase |
python | python-excel__xlrd | xlrd/formatting.py | {
"start": 43593,
"end": 45573
} | class ____(BaseObject):
"""
eXtended Formatting information for cells, rows, columns and styles.
Each of the 6 flags below describes the validity of
a specific group of attributes.
In cell XFs:
- ``flag==0`` means the attributes of the parent style ``XF`` are
used, (but only if the attr... | XF |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1597421,
"end": 1597593
} | class ____(sgqlc.types.Union):
"""Types that can be assigned to reactions."""
__schema__ = github_schema
__types__ = (Bot, Mannequin, Organization, User)
| Reactor |
python | celery__celery | t/unit/backends/test_cache.py | {
"start": 6621,
"end": 8245
} | class ____(MockCacheMixin):
def test_pylibmc(self):
with self.mock_pylibmc():
with conftest.reset_modules('celery.backends.cache'):
from celery.backends import cache
cache._imp = [None]
assert cache.get_best_memcache()[0].__module__ == 'pylibmc'
... | test_get_best_memcache |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 1883,
"end": 2794
} | class ____(unittest.TestCase):
def test(self):
b_plain_data = b'some text to hexlify'
b_data = hexlify(b_plain_data)
res = vault._unhexlify(b_data)
self.assertEqual(res, b_plain_data)
def test_odd_length(self):
b_data = b'123456789abcdefghijklmnopqrstuvwxyz'
sel... | TestUnhexlify |
python | protocolbuffers__protobuf | python/google/protobuf/json_format.py | {
"start": 16285,
"end": 37303
} | class ____(object):
"""JSON format parser for protocol message."""
def __init__(
self, ignore_unknown_fields, descriptor_pool, max_recursion_depth
):
self.ignore_unknown_fields = ignore_unknown_fields
self.descriptor_pool = descriptor_pool
self.max_recursion_depth = max_recursion_depth
self... | _Parser |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 174002,
"end": 177308
} | class ____(Request):
"""
Adds a task into a queue.
Fails if task state is not 'created'.
Fails if the following parameters in the task were not filled:
* execution.script.repository
* execution.script.entrypoint
:param queue: Queue id. If not provided, task is added to the default queu... | EnqueueRequest |
python | redis__redis-py | redis/asyncio/cluster.py | {
"start": 54353,
"end": 67252
} | class ____:
__slots__ = (
"_dynamic_startup_nodes",
"_moved_exception",
"_event_dispatcher",
"connection_kwargs",
"default_node",
"nodes_cache",
"read_load_balancer",
"require_full_coverage",
"slots_cache",
"startup_nodes",
"add... | NodesManager |
python | doocs__leetcode | solution/2700-2799/2768.Number of Black Blocks/Solution.py | {
"start": 0,
"end": 509
} | class ____:
def countBlackBlocks(
self, m: int, n: int, coordinates: List[List[int]]
) -> List[int]:
cnt = Counter()
for x, y in coordinates:
for a, b in pairwise((0, 0, -1, -1, 0)):
i, j = x + a, y + b
if 0 <= i < m - 1 and 0 <= j < n - 1:
... | Solution |
python | huggingface__transformers | src/transformers/models/instructblip/modeling_instructblip.py | {
"start": 27398,
"end": 28542
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList(
[InstructBlipQFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.gradient_checkpointing = False
@can_re... | InstructBlipQFormerEncoder |
python | apache__thrift | test/py/SerializationTest.py | {
"start": 13336,
"end": 13470
} | class ____(AbstractTest):
protocol_factory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False)
| AcceleratedBinaryTest |
python | sqlalchemy__sqlalchemy | test/orm/test_events.py | {
"start": 35379,
"end": 57272
} | class ____(RemoveORMEventsGlobally, _fixtures.FixtureTest):
run_inserts = None
@classmethod
def define_tables(cls, metadata):
super().define_tables(metadata)
metadata.tables["users"].append_column(
Column("extra", Integer, default=5, onupdate=10)
)
def test_instance... | MapperEventsTest |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_param_kind.py | {
"start": 383,
"end": 4438
} | 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... | V1beta1ParamKind |
python | django__django | django/middleware/common.py | {
"start": 373,
"end": 5101
} | class ____(MiddlewareMixin):
"""
"Common" middleware for taking care of some basic operations:
- Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS
- URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
append missing slashes and/or prepends missing "www."s... | CommonMiddleware |
python | walkccc__LeetCode | solutions/1419. Minimum Number of Frogs Croaking/1419.py | {
"start": 0,
"end": 421
} | class ____:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
CROAK = 'croak'
ans = 0
frogs = 0
count = [0] * 5
for c in croakOfFrogs:
count[CROAK.index(c)] += 1
if any(count[i] > count[i - 1] for i in range(1, 5)):
return -1
if c == 'c':
frogs += 1
eli... | Solution |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 27702,
"end": 30159
} | class ____(unittest.TestCase):
def _callFUT(self, resource, *elements):
from pyramid.traversal import resource_path
return resource_path(resource, *elements)
def test_it(self):
baz = DummyContext()
bar = DummyContext(baz)
foo = DummyContext(bar)
root = DummyCont... | ResourcePathTests |
python | pypa__pip | src/pip/_vendor/resolvelib/reporters.py | {
"start": 212,
"end": 2037
} | class ____(Generic[RT, CT, KT]):
"""Delegate class to provide progress reporting for the resolver."""
def starting(self) -> None:
"""Called before the resolution actually starts."""
def starting_round(self, index: int) -> None:
"""Called before each round of resolution starts.
The... | BaseReporter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/plugin/plugin_base.py | {
"start": 22248,
"end": 23101
} | class ____(abc.ABC):
@abc.abstractmethod
def skip_test_exception(self, *arg, **kw):
raise NotImplementedError()
@abc.abstractmethod
def combinations(self, *args, **kw):
raise NotImplementedError()
@abc.abstractmethod
def param_ident(self, *args, **kw):
raise NotImplemen... | FixtureFunctions |
python | doocs__leetcode | solution/2000-2099/2081.Sum of k-Mirror Numbers/Solution.py | {
"start": 0,
"end": 708
} | class ____:
def kMirror(self, k: int, n: int) -> int:
def check(x: int, k: int) -> bool:
s = []
while x:
s.append(x % k)
x //= k
return s == s[::-1]
ans = 0
for l in count(1):
x = 10 ** ((l - 1) // 2)
... | Solution |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 12351,
"end": 12753
} | class ____(BaseSafeMigrationTest):
app = "bad_flow_delete_field_without_pending_app"
migrate_from = "0001"
migrate_to = "0002"
def test(self) -> None:
with pytest.raises(
UnsafeOperationException,
match="Field must be in the pending deletion state before full deletion",
... | DeletionFieldBadDeleteWithoutPendingTest |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_tk.py | {
"start": 25999,
"end": 40595
} | class ____(NavigationToolbar2, tk.Frame):
def __init__(self, canvas, window=None, *, pack_toolbar=True):
"""
Parameters
----------
canvas : `FigureCanvas`
The figure canvas on which to operate.
window : tk.Window
The tk.Window which owns this toolbar.
... | NavigationToolbar2Tk |
python | falconry__falcon | falcon/errors.py | {
"start": 6507,
"end": 8831
} | class ____(HTTPError):
"""400 Bad Request.
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
(See also: RFC 7231, Section 6.5.1)
All the... | HTTPBadRequest |
python | django__django | tests/gis_tests/test_spatialrefsys.py | {
"start": 2306,
"end": 6136
} | class ____(TestCase):
@cached_property
def SpatialRefSys(self):
return connection.ops.connection.ops.spatial_ref_sys()
def test_get_units(self):
epsg_4326 = next(f for f in test_srs if f["srid"] == 4326)
unit, unit_name = self.SpatialRefSys().get_units(epsg_4326["wkt"])
self... | SpatialRefSysTest |
python | eventlet__eventlet | tests/greenthread_test.py | {
"start": 277,
"end": 464
} | class ____:
def assert_dead(self, gt):
if hasattr(gt, 'wait'):
self.assertRaises(greenlet.GreenletExit, gt.wait)
assert gt.dead
assert not gt
| Asserts |
python | nedbat__coveragepy | coverage/bytecode.py | {
"start": 1464,
"end": 6666
} | class ____:
"""Utility to step through trails of instructions.
We have two reasons to need sequences of instructions from a code object:
First, in strict sequence to visit all the instructions in the object.
This is `walk(follow_jumps=False)`. Second, we want to follow jumps to
understand how exec... | InstructionWalker |
python | keras-team__keras | keras/src/backend/openvino/core.py | {
"start": 4481,
"end": 20481
} | class ____:
def __init__(self, x, data=None):
x_shape = x.get_partial_shape()
if x_shape.rank.is_dynamic:
x_keras_shape = None
else:
x_keras_shape = [
None if dim.is_dynamic else dim.get_length()
for dim in list(x_shape)
]
... | OpenVINOKerasTensor |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/whole_site/base.py | {
"start": 417,
"end": 5234
} | class ____(BaseReader):
"""
BFS Web Scraper for websites.
This class provides functionality to scrape entire websites using a breadth-first search algorithm.
It navigates web pages from a given base URL, following links that match a specified prefix.
Attributes:
prefix (str): URL prefix to... | WholeSiteReader |
python | scikit-image__scikit-image | benchmarks/benchmark_transform_warp.py | {
"start": 268,
"end": 2073
} | class ____:
params = (
[np.uint8, np.uint16, np.float32, np.float64],
[128, 1024, 4096],
[0, 1, 3],
# [np.float32, np.float64]
)
# param_names = ['dtype_in', 'N', 'order', 'dtype_tform']
param_names = ['dtype_in', 'N', 'order']
# def setup(self, dtype_in, N, order, d... | WarpSuite |
python | numpy__numpy | tools/swig/test/testTensor.py | {
"start": 13459,
"end": 13761
} | class ____(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
self.result = int(self.result)
######################################################################
| longTestCase |
python | cookiecutter__cookiecutter | tests/test_prompt.py | {
"start": 555,
"end": 2428
} | class ____:
"""Class to unite simple and complex tests for render_variable function."""
@pytest.mark.parametrize(
'raw_var, rendered_var',
[
(1, '1'),
(True, True),
('foo', 'foo'),
('{{cookiecutter.project}}', 'foobar'),
(None, None),
... | TestRenderVariable |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/cpython/common.py | {
"start": 1151,
"end": 2653
} | class ____(CPython, WindowsSupports, ABC):
@classmethod
def _executables(cls, interpreter):
# symlink of the python executables does not work reliably, copy always instead
# - https://bugs.python.org/issue42013
# - venv
host = cls.host_python(interpreter)
names = {"python... | CPythonWindows |
python | yaml__pyyaml | lib/yaml/constructor.py | {
"start": 28592,
"end": 28639
} | class ____(UnsafeConstructor):
pass
| Constructor |
python | keras-team__keras | keras/src/initializers/random_initializers.py | {
"start": 2880,
"end": 4855
} | class ____(RandomInitializer):
"""Initializer that generates a truncated normal distribution.
The values generated are similar to values from a
`RandomNormal` initializer, except that values more
than two standard deviations from the mean are
discarded and re-drawn.
Examples:
>>> # Standa... | TruncatedNormal |
python | pypa__pipenv | pipenv/vendor/click/core.py | {
"start": 31503,
"end": 44709
} | class ____:
"""The base command implements the minimal API contract of commands.
Most code will never use this as it does not implement a lot of useful
functionality but it can act as the direct subclass of alternative
parsing methods that do not depend on the Click parser.
For instance, this can b... | BaseCommand |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 23301,
"end": 23869
} | class ____:
def __init__(self, role_name: str, entities: List[milvus_types.UserEntity]):
self._role_name = role_name
users = []
for entity in entities:
if isinstance(entity, milvus_types.UserEntity):
users.append(entity.name)
self._users = tuple(users)
... | RoleItem |
python | django__django | tests/requests_tests/tests.py | {
"start": 753,
"end": 940
} | class ____(MemoryFileUploadHandler):
def handle_raw_input(
self, input_data, META, content_length, boundary, encoding=None
):
raise ValueError
| ErrorFileUploadHandler |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 12654,
"end": 13333
} | class ____(GoogleAdsHttpRequester):
"""
Custom HTTP requester for ClickView stream.
"""
schema_loader: InlineSchemaLoader = None
def get_request_body_json(
self,
*,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
next_... | ClickViewHttpRequester |
python | django__django | tests/queries/tests.py | {
"start": 123452,
"end": 125698
} | class ____(unittest.TestCase):
"""
Tests for the union of two querysets. Bug #12252.
"""
@classmethod
def setUpTestData(cls):
objectas = []
objectbs = []
objectcs = []
a_info = ["one", "two", "three"]
for name in a_info:
o = ObjectA(name=name)
... | UnionTests |
python | encode__django-rest-framework | rest_framework/response.py | {
"start": 388,
"end": 3543
} | class ____(SimpleTemplateResponse):
"""
An HttpResponse that allows its data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None):
"""
Alters ... | Response |
python | walkccc__LeetCode | solutions/71. Simplify Path/71.py | {
"start": 0,
"end": 286
} | class ____:
def simplifyPath(self, path: str) -> str:
stack = []
for str in path.split('/'):
if str in ('', '.'):
continue
if str == '..':
if stack:
stack.pop()
else:
stack.append(str)
return '/' + '/'.join(stack)
| Solution |
python | pydantic__pydantic | pydantic/json_schema.py | {
"start": 114939,
"end": 116494
} | class ____:
"""!!! abstract "Usage Documentation"
[`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
Add this as an annotation on a field to override the (base) JSON schema that would be generated for that field.
This provides a way to set a JSON schema for types th... | WithJsonSchema |
python | python-pillow__Pillow | Tests/test_color_lut.py | {
"start": 10622,
"end": 16319
} | class ____:
def test_wrong_args(self) -> None:
with pytest.raises(ValueError, match="should be either an integer"):
ImageFilter.Color3DLUT("small", [1]) # type: ignore[arg-type]
with pytest.raises(ValueError, match="should be either an integer"):
ImageFilter.Color3DLUT((11,... | TestColorLut3DFilter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.