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 | openai__openai-python | src/openai/types/image_gen_partial_image_event.py | {
"start": 201,
"end": 1077
} | class ____(BaseModel):
b64_json: str
"""Base64-encoded partial image data, suitable for rendering as an image."""
background: Literal["transparent", "opaque", "auto"]
"""The background setting for the requested image."""
created_at: int
"""The Unix timestamp when the event was created."""
... | ImageGenPartialImageEvent |
python | walkccc__LeetCode | solutions/1028. Recover a Tree From Preorder Traversal/1028.py | {
"start": 0,
"end": 633
} | class ____:
def recoverFromPreorder(self, traversal: str) -> TreeNode | None:
i = 0
def recoverFromPreorder(depth: int) -> TreeNode | None:
nonlocal i
nDashes = 0
while i + nDashes < len(traversal) and traversal[i + nDashes] == '-':
nDashes += 1
if nDashes != depth:
re... | Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_athena.py | {
"start": 2149,
"end": 14280
} | class ____:
def setup_method(self, _):
self.athena = AthenaHook()
def test_init(self):
assert self.athena.aws_conn_id == "aws_default"
@mock.patch.object(AthenaHook, "get_conn")
def test_hook_run_query_without_token(self, mock_conn):
mock_conn.return_value.start_query_execution... | TestAthenaHook |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 14656,
"end": 15426
} | class ____(Interface):
"""An object implementing this interface is passed to every
:term:`renderer factory` constructor as its only argument (conventionally
named ``info``)"""
name = Attribute('The value passed by the user as the renderer name')
package = Attribute(
'The "current package" w... | IRendererInfo |
python | sphinx-doc__sphinx | sphinx/domains/c/__init__.py | {
"start": 15744,
"end": 16556
} | class ____(SphinxDirective):
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
stack = self.env.current_document.c_namespace_stack
if len(stack) == 0:
... | CNamespacePopObject |
python | scipy__scipy | scipy/optimize/_shgo.py | {
"start": 21321,
"end": 61425
} | class ____:
def __init__(self, func, bounds, args=(), constraints=None, n=None,
iters=None, callback=None, minimizer_kwargs=None,
options=None, sampling_method='simplicial', workers=1):
from scipy.stats import qmc
# Input checks
methods = ['halton', 'sobol',... | SHGO |
python | EpistasisLab__tpot | tpot/tpot_estimator/templates/tpottemplates.py | {
"start": 19046,
"end": 36367
} | class ____(TPOTEstimator):
def __init__( self,
search_space = "linear",
scorers=['roc_auc_ovr'],
scorers_weights=[1],
cv = 10,
other_objective_functions=[], #tpot.objectives.estimator_objec... | TPOTClassifier |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 116403,
"end": 119559
} | class ____(Request):
"""
Indicates that task is closed
:param force: Allows forcing state change even if transition is not supported
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: ... | CloseRequest |
python | ray-project__ray | python/ray/serve/_private/common.py | {
"start": 5485,
"end": 6090
} | class ____(str, Enum):
"""Explains how a deployment reached its current DeploymentStatus."""
UNSPECIFIED = "UNSPECIFIED"
CONFIG_UPDATE_STARTED = "CONFIG_UPDATE_STARTED"
CONFIG_UPDATE_COMPLETED = "CONFIG_UPDATE_COMPLETED"
UPSCALE_COMPLETED = "UPSCALE_COMPLETED"
DOWNSCALE_COMPLETED = "DOWNSCALE_C... | DeploymentStatusTrigger |
python | joblib__joblib | joblib/test/test_memory.py | {
"start": 46352,
"end": 48714
} | class ____:
"Tests on parameter `cache_validation_callback`"
def foo(self, x, d, delay=None):
d["run"] = True
if delay is not None:
time.sleep(delay)
return x * 2
def test_invalid_cache_validation_callback(self, memory):
"Test invalid values for `cache_validatio... | TestCacheValidationCallback |
python | google__pytype | pytype/overlays/dataclass_overlay.py | {
"start": 463,
"end": 827
} | class ____(overlay.Overlay):
"""A custom overlay for the 'dataclasses' module."""
def __init__(self, ctx):
member_map = {
"dataclass": Dataclass.make,
"field": FieldFunction.make,
"replace": Replace.make,
}
ast = ctx.loader.import_name("dataclasses")
super().__init__(ctx, "d... | DataclassOverlay |
python | openai__openai-python | src/openai/types/moderation_text_input_param.py | {
"start": 224,
"end": 406
} | class ____(TypedDict, total=False):
text: Required[str]
"""A string of text to classify."""
type: Required[Literal["text"]]
"""Always `text`."""
| ModerationTextInputParam |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver32.py | {
"start": 534,
"end": 778
} | class ____:
def __add__(self, other: bool | int) -> Self: ...
def __sub__(self, other: "DateTime") -> TimeDelta: ...
def func1(__val: DT) -> DT:
return __val
dt = DateTime()
reveal_type(func1(dt), expected_text="DateTime")
| DateTime |
python | kamyu104__LeetCode-Solutions | Python/maximum-segment-sum-after-removals.py | {
"start": 1654,
"end": 2477
} | class ____(object):
def maximumSegmentSum(self, nums, removeQueries):
"""
:type nums: List[int]
:type removeQueries: List[int]
:rtype: List[int]
"""
removed_idxs = SortedList([-1, len(nums)])
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
... | Solution2 |
python | django__django | django/db/models/fields/files.py | {
"start": 14864,
"end": 15429
} | class ____(ImageFile, FieldFile):
def _set_instance_attribute(self, name, content):
setattr(self.instance, self.field.attname, content)
# Update the name in case generate_filename() or storage.save() changed
# it, but bypass the descriptor to avoid re-reading the file.
self.instance.... | ImageFieldFile |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 97782,
"end": 99089
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
norm_layer = nn.BatchNorm2d
inplanes = 3
self.conv1 = nn.Conv2d(inplanes, inplanes, (1, 1), bias=False)
self.conv2 = nn.Conv2d(inplanes, inplanes, (1, 1), bias=False)
self.bn1 = norm_layer(inp... | ModelMultipleOps |
python | django__django | tests/expressions/test_queryset_values.py | {
"start": 209,
"end": 4197
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Company.objects.create(
name="Example Inc.",
num_employees=2300,
num_chairs=5,
ceo=Employee.objects.create(firstname="Joe", lastname="Smith", salary=10),
)
Company.objects.create(
... | ValuesExpressionsTests |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py | {
"start": 20765,
"end": 23859
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen2_5_VLConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
s... | Qwen2_5_VLRotaryEmbedding |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_aggregate_metrics/column_values_not_match_regex_values.py | {
"start": 636,
"end": 2142
} | class ____(ColumnAggregateMetricProvider):
metric_name = "column_values.not_match_regex_values"
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy( # FIXME CoP
cls,
execution_engine: SqlAlchemyExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: di... | ColumnValuesNotMatchRegexValues |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 21969,
"end": 22363
} | class ____(ReplayGroupTypeDefaults, GroupType):
type_id = 5003
slug = "replay_hydration_error"
description = "Hydration Error Detected"
category = GroupCategory.REPLAY.value
category_v2 = GroupCategory.FRONTEND.value
default_priority = PriorityLevel.MEDIUM
notification_config = NotificationC... | ReplayHydrationErrorType |
python | huggingface__transformers | src/transformers/models/starcoder2/modular_starcoder2.py | {
"start": 9296,
"end": 9574
} | class ____(MistralForTokenClassification):
pass
__all__ = [
"Starcoder2ForCausalLM",
"Starcoder2Model",
"Starcoder2PreTrainedModel", # noqa: F822
"Starcoder2ForSequenceClassification",
"Starcoder2ForTokenClassification",
]
| Starcoder2ForTokenClassification |
python | numpy__numpy | numpy/lib/tests/test_stride_tricks.py | {
"start": 18109,
"end": 23012
} | class ____(VerySimpleSubClass):
def __new__(cls, *args, **kwargs):
self = np.array(*args, subok=True, **kwargs).view(cls)
self.info = 'simple'
return self
def __array_finalize__(self, obj):
self.info = getattr(obj, 'info', '') + ' finalized'
def test_subclasses():
# test t... | SimpleSubClass |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 2795,
"end": 3247
} | class ____(Flaky):
"""
This function appears to cause inconsistent data generation.
Common causes for this problem are:
1. The strategy depends on external state. e.g. it uses an external
random number generator. Try to make a version that passes all the
relevant state in from... | FlakyStrategyDefinition |
python | django__django | tests/defer_regress/tests.py | {
"start": 13726,
"end": 15117
} | class ____(TestCase):
senders = [Item, Proxy]
@classmethod
def setUpTestData(cls):
cls.item_pk = Item.objects.create(value=1).pk
def setUp(self):
self.pre_delete_senders = []
self.post_delete_senders = []
for sender in self.senders:
models.signals.pre_delete... | DeferDeletionSignalsTests |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_sources.py | {
"start": 2238,
"end": 7073
} | class ____:
@pytest.fixture(autouse=True)
def setup(self, url_safe_serializer) -> None:
self.clear_db()
def teardown_method(self) -> None:
self.clear_db()
@staticmethod
def _get_dag_file_code(fileloc: str) -> str | None:
with open(fileloc) as f:
file_contents = ... | TestGetDAGSource |
python | doocs__leetcode | solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/Solution.py | {
"start": 0,
"end": 587
} | class ____:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
def dfs(i):
nonlocal ans
if i == len(jobs):
ans = min(ans, max(cnt))
return
for j in range(k):
if cnt[j] + jobs[i] >= ans:
contin... | Solution |
python | huggingface__transformers | src/transformers/models/jamba/modular_jamba.py | {
"start": 2604,
"end": 7633
} | class ____:
"""
A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
(which has a constant shape regardless of seq_len).
This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
and `ssm_... | HybridMambaAttentionDynamicCache |
python | wandb__wandb | wandb/vendor/pygments/lexers/r.py | {
"start": 510,
"end": 2331
} | class ____(Lexer):
"""
For R console transcripts or R CMD BATCH output files.
"""
name = 'RConsole'
aliases = ['rconsole', 'rout']
filenames = ['*.Rout']
def get_tokens_unprocessed(self, text):
slexer = SLexer(**self.options)
current_code_block = ''
insertions = []... | RConsoleLexer |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 72810,
"end": 73869
} | class ____(BiffRecord):
"""
This record is part of the Page Settings Block. It contains all
horizontal manual page breaks.
Record HORIZONTALPAGEBREAKS, BIFF8:
Offset Size Contents
0 2 Number of following row index structures (nm)
2 6nm List of nm row index struct... | HorizontalPageBreaksRecord |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chartsheet09.py | {
"start": 315,
"end": 1602
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chartsheet09.xlsx")
def test_create_file(self):
"""Test the worksheet properties of an XlsxWriter chartsheet file with series format proper... | TestCompareXLSXFiles |
python | astropy__astropy | astropy/io/ascii/ipac.py | {
"start": 972,
"end": 1809
} | class ____(core.BaseSplitter):
"""Splitter for Ipac Headers.
This splitter is similar its parent when reading, but supports a
fixed width format (as required for Ipac table headers) for writing.
"""
process_line = None
process_val = None
delimiter = "|"
delimiter_pad = ""
skipiniti... | IpacHeaderSplitter |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 412886,
"end": 428295
} | class ____(VegaLiteSchema):
r"""
FieldOrDatumDefWithConditionStringFieldDefstring schema wrapper.
Parameters
----------
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', '... | FieldOrDatumDefWithConditionStringFieldDefstring |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 21187,
"end": 21975
} | class ____(_SimulatedWithAsyncMixin,
_base.ChildMixin,
watcher):
_watcher_skip_ffi = True
# We'll have to implement this one completely manually.
# Our approach is to use a SIGCHLD handler and the original
# os.waitpid call.
# On Unix, libuv's uv_process_t and uv_spawn use S... | child |
python | ray-project__ray | python/ray/serve/_private/application_state.py | {
"start": 6174,
"end": 7679
} | class ____:
"""Defines target state of application.
Target state can become inconsistent if the code version doesn't
match that of the config. When that happens, a new build app task
should be kicked off to reconcile the inconsistency.
deployment_infos: map of deployment name to deployment info. T... | ApplicationTargetState |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1338101,
"end": 1339278
} | class ____(sgqlc.types.Type, Node):
"""A workflow inside a project."""
__schema__ = github_schema
__field_names__ = ("created_at", "database_id", "enabled", "name", "number", "project", "updated_at")
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identif... | ProjectV2Workflow |
python | matplotlib__matplotlib | lib/matplotlib/spines.py | {
"start": 18498,
"end": 19820
} | class ____:
"""
A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.
The proxy cannot be used for any other operations on its members.
The supported methods are determined dynamically based on the contained
spines. If not all spines support a given method, it's execu... | SpinesProxy |
python | walkccc__LeetCode | solutions/567. Permutation in String/567-2.py | {
"start": 0,
"end": 439
} | class ____:
def checkInclusion(self, s1: str, s2: str) -> bool:
count = collections.Counter(s1)
required = len(s1)
for r, c in enumerate(s2):
count[c] -= 1
if count[c] >= 0:
required -= 1
if r >= len(s1): # The window is oversized.
count[s2[r - len(s1)]] += 1
if... | Solution |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 38607,
"end": 38671
} | class ____(ExprNode):
__slots__ = ("slice", "value")
| Subscript |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 2703,
"end": 2854
} | class ____(models.Model):
planned_date = models.DateField()
class Meta:
abstract = True
verbose_name_plural = "Audits"
| AuditBase |
python | walkccc__LeetCode | solutions/415. Add Strings/415.py | {
"start": 0,
"end": 386
} | class ____:
def addStrings(self, num1: str, num2: str) -> str:
ans = []
carry = 0
i = len(num1) - 1
j = len(num2) - 1
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += int(num1[i])
if j >= 0:
carry += int(num2[j])
ans.append(str(carry % 10))
carry //= 10... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 133774,
"end": 138289
} | class ____(DataplexCatalogBaseOperator):
"""
Create an AspectType resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogCreateAspectTypeOperator`
:param aspect_type_id: Required. AspectType identifier.
... | DataplexCatalogCreateAspectTypeOperator |
python | getsentry__sentry | src/sentry/testutils/helpers/backups.py | {
"start": 5871,
"end": 14383
} | class ____(Exception):
def __init__(self, info: ComparatorFindings):
super().__init__(info.pretty())
self.info = info
def export_to_file(
path: Path,
scope: ExportScope,
filter_by: set[str] | None = None,
checkpointer: ExportCheckpointer | None = None,
) -> Any:
"""
Helper ... | ValidationError |
python | has2k1__plotnine | plotnine/iapi.py | {
"start": 1308,
"end": 1461
} | class ____:
"""
Range information after training
"""
range: tuple[float, float]
range_coord: tuple[float, float]
@dataclass
| range_view |
python | mlflow__mlflow | mlflow/entities/model_registry/registered_model_deployment_job_state.py | {
"start": 88,
"end": 1757
} | class ____:
"""Enum for registered model deployment state of an
:py:class:`mlflow.entities.model_registry.RegisteredModel`.
"""
NOT_SET_UP = DeploymentJobConnection.State.Value("NOT_SET_UP")
CONNECTED = DeploymentJobConnection.State.Value("CONNECTED")
NOT_FOUND = DeploymentJobConnection.State.V... | RegisteredModelDeploymentJobState |
python | ray-project__ray | rllib/models/tests/test_action_distributions.py | {
"start": 468,
"end": 6713
} | class ____(unittest.TestCase):
"""Tests ActionDistribution classes."""
@classmethod
def setUpClass(cls) -> None:
# Set seeds for deterministic tests (make sure we don't fail
# because of "bad" sampling).
np.random.seed(42 + 1)
torch.manual_seed(42 + 1)
def _stability_te... | TestActionDistributions |
python | gevent__gevent | src/greentest/3.13/test_ftplib.py | {
"start": 32296,
"end": 33845
} | class ____(TestCase):
def setUp(self):
self.server = DummyFTPServer((HOSTv6, 0),
af=socket.AF_INET6,
encoding=DEFAULT_ENCODING)
self.server.start()
self.client = ftplib.FTP(timeout=TIMEOUT, encoding=DEFAULT_ENCODING)
... | TestIPv6Environment |
python | django__django | tests/admin_views/admin.py | {
"start": 9572,
"end": 9655
} | class ____(admin.StackedInline):
model = FooAccount
extra = 1
| FooAccountAdmin |
python | cython__cython | tests/run/purecdef.py | {
"start": 1251,
"end": 1802
} | class ____(object):
a = cython.declare(cython.double)
def __init__(self, a):
self.a = a
def __call__(self):
return self.a
@cython.test_assert_path_exists('//CFuncDefNode')
@cython.cfunc
def puremeth(self, a):
return a*2
def test_method():
"""
>>> test_method()... | PureFoo |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 5074,
"end": 5427
} | class ____(GQLResult):
typename__: Typename[Literal["ArtifactSequence", "ArtifactPortfolio"]]
id: GQLId
name: str
description: Optional[str]
created_at: str = Field(alias="createdAt")
project: Optional[ProjectInfoFragment]
type: RegistryCollectionFragmentType
tags: RegistryCollectionFrag... | RegistryCollectionFragment |
python | ansible__ansible | test/lib/ansible_test/_internal/ci/__init__.py | {
"start": 2705,
"end": 4684
} | class ____(metaclass=abc.ABCMeta):
"""Base class for CI provider plugins."""
priority = 500
@staticmethod
@abc.abstractmethod
def is_supported() -> bool:
"""Return True if this provider is supported in the current running environment."""
@property
@abc.abstractmethod
def code(... | CIProvider |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 31180,
"end": 31975
} | class ____(DataModel):
def __init__(self, dmm, fe_type):
super(UnicodeCharSeq, self).__init__(dmm, fe_type)
charty = ir.IntType(numpy_support.sizeof_unicode_char * 8)
self._be_type = ir.ArrayType(charty, fe_type.count)
def get_value_type(self):
return self._be_type
def get_... | UnicodeCharSeq |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_metadata.py | {
"start": 5020,
"end": 7126
} | class ____:
def test_fail_when_no_cdk_tags(self, mocker):
# Arrange
connector = mocker.MagicMock(metadata={"tags": []})
# Act
result = metadata.CheckConnectorCDKTag()._run(connector)
# Assert
assert result.status == CheckStatus.FAILED
assert result.message =... | TestCheckConnectorCDKTag |
python | realpython__materials | python-class/aircrafts.py | {
"start": 326,
"end": 632
} | class ____(Aircraft):
def __init__(self, thrust, lift, max_speed, num_rotors):
super().__init__(thrust, lift, max_speed)
self.num_rotors = num_rotors
def show_technical_specs(self):
super().show_technical_specs()
print(f"Number of rotors: {self.num_rotors}")
| Helicopter |
python | ray-project__ray | python/ray/dashboard/modules/aggregator/tests/test_ray_event_publisher.py | {
"start": 5217,
"end": 5753
} | class ____:
"""Test no-op publisher implementation."""
@pytest.mark.asyncio
async def test_all_methods_noop(self):
"""Test that run_forever can be cancelled and metrics return expected values."""
publisher = NoopPublisher()
# Start and cancel run_forever
task = asyncio.crea... | TestNoopPublisher |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 10089,
"end": 12305
} | class ____(unittest.TestCase):
"""Tests person in the de_AT locale"""
def setUp(self):
self.fake = Faker("de_AT")
Faker.seed(0)
def test_academic_prefix(self):
academic_prefix = self.fake.academic_prefix()
assert isinstance(academic_prefix, str)
assert academic_pref... | TestDeAt |
python | jmcnamara__XlsxWriter | xlsxwriter/drawing.py | {
"start": 410,
"end": 576
} | class ____(Enum):
"""
Enum to represent different types of drawings in a worksheet.
"""
NONE = 0
CHART = 1
IMAGE = 2
SHAPE = 3
| DrawingTypes |
python | django__django | tests/model_forms/tests.py | {
"start": 4380,
"end": 4594
} | class ____(forms.ModelForm):
name1 = forms.CharField(error_messages={"invalid": "Form custom error message."})
class Meta:
fields = "__all__"
model = CustomErrorMessage
| CustomErrorMessageForm |
python | pypa__warehouse | warehouse/packaging/services.py | {
"start": 5418,
"end": 5864
} | class ____:
def __init__(self, bucket, *, prefix: str | None = None):
self.bucket = bucket
self.prefix = prefix
def _get_path(self, path: str) -> str:
# If we have a prefix, then prepend it to our path. This will let us
# store items inside of a sub directory without exposing th... | GenericBlobStorage |
python | scrapy__scrapy | scrapy/core/http2/agent.py | {
"start": 855,
"end": 4087
} | class ____:
def __init__(self, reactor: ReactorBase, settings: Settings) -> None:
self._reactor = reactor
self.settings = settings
# Store a dictionary which is used to get the respective
# H2ClientProtocolInstance using the key as Tuple(scheme, hostname, port)
self._connec... | H2ConnectionPool |
python | tensorflow__tensorflow | tensorflow/python/training/coordinator_test.py | {
"start": 10062,
"end": 10922
} | class ____(test.TestCase):
def testTargetArgs(self):
n = [3]
coord = coordinator.Coordinator()
thread = coordinator.LooperThread.loop(
coord, 0, target=_StopAt0, args=(coord, n))
coord.join([thread])
self.assertEqual(0, n[0])
def testTargetKwargs(self):
n = [3]
coord = coordina... | LooperTest |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 13862,
"end": 14001
} | class ____(OracleToleranceMixin, GeomOutputGeoFunc):
arity = 2
geom_param_pos = (0, 1)
@BaseSpatialField.register_lookup
| Intersection |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 11355,
"end": 11430
} | class ____(PolymorphicModel):
name = models.CharField(max_length=30)
| Duck |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 46102,
"end": 47040
} | class ____(FieldValues):
"""
Valid and invalid values for `DateField`.
"""
valid_inputs = {
'2001-01-01': datetime.date(2001, 1, 1),
datetime.date(2001, 1, 1): datetime.date(2001, 1, 1),
}
invalid_inputs = {
'abc': ['Date has wrong format. Use one of these formats instead... | TestDateField |
python | fluentpython__example-code-2e | 10-dp-1class-func/pytypes/classic_strategy.py | {
"start": 2118,
"end": 2304
} | class ____(ABC): # the Strategy: an abstract base class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
@typelogged
| Promotion |
python | pypa__warehouse | warehouse/oidc/forms/gitlab.py | {
"start": 4909,
"end": 4966
} | class ____(GitLabPublisherBase):
pass
| GitLabPublisherForm |
python | huggingface__transformers | src/transformers/models/wav2vec2/modeling_wav2vec2.py | {
"start": 17171,
"end": 18865
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
self.dropout = nn.Dropout(config.feat_proj_dropout)
def forwa... | Wav2Vec2FeatureProjection |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 6464,
"end": 6619
} | class ____:
def test_ordinal_number(self):
assert self.locale.ordinal_number(1) == "1º"
@pytest.mark.usefixtures("lang_locale")
| TestItalianLocale |
python | huggingface__transformers | src/transformers/models/pvt/modeling_pvt.py | {
"start": 17787,
"end": 18728
} | class ____(PreTrainedModel):
config: PvtConfig
base_model_prefix = "pvt"
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = []
@torch.no_grad()
def _init_weights(self, module: nn.Module) -> None:
"""Initialize the weights"""
std = self.config.... | PvtPreTrainedModel |
python | PyCQA__pylint | pylint/pyreverse/diagrams.py | {
"start": 563,
"end": 685
} | class ____:
"""Base class for counter handling."""
def __init__(self) -> None:
self.fig_id: str = ""
| Figure |
python | doocs__leetcode | solution/3000-3099/3001.Minimum Moves to Capture The Queen/Solution.py | {
"start": 0,
"end": 487
} | class ____:
def minMovesToCaptureTheQueen(
self, a: int, b: int, c: int, d: int, e: int, f: int
) -> int:
if a == e and (c != a or (d - b) * (d - f) > 0):
return 1
if b == f and (d != b or (c - a) * (c - e) > 0):
return 1
if c - e == d - f and (a - e != b ... | Solution |
python | tornadoweb__tornado | tornado/web.py | {
"start": 4338,
"end": 4411
} | class ____:
pass
_ARG_DEFAULT = _ArgDefaultMarker()
| _ArgDefaultMarker |
python | arrow-py__arrow | arrow/locales.py | {
"start": 61241,
"end": 61801
} | class ____(ArabicLocale):
names = ["ar-mr"]
month_names = [
"",
"يناير",
"فبراير",
"مارس",
"إبريل",
"مايو",
"يونيو",
"يوليو",
"أغشت",
"شتمبر",
"أكتوبر",
"نوفمبر",
"دجمبر",
]
month_abbreviations = [
... | MauritaniaArabicLocale |
python | pypa__pipenv | pipenv/installers.py | {
"start": 1804,
"end": 5857
} | class ____(metaclass=ABCMeta):
def __init__(self, project):
self.cmd = self._find_installer()
self.project = project
def __str__(self):
return self.__class__.__name__
@abstractmethod
def _find_installer(self):
pass
@staticmethod
def _find_python_installer_by_na... | Installer |
python | ray-project__ray | python/ray/train/lightning/_lightning_utils.py | {
"start": 5876,
"end": 8081
} | class ____(LightningEnvironment): # noqa: F821
"""Setup Lightning DDP training environment for Ray cluster."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYLIGHTNINGENVIRONMENT, "1")
def world_size(self) -> int:
... | RayLightningEnvironment |
python | pydata__xarray | xarray/tests/test_indexing.py | {
"start": 9415,
"end": 18855
} | class ____:
@pytest.mark.parametrize(
["indexer", "size", "expected"],
(
(4, 5, 4),
(-1, 3, 2),
(slice(None), 4, slice(0, 4, 1)),
(slice(1, -3), 7, slice(1, 4, 1)),
(np.array([-1, 3, -2]), 5, np.array([4, 3, 3])),
),
)
def n... | TestLazyArray |
python | arrow-py__arrow | arrow/locales.py | {
"start": 19477,
"end": 21914
} | class ____(Locale):
names = ["fi", "fi-fi"]
# The finnish grammar is very complex, and its hard to convert
# 1-to-1 to something like English.
past = "{0} sitten"
future = "{0} kuluttua"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "juuri n... | FinnishLocale |
python | kamyu104__LeetCode-Solutions | Python/check-if-move-is-legal.py | {
"start": 73,
"end": 922
} | class ____(object):
def checkMove(self, board, rMove, cMove, color):
"""
:type board: List[List[str]]
:type rMove: int
:type cMove: int
:type color: str
:rtype: bool
"""
def check(board, color, r, c, dr, dc):
l = 2
while 0 <= r ... | Solution |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 25586,
"end": 32003
} | class ____(TimesformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.timesformer = TimesformerModel(config)
# Classifier head
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_la... | TimesformerForVideoClassification |
python | huggingface__transformers | src/transformers/models/zamba2/modular_zamba2.py | {
"start": 41026,
"end": 44522
} | class ____(ZambaHybridLayer):
def __init__(
self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
):
super().__init__(shared_transformer, linear, mamba)
del self.shared_transf
self.shared_transformer = shared_transformer
def... | Zamba2HybridLayer |
python | pytorch__pytorch | torch/backends/__init__.py | {
"start": 830,
"end": 1319
} | class ____:
def __init__(self, getter, setter):
self.getter = getter
self.setter = setter
def __get__(self, obj, objtype):
return self.getter()
def __set__(self, obj, val):
if not flags_frozen():
self.setter(val)
else:
raise RuntimeError(
... | ContextProp |
python | sphinx-doc__sphinx | sphinx/theming.py | {
"start": 15394,
"end": 19934
} | class ____:
__slots__ = (
'stylesheets',
'sidebar_templates',
'pygments_style_default',
'pygments_style_dark',
'options',
)
def __init__(
self,
stylesheets: tuple[str, ...] | None,
sidebar_templates: tuple[str, ...] | None,
pygments_st... | _ConfigFile |
python | django__django | tests/migrations/test_graph.py | {
"start": 18439,
"end": 18986
} | class ____(SimpleTestCase):
def test_node_repr(self):
node = Node(("app_a", "0001"))
self.assertEqual(repr(node), "<Node: ('app_a', '0001')>")
def test_node_str(self):
node = Node(("app_a", "0001"))
self.assertEqual(str(node), "('app_a', '0001')")
def test_dummynode_repr(se... | NodeTests |
python | huggingface__transformers | src/transformers/models/umt5/modeling_umt5.py | {
"start": 73231,
"end": 82064
} | class ____(UMT5PreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config):
super().__init__(config)
self.model_dim = config.d_model
self.shared = nn.Embedding(... | UMT5ForQuestionAnswering |
python | pytransitions__transitions | tests/utils.py | {
"start": 2169,
"end": 2401
} | class ____(Machine):
def __init__(self, states, initial='A'):
self.state = None
Machine.__init__(self, states=states, initial=initial)
@staticmethod
def this_passes():
return True
| InheritedStuff |
python | getsentry__sentry | src/sentry/snuba/outcomes.py | {
"start": 5199,
"end": 5744
} | class ____(Dimension[Outcome]):
def resolve_filter(self, raw_filter: Sequence[str]) -> list[Outcome]:
def _parse_outcome(outcome: str) -> Outcome:
try:
return Outcome.parse(outcome)
except KeyError:
raise InvalidField(f'Invalid outcome: "{outcome}"')
... | OutcomeDimension |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 44249,
"end": 47876
} | class ____(_DOF_estimator):
"""Fast 'geometric' approximation, recommended for large arrays."""
def compute_dz(self):
"""
self.df is computed as weighted average of _triangles sharing a common
node. On each triangle itri f is first assumed linear (= ~f), which
allows to compute ... | _DOF_estimator_geom |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/singledispatch_method.py | {
"start": 120,
"end": 925
} | class ____:
@singledispatch # [singledispatch-method]
@classmethod
def convert_position(cls, position):
pass
@singledispatch # [singledispatch-method]
def move(self, position):
pass
@singledispatchmethod
def place(self, position):
pass
@singledispatch # [sin... | Board |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 2594,
"end": 3134
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_prompts, hidden_size)`):
Encoded geometry prompt features (boxes).
attention_mask (`torch.BoolTensor` of shape `(batch_size, num_prompts)`, *optional*):
Attention mask for geometry prompts where T... | Sam3GeometryEncoderOutput |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 449564,
"end": 450972
} | class ____(Request):
"""
Get the list of task types used in the specified projects
:param projects: The list of projects which tasks will be analyzed. If not
passed or empty then all the company and public tasks will be analyzed
:type projects: Sequence[str]
"""
_service = "tasks"
... | GetTypesRequest |
python | openai__openai-python | src/openai/types/responses/response_text_delta_event.py | {
"start": 265,
"end": 450
} | class ____(BaseModel):
token: Optional[str] = None
"""A possible text token."""
logprob: Optional[float] = None
"""The log probability of this token."""
| LogprobTopLogprob |
python | pyinstaller__pyinstaller | PyInstaller/isolated/_parent.py | {
"start": 6818,
"end": 18005
} | class ____:
"""
Start and connect to a separate Python subprocess.
This is the lowest level of public API provided by this module. The advantage of using this class directly is
that it allows multiple functions to be evaluated in a single subprocess, making it faster than multiple calls to
:func:`c... | Python |
python | dask__distributed | distributed/deploy/subprocess.py | {
"start": 579,
"end": 1417
} | class ____(ProcessInterface, abc.ABC):
process: asyncio.subprocess.Process | None
def __init__(self):
if WINDOWS:
# FIXME: distributed#7434
raise RuntimeError("Subprocess does not support Windows.")
self.process = None
super().__init__()
async def start(self... | Subprocess |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_impl.py | {
"start": 49613,
"end": 49783
} | class ____:
"""See `v1.image.resize` for details."""
BILINEAR = 0
NEAREST_NEIGHBOR = 1
BICUBIC = 2
AREA = 3
@tf_export('image.ResizeMethod', v1=[])
| ResizeMethodV1 |
python | numba__numba | numba/tests/test_funcdesc.py | {
"start": 216,
"end": 790
} | class ____(unittest.TestCase):
def test_module_not_in_namespace(self):
""" Test of trying to run a compiled function
where the module from which the function is being compiled
doesn't exist in the namespace.
"""
filename = 'test.py'
name = 'mypackage'
code = "... | TestModule |
python | openai__openai-python | src/openai/types/responses/file_search_tool.py | {
"start": 478,
"end": 716
} | class ____(BaseModel):
embedding_weight: float
"""The weight of the embedding in the reciprocal ranking fusion."""
text_weight: float
"""The weight of the text in the reciprocal ranking fusion."""
| RankingOptionsHybridSearch |
python | wandb__wandb | tools/graphql_codegen/plugin_utils.py | {
"start": 4374,
"end": 4554
} | class ____(ParsedConstraints):
min: int | None = Field(None, serialization_alias="min_length")
max: int | None = Field(None, serialization_alias="max_length")
| ListConstraints |
python | langchain-ai__langchain | libs/langchain/langchain_classic/indexes/_sql_record_manager.py | {
"start": 2479,
"end": 21158
} | class ____(RecordManager):
"""A SQL Alchemy based implementation of the record manager."""
def __init__(
self,
namespace: str,
*,
engine: Engine | AsyncEngine | None = None,
db_url: None | str | URL = None,
engine_kwargs: dict[str, Any] | None = None,
asy... | SQLRecordManager |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-rearrange-sticks-with-k-sticks-visible.py | {
"start": 33,
"end": 652
} | class ____(object):
def rearrangeSticks(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
MOD = 10**9+7
dp = [[0 for _ in xrange(k+1)] for _ in xrange(2)]
dp[1][1] = 1
for i in xrange(2, n+1):
for j in xrange(1, min(i, k)+1... | Solution |
python | dask__dask | dask/dataframe/dask_expr/diagnostics/_analyze_plugin.py | {
"start": 905,
"end": 1912
} | class ____(SchedulerPlugin):
idempotent: ClassVar[bool] = True
name: ClassVar[str] = "analyze"
_scheduler: Scheduler | None
def __init__(self) -> None:
self._scheduler = None
async def start(self, scheduler: Scheduler) -> None:
self._scheduler = scheduler
scheduler.handlers... | AnalyzePlugin |
python | bokeh__bokeh | src/bokeh/models/nodes.py | {
"start": 3366,
"end": 3622
} | class ____(Model):
""" A base class for various types of coordinate specifications.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| Coordinate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.