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 | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver37.py | {
"start": 144,
"end": 409
} | class ____(Generic[A]): ...
def func1(x: A) -> A: ...
def func2(x: Gen[A], y: A) -> Gen[Gen[A]]: ...
def func3(x: Gen[Gen[A]]) -> Gen[A]:
return func4(x, func1, func2)
def func4(x: Gen[A], id_: Callable[[B], B], step: Callable[[A, B], Gen[A]]) -> A: ...
| Gen |
python | walkccc__LeetCode | solutions/3185. Count Pairs That Form a Complete Day II/3185.py | {
"start": 0,
"end": 276
} | class ____:
# Same as 3184. Count Pairs That Form a Complete Day I
def countCompleteDayPairs(self, hours: list[int]) -> int:
ans = 0
count = [0] * 24
for hour in hours:
ans += count[(24 - hour % 24) % 24]
count[hour % 24] += 1
return ans
| Solution |
python | pytorch__pytorch | test/export/test_passes.py | {
"start": 2403,
"end": 3047
} | class ____(OperatorSupport):
def is_node_supported(self, submodules, node: torch.fx.Node) -> bool:
return node.op == "call_function" and node.target in {torch.ops.aten.add.Tensor}
def _to_partition_names(partitions: list[Partition]) -> list[set[str]]:
return [{n.name for n in p.nodes} for p in partiti... | _AtenAddOperatorSupport |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 14492,
"end": 16297
} | class ____(TestCase, RowDeprecationTestMixin):
def setUp(self):
self.value = 11.111
self.widget = widgets.FloatWidget()
self.widget_coerce_to_string = widgets.FloatWidget(coerce_to_string=True)
def test_clean(self):
self.assertEqual(self.widget.clean(11.111), self.value)
@o... | FloatWidgetTest |
python | django__django | django/utils/xmlutils.py | {
"start": 158,
"end": 1172
} | class ____(XMLGenerator):
def addQuickElement(self, name, contents=None, attrs=None):
"Convenience method for adding an element with no children"
if attrs is None:
attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents)
... | SimplerXMLGenerator |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/auto_width_input.py | {
"start": 95,
"end": 439
} | class ____(App[None]):
CSS = """
Input.auto {
width: auto;
max-width: 100%;
}
"""
def compose(self) -> ComposeResult:
yield Header()
yield Input(placeholder="This has auto width", classes="auto")
yield Footer()
if __name__ == "__main__":
InputWidthAutoA... | InputWidthAutoApp |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels20.py | {
"start": 315,
"end": 1472
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels20.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/plugins/providers/base.py | {
"start": 595,
"end": 3045
} | class ____:
auth_provider: str | None = None
logger = logging.getLogger(__name__)
def link_auth(self, user, organization, data):
usa = usersocialauth_service.get_one_or_none(
filter={
"id": data["default_auth_id"],
"user_id": user.id,
"pro... | ProviderMixin |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/sensors/test_spark_kubernetes.py | {
"start": 20522,
"end": 33567
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(conn_id="kubernetes_default", conn_type="kubernetes", extra=json.dumps({}))
)
create_connection_without_db(
Connection(
... | TestSparkKubernetesSensor |
python | mlflow__mlflow | dev/update_ml_package_versions.py | {
"start": 901,
"end": 11032
} | class ____:
version: str
upload_time: datetime
def get_package_version_infos(package_name: str) -> list[VersionInfo]:
url = f"https://pypi.python.org/pypi/{package_name}/json"
for _ in range(5): # Retry up to 5 times
try:
with urllib.request.urlopen(url) as res:
da... | VersionInfo |
python | rq__rq | tests/test_cli.py | {
"start": 34857,
"end": 38688
} | class ____(CLITestCase):
"""Tests the `rq cron` CLI command."""
def setUp(self):
# Call parent setUp first to initialize self.connection, self.redis_url etc.
super().setUp()
# Path to the existing cron config file
current_dir = os.path.dirname(__file__)
self.cron_config... | CronCLITestCase |
python | realpython__materials | inheritance-and-composition/inheritance/disgruntled.py | {
"start": 0,
"end": 166
} | class ____:
def __init__(self, id, name):
self.id = id
self.name = name
def calculate_payroll(self):
return 1_000_000
| DisgruntledEmployee |
python | realpython__materials | python-basic-data-types/point.py | {
"start": 0,
"end": 267
} | class ____:
def __init__(self, x, y):
self.x = x
self.y = y
def __bool__(self):
if self.x == self.y == 0:
return False
return True
origin = Point(0, 0)
print(bool(origin))
point = Point(2, 4)
print(bool(point))
| Point |
python | astropy__astropy | astropy/coordinates/baseframe.py | {
"start": 15069,
"end": 91942
} | class ____(MaskableShapedLikeNDArray):
"""
The base class for coordinate frames.
This class is intended to be subclassed to create instances of specific
systems. Subclasses can implement the following attributes:
* `default_representation`
A subclass of `~astropy.coordinates.BaseRepresent... | BaseCoordinateFrame |
python | python-poetry__poetry | src/poetry/inspection/info.py | {
"start": 1544,
"end": 19367
} | class ____:
def __init__(
self,
*,
name: str | None = None,
version: str | None = None,
summary: str | None = None,
requires_dist: list[str] | None = None,
requires_python: str | None = None,
files: Sequence[Mapping[str, str]] | None = None,
ya... | PackageInfo |
python | pdm-project__pdm | src/pdm/_types.py | {
"start": 316,
"end": 3569
} | class ____:
"""Private dataclass to be subclassed"""
config_prefix: str
name: str
url: str | None = None
username: str | None = None
password: str | None = dc.field(default=None, repr=False)
verify_ssl: bool | None = None
type: str | None = None
ca_certs: str | None = None
clie... | RepositoryConfig |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 10146,
"end": 10457
} | class ____(Type):
"""A disallowed type.
Assignments to a InvalidType result in a Never Type. InvalidType is basically the
invalid case.
"""
name = "invalid"
types: t.ClassVar[t.List[type]] = []
def assign_type(self, wb_type: "Type") -> "InvalidType":
return self
| InvalidType |
python | great-expectations__great_expectations | great_expectations/execution_engine/sparkdf_batch_data.py | {
"start": 90,
"end": 353
} | class ____(BatchData):
def __init__(self, execution_engine, dataframe) -> None:
super().__init__(execution_engine=execution_engine)
self._dataframe = dataframe
@property
def dataframe(self):
return self._dataframe
| SparkDFBatchData |
python | wntrblm__nox | nox/logger.py | {
"start": 1700,
"end": 2511
} | class ____(ColoredFormatter):
def __init__(
self,
*,
datefmt: Any = None,
style: Any = None,
log_colors: Any = None,
reset: bool = True,
secondary_log_colors: Any = None,
add_timestamp: bool = False,
) -> None:
super().__init__(
... | NoxColoredFormatter |
python | facebook__pyre-check | scripts/explore_pysa_models.py | {
"start": 903,
"end": 1272
} | class ____(NamedTuple):
models: Dict[str, FilePosition] = {}
issues: Dict[str, List[FilePosition]] = {}
call_graphs: Dict[str, FilePosition] = {}
def update(self, index: "AnalysisOutputIndex") -> None:
self.models.update(index.models)
self.issues.update(index.issues)
self.call_g... | AnalysisOutputIndex |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py | {
"start": 23999,
"end": 30534
} | class ____(AwsBaseOperator[GlueDataQualityHook]):
"""
Starts a recommendation run that is used to generate rules, Glue Data Quality analyzes the data and comes up with recommendations for a potential ruleset.
Recommendation runs are automatically deleted after 90 days.
.. seealso::
For more in... | GlueDataQualityRuleRecommendationRunOperator |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 33016,
"end": 39385
} | class ____(BlipTextPreTrainedModel, GenerationMixin):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
self.bert ... | BlipTextLMHeadModel |
python | huggingface__transformers | tests/models/markuplm/test_feature_extraction_markuplm.py | {
"start": 1792,
"end": 3616
} | class ____(FeatureExtractionSavingTestMixin, unittest.TestCase):
feature_extraction_class = MarkupLMFeatureExtractor if is_bs4_available() else None
def setUp(self):
self.feature_extract_tester = MarkupLMFeatureExtractionTester(self)
@property
def feat_extract_dict(self):
return self.f... | MarkupLMFeatureExtractionTest |
python | jazzband__django-pipeline | pipeline/compressors/jsmin.py | {
"start": 50,
"end": 306
} | class ____(CompressorBase):
"""
JS compressor based on the Python library jsmin
(http://pypi.python.org/pypi/jsmin/).
"""
def compress_js(self, js):
from jsmin import jsmin # noqa: PLC0415
return jsmin(js)
| JSMinCompressor |
python | pytorch__pytorch | torch/profiler/_pattern_matcher.py | {
"start": 4473,
"end": 4843
} | class ____(Pattern):
def __init__(
self, prof: profile, name: str, should_benchmark: bool = False
) -> None:
super().__init__(prof, should_benchmark)
self.description = f"Matched Name Event: {name}"
self.name = name
def match(self, event: _ProfilerEvent):
return re.s... | NamePattern |
python | bokeh__bokeh | tests/unit/bokeh/models/test_plots.py | {
"start": 11817,
"end": 12017
} | class ____(BaseTwinAxis):
"""Test whether extra x and y ranges can be categorical"""
@staticmethod
def get_range_instance():
return FactorRange('foo', 'bar')
| TestCategoricalTwinAxis |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 869877,
"end": 870613
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PullRequest."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PullRequestEdge"), graphql_name="edges")
"""A list of edges."""
nodes ... | PullRequestConnection |
python | django__django | tests/update_only_fields/models.py | {
"start": 1016,
"end": 1084
} | class ____(Employee):
class Meta:
proxy = True
| ProxyEmployee |
python | django__django | tests/i18n/patterns/tests.py | {
"start": 17808,
"end": 18344
} | class ____(URLTestCaseBase):
"""
#21579 - LocaleMiddleware should respect the script prefix.
"""
def test_language_prefix_with_script_prefix(self):
prefix = "/script_prefix"
with override_script_prefix(prefix):
response = self.client.get(
"/prefixed/", header... | URLRedirectWithScriptAliasTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF052_0.py | {
"start": 697,
"end": 1229
} | class ____:
_valid_private_cls_attr = 1
print(_valid_private_cls_attr)
def __init__(self):
self._valid_private_ins_attr = 2
print(self._valid_private_ins_attr)
def _valid_method(self):
return self._valid_private_ins_attr
def method(arg):
_valid_unused_var = arg
... | ClassOk |
python | oauthlib__oauthlib | tests/test_common.py | {
"start": 3070,
"end": 4311
} | class ____(TestCase):
def test_generate_timestamp(self):
timestamp = generate_timestamp()
self.assertIsInstance(timestamp, str)
self.assertTrue(int(timestamp))
self.assertGreater(int(timestamp), 1331672335)
def test_generate_nonce(self):
"""Ping me (ib-lundgren) when yo... | GeneratorTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generic2.py | {
"start": 166,
"end": 440
} | class ____(Generic[_T1]):
pass
# This should generate an error.
def func1(a: _T1) -> Generic[_T1]: ...
# This should generate an error.
def func2(p1: Generic[_T1]) -> _T1: ...
TA1 = Generic
# This should generate an error.
def func3(a: _T1) -> TA1[_T1]: ...
| ClassA |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_all_reduce_strategy_test.py | {
"start": 30590,
"end": 31860
} | class ____(test.TestCase):
def testIsInstance(self):
# It's not uncommon for people to special case MultiWorkerMirroredStrategy,
# so we need to make sure isinstance check works for combinations between
# the experimental and non-experimental endpoints.
strategy = CollectiveAllReduceStrategy()
ex... | ExperimentalCompatibilityTest |
python | ray-project__ray | rllib/core/models/torch/primitives.py | {
"start": 22684,
"end": 23303
} | class ____(nn.Module):
def __init__(self, num_features, **kwargs):
super().__init__()
self.layer_norm = nn.LayerNorm(num_features, **kwargs)
def forward(self, x):
# x shape: (B, dim, dim, channels).
batch_size, channels, h, w = x.size()
# Reshape to (batch_size * height ... | LayerNorm1D |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py | {
"start": 163,
"end": 3992
} | class ____(Renderer):
def open_figure(self, fig: Any, props: Dict[str, Union[int, float]]) -> None:
self.props = props
self.figwidth = int(props["figwidth"] * props["dpi"])
self.figheight = int(props["figheight"] * props["dpi"])
self.data = []
self.scales = []
self.ax... | VegaRenderer |
python | pytorch__pytorch | torch/distributed/checkpoint/_extension.py | {
"start": 660,
"end": 1665
} | class ____(abc.ABC):
"""
Extensions provide modular additions to functionality within distributed checkpointing,
which affect the layout or format of the written artifacts. Extensions may be
built into pytorch, or provided externally.
When writing, the caller provides a list of extension instances... | Extension |
python | ray-project__ray | rllib/models/torch/misc.py | {
"start": 11397,
"end": 11632
} | class ____(nn.Module):
"""Standard module that reshapes/views a tensor"""
def __init__(self, shape: List):
super().__init__()
self.shape = shape
def forward(self, x):
return x.view(*self.shape)
| Reshape |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 49665,
"end": 56383
} | class ____(_AssociationSingleItem[_T], MutableSequence[_T]):
"""Generic, converting, list-to-list proxy."""
col: MutableSequence[_T]
def _set(self, object_: Any, value: _T) -> None:
self.setter(object_, value)
@overload
def __getitem__(self, index: int) -> _T: ...
@overload
def _... | _AssociationList |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/pipes/client.py | {
"start": 6357,
"end": 11022
} | class ____(ABC):
@abstractmethod
@contextmanager
def read_messages(self, handler: "PipesMessageHandler") -> Iterator[PipesParams]:
"""A `@contextmanager` that reads messages reported by an external process.
This method should start a thread to continuously read messages from some location
... | PipesMessageReader |
python | keon__algorithms | tests/test_dp.py | {
"start": 945,
"end": 1273
} | class ____(unittest.TestCase):
def test_climb_stairs(self):
self.assertEqual(climb_stairs(2), 2)
self.assertEqual(climb_stairs(10), 89)
def test_climb_stairs_optimized(self):
self.assertEqual(climb_stairs_optimized(2), 2)
self.assertEqual(climb_stairs_optimized(10), 89)
| TestClimbingStairs |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_operator.py | {
"start": 1268,
"end": 1641
} | class ____(object):
def __init__(self, lst):
self.lst = lst
def __len__(self):
return len(self.lst)
def __getitem__(self, i):
return self.lst[i]
def __add__(self, other):
return self.lst + other.lst
def __mul__(self, other):
return self.lst * other
def __r... | Seq2 |
python | huggingface__transformers | src/transformers/models/persimmon/modeling_persimmon.py | {
"start": 33651,
"end": 33930
} | class ____(GenericForTokenClassification, PersimmonPreTrainedModel): ...
__all__ = [
"PersimmonForCausalLM",
"PersimmonModel",
"PersimmonPreTrainedModel",
"PersimmonForSequenceClassification",
"PersimmonForTokenClassification",
]
| PersimmonForTokenClassification |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 26148,
"end": 26600
} | class ____(ProjectAdminMixin, PrivateViewMixin):
form_class = TranslationForm
def get_success_url(self):
return reverse(
"projects_translations",
args=[self.get_project().slug],
)
def get_form(self, data=None, files=None, **kwargs):
kwargs["parent"] = self.g... | ProjectTranslationsMixin |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 1764,
"end": 2223
} | class ____(Filters, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-filters/#api-rest-api-3-filter-post
"""
def generate(self):
for index in range(1, 20):
payload = json.dumps(
{"jql": "type = Bug and resolution is empty", "... | FiltersGenerator |
python | kamyu104__LeetCode-Solutions | Python/find-if-path-exists-in-graph.py | {
"start": 2239,
"end": 3058
} | class ____(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
def dfs(adj, start, target):
stk = [start]
lookup = set(stk)
... | Solution3 |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 1446,
"end": 1553
} | class ____(ApeException):
"""
Raised when a problem occurs when using accounts.
"""
| AccountsError |
python | plotly__plotly.py | plotly/graph_objs/_scatterternary.py | {
"start": 215,
"end": 71953
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "scatterternary"
_valid_props = {
"a",
"asrc",
"b",
"bsrc",
"c",
"cliponaxis",
"connectgaps",
"csrc",
"customdata",
"customdatasrc",
"fill",
"fillcolo... | Scatterternary |
python | getsentry__sentry | tests/sentry/integrations/msteams/notifications/test_issue_alert.py | {
"start": 720,
"end": 4783
} | class ____(MSTeamsActivityNotificationTest):
def test_issue_alert_user(self, mock_send_card: MagicMock) -> None:
"""Test that issue alerts are sent to a MS Teams user."""
event = self.store_event(
data={"message": "Hello world", "level": "error"}, project_id=self.project.id
)
... | MSTeamsIssueAlertNotificationTest |
python | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 3754,
"end": 4124
} | class ____(_TestFFTBase):
def setup_method(self):
self.cdt = np.complex64
self.rdt = np.float32
reason = ("single-precision FFT implementation is partially disabled, "
"until accuracy issues with large prime powers are resolved")
@pytest.mark.xfail(run=False, reason=reason)
... | TestSingleFFT |
python | gevent__gevent | src/gevent/_config.py | {
"start": 17590,
"end": 17817
} | class ____(object):
document = False
@property
def kwarg_name(self):
return self.name[5:]
validate = staticmethod(validate_anything)
_convert = staticmethod(convert_str_value_as_is)
| AresSettingMixin |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_int.py | {
"start": 3215,
"end": 4165
} | class ____(BaseTestZDType):
test_cls = Int64
scalar_type = np.int64
valid_dtype = (np.dtype(">i8"), np.dtype("<i8"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float64),
)
valid_json_v2 = (
{"name": ">i8", "object_codec_id": None},
... | TestInt64 |
python | PrefectHQ__prefect | tests/experimental/test_sla.py | {
"start": 8694,
"end": 28890
} | class ____:
@pytest.fixture
def deployment_id(self):
return UUID("89f0ac57-514a-4eb1-a068-dbbf44d2e199")
class TestClientMethodCall:
async def test_create_slas(self, prefect_client, monkeypatch, deployment_id):
monkeypatch.setattr(prefect_client, "server_type", ServerType.CLOUD)... | TestDeploymentCLI |
python | getsentry__sentry | src/sentry/search/events/builder/spans_metrics.py | {
"start": 581,
"end": 2793
} | class ____(MetricsQueryBuilder):
requires_organization_condition = True
spans_metrics_builder = True
has_transaction = False
config_class = SpansMetricsDatasetConfig
size_fields = SIZE_FIELDS
column_remapping = {
# We want to remap `message` to `span.description` for the free
# ... | SpansMetricsQueryBuilder |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 118736,
"end": 120421
} | class ____:
def test_sign(self):
a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
out = np.zeros(a.shape)
tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
with np.errstate(invalid='ignore'):
res = ncu.sign(a)
assert_equal(res, tgt)
res = n... | TestSign |
python | google__pytype | pytype/convert.py | {
"start": 1143,
"end": 42775
} | class ____(utils.ContextWeakrefMixin):
"""Functions for creating the classes in abstract.py."""
unsolvable: abstract.Unsolvable
# Define this error inside Converter so that it is exposed to abstract.py
class TypeParameterError(Exception):
def __init__(self, type_param_name):
super().__init__(type_p... | Converter |
python | google__pytype | pytype/tests/test_pickle2.py | {
"start": 164,
"end": 2096
} | class ____(test_base.BaseTest):
"""Tests for loading and saving pickled files."""
def test_container(self):
pickled = self.Infer(
"""
import collections, json
def f() -> collections.OrderedDict[int, int]:
return collections.OrderedDict({1: 1})
def g() -> json.JSONDecoder:
... | PickleTest |
python | falconry__falcon | falcon/bench/queues/claims.py | {
"start": 586,
"end": 684
} | class ____:
def on_post(self, req, resp, tenant_id, queue_name):
pass
| CollectionResource |
python | spyder-ide__spyder | spyder/plugins/mainmenu/api.py | {
"start": 3104,
"end": 3262
} | class ____:
StartDebug = 'start_debug_section'
ControlDebug = 'control_debug_section'
EditBreakpoints = 'edit_breakpoints_section'
| DebugMenuSections |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/fail_test_audit/package.py | {
"start": 225,
"end": 936
} | class ____(MakefilePackage):
"""Simple package attempting to re-use stand-alone test method as a build check."""
homepage = "http://github.com/dummy/fail-test-audit"
url = "https://github.com/dummy/fail-test-audit/archive/v1.0.tar.gz"
version("2.0", sha256="c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed... | FailTestAudit |
python | sympy__sympy | sympy/physics/control/routh_table.py | {
"start": 135,
"end": 9775
} | class ____(MutableDenseMatrix):
r"""
A class for creating a Routh-Hurwitz table from a given polynomial.
It handles special cases with methods discussed in [1]_.
Note: When at least a row of the table is zero,
the property ``zero_row_case`` is set to True.
Explanation
============
In ... | RouthHurwitz |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 32593,
"end": 32638
} | class ____(Stmt):
"""Break a loop."""
| Break |
python | kubernetes-client__python | kubernetes/client/api/resource_api.py | {
"start": 543,
"end": 5189
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | ResourceApi |
python | rapidsai__cudf | python/cudf/cudf/core/dataframe.py | {
"start": 17354,
"end": 29217
} | class ____(_DataFrameIlocIndexer):
pass
@_performance_tracking
def _listlike_to_column_accessor(
data: Sequence,
columns: None | pd.Index,
index: None | Index,
nan_as_null: bool,
) -> tuple[dict[Any, ColumnBase], Index, pd.Index]:
"""
Convert a list-like to a dict for ColumnAccessor for Da... | _DataFrameiAtIndexer |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 43617,
"end": 47001
} | class ____(TestCase):
@xfail # (reason="bools not interned")
def test_test_interning(self):
a0 = np.bool_(0)
b0 = np.bool_(False)
assert_(a0 is b0)
a1 = np.bool_(1)
b1 = np.bool_(True)
assert_(a1 is b1)
assert_(np.array([True])[0] is a1)
assert_(n... | TestBool |
python | dask__distributed | distributed/semaphore.py | {
"start": 9102,
"end": 20900
} | class ____(SyncMethodMixin):
"""Semaphore
This `semaphore <https://en.wikipedia.org/wiki/Semaphore_(programming)>`_
will track leases on the scheduler which can be acquired and
released by an instance of this class. If the maximum amount of leases are
already acquired, it is not possible to acquire... | Semaphore |
python | kamyu104__LeetCode-Solutions | Python/maximum-unique-subarray-sum-after-deletion.py | {
"start": 42,
"end": 260
} | class ____(object):
def maxSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mx = max(nums)
return mx if mx < 0 else sum(x for x in set(nums) if x >= 0)
| Solution |
python | django__django | tests/model_enums/tests.py | {
"start": 9127,
"end": 9312
} | class ____(ipaddress.IPv4Address, models.Choices):
LOCALHOST = "127.0.0.1", "Localhost"
GATEWAY = "192.168.0.1", "Gateway"
BROADCAST = "192.168.0.255", "Broadcast"
| IPv4Address |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/transformer.py | {
"start": 2901,
"end": 4175
} | class ____(nn.Module):
def __init__(self, dim: int, dropout: float = 0.1, max_len: int = 5000) -> None:
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.dim = dim
self.max_len = max_len
self.pe: Optional[Tensor] = None
def forward(self, x: Tensor) -> Tensor:
... | PositionalEncoding |
python | spack__spack | lib/spack/spack/solver/asp.py | {
"start": 160667,
"end": 167444
} | class ____:
"""This is the main external interface class for solving.
It manages solver configuration and preferences in one place. It sets up the solve
and passes the setup method to the driver, as well.
"""
def __init__(self):
# Compute possible compilers first, so we see them as externa... | Solver |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 20710,
"end": 21366
} | class ____:
"""The key and value content to get from each line.
This class defines the key and value used for `tf.lookup.TextFileInitializer`.
The key and value content to get from each line is specified either
by the following, or a value `>=0`.
* `TextFileIndex.LINE_NUMBER` means use the line number start... | TextFileIndex |
python | huggingface__transformers | src/transformers/models/grounding_dino/processing_grounding_dino.py | {
"start": 3906,
"end": 11503
} | class ____(ProcessorMixin):
r"""
Constructs a Grounding DINO processor which wraps a Deformable DETR image processor and a BERT tokenizer into a
single processor.
[`GroundingDinoProcessor`] offers all the functionalities of [`GroundingDinoImageProcessor`] and
[`AutoTokenizer`]. See the docstring of... | GroundingDinoProcessor |
python | tornadoweb__tornado | tornado/template.py | {
"start": 20949,
"end": 21047
} | class ____(_Node):
def __init__(self, name: str) -> None:
self.name = name
| _ExtendsBlock |
python | django__django | tests/file_storage/tests.py | {
"start": 23910,
"end": 24378
} | class ____(FileStorageTests):
storage_class = CustomStorage
def test_custom_get_available_name(self):
first = self.storage.save("custom_storage", ContentFile("custom contents"))
self.assertEqual(first, "custom_storage")
second = self.storage.save("custom_storage", ContentFile("more cont... | CustomStorageTests |
python | apache__avro | lang/py/avro/tether/tether_task.py | {
"start": 3979,
"end": 5000
} | class ____:
"""
This is a small requestor subclass I created for the HTTP protocol.
Since the HTTP protocol isn't persistent, we need to instantiate
a new transciever and new requestor for each request.
But I wanted to use of the requestor to be identical to that for
SocketTransciever so that we... | HTTPRequestor |
python | Textualize__textual | docs/examples/widgets/tabbed_content_label_color.py | {
"start": 103,
"end": 574
} | class ____(App):
CSS = """
TabbedContent #--content-tab-green {
color: green;
}
TabbedContent #--content-tab-red {
color: red;
}
"""
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("Red", id="red"):
yield Label("Red... | ColorTabsApp |
python | kamyu104__LeetCode-Solutions | Python/shortest-unsorted-continuous-subarray.py | {
"start": 29,
"end": 569
} | class ____(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
left, right = -1, -2
min_from_right, max_from_left = nums[-1], nums[0]
for i in xrange(1, n):
max_from_left = max(max_from_lef... | Solution |
python | bokeh__bokeh | src/bokeh/core/property/container.py | {
"start": 5671,
"end": 5869
} | class ____(Seq[T]):
""" Accept NumPy array values.
"""
@classmethod
def _is_seq(cls, value: Any) -> bool:
import numpy as np
return isinstance(value, np.ndarray)
| Array |
python | TheAlgorithms__Python | machine_learning/sequential_minimum_optimization.py | {
"start": 13253,
"end": 20163
} | class ____:
def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0):
self.degree = np.float64(degree)
self.coef0 = np.float64(coef0)
self.gamma = np.float64(gamma)
self._kernel_name = kernel
self._kernel = self._get_kernel(kernel_name=kernel)
self._check()
d... | Kernel |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 39646,
"end": 39839
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("CREATED_AT", "MONTHLY_PRICE_IN_CENTS")
| SponsorsTierOrderField |
python | getsentry__sentry | tests/sentry/preprod/test_tasks.py | {
"start": 15759,
"end": 18996
} | class ____(BaseAssembleTest):
def setUp(self) -> None:
super().setUp()
self.preprod_artifact = PreprodArtifact.objects.create(
project=self.project, state=PreprodArtifact.ArtifactState.UPLOADED
)
def _run_task_and_verify_status(
self, content, checksum=None, chunks=N... | AssemblePreprodArtifactInstallableAppTest |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/i18n/main.py | {
"start": 800,
"end": 1476
} | class ____(BaseHandler):
"""A simple handler with internationalized strings.
This handler demonstrates how to internationalize strings in
Python, Jinja2 template and Javascript.
"""
def get(self):
"""A get handler for this sample.
It just shows internationalized strings in Python,... | MainHandler |
python | pytorch__pytorch | test/inductor/test_extension_backend.py | {
"start": 1491,
"end": 3392
} | class ____(TestCase):
module = None
# Use a lock file so that only one test can build this extension at a time
lock_file = "extension_device.lock"
lock = FileLock(lock_file)
@classmethod
def setUpClass(cls):
super().setUpClass()
try:
cls.lock.acquire(timeout=600)
... | BaseExtensionBackendTests |
python | giampaolo__psutil | tests/test_linux.py | {
"start": 35326,
"end": 37210
} | class ____(PsutilTestCase):
def test_ips(self):
for name, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == psutil.AF_LINK:
assert addr.address == get_mac_address(name)
elif addr.family == socket.AF_INET:
... | TestSystemNetIfAddrs |
python | pallets__werkzeug | examples/couchy/application.py | {
"start": 429,
"end": 1493
} | class ____:
def __init__(self, db_uri):
local.application = self
server = Server(db_uri)
try:
db = server.create("urls")
except Exception:
db = server["urls"]
self.dispatch = SharedDataMiddleware(self.dispatch, {"/static": STATIC_PATH})
URL.d... | Couchy |
python | TheAlgorithms__Python | data_structures/binary_tree/binary_search_tree_recursive.py | {
"start": 7400,
"end": 16490
} | class ____(unittest.TestCase):
@staticmethod
def _get_binary_search_tree() -> BinarySearchTree:
r"""
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
\
5
"""
t = BinarySearch... | BinarySearchTreeTest |
python | jazzband__django-pipeline | tests/tests/test_storage.py | {
"start": 1065,
"end": 4914
} | class ____(TestCase):
def tearDown(self):
staticfiles_storage._setup()
@pipeline_settings(JS_COMPRESSOR=None, CSS_COMPRESSOR=None)
def test_post_process_dry_run(self):
default_collector.collect()
processed_files = PipelineStorage().post_process({}, True)
self.assertEqual(lis... | StorageTest |
python | huggingface__transformers | src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | {
"start": 60178,
"end": 84621
} | class ____(TimeSeriesTransformerPreTrainedModel):
def __init__(self, config: TimeSeriesTransformerConfig):
super().__init__(config)
self.model = TimeSeriesTransformerModel(config)
if config.distribution_output == "student_t":
self.distribution_output = StudentTOutput(dim=config.i... | TimeSeriesTransformerForPrediction |
python | Unity-Technologies__ml-agents | ml-agents-envs/tests/simple_test_envs.py | {
"start": 10473,
"end": 19063
} | class ____(BaseEnv):
"""
The MultiAgentEnvironment maintains a list of SimpleEnvironment, one for each agent.
When sending DecisionSteps and TerminalSteps to the trainers, it first batches the
decision steps from the individual environments. When setting actions, it indexes the
batched ActionTuple t... | MultiAgentEnvironment |
python | getsentry__sentry-python | tests/test_client.py | {
"start": 40221,
"end": 47330
} | class ____:
"""
Tests for client reports related to spans.
"""
__test__ = False
@staticmethod
def span_dropper(spans_to_drop):
"""
Returns a function that can be used to drop spans from an event.
"""
def drop_spans(event, _):
event["spans"] = event[... | TestSpanClientReports |
python | coleifer__peewee | examples/blog/app.py | {
"start": 4857,
"end": 9501
} | class ____(FTSModel):
content = TextField()
class Meta:
database = database
def login_required(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
if session.get('logged_in'):
return fn(*args, **kwargs)
return redirect(url_for('login', next=request.path))
retu... | FTSEntry |
python | joerick__pyinstrument | pyinstrument/session.py | {
"start": 508,
"end": 7705
} | class ____:
def __init__(
self,
frame_records: list[FrameRecordType],
start_time: float,
duration: float,
min_interval: float,
max_interval: float,
sample_count: int,
start_call_stack: list[str],
target_description: str,
cpu_time: float... | Session |
python | numpy__numpy | numpy/_core/tests/test_cpu_features.py | {
"start": 13110,
"end": 13502
} | class ____(AbstractTest):
features = ["VSX", "VSX2", "VSX3", "VSX4"]
features_map = {"VSX2": "ARCH_2_07", "VSX3": "ARCH_3_00", "VSX4": "ARCH_3_1"}
def load_flags(self):
self.load_flags_auxv()
is_zarch = re.match(r"^(s390x)", machine, re.IGNORECASE)
@pytest.mark.skipif(not is_linux or not is_zarch... | Test_POWER_Features |
python | ray-project__ray | python/ray/tests/horovod/horovod_example.py | {
"start": 488,
"end": 7150
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forwa... | Net |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 979,
"end": 1024
} | class ____(Class4[T_contra]): ...
| Class4_Child1 |
python | PyCQA__pylint | tests/functional/b/bugfix_local_scope_metaclass_1177.py | {
"start": 136,
"end": 165
} | class ____(type):
pass
| Meta |
python | pytorch__pytorch | test/cpp_extensions/torch_stable_test_extension/setup.py | {
"start": 271,
"end": 1826
} | class ____(distutils.command.clean.clean):
def run(self):
# Run default behavior first
distutils.command.clean.clean.run(self)
# Remove extension
for path in (ROOT_DIR / "torch_stable_test").glob("**/*.so"):
path.unlink()
# Remove build and dist and egg-info dire... | clean |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels34.py | {
"start": 315,
"end": 1983
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels34.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | django__django | django/db/models/fields/related_descriptors.py | {
"start": 15160,
"end": 17501
} | class ____(ForwardManyToOneDescriptor):
"""
Accessor to the related object on the forward side of a one-to-one
relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
``Restaurant.place`` is a ``ForwardOneToOneDescriptor`` in... | ForwardOneToOneDescriptor |
python | numba__numba | numba/core/event.py | {
"start": 5998,
"end": 7104
} | class ____(Listener):
"""A listener that measures the total time spent between *START* and
*END* events during the time this listener is active.
"""
def __init__(self):
self._depth = 0
def on_start(self, event):
if self._depth == 0:
self._ts = timer()
self._depth... | TimingListener |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 2178,
"end": 6806
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
Contrastive loss for image-text similarity.
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
The scaled dot product scores betwee... | OwlViTOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.