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 | apache__airflow | airflow-core/src/airflow/secrets/metastore.py | {
"start": 1174,
"end": 2329
} | class ____(BaseSecretsBackend):
"""Retrieves Connection object and Variable from airflow metastore database."""
@provide_session
def get_connection(self, conn_id: str, session: Session = NEW_SESSION) -> Connection | None:
"""
Get Airflow Connection from Metadata DB.
:param conn_id:... | MetastoreBackend |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/mock.py | {
"start": 4006,
"end": 4127
} | class ____(StaticStringIndexer):
def __init__(self) -> None:
super().__init__(RawSimpleIndexer())
| SimpleIndexer |
python | doocs__leetcode | solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/Solution.py | {
"start": 0,
"end": 198
} | class ____:
def canArrange(self, arr: List[int], k: int) -> bool:
cnt = Counter(x % k for x in arr)
return cnt[0] % 2 == 0 and all(cnt[i] == cnt[k - i] for i in range(1, k))
| Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/PenPreviewLabel.py | {
"start": 74,
"end": 1106
} | class ____(QtWidgets.QLabel):
def __init__(self, param):
super().__init__()
self.param = param
self.pen = QtGui.QPen(self.param.pen)
param.sigValueChanging.connect(self.onPenChanging)
def onPenChanging(self, param, val):
self.pen = QtGui.QPen(val)
self.update()
... | PenPreviewLabel |
python | Delgan__loguru | loguru/_colorizer.py | {
"start": 1477,
"end": 1912
} | class ____:
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
LIGHTBLACK_EX = 100
LIGHTRED_EX = 101
LIGHTGREEN_EX = 102
LIGHTYELLOW_EX = 103
LIGHTBLUE_EX = 104
LIGHTMAGENTA_EX = 105
LIGHTCYAN_EX = 106
LI... | Back |
python | kamyu104__LeetCode-Solutions | Python/smallest-integer-divisible-by-k.py | {
"start": 29,
"end": 1165
} | class ____(object):
def smallestRepunitDivByK(self, K):
"""
:type K: int
:rtype: int
"""
# by observation, K % 2 = 0 or K % 5 = 0, it is impossible
if K % 2 == 0 or K % 5 == 0:
return -1
# let f(N) is a N-length integer only containing digit 1
... | Solution |
python | numba__numba | numba/core/pythonapi.py | {
"start": 1475,
"end": 1781
} | class ____(namedtuple("_BoxContext",
("context", "builder", "pyapi", "env_manager"))):
"""
The facilities required by boxing implementations.
"""
__slots__ = ()
def box(self, typ, val):
return self.pyapi.from_native_value(typ, val, self.env_manager)
| _BoxContext |
python | django__django | tests/template_tests/syntax_tests/test_static.py | {
"start": 332,
"end": 3963
} | class ____(SimpleTestCase):
libraries = {"static": "django.templatetags.static"}
@setup({"static-prefixtag01": "{% load static %}{% get_static_prefix %}"})
def test_static_prefixtag01(self):
output = self.engine.render_to_string("static-prefixtag01")
self.assertEqual(output, settings.STATIC... | StaticTagTests |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 10005,
"end": 12140
} | class ____(SingleContinuousDistribution):
_argnames = ('alpha', 'beta')
set = Interval(0, 1)
@staticmethod
def check(alpha, beta):
_value_check(alpha > 0, "Shape parameter Alpha must be positive.")
_value_check(beta > 0, "Shape parameter Beta must be positive.")
def pdf(self, x):
... | BetaDistribution |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/data_forwarding_details.py | {
"start": 1670,
"end": 2366
} | class ____(OrganizationPermission):
scope_map = {
"PUT": ["org:write"],
"DELETE": ["org:write"],
}
def has_object_permission(
self,
request: Request,
view: APIView,
organization: Organization | RpcOrganization | RpcUserOrganizationContext,
) -> bool:
... | OrganizationDataForwardingDetailsPermission |
python | apache__airflow | airflow-core/tests/unit/always/test_secrets.py | {
"start": 4950,
"end": 8227
} | class ____:
def setup_method(self) -> None:
clear_db_variables()
SecretCache.reset()
def teardown_method(self) -> None:
clear_db_variables()
@mock.patch("airflow.secrets.metastore.MetastoreBackend.get_variable")
@mock.patch("airflow.secrets.environment_variables.EnvironmentVari... | TestVariableFromSecrets |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_shape_base.py | {
"start": 2543,
"end": 3758
} | class ____(TestCase):
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_2d(a), atleast_2d(b)]
desired = [array([[1]]), array([[2]])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
res ... | TestAtleast2d |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent.py | {
"start": 11453,
"end": 11956
} | class ____(
BaseOutputParser[list[AgentAction] | AgentFinish],
):
"""Base class for parsing agent output into agent actions/finish.
This is used for agents that can return multiple actions.
"""
@abstractmethod
def parse(self, text: str) -> list[AgentAction] | AgentFinish:
"""Parse text... | MultiActionAgentOutputParser |
python | doocs__leetcode | solution/0100-0199/0110.Balanced Binary Tree/Solution.py | {
"start": 192,
"end": 551
} | class ____:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if root is None:
return 0
l, r = height(root.left), height(root.right)
if l == -1 or r == -1 or abs(l - r) > 1:
return -1
return 1 + max(l, r)... | Solution |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 15590,
"end": 16322
} | class ____(BaseModel):
a: ClassVar[int]
_b: ClassVar[int]
_c: ClassVar[Forward]
_d: Annotated[ClassVar[int], ...]
_e: CV[int]
_f: Annotated[CV[int], ...]
# Doesn't work as of today:
# _g: CV[Forward]
Forward = int
"""
)
assert module.Model.__class_vars__ == {'a', '_b', '_c', '_... | Model |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_deprecation.py | {
"start": 812,
"end": 2294
} | class ____:
"""A deprecated class that overrides __new__."""
def __new__(cls, *args, **kwargs):
assert len(args) > 0
return super().__new__(cls)
@deprecated()
def mock_function():
return 10
def test_deprecated():
with pytest.warns(FutureWarning, match="qwerty"):
MockClass1()... | MockClass6 |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 50291,
"end": 51968
} | class ____(RegexLexer):
"""
Coldfusion markup only
"""
name = 'Coldfusion'
aliases = ['cf']
filenames = []
mimetypes = []
tokens = {
'root': [
(r'[^<]+', Other),
include('tags'),
(r'<[^<>]*', Other),
],
'tags': [
(r... | ColdfusionMarkupLexer |
python | spyder-ide__spyder | spyder/plugins/profiler/widgets/main_widget.py | {
"start": 1671,
"end": 1966
} | class ____:
# BrowseView = "view_section" # To be added later
ExpandCollapse = "collapse_section"
ChangeView = "change_view_section"
Stop = "stop_section"
# --- Widgets
# ----------------------------------------------------------------------------
| ProfilerWidgetMainToolbarSections |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 64272,
"end": 66124
} | class ____(Response):
"""
Response of models.edit endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "models"
_action = "edit"
_version = "2.23"
_schema = {
... | EditResponse |
python | kubernetes-client__python | kubernetes/client/models/v1_service_account_token_projection.py | {
"start": 383,
"end": 6831
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1ServiceAccountTokenProjection |
python | astropy__astropy | astropy/coordinates/angles/errors.py | {
"start": 3359,
"end": 3928
} | class ____(AstropyWarning):
"""
Raised when a second value is 60.
Parameters
----------
second : int, float
"""
def __init__(self, second, alternativeactionstr=None):
self.second = second
self.alternativeactionstr = alternativeactionstr
def __str__(self):
messa... | IllegalSecondWarning |
python | cython__cython | tests/run/pure_py.py | {
"start": 11200,
"end": 11502
} | class ____:
a = cython.declare(cython.double)
b = cython.declare(cython.double)
c = cython.declare(cython.double)
@cython.locals(a=cython.double, b=cython.double, c=cython.double)
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
@cython.cclass
| Foo |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_country_fip.py | {
"start": 1965,
"end": 4543
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid country fip code.
See https://github.com/yaph/geonamescache for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = ... | ExpectColumnValuesToBeValidCountryFip |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 116588,
"end": 118036
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_deprecated_v1
def testNoLabel(self):
with self.cached_session():
self.assertAllEqual(b"My label is: default",
test_ops.kernel_label().eval())
@test_util.run_deprecated_v1
def testLabelMap(self):
with self.cached_s... | KernelLabelTest |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 35074,
"end": 35477
} | class ____(str, Enum):
"""
* INSTANCE_POOL_MAX_CAPACITY_FAILURE: The pool max capacity has been reached.
* INSTANCE_POOL_NOT_FOUND_FAILURE: The pool specified by the cluster is no longer active or doesn’t exist.
"""
instancepoolmaxcapacityfailure = "INSTANCE_POOL_MAX_CAPACITY_FAILURE"
insta... | PoolClusterTerminationCode |
python | pytorch__pytorch | torch/_inductor/remote_cache.py | {
"start": 7926,
"end": 9954
} | class ____(RemoteCacheBackend[bytes]):
"""
A Redis implementation of a remote/distributed cache.
"""
# pyrefly: ignore [missing-attribute]
_redis: Optional[redis.Redis] = None
def __init__(self, cache_id: str) -> None:
super().__init__()
if not redis:
raise RuntimeE... | RedisRemoteCacheBackend |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_traces.py | {
"start": 759,
"end": 85132
} | class ____(BaseSpansTestCase, APITestCase):
view = "sentry-api-0-organization-traces"
is_eap: bool = True
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def double_write_segment(
self,
*,
project,
trace_id,
transaction_id,... | OrganizationTracesEndpointTest |
python | scrapy__scrapy | scrapy/core/http2/protocol.py | {
"start": 16845,
"end": 17368
} | class ____(Factory):
def __init__(
self,
uri: URI,
settings: Settings,
conn_lost_deferred: Deferred[list[BaseException]],
) -> None:
self.uri = uri
self.settings = settings
self.conn_lost_deferred = conn_lost_deferred
def buildProtocol(self, addr: IAd... | H2ClientFactory |
python | tensorflow__tensorflow | tensorflow/python/framework/func_graph.py | {
"start": 2538,
"end": 5331
} | class ____(object):
"""Signifies an argument which is not currently handled."""
def convert_structure_to_signature(structure, arg_names=None,
signature_context=None):
"""Convert a potentially nested structure to a signature.
Args:
structure: Structure to convert, where to... | UnknownArgument |
python | sympy__sympy | sympy/polys/domains/gmpyfinitefield.py | {
"start": 224,
"end": 437
} | class ____(FiniteField):
"""Finite field based on GMPY integers. """
alias = 'FF_gmpy'
def __init__(self, mod, symmetric=True):
super().__init__(mod, GMPYIntegerRing(), symmetric)
| GMPYFiniteField |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/via_value_of.py | {
"start": 302,
"end": 4463
} | class ____(enum.Enum):
FOO = 1
def test_string_literals():
return return_via_parameter_name("A")
def test_numerals():
return return_via_parameter_name(1)
def test_bool():
return return_via_parameter_name(False)
def test_enums():
return return_via_parameter_name(MyEnum.FOO)
def test_missing... | MyEnum |
python | numba__numba | numba/tests/test_unpack_sequence.py | {
"start": 1800,
"end": 6745
} | class ____(MemoryLeakMixin, TestCase):
def check_nullary_npm(self, pyfunc):
cfunc = njit(pyfunc)
self.assertPreciseEqual(cfunc(), pyfunc())
def check_nullary_objmode(self, pyfunc):
cfunc = jit(forceobj=True)(pyfunc)
self.assertPreciseEqual(cfunc(), pyfunc())
def test_unpac... | TestUnpack |
python | RaRe-Technologies__gensim | gensim/test/test_utils.py | {
"start": 5007,
"end": 8493
} | class ____(unittest.TestCase):
arr10_5 = np.array([
[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 9]
])
def _assert_arrays_equal(self, expected, actual):
self.assertEqual(expected.shape, actual.shap... | TestWindowing |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 72083,
"end": 77065
} | class ____(NonStrictDataModel):
"""
:param metric: Metric name
:type metric: str
:param variant: Variant name
:type variant: str
:param value: Last value reported
:type value: float
:param min_value: Minimum value reported
:type min_value: float
:param min_value_iteration: The it... | LastMetricsEvent |
python | ray-project__ray | rllib/connectors/connector_v2.py | {
"start": 808,
"end": 45905
} | class ____(Checkpointable, abc.ABC):
"""Base class defining the API for an individual "connector piece".
A ConnectorV2 ("connector piece") is usually part of a whole series of connector
pieces within a so-called connector pipeline, which in itself also abides to this
very API.
For example, you migh... | ConnectorV2 |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/context_manager.py | {
"start": 1217,
"end": 1944
} | class ____:
def __init__(self, value):
self.value = value
def __enter__(self):
_test_sink(self.value)
return self
def __exit__(self, exc_type, exc_value, traceback):
return
def test_sink_on_enter(x): # Inferred sink on x
c = SinkOnEnter(x)
with c:
c.value... | SinkOnEnter |
python | scipy__scipy | scipy/optimize/tests/test_bracket.py | {
"start": 16047,
"end": 36152
} | class ____:
def init_f(self):
def f(x, a, b):
f.count += 1
return (x - a)**2 + b
f.count = 0
return f
def assert_valid_bracket(self, result, xp):
assert xp.all(
(result.xl < result.xm) & (result.xm < result.xr)
)
assert xp.all(... | TestBracketMinimum |
python | allegroai__clearml | clearml/model.py | {
"start": 49650,
"end": 59703
} | class ____(BaseModel):
"""
Represent an existing model in the system, search by model id.
The Model will be read-only and can be used to pre initialize a network
"""
def __init__(self, model_id: str) -> None:
"""
Load model based on id, returned object is read-only and can be connec... | Model |
python | getsentry__sentry | src/sentry/workflow_engine/buffer/batch_client.py | {
"start": 623,
"end": 1761
} | class ____:
workflow: Workflow
event: GroupEvent
delayed_when_group_id: DataConditionGroupId | None
delayed_if_group_ids: list[DataConditionGroupId]
passing_if_group_ids: list[DataConditionGroupId]
# Used to pick the end of the time window in snuba querying.
# Should be close to when fast c... | DelayedWorkflowItem |
python | spyder-ide__spyder | spyder/plugins/remoteclient/widgets/__init__.py | {
"start": 275,
"end": 506
} | class ____:
"""Enum for the different authentication methods we support."""
Password = "password_login"
KeyFile = "keyfile_login"
ConfigFile = "configfile_login"
JupyterHub = "jupyterhub_login"
| AuthenticationMethod |
python | pytorch__pytorch | torch/_numpy/testing/utils.py | {
"start": 56806,
"end": 59571
} | class ____(warnings.catch_warnings):
"""Context manager that resets warning registry for catching warnings
Warnings can be slippery, because, whenever a warning is triggered, Python
adds a ``__warningregistry__`` member to the *calling* module. This makes
it impossible to retrigger the warning in this... | clear_and_catch_warnings |
python | google__jax | tests/export_test.py | {
"start": 5348,
"end": 89081
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
# Find the available platforms
self.platforms = []
for backend in ["cpu", "gpu", "tpu"]:
try:
jax.devices(backend)
except RuntimeError:
continue
self.platforms.append(backend)
def test_basic_export_only... | JaxExportTest |
python | django__django | tests/template_tests/filter_tests/test_make_list.py | {
"start": 1365,
"end": 1582
} | class ____(SimpleTestCase):
def test_string(self):
self.assertEqual(make_list("abc"), ["a", "b", "c"])
def test_integer(self):
self.assertEqual(make_list(1234), ["1", "2", "3", "4"])
| FunctionTests |
python | ansible__ansible | test/units/playbook/test_helpers.py | {
"start": 3512,
"end": 14372
} | class ____(unittest.TestCase, MixinForMocks):
def setUp(self):
self._setup()
def _assert_is_task_list_or_blocks(self, results):
self.assertIsInstance(results, list)
for result in results:
self.assertIsInstance(result, (Task, Block))
def test_ds_not_list(self):
d... | TestLoadListOfTasks |
python | scikit-learn__scikit-learn | sklearn/preprocessing/_data.py | {
"start": 24028,
"end": 40277
} | class ____(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Standardize features by removing the mean and scaling to unit variance.
The standard score of a sample `x` is calculated as:
.. code-block:: text
z = (x - u) / s
where `u` is the mean of the training samples or zero if `wi... | StandardScaler |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 20036,
"end": 20369
} | class ____(Helper):
"""A key, value pair for dicts."""
fields = ("key", "value")
key: Expr
value: Expr
def as_const(self, eval_ctx: EvalContext | None = None) -> tuple[t.Any, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const... | Pair |
python | fastai__fastai | fastai/tabular/core.py | {
"start": 13750,
"end": 14879
} | class ____(TabularProc):
"Fill the missing values in continuous columns."
def __init__(self, fill_strategy=FillStrategy.median, add_col=True, fill_vals=None):
if fill_vals is None: fill_vals = defaultdict(int)
store_attr()
def setups(self, to):
missing = pd.isnull(to.conts).any()
... | FillMissing |
python | encode__django-rest-framework | tests/browsable_api/test_form_rendering.py | {
"start": 479,
"end": 866
} | class ____(generics.GenericAPIView):
queryset = BasicModel.objects.all()
serializer_class = BasicSerializer
renderer_classes = (renderers.BrowsableAPIRenderer, renderers.JSONRenderer)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(self.get_queryset(), many=True)
... | ManyPostView |
python | django-haystack__django-haystack | haystack/management/commands/update_index.py | {
"start": 5318,
"end": 16117
} | class ____(BaseCommand):
help = "Freshens the index for the given app(s)." # noqa A003
def add_arguments(self, parser):
parser.add_argument(
"app_label",
nargs="*",
help="App label of an application to update the search index.",
)
parser.add_argument... | Command |
python | scrapy__scrapy | tests/test_downloadermiddleware_robotstxt.py | {
"start": 10493,
"end": 10728
} | class ____(TestRobotsTxtMiddleware):
def setup_method(self):
super().setup_method()
self.crawler.settings.set(
"ROBOTSTXT_PARSER", "scrapy.robotstxt.RerpRobotParser"
)
| TestRobotsTxtMiddlewareWithRerp |
python | ray-project__ray | python/ray/data/tests/test_custom_agg.py | {
"start": 4275,
"end": 9789
} | class ____:
"""Test cases for ZeroPercentage aggregation."""
def test_zero_percentage_basic(self, ray_start_regular_shared_2_cpus):
"""Test basic zero percentage calculation."""
data = [
{"id": 1, "value": 10},
{"id": 2, "value": 0},
{"id": 3, "value": 30},
... | TestZeroPercentage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 105933,
"end": 113334
} | class ____(ShopifyBulkQuery):
"""
{
orders(query: "updated_at:>='2021-04-13T00:00:00+00:00' AND updated_at:<='2024-05-20T13:50:06.882235+00:00'" sortKey: UPDATED_AT) {
edges {
node {
__typename
updatedAt
order_id: id... | OrderRisk |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 22540,
"end": 23692
} | class ____(FileHandler):
def __init__(
self,
filename,
encoding=None,
level=NOTSET,
format_string=None,
delay=False,
filter=None,
bubble=False,
compression_quality=9,
):
self._compression_quality = compression_quality
super(... | GZIPCompressionHandler |
python | getsentry__sentry | src/sentry/search/events/datasets/profile_functions.py | {
"start": 2820,
"end": 3226
} | class ____(ColumnArg):
def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> str:
column = COLUMN_MAP.get(value)
# must be a known column or field alias
if column is None and value not in {PROJECT_ALIAS, PROJECT_NAME_ALIAS}:
raise InvalidFunctionA... | ProfileFunctionColumnArg |
python | mlflow__mlflow | docs/scripts/convert-notebooks.py | {
"start": 509,
"end": 3591
} | class ____(Preprocessor):
def preprocess_cell(self, cell, resources, cell_index):
if cell.cell_type == "code":
# escape backticks, as code blocks will be rendered
# inside a custom react component like:
# <NotebookCellOutput>`{{ content }}`</NotebookCellOutput>
... | EscapeBackticksPreprocessor |
python | scrapy__scrapy | tests/CrawlerProcess/asyncio_enabled_reactor.py | {
"start": 993,
"end": 1302
} | class ____:
def __init__(self):
if not is_asyncio_reactor_installed():
raise RuntimeError("ReactorCheckExtension requires the asyncio reactor.")
if not is_asyncio_available():
raise RuntimeError("ReactorCheckExtension requires asyncio support.")
| ReactorCheckExtension |
python | sympy__sympy | sympy/sets/sets.py | {
"start": 55605,
"end": 56587
} | class ____(Set, metaclass=Singleton):
"""
Represents the set of all things.
The universal set is available as a singleton as ``S.UniversalSet``.
Examples
========
>>> from sympy import S, Interval
>>> S.UniversalSet
UniversalSet
>>> Interval(1, 2).intersect(S.UniversalSet)
Int... | UniversalSet |
python | facelessuser__soupsieve | tests/test_level2/test_child.py | {
"start": 94,
"end": 1671
} | class ____(util.TestCase):
"""Test child combinators."""
MARKUP = """
<div>
<p id="0">Some text <span id="1"> in a paragraph</span>.</p>
<a id="2" href="http://google.com">Link</a>
<span id="3">Direct child</span>
<pre>
<span id="4">Child 1</span>
<span id="5">Child 2</span>
<sp... | TestChild |
python | django__django | tests/prefetch_related/models.py | {
"start": 286,
"end": 712
} | class ____(models.Model):
name = models.CharField(max_length=50, unique=True)
first_book = models.ForeignKey(
"Book", models.CASCADE, related_name="first_time_authors"
)
favorite_authors = models.ManyToManyField(
"self", through="FavoriteAuthors", symmetrical=False, related_name="favors_... | Author |
python | streamlit__streamlit | lib/streamlit/runtime/websocket_session_manager.py | {
"start": 1249,
"end": 6943
} | class ____(SessionManager):
"""A SessionManager used to manage sessions with lifecycles tied to those of a
browser tab's websocket connection.
WebsocketSessionManagers differentiate between "active" and "inactive" sessions.
Active sessions are those with a currently active websocket connection. Inactiv... | WebsocketSessionManager |
python | facebook__pyre-check | pyre_extensions/safe_json.py | {
"start": 519,
"end": 3600
} | class ____(json.JSONDecodeError):
def __init__(self, message: str) -> None:
super().__init__(message, "", 0)
def _is_primitive(target_type: Type[object]) -> bool:
return target_type in (int, float, str, bool)
def _is_list(target_type: Type[object]) -> bool:
return get_origin(target_type) in (Lis... | InvalidJson |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/cfg.py | {
"start": 1931,
"end": 3420
} | class ____(object):
"""A node in the CFG.
Although new instances of this class are mutable, the objects that a user
finds in the CFG are typically not.
The nodes represent edges in the CFG graph, and maintain pointers to allow
efficient walking in both forward and reverse order. The following property
hol... | Node |
python | getsentry__sentry-python | sentry_sdk/integrations/sys_exit.py | {
"start": 319,
"end": 2493
} | class ____(Integration):
"""Captures sys.exit calls and sends them as events to Sentry.
By default, SystemExit exceptions are not captured by the SDK. Enabling this integration will capture SystemExit
exceptions generated by sys.exit calls and send them to Sentry.
This integration, in its default conf... | SysExitIntegration |
python | psf__black | src/black/handle_ipynb_magics.py | {
"start": 800,
"end": 10670
} | class ____:
mask: str
src: str
@lru_cache
def jupyter_dependencies_are_installed(*, warn: bool) -> bool:
installed = (
find_spec("tokenize_rt") is not None and find_spec("IPython") is not None
)
if not installed and warn:
msg = (
"Skipping .ipynb files as Jupyter depend... | Replacement |
python | py-pdf__pypdf | pypdf/_text_extraction/__init__.py | {
"start": 388,
"end": 8519
} | class ____(Exception):
pass
def set_custom_rtl(
_min: Union[str, int, None] = None,
_max: Union[str, int, None] = None,
specials: Union[str, list[int], None] = None,
) -> tuple[int, int, list[int]]:
"""
Change the Right-To-Left and special characters custom parameters.
Args:
_min:... | OrientationNotFoundError |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 19743,
"end": 20662
} | class ____(BaseCrashRateMetricsEntitySubscription):
metric_key: SessionMRI = SessionMRI.RAW_SESSION
def get_snql_aggregations(self) -> list[str]:
return [
"sumIf(session.status, init) as count",
"sumIf(session.status, crashed) as crashed",
]
def get_snql_extra_condi... | MetricsCountersEntitySubscription |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_str.py | {
"start": 151,
"end": 205
} | class ____:
def __str__(self):
return 0
| Int2 |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 28629,
"end": 29589
} | class ____(fixtures.MappedTest):
"""Ensure the mapper doesn't break bind param naming rules on flush."""
@classmethod
def define_tables(cls, metadata):
Table(
"book",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True... | ColumnCollisionTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass4.py | {
"start": 281,
"end": 320
} | class ____:
ff: int
@dataclass
| NonDC2 |
python | pytest-dev__pytest-asyncio | pytest_asyncio/plugin.py | {
"start": 1423,
"end": 12448
} | class ____(str, enum.Enum):
AUTO = "auto"
STRICT = "strict"
ASYNCIO_MODE_HELP = """\
'auto' - for automatically handling all async functions by the plugin
'strict' - for autoprocessing disabling (useful if different async frameworks \
should be tested together, e.g. \
both pytest-asyncio and pytest-trio are u... | Mode |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 12914,
"end": 13277
} | class ____(serializers.Serializer):
code = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
def get_code(self, language):
return language
def get_name(self, language):
for code, name in LANGUAGES:
if code == language:
return nam... | LanguageSerializer |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 38195,
"end": 40594
} | class ____(nn.Module):
def __init__(self, config: Owlv2VisionConfig):
super().__init__()
self.config = config
self.embeddings = Owlv2VisionEmbeddings(config)
self.pre_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.encoder = Owlv2Encoder(config)
... | Owlv2VisionTransformer |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py | {
"start": 21354,
"end": 24297
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.gke_hook = GKEKubernetesHook(
gcp_conn_id="test",
impersonation_chain=IMPERSONATE_CHAIN,
... | TestGKEKubernetesHookPod |
python | facebook__pyre-check | client/command_arguments.py | {
"start": 9916,
"end": 12276
} | class ____:
debug: bool = False
dump_call_graph: Optional[str] = None
dump_model_query_results: Optional[str] = None
enable_memory_profiling: bool = False
enable_profiling: bool = False
find_missing_flows: Optional[MissingFlowsKind] = None
infer_self_tito: bool = True
infer_argument_tito... | AnalyzeArguments |
python | tensorflow__tensorflow | tensorflow/python/ops/parsing_config.py | {
"start": 15150,
"end": 15951
} | class ____(collections.namedtuple(
"FixedLenFeature", ["shape", "dtype", "default_value"])):
"""Configuration for parsing a fixed-length input feature.
To treat sparse input as dense, provide a `default_value`; otherwise,
the parse functions will fail on any examples missing this feature.
Fields:
shap... | FixedLenFeature |
python | doocs__leetcode | solution/1100-1199/1145.Binary Tree Coloring Game/Solution.py | {
"start": 192,
"end": 710
} | class ____:
def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
def dfs(root):
if root is None or root.val == x:
return root
return dfs(root.left) or dfs(root.right)
def count(root):
if root is None:
r... | Solution |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 60774,
"end": 61996
} | class ____(ObserverBase):
r"""This observer is used when we want to reuse the observer from the operator
that produces the input Tensor, typically used for operators like reshape, e.g.
```
x0 = ...
x1 = x0.reshape()
```
if we configure x0 to be observed by some observer, let's say MinMaxObse... | ReuseInputObserver |
python | numba__numba | numba/tests/test_withlifting.py | {
"start": 4885,
"end": 5668
} | class ____(BaseTestWithLifting):
def test_lift1(self):
self.check_extracted_with(lift1, expect_count=1,
expected_stdout="A\nC\n")
def test_lift2(self):
self.check_extracted_with(lift2, expect_count=2,
expected_stdout="A 1\nD 3... | TestLiftByPass |
python | pandas-dev__pandas | pandas/core/indexes/range.py | {
"start": 1657,
"end": 53881
} | class ____(Index):
"""
Immutable Index implementing a monotonic integer range.
RangeIndex is a memory-saving special case of an Index limited to representing
monotonic ranges with a 64-bit dtype. Using RangeIndex may in some instances
improve computing speed.
This is the default index type use... | RangeIndex |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 70922,
"end": 71393
} | class ____(BiffRecord):
"""
This record specifies if the option to print sheet grid lines
(record PRINTGRIDLINES) has ever been changed.
Record GRIDSET, BIFF3-BIFF8:
Offset Size Contents
0 2 0 = Print grid lines option never changed
1 = Print grid lines opti... | GridSetRecord |
python | zostera__django-bootstrap4 | tests/test_media.py | {
"start": 184,
"end": 3434
} | class ____(TestCase):
def expected_css(self, tag):
template = '<link href="{href}" integrity="{integrity}" crossorigin="{crossorigin}" rel="stylesheet">'
setting = get_bootstrap_setting(tag + "_url")
return template.format(**setting)
def expected_js(self, tag):
template = '<scri... | MediaTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 537363,
"end": 537841
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateEnvironment"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "environment")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the ... | CreateEnvironmentPayload |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 321298,
"end": 322553
} | class ____(Request):
"""
Convert public tasks to private
:param ids: Ids of the tasks to convert. Only the tasks originated by the
company can be converted
:type ids: Sequence[str]
"""
_service = "tasks"
_action = "make_private"
_version = "2.13"
_schema = {
"defini... | MakePrivateRequest |
python | django__django | tests/null_fk/models.py | {
"start": 326,
"end": 468
} | class ____(models.Model):
system_info = models.ForeignKey(SystemInfo, models.CASCADE)
forum_name = models.CharField(max_length=32)
| Forum |
python | sympy__sympy | sympy/physics/quantum/cg.py | {
"start": 7162,
"end": 9642
} | class ____(Expr):
"""Class for the Wigner-6j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j, j23):
args = map(sympify, (j1, j2, j12, j3, j, j23))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self... | Wigner6j |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 3163,
"end": 3324
} | class ____(Proto_ContraRecurs):
# This should generate a reportIncompatibleMethodOverride error.
def m(self, x: Self) -> None: ...
| Impl_ContraSelfExplicit1 |
python | ethereum__web3.py | tests/integration/go_ethereum/common.py | {
"start": 3023,
"end": 3114
} | class ____(GoEthereumAdminModuleTest):
pass
# --- async --- #
| GoEthereumAdminModuleTest |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called_py38.py | {
"start": 156,
"end": 295
} | class ____(Protocol):
"""A protocol."""
@abstractmethod
def __init__(self) -> None:
raise NotImplementedError
| MyProtocol |
python | PyCQA__pylint | tests/functional/m/match_class_pattern.py | {
"start": 200,
"end": 238
} | class ____:
__match_args__ = ("x",)
| A |
python | pytorch__pytorch | torch/_lazy/device_context.py | {
"start": 75,
"end": 681
} | class ____:
_CONTEXTS: dict[str, Any] = {}
_CONTEXTS_LOCK = threading.Lock()
def __init__(self, device: str) -> None:
self.device = device
def get_device_context(device: Optional[str] = None) -> DeviceContext:
if device is None:
device = torch._C._lazy._get_default_device_type()
e... | DeviceContext |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 2873,
"end": 2930
} | class ____:
class Inner(Generic[T]):
var: T
| Outer |
python | python-poetry__poetry | src/poetry/plugins/plugin_manager.py | {
"start": 1079,
"end": 3034
} | class ____:
"""
This class registers and activates plugins.
"""
def __init__(self, group: str) -> None:
self._group = group
self._plugins: list[Plugin] = []
@staticmethod
def add_project_plugin_path(directory: Path) -> None:
from poetry.factory import Factory
t... | PluginManager |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 30291,
"end": 31843
} | class ____(CommBufferLine):
def codegen(self, code: IndentedBuffer) -> None:
assert self.node.get_name() not in V.graph.removed_buffers
name = self.node.get_name()
device = self.node.get_device()
dtype = self.node.get_dtype()
shape = tuple(self.node.get_size())
stride... | CommBufferAllocateLine |
python | walkccc__LeetCode | solutions/3181. Maximum Total Reward Using Operations II/3181.py | {
"start": 0,
"end": 391
} | class ____:
# Same as 3180. Maximum Total Reward Using Operations I
def maxTotalReward(self, rewardValues: list[int]) -> int:
dp = 1 # the possible rewards (initially, 0 is achievable)
for num in sorted(rewardValues):
# Remove the numbers >= the current number.
smallerNums = dp & ((1 << num) -... | Solution |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable.py | {
"start": 8981,
"end": 9071
} | class ____:
def say_hello(self) -> __module__: # <3.14:[undefined-variable]
...
| A |
python | kubernetes-client__python | kubernetes/client/models/v1_capabilities.py | {
"start": 383,
"end": 4053
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Capabilities |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_log_util.py | {
"start": 231,
"end": 4969
} | class ____(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.logger = Mock(spec=logging.Logger)
self.time_func = Mock(return_value=0)
self.tracker = BatchPerformanceTracker(
"test_operation",
self.logger,
timedelta(seconds=100),
... | TestBatchPerformanceTracker |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 9459,
"end": 9841
} | class ____(ArgDecorator):
""" Provide other keywords to the sub-parser constructor.
"""
def __init__(self, **kwds):
self.kwds = kwds
def __call__(self, func):
func = super(kwds, self).__call__(func)
func.argcmd_kwds = self.kwds
return func
__all__ = ['magic_arguments',... | kwds |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 29786,
"end": 34573
} | class ____(BaseValidator):
"""
"string": {
"description": "A string value. Numbers are converted to strings
except for attributes with `strict` set to true.",
"requiredOpts": [],
"otherOpts": [
"dflt",
"noBlank",
"strict",
... | StringValidator |
python | pallets__werkzeug | tests/test_http.py | {
"start": 426,
"end": 22852
} | class ____:
def test_accept(self):
a = http.parse_accept_header("en-us,ru;q=0.5")
assert list(a.values()) == ["en-us", "ru"]
assert a.best == "en-us"
assert a.find("ru") == 1
pytest.raises(ValueError, a.index, "de")
assert a.to_header() == "en-us,ru;q=0.5"
def te... | TestHTTPUtility |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.