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 | scikit-learn__scikit-learn | sklearn/utils/tests/test_estimator_checks.py | {
"start": 4659,
"end": 4834
} | class ____(BaseEstimator):
def fit(self, X, y=None):
self._good_attribute = 1
X, y = validate_data(self, X, y)
return self
| ChangesUnderscoreAttribute |
python | dagster-io__dagster | python_modules/libraries/dagster-omni/dagster_omni/objects.py | {
"start": 535,
"end": 817
} | class ____:
name: str
verified: bool
@classmethod
def from_json(cls, data: dict[str, Any]) -> "OmniLabel":
"""Create OmniLabel from JSON response data."""
return cls(name=data["name"], verified=data["verified"])
@whitelist_for_serdes
@record
| OmniLabel |
python | pytest-dev__pytest | testing/test_debugging.py | {
"start": 32744,
"end": 36605
} | class ____:
@pytest.mark.parametrize("arg", ["--pdb", ""])
def test_sys_breakpointhook_configure_and_unconfigure(
self, pytester: Pytester, arg: str
) -> None:
"""
Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
hook is reset to system v... | TestDebuggingBreakpoints |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_worksheet09.py | {
"start": 382,
"end": 4746
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with a blank cell."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle(fh)
... | TestAssembleWorksheet |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py | {
"start": 144010,
"end": 154352
} | class ____(AllRepositoryGraphQLContextTestMatrix):
def test_cross_repo_derived_asset_dependencies(self, graphql_context: WorkspaceRequestContext):
result = execute_dagster_graphql(
graphql_context,
CROSS_REPO_ASSET_GRAPH,
)
asset_nodes = result.data["assetNodes"]
... | TestCrossRepoAssetDependedBy |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py | {
"start": 8677,
"end": 10119
} | class ____(Benchmark):
r"""
HolderTable objective function.
This class defines the HolderTable [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{HolderTable}}({x}) = - \left|{e^{\left|{1
- \frac{\sqrt{x_{1}^{2} + x_... | HolderTable |
python | kamyu104__LeetCode-Solutions | Python/concatenated-divisibility.py | {
"start": 78,
"end": 1530
} | class ____(object):
def concatenatedDivisibility(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
def length(x):
l = 0
while x:
l += 1
x //= 10
return max(l, 1)
lo... | Solution |
python | huggingface__transformers | src/transformers/models/mpt/modeling_mpt.py | {
"start": 8836,
"end": 9037
} | class ____(PreTrainedModel):
config: MptConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_no_split_modules = ["MptBlock"]
@auto_docstring
| MptPreTrainedModel |
python | numpy__numpy | numpy/f2py/tests/test_callback.py | {
"start": 192,
"end": 5158
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "callback", "foo.f")]
@pytest.mark.parametrize("name", ["t", "t2"])
@pytest.mark.slow
def test_all(self, name):
self.check_function(name)
@pytest.mark.xfail(IS_PYPY,
reason="PyPy cannot modify tp_doc ... | TestF77Callback |
python | giampaolo__psutil | tests/test_process_all.py | {
"start": 2655,
"end": 15378
} | class ____(PsutilTestCase):
"""Test which iterates over all running processes and performs
some sanity checks against Process API's returned values.
Uses a process pool to get info about all processes.
"""
def setUp(self):
psutil._set_debug(False)
# Using a pool in a CI env may resu... | TestFetchAllProcesses |
python | python__mypy | mypy/nodes.py | {
"start": 97953,
"end": 98375
} | class ____(Expression):
"""Typed dict expression TypedDict(...)."""
__slots__ = ("info",)
__match_args__ = ("info",)
# The class representation of this typed dict
info: TypeInfo
def __init__(self, info: TypeInfo) -> None:
super().__init__()
self.info = info
def accept(se... | TypedDictExpr |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 14436,
"end": 14696
} | class ____(models.Model):
series = models.ForeignKey("Series", on_delete=models.CASCADE, related_name="works")
title = models.CharField(max_length=100)
history = HistoricalRecords()
class Meta:
order_with_respect_to = "series"
| SeriesWork |
python | wandb__wandb | wandb/old/summary.py | {
"start": 5877,
"end": 11399
} | class ____(SummarySubDict):
"""Store summary metrics (eg. accuracy) during and after a run.
You can manipulate this as if it's a Python dictionary but the keys
get mangled. .strip() is called on them, so spaces at the beginning
and end are removed.
"""
def __init__(self, run, summary=None):
... | Summary |
python | huggingface__transformers | src/transformers/models/vit_msn/modeling_vit_msn.py | {
"start": 10890,
"end": 11617
} | class ____(nn.Module):
"""
The residual connection is defined in ViTMSNLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config: ViTMSNConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size... | ViTMSNSelfOutput |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 217306,
"end": 220774
} | class ____:
def test_pdf(self):
rng = np.random.default_rng(3791303244302340058)
size = 10 # number of points to check
x = rng.normal(scale=10, size=size)
a = rng.uniform(high=10, size=size)
res = stats.dgamma.pdf(x, a)
ref = stats.gamma.pdf(np.abs(x), a) / 2
... | TestDgamma |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/training_status.py | {
"start": 375,
"end": 580
} | class ____(Enum):
LESSON_NUM = "lesson_num"
STATS_METADATA = "metadata"
CHECKPOINTS = "checkpoints"
FINAL_CHECKPOINT = "final_checkpoint"
ELO = "elo"
@attr.s(auto_attribs=True)
| StatusType |
python | wandb__wandb | tests/unit_tests/test_lib/test_fsm.py | {
"start": 463,
"end": 982
} | class ____(TrackCalls):
def __init__(self, calls):
super().__init__(calls)
def on_state(self, inputs) -> None:
self._calls.append("B:on_state")
def to_a(self, inputs) -> bool:
self._calls.append("to_a")
return True
def test_normal():
calls = []
sa = A(calls)
s... | B |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 117179,
"end": 119007
} | class ____(fixtures.DeclarativeMappedTest):
"""test :ticket:`3831`"""
__only_on__ = "sqlite"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Venue(Base):
__tablename__ = "venue"
id = Column(Integer, primary_key=True)
name = Co... | FunctionAsPrimaryJoinTest |
python | pytorch__pytorch | test/distributed/checkpoint/test_file_system_checkpoint_cpu.py | {
"start": 3124,
"end": 3602
} | class ____:
def __init__(self, value: IO[bytes]) -> Any:
self.state = {"blob": value}
def state_dict(self) -> dict[str, Any]:
return self.state
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
self.state = state_dict
def __eq__(self, other: object) -> bool:
... | BlobState |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_legacy_class_based/_documenters.py | {
"start": 2619,
"end": 3608
} | class ____:
"""A member of object.
This is used for the result of `Documenter.get_module_members()` to
represent each member of the object.
"""
__slots__ = '__name__', 'object', 'docstring', 'class_', 'skipped'
__name__: str
object: Any
docstring: str | None
class_: Any
skippe... | ObjectMember |
python | huggingface__transformers | src/transformers/models/cpmant/tokenization_cpmant.py | {
"start": 2345,
"end": 8039
} | class ____(PreTrainedTokenizer):
"""
Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
Args:
vocab_file (`str`):
Path to the vocabulary file.
bod_token (`str`, *optional*, defaults to `"<d>"`):
The beginning of document token.
eod_token (`... | CpmAntTokenizer |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/dist_autograd_test.py | {
"start": 6809,
"end": 39643
} | class ____(RpcAgentTestFixture):
def _exec_func_with_dst(self, dst, exec_mode, method, *args):
if ExecMode.LOCAL == exec_mode:
if len(args) == 1 and isinstance(args[0], list):
return method(*args[0])
return method(*args)
elif ExecMode.RPC_SYNC == exec_mode:
... | CommonDistAutogradTest |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 4625,
"end": 4742
} | class ____(TemplateRuntimeError):
"""Raised if a template tries to operate on :class:`Undefined`."""
| UndefinedError |
python | getsentry__sentry | src/sentry/auth/authenticators/base.py | {
"start": 1241,
"end": 1361
} | class ____(Enum):
NEW = "new"
MULTI = "multi"
ROTATION = "rotation"
EXISTING = "existing"
| EnrollmentStatus |
python | scipy__scipy | scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py | {
"start": 969,
"end": 1287
} | class ____:
"""Build LinearOperator from hessp"""
def __init__(self, hessp, n):
self.hessp = hessp
self.n = n
def __call__(self, x, *args):
def matvec(p):
return self.hessp(x, p, *args)
return LinearOperator((self.n, self.n), matvec=matvec)
| HessianLinearOperator |
python | sympy__sympy | sympy/sets/fancysets.py | {
"start": 3638,
"end": 4373
} | class ____(Naturals):
"""Represents the whole numbers which are all the non-negative integers,
inclusive of zero.
See Also
========
Naturals : positive integers; does not include 0
Integers : also includes the negative integers
"""
_inf = S.Zero
def _contains(self, other):
... | Naturals0 |
python | getsentry__sentry | src/sentry/workflow_engine/models/detector_state.py | {
"start": 336,
"end": 1740
} | class ____(DefaultFieldsModel):
"""
This table can be seen as a denormalization of the latest open period state
of the issue associated to a detector. We need this because open-periods
are asynchronously created and there are scernios where we need to know the
detector state immediately after a stat... | DetectorState |
python | explosion__spaCy | spacy/lang/pl/__init__.py | {
"start": 466,
"end": 713
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
infixes = TOKENIZER_INFIXES
suffixes = TOKENIZER_SUFFIXES
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
| PolishDefaults |
python | pytoolz__toolz | toolz/functoolz.py | {
"start": 20995,
"end": 29757
} | class ____:
"""A wrapper around a function to catch exceptions and
dispatch to a handler.
This is like a functional try/except block, in the same way that
ifexprs are functional if/else blocks.
Examples
--------
>>> excepting = excepts(
... ValueError,
... lambda a: [1, 2].... | excepts |
python | huggingface__transformers | src/transformers/models/video_llava/configuration_video_llava.py | {
"start": 888,
"end": 6448
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VideoLlavaForConditionalGeneration`]. It is used to instantiate an
VideoLlava model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults ... | VideoLlavaConfig |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 25415,
"end": 25708
} | class ____(Interface):
"""A utility which generates a request"""
def __call__(environ):
"""Return an instance of ``pyramid.request.Request``"""
def blank(path):
"""Return an empty request object (see
:meth:`pyramid.request.Request.blank`)"""
| IRequestFactory |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_auth.py | {
"start": 1059,
"end": 2573
} | class ____:
@mock.patch("airflow.api_fastapi.core_api.routes.ui.auth.get_auth_manager")
def test_should_response_200(self, mock_get_auth_manager, test_client):
mock_get_auth_manager.return_value.get_authorized_menu_items.return_value = [
MenuItem.VARIABLES,
MenuItem.CONNECTIONS,
... | TestGetAuthLinks |
python | oauthlib__oauthlib | oauthlib/oauth1/rfc5849/errors.py | {
"start": 2406,
"end": 2474
} | class ____(OAuth1Error):
error = 'invalid_client'
| InvalidClientError |
python | pydata__xarray | xarray/core/groupby.py | {
"start": 16661,
"end": 19573
} | class ____:
"""
Helper class for multi-variable GroupBy.
This satisfies the Grouper interface, but is awkward to wrap in ResolvedGrouper.
For one, it simply re-infers a new EncodedGroups using known information
in existing ResolvedGroupers. So passing in a `group` (hard to define),
and `obj` (po... | ComposedGrouper |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/represented.py | {
"start": 576,
"end": 3879
} | class ____(ABC):
"""RepresentedJob is a base class for ExternalPipeline or HistoricalPipeline.
The name is "represented" because this is an in-memory representation of a job.
The representation of a job could be referring to a job resident in
another process *or* could be referring to a historical view... | RepresentedJob |
python | celery__celery | t/unit/utils/test_time.py | {
"start": 1469,
"end": 7695
} | class ____:
def test_parse_with_timezone(self):
d = datetime.now(_timezone.utc).replace(tzinfo=ZoneInfo("UTC"))
assert parse_iso8601(d.isoformat()) == d
# 2013-06-07T20:12:51.775877+00:00
iso = d.isoformat()
iso1 = iso.replace('+00:00', '-01:00')
d1 = parse_iso8601(i... | test_iso8601 |
python | pytorch__pytorch | test/package/package_a/fake_script_class.py | {
"start": 57,
"end": 339
} | class ____:
"""Intended to be scripted."""
def __init__(self, x):
self.foo = x
def set_foo(self, x):
self.foo = x
@torch.jit.script
def uses_script_class(x):
"""Intended to be scripted."""
foo = MyScriptClass(x)
return foo.foo
| MyScriptClass |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 8470,
"end": 8543
} | class ____(VyperException):
"""Invalid literal value."""
| InvalidLiteral |
python | coleifer__peewee | tests/sqlite_udf.py | {
"start": 788,
"end": 946
} | class ____(TestModel):
url = TextField(default='')
data = TextField(default='')
timestamp = DateTimeField(default=datetime.datetime.now)
| APIResponse |
python | PyCQA__pylint | tests/functional/p/postponed/postponed_evaluation_pep585.py | {
"start": 477,
"end": 526
} | class ____(typing.List[int]):
pass
| CustomIntList |
python | django__django | django/core/validators.py | {
"start": 4432,
"end": 7475
} | class ____(RegexValidator):
# IP patterns
ipv4_re = (
r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)"
r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}"
)
ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later)
hostname_re = DomainNameValidator.hostname_r... | URLValidator |
python | walkccc__LeetCode | solutions/1136. Parallel Courses/1136.py | {
"start": 24,
"end": 85
} | class ____(Enum):
INIT = 0
VISITING = 1
VISITED = 2
| State |
python | django__django | django/template/smartif.py | {
"start": 3754,
"end": 4382
} | class ____(TokenBase):
"""
A basic self-resolvable object similar to a Django template variable.
"""
# IfParser uses Literal in create_var, but TemplateIfParser overrides
# create_var so that a proper implementation that actually resolves
# variables, filters etc. is used.
id = "literal"
... | Literal |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass3.py | {
"start": 233,
"end": 545
} | class ____(A):
y: int
def __init__(self, a: A, y: int):
self.__dict__ = a.__dict__
a = A(3)
b = B(a, 5)
# This should generate an error because there is an extra parameter
a = A(3, 4)
# This should generate an error because there is one too few parameters
b = B(a)
A.__new__(A)
B.__new__(B)
| B |
python | bokeh__bokeh | src/bokeh/document/events.py | {
"start": 21745,
"end": 24045
} | class ____(DocumentPatchedEvent):
''' A concrete event representing a change to the title of a Bokeh
Document.
'''
kind = "TitleChanged"
def __init__(self, document: Document, title: str,
setter: Setter | None = None, callback_invoker: Invoker | None = None):
'''
Args... | TitleChangedEvent |
python | sphinx-doc__sphinx | sphinx/domains/changeset.py | {
"start": 3775,
"end": 6295
} | class ____(Domain):
"""Domain for changesets."""
name = 'changeset'
label = 'changeset'
initial_data: ClassVar[dict[str, dict[str, list[ChangeSet]]]] = {
'changes': {}, # version -> list of ChangeSet
}
@property
def changesets(self) -> dict[str, list[ChangeSet]]:
return s... | ChangeSetDomain |
python | PyCQA__pylint | pylint/checkers/classes/class_checker.py | {
"start": 2227,
"end": 6501
} | class ____(NamedTuple):
args: list[str]
kwonlyargs: list[str]
varargs: str
kwargs: str
def _signature_from_call(call: nodes.Call) -> _CallSignature:
kws = {}
args = []
starred_kws = []
starred_args = []
for keyword in call.keywords or []:
arg, value = keyword.arg, keyword.v... | _ParameterSignature |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 18524,
"end": 18665
} | class ____(_TestIDSTBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 6
self.type = 4
| TestIDSTIVFloat |
python | numba__numba | numba/tests/test_analysis.py | {
"start": 33327,
"end": 37230
} | class ____(TestBranchPruneBase):
# Tests that semantic constants rewriting works by virtue of branch pruning
def test_array_ndim_attr(self):
def impl(array):
if array.ndim == 2:
if array.shape[1] == 2:
return 1
else:
return 10... | TestBranchPrunePostSemanticConstRewrites |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/op_reg_gen_test.py | {
"start": 1533,
"end": 2545
} | class ____(test.TestCase):
"""MLIR Generation Tests for MLIR TFR Program."""
def test_op_reg_gen(self):
cxx_code = gen_register_op(sys.modules[__name__])
cxx_code_exp = r"""
CHECK: #include "tensorflow/core/framework/op.h"
CHECK-EMPTY
CHECK: namespace tensorflow {
CHECK-EMPTY
... | TFRGenTensorTest |
python | doocs__leetcode | solution/1300-1399/1387.Sort Integers by The Power Value/Solution.py | {
"start": 176,
"end": 302
} | class ____:
def getKth(self, lo: int, hi: int, k: int) -> int:
return sorted(range(lo, hi + 1), key=f)[k - 1]
| Solution |
python | walkccc__LeetCode | solutions/2833. Furthest Point From Origin/2833.py | {
"start": 0,
"end": 146
} | class ____:
def furthestDistanceFromOrigin(self, moves: str) -> int:
return abs(moves.count('L') - moves.count('R')) + moves.count('_')
| Solution |
python | boto__boto3 | tests/unit/s3/test_inject.py | {
"start": 8412,
"end": 10294
} | class ____(unittest.TestCase):
def setUp(self):
self.client = mock.Mock()
self.resource = mock.Mock()
self.resource.meta.client = self.client
self.head_object_response = {'ContentLength': 5, 'ETag': 'my-etag'}
self.client.head_object.return_value = self.head_object_response
... | TestObejctSummaryLoad |
python | ApeWorX__ape | src/ape/utils/basemodel.py | {
"start": 2701,
"end": 3975
} | class ____(property):
"""
Injected properties are injected class variables that must be set before use.
**NOTE**: do not appear in a Pydantic model's set of properties.
"""
def __get__(self, *args):
arg_strs = []
for argument in args:
try:
arg_str = str(... | injected_before_use |
python | sympy__sympy | sympy/physics/mechanics/tests/test_pathway.py | {
"start": 12507,
"end": 24944
} | class ____:
def test_is_pathway_base_subclass(self):
assert issubclass(WrappingPathway, PathwayBase)
@pytest.fixture(autouse=True)
def _wrapping_pathway_fixture(self):
self.pA = Point('pA')
self.pB = Point('pB')
self.r = Symbol('r', positive=True)
self.pO = Point('p... | TestWrappingPathway |
python | huggingface__transformers | tests/models/vit_mae/test_modeling_vit_mae.py | {
"start": 12426,
"end": 15752
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return ViTImageProcessor.from_pretrained("facebook/vit-mae-base")
@cached_property
def default_model(self):
return ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base").to(torch_device)
@slow... | ViTMAEModelIntegrationTest |
python | gevent__gevent | src/greentest/3.10/test_httplib.py | {
"start": 2236,
"end": 2639
} | class ____(FakeSocket):
def __init__(self, text, pipe_trigger):
# When sendall() is called with pipe_trigger, raise EPIPE.
FakeSocket.__init__(self, text)
self.pipe_trigger = pipe_trigger
def sendall(self, data):
if self.pipe_trigger in data:
raise OSError(errno.EPI... | EPipeSocket |
python | sqlalchemy__sqlalchemy | tools/format_docs_code.py | {
"start": 1134,
"end": 14285
} | class ____(NamedTuple):
line: str
line_no: int
code: str
padding: str | None = None # relevant only on first line of block
sql_marker: str | None = None
_Block = list[BlockLine]
def _format_block(
input_block: _Block,
exit_on_error: bool,
errors: list[tuple[int, str, Exception]],
... | BlockLine |
python | scipy__scipy | scipy/integrate/_rules/_gauss_legendre.py | {
"start": 174,
"end": 1733
} | class ____(FixedRule):
"""
Gauss-Legendre quadrature.
Parameters
----------
npoints : int
Number of nodes for the higher-order rule.
xp : array_namespace, optional
The namespace for the node and weight arrays. Default is None, where NumPy is
used.
Examples
----... | GaussLegendreQuadrature |
python | apache__airflow | task-sdk/tests/task_sdk/api/test_client.py | {
"start": 28339,
"end": 36898
} | class ____:
"""
Test that the XComOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for xcoms including endpoint and
response parsing.
"""
@pytest.mark.parametrize(
"value",
[
pytest.param("val... | TestXCOMOperations |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25440,
"end": 25561
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Gentoo'
strategy_class = OpenRCStrategy
| GentooHostname |
python | run-llama__llama_index | llama-index-core/tests/indices/knowledge_graph/test_retrievers.py | {
"start": 545,
"end": 6606
} | class ____(BaseEmbedding):
@classmethod
def class_name(cls) -> str:
return "MockEmbedding"
async def _aget_query_embedding(self, query: str) -> List[float]:
del query
return [0, 0, 1, 0, 0]
async def _aget_text_embedding(self, text: str) -> List[float]:
# assume dimensi... | MockEmbedding |
python | numpy__numpy | numpy/distutils/fcompiler/sun.py | {
"start": 138,
"end": 1577
} | class ____(FCompiler):
compiler_type = 'sun'
description = 'Sun or Forte Fortran 95 Compiler'
# ex:
# f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 111690-10 2003/08/28
version_match = simple_version_match(
start=r'f9[05]: (Sun|Forte|WorkShop).*Fortran 95')
executable... | SunFCompiler |
python | numba__numba | numba/tests/test_exceptions.py | {
"start": 718,
"end": 1192
} | class ____(Exception):
def __init__(self, arg, value0):
super(UDEArgsToSuper, self).__init__(arg)
self.value0 = value0
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
same = True
same |= self.args == other.args
same |= ... | UDEArgsToSuper |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 112928,
"end": 113517
} | class ____(SendmsgTests):
# Tests for sendmsg() which require a connectionless-mode
# (e.g. datagram) socket, and do not involve recvmsg() or
# recvmsg_into().
def testSendmsgNoDestAddr(self):
# Check that sendmsg() fails when no destination address is
# given for unconnected socket.
... | SendmsgConnectionlessTests |
python | scipy__scipy | scipy/sparse/tests/test_arithmetic1d.py | {
"start": 786,
"end": 11984
} | class ____:
def test_empty_arithmetic(self, spcreator):
shape = (5,)
for mytype in [
np.dtype('int32'),
np.dtype('float32'),
np.dtype('float64'),
np.dtype('complex64'),
np.dtype('complex128'),
]:
a = spcreator(shape, dty... | TestArithmetic1D |
python | openai__openai-python | src/openai/types/beta/threads/image_url_delta.py | {
"start": 219,
"end": 582
} | class ____(BaseModel):
detail: Optional[Literal["auto", "low", "high"]] = None
"""Specifies the detail level of the image.
`low` uses fewer tokens, you can opt in to high resolution using `high`.
"""
url: Optional[str] = None
"""
The URL of the image, must be a supported image types: jpeg,... | ImageURLDelta |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 1700,
"end": 1784
} | class ____(ABCMeta): # safe
def method(self):
foo()
| non_keyword_abcmeta_1 |
python | apache__airflow | providers/standard/tests/unit/standard/triggers/test_file.py | {
"start": 2381,
"end": 3697
} | class ____:
FILE_PATH = "/files/dags/example_async_file.py"
def test_serialization(self):
"""Asserts that the trigger correctly serializes its arguments and classpath."""
trigger = FileDeleteTrigger(filepath=self.FILE_PATH, poll_interval=5)
classpath, kwargs = trigger.serialize()
... | TestFileDeleteTrigger |
python | neetcode-gh__leetcode | python/0004-median-of-two-sorted-arrays.py | {
"start": 25,
"end": 1036
} | class ____:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
A, B = nums1, nums2
total = len(nums1) + len(nums2)
half = total // 2
if len(B) < len(A):
A, B = B, A
l, r = 0, len(A) - 1
while True:
i = (l + r) // 2... | Solution |
python | PyCQA__pylint | tests/reporters/unittest_reporting.py | {
"start": 5344,
"end": 12985
} | class ____(BaseReporter):
name = "nop-reporter"
extension = ""
def __init__(self, output: TextIO | None = None) -> None:
super().__init__(output)
print("A NopReporter was initialized.", file=self.out)
def writeln(self, string: str = "") -> None:
pass
def _display(self, lay... | NopReporter |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 89734,
"end": 91299
} | class ____(BasePostProgressGroupMixin):
def test_set_has_flags(
self, mock_dist: MagicMock, mock_incr: MagicMock, mock_record: MagicMock
) -> None:
project = self.create_project(platform="other")
event_id = "a" * 32
event = self.create_event(
data={
"e... | CheckIfFlagsSentTestMixin |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/dagster_run.py | {
"start": 1923,
"end": 4184
} | class ____(Enum):
"""The status of run execution."""
# Runs waiting to be launched by the Dagster Daemon.
QUEUED = "QUEUED"
# Runs in the brief window between creating the run and launching or enqueueing it.
NOT_STARTED = "NOT_STARTED"
# Runs that are managed outside of the Dagster control pl... | DagsterRunStatus |
python | rapidsai__cudf | python/custreamz/custreamz/kafka.py | {
"start": 276,
"end": 2096
} | class ____:
def __init__(self, kafka_configs):
"""
Base object for any client that wants to interact with a Kafka broker.
This object creates the underlying KafkaDatasource connection which
is used to read data from Kafka and create cudf Dataframes.
This class should not be d... | CudfKafkaClient |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 10117,
"end": 10757
} | class ____:
param_names = ["shapes", "binary_op"]
params = [
get_benchmark_shapes("TimeBinaryOpSeries"),
["mul"],
]
def setup(self, shapes, binary_op):
df1 = generate_dataframe("int", *shapes[0], RAND_LOW, RAND_HIGH)
df2 = generate_dataframe("int", *shapes[1], RAND_LOW, ... | TimeBinaryOpSeries |
python | pytorch__pytorch | torch/package/_directory_reader.py | {
"start": 390,
"end": 1915
} | class ____:
"""
Class to allow PackageImporter to operate on unzipped packages. Methods
copy the behavior of the internal PyTorchFileReader class (which is used for
accessing packages in all other cases).
N.B.: ScriptObjects are not depickleable or accessible via this DirectoryReader
class due ... | DirectoryReader |
python | geekcomputers__Python | linear-algebra-python/src/tests.py | {
"start": 234,
"end": 5124
} | class ____(unittest.TestCase):
def test_component(self):
"""
test for method component
"""
x = Vector([1, 2, 3])
self.assertEqual(x.component(0), 1)
self.assertEqual(x.component(2), 3)
try:
y = Vector()
self.assertTrue(False)
ex... | Test |
python | getsentry__sentry | tests/sentry/middleware/test_customer_domain.py | {
"start": 7212,
"end": 7961
} | class ____(Endpoint):
permission_classes = (AllowAny,)
def get(self, request, organization_id_or_slug):
return Response(
{
"organization_id_or_slug": organization_id_or_slug,
"subdomain": request.subdomain,
"activeorg": request.session.get("ac... | OrganizationTestEndpoint |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 12720,
"end": 14257
} | class ____:
__slots__ = ("_role_class", "name", "_use_inspection")
def _literal_coercion(self, element, **kw):
raise NotImplementedError()
_post_coercion: Any = None
_resolve_literal_only = False
_skip_clauseelement_for_target_match = False
def __init__(self, role_class):
self... | RoleImpl |
python | eventlet__eventlet | eventlet/green/http/client.py | {
"start": 58888,
"end": 59137
} | class ____(ConnectionResetError, BadStatusLine):
def __init__(self, *pos, **kw):
BadStatusLine.__init__(self, "")
ConnectionResetError.__init__(self, *pos, **kw)
# for backwards compatibility
error = HTTPException
| RemoteDisconnected |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_cairo.py | {
"start": 2432,
"end": 10819
} | class ____(RendererBase):
def __init__(self, dpi):
self.dpi = dpi
self.gc = GraphicsContextCairo(renderer=self)
self.width = None
self.height = None
self.text_ctx = cairo.Context(
cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
super().__init__()
def se... | RendererCairo |
python | google__pytype | pytype/abstract/_special_classes.py | {
"start": 3310,
"end": 4411
} | class ____(_Builder):
"""Build a typed dict."""
# TODO: b/350643999 - Should rather be a ClassVar[Sequence[str]]
CLASSES: Sequence[str] = ("typing.TypedDict", "typing_extensions.TypedDict")
def matches_class(self, c: "_classes.PyTDClass") -> bool:
return c.name in self.CLASSES
def matches_base(self, c:... | _TypedDictBuilder |
python | PyCQA__pylint | doc/data/messages/i/init-is-generator/good.py | {
"start": 0,
"end": 211
} | class ____:
def __init__(self, worms):
self.__worms = worms
def worms(self):
yield from self.__worms
apple = Fruit(["Fahad", "Anisha", "Tabatha"])
for worm in apple.worms():
pass
| Fruit |
python | django__django | tests/admin_views/models.py | {
"start": 16205,
"end": 16328
} | class ____(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
| Topping |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 11403,
"end": 11843
} | class ____:
"""Used in AssetEventResult."""
dag_id: str
task_id: str
run_id: str
map_index: int
def xcom_pull(
self,
*,
key: str = "return_value",
default: Any = None,
) -> Any:
from airflow.sdk.execution_time.xcom import XCom
if (value := X... | AssetEventSourceTaskInstance |
python | getsentry__sentry | src/sentry/integrations/on_call/metrics.py | {
"start": 458,
"end": 1155
} | class ____(Enum):
"""
A way in which a user can interact with Sentry through an on-call app.
"""
# General interactions
ADD_KEY = "ADD_KEY"
POST_INSTALL = "POST_INSTALL"
# Interacting with external alerts
CREATE = "CREATE" # create an alert in Opsgenie/Pagerduty
RESOLVE = "RESOLVE"... | OnCallInteractionType |
python | walkccc__LeetCode | solutions/2471. Minimum Number of Operations to Sort a Binary Tree by Level/2471.py | {
"start": 0,
"end": 857
} | class ____:
def minimumOperations(self, root: TreeNode | None) -> int:
ans = 0
q = collections.deque([root])
# e.g. vals = [7, 6, 8, 5]
# [2, 1, 3, 0]: Initialize the ids based on the order of vals.
# [3, 1, 2, 0]: Swap 2 with 3, so 2 is in the right place (i == ids[i]).
# [0, 1, 2, 3]: Swap ... | Solution |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_ignored_modules.py | {
"start": 1099,
"end": 1965
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer0 = torch.nn.Linear(3, 5)
layer1_modules = [
torch.nn.Linear(5, 4),
torch.nn.Linear(4, 4),
torch.nn.Linear(4, 4),
]
self.layer1 = torch.nn.Sequential(*lay... | Model |
python | justquick__django-activity-stream | runtests/testapp/apps.py | {
"start": 42,
"end": 398
} | class ____(AppConfig):
name = 'testapp'
def ready(self):
from actstream.registry import register
register(apps.get_model('auth', 'group'))
register(apps.get_model('sites', 'site'))
register(self.get_model('player'))
myuser = self.get_model('myuser')
if myuser:
... | TestappConfig |
python | GoogleCloudPlatform__python-docs-samples | recaptcha_enterprise/demosite/app/urls.py | {
"start": 1487,
"end": 1662
} | class ____(enum.Enum):
INVALID_TOKEN = "Invalid token"
ACTION_MISMATCH = "Action mismatch"
SCORE_LESS_THAN_THRESHOLD = "Returned score less than threshold set"
| Error |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_versions.py | {
"start": 377,
"end": 531
} | class ____(GQLResult):
org_entity: Optional[RegistryVersionsOrganizationOrgEntity] = Field(
alias="orgEntity"
)
| RegistryVersionsOrganization |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 957027,
"end": 960420
} | class ____(Predicate):
"""
FieldLTPredicate schema wrapper.
Parameters
----------
field : str, :class:`FieldName`
Field to be tested.
lt : str, dict, float, :class:`ExprRef`, :class:`DateTime`
The value that the field should be less than.
timeUnit : dict, :class:`TimeUnit`, ... | FieldLTPredicate |
python | pytorch__pytorch | torch/cuda/memory.py | {
"start": 48828,
"end": 51180
} | class ____(_CUDAAllocator):
r"""CUDA memory allocator loaded from a so file."""
def __init__(self, path_to_so_file: str, alloc_fn_name: str, free_fn_name: str):
r"""Memory allocators are compiled in .so files and loaded dynamically using ctypes.
To change the active allocator use the :func:`to... | CUDAPluggableAllocator |
python | fluentpython__example-code-2e | 06-obj-ref/haunted_bus.py | {
"start": 717,
"end": 1039
} | class ____:
"""A bus model haunted by ghost passengers"""
def __init__(self, passengers=[]): # <1>
self.passengers = passengers # <2>
def pick(self, name):
self.passengers.append(name) # <3>
def drop(self, name):
self.passengers.remove(name)
# end::HAUNTED_BUS_CLASS[]
| HauntedBus |
python | huggingface__transformers | tests/models/speech_to_text/test_modeling_speech_to_text.py | {
"start": 2138,
"end": 10055
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_labels=False,
vocab_size=99,
hidden_size=16,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=4,
num_conv_layers=2,
... | Speech2TextModelTester |
python | graphql-python__graphene | graphene/types/tests/test_inputobjecttype.py | {
"start": 366,
"end": 4892
} | class ____(UnmountedType):
def get_type(self):
return MyType
def test_generate_inputobjecttype():
class MyInputObjectType(InputObjectType):
"""Documentation"""
assert MyInputObjectType._meta.name == "MyInputObjectType"
assert MyInputObjectType._meta.description == "Documentation"
... | MyScalar |
python | ipython__ipython | IPython/core/displaypub.py | {
"start": 1092,
"end": 6229
} | class ____(Configurable):
"""A traited class that publishes display data to frontends.
Instances of this class are created by the main IPython object and should
be accessed there.
"""
def __init__(self, shell=None, *args, **kwargs):
self.shell = shell
self._is_publishing = False
... | DisplayPublisher |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_collections.py | {
"start": 2277,
"end": 2384
} | class ____(list[collections.abc.Iterable[int]]):
pass
# Multiple generic base classes
| DerivedListIterable |
python | django__django | tests/delete/models.py | {
"start": 7649,
"end": 7803
} | class ____(models.Model):
generic_delete_bottom = models.ForeignKey(
GenericDeleteBottom, on_delete=models.CASCADE
)
| GenericDeleteBottomParent |
python | django__django | tests/migrations/migrations_test_apps/lookuperror_a/migrations/0001_initial.py | {
"start": 43,
"end": 525
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="A1",
fields=[
(
"id",
models.AutoField(
serialize=False,
verbose_name="ID",
... | Migration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.