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 | scrapy__scrapy | tests/test_command_crawl.py | {
"start": 1877,
"end": 2721
} | class ____(scrapy.Spider):
name = 'myspider'
async def start(self):
self.logger.debug(
'FEEDS: {}'.format(
json.dumps(self.settings.getdict('FEEDS'), sort_keys=True)
)
)
return
yield
"""
j = proj_path / "example.json"
j.wri... | MySpider |
python | getsentry__sentry | src/sentry/models/groupowner.py | {
"start": 3543,
"end": 9560
} | class ____(Model):
"""
Tracks the "owners" or "suggested assignees" of a group.
"""
__relocation_scope__ = RelocationScope.Excluded
group = FlexibleForeignKey("sentry.Group", db_constraint=False)
project = FlexibleForeignKey("sentry.Project", db_constraint=False)
organization = FlexibleFor... | GroupOwner |
python | kamyu104__LeetCode-Solutions | Python/repeated-dna-sequences.py | {
"start": 49,
"end": 888
} | class ____(object):
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
dict, rolling_hash, res = {}, 0, []
for i in xrange(len(s)):
rolling_hash = ((rolling_hash << 3) & 0x3fffffff) | (ord(s[i]) & 7)
if rolling_hash ... | Solution |
python | google__pytype | pytype/datatypes.py | {
"start": 334,
"end": 3479
} | class ____:
r"""A disjoint-set data structure for `AliasingDict`.
This is used to record the alias information for `AliasingDict`. It is
consist of different components. Each component will contain the names
that represent the same thing.
E.g., for a five-node component/tree, the representative for all the... | UnionFind |
python | marshmallow-code__marshmallow | tests/test_decorators.py | {
"start": 30022,
"end": 30090
} | class ____:
def __init__(self, foo):
self.foo = foo
| Nested |
python | pytorch__pytorch | torch/package/_mangling.py | {
"start": 113,
"end": 1892
} | class ____:
"""
Used on import, to ensure that all modules imported have a shared mangle parent.
"""
def __init__(self) -> None:
global _mangle_index
self._mangle_index = _mangle_index
# Increment the global index
_mangle_index += 1
# Angle brackets are used so t... | PackageMangler |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py | {
"start": 3827,
"end": 4083
} | class ____(models.Model):
"""Model with type-annotated abstract = True using regular Meta - should not trigger DJ008"""
new_field = models.CharField(max_length=10)
class Meta:
abstract: ClassVar[bool] = True
| TypeAnnotatedAbstractModel2 |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecs/tasks.py | {
"start": 15341,
"end": 18443
} | class ____(
NamedTuple("_CurrentEcsTaskMetadata", [("cluster", str), ("task_arn", str)])
):
pass
def get_current_ecs_task_metadata() -> CurrentEcsTaskMetadata:
task_metadata_uri = _container_metadata_uri() + "/task" # pyright: ignore[reportOptionalOperand]
response = requests.get(task_metadata_uri).j... | CurrentEcsTaskMetadata |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 23639,
"end": 24164
} | class ____(_FilterTestCommon):
"""Apply a filter to an expression. ``name`` is the name of the
filter, the other fields are the same as :class:`Call`.
If ``node`` is ``None``, the filter is being used in a filter block
and is applied to the content of the block.
"""
node: t.Optional[Expr] # t... | Filter |
python | sphinx-doc__sphinx | tests/test_util/test_util_typing.py | {
"start": 1675,
"end": 1756
} | class ____(Enum):
a = 1
T = TypeVar('T')
MyInt = NewType('MyInt', int)
| MyEnum |
python | ray-project__ray | python/ray/data/tests/test_transform_pyarrow.py | {
"start": 28608,
"end": 107282
} | class ____:
pass
def _create_dataset(op, data):
ds = ray.data.range(2, override_num_blocks=2)
if op == "map":
def map(x):
return {
"id": x["id"],
"my_data": data[x["id"]],
}
ds = ds.map(map)
else:
assert op == "map_batc... | UnsupportedType |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 78811,
"end": 80522
} | class ____(Operation):
def __init__(
self,
max_val,
*,
name=None,
):
super().__init__(name=name)
self.max_val = max_val
def call(self, x1, x2):
return backend.nn.psnr(
x1=x1,
x2=x2,
max_val=self.max_val,
)
... | PSNR |
python | getsentry__sentry | src/sentry/integrations/messaging/linkage.py | {
"start": 10490,
"end": 11391
} | class ____(IdentityLinkageView, ABC):
@property
def confirmation_template(self) -> str:
return "sentry/auth-link-identity.html"
@property
def metrics_operation_key(self) -> str:
return "link_identity_view"
def persist_identity(
self, idp: IdentityProvider | None, external_i... | LinkIdentityView |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 37087,
"end": 45065
} | class ____:
"""
Render information for the last render time of this control.
It stores mapping information between the input buffers (in case of a
:class:`~prompt_toolkit.layout.controls.BufferControl`) and the actual
render position on the output screen.
(Could be used for implementation of th... | WindowRenderInfo |
python | pytorch__pytorch | test/jit/test_complex.py | {
"start": 479,
"end": 15531
} | class ____(JitTestCase):
def test_script(self):
def fn(a: complex):
return a
self.checkScript(fn, (3 + 5j,))
def test_complexlist(self):
def fn(a: List[complex], idx: int):
return a[idx]
input = [1j, 2, 3 + 4j, -5, -7j]
self.checkScript(fn, (inp... | TestComplex |
python | huggingface__transformers | src/transformers/models/glpn/configuration_glpn.py | {
"start": 791,
"end": 5998
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GLPNModel`]. It is used to instantiate an GLPN
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configurat... | GLPNConfig |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 39414,
"end": 48291
} | class ____(_ConvTransposeNd):
__doc__ = (
r"""Applies a 2D transposed convolution operator over an input image
composed of several input planes.
This module can be seen as the gradient of Conv2d with respect to its input.
It is also known as a fractionally-strided convolution or
a deconvolu... | ConvTranspose2d |
python | walkccc__LeetCode | solutions/215. Kth Largest Element in an Array/215-3.py | {
"start": 0,
"end": 777
} | class ____:
def findKthLargest(self, nums: list[int], k: int) -> int:
def quickSelect(l: int, r: int, k: int) -> int:
randIndex = random.randint(0, r - l) + l
nums[randIndex], nums[r] = nums[r], nums[randIndex]
pivot = nums[r]
nextSwapped = l
for i in range(l, r):
if nums[i]... | Solution |
python | django__django | tests/admin_views/admin.py | {
"start": 13202,
"end": 13270
} | class ____(admin.StackedInline):
model = DooHickey
| DooHickeyInline |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 109586,
"end": 115485
} | class ____(BigBirdPegasusPreTrainedModel):
def __init__(self, config: BigBirdPegasusConfig, **kwargs):
super().__init__(config, **kwargs)
self.model = BigBirdPegasusModel(config)
self.classification_head = BigBirdPegasusClassificationHead(
config.d_model,
config.d_mod... | BigBirdPegasusForSequenceClassification |
python | tornadoweb__tornado | demos/facebook/facebook.py | {
"start": 1998,
"end": 2441
} | class ____(BaseHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.authenticated
async def get(self):
stream = await self.facebook_request(
"/me/home", self._on_stream, access_token=self.current_user["access_token"]
)
if stream is None:
# Session may have expi... | MainHandler |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/sensors.py | {
"start": 7812,
"end": 7996
} | class ____(graphene.Union):
class Meta:
types = (GrapheneSensors, GrapheneRepositoryNotFoundError, GraphenePythonError)
name = "SensorsOrError"
| GrapheneSensorsOrError |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 13131,
"end": 15052
} | class ____(NonStrictDataModel):
"""
:param active: Stats for active tasks
:type active: StatsStatusCount
:param archived: Stats for archived tasks
:type archived: StatsStatusCount
"""
_schema = {
"properties": {
"active": {
"description": "Stats for activ... | Stats |
python | getsentry__sentry | src/sentry/integrations/messaging/spec.py | {
"start": 9495,
"end": 9966
} | class ____(ActionHandlerFactory):
def __init__(self, spec: MessagingIntegrationSpec) -> None:
super().__init__(
slug=spec.provider_slug,
service_type=spec.action_service,
supported_target_types=[ActionTarget.SPECIFIC],
integration_provider=spec.provider_slug,
... | _MessagingHandlerFactory |
python | encode__django-rest-framework | tests/test_renderers.py | {
"start": 15654,
"end": 16539
} | class ____(TestCase):
"""
Tests specific to caching responses
"""
def test_head_caching(self):
"""
Test caching of HEAD requests
"""
response = self.client.head('/cache')
cache.set('key', response)
cached_response = cache.get('key')
assert isinstan... | CacheRenderTest |
python | ray-project__ray | python/ray/tune/tests/test_trial_scheduler.py | {
"start": 79927,
"end": 83247
} | class ____(unittest.TestCase):
def setUp(self):
ray.init(num_cpus=4)
register_mock_trainable()
def tearDown(self):
ray.shutdown()
def basicSetup(
self,
resample_prob=0.0,
explore=None,
perturbation_interval=10,
log_config=False,
hype... | E2EPopulationBasedTestingSuite |
python | sqlalchemy__sqlalchemy | test/engine/test_ddlevents.py | {
"start": 27845,
"end": 30392
} | class ____(fixtures.TestBase):
"""test DDL transactional behavior as of SQLAlchemy 1.4."""
@testing.fixture
def metadata_fixture(self):
m = MetaData()
Table("t1", m, Column("q", Integer))
Table("t2", m, Column("q", Integer))
try:
yield m
finally:
... | DDLTransactionTest |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_registries.py | {
"start": 273,
"end": 365
} | class ____(GQLResult):
organization: Optional[FetchRegistriesOrganization]
| FetchRegistries |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels44.py | {
"start": 315,
"end": 1752
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels44.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | euske__pdfminer | pdfminer/cmapdb.py | {
"start": 4342,
"end": 4588
} | class ____(CMap):
def __init__(self, name, module):
CMap.__init__(self, CMapName=name)
self.code2cid = module.CODE2CID
if module.IS_VERTICAL:
self.attrs['WMode'] = 1
return
## PyUnicodeMap
##
| PyCMap |
python | getsentry__sentry | src/sentry/integrations/discord/client.py | {
"start": 1448,
"end": 8855
} | class ____(ApiClient):
integration_name: str = IntegrationProviderSlug.DISCORD.value
base_url: str = DISCORD_BASE_URL
_METRICS_FAILURE_KEY: str = "sentry.integrations.discord.failure"
_METRICS_SUCCESS_KEY: str = "sentry.integrations.discord.success"
_METRICS_USER_ERROR_KEY: str = "sentry.integration... | DiscordClient |
python | bokeh__bokeh | src/bokeh/document/events.py | {
"start": 24045,
"end": 25866
} | class ____(DocumentPatchedEvent):
''' A concrete event representing a change to add a new Model to a
Document's collection of "root" models.
'''
kind = "RootAdded"
def __init__(self, document: Document, model: Model, setter: Setter | None = None, callback_invoker: Invoker | None = None) -> None:
... | RootAddedEvent |
python | dask__distributed | distributed/spill.py | {
"start": 2419,
"end": 10266
} | class ____(zict.Buffer[Key, object]):
"""MutableMapping that automatically spills out dask key/value pairs to disk when
the total size of the stored data exceeds the target. If max_spill is provided the
key/value pairs won't be spilled once this threshold has been reached.
Parameters
----------
... | SpillBuffer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass7.py | {
"start": 1080,
"end": 1195
} | class ____(type):
def __call__(cls, *args, **kwargs):
return super().__call__(*args, **kwargs)
| MetaClass4 |
python | davidhalter__parso | parso/python/tree.py | {
"start": 22146,
"end": 22214
} | class ____(Flow):
type = 'while_stmt'
__slots__ = ()
| WhileStmt |
python | neetcode-gh__leetcode | python/0141-linked-list-cycle.py | {
"start": 136,
"end": 408
} | class ____:
def hasCycle(self, head: ListNode) -> bool:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
| Solution |
python | getsentry__sentry | src/sentry/models/projectteam.py | {
"start": 541,
"end": 936
} | class ____(BaseManager["ProjectTeam"]):
def get_for_teams_with_org_cache(self, teams: Sequence["Team"]) -> QuerySet["ProjectTeam"]:
return (
self.filter(team__in=teams, project__status=ObjectStatus.ACTIVE)
.order_by("project__name", "project__slug")
.select_related("proje... | ProjectTeamManager |
python | huggingface__transformers | src/transformers/image_utils.py | {
"start": 37076,
"end": 37545
} | class ____:
"""
Hashable dictionary to store image size information.
"""
height: Optional[int] = None
width: Optional[int] = None
longest_edge: Optional[int] = None
shortest_edge: Optional[int] = None
max_height: Optional[int] = None
max_width: Optional[int] = None
def __getite... | SizeDict |
python | networkx__networkx | networkx/algorithms/tests/test_cycles.py | {
"start": 30906,
"end": 33821
} | class ____:
@classmethod
def setup_class(cls):
T = nx.Graph()
nx.add_cycle(T, [1, 2, 3, 4], weight=1)
T.add_edge(2, 4, weight=5)
cls.diamond_graph = T
def test_unweighted_diamond(self):
mcb = nx.minimum_cycle_basis(self.diamond_graph)
assert_basis_equal(mcb, ... | TestMinimumCycleBasis |
python | optuna__optuna | optuna/samplers/_nsgaiii/_sampler.py | {
"start": 1100,
"end": 8767
} | class ____(BaseGASampler):
"""Multi-objective sampler using the NSGA-III algorithm.
NSGA-III stands for "Nondominated Sorting Genetic Algorithm III",
which is a modified version of NSGA-II for many objective optimization problem.
For further information about NSGA-III, please refer to the following pa... | NSGAIIISampler |
python | scikit-learn__scikit-learn | sklearn/tests/test_base.py | {
"start": 2549,
"end": 2715
} | class ____:
def __init__(self):
pass
def fit(self, X=None, y=None):
return self
def predict(self, X=None):
return None
| NoEstimator |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 3869,
"end": 3915
} | class ____(GeoFuncMixin, Func):
pass
| GeoFunc |
python | walkccc__LeetCode | solutions/2930. Number of Strings Which Can Be Rearranged to Contain Substring/2930.py | {
"start": 0,
"end": 681
} | class ____:
def stringCount(self, n: int) -> int:
# There're three invalid conditions:
# a. count('l') == 0
# b. count('e') < 2
# c. count('t') == 0
#
# By Principle of Inclusion-Exclusion (PIE):
# ans = allCount - a - b - c + ab + ac + bc - abc
MOD = 1_000_000_007
allCount... | Solution |
python | numba__numba | numba/tests/test_extending.py | {
"start": 3967,
"end": 10326
} | class ____(ConcreteTemplate):
key = "print_item"
cases = [signature(types.none, mydummy_type)]
@lower_builtin("print_item", MyDummyType)
def print_dummy(context, builder, sig, args):
[x] = args
pyapi = context.get_python_api(builder)
strobj = pyapi.unserialize(pyapi.serialize_object("hello!"))
... | PrintDummy |
python | allegroai__clearml | clearml/automation/controller.py | {
"start": 1235,
"end": 184560
} | class ____(object):
"""
Pipeline controller.
Pipeline is a DAG of base tasks, each task will be cloned (arguments changed as required), executed, and monitored.
The pipeline process (task) itself can be executed manually or by the clearml-agent services queue.
Notice: The pipeline controller lives a... | PipelineController |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/json.py | {
"start": 1264,
"end": 2510
} | class ____(sqltypes.JSON.JSONPathType):
def _processor(
self, dialect: Dialect, super_proc: Optional[Callable[[Any], Any]]
) -> Callable[[Any], Any]:
def process(value: Any) -> Any:
if isinstance(value, str):
# If it's already a string assume that it's in json path
... | JSONPathType |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 34545,
"end": 35847
} | class ____(Sky2PixProjection, Conic):
r"""
Conic orthomorphic projection - sky to pixel.
Corresponds to the ``COO`` projection in FITS WCS.
See `Conic` for a description of the entire equation.
The projection formulae are:
.. math::
C &= \frac{\ln \left( \frac{\cos\theta_2}{\cos\the... | Sky2Pix_ConicOrthomorphic |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 26284,
"end": 27965
} | class ____(Reduction):
_parameters = [
"frame",
"meta",
"chunk_kwargs",
"aggregate_kwargs",
"combine_kwargs",
"split_every",
"token",
]
@functools.cached_property
def _name(self):
name = self.operand("token") or funcname(type(self)).lower(... | CustomReduction |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/summary_ops/summary_v1_tensor_op_test.py | {
"start": 1098,
"end": 5943
} | class ____(test.TestCase):
def _SummarySingleValue(self, s):
summ = summary_pb2.Summary()
summ.ParseFromString(s)
self.assertEqual(len(summ.value), 1)
return summ.value[0]
def _AssertNumpyEq(self, actual, expected):
self.assertTrue(np.array_equal(actual, expected))
def testTags(self):
w... | SummaryV1TensorOpTest |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 72088,
"end": 73512
} | class ____(FunctionPass):
"""Perform SSA-reconstruction
Produces minimal SSA.
"""
_name = "reconstruct_ssa"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
state.func_ir = reconstruct_ssa(state.func_ir)
self._patch_locals(state)
# Re... | ReconstructSSA |
python | pallets__flask | src/flask/cli.py | {
"start": 26527,
"end": 29098
} | class ____(click.ParamType):
"""Click option type for the ``--cert`` option. Allows either an
existing file, the string ``'adhoc'``, or an import for a
:class:`~ssl.SSLContext` object.
"""
name = "path"
def __init__(self) -> None:
self.path_type = click.Path(exists=True, dir_okay=False... | CertParamType |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/handlers/rendering.py | {
"start": 5078,
"end": 7298
} | class ____(Treeprocessor):
"""Prepend the configured prefix to IDs of all HTML elements."""
name: str = "mkdocstrings_ids"
"""The name of the treeprocessor."""
id_prefix: str
"""The prefix to add to every ID. It is prepended without any separator; specify your own separator if needed."""
def ... | IdPrependingTreeprocessor |
python | bottlepy__bottle | bottle.py | {
"start": 127198,
"end": 131509
} | class ____:
def __init__(self, buffer_size=2 ** 16, memfile_limit=2 ** 18, charset="latin1"):
self.headerlist = []
self.headers = None
self.file = False
self.size = 0
self._buf = b""
self.disposition = None
self.name = None
self.filename = None
... | _MultipartPart |
python | keras-team__keras | keras/src/backend/openvino/export.py | {
"start": 0,
"end": 360
} | class ____:
def track(self, resource):
raise NotImplementedError(
"`track` is not implemented in the openvino backend."
)
def add_endpoint(self, name, fn, input_signature=None, **kwargs):
raise NotImplementedError(
"`add_endpoint` is not implemented in the openvi... | OpenvinoExportArchive |
python | kamyu104__LeetCode-Solutions | Python/maximum-of-minimum-values-in-all-subarrays.py | {
"start": 29,
"end": 898
} | class ____(object):
def findMaximums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def find_bound(nums, direction, init):
result = [0]*len(nums)
stk = [init]
for i in direction(xrange(len(nums))):
while stk[-1... | Solution |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 20444,
"end": 20836
} | class ____(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
history = HistoricalRecords()
# Clear the SIMPLE_HISTORY_HISTORY_ID_USE_UUID
delattr(settings, "SIMPLE_HISTORY_HISTORY_ID_USE_UUID")
# Set the SIMPLE_HISTORY_HISTORY_CHANGE_REASON_FIELD
setattr(settings, "SI... | UUIDDefaultModel |
python | dask__distributed | distributed/protocol/tests/test_pickle.py | {
"start": 493,
"end": 6392
} | class ____:
def __init__(self, mv):
self.mv = memoryview(mv)
def __reduce_ex__(self, protocol):
if protocol >= 5:
return MemoryviewHolder, (pickle.PickleBuffer(self.mv),)
else:
return MemoryviewHolder, (self.mv.tobytes(),)
@pytest.mark.parametrize("protocol", r... | MemoryviewHolder |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 328,
"end": 423
} | class ____(ASTNode):
module: str
name: str
alias: Optional[str]
@dataclass
| ImportFrom |
python | getsentry__sentry | tests/sentry/integrations/slack/test_integration.py | {
"start": 1834,
"end": 9980
} | class ____(IntegrationTestCase):
provider = SlackIntegrationProvider
def setUp(self) -> None:
super().setUp()
def assert_setup_flow(
self,
team_id="TXXXXXXX1",
authorizing_user_id="UXXXXXXX1",
expected_client_id="slack-client-id",
expected_client_secret="sla... | SlackIntegrationTest |
python | python__mypy | mypy/types.py | {
"start": 20486,
"end": 21960
} | class ____(ProperType):
__slots__ = ("name", "fullname", "id", "upper_bound", "default")
name: str # Name (may be qualified)
fullname: str # Fully qualified name
id: TypeVarId
upper_bound: Type
default: Type
def __init__(
self,
name: str,
fullname: str,
id... | TypeVarLikeType |
python | davidhalter__parso | parso/python/tree.py | {
"start": 8979,
"end": 9084
} | class ____(_LeafWithoutNewlines, _StringComparisonMixin):
type = 'operator'
__slots__ = ()
| Operator |
python | keras-team__keras | keras/src/saving/serialization_lib_test.py | {
"start": 15499,
"end": 16540
} | class ____(keras.layers.Layer):
def __init__(
self,
units,
*,
kernel_regularizer=None,
kernel_initializer=None,
**kwargs,
):
super().__init__(**kwargs)
self._units = units
self._kernel_regularizer = kernel_regularizer
self._kernel_i... | MyDense |
python | numpy__numpy | numpy/f2py/tests/test_crackfortran.py | {
"start": 2553,
"end": 3848
} | class ____:
def test_moduleOperators(self, tmp_path):
fpath = util.getpath("tests", "src", "crackfortran", "operators.f90")
mod = crackfortran.crackfortran([str(fpath)])
assert len(mod) == 1
mod = mod[0]
assert "body" in mod and len(mod["body"]) == 9
assert mod["body"... | TestModuleProcedure |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 7495,
"end": 7622
} | class ____(Web3Exception):
"""
Raised when a persistent connection encounters an error.
"""
| PersistentConnectionError |
python | pypa__setuptools | setuptools/_vendor/wheel/vendored/packaging/markers.py | {
"start": 1009,
"end": 5790
} | class ____(ValueError):
"""
A name was attempted to be used that does not exist inside of the
environment.
"""
def _normalize_extra_values(results: Any) -> Any:
"""
Normalize extra values.
"""
if isinstance(results[0], tuple):
lhs, op, rhs = results[0]
if isinstance(lhs... | UndefinedEnvironmentName |
python | pytorch__pytorch | test/dynamo/cpython/3_13/typinganndata/_typed_dict_helper.py | {
"start": 745,
"end": 859
} | class ____(TypedDict, total=False):
a: Annotated[Annotated[Annotated[Required[int], "a"], "b"], "c"]
| VeryAnnotated |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_data.py | {
"start": 14200,
"end": 59900
} | class ____:
"""Data set from a debug-dump directory on filesystem.
An instance of `DebugDumpDir` contains all `DebugTensorDatum` instances
in a tfdbg dump root directory.
"""
def __init__(self, dump_root, partition_graphs=None, validate=True):
"""`DebugDumpDir` constructor.
Args:
dump_root: (... | DebugDumpDir |
python | spack__spack | lib/spack/spack/cmd/common/arguments.py | {
"start": 4442,
"end": 5492
} | class ____(argparse.Action):
"""Like the builtin store_true, but prints a deprecation warning."""
def __init__(
self,
option_strings,
dest: str,
default: Optional[Any] = False,
required: bool = False,
help: Optional[str] = None,
removed_in: Optional[str] ... | DeprecatedStoreTrueAction |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_hash_returned.py | {
"start": 696,
"end": 826
} | class ____:
""" __hash__ returns str """
def __hash__(self): # [invalid-hash-returned]
return "True"
| SecondBadHash |
python | walkccc__LeetCode | solutions/2272. Substring With Largest Variance/2272.py | {
"start": 0,
"end": 989
} | class ____:
def largestVariance(self, s: str) -> int:
# a := the letter with the higher frequency
# b := the letter with the lower frequency
def kadane(a: str, b: str) -> int:
ans = 0
countA = 0
countB = 0
canExtendPrevB = False
for c in s:
if c != a and c != b:
... | Solution |
python | langchain-ai__langchain | libs/cli/langchain_cli/utils/git.py | {
"start": 422,
"end": 7522
} | class ____(TypedDict):
"""Dependency source information."""
git: str
ref: str | None
subdirectory: str | None
api_path: str | None
event_metadata: dict[str, Any]
# use poetry dependency string format
def parse_dependency_string(
dep: str | None,
repo: str | None,
branch: str | Non... | DependencySource |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 10614,
"end": 11081
} | class ____:
test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["rfc-4196.txt"],
lambda key, **kwargs: SEED(binascii.unhexlify(key)),
lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lambda ... | TestSEEDModeCBC |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 7673,
"end": 9593
} | class ____:
def test_no_file(self) -> None:
with pytest.raises(ValueError) as e:
bsa.AuthModule("junkjunkjunk")
assert str(e).startswith("no file exists at module_path:")
def test_both_user(self) -> None:
def func(filename: str):
with pytest.raises(ValueError... | TestAuthModule_validation |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 531,
"end": 656
} | class ____(Protocol1): ...
# This should generate an error because some attributes are not implemented.
Concrete1()
| Concrete1 |
python | pyinstaller__pyinstaller | bootloader/waflib/Utils.py | {
"start": 1497,
"end": 2156
} | class ____(dict):
def __init__(self, *k, **kw):
self.lst = deque()
dict.__init__(self, *k, **kw)
def clear(self):
dict.clear(self)
self.lst = deque()
def __setitem__(self, key, value):
if key in dict.keys(self):
self.lst.remove(key)
dict.__setite... | ordered_iter_dict |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/concurrency.py | {
"start": 253,
"end": 346
} | class ____(Enum):
BLOCKED = "BLOCKED"
CLAIMED = "CLAIMED"
@record
| ConcurrencySlotStatus |
python | walkccc__LeetCode | solutions/2907. Maximum Profitable Triplets With Increasing Prices I/2907.py | {
"start": 446,
"end": 1084
} | class ____:
def maxProfit(self, prices: list[int], profits: list[int]) -> int:
ans = -1
maxPrice = max(prices)
maxProfitTree1 = FenwickTree(maxPrice)
maxProfitTree2 = FenwickTree(maxPrice)
for price, profit in zip(prices, profits):
# max(proftis[i])
maxProfit1 = maxProfitTree1.get(pri... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/hitl.py | {
"start": 1907,
"end": 2973
} | class ____(BaseModel):
"""Schema for the response part of a Human-in-the-loop detail for a specific task instance."""
response_received: bool
responded_by_user: HITLUser | None = None
responded_at: UtcDateTime | None
# It's empty if the user has not yet responded.
chosen_options: Iterable[str] ... | HITLDetailResponse |
python | pytorch__pytorch | torch/_inductor/cpp_builder.py | {
"start": 21276,
"end": 34077
} | class ____:
"""
This is the Base class for store cxx build options, as a template.
Actually, to build a cxx shared library. We just need to select a compiler
and maintains the suitable args.
"""
def __init__(
self,
compiler: str = "",
definitions: Optional[list[str]] = N... | BuildOptionsBase |
python | tiangolo__fastapi | tests/test_pydantic_v1_v2_multifile/modelsv2.py | {
"start": 65,
"end": 115
} | class ____(BaseModel):
new_sub_name: str
| SubItem |
python | astropy__astropy | astropy/constants/codata2018.py | {
"start": 354,
"end": 477
} | class ____(Constant):
default_reference = "CODATA 2018"
_registry = {}
_has_incompatible_units = set()
| CODATA2018 |
python | getsentry__sentry | src/sentry/integrations/gitlab/webhooks.py | {
"start": 5012,
"end": 7579
} | class ____(GitlabWebhook):
"""
Handle Merge Request Hook
See https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#merge-request-events
"""
@property
def event_type(self) -> IntegrationWebhookEventType:
return IntegrationWebhookEventType.PULL_REQUEST
def __call__(self... | MergeEventWebhook |
python | fastai__fastai | fastai/vision/learner.py | {
"start": 9055,
"end": 19974
} | class ____(nn.Module):
def __init__(self, model, pretrained:bool=True, cut=None, n_in:int=3):
super().__init__()
self.needs_pool = model.default_cfg.get('pool_size', None) is not None
self.model = model if cut is None else cut_model(model, cut)
def forward(self,x): return self.model... | TimmBody |
python | mlflow__mlflow | mlflow/sklearn/__init__.py | {
"start": 21548,
"end": 25859
} | class ____(pickle.PicklingError):
"""
Exception for describing error raised during pickling custom sklearn estimator
"""
def __init__(self, sk_model, original_exception):
"""
Args:
sk_model: The custom sklearn model to be pickled
original_exception: The original ... | _SklearnCustomModelPicklingError |
python | bokeh__bokeh | src/bokeh/models/ui/icons.py | {
"start": 3545,
"end": 3866
} | class ____(Icon):
""" SVG icons with inline definitions. """
# explicit __init__ to support Init signatures
def __init__(self, svg: Init[str] = Intrinsic, **kwargs: Any) -> None:
super().__init__(svg=svg, **kwargs)
svg = Required(String, help="""
The SVG definition of an icon.
""")
| SVGIcon |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0008_add_subproject_alias_prefix.py | {
"start": 100,
"end": 485
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0007_migrate_canonical_data"),
]
operations = [
migrations.AddField(
model_name="projectrelationship",
name="alias",
field=models.CharField(max_length=255, nul... | Migration |
python | getsentry__sentry | src/sentry/issues/endpoints/group_integration_details.py | {
"start": 2516,
"end": 17393
} | class ____(GroupEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
"POST": ApiPublishStatus.UNKNOWN,
"PUT": ApiPublishStatus.UNKNOWN,
"DELETE": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, group, integration_id) -> Re... | GroupIntegrationDetailsEndpoint |
python | django__django | tests/admin_views/test_actions.py | {
"start": 752,
"end": 19377
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.s1 = ExternalSubscriber.objects.create(
name="John Doe", email="john@example.org"
... | AdminActionsTest |
python | numpy__numpy | numpy/lib/tests/test_io.py | {
"start": 12918,
"end": 23577
} | class ____:
def test_array(self):
a = np.array([[1, 2], [3, 4]], float)
fmt = "%.18e"
c = BytesIO()
np.savetxt(c, a, fmt=fmt)
c.seek(0)
assert_equal(c.readlines(),
[asbytes((fmt + ' ' + fmt + '\n') % (1, 2)),
asbytes((fmt + '... | TestSaveTxt |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 41249,
"end": 41717
} | class ____(VOWarning, ValueError):
"""
The ``type`` attribute on the ``VALUES`` element must be either
``legal`` or ``actual``.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/2009... | E08 |
python | ansible__ansible | lib/ansible/module_utils/_internal/_patches/_sys_intern_patch.py | {
"start": 252,
"end": 849
} | class ____(CallablePatch):
"""Patch `sys.intern` so that subclasses of `str` are accepted."""
target_container: t.ClassVar = sys
target_attribute = 'intern'
@classmethod
def is_patch_needed(cls) -> bool:
with contextlib.suppress(TypeError):
sys.intern(_CustomStr("x"))
... | SysInternPatch |
python | milvus-io__pymilvus | pymilvus/orm/connections.py | {
"start": 1911,
"end": 20522
} | class ____(metaclass=SingleInstanceMetaClass):
"""Class for managing all connections of milvus. Used as a singleton in this module."""
def __init__(self) -> None:
"""Constructs a default milvus alias config
default config will be read from env: MILVUS_URI and MILVUS_CONN_ALIAS
... | Connections |
python | numba__numba | numba/cuda/deviceufunc.py | {
"start": 20852,
"end": 24584
} | class ____(object):
def __init__(self, kernelmap, engine):
self.kernelmap = kernelmap
self.engine = engine
self.max_blocksize = 2 ** 30
def __call__(self, *args, **kws):
callsteps = self._call_steps(self.engine.nin, self.engine.nout,
args, kw... | GeneralizedUFunc |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/automation_condition_scenario.py | {
"start": 1173,
"end": 1558
} | class ____(dg.AutomationCondition):
"""Always returns the empty subset."""
label: Optional[str] = None
@property
def description(self) -> str:
return ""
def evaluate(self, context: AutomationContext) -> dg.AutomationResult:
return dg.AutomationResult(context, true_subset=context.g... | FalseAutomationCondition |
python | jina-ai__jina | tests/integration/issues/github_2103/test_search_attributes.py | {
"start": 914,
"end": 1718
} | class ____(Executor):
@requests
def foo(self, docs, *args, **kwargs):
for doc in docs:
doc.tags['tag'] = 'test'
def test_no_matches_rest(query_dict):
port = helper.random_port()
with Flow(
protocol='http',
port=port,
).add(uses=MockExecutor):
# temporari... | MockExecutor |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_exclude_lists_audit.py | {
"start": 5375,
"end": 9340
} | class ____:
"""Test suite for _audit_exclude_missing_export function."""
def test_audit_exclude_missing_export_all_valid(self):
"""Test audit when all EXCLUDE_MISSING_EXPORT entries are still valid."""
# Mock validator with symbols that are not exported
mock_symbols = [
Publ... | TestAuditExcludeMissingExport |
python | walkccc__LeetCode | solutions/1547. Minimum Cost to Cut a Stick/1547.py | {
"start": 0,
"end": 298
} | class ____:
def minCost(self, n: int, cuts: list[int]) -> int:
A = sorted([0] + cuts + [n])
@functools.lru_cache(None)
def dp(i, j):
if j - i <= 1:
return 0
return min(A[j] - A[i] + dp(i, k) + dp(k, j) for k in range(i + 1, j))
return dp(0, len(A) - 1)
| Solution |
python | PyCQA__pylint | tests/functional/p/protected_access_access_different_scopes.py | {
"start": 60,
"end": 235
} | class ____:
async def method(self):
pass
def function():
assert self.attr # [undefined-variable]
def func():
self.attr += 2 # [undefined-variable]
| MyClass |
python | coleifer__peewee | peewee.py | {
"start": 216301,
"end": 216604
} | class ____(Metadata):
models = []
def __init__(self, model, *args, **kwargs):
super(SubclassAwareMetadata, self).__init__(model, *args, **kwargs)
self.models.append(model)
def map_models(self, fn):
for model in self.models:
fn(model)
| SubclassAwareMetadata |
python | doocs__leetcode | solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/Solution.py | {
"start": 0,
"end": 334
} | class ____:
def numberOfGoodSubarraySplits(self, nums: List[int]) -> int:
mod = 10**9 + 7
ans, j = 1, -1
for i, x in enumerate(nums):
if x == 0:
continue
if j > -1:
ans = ans * (i - j) % mod
j = i
return 0 if j == -1... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.