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 | spyder-ide__spyder | spyder/api/plugin_registration/_confpage.py | {
"start": 558,
"end": 5918
} | class ____(PluginConfigPage):
def setup_page(self):
newcb = self.create_checkbox
self.plugins_checkboxes = {}
header_label = QLabel(
_("Disable a Spyder plugin (external or built-in) to prevent it "
"from loading until re-enabled here, to simplify the interface "
... | PluginsConfigPage |
python | jmcnamara__XlsxWriter | xlsxwriter/chart_line.py | {
"start": 323,
"end": 3860
} | class ____(chart.Chart):
"""
A class for writing the Excel XLSX Line charts.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self, options: O... | ChartLine |
python | apache__airflow | devel-common/src/tests_common/test_utils/fake_datetime.py | {
"start": 855,
"end": 1058
} | class ____(datetime):
"""A fake replacement for datetime that can be mocked for testing."""
def __new__(cls, *args, **kwargs):
return datetime.__new__(datetime, *args, **kwargs)
| FakeDatetime |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 37979,
"end": 38187
} | class ____(_CreateDropBase["Table"]):
"""Represent a COMMENT ON TABLE '' statement.
Note this varies a lot across database backends.
"""
__visit_name__ = "drop_table_comment"
| DropTableComment |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/attributes/duplicates.py | {
"start": 420,
"end": 620
} | class ____:
def __init__(self) -> None:
self.val: str | int = "1"
self.lav: list[str] = []
def bar(self) -> None:
self.val = "2"
self.lav = []
| DuplicateAnnotations |
python | apache__airflow | airflow-core/tests/unit/jobs/test_scheduler_job.py | {
"start": 7311,
"end": 323847
} | class ____:
@staticmethod
def clean_db():
clear_db_dags()
clear_db_runs()
clear_db_backfills()
clear_db_pools()
clear_db_import_errors()
clear_db_jobs()
clear_db_assets()
clear_db_deadline()
clear_db_callbacks()
clear_db_triggers()
... | TestSchedulerJob |
python | wandb__wandb | wandb/vendor/pygments/lexers/c_cpp.py | {
"start": 8245,
"end": 10523
} | class ____(CFamilyLexer):
"""
For C++ source code with preprocessor directives.
"""
name = 'C++'
aliases = ['cpp', 'c++']
filenames = ['*.cpp', '*.hpp', '*.c++', '*.h++',
'*.cc', '*.hh', '*.cxx', '*.hxx',
'*.C', '*.H', '*.cp', '*.CPP']
mimetypes = ['text/x-c... | CppLexer |
python | conda__conda | conda/plugins/types.py | {
"start": 14559,
"end": 15090
} | class ____(CondaPlugin):
"""
Return type to use when defining a post-transaction action hook.
For details on how this is used, see
:meth:`~conda.plugins.hookspec.CondaSpecs.conda_post_transaction_actions`.
:param name: Post transaction name (this is just a label)
:param action: Action class wh... | CondaPostTransactionAction |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 93542,
"end": 95208
} | class ____(PForTestCase, parameterized.TestCase):
@parameterized.parameters(
(fft_ops.fft,),
(fft_ops.fft2d,),
(fft_ops.fft3d,),
(fft_ops.ifft,),
(fft_ops.ifft2d,),
(fft_ops.ifft3d,),
)
def test_fft(self, op_func):
shape = [2, 3, 4, 3, 4]
x = np.random.uniform(size=sha... | SpectralTest |
python | Lightning-AI__lightning | tests/tests_pytorch/core/test_metric_result_integration.py | {
"start": 1550,
"end": 9390
} | class ____(Metric):
x: Tensor
def __init__(self):
super().__init__()
self.add_state("x", tensor(0), dist_reduce_fx="sum")
def update(self, x):
self.x += x
def compute(self):
return self.x
def result_reduce_ddp_fn(strategy):
rank = strategy.local_rank
worldsiz... | DummyMetric |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/csv_asset.py | {
"start": 7998,
"end": 8078
} | class ____(FileDataAsset, CSVAssetBase):
type: Literal["csv"] = "csv"
| CSVAsset |
python | PyCQA__pylint | pylint/utils/linterstats.py | {
"start": 1072,
"end": 1233
} | class ____(TypedDict):
"""TypedDict to store counts of different types of nodes."""
function: int
klass: int
method: int
module: int
| NodeCount |
python | walkccc__LeetCode | solutions/3493. Properties Graph/3493.py | {
"start": 609,
"end": 972
} | class ____:
def numberOfComponents(self, properties: list[list[int]], k: int) -> int:
n = len(properties)
uf = UnionFind(n)
propertySets = [set(property) for property in properties]
for i, j in itertools.combinations(range(n), 2):
if len(propertySets[i] & propertySets[j]) >= k:
uf.union... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_types.py | {
"start": 22857,
"end": 23258
} | class ____(_DateFixture, fixtures.TablesTest):
__requires__ = ("time_timezone",)
__backend__ = True
datatype = Time(timezone=True)
data = datetime.time(12, 57, 18, tzinfo=datetime.timezone.utc)
@testing.requires.time_implicit_bound
def test_select_direct(self, connection):
result = conn... | TimeTZTest |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py | {
"start": 22786,
"end": 34469
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen2_5OmniTalkerForConditionalGeneration`]. It is used to instantiate an
Qwen2.5-Omni-Talker model according to the specified arguments, defining the model architecture. Instantiating a configuration
wi... | Qwen2_5OmniTalkerConfig |
python | ansible__ansible | test/lib/ansible_test/_util/controller/sanity/validate-modules/validate_modules/utils.py | {
"start": 1176,
"end": 3121
} | class ____(TextIOWrapper):
def write(self, s):
super(AnsibleTextIOWrapper, self).write(to_text(s, self.encoding, errors='replace'))
def find_executable(executable, cwd=None, path=None):
"""Finds the full path to the executable specified"""
match = None
real_cwd = os.getcwd()
if not cwd:
... | AnsibleTextIOWrapper |
python | aio-libs__aiohttp | tests/test_payload.py | {
"start": 4989,
"end": 47363
} | class ____(AbstractStreamWriter):
"""Mock stream writer for testing payload writes."""
def __init__(self) -> None:
self.written: list[bytes] = []
async def write(
self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
) -> None:
"""Store the chunk in the w... | MockStreamWriter |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_sampled_from.py | {
"start": 2640,
"end": 4156
} | class ____(enum.Flag):
# Would fail under EnumCheck.NAMED_FLAGS
a = 0
b = 7
def test_flag_enum_repr_uses_class_not_a_list():
lazy_repr = repr(st.sampled_from(AFlag))
assert lazy_repr == "sampled_from(tests.nocover.test_sampled_from.AFlag)"
def test_exhaustive_flags():
# Generate powerset of ... | UnnamedFlag |
python | numba__numba | numba/core/types/npytypes.py | {
"start": 7905,
"end": 8517
} | class ____(DTypeSpec, Opaque):
"""
Type class associated with the `np.dtype`.
i.e. :code:`assert type(np.dtype('int32')) == np.dtype`
np.dtype('int32')
"""
def __init__(self, dtype):
assert isinstance(dtype, Type)
self._dtype = dtype
name = "dtype(%s)" % (dtype,)
... | DType |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_not_null_m2m_app/models.py | {
"start": 123,
"end": 319
} | class ____(models.Model):
alert_rule = FlexibleForeignKey(OtherTable)
test_table = FlexibleForeignKey(
"good_flow_delete_field_pending_with_not_null_m2m_app.TestTable"
)
| M2MTable |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 2459,
"end": 2592
} | class ____(CreateView):
model = PollWithHistoricalIPAddress
fields = ["question", "pub_date"]
| PollWithHistoricalIPAddressCreate |
python | tensorflow__tensorflow | tensorflow/python/tpu/tensor_tracer_report.py | {
"start": 4429,
"end": 7205
} | class ____(object):
"""Class that is responsible from storing the trace-id of the tensors."""
def __init__(self, graph_order, traced_tensors):
self.graph_order = graph_order
self.traced_tensors = traced_tensors
self._create_tensor_maps()
def _create_tensor_maps(self):
"""Creates tensor to cache ... | TensorTraceOrder |
python | sphinx-doc__sphinx | sphinx/domains/c/_symbol.py | {
"start": 838,
"end": 1313
} | class ____:
__slots__ = 'symbols', 'parent_symbol', 'ident'
symbols: Iterable[Symbol]
parent_symbol: Symbol
ident_or_op: ASTIdentifier
def __init__(
self, symbols: Iterable[Symbol], parent_symbol: Symbol, ident: ASTIdentifier
) -> None:
self.symbols = symbols
self.paren... | SymbolLookupResult |
python | django-extensions__django-extensions | django_extensions/management/commands/validate_templates.py | {
"start": 438,
"end": 4040
} | class ____(BaseCommand):
args = ""
help = "Validate templates on syntax and compile errors"
ignores = set(
[
".DS_Store",
"*.swp",
"*~",
]
)
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
... | Command |
python | ray-project__ray | python/ray/serve/_private/request_router/request_router.py | {
"start": 1427,
"end": 6753
} | class ____:
"""Mixin for locality routing.
This mixin is used to route requests to replicas that are colocated
with the handle. It adds necessary attributes and methods to keep track of
locality scopes and offer the helpers to apply locality routing and
rank replicas based on locality.
"""
... | LocalityMixin |
python | aio-libs__aiohttp | aiohttp/web_protocol.py | {
"start": 1877,
"end": 1950
} | class ____(Exception):
"""Payload parsing error."""
| RequestPayloadError |
python | pytorch__pytorch | benchmarks/gpt_fast/common.py | {
"start": 153,
"end": 544
} | class ____:
name: str
metric: str
target: float
actual: float
dtype: str
device: str
arch: str # GPU name for CUDA or CPU arch for CPU
is_model: bool = False
def register_experiment(name: Optional[str] = None):
def decorator(func):
key = name or func.__name__
all_e... | Experiment |
python | viewflow__viewflow | viewflow/this_object.py | {
"start": 2555,
"end": 3645
} | class ____:
"""
Helper for building forward references to class attributes and methods.
The rationale is the ability to specify references to the class attributes and
methods before they are declared. `this` acts similarly to `self`, but for
class-level forward references.
"""
def resolve(... | This |
python | django__django | tests/model_fields/test_uuid.py | {
"start": 7966,
"end": 8963
} | class ____(SimpleTestCase):
test_data = (
'[{"fields": {"field": "550e8400-e29b-41d4-a716-446655440000"}, '
'"model": "model_fields.uuidmodel", "pk": null}]'
)
nullable_test_data = (
'[{"fields": {"field": null}, '
'"model": "model_fields.nullableuuidmodel", "pk": null}]'
... | TestSerialization |
python | miyuchina__mistletoe | test/base_test.py | {
"start": 108,
"end": 1719
} | class ____(TestCase):
"""
Base class for tests of renderers.
"""
def setUp(self):
self.maxDiff = None
def markdownResultTest(self, markdown, expected):
output = self.renderer.render(Document(markdown))
self.assertEqual(output, expected)
def filesBasedTest(func):
... | BaseRendererTest |
python | PrefectHQ__prefect | tests/server/models/test_variables.py | {
"start": 6038,
"end": 6667
} | class ____:
async def test_count_zero_variables(
self,
session,
):
res = await count_variables(session)
assert res == 0
async def test_count_one_variables(
self,
session,
variable,
):
res = await count_variables(session)
assert res... | TestCountVariables |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-convex/destination_convex/writer.py | {
"start": 193,
"end": 1628
} | class ____:
"""
Buffers messages before sending them to Convex.
"""
write_buffer: List[Mapping[str, Any]] = []
flush_interval = 1000
def __init__(self, client: ConvexClient):
self.client = client
def delete_tables(self, table_names: List[str]) -> None:
"""Deletes all the r... | ConvexWriter |
python | pypa__warehouse | tests/unit/accounts/test_services.py | {
"start": 73650,
"end": 79045
} | class ____:
def test_device_is_known(self, user_service):
user = UserFactory.create()
UserUniqueLoginFactory.create(
user=user, ip_address=REMOTE_ADDR, status="confirmed"
)
request = pretend.stub(
db=user_service.db,
remote_addr=REMOTE_ADDR,
... | TestDeviceIsKnown |
python | pytorch__pytorch | test/profiler/test_memory_profiler.py | {
"start": 11851,
"end": 34208
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.maxDiff = None
@staticmethod
def formatSchemas(
prof: torch.profiler.profile, indent: int = 12
) -> tuple[tuple[str, tuple[bool, ...]], ...]:
tree = prof.profiler.kineto_results.experimental_event_tree()... | TestDataFlow |
python | walkccc__LeetCode | solutions/2186. Minimum Number of Steps to Make Two Strings Anagram II/2186.py | {
"start": 0,
"end": 188
} | class ____:
def minSteps(self, s: str, t: str) -> int:
count = collections.Counter(s)
count.subtract(collections.Counter(t))
return sum([abs(c) for c in count.values()])
| Solution |
python | coleifer__peewee | tests/regressions.py | {
"start": 8090,
"end": 8823
} | class ____(ModelTestCase):
def setUp(self):
super(TestInsertFromSQL, self).setUp()
self.database.execute_sql('create table if not exists user_src '
'(name TEXT);')
tbl = Table('user_src').bind(self.database)
tbl.insert(name='foo').execute()
def... | TestInsertFromSQL |
python | doocs__leetcode | solution/0100-0199/0152.Maximum Product Subarray/Solution.py | {
"start": 0,
"end": 276
} | class ____:
def maxProduct(self, nums: List[int]) -> int:
ans = f = g = nums[0]
for x in nums[1:]:
ff, gg = f, g
f = max(x, ff * x, gg * x)
g = min(x, ff * x, gg * x)
ans = max(ans, f)
return ans
| Solution |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 18706,
"end": 18854
} | class ____(CohereForCausalLM):
pass
__all__ = ["Cohere2Config", "Cohere2ForCausalLM", "Cohere2Model", "Cohere2PreTrainedModel"]
| Cohere2ForCausalLM |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/import7.py | {
"start": 115,
"end": 267
} | class ____:
# This should generate an error.
from .import5 import *
def func1():
# This should generate an error.
from .import5 import *
| A |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_kms_system.py | {
"start": 1599,
"end": 4302
} | class ____(GoogleSystemTest):
@provide_gcp_context(GCP_KMS_KEY)
def test_encrypt(self):
with TemporaryDirectory() as tmp_dir:
kms_hook = CloudKMSHook()
content = kms_hook.encrypt(
key_name=(
f"projects/{kms_hook.project_id}/locations/global/key... | TestKmsHookSystem |
python | RaRe-Technologies__gensim | gensim/models/phrases.py | {
"start": 31338,
"end": 34068
} | class ____(_PhrasesTransformation):
"""Minimal state & functionality exported from a trained :class:`~gensim.models.phrases.Phrases` model.
The goal of this class is to cut down memory consumption of `Phrases`, by discarding model state
not strictly needed for the phrase detection task.
Use this inste... | FrozenPhrases |
python | walkccc__LeetCode | solutions/2203. Minimum Weighted Subgraph With the Required Paths/2203.py | {
"start": 0,
"end": 1046
} | class ____:
def minimumWeight(
self,
n: int,
edges: list[list[int]],
src1: int,
src2: int,
dest: int,
) -> int:
graph = [[] for _ in range(n)]
reversedGraph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
reversedGraph[v].append((u,... | Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/convolutional.py | {
"start": 29027,
"end": 34195
} | class ____(keras_layers.SeparableConv1D, base.Layer):
"""Depthwise separable 1D convolution.
This layer performs a depthwise convolution that acts separately on
channels, followed by a pointwise convolution that mixes channels.
If `use_bias` is True and a bias initializer is provided,
it adds a bias vector t... | SeparableConv1D |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 10543,
"end": 11011
} | class ____:
inputs: Annotated[list[Argument], 10]
outputs: Annotated[list[Argument], 20]
# These are serialized by calling pytree.treespec_loads
# And deserialized by calling pytree.treespec_dumps
in_spec: Annotated[str, 30]
out_spec: Annotated[str, 40]
# This field is used to prettify the... | ModuleCallSignature |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 6788,
"end": 8373
} | class ____(IssueRemoteLinks, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-remote-links/#api-rest-api-3-issue-issueidorkey-remotelink-post
"""
def generate(self):
issues_stream = Issues(authenticator=self._session.auth, domain=self._domain)
... | IssueRemoteLinksGenerator |
python | keon__algorithms | algorithms/tree/bst/bst.py | {
"start": 3095,
"end": 3735
} | class ____(unittest.TestCase):
def setUp(self):
self.tree = BST()
self.tree.insert(10)
self.tree.insert(15)
self.tree.insert(6)
self.tree.insert(4)
self.tree.insert(9)
self.tree.insert(12)
self.tree.insert(24)
self.tree.insert(7)
self.t... | TestSuite |
python | numba__numba | numba/tests/test_flow_control.py | {
"start": 3463,
"end": 9023
} | class ____(TestCase):
def run_test(self, pyfunc, x_operands, y_operands,
flags=enable_pyobj_flags):
cfunc = jit((types.intp, types.intp), **flags)(pyfunc)
for x, y in itertools.product(x_operands, y_operands):
pyerr = None
cerr = None
try:
... | TestFlowControl |
python | apache__thrift | test/py/TestClient.py | {
"start": 16872,
"end": 17379
} | class ____(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = make_pedantic(TJSONProtocol.TJSONProtocolFactory().getProtocol(transport))
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, transport):
wrapped_pr... | MultiplexedJSONTest |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 117363,
"end": 119267
} | class ____(IterableDataset):
def __init__(self, len, size):
super(RandomDataset).__init__()
self.len = len
self.size = size
def __iter__(self):
return self
def __next__(self):
if self.len <= 0:
raise StopIteration
self.len -= 1
return tor... | RandomDataset |
python | PyCQA__pylint | tests/functional/u/unsupported/unsupported_assignment_operation.py | {
"start": 1763,
"end": 1894
} | class ____(LibSubscriptable):
pass
MaybeSubscriptable()[0] = 42
# subscriptable classes (through metaclasses)
| MaybeSubscriptable |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/callback.py | {
"start": 804,
"end": 11010
} | class ____:
r"""Abstract base class used to build new callbacks.
Subclass this class and override any of the relevant hooks
"""
@property
def state_key(self) -> str:
"""Identifier for the state of the callback.
Used to store and retrieve a callback's state from the checkpoint dic... | Callback |
python | pyparsing__pyparsing | examples/bf.py | {
"start": 2742,
"end": 2843
} | class ____(Instruction):
def execute(self, bf_engine: BFEngine):
bf_engine.ptr -= 1
| DecrPtr |
python | davidhalter__jedi | jedi/inference/lazy_value.py | {
"start": 512,
"end": 632
} | class ____(AbstractLazyValue):
"""data is a ValueSet."""
def infer(self):
return self.data
| LazyKnownValues |
python | kubernetes-client__python | kubernetes/client/models/v1_subject_access_review_status.py | {
"start": 383,
"end": 7409
} | 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... | V1SubjectAccessReviewStatus |
python | pytorch__pytorch | test/test_decomp.py | {
"start": 42535,
"end": 50699
} | class ____(TestCase):
@onlyNativeDeviceTypes
@skipIfCrossRef
def test_contiguous_softmax(self, device):
size = (2, 4, 3, 3)
stride = (9, 18, 3, 1)
dtype = torch.float32
x = torch.randn(size, dtype=dtype, device=device)
x = torch.as_strided(x, size, stride)
r... | DecompOneOffTests |
python | pypa__pipenv | pipenv/vendor/zipp/compat/overlay.py | {
"start": 500,
"end": 805
} | class ____(types.SimpleNamespace):
def __hash__(self):
return hash(tuple(vars(self)))
zipfile = HashableNamespace(**vars(importlib.import_module('zipfile')))
zipfile.Path = zipp.Path
zipfile._path = zipp
sys.modules[__name__ + '.zipfile'] = zipfile # type: ignore[assignment]
| HashableNamespace |
python | realpython__materials | python-protocol/animals_v2.py | {
"start": 0,
"end": 263
} | class ____:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def drink(self):
print(f"{self.name} is drinking.")
def make_sound(self):
print(f"{self.name} is barking.")
| Dog |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable.py | {
"start": 5096,
"end": 5245
} | class ____:
myattr = 1
# Different base_scope scope but still applies
mylambda2 = lambda: [LambdaClass2.myattr for _ in [1, 2]]
| LambdaClass2 |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 2449,
"end": 2726
} | class ____(TypedDict, total=False):
_version: str
source_type: str
source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict]
input_types: Dict[str, Any]
output_types: Dict[str, Any]
runtime: Optional[str]
services: Dict[str, str]
| JobSourceDict |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_campaign_manager.py | {
"start": 2958,
"end": 7424
} | class ____:
def setup_method(self):
with create_session() as session:
session.query(TI).delete()
def teardown_method(self):
with create_session() as session:
session.query(TI).delete()
@mock.patch("airflow.providers.google.marketing_platform.operators.campaign_manag... | TestGoogleCampaignManagerDownloadReportOperator |
python | pytorch__pytorch | torch/distributed/_shard/sharding_spec/api.py | {
"start": 1022,
"end": 1469
} | class ____(PlacementSpec):
"""
Associates placement of an entity with a single device.
Args:
device(:class:`torch.distributed._remote_device`): The device to place the entity on.
"""
device: torch.distributed._remote_device
def __post_init__(self):
if not isinstance(self.devic... | DevicePlacementSpec |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/few_shot_with_templates.py | {
"start": 378,
"end": 7804
} | class ____(StringPromptTemplate):
"""Prompt template that contains few shot examples."""
examples: list[dict] | None = None
"""Examples to format into the prompt.
Either this or example_selector should be provided."""
example_selector: Any = None
"""ExampleSelector to choose the examples to fo... | FewShotPromptWithTemplates |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring.py | {
"start": 1859,
"end": 1942
} | class ____:
b""" has leading whitespace"""
first_statement = 1
| ByteDocstring |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1252429,
"end": 1252677
} | class ____(sgqlc.types.Type, Node, AuditEntry, EnterpriseAuditEntryData, OrganizationAuditEntryData):
"""Audit log entry for a org.invite_to_business event."""
__schema__ = github_schema
__field_names__ = ()
| OrgInviteToBusinessAuditEntry |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1089353,
"end": 1094899
} | class ____(sgqlc.types.Type, Node):
"""A check suite."""
__schema__ = github_schema
__field_names__ = (
"app",
"branch",
"check_runs",
"commit",
"conclusion",
"created_at",
"creator",
"database_id",
"matching_pull_requests",
"p... | CheckSuite |
python | readthedocs__readthedocs.org | readthedocs/organizations/forms.py | {
"start": 4246,
"end": 5664
} | class ____(OrganizationForm):
"""
Simple organization creation form.
This trims down the number of inputs required to create a new organization.
This is used on the initial organization signup, to keep signup terse.
:param user: User instance, responsible for ownership of Organization
:type us... | OrganizationSignupFormBase |
python | allegroai__clearml | clearml/backend_api/services/v2_13/auth.py | {
"start": 6683,
"end": 8293
} | class ____(Request):
"""
Edit a users' auth data properties
:param user: User ID
:type user: str
:param role: The new user's role within the company
:type role: str
"""
_service = "auth"
_action = "edit_user"
_version = "2.13"
_schema = {
"definitions": {},
... | EditUserRequest |
python | django__django | tests/apps/apps.py | {
"start": 412,
"end": 476
} | class ____(AppConfig):
name = "there is no such app"
| NoSuchApp |
python | dask__dask | dask/tests/test_expr.py | {
"start": 3859,
"end": 4524
} | class ____(Expr):
def _layer(self) -> dict:
return {"foo": DataNode("foo", 42)}
def test_prohibit_reuse():
once = FooExpr()
ProhibitReuse._ALLOWED_TYPES.append(FooExpr)
try:
dsk = _ExprSequence(once, ProhibitReuse(once)).optimize().__dask_graph__()
assert len(dsk) == 2
... | FooExpr |
python | huggingface__transformers | src/transformers/models/ministral/modeling_ministral.py | {
"start": 11622,
"end": 12167
} | class ____(PreTrainedModel):
config: MinistralConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["MinistralDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = ... | MinistralPreTrainedModel |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 14066,
"end": 15178
} | class ____(Converter):
def converted(self) -> Tokenizer:
tokenizer_info_str = "#version:"
token_suffix = "</w>"
vocab = self.original_tokenizer.encoder
merges = list(self.original_tokenizer.bpe_ranks.keys())
if tokenizer_info_str in merges[0][0]:
merges = merges[... | HerbertConverter |
python | dagster-io__dagster | examples/docs_projects/project_mini/src/project_mini/defs/resource_caching/expensive_resource_cache.py | {
"start": 121,
"end": 1045
} | class ____(dg.ConfigurableResource):
@lru_cache(maxsize=128)
def addition(self, num1: int, num2: int) -> int:
time.sleep(5)
return num1 + num2
# highlight-end
@dg.asset
def expensive_asset_cache(
expensive_resource_cache: ExpensiveResourceCache,
) -> dg.MaterializeResult:
value = exp... | ExpensiveResourceCache |
python | pennersr__django-allauth | allauth/account/adapter.py | {
"start": 1703,
"end": 36568
} | class ____(BaseAdapter):
"""The adapter class allows you to override various functionality of the
``allauth.account`` app. To do so, point ``settings.ACCOUNT_ADAPTER`` to
your own class that derives from ``DefaultAccountAdapter`` and override the
behavior by altering the implementation of the methods a... | DefaultAccountAdapter |
python | python-pillow__Pillow | src/PIL/TiffImagePlugin.py | {
"start": 74172,
"end": 85002
} | class ____(io.BytesIO):
fieldSizes = [
0, # None
1, # byte
1, # ascii
2, # short
4, # long
8, # rational
1, # sbyte
1, # undefined
2, # sshort
4, # slong
8, # srational
4, # float
8, # double
... | AppendingTiffWriter |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_experiment_service.py | {
"start": 6948,
"end": 8768
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_no_default_project_id
):
self.hook = ExperimentRunHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(EXPERIMENT_SERVICE_STRING.format("aiplatform.Experi... | TestExperimentRunWithoutDefaultProjectIdHook |
python | apache__airflow | providers/standard/src/airflow/providers/standard/sensors/external_task.py | {
"start": 2404,
"end": 3655
} | class ____(BaseOperatorLink):
"""
Operator link for ExternalTaskSensor and ExternalTaskMarker.
It allows users to access DAG waited with ExternalTaskSensor or cleared by ExternalTaskMarker.
"""
name = "External DAG"
def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str... | ExternalDagLink |
python | psf__black | tests/data/cases/form_feeds.py | {
"start": 696,
"end": 1657
} | class ____:
def __init__(self):
pass
def something(self):
pass
#
pass
pass #
a = 1
#
pass
a = 1
a = [
]
# as internal whitespace of a comment is allowed but why
"form feed literal in a string is okay"
# form feeds at the very end get removed.
# output
# W... | Baz |
python | fluentpython__example-code | 14-it-generator/sentence_iter.py | {
"start": 525,
"end": 1498
} | class ____:
def __init__(self, words):
self.words = words # <3>
self.index = 0 # <4>
def __next__(self):
try:
word = self.words[self.index] # <5>
except IndexError:
raise StopIteration() # <6>
self.index += 1 # <7>
return word # <8>... | SentenceIterator |
python | pydata__xarray | xarray/core/types.py | {
"start": 11708,
"end": 11905
} | class ____(Protocol):
def acquire(self, *args, **kwargs) -> Any: ...
def release(self) -> None: ...
def __enter__(self) -> Any: ...
def __exit__(self, *args, **kwargs) -> None: ...
| Lock |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 67533,
"end": 68087
} | class ____(BiffRecord):
"""
This record is part of the Calculation Settings Block. It specifies the maximum
number of times the formulas should be iteratively calculated. This is a fail-safe
against mutually recursive formulas locking up a spreadsheet application.
Record CALCCOUNT, BIFF2-BIFF8:
... | CalcCountRecord |
python | urllib3__urllib3 | src/urllib3/response.py | {
"start": 6282,
"end": 8440
} | class ____:
"""Memory-efficient bytes buffer
To return decoded data in read() and still follow the BufferedIOBase API, we need a
buffer to always return the correct amount of bytes.
This buffer should be filled using calls to put()
Our maximum memory usage is determined by the sum of the size of:... | BytesQueueBuffer |
python | tensorflow__tensorflow | tensorflow/python/compiler/xla/experimental/xla_sharding.py | {
"start": 1032,
"end": 23389
} | class ____(object):
"""A class to support adding sharding attributes to Ops.
Use the factory constructors and then call apply_to_tensor:
Sharding.replicate().apply_to_tensor(tensor)
"""
def __init__(self, proto=None):
"""Do not use this constructor; use the factory functions below."""
self._proto ... | Sharding |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/optimization/test_multiple_optimizers.py | {
"start": 786,
"end": 3004
} | class ____(BoringModel):
def configure_optimizers(self):
opt_a = torch.optim.SGD(self.layer.parameters(), lr=0.001)
opt_b = torch.optim.SGD(self.layer.parameters(), lr=0.001)
return opt_a, opt_b
def test_multiple_optimizers_automatic_optimization_raises():
"""Test that multiple optimiz... | MultiOptModel |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/shrinking/integer.py | {
"start": 624,
"end": 2218
} | class ____(Shrinker):
"""Attempts to find a smaller integer. Guaranteed things to try ``0``,
``1``, ``initial - 1``, ``initial - 2``. Plenty of optimisations beyond
that but those are the guaranteed ones.
"""
def short_circuit(self):
for i in range(2):
if self.consider(i):
... | Integer |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/optimization/map_and_filter_fusion_test.py | {
"start": 2593,
"end": 4581
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
def _testDataset(self, dataset, function, predicate):
expected_output = []
for x in range(10):
r = function(x)
if isinstance(r, tuple):
b = predicate(*r) # Pass tuple as multiple arguments.
else:
b = predicate(r... | MapAndFilterFusionTest |
python | ray-project__ray | python/ray/data/_internal/datasource/image_datasink.py | {
"start": 125,
"end": 705
} | class ____(RowBasedFileDatasink):
def __init__(
self, path: str, column: str, file_format: str, **file_datasink_kwargs
):
super().__init__(path, file_format=file_format, **file_datasink_kwargs)
self.column = column
self.file_format = file_format
def write_row_to_file(self, ... | ImageDatasink |
python | Textualize__rich | tests/test_protocol.py | {
"start": 361,
"end": 1861
} | class ____:
def __getattr__(self, name):
return 12
def __repr__(self) -> str:
return "Fake()"
def test_rich_cast_fake():
fake = Fake()
console = Console(file=io.StringIO())
console.print(fake)
assert console.file.getvalue() == "Fake()\n"
def test_rich_cast_container():
f... | Fake |
python | getsentry__sentry | src/sentry/users/services/usersocialauth/impl.py | {
"start": 899,
"end": 4048
} | class ____(UserSocialAuthService):
def get_many(self, *, filter: UserSocialAuthFilterArgs) -> list[RpcUserSocialAuth]:
return self._FQ.get_many(filter=filter)
def get_one_or_none(self, *, filter: UserSocialAuthFilterArgs) -> RpcUserSocialAuth | None:
auths = self.get_many(filter=filter)
... | DatabaseBackedUserSocialAuthService |
python | facebookresearch__faiss | faiss/python/extra_wrappers.py | {
"start": 12936,
"end": 20493
} | class ____:
"""Object that performs k-means clustering and manages the centroids.
The `Kmeans` class is essentially a wrapper around the C++ `Clustering` object.
Parameters
----------
d : int
dimension of the vectors to cluster
k : int
number of clusters
gpu: bool or int, opti... | Kmeans |
python | falconry__falcon | tests/test_inspect.py | {
"start": 12428,
"end": 13293
} | class ____:
def test_inspect_visitor(self):
iv = inspect.InspectVisitor()
with pytest.raises(RuntimeError, match='This visitor does not support'):
iv.process(123)
with pytest.raises(RuntimeError, match='This visitor does not support'):
iv.process(inspect.RouteInfo('f'... | TestInspectVisitor |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 24994,
"end": 25405
} | class ____(Lexer):
"""
Lexer for handling Cheetah's special $ tokens in Python syntax.
"""
def get_tokens_unprocessed(self, text):
pylexer = PythonLexer(**self.options)
for pos, type_, value in pylexer.get_tokens_unprocessed(text):
if type_ == Token.Error and value == '$':
... | CheetahPythonLexer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassTransform2.py | {
"start": 1167,
"end": 1942
} | class ____(ModelBase, order=True):
id: int
name: str = model_field(default="None")
c1_1 = Customer1(id=3, name="Sue", other_name="Susan")
# This should generate an error because the class is frozen.
c1_1.id = 4
# This should generate an error because the class is kw_only.
c1_2 = Customer1(3, "Sue")
# This ... | Customer2 |
python | falconry__falcon | falcon/_typing.py | {
"start": 6123,
"end": 6409
} | class ____(Protocol[_ReqT, _RespT]):
"""WSGI Middleware with resource handler."""
def process_resource(
self,
req: _ReqT,
resp: _RespT,
resource: Resource | None,
params: dict[str, Any],
) -> None: ...
| WsgiMiddlewareWithProcessResource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/job.py | {
"start": 1111,
"end": 28673
} | class ____:
http_client: HttpClient
base_url: str
query: ShopifyBulkQuery
job_termination_threshold: float
job_size: float
job_checkpoint_interval: int
parent_stream_name: Optional[str] = None
parent_stream_cursor: Optional[str] = None
# 10Mb chunk size to save the file
_retrie... | ShopifyBulkManager |
python | ray-project__ray | python/ray/serve/tests/unit/test_schema.py | {
"start": 29342,
"end": 36839
} | class ____:
def test_parse_dict(self):
schema = LoggingConfig.parse_obj(
{
"log_level": logging.DEBUG,
"encoding": "JSON",
"logs_dir": "/my_dir",
"enable_access_log": True,
}
)
assert schema.log_level == ... | TestLoggingConfig |
python | apache__airflow | providers/standard/src/airflow/providers/standard/decorators/branch_external_python.py | {
"start": 1217,
"end": 2403
} | class ____(_PythonDecoratedOperator, BranchExternalPythonOperator):
"""Wraps a Python callable and captures args/kwargs when called for execution."""
template_fields = BranchExternalPythonOperator.template_fields
custom_operator_name: str = "@task.branch_external_python"
def branch_external_python_task(
... | _BranchExternalPythonDecoratedOperator |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py | {
"start": 3350,
"end": 5533
} | class ____(nn.Module):
"""Embeds batches of token IDs into feature space.
Attributes:
vocab_size: The size of the vocabulary (i.e., the number of embeddings).
embedding_size: The dimensionality of the embeddings.
embedding_init: The initializer used to initialize the embeddings.
frozen: Freezes the... | Embedder |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 972,
"end": 1129
} | class ____(Completion):
"""Argument completion unavailable."""
message: str = 'No completions available.'
@dataclasses.dataclass
| CompletionUnavailable |
python | huggingface__transformers | tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py | {
"start": 27294,
"end": 31222
} | class ____(EncoderDecoderMixin, unittest.TestCase):
def get_encoder_decoder_model(self, config, decoder_config):
encoder_model = SwinModel(config).eval()
decoder_model = BartForCausalLM(decoder_config).eval()
return encoder_model, decoder_model
def prepare_config_and_inputs(self):
... | Swin2BartModelTest |
python | facebook__pyre-check | client/configuration/tests/scheduler_policies_test.py | {
"start": 383,
"end": 4697
} | class ____(testslide.TestCase):
def test_policy_from_and_to_json(self) -> None:
def assert_parsed(input: object, expected: SchedulerPolicy) -> None:
self.assertEqual(SchedulerPolicy.from_json(input, "<unknown>"), expected)
self.assertEqual(input, expected.to_json())
def asse... | SchedulerPoliciesTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.