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 | run-llama__llama_index | llama-index-core/llama_index/core/service_context_elements/llm_predictor.py | {
"start": 562,
"end": 2100
} | class ____(BaseComponent, DispatcherSpanMixin, ABC):
"""Base LLM Predictor."""
def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
print("here", flush=True)
data = super().model_dump(**kwargs)
data["llm"] = self.llm.to_dict()
return data
def dict(self, **kwargs: Any) -> ... | BaseLLMPredictor |
python | dask__distributed | distributed/pytest_resourceleaks.py | {
"start": 10414,
"end": 16507
} | class ____:
checkers: list[ResourceChecker]
grace_delay: float
mark_failed: bool
# {nodeid: {checkers}}
skip_checkers: dict[str, set[ResourceChecker]]
# {nodeid: {checker: [(before, after)]}}
counters: dict[str, dict[ResourceChecker, list[tuple[Any, Any]]]]
# {nodeid: [(checker, before,... | LeakChecker |
python | faif__python-patterns | patterns/behavioral/observer.py | {
"start": 624,
"end": 1609
} | class ____:
_observers: List[Observer]
def __init__(self) -> None:
"""
Initialize the subject with an empty observer list.
"""
self._observers = []
def attach(self, observer: Observer) -> None:
"""
Attach an observer to the subject.
Args:
... | Subject |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 3813,
"end": 4243
} | class ____(beat.Scheduler):
def __init__(self, *args, **kwargs):
self.sent = []
super().__init__(*args, **kwargs)
def send_task(self, name=None, args=None, kwargs=None, **options):
self.sent.append({'name': name,
'args': args,
'kwargs... | mScheduler |
python | huggingface__transformers | src/transformers/models/udop/processing_udop.py | {
"start": 1171,
"end": 1658
} | class ____(ProcessingKwargs, total=False):
text_kwargs: UdopTextKwargs
_defaults = {
"text_kwargs": {
"add_special_tokens": True,
"padding": False,
"truncation": False,
"stride": 0,
"return_overflowing_tokens": False,
"return_specia... | UdopProcessorKwargs |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_health/asset_freshness_health.py | {
"start": 809,
"end": 2698
} | class ____(LoadableBy[AssetKey]):
"""Maintains the latest freshness state for the asset."""
freshness_state: FreshnessState
updated_timestamp: Optional[float] = None
@property
def health_status(self) -> AssetHealthStatus:
if self.freshness_state == FreshnessState.PASS:
return A... | AssetFreshnessHealthState |
python | getsentry__sentry | src/sentry/snuba/types.py | {
"start": 290,
"end": 1514
} | class ____(Protocol):
def __call__(
self,
selected_columns: list[str],
query: str,
snuba_params: SnubaParams,
equations: list[str] | None = None,
orderby: list[str] | None = None,
offset: int | None = None,
limit: int = 50,
auto_fields: bool = ... | DatasetQuery |
python | cherrypy__cherrypy | cherrypy/test/test_iterator.py | {
"start": 51,
"end": 262
} | class ____(object):
created = 0
datachunk = 'butternut squash' * 256
@classmethod
def incr(cls):
cls.created += 1
@classmethod
def decr(cls):
cls.created -= 1
| IteratorBase |
python | django__django | tests/dates/models.py | {
"start": 65,
"end": 315
} | class ____(models.Model):
title = models.CharField(max_length=100)
pub_date = models.DateField()
pub_datetime = models.DateTimeField(default=timezone.now)
categories = models.ManyToManyField("Category", related_name="articles")
| Article |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 3373,
"end": 3467
} | class ____(ASTNode):
target: ASTNode
op: ASTNode
value: ASTNode
@dataclass
| AugAssign |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass4.py | {
"start": 1712,
"end": 1803
} | class ____:
a: str = field(init=False, default="s")
b: bool = field()
@dataclass
| DC10 |
python | realpython__materials | directory-tree-generator-python/source_code_final/rptree/rptree.py | {
"start": 826,
"end": 2561
} | class ____:
def __init__(self, root_dir, dir_only=False):
self._root_dir = pathlib.Path(root_dir)
self._dir_only = dir_only
self._tree = []
def build_tree(self):
self._tree_head()
self._tree_body(self._root_dir)
return self._tree
def _tree_head(self):
... | _TreeGenerator |
python | huggingface__transformers | src/transformers/models/vitpose_backbone/modeling_vitpose_backbone.py | {
"start": 15101,
"end": 17477
} | class ____(VitPoseBackbonePreTrainedModel, BackboneMixin):
def __init__(self, config: VitPoseBackboneConfig):
super().__init__(config)
super()._init_backbone(config)
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
self.embeddings = VitPoseBackbo... | VitPoseBackbone |
python | pennersr__django-allauth | allauth/mfa/webauthn/forms.py | {
"start": 2393,
"end": 3561
} | class ____(forms.Form):
credential = forms.JSONField(required=True, widget=forms.HiddenInput)
reauthenticated = False
passwordless = False
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
def clean_credential(self):
crede... | AuthenticateWebAuthnForm |
python | doocs__leetcode | solution/0800-0899/0807.Max Increase to Keep City Skyline/Solution.py | {
"start": 0,
"end": 338
} | class ____:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
row_max = [max(row) for row in grid]
col_max = [max(col) for col in zip(*grid)]
return sum(
min(row_max[i], col_max[j]) - x
for i, row in enumerate(grid)
for j, x in enumerate(r... | Solution |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 1099,
"end": 1271
} | class ____(TypedDict):
organization_id: int
project_id: int
config: AnomalyDetectionConfig
context: AlertInSeer | list[TimeSeriesPoint]
| DetectAnomaliesRequest |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 35193,
"end": 35651
} | class ____(Interface):
virtual_path = Attribute(
'The virtual url path of the resource as a string.'
)
physical_path = Attribute(
'The physical url path of the resource as a string.'
)
virtual_path_tuple = Attribute(
'The virtual url path of the resource as a tuple. (New in ... | IResourceURL |
python | pypa__pip | src/pip/_internal/operations/install/wheel.py | {
"start": 14279,
"end": 14858
} | class ____(InstallationError):
def __init__(self, entry_point: str) -> None:
super().__init__(
f"Invalid script entry point: {entry_point} - A callable "
"suffix is required. See https://packaging.python.org/"
"specifications/entry-points/#use-for-scripts for more "
... | MissingCallableSuffix |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_micro_benchmarks.py | {
"start": 44910,
"end": 47362
} | class ____:
@pytest.fixture(scope='class')
def validator(self):
return SchemaValidator(core_schema.decimal_schema())
@pytest.fixture(scope='class')
def pydantic_validator(self):
Decimal = decimal.Decimal
def to_decimal(v: str) -> decimal.Decimal:
try:
... | TestBenchmarkDecimal |
python | Netflix__metaflow | metaflow/_vendor/importlib_metadata/_meta.py | {
"start": 114,
"end": 758
} | class ____(Protocol):
def __len__(self) -> int:
... # pragma: no cover
def __contains__(self, item: str) -> bool:
... # pragma: no cover
def __getitem__(self, key: str) -> str:
... # pragma: no cover
def __iter__(self) -> Iterator[str]:
... # pragma: no cover
... | PackageMetadata |
python | matplotlib__matplotlib | lib/matplotlib/_type1font.py | {
"start": 960,
"end": 2095
} | class ____:
"""
A token in a PostScript stream.
Attributes
----------
pos : int
Position, i.e. offset from the beginning of the data.
raw : str
Raw text of the token.
kind : str
Description of the token (for debugging or testing).
"""
__slots__ = ('pos', 'raw... | _Token |
python | great-expectations__great_expectations | tests/expectations/fixtures/expect_column_values_to_equal_three.py | {
"start": 3412,
"end": 6715
} | class ____(
ExpectColumnValuesToEqualThree__SecondIteration
):
@classmethod
@renderer(renderer_type="renderer.question")
def _question_renderer(cls, configuration, result=None, runtime_configuration=None):
column = configuration.kwargs.get("column")
mostly = configuration.kwargs.get("mos... | ExpectColumnValuesToEqualThree__ThirdIteration |
python | doocs__leetcode | solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/Solution.py | {
"start": 0,
"end": 631
} | class ____:
def sumImbalanceNumbers(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
sl = SortedList()
cnt = 0
for j in range(i, n):
k = sl.bisect_left(nums[j])
h = k - 1
if h >= 0 and ... | Solution |
python | pypa__pip | tests/unit/test_resolution_legacy_resolver.py | {
"start": 4732,
"end": 8804
} | class ____:
"""
Test _check_dist_requires_python().
"""
def test_compatible(self, caplog: pytest.LogCaptureFixture) -> None:
"""
Test a Python version compatible with the dist's Requires-Python.
"""
caplog.set_level(logging.DEBUG)
dist = make_fake_dist(requires_p... | TestCheckDistRequiresPython |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 35744,
"end": 36024
} | class ____(ReferenceInlineProcessor):
"""Short form of reference: `[google]`. """
def evalId(self, data: str, index: int, text: str) -> tuple[str, int, bool]:
"""Evaluate the id of `[ref]`. """
return text.lower(), index, True
| ShortReferenceInlineProcessor |
python | realpython__materials | python-unittest/test_calculations.py | {
"start": 689,
"end": 2975
} | class ____(unittest.TestCase):
def test_mean(self):
self.assertEqual(mean([1, 2, 3, 4, 5, 6]), 3.5)
def test_median_odd(self):
self.assertEqual(median([1, 3, 3, 6, 7, 8, 9]), 6)
def test_median_even(self):
self.assertEqual(median([1, 2, 3, 4, 5, 6, 8, 9]), 4.5)
def test_median... | TestStatisticalOperations |
python | django__django | tests/properties/models.py | {
"start": 131,
"end": 564
} | class ____(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def _set_full_name(self, combined_name):
self.first_name, self.last_name = combined_name.split... | Person |
python | pytorch__pytorch | torchgen/model.py | {
"start": 80738,
"end": 84158
} | class ____:
# NB: I didn't put kwarg_only as a boolean field here, unlike
# c10::Argument, so that printing works correctly
name: str
type: Type
default: str | None
# The semantics of the annotation field are a little strange.
#
# Alias annotations parametrize Tensors (since Tensors ar... | Argument |
python | keon__algorithms | algorithms/tree/bst/bst.py | {
"start": 159,
"end": 286
} | class ____(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
| Node |
python | networkx__networkx | networkx/algorithms/community/tests/test_centrality.py | {
"start": 441,
"end": 2932
} | class ____:
"""Unit tests for the
:func:`networkx.algorithms.community.centrality.girvan_newman`
function.
"""
def test_no_edges(self):
G = nx.empty_graph(3)
communities = list(nx.community.girvan_newman(G))
assert len(communities) == 1
validate_communities(communit... | TestGirvanNewman |
python | PyCQA__pylint | tests/functional/u/unnecessary/unnecessary_dunder_call.py | {
"start": 1282,
"end": 1345
} | class ____:
def __new__(cls):
object.__new__(cls)
| Bar1 |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_arithmatex.py | {
"start": 3762,
"end": 4989
} | class ____(util.MdCase):
"""Test hang cases."""
def test_hang_dollar(self):
"""
We are just making sure this works.
Previously this pattern would hang. It isn't supposed to match due to the space before the last dollar,
but it definitely shouldn't hang the process.
"""
... | TestArithmatexHang |
python | pdm-project__pdm | src/pdm/resolver/providers.py | {
"start": 1796,
"end": 16559
} | class ____(AbstractProvider[Requirement, Candidate, str]):
def __init__(
self,
repository: BaseRepository,
allow_prereleases: bool | None = None,
overrides: dict[str, str] | None = None,
direct_minimal_versions: bool = False,
*,
locked_repository: LockedReposi... | BaseProvider |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 49465,
"end": 49678
} | class ____(BatchPointwiseOpsPostGradFusion):
def __init__(self, **kwargs) -> None:
super().__init__(aten.relu.default, **kwargs)
@register_fusion("batch_aten_add", pre_grad=False)
| BatchReLuPostGradFusion |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 32196,
"end": 32986
} | class ____(unittest.TestCase):
def _callFUT(self, s):
from pyramid.traversal import quote_path_segment
return quote_path_segment(s)
def test_unicode(self):
la = text_(b'/La Pe\xc3\xb1a', 'utf-8')
result = self._callFUT(la)
self.assertEqual(result, '%2FLa%20Pe%C3%B1a')
... | QuotePathSegmentTests |
python | google__jax | tests/layout_test.py | {
"start": 1032,
"end": 24889
} | class ____(jtu.JaxTestCase):
def test_auto_layout(self):
mesh = jtu.create_mesh((2, 2), ('x', 'y'))
shape1 = (128, 128)
shape2 = (128, 128)
s1 = NamedSharding(mesh, P('x', 'y'))
s2 = NamedSharding(mesh, P('x'))
def apply(x, y):
return x.T, y.T
def init(x, y):
return x * 2, y... | LayoutTest |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 50095,
"end": 50719
} | class ____(BlenderbotSmallPreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
used in combination with the [`EncoderDecoderModel`] framework.
"""
def __init__(self, config):
super().__init__(config)
se... | BlenderbotSmallDecoderWrapper |
python | django__django | django/db/backends/sqlite3/_functions.py | {
"start": 14299,
"end": 14351
} | class ____(list):
step = list.append
| ListAggregate |
python | explosion__spaCy | spacy/schemas.py | {
"start": 17287,
"end": 18311
} | class ____(BaseModel):
# fmt: off
max_epochs: StrictInt = Field(..., title="Maximum number of epochs to train for")
dropout: StrictFloat = Field(..., title="Dropout rate")
n_save_every: Optional[StrictInt] = Field(..., title="Saving additional temporary model after n batches within an epoch")
n_save... | ConfigSchemaPretrain |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py | {
"start": 34889,
"end": 35044
} | class ____(ScatterNdDeterminismTest,
ScatterNdNonAliasingAddTest):
pass
| ScatterNdNonAliasingAddDeterminismTest |
python | openai__openai-python | src/openai/types/webhooks/batch_expired_webhook_event.py | {
"start": 324,
"end": 756
} | class ____(BaseModel):
id: str
"""The unique ID of the event."""
created_at: int
"""The Unix timestamp (in seconds) of when the batch API request expired."""
data: Data
"""Event data payload."""
type: Literal["batch.expired"]
"""The type of the event. Always `batch.expired`."""
o... | BatchExpiredWebhookEvent |
python | dagster-io__dagster | python_modules/libraries/dagster-tableau/dagster_tableau/translator.py | {
"start": 1961,
"end": 2204
} | class ____:
"""A record representing a piece of content in Tableau.
Includes the content's type and data as returned from the API.
"""
content_type: TableauContentType
properties: Mapping[str, Any]
@record
| TableauContentData |
python | sanic-org__sanic | sanic/constants.py | {
"start": 63,
"end": 275
} | class ____(UpperStrEnum):
"""HTTP methods that are commonly used."""
GET = auto()
POST = auto()
PUT = auto()
HEAD = auto()
OPTIONS = auto()
PATCH = auto()
DELETE = auto()
| HTTPMethod |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 98318,
"end": 98553
} | class ____(Structure):
_fields_ = [("device", c_nvmlDevice_t),
("id", c_uint),
("profileId", c_uint),
("placement", c_nvmlGpuInstancePlacement_t)
]
| c_nvmlGpuInstanceInfo_t |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 91938,
"end": 95760
} | class ____(Request):
"""
Get user and system tags used for the tasks under the specified projects
:param include_system: If set to 'true' then the list of the system tags is
also returned. The default value is 'false'
:type include_system: bool
:param projects: The list of projects under wh... | GetTaskTagsRequest |
python | scikit-learn__scikit-learn | sklearn/semi_supervised/_label_propagation.py | {
"start": 17049,
"end": 21709
} | class ____(BaseLabelPropagation):
"""LabelSpreading model for semi-supervised learning.
This model is similar to the basic Label Propagation algorithm,
but uses affinity matrix based on the normalized graph Laplacian
and soft clamping across the labels.
Read more in the :ref:`User Guide <label_pro... | LabelSpreading |
python | gevent__gevent | src/gevent/tests/lock_tests.py | {
"start": 6490,
"end": 8499
} | class ____(BaseTestCase):
"""
Tests for Event objects.
"""
def eventtype(self):
raise NotImplementedError()
def test_is_set(self):
evt = self.eventtype()
self.assertFalse(evt.is_set())
evt.set()
self.assertTrue(evt.is_set())
evt.set()
self.as... | EventTests |
python | pyca__cryptography | src/cryptography/hazmat/primitives/ciphers/modes.py | {
"start": 2715,
"end": 3144
} | class ____(ModeWithNonce):
name = "CTR"
def __init__(self, nonce: utils.Buffer):
utils._check_byteslike("nonce", nonce)
self._nonce = nonce
@property
def nonce(self) -> utils.Buffer:
return self._nonce
def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
... | CTR |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 46241,
"end": 46341
} | class ____(generics.RetrieveAPIView):
queryset = BasicModel.objects.all()
| BasicNamingCollisionView |
python | huggingface__transformers | src/transformers/modeling_utils.py | {
"start": 41299,
"end": 44908
} | class ____:
"""
Base utilities to regroup getters and setters for embeddings.
Introduces the `input_layer_embed` attribute, which indicates
where the input embeddings come from and where they
should be set.
"""
_input_embed_layer = "embed_tokens" # default layer that holds input embeddings... | EmbeddingAccessMixin |
python | sympy__sympy | sympy/core/facts.py | {
"start": 10887,
"end": 17328
} | class ____:
"""Rules that describe how to deduce facts in logic space
When defined, these rules allow implications to quickly be determined
for a set of facts. For this precomputed deduction tables are used.
see `deduce_all_facts` (forward-chaining)
Also it is possible to gather prer... | FactRules |
python | automl__auto-sklearn | autosklearn/ensemble_building/run.py | {
"start": 193,
"end": 5336
} | class ____:
"""Class for storing information about a run used during ensemble building.
Note
----
This is for internal use by the EnsembleBuilder and not for general usage.
"""
# For matching prediction files
RE_MODEL_PREDICTION_FILE = (
r"^predictions_ensemble_([0-9]*)_([0-9]*)_([... | Run |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 4229,
"end": 4396
} | class ____(GreatExpectationsError):
def __init__(self, message: str):
super().__init__(f"Bad input to build_batch_request: {message}")
| BuildBatchRequestError |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 2863,
"end": 3105
} | class ____(TimeoutError, RequestError):
"""Raised when a socket timeout occurs while receiving data from a server"""
pass
# This timeout error does not have a URL attached and needs to inherit from the
# base HTTPError
| ReadTimeoutError |
python | giampaolo__psutil | tests/test_windows.py | {
"start": 13955,
"end": 21806
} | class ____(WindowsTestCase):
@classmethod
def setUpClass(cls):
cls.pid = spawn_subproc().pid
@classmethod
def tearDownClass(cls):
terminate(cls.pid)
def test_issue_24(self):
p = psutil.Process(0)
with pytest.raises(psutil.AccessDenied):
p.kill()
def... | TestProcess |
python | walkccc__LeetCode | solutions/1982. Find Array Given Subset Sums/1982.py | {
"start": 0,
"end": 1164
} | class ____:
def recoverArray(self, n: int, sums: list[int]) -> list[int]:
def recover(sums: list[int]) -> list[int]:
if len(sums) == 1:
return []
count = collections.Counter(sums)
# Either num or -num must be in the final array.
# num + sumsExcludingNum = sumsIncludingNum
#... | Solution |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 22210,
"end": 22511
} | class ____(TreeArgumentsWrapper):
def __init__(self, instance, arguments):
super().__init__(arguments)
self.instance = instance
def unpack(self, func=None):
yield None, LazyKnownValue(self.instance)
yield from self._wrapped_arguments.unpack(func)
| InstanceArguments |
python | run-llama__llama_index | llama-index-core/llama_index/core/selectors/llm_selectors.py | {
"start": 1744,
"end": 4505
} | class ____(BaseSelector):
"""
LLM single selector.
LLM-based selector that chooses one out of many options.
Args:
LLM (LLM): An LLM.
prompt (SingleSelectPrompt): A LLM prompt for selecting one out of many options.
"""
def __init__(
self,
llm: LLM,
prom... | LLMSingleSelector |
python | google__pytype | pytype/tests/test_fiddle_overlay.py | {
"start": 15941,
"end": 17973
} | class ____(test_base.BaseTest):
"""Tests for Config wrapping a function."""
def test_basic(self):
# Config values wrapping non-dataclasses are currently treated as Any
with self.DepTree([("fiddle.pyi", _FIDDLE_PYI)]):
self.Check("""
import fiddle
def Simple(x: int, y: str):
... | TestFunctionConfig |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_group_notes.py | {
"start": 653,
"end": 3855
} | class ____(APITestCase):
def test_simple(self) -> None:
group = self.group
activity = Activity.objects.create(
group=group,
project=group.project,
type=ActivityType.NOTE.value,
user_id=self.user.id,
data={"text": "hello world"},
)
... | GroupNoteTest |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 91882,
"end": 91940
} | class ____(UserDefinedObjectVariable):
pass
| RandomVariable |
python | walkccc__LeetCode | solutions/1964. Find the Longest Valid Obstacle Course at Each Position/1964.py | {
"start": 0,
"end": 568
} | class ____:
# Similar to 300. Longest Increasing Subsequence
def longestObstacleCourseAtEachPosition(
self, obstacles: list[int],
) -> list[int]:
ans = []
# tails[i] := the minimum tail of all the increasing subsequences having
# length i + 1
tails = []
for obstacle in obstacles:
... | Solution |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_jira.py | {
"start": 1025,
"end": 8406
} | class ____(TestCase):
factory = RequestFactory()
path_base = f"{IntegrationClassification.integration_prefix}jira"
def get_response(self, req: HttpRequest) -> HttpResponse:
return HttpResponse(status=200, content="passthrough")
def get_integration(self) -> Integration:
self.organizatio... | JiraRequestParserTest |
python | django__django | tests/foreign_object/models/person.py | {
"start": 48,
"end": 197
} | class ____(models.Model):
# Table Column Fields
name = models.CharField(max_length=50)
def __str__(self):
return self.name
| Country |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE794.py | {
"start": 278,
"end": 407
} | class ____(BaseModel):
bar: str = StringField()
foo: bool = BooleanField()
# ...
bar = StringField() # PIE794
| User |
python | wandb__wandb | wandb/vendor/pygments/lexers/parsers.py | {
"start": 25866,
"end": 26222
} | class ____(DelegatingLexer):
"""
A lexer for `Treetop <http://treetop.rubyforge.org/>`_ grammars.
.. versionadded:: 1.6
"""
name = 'Treetop'
aliases = ['treetop']
filenames = ['*.treetop', '*.tt']
def __init__(self, **options):
super(TreetopLexer, self).__init__(RubyLexer, Tre... | TreetopLexer |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 6579,
"end": 7843
} | class ____(HostConfig, metaclass=abc.ABCMeta):
"""Base class for remote host configuration."""
name: t.Optional[str] = None
provider: t.Optional[str] = None
arch: t.Optional[str] = None
@property
def platform(self) -> str:
"""The name of the platform."""
return self.name.partit... | RemoteConfig |
python | huggingface__transformers | src/transformers/models/marian/modeling_marian.py | {
"start": 56225,
"end": 56810
} | class ____(MarianPreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
used in combination with the [`EncoderDecoderModel`] framework.
"""
def __init__(self, config):
super().__init__(config)
self.decode... | MarianDecoderWrapper |
python | pypa__hatch | tests/backend/builders/test_binary.py | {
"start": 8395,
"end": 25679
} | class ____:
def test_default(self, hatch, temp_dir, mocker):
subprocess_run = mocker.patch("subprocess.run", side_effect=cargo_install)
project_name = "My.App"
with temp_dir.as_cwd():
result = hatch("new", project_name)
assert result.exit_code == 0, result.output
... | TestBuildBootstrap |
python | PrefectHQ__prefect | src/integrations/prefect-azure/tests/experimental/bundles/test_upload.py | {
"start": 1028,
"end": 5696
} | class ____:
"""Tests for the upload_bundle_to_azure_blob_storage function."""
async def test_upload_bundle_with_credentials_block(
self, tmp_bundle_file: Path, mock_blob_storage_credentials: MagicMock
) -> None:
"""Test uploading a bundle using a credentials block."""
container = "t... | TestUploadBundleToAzureBlobStorage |
python | pytorch__pytorch | test/nn/test_dropout.py | {
"start": 627,
"end": 3491
} | class ____(NNTestCase):
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = True
def _test_alpha_dropout(self, cls, input):
mean = input.mean()
std = input.std()
for p in [0.2, 0.5, 0.8]:
module = cls(p)
input_var = input.detach().clone().require... | TestDropoutNN |
python | huggingface__transformers | src/transformers/models/siglip2/configuration_siglip2.py | {
"start": 9776,
"end": 12737
} | class ____(PreTrainedConfig):
r"""
[`Siglip2Config`] is the configuration class to store the configuration of a [`Siglip2Model`]. It is used to
instantiate a Siglip2 model according to the specified arguments, defining the text model and vision model configs.
Instantiating a configuration with the defau... | Siglip2Config |
python | pypa__hatch | docs/.hooks/render_default_test_env.py | {
"start": 1435,
"end": 1788
} | class ____(Preprocessor):
def run(self, lines): # noqa: PLR6301
return (
"\n".join(lines)
.replace(MARKER_DEPENDENCIES, get_dependencies_toml())
.replace(MARKER_MATRIX, get_matrix_toml())
.replace(MARKER_SCRIPTS, get_scripts_toml())
.splitlines()
... | TestEnvDefaultsPreprocessor |
python | jazzband__django-simple-history | simple_history/template_utils.py | {
"start": 855,
"end": 6325
} | class ____:
"""
Class containing various utilities for formatting the template context for
a historical record.
"""
DEFAULT_MAX_DISPLAYED_DELTA_CHANGE_CHARS: Final = 100
def __init__(
self,
model: type[Model],
historical_record: HistoricalChanges,
*,
max... | HistoricalRecordContextHelper |
python | huggingface__transformers | tests/models/mgp_str/test_modeling_mgp_str.py | {
"start": 4108,
"end": 7915
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": MgpstrForSceneTextRecognition, "image-feature-extraction": MgpstrModel}
if is_torch_availab... | MgpstrModelTest |
python | pytorch__pytorch | torch/distributed/_tools/mem_tracker.py | {
"start": 4639,
"end": 11633
} | class ____:
"""
Manages memory statistics and device attributes for tensor storages.
"""
def __init__(
self, size: int, element_size: int, device: torch.device, reftype: _RefType
) -> None:
"""
Initializes the ``_WeakRefInfo`` object with tensor storage properties.
... | _WeakRefInfo |
python | Textualize__textual | docs/examples/guide/content/renderables.py | {
"start": 538,
"end": 883
} | class ____(App):
"""App to demonstrate Rich renderables in Textual."""
def compose(self) -> ComposeResult:
with open(__file__) as self_file:
code = self_file.read()
code_view = CodeView()
code_view.code = code
yield code_view
if __name__ == "__main__":
app = Co... | CodeApp |
python | pytorch__pytorch | torch/masked/maskedtensor/_ops_refs.py | {
"start": 1803,
"end": 2739
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, input):
if not is_masked_tensor(input):
raise ValueError("MaskedToDense forward: input must be a MaskedTensor.")
if input.layout == torch.strided:
return input
... | _MaskedToDense |
python | doocs__leetcode | lcp/LCP 10. 二叉树任务调度/Solution.py | {
"start": 0,
"end": 356
} | class ____:
def minimalExecTime(self, root: TreeNode) -> float:
def dfs(root: TreeNode) -> Tuple[int, int]:
if not root:
return 0, 0
s1, t1 = dfs(root.left)
s2, t2 = dfs(root.right)
return s1 + s2 + root.val, max(t1, t2, (s1 + s2) / 2) + root.v... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vision.py | {
"start": 7911,
"end": 8671
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook")
def test_minimal_green_path(self, mock_hook):
mock_hook.return_value.get_product.return_value = {}
op = CloudVisionGetProductOperator(location=LOCATION_TEST, product_id=PRODUCT_ID_TEST, task_id="id")
... | TestCloudVisionProductGet |
python | getsentry__sentry | src/sentry/integrations/jira_server/actions/create_ticket.py | {
"start": 371,
"end": 1559
} | class ____(TicketEventAction):
id = "sentry.integrations.jira_server.notify_action.JiraServerCreateTicketAction"
label = "Create a Jira Server issue in {integration} with these "
ticket_type = "a Jira Server issue"
link = "https://docs.sentry.io/product/integrations/issue-tracking/jira/#issue-sync"
... | JiraServerCreateTicketAction |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 32578,
"end": 34445
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=T... | PatchTSTModelOutput |
python | celery__celery | celery/exceptions.py | {
"start": 6540,
"end": 6603
} | class ____(CeleryError):
"""Task related errors."""
| TaskError |
python | kamyu104__LeetCode-Solutions | Python/delete-nodes-and-return-forest.py | {
"start": 233,
"end": 1034
} | class ____(object):
def delNodes(self, root, to_delete):
"""
:type root: TreeNode
:type to_delete: List[int]
:rtype: List[TreeNode]
"""
def delNodesHelper(to_delete_set, root, is_root, result):
if not root:
return None
is_delete... | Solution |
python | pytorch__pytorch | test/test_optim.py | {
"start": 1880,
"end": 101851
} | class ____(TestCase):
"""
This test class validates the core optimizers and is structured as the correctness of:
- The update algorithms (forloop implementation)
* Every optimizer's algorithm is most readably implemented through a big for-loop
over all the parameters, which is what we refe... | TestOptimRenewed |
python | pytorch__pytorch | test/quantization/core/test_quantized_functional.py | {
"start": 542,
"end": 10477
} | class ____(QuantizationTestCase):
def test_relu_api(self):
X = torch.arange(-5, 5, dtype=torch.float)
scale = 2.0
zero_point = 1
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point, dtype=torch.quint8)
qY = torch.relu(qX)
qY_hat = F.relu(qX)
s... | TestQuantizedFunctionalOps |
python | gevent__gevent | src/greentest/3.14/test__interpreters.py | {
"start": 14172,
"end": 16439
} | class ____(TestBase):
def setUp(self):
super().setUp()
self.id = _interpreters.create()
def test_signatures(self):
# See https://github.com/python/cpython/issues/126654
msg = r'_interpreters.exec\(\) argument 3 must be dict, not int'
with self.assertRaisesRegex(TypeError... | CommonTests |
python | getsentry__sentry-python | sentry_sdk/client.py | {
"start": 5282,
"end": 7806
} | class ____:
"""
.. versionadded:: 2.0.0
The basic definition of a client that is used for sending data to Sentry.
"""
spotlight = None # type: Optional[SpotlightClient]
def __init__(self, options=None):
# type: (Optional[Dict[str, Any]]) -> None
self.options = options if opti... | BaseClient |
python | joblib__joblib | joblib/compressor.py | {
"start": 2278,
"end": 3443
} | class ____:
"""A wrapper around a compressor file object.
Attributes
----------
obj: a file-like object
The object must implement the buffer interface and will be used
internally to compress/decompress the data.
prefix: bytestring
A bytestring corresponding to the magic numb... | CompressorWrapper |
python | huggingface__transformers | src/transformers/models/aria/modeling_aria.py | {
"start": 5819,
"end": 8267
} | class ____(nn.Module):
"""
Aria Projector module.
This module projects vision features into the language model's embedding space, enabling interaction between vision and language components.
Args:
config (`AriaConfig`):
Configuration object for the model.
"""
def __init__(... | AriaProjector |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/colorbar/_title.py | {
"start": 233,
"end": 3999
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d.colorbar"
_path_str = "histogram2d.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
... | Title |
python | pytorch__pytorch | test/package/test_dependency_hooks.py | {
"start": 329,
"end": 3970
} | class ____(PackageTestCase):
"""Dependency management hooks API tests.
- register_mock_hook()
- register_extern_hook()
"""
def test_single_hook(self):
buffer = BytesIO()
my_externs = set()
def my_extern_hook(package_exporter, module_name):
my_externs.add(module... | TestDependencyHooks |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/run_request.py | {
"start": 1927,
"end": 2595
} | class ____(NamedTuple("_SkipReason", [("skip_message", PublicAttr[Optional[str]])])):
"""Represents a skipped evaluation, where no runs are requested. May contain a message to indicate
why no runs were requested.
Args:
skip_message (Optional[str]): A message displayed in the Dagster UI for why this... | SkipReason |
python | patrys__httmock | httmock.py | {
"start": 3991,
"end": 7776
} | class ____(object):
"""
Acts as a context manager to allow mocking
"""
STATUS_CODE = 200
def __init__(self, *handlers):
self.handlers = handlers
def __enter__(self):
self._real_session_send = requests.Session.send
self._real_session_prepare_request = requests.Session.pr... | HTTMock |
python | jazzband__django-oauth-toolkit | tests/test_oauth2_validators.py | {
"start": 1688,
"end": 17433
} | class ____(TransactionTestCase):
def setUp(self):
self.user = UserModel.objects.create_user("user", "test@example.com", "123456")
self.request = mock.MagicMock(wraps=Request)
self.request.user = self.user
self.request.grant_type = "not client"
self.validator = OAuth2Validator... | TestOAuth2Validator |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 680134,
"end": 680619
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "repository", "teams")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
repository = sgqlc.types.Field("Repository", graph... | UpdateTeamsRepositoryPayload |
python | apache__airflow | task-sdk/tests/task_sdk/api/test_client.py | {
"start": 54722,
"end": 58990
} | class ____:
def test_add_response(self) -> None:
ti_id = uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path in (f"/hitlDetails/{ti_id}"):
return httpx.Response(
status_code=201,
json={
... | TestHITLOperations |
python | ApeWorX__ape | src/ape_ethereum/trace.py | {
"start": 21234,
"end": 27441
} | class ____(Trace):
tx: dict
"""
Transaction data. Is a dictionary to allow traces to easily
be created near sending the request.
"""
arguments: list[Any] = []
"""
Remaining eth-call arguments, minus the transaction.
"""
call_trace_approach: TraceApproach = TraceApproach.GETH_ST... | CallTrace |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 943830,
"end": 944590
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for RepositoryRuleset."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("RepositoryRulesetEdge"), graphql_name="edges")
"""A list of edges."""... | RepositoryRulesetConnection |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/model_tests/model_handler.py | {
"start": 12622,
"end": 14722
} | class ____(_ModelHandlerBase):
"""Runs a model in TF2."""
@property
def graph_func(self):
try:
return self._graph_func
except:
graph_func = load_graph_func(
saved_model_dir=self.model_config.saved_model_dir,
saved_model_tags=self.model_config.saved_model_tags,
sa... | ModelHandlerV2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.