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 | openai__openai-python | src/openai/resources/beta/assistants.py | {
"start": 1300,
"end": 23090
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> AssistantsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.githu... | Assistants |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/compute_log_manager.py | {
"start": 2882,
"end": 3891
} | class ____(
NamedTuple(
"_CapturedLogMetadata",
[
("stdout_location", Optional[str]),
("stderr_location", Optional[str]),
("stdout_download_url", Optional[str]),
("stderr_download_url", Optional[str]),
],
)
):
"""Object representing met... | CapturedLogMetadata |
python | django-crispy-forms__django-crispy-forms | crispy_forms/layout.py | {
"start": 27145,
"end": 28923
} | class ____(Div):
"""
Layout object. It wraps fields in a ``<div>`` and the template adds the
appropriate class to render the contents in a column. e.g. ``col-md`` when
using the Bootstrap4 template pack.
Attributes
----------
template : str
The default template which this Layout Obj... | Column |
python | Textualize__textual | src/textual/color.py | {
"start": 3803,
"end": 20771
} | class ____(NamedTuple):
"""A class to represent a color.
Colors are stored as three values representing the degree of red, green, and blue in a color, and a
fourth "alpha" value which defines where the color lies on a gradient of opaque to transparent.
Example:
```python
>>> from textu... | Color |
python | ray-project__ray | rllib/models/tests/test_catalog.py | {
"start": 789,
"end": 897
} | class ____(Preprocessor):
def _init_shape(self, obs_space, options):
return [1]
| CustomPreprocessor |
python | spyder-ide__spyder | spyder/widgets/collapsible.py | {
"start": 471,
"end": 4895
} | class ____(QCollapsible):
"""Collapsible widget to hide and show child widgets."""
def __init__(self, parent=None, title=""):
super().__init__(title=title, parent=parent)
# Align widget to the left to text before or after it (don't know why
# this is necessary).
self.layout().s... | CollapsibleWidget |
python | pytorch__pytorch | test/test_fake_tensor.py | {
"start": 70703,
"end": 94599
} | class ____(TestCase):
def test_shape_env_settings(self):
"""
Validation that any boolean settings in ShapeEnv are present in the
ShapeEnvSettings. We hope to ensure that any new settings that might
affect FakeTensor dispatch are included in the cache key calculation.
If this ... | FakeTensorDispatchCache |
python | pytorch__pytorch | torch/backends/cudnn/rnn.py | {
"start": 1047,
"end": 2304
} | class ____:
def __init__(self, inner):
self.inner = inner
def get(self):
return self.inner
def __getstate__(self):
# Note: can't return {}, because python2 won't call __setstate__
# if the value evaluates to False
return "<unserializable>"
def __setstate__(self... | Unserializable |
python | pytest-dev__pytest | src/_pytest/fixtures.py | {
"start": 59028,
"end": 79621
} | class ____:
"""pytest fixture definitions and information is stored and managed
from this class.
During collection fm.parsefactories() is called multiple times to parse
fixture function definitions into FixtureDef objects and internal
data structures.
During collection of test functions, metaf... | FixtureManager |
python | pytorch__pytorch | torch/_inductor/utils.py | {
"start": 4240,
"end": 4644
} | class ____(sympy.Function):
"""Symbolically round up to the nearest multiple of ALIGN_BYTES"""
nargs = (1,)
is_integer = True
@classmethod
def eval(cls, value: sympy.Expr) -> Optional[sympy.Expr]:
if isinstance(value, (int, sympy.Integer)):
return _align(int(value))
if ... | align |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 5186,
"end": 5263
} | class ____:
def func(self, user_input: FooT1) -> None:
pass
| ParentT3 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar8.py | {
"start": 127,
"end": 560
} | class ____:
def __init__(self, x: Any) -> None:
pass
def f(self) -> None:
pass
T = TypeVar("T", str, int, A)
def factory(desired_type: type[T]) -> T:
return desired_type(1)
factory(str)
reveal_type(factory(str), expected_text="str")
factory(int)
reveal_type(factory(int), expected_tex... | A |
python | kubernetes-client__python | kubernetes/client/models/v1_lifecycle.py | {
"start": 383,
"end": 5331
} | 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... | V1Lifecycle |
python | jackfrued__Python-100-Days | 公开课/年薪50W+的Python程序员如何写代码/code/Python/opencourse/part01/example05.py | {
"start": 63,
"end": 327
} | class ____(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write('<h1>goodbye, world</h1>'.encode())
server = HTTPServer(('', 8000), RequestHandler)
server.serve_forever()
| RequestHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass6.py | {
"start": 664,
"end": 827
} | class ____(ParentA):
prop_2: str = "bye"
test = ChildA(prop_2="test", prop_4="hi")
assert test.prop_1 == "test"
assert test.prop_2 == "test"
@dataclass
| ChildA |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 361910,
"end": 376165
} | class ____(VegaLiteSchema):
r"""
FacetFieldDef schema wrapper.
Parameters
----------
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'c... | FacetFieldDef |
python | bokeh__bokeh | tests/support/plugins/managed_server_loop.py | {
"start": 1554,
"end": 2637
} | class ____(Protocol):
def __call__(self, application: Application, port: int | None = None, **server_kwargs: Any) -> ContextManager[Server]: ...
@pytest.fixture
def ManagedServerLoop(unused_tcp_port: int) -> MSL:
@contextmanager
def msl(application: Application, port: int | None = None, **server_kwargs: An... | MSL |
python | django__django | tests/template_tests/filter_tests/test_truncatechars.py | {
"start": 68,
"end": 1074
} | class ____(SimpleTestCase):
@setup({"truncatechars01": "{{ a|truncatechars:3 }}"})
def test_truncatechars01(self):
output = self.engine.render_to_string(
"truncatechars01", {"a": "Testing, testing"}
)
self.assertEqual(output, "Te…")
@setup({"truncatechars02": "{{ a|trunc... | TruncatecharsTests |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_named_vectors.py | {
"start": 3119,
"end": 64617
} | class ____:
@staticmethod
def none(
name: str, *, vector_index_config: Optional[_VectorIndexConfigCreate] = None
) -> _NamedVectorConfigCreate:
"""Create a named vector using no vectorizer. You will need to provide the vectors yourself.
Args:
name: The name of the named ... | _NamedVectors |
python | encode__httpx | httpx/_transports/asgi.py | {
"start": 1132,
"end": 1352
} | class ____(AsyncByteStream):
def __init__(self, body: list[bytes]) -> None:
self._body = body
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
yield b"".join(self._body)
| ASGIResponseStream |
python | Pylons__pyramid | docs/tutorials/wiki2/src/tests/tests/test_views.py | {
"start": 3523,
"end": 4944
} | class ____:
def _callFUT(self, request):
from tutorial.views.default import edit_page
return edit_page(request)
def _makeContext(self, page):
from tutorial.routes import PageResource
return PageResource(page)
def _addRoutes(self, config):
config.add_route('edit_page... | Test_edit_page |
python | getsentry__sentry | tests/sentry/notifications/api/endpoints/test_user_notification_settings_options.py | {
"start": 363,
"end": 500
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-notification-options"
@control_silo_test
| UserNotificationSettingsOptionsBaseTest |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 1103,
"end": 1306
} | class ____(analytics.Event):
organization_id: int
project_id: int
user_id: int | None = None
@analytics.eventclass("preprod_artifact.api.admin_rerun_analysis")
| PreprodArtifactApiListBuildsEvent |
python | huggingface__transformers | tests/models/vivit/test_image_processing_vivit.py | {
"start": 3004,
"end": 10210
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = VivitImageProcessor if is_vision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = VivitImageProcessingTester(self)
@property
def image_processor_dict(self):
ret... | VivitImageProcessingTest |
python | ApeWorX__ape | src/ape_ethereum/transactions.py | {
"start": 1252,
"end": 1591
} | class ____(IntEnum):
"""
An ``Enum`` class representing the status of a transaction.
"""
FAILING = 0
"""The transaction has failed or is in the process of failing."""
NO_ERROR = 1
"""
The transaction is successful and is confirmed or is in the process
of getting confirmed.
"""
... | TransactionStatusEnum |
python | kamyu104__LeetCode-Solutions | Python/number-of-burgers-with-no-waste-of-ingredients.py | {
"start": 29,
"end": 742
} | class ____(object):
def numOfBurgers(self, tomatoSlices, cheeseSlices):
"""
:type tomatoSlices: int
:type cheeseSlices: int
:rtype: List[int]
"""
# let the number of jumbo burger be x, the number of small burger be y:
# 4x + 2y = t
# x + y = c
... | Solution |
python | joke2k__faker | faker/providers/job/pt_BR/__init__.py | {
"start": 130,
"end": 20212
} | class ____(BaseProvider):
jobs = [
"Acompanhante",
"Açougueiro",
"Acupunturista",
"Adestrador de animais",
"Administrador",
"Administrador de banco de dados DBA",
"Administrador de redes",
"Administrador público",
"Advogado",
"Aeromoça"... | Provider |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_iana_timezone.py | {
"start": 761,
"end": 1810
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.iana_timezone"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cl... | ColumnValuesIanaTimezone |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 13047,
"end": 14639
} | class ____(Structure):
_fields_ = (("cmd", p_uint32), ("cmdsize", p_uint32))
def get_cmd_name(self):
return LC_NAMES.get(self.cmd, self.cmd)
LC_REQ_DYLD = 0x80000000
(
LC_SEGMENT,
LC_SYMTAB,
LC_SYMSEG,
LC_THREAD,
LC_UNIXTHREAD,
LC_LOADFVMLIB,
LC_IDFVMLIB,
LC_IDENT,
... | load_command |
python | great-expectations__great_expectations | great_expectations/types/connect_args.py | {
"start": 41,
"end": 168
} | class ____(TypedDict, total=False):
"""Type definition for connection arguments."""
private_key: Optional[str]
| ConnectArgs |
python | fluentpython__example-code | 10-seq-hacking/vector_v3.py | {
"start": 3146,
"end": 5542
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | walkccc__LeetCode | solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py | {
"start": 0,
"end": 609
} | class ____:
def __init__(self, n: int):
self.count = n
self.id = list(range(n))
self.rank = [0] * n
def unionByRank(self, u: int, v: int) -> None:
i = self._find(u)
j = self._find(v)
if i == j:
return
if self.rank[i] < self.rank[j]:
self.id[i] = j
elif self.rank[i] > sel... | UnionFind |
python | spyder-ide__spyder | spyder/plugins/application/widgets/about.py | {
"start": 1059,
"end": 13189
} | class ____(QDialog, SvgToScaledPixmap):
PADDING = 5 if MAC else 15
def __init__(self, parent):
"""Create About Spyder dialog with general information."""
QDialog.__init__(self, parent)
self.setWindowFlags(
self.windowFlags() & ~Qt.WindowContextHelpButtonHint
)
... | AboutDialog |
python | PrefectHQ__prefect | tests/utilities/test_templating.py | {
"start": 413,
"end": 4846
} | class ____:
def test_empty_template(self):
template = ""
placeholders = find_placeholders(template)
assert len(placeholders) == 0
def test_single_placeholder(self):
template = "Hello {{name}}!"
placeholders = find_placeholders(template)
assert len(placeholders) =... | TestFindPlaceholders |
python | scikit-learn__scikit-learn | sklearn/multioutput.py | {
"start": 30671,
"end": 40251
} | class ____(MetaEstimatorMixin, ClassifierMixin, _BaseChain):
"""A multi-label model that arranges binary classifiers into a chain.
Each model makes a prediction in the order specified by the chain using
all of the available features provided to the model plus the predictions
of models that are earlier ... | ClassifierChain |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-oracleai/llama_index/readers/oracleai/base.py | {
"start": 13133,
"end": 14581
} | class ____:
"""Splitting text using Oracle chunker."""
def __init__(self, conn: Connection, params: Dict[str, Any]):
self.conn = conn
self.params = params
try:
import oracledb
except ImportError as e:
raise ImportError(
"Unable to import ... | OracleTextSplitter |
python | streamlit__streamlit | lib/tests/streamlit/elements/alert_test.py | {
"start": 960,
"end": 2370
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall Alert proto."""
@parameterized.expand([(st.error,), (st.warning,), (st.info,), (st.success,)])
def test_st_alert_exceptions(self, alert_func):
"""Test that alert functions throw an exception when a non-emoji is given as an icon."""
... | AlertAPITest |
python | sqlalchemy__sqlalchemy | test/sql/test_type_expressions.py | {
"start": 541,
"end": 3560
} | class ____:
def _test_table(self, type_):
test_table = Table(
"test_table", MetaData(), Column("x", String), Column("y", type_)
)
return test_table
def _fixture(self):
class MyString(String):
# supersedes any processing that might be on
# Stri... | _ExprFixture |
python | pallets__werkzeug | src/werkzeug/middleware/http_proxy.py | {
"start": 551,
"end": 7834
} | class ____:
"""Proxy requests under a path to an external server, routing other
requests to the app.
This middleware can only proxy HTTP requests, as HTTP is the only
protocol handled by the WSGI server. Other protocols, such as
WebSocket requests, cannot be proxied at this layer. This should
o... | ProxyMiddleware |
python | getsentry__sentry | src/sentry/profiles/task.py | {
"start": 23451,
"end": 41450
} | class ____(Exception):
pass
@metrics.wraps("process_profile.symbolicate.request")
def run_symbolicate(
project: Project,
profile: Profile,
modules: list[Any],
stacktraces: list[Any],
frame_order: FrameOrder,
platform: str,
) -> tuple[list[Any], list[Any], bool]:
symbolication_start_tim... | SymbolicationTimeout |
python | openai__openai-python | src/openai/types/responses/response_audio_done_event.py | {
"start": 199,
"end": 414
} | class ____(BaseModel):
sequence_number: int
"""The sequence number of the delta."""
type: Literal["response.audio.done"]
"""The type of the event. Always `response.audio.done`."""
| ResponseAudioDoneEvent |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg_catalog.py | {
"start": 1340,
"end": 10417
} | class ____:
def result_processor(
self, dialect: Dialect, coltype: object
) -> _ResultProcessorType[list[int]]:
def process(value: Any) -> Optional[list[int]]:
if value is None:
return value
return [int(p) for p in value.split(" ")]
return process... | _SpaceVector |
python | squidfunk__mkdocs-material | material/plugins/projects/plugin.py | {
"start": 1969,
"end": 12022
} | class ____(BasePlugin[ProjectsConfig]):
# Projects builder
builder: ProjectsBuilder = None
# Initialize plugin
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Initialize incremental builds
self.is_serve = False
self.is_dirty = False
# ... | ProjectsPlugin |
python | facebookresearch__faiss | tests/test_io.py | {
"start": 13019,
"end": 14060
} | class ____(unittest.TestCase):
def test_reader(self):
d, n = 32, 1000
xq = np.random.uniform(size=(n, d)).astype('float32')
xb = np.random.uniform(size=(n, d)).astype('float32')
index = faiss.index_factory(32, "IVF32,PQ16np", faiss.METRIC_L2)
index.train(xb)
index.ad... | TestIVFPQRead |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 2284,
"end": 2999
} | class ____(ABC):
"""How to load the data for a step input."""
@property
def step_key_dependencies(self) -> set[str]:
return set()
@property
def step_output_handle_dependencies(self) -> Sequence[StepOutputHandle]:
return []
@abstractmethod
def load_input_object(
sel... | StepInputSource |
python | pandas-dev__pandas | pandas/tests/frame/test_query_eval.py | {
"start": 37490,
"end": 38065
} | class ____(TestDataFrameQueryNumExprPython):
@pytest.fixture
def engine(self):
return "python"
@pytest.fixture
def parser(self):
return "python"
def test_query_builtin(self, engine, parser):
n = m = 10
df = DataFrame(
np.random.default_rng(2).integers(m,... | TestDataFrameQueryPythonPython |
python | plotly__plotly.py | plotly/graph_objs/scattermapbox/marker/_colorbar.py | {
"start": 233,
"end": 61773
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermapbox.marker"
_path_str = "scattermapbox.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
... | ColorBar |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 981761,
"end": 982147
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("Sponsorship", graphql_nam... | SponsorshipEdge |
python | pypa__pip | src/pip/_vendor/rich/panel.py | {
"start": 467,
"end": 11157
} | class ____(JupyterMixin):
"""A console renderable that draws a border around its contents.
Example:
>>> console.print(Panel("Hello, World!"))
Args:
renderable (RenderableType): A console renderable object.
box (Box): A Box instance that defines the look of the border (see :ref:`app... | Panel |
python | wandb__wandb | wandb/jupyter.py | {
"start": 936,
"end": 2642
} | class ____:
"""State for a cell with the %%wandb cell magic."""
def __init__(self, *, height: int) -> None:
"""Initializes the %%wandb cell magic state.
Args:
height: The desired height for displayed iframes.
"""
self._height = height
self._already_displayed... | _WandbCellMagicState |
python | pandas-dev__pandas | pandas/core/internals/api.py | {
"start": 2259,
"end": 5615
} | class ____(DatetimeLikeBlock):
"""implement a datetime64 block with a tz attribute"""
values: DatetimeArray
__slots__ = ()
def make_block(
values, placement, klass=None, ndim=None, dtype: Dtype | None = None
) -> Block:
"""
This is a pseudo-public analogue to blocks.new_block.
We ask th... | _DatetimeTZBlock |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 93890,
"end": 94091
} | class ____(
ScalarRemoveTest, fixtures.DeclarativeMappedTest
):
run_create_tables = None
useobject = True
cascade_scalar_deletes = False
uselist = True
| ScalarRemoveListObjectNoCascade |
python | numpy__numpy | benchmarks/benchmarks/bench_reduce.py | {
"start": 2351,
"end": 2682
} | class ____(Benchmark):
params = [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32,
np.int64, np.uint64, np.float32, np.float64, bool]
param_names = ['dtype']
def setup(self, dtype):
self.d = np.ones(200000, dtype=dtype)
def time_argmin(self, dtype):
np.argmin(s... | ArgMin |
python | python__mypy | misc/generate_changelog.py | {
"start": 847,
"end": 6556
} | class ____:
commit: str
author: str
title: str
pr_number: int | None
def normalize_author(author: str) -> str:
# Some ad-hoc rules to get more consistent author names.
if author == "AlexWaygood":
return "Alex Waygood"
elif author == "jhance":
return "Jared Hance"
return... | CommitInfo |
python | readthedocs__readthedocs.org | readthedocs/redirects/admin.py | {
"start": 148,
"end": 594
} | class ____(admin.ModelAdmin):
list_display = [
"project",
"redirect_type",
"from_url",
"to_url",
"position",
"enabled",
]
list_select_related = ("project",)
list_filter = ("redirect_type", "enabled")
raw_id_fields = ("project",)
search_fields = (
... | RedirectAdmin |
python | huggingface__transformers | tests/models/xcodec/test_modeling_xcodec.py | {
"start": 3669,
"end": 11554
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (XcodecModel,) if is_torch_available() else ()
is_encoder_decoder = True
test_resize_embeddings = False
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
# model does not support returning hidden st... | XcodecModelTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_batch.py | {
"start": 3576,
"end": 4431
} | class ____:
@mock.patch(CLOUD_BATCH_HOOK_PATH)
def test_execute(self, hook_mock):
delete_operation_mock = self._delete_operation_mock()
hook_mock.return_value.delete_job.return_value = delete_operation_mock
operator = CloudBatchDeleteJobOperator(
task_id=TASK_ID,
... | TestCloudBatchDeleteJobOperator |
python | pypa__pip | src/pip/_internal/commands/list.py | {
"start": 1342,
"end": 13514
} | class ____(IndexGroupCommand):
"""
List installed packages, including editables.
Packages are listed in a case-insensitive sorted order.
"""
ignore_require_venv = True
usage = """
%prog [options]"""
def add_options(self) -> None:
self.cmd_opts.add_option(
"-o",
... | ListCommand |
python | Pylons__pyramid | src/pyramid/config/factories.py | {
"start": 447,
"end": 9175
} | class ____:
@action_method
def set_root_factory(self, factory):
"""Add a :term:`root factory` to the current configuration
state. If the ``factory`` argument is ``None`` a default root
factory will be registered.
.. note::
Using the ``root_factory`` argument to the
... | FactoriesConfiguratorMixin |
python | huggingface__transformers | tests/models/pix2struct/test_modeling_pix2struct.py | {
"start": 27474,
"end": 32382
} | class ____(unittest.TestCase):
def test_inference_image_captioning(self):
model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base").to(torch_device)
processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-base")
image = prepare_img()
... | Pix2StructIntegrationTest |
python | pytest-dev__pytest | testing/test_assertion.py | {
"start": 14216,
"end": 31299
} | class ____:
def test_different_types(self) -> None:
assert callequal([0, 1], "foo") is None
def test_summary(self) -> None:
lines = callequal([0, 1], [0, 2])
assert lines is not None
summary = lines[0]
assert len(summary) < 65
def test_text_diff(self) -> None:
... | TestAssert_reprcompare |
python | huggingface__transformers | src/transformers/models/apertus/modular_apertus.py | {
"start": 1407,
"end": 8907
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ApertusModel`]. It is used to instantiate a Apertus
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar confi... | ApertusConfig |
python | sympy__sympy | sympy/assumptions/assume.py | {
"start": 4723,
"end": 6485
} | class ____(type):
def __new__(cls, clsname, bases, dct):
# If handler is not defined, assign empty dispatcher.
if "handler" not in dct:
name = f"Ask{clsname.capitalize()}Handler"
handler = Dispatcher(name, doc=f"Handler for key {name}")
dct["handler"] = handler
... | PredicateMeta |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_unittest/test_assertions.py | {
"start": 6472,
"end": 18605
} | class ____(__TestCase):
"""Test that the individual asserts honour longMessage.
This actually tests all the message behaviour for
asserts that use longMessage."""
def setUp(self):
super().setUp()
class TestableTestFalse(unittest.TestCase):
longMessage = False
fai... | TestLongMessage |
python | getsentry__sentry | src/sentry/snuba/metrics/extraction.py | {
"start": 41899,
"end": 42013
} | class ____:
function: str
arguments: Sequence[str]
alias: str
@dataclass(frozen=True)
| FieldParsingResult |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 1478,
"end": 1785
} | class ____(BaseBackend):
def get_user_permissions(self, user_obj, obj=None):
return ["user_perm"]
def get_group_permissions(self, user_obj, obj=None):
return ["group_perm"]
@override_settings(
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleBackend"]
)
| SimpleBackend |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 24594,
"end": 25422
} | class ____(ModuleWithDelay):
@staticmethod
def init( # type: ignore[override]
group: dist.ProcessGroup,
fsdp_init_mode: FSDPInitMode,
device_init_mode: DEVICEInitMode = DEVICEInitMode.DEVICE_AFTER,
fsdp_kwargs: Optional[dict[str, Any]] = None,
deterministic: bool = False... | NestedWrappedModuleWithDelay |
python | encode__django-rest-framework | rest_framework/renderers.py | {
"start": 14669,
"end": 29493
} | class ____(BaseRenderer):
"""
HTML renderer used to self-document the API.
"""
media_type = 'text/html'
format = 'api'
template = 'rest_framework/api.html'
filter_template = 'rest_framework/filters/base.html'
code_style = 'emacs'
charset = 'utf-8'
form_renderer_class = HTMLFormRe... | BrowsableAPIRenderer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol3.py | {
"start": 2513,
"end": 2619
} | class ____:
@property
def bar(self: C6) -> ContextManager[C6]: ...
i: MockClass6 = Class6()
| Class6 |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 181880,
"end": 182210
} | class ____(PyrexType):
# Used as a placeholder until the type can be determined.
is_unspecified = 1
def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0):
return "<unspecified>"
def same_as_resolved_type(self, other_type):
return False
| UnspecifiedType |
python | django__django | tests/test_runner/test_debug_sql.py | {
"start": 6575,
"end": 11786
} | class ____(unittest.TestCase):
class PassingTest(TestCase):
def runTest(self):
Person.objects.filter(first_name="pass").count()
class FailingTest(TestCase):
def runTest(self):
Person.objects.filter(first_name="fail").count()
self.fail()
class ErrorTest(T... | TestDebugSQL |
python | spack__spack | lib/spack/spack/modules/lmod.py | {
"start": 18938,
"end": 19130
} | class ____(spack.error.SpackError, TypeError):
"""Error raised if non-virtual specs are used as hierarchy tokens in
the lmod section of ``modules.yaml``.
"""
| NonVirtualInHierarchyError |
python | huggingface__transformers | src/transformers/pipelines/automatic_speech_recognition.py | {
"start": 4077,
"end": 33333
} | class ____(ChunkPipeline):
"""
Pipeline that aims at extracting spoken text contained within some audio.
The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for
to support multiple audio formats
Unless the model you're using explicitly sets... | AutomaticSpeechRecognitionPipeline |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super4.py | {
"start": 391,
"end": 572
} | class ____(Parent1["Child1"]):
@classmethod
def construct(cls) -> "Child1":
return super().construct()
reveal_type(Child1.construct(), expected_text="Child1")
| Child1 |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/sql_dataset_test.py | {
"start": 28130,
"end": 29214
} | class ____(SqlDatasetTestBase,
checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self, num_repeats):
data_source_name = os.path.join(test.get_temp_dir(), "tftest.sqlite")
driver_name = array_ops.placeholder_with_... | SqlDatasetCheckpointTest |
python | doocs__leetcode | solution/0800-0899/0885.Spiral Matrix III/Solution.py | {
"start": 0,
"end": 664
} | class ____:
def spiralMatrixIII(
self, rows: int, cols: int, rStart: int, cStart: int
) -> List[List[int]]:
ans = [[rStart, cStart]]
if rows * cols == 1:
return ans
k = 1
while True:
for dr, dc, dk in [[0, 1, k], [1, 0, k], [0, -1, k + 1], [-1, 0, ... | Solution |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 13024,
"end": 14012
} | class ____(object):
"""*
jina gRPC service to expose Endpoints from Executors.
"""
def dry_run(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | JinaGatewayDryRunRPCServicer |
python | langchain-ai__langchain | libs/partners/mistralai/langchain_mistralai/embeddings.py | {
"start": 858,
"end": 1095
} | class ____:
"""Dummy tokenizer for when tokenizer cannot be accessed (e.g., via Huggingface)."""
@staticmethod
def encode_batch(texts: list[str]) -> list[list[str]]:
return [list(text) for text in texts]
| DummyTokenizer |
python | getsentry__sentry | tests/acceptance/test_proxy.py | {
"start": 1216,
"end": 2840
} | class ____(TransactionTestCase):
live_server: LiveServer
endpoint = "sentry-api-0-organization-teams"
method = "post"
organization: Organization
api_key: ApiKey
def get_response(self, *args: str, **params: Any) -> HttpResponse | StreamingHttpResponse:
url = reverse(self.endpoint, args=a... | EndToEndAPIProxyTest |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/_utils.py | {
"start": 18889,
"end": 19213
} | class ____(LoadFromBytesImpl):
def load_from_bytes(self, byte_values: list[bytes | None]) -> pl.Series:
import polars as pl
return (
pl.Series(byte_values, dtype=pl.Binary)
.bin.reinterpret(dtype=pl.Int32, endianness="little")
.cast(pl.Date)
)
| LoadDateFromBytes |
python | huggingface__transformers | src/transformers/models/dinov2/modeling_dinov2.py | {
"start": 10930,
"end": 11352
} | class ____(nn.Module):
def __init__(self, config: Dinov2Config):
super().__init__()
self.attention = Dinov2SelfAttention(config)
self.output = Dinov2SelfOutput(config)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
self_attn_output, _ = self.attention(hidden_sta... | Dinov2Attention |
python | kamyu104__LeetCode-Solutions | Python/substrings-that-begin-and-end-with-the-same-letter.py | {
"start": 377,
"end": 579
} | class ____(object):
def numberOfSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
return sum(v*(v+1)//2 for v in collections.Counter(s).itervalues())
| Solution |
python | python-poetry__poetry | src/poetry/repositories/repository.py | {
"start": 662,
"end": 3821
} | class ____(AbstractRepository):
def __init__(self, name: str, packages: Sequence[Package] | None = None) -> None:
super().__init__(name)
self._packages: list[Package] = []
for package in packages or []:
self.add_package(package)
@property
def packages(self) -> list[Pack... | Repository |
python | getsentry__sentry | src/sentry/models/groupemailthread.py | {
"start": 219,
"end": 1202
} | class ____(Model):
"""
Keep track of the original Message-Id that was sent
unique per email destination and Group object.This allows
the tracking of proper In-Reply-To and References headers
for email threading.
"""
__relocation_scope__ = RelocationScope.Excluded
email = models.EmailFi... | GroupEmailThread |
python | ray-project__ray | python/ray/serve/tests/test_standalone_2.py | {
"start": 9548,
"end": 10602
} | class ____:
def __call__(self):
return "Hello B"
serve.run(B.bind())"""
f1 = tmp_path / "file1.py"
f1.write_text(file1)
# Driver 1 (starts Serve controller)
output = subprocess.check_output(
[sys.executable, str(f1)], stderr=subprocess.STDOUT
)
assert "Connecting to existing... | B |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/cloud_providers/read_only/cloud_provider.py | {
"start": 524,
"end": 2680
} | class ____(ICloudInstanceProvider):
"""
A read only provider that use the ray node states from the GCS as the
cloud instances.
This is used for laptop mode / manual cluster setup modes, in order to
provide status reporting in the same way for users.
"""
def __init__(self, provider_config: ... | ReadOnlyProvider |
python | pyca__cryptography | tests/hazmat/primitives/test_serialization.py | {
"start": 52618,
"end": 55458
} | class ____:
def test_load_der_private_key(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "Ed25519", "ed25519-pkcs8-enc.der"),
lambda derfile: derfile.read(),
mode="rb",
)
unencrypted = load_vectors_from_file(
os.path.... | TestEd25519Serialization |
python | joke2k__faker | faker/providers/geo/tr_TR/__init__.py | {
"start": 41,
"end": 6700
} | class ____(GeoProvider):
# Source: https://tr.wikipedia.org/wiki/T%C3%BCrkiye%27nin_illeri
land_coords = (
("37.003277000000004", "35.3261219", "Adana", "TR", "Europe/Istanbul"),
("37.7640008", "38.2764355", "Adıyaman", "TR", "Europe/Istanbul"),
(
"38.756850899999996",
... | Provider |
python | google__jax | jax/experimental/mosaic/gpu/constraints.py | {
"start": 23290,
"end": 32388
} | class ____:
...
def non_splat_variables(
constraints: Sequence[Constraint],
) -> set[Variable]:
"""Returns a all vars distinct from a splat."""
vars: set[Variable] = set()
for constraint in constraints:
match constraint:
case NotOfType(expr=Variable() as var, type=fa.WGSplatFragLayout):
... | Tautological |
python | pandas-dev__pandas | pandas/io/sas/sas7bdat.py | {
"start": 3002,
"end": 27011
} | class ____(SASReader):
"""
Read SAS files in SAS7BDAT format.
Parameters
----------
path_or_buf : path name or buffer
Name of SAS file or file-like object pointing to SAS file
contents.
index : column identifier, defaults to None
Column to use as index.
convert_dates... | SAS7BDATReader |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 53015,
"end": 56026
} | class ____(np.recarray, MaskedNDArray, data_cls=np.recarray):
# Explicit definition since we need to override some methods.
info = MaskedRecarrayInfo()
def __array_finalize__(self, obj):
# recarray.__array_finalize__ does not do super, so we do it
# explicitly.
super().__array_fina... | MaskedRecarray |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/websocket_client.py | {
"start": 15089,
"end": 16956
} | class ____:
time_to_dead: float = 1.0
def __init__(
self,
websocket: aiohttp.ClientWebSocketResponse,
):
self._websocket = websocket
self._websocket._handle_ping_pong_exception = MethodType(
self._handle_heartbeat_exc(
self._websocket._handle_ping... | _WebSocketHBChannel |
python | walkccc__LeetCode | solutions/3529. Count Cells in Overlapping Horizontal and Vertical Substrings/3529.py | {
"start": 0,
"end": 1953
} | class ____:
def countCells(self, grid: list[list[str]], pattern: str) -> int:
BASE = 13
HASH = 1_000_000_007
m = len(grid)
n = len(grid[0])
def markMatchedCells(flattenedGrid: str, isHorizontal: bool) -> list[list[bool]]:
matchMatrix = [[False] * n for _ in range(m)]
matchPrefix = [0]... | Solution |
python | davidhalter__parso | parso/python/tokenize.py | {
"start": 8263,
"end": 8651
} | class ____(NamedTuple):
type: PythonTokenTypes
string: str
start_pos: Tuple[int, int]
prefix: str
@property
def end_pos(self) -> Tuple[int, int]:
lines = split_lines(self.string)
if len(lines) > 1:
return self.start_pos[0] + len(lines) - 1, 0
else:
... | Token |
python | doocs__leetcode | solution/3100-3199/3144.Minimum Substring Partition of Equal Character Frequency/Solution3.py | {
"start": 0,
"end": 448
} | class ____:
def minimumSubstringsInPartition(self, s: str) -> int:
n = len(s)
f = [inf] * (n + 1)
f[0] = 0
for i in range(n):
cnt = defaultdict(int)
m = 0
for j in range(i, -1, -1):
cnt[s[j]] += 1
m = max(m, cnt[s[j]... | Solution |
python | coleifer__peewee | playhouse/reflection.py | {
"start": 11015,
"end": 12052
} | class ____(PostgresqlMetadata):
# CRDB treats INT the same as BIGINT, so we just map bigint type OIDs to
# regular IntegerField.
column_map = PostgresqlMetadata.column_map.copy()
column_map[20] = IntegerField
array_types = PostgresqlMetadata.array_types.copy()
array_types[1016] = IntegerField
... | CockroachDBMetadata |
python | pypa__pipenv | pipenv/patched/pip/_internal/exceptions.py | {
"start": 20274,
"end": 21256
} | class ____(ConfigurationError):
"""When there are errors while loading a configuration file"""
def __init__(
self,
reason: str = "could not be loaded",
fname: Optional[str] = None,
error: Optional[configparser.Error] = None,
) -> None:
super().__init__(error)
... | ConfigurationFileCouldNotBeLoaded |
python | django__django | django/test/runner.py | {
"start": 4829,
"end": 5001
} | class ____:
"""
Dummy list class for faking storage of results in unittest.TestResult.
"""
__slots__ = ()
def append(self, item):
pass
| DummyList |
python | scikit-learn__scikit-learn | sklearn/ensemble/_voting.py | {
"start": 18275,
"end": 24898
} | class ____(RegressorMixin, _BaseVoting):
"""Prediction voting regressor for unfitted estimators.
A voting regressor is an ensemble meta-estimator that fits several base
regressors, each on the whole dataset. Then it averages the individual
predictions to form a final prediction.
For a detailed exa... | VotingRegressor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mailchimp/unit_tests/test_config_datacenter_migration.py | {
"start": 3793,
"end": 4895
} | class ____:
"""Integration tests using actual config files."""
@pytest.mark.parametrize(
"config_path,expected_data_center",
[
("test_configs/test_config_api_key.json", "us10"),
("test_configs/test_config_oauth.json", "us10"),
],
ids=["api_key_config", "o... | TestExtractAndSetDataCenterConfigValueIntegration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.