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 | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 61676,
"end": 61830
} | class ____(_PrintableStructure):
_fields_ = [
('referenceTime', c_ulonglong),
('violationTime', c_ulonglong),
]
| c_nvmlViolationTime_t |
python | sqlalchemy__sqlalchemy | test/orm/test_assorted_eager.py | {
"start": 26123,
"end": 29643
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"companies",
metadata,
Column(
"company_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),... | EagerTest7 |
python | google__pytype | pytype/tests/test_typing2.py | {
"start": 132,
"end": 22382
} | class ____(test_base.BaseTest):
"""Tests for typing.py."""
_TEMPLATE = """
import collections
import typing
def f(s: %(annotation)s):%(disables)s
return s
f(%(arg)s)
"""
def _test_match(self, arg, annotation, disables=""):
self.Check(self._TEMPLATE % locals())
def _test_no_match(s... | TypingTest |
python | keras-team__keras | keras/src/metrics/probabilistic_metrics.py | {
"start": 419,
"end": 1692
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Computes Kullback-Leibler divergence metric between `y_true` and
`y_pred`.
Formula:
```python
metric = y_true * log(y_true / y_pred)
```
`y_true` and `y_pred` are expected to be probability
distributions, with values between 0 and 1.... | KLDivergence |
python | python__mypy | mypy/plugins/attrs.py | {
"start": 2908,
"end": 39102
} | class ____:
"""The value of an attr.ib() call."""
def __init__(
self,
name: str,
alias: str | None,
info: TypeInfo,
has_default: bool,
init: bool,
kw_only: bool,
converter: Converter | None,
context: Context,
init_type: Type | None... | Attribute |
python | agronholm__apscheduler | src/apscheduler/_events.py | {
"start": 3170,
"end": 3575
} | class ____(DataStoreEvent):
"""
Signals that a new job was added to the store.
:ivar job_id: ID of the job that was added
:ivar task_id: ID of the task the job would run
:ivar schedule_id: ID of the schedule the job was created from
"""
job_id: UUID = attrs.field(converter=as_uuid)
tas... | JobAdded |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 2339,
"end": 4878
} | class ____(Metadata):
codec_name: str
codec_config: dict[str, JSON]
def __init_subclass__(cls, *, codec_name: str | None = None, **kwargs: Any) -> None:
"""To be used only when creating the actual public-facing codec class."""
super().__init_subclass__(**kwargs)
if codec_name is not... | _NumcodecsCodec |
python | sphinx-doc__sphinx | sphinx/directives/other.py | {
"start": 8862,
"end": 9495
} | class ____(SphinxDirective):
"""Directive for a list of names."""
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
children = self.parse_content_to_nodes()
... | Acks |
python | pytorch__pytorch | test/test_tensor_creation_ops.py | {
"start": 3397,
"end": 154551
} | class ____(TestCase):
exact_dtype = True
@onlyCPU
@dtypes(torch.float)
def test_diag_embed(self, device, dtype):
x = torch.arange(3 * 4, dtype=dtype, device=device).view(3, 4)
result = torch.diag_embed(x)
expected = torch.stack([torch.diag(r) for r in x], 0)
self.assertE... | TestTensorCreation |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/embedding_ops.py | {
"start": 294,
"end": 3038
} | class ____(torch.nn.Module):
_version = 1
def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8):
super().__init__()
self.dtype = dtype
if self.dtype in [torch.quint8, torch.quint4x2]:
scales = torch.ones(num_embeddings, dtype=torch.float)
zero_poi... | EmbeddingPackedParams |
python | hynek__structlog | tests/processors/test_processors.py | {
"start": 6966,
"end": 7656
} | class ____:
@pytest.mark.parametrize("true_value", [True, 1, 1.1])
def test_obtains_exc_info_on_True(self, true_value):
"""
If the passed argument evaluates to True obtain exc_info ourselves.
"""
try:
0 / 0
except Exception:
assert sys.exc_info() =... | TestFigureOutExcInfo |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_data_condition_index.py | {
"start": 3163,
"end": 5285
} | class ____(OrganizationDataConditionAPITestCase):
def test_group_filter(self) -> None:
response = self.get_success_response(
self.organization.slug,
group=DataConditionHandler.Group.WORKFLOW_TRIGGER,
status_code=200,
)
assert len(response.data) == 1
... | OrganizationDataConditionIndexBaseTest |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-vertex/llama_index/embeddings/vertex/base.py | {
"start": 3834,
"end": 8876
} | class ____(BaseEmbedding):
embed_mode: VertexEmbeddingMode = Field(
default=VertexEmbeddingMode.RETRIEVAL_MODE,
description="The embedding mode to use.",
)
additional_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Additional kwargs for the Vertex."
)
clien... | VertexTextEmbedding |
python | ApeWorX__ape | src/ape_ethereum/multicall/exceptions.py | {
"start": 415,
"end": 557
} | class ____(MulticallException):
def __init__(self):
super().__init__("Multicall not supported on this chain.")
| UnsupportedChainError |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 27902,
"end": 28673
} | class ____(DelegatingLexer):
"""
Subclass of the `CheetahLexer` that highlights unlexed data
with the `JavascriptLexer`.
"""
name = 'JavaScript+Cheetah'
aliases = ['js+cheetah', 'javascript+cheetah',
'js+spitfire', 'javascript+spitfire']
mimetypes = ['application/x-javascript... | CheetahJavascriptLexer |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/N802.py | {
"start": 515,
"end": 635
} | class ____(ast.NodeVisitor):
def visit_Constant(self, node):
pass
def bad_Name(self):
pass
| Visitor |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/natbot/crawler.py | {
"start": 429,
"end": 770
} | class ____(TypedDict):
"""A typed dictionary containing information about elements in the viewport."""
node_index: str
backend_node_id: int
node_name: str | None
node_value: str | None
node_meta: list[str]
is_clickable: bool
origin_x: int
origin_y: int
center_x: int
center_y... | ElementInViewPort |
python | jazzband__django-pipeline | tests/tests/test_compiler.py | {
"start": 868,
"end": 1274
} | class ____(SubProcessCompiler):
output_extension = "junk"
def match_file(self, path):
return path.endswith(".coffee")
def compile_file(self, infile, outfile, outdated=False, force=False):
command = (
("this-exists-nowhere-as-a-command-and-should-fail",),
infile,
... | InvalidCompiler |
python | pyodide__pyodide | src/py/_pyodide/_base.py | {
"start": 2603,
"end": 5485
} | class ____(Exception):
"""We will throw this to return a result from our code.
This allows us to distinguish between "code used top level await" and "code
returned a generator or coroutine".
"""
def __init__(self, v: Any) -> None:
super().__init__(v)
self.value = v
# We need Eval... | EvalCodeResultException |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 40981,
"end": 41790
} | class ____(nn.Module):
def __init__(self, config: Union[ClapAudioConfig, ClapTextConfig]):
super().__init__()
self.config = config
hidden_size = config.hidden_size
projection_dim = config.projection_dim
self.linear1 = nn.Linear(hidden_size, projection_dim)
self.activ... | ClapProjectionLayer |
python | GoogleCloudPlatform__python-docs-samples | compute/autoscaler/demo/frontend.py | {
"start": 3514,
"end": 3713
} | class ____(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
pass
if __name__ == "__main__":
httpd = DemoHttpServer(("", 80), DemoRequestHandler)
httpd.serve_forever()
| DemoHttpServer |
python | doocs__leetcode | solution/2300-2399/2331.Evaluate Boolean Binary Tree/Solution.py | {
"start": 192,
"end": 457
} | class ____:
def evaluateTree(self, root: Optional[TreeNode]) -> bool:
if root.left is None:
return bool(root.val)
op = or_ if root.val == 2 else and_
return op(self.evaluateTree(root.left), self.evaluateTree(root.right))
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/matrix_inverse_op_test.py | {
"start": 6295,
"end": 8247
} | class ____(test.Benchmark):
shapes = [
(4, 4),
(10, 10),
(16, 16),
(101, 101),
(256, 256),
(1000, 1000),
(1024, 1024),
(2048, 2048),
(513, 4, 4),
(513, 16, 16),
(513, 256, 256),
]
def _GenerateMatrix(self, shape):
batch_shape = shape[:-2]
... | MatrixInverseBenchmark |
python | pyca__cryptography | src/cryptography/x509/name.py | {
"start": 7104,
"end": 8935
} | class ____:
def __init__(self, attributes: Iterable[NameAttribute[str | bytes]]):
attributes = list(attributes)
if not attributes:
raise ValueError("a relative distinguished name cannot be empty")
if not all(isinstance(x, NameAttribute) for x in attributes):
raise Typ... | RelativeDistinguishedName |
python | pappasam__jedi-language-server | jedi_language_server/text_edit_utils.py | {
"start": 1251,
"end": 4336
} | class ____:
"""Convert jedi Refactoring objects into renaming machines."""
def __init__(self, workspace: Workspace, refactoring: Refactoring) -> None:
self.workspace = workspace
self.refactoring = refactoring
def lsp_renames(self) -> Iterator[RenameFile]:
"""Get all File rename ope... | RefactoringConverter |
python | coleifer__peewee | tests/expressions.py | {
"start": 440,
"end": 878
} | class ____(BaseNamesTest):
@skip_if(IS_SQLITE)
def test_regexp_iregexp(self):
people = [Person.create(name=name) for name in ('n1', 'n2', 'n3')]
self.assertNames(Person.name.regexp('n[1,3]'), ['n1', 'n3'])
self.assertNames(Person.name.regexp('N[1,3]'), [])
self.assertNames(Perso... | TestRegexp |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_invite_request_details.py | {
"start": 1802,
"end": 2944
} | class ____(InviteRequestBase):
def test_get_invalid(self) -> None:
self.login_as(user=self.user)
resp = self.get_response(self.org.slug, "123")
assert resp.status_code == 404
def test_me_not_supported(self) -> None:
self.login_as(user=self.user)
# the serializer allows t... | OrganizationInviteRequestGetTest |
python | django__django | django/forms/fields.py | {
"start": 24629,
"end": 26752
} | class ____(FileField):
default_validators = [validators.validate_image_file_extension]
default_error_messages = {
"invalid_image": _(
"Upload a valid image. The file you uploaded was either not an "
"image or a corrupted image."
),
}
def to_python(self, data):
... | ImageField |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 21098,
"end": 22814
} | class ____(
NamedTuple(
"_ExternalScheduleExecutionArgs",
[
("repository_origin", RemoteRepositoryOrigin),
("instance_ref", Optional[InstanceRef]),
("schedule_name", str),
("scheduled_execution_timestamp", Optional[float]),
("scheduled_exec... | ExternalScheduleExecutionArgs |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 6556,
"end": 7600
} | class ____(RequestHandler): pass
""", func, suffix='.py')
def test_logout_url(self) -> None:
def func(filename: str):
am = bsa.AuthModule(filename)
assert am.login_url == "/foo"
assert am.get_login_url is None
assert am.login_handler is None
... | LoginHandler |
python | sanic-org__sanic | sanic/touchup/schemes/base.py | {
"start": 158,
"end": 992
} | class ____(ABC):
ident: str
_registry: set[type] = set()
def __init__(self, app) -> None:
self.app = app
@abstractmethod
def visitors(self) -> list[NodeTransformer]: ...
def __init_subclass__(cls):
BaseScheme._registry.add(cls)
def __call__(self):
return self.visi... | BaseScheme |
python | wandb__wandb | wandb/vendor/pygments/lexers/markup.py | {
"start": 10588,
"end": 12277
} | class ____(RegexLexer):
"""
Lexer for the TeX and LaTeX typesetting languages.
"""
name = 'TeX'
aliases = ['tex', 'latex']
filenames = ['*.tex', '*.aux', '*.toc']
mimetypes = ['text/x-tex', 'text/x-latex']
tokens = {
'general': [
(r'%.*?\n', Comment),
(r... | TexLexer |
python | astropy__astropy | astropy/extern/ply/yacc.py | {
"start": 79245,
"end": 82667
} | class ____(object):
def __init__(self):
self.lr_action = None
self.lr_goto = None
self.lr_productions = None
self.lr_method = None
def read_table(self, module):
if isinstance(module, types.ModuleType):
parsetab = module
else:
exec('import ... | LRTable |
python | sympy__sympy | sympy/assumptions/relation/equality.py | {
"start": 2928,
"end": 3988
} | class ____(BinaryRelation):
"""
Binary predicate for $>$.
The purpose of this class is to provide the instance which represent
the ">" predicate in order to allow the logical inference.
This class must remain internal to assumptions module and user must
use :obj:`~.Gt()` instead to construct th... | StrictGreaterThanPredicate |
python | realpython__materials | duck-typing-python/vehicles_duck.py | {
"start": 0,
"end": 311
} | class ____:
def __init__(self, make, model, color):
self.make = make
self.model = model
self.color = color
def start(self):
print("The car is starting")
def stop(self):
print("The car is stopping")
def drive(self):
print("The car is driving")
| Car |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 35636,
"end": 35836
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DEVELOPMENT", "RUNTIME")
| RepositoryVulnerabilityAlertDependencyScope |
python | getsentry__sentry | src/sentry/taskworker/silolimiter.py | {
"start": 174,
"end": 1797
} | class ____(SiloLimit):
"""
Silo limiter for tasks
We don't want tasks to be spawned in the incorrect silo.
We can't reliably cause tasks to fail as not all tasks use
the ORM (which also has silo bound safety).
"""
def handle_when_unavailable(
self,
original_method: Callable... | TaskSiloLimit |
python | google__pytype | pytype/abstract/_function_base.py | {
"start": 5971,
"end": 10140
} | class ____(Function):
"""An abstract value representing a native function.
Attributes:
name: Function name. Might just be something like "<lambda>".
func: An object with a __call__ method.
ctx: context.Context instance.
"""
def __init__(self, name: str, func: Callable, ctx: "context.Context") -> N... | NativeFunction |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 29371,
"end": 33143
} | class ____(AggregateFnV2[List[Any], List[Any]]):
"""Defines Quantile aggregation.
Example:
.. testcode::
import ray
from ray.data.aggregate import Quantile
ds = ray.data.range(100)
# Schema: {'id': int64}
ds = ds.add_column("group_key", lam... | Quantile |
python | django__django | tests/model_fields/test_jsonfield.py | {
"start": 2281,
"end": 4547
} | class ____(SimpleTestCase):
def test_deconstruct(self):
field = models.JSONField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.JSONField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {})
def test_deconstruct_custom_enco... | TestMethods |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/memcache/guestbook/main.py | {
"start": 932,
"end": 1354
} | class ____(ndb.Model):
"""Models an individual Guestbook entry with author, content, and date."""
author = ndb.StringProperty()
content = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entit... | Greeting |
python | Textualize__textual | docs/examples/how-to/containers08.py | {
"start": 275,
"end": 732
} | class ____(App):
"""Simple app to play with containers."""
CSS = """
.with-border {
border: heavy green;
}
"""
def compose(self) -> ComposeResult:
yield Box("Box 1") # (1)!
with Center(classes="with-border"): # (2)!
yield Box("Box 2")
with Right(cl... | ContainerApp |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 137258,
"end": 138405
} | class ____(Response):
"""
Response of projects.make_private endpoint.
:param updated: Number of projects updated
:type updated: int
"""
_service = "projects"
_action = "make_private"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"updat... | MakePrivateResponse |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 27331,
"end": 28743
} | class ____(unittest.TestCase):
def _makeConfig(self):
from pyramid.config import Configurator
config = Configurator()
return config
def _makeTestApp(self, config):
app = config.make_wsgi_app()
return TestApp(app)
def test_unicode_in_url_404(self):
request_p... | UnicodeInURLTest |
python | openai__openai-python | src/openai/types/evals/run_cancel_response.py | {
"start": 11886,
"end": 12365
} | class ____(BaseModel):
cached_tokens: int
"""The number of tokens retrieved from cache."""
completion_tokens: int
"""The number of completion tokens generated."""
invocation_count: int
"""The number of invocations."""
run_model_name: str = FieldInfo(alias="model_name")
"""The name of ... | PerModelUsage |
python | numba__numba | numba/cuda/stubs.py | {
"start": 1003,
"end": 1217
} | class ____(Stub):
'''A triple, (x, y, z)'''
_description_ = '<Dim3>'
@property
def x(self):
pass
@property
def y(self):
pass
@property
def z(self):
pass
| Dim3 |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 1650,
"end": 1934
} | class ____:
def setup(self):
self.df = DataFrame(np.random.randn(10000, 25))
self.df["foo"] = "bar"
self.df["bar"] = "baz"
self.df = self.df._consolidate()
def time_frame_get_numeric_data(self):
self.df._get_numeric_data()
| GetNumericData |
python | getsentry__sentry | tests/sentry/integrations/jira/test_sentry_installation.py | {
"start": 931,
"end": 1876
} | class ____(JiraSentryInstallationViewTestCase):
@patch(
"sentry.integrations.jira.views.sentry_installation.get_integration_from_request",
side_effect=ExpiredSignatureError(),
)
def test_expired_signature_error(self, mock_get_integration_from_request: MagicMock) -> None:
response = s... | JiraSentryInstallationViewErrorsTest |
python | PyCQA__pylint | tests/functional/c/crash_missing_module_type.py | {
"start": 267,
"end": 434
} | class ____:
""" Class """
@decor
def prop(self):
""" method """
return self
if __name__ == '__main__':
trop = Foo()
trop.prop = 42
| Foo |
python | celery__celery | celery/bootsteps.py | {
"start": 8727,
"end": 10552
} | class ____(metaclass=StepType):
"""A Bootstep.
The :meth:`__init__` method is called when the step
is bound to a parent object, and can as such be used
to initialize attributes in the parent object at
parent instantiation-time.
"""
#: Optional step name, will use ``qualname`` if not specif... | Step |
python | django-extensions__django-extensions | django_extensions/admin/__init__.py | {
"start": 7179,
"end": 7292
} | class ____(
ForeignKeyAutocompleteAdminMixin, admin.StackedInline
):
pass
| ForeignKeyAutocompleteStackedInline |
python | eth-brownie__brownie | brownie/network/gas/strategies.py | {
"start": 3719,
"end": 4647
} | class ____(SimpleGasStrategy):
"""
Gas strategy for determining a price using the GasNow API.
GasNow returns 4 possible prices:
rapid: the median gas prices for all transactions currently included
in the mining block
fast: the gas price transaction "N", the minimum priced tx currently
... | GasNowStrategy |
python | ApeWorX__ape | tests/functional/utils/test_github.py | {
"start": 846,
"end": 6109
} | class ____:
def test_get_repo_unknown_repo(self, mocker, mock_session):
client = _GithubClient(session=mock_session)
# Make it raise 404.
response = mocker.MagicMock()
response.status_code = 404
error = HTTPError(response=response)
mock_session.request.side_effect = ... | TestGithubClient |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/tests/test_00_console_widget.py | {
"start": 8936,
"end": 27612
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
""" Create the application for the test case.
"""
cls._app = QtWidgets.QApplication.instance()
if cls._app is None:
cls._app = QtWidgets.QApplication([])
cls._app.setQuitOnLastWindowClosed(False... | TestConsoleWidget |
python | langchain-ai__langchain | libs/partners/deepseek/tests/unit_tests/test_chat_models.py | {
"start": 2432,
"end": 3527
} | class ____(ChatModelUnitTests):
"""Standard unit tests for `ChatDeepSeek` chat model."""
@property
def chat_model_class(self) -> type[ChatDeepSeek]:
"""Chat model class being tested."""
return ChatDeepSeek
@property
def init_from_env_params(self) -> tuple[dict, dict, dict]:
... | TestChatDeepSeekUnit |
python | python__mypy | mypy/error_formatter.py | {
"start": 427,
"end": 1115
} | class ____(ErrorFormatter):
"""Formatter for basic JSON output format."""
def report_error(self, error: "MypyError") -> str:
"""Prints out the errors as simple, static JSON lines."""
return json.dumps(
{
"file": error.file_path,
"line": error.line,
... | JSONFormatter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/annotations4.py | {
"start": 522,
"end": 1099
} | class ____:
# This should generate an error because aa is redeclared.
aa: int
def aa(self):
return 3
# This should generate two errors, one for each param.
def my_func(param1: int, param2):
param1: int = 3
param2: int = 4
# This should be fine because both declarations of 'e'
# use the ... | Foo |
python | tensorflow__tensorflow | tensorflow/python/ops/data_flow_ops.py | {
"start": 35045,
"end": 38378
} | class ____(QueueBase):
"""A FIFOQueue that supports batching variable-sized tensors by padding.
A `PaddingFIFOQueue` may contain components with dynamic shape, while also
supporting `dequeue_many`. See the constructor for more details.
See `tf.queue.QueueBase` for a description of the methods on
this class... | PaddingFIFOQueue |
python | kamyu104__LeetCode-Solutions | Python/maximum-good-subarray-sum.py | {
"start": 63,
"end": 551
} | class ____(object):
def maximumSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
prefix = collections.defaultdict(lambda: float("inf"))
curr = 0
result = float("-inf")
for x in nums:
prefix[x] = min(... | Solution |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/framesbrowser.py | {
"start": 12418,
"end": 13061
} | class ____(QTreeWidgetItem):
def __init__(self, parent, name):
self.name = str(name)
text_color = SpyderPalette.COLOR_TEXT_1
title_format = str(
'<!-- ThreadItem -->'
'<b style="color:{1}">{0}</b>'
)
title = (title_format.format(name, text_color))
... | ThreadItem |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_connection.py | {
"start": 5911,
"end": 8196
} | class ____(ConnectionPool):
"""Connection pool for Azure Database for PostgreSQL connections."""
def __init__(
self,
conninfo: str = "",
*,
azure_conn_info: ConnectionInfo = ConnectionInfo(),
**kwargs,
):
if isinstance(azure_conn_info.credentials, TokenCreden... | AzurePGConnectionPool |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 627,
"end": 757
} | class ____(NewAaaa):
"""new style"""
def __init__(self):
super().__init__() # <3.0:[missing-super-argument]
| Py3kAaaa |
python | mlflow__mlflow | examples/spark_udf/structs_and_arrays.py | {
"start": 89,
"end": 2122
} | class ____(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input):
return [str(" | ".join(map(str, row))) for _, row in model_input.iterrows()]
def main():
with SparkSession.builder.getOrCreate() as spark:
df = spark.createDataFrame(
[
(
... | MyModel |
python | pytorch__pytorch | torch/distributed/tensor/examples/convnext_example.py | {
"start": 1297,
"end": 2515
} | class ____(nn.Module):
def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-6):
super().__init__()
self.dwconv = nn.Conv2d(
dim, dim, kernel_size=7, padding=3, groups=dim
) # depthwise conv
self.norm = LayerNorm(dim, eps=1e-6, data_format=torch.contiguous_for... | Block |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 484555,
"end": 485250
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CancelEnterpriseAdminInvitation"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "invitation", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for th... | CancelEnterpriseAdminInvitationPayload |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-monday/unit_tests/integrations/monday_responses/records/record_builder.py | {
"start": 151,
"end": 394
} | class ____(RecordBuilder):
@staticmethod
def extract_record(resource: str, execution_folder: str, data_field: Path):
return data_field.extract(find_template(resource=resource, execution_folder=execution_folder))
| MondayRecordBuilder |
python | html5lib__html5lib-python | html5lib/_inputstream.py | {
"start": 5687,
"end": 13658
} | class ____(object):
"""Provides a unicode stream of characters to the HTMLTokenizer.
This class takes care of character encoding and removing or replacing
incorrect byte-sequences and also provides column and line tracking.
"""
_defaultChunkSize = 10240
def __init__(self, source):
""... | HTMLUnicodeInputStream |
python | openai__openai-python | src/openai/types/chat/chat_completion_message.py | {
"start": 774,
"end": 991
} | class ____(BaseModel):
type: Literal["url_citation"]
"""The type of the URL citation. Always `url_citation`."""
url_citation: AnnotationURLCitation
"""A URL citation when using web search."""
| Annotation |
python | uqfoundation__dill | dill/tests/test_recursive.py | {
"start": 2177,
"end": 2469
} | class ____(Machine2):
def __init__(self):
super(SubMachine, self).__init__()
def test_partials():
assert copy(SubMachine(), byref=True)
assert copy(SubMachine(), byref=True, recurse=True)
assert copy(SubMachine(), recurse=True)
assert copy(SubMachine())
| SubMachine |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 30079,
"end": 31019
} | class ____(CharField):
"""Support both IPAddressField and GenericIPAddressField"""
default_error_messages = {
'invalid': _('Enter a valid IPv4 or IPv6 address.'),
}
def __init__(self, protocol='both', **kwargs):
self.protocol = protocol.lower()
self.unpack_ipv4 = (self.protocol... | IPAddressField |
python | sqlalchemy__sqlalchemy | test/orm/test_of_type.py | {
"start": 14435,
"end": 17456
} | class ____(
_PolymorphicTestBase, _PolymorphicAliasedJoins
):
def _polymorphic_join_target(self, cls):
return (
"(SELECT people.person_id AS people_person_id, "
"people.company_id AS people_company_id, "
"people.name AS people_name, people.type AS people_type, "
... | PolymorphicAliasedJoinsTest |
python | openai__openai-python | src/openai/types/container_list_params.py | {
"start": 209,
"end": 893
} | class ____(TypedDict, total=False):
after: str
"""A cursor for use in pagination.
`after` is an object ID that defines your place in the list. For instance, if
you make a list request and receive 100 objects, ending with obj_foo, your
subsequent call can include after=obj_foo in order to fetch the ... | ContainerListParams |
python | walkccc__LeetCode | solutions/624. Maximum Distance in Arrays/624.py | {
"start": 0,
"end": 249
} | class ____:
def maxDistance(self, arrays: list[list[int]]) -> int:
ans = 0
mn = 10000
mx = -10000
for A in arrays:
ans = max(ans, A[-1] - mn, mx - A[0])
mn = min(mn, A[0])
mx = max(mx, A[-1])
return ans
| Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/oracle_to_gcs.py | {
"start": 1257,
"end": 5869
} | class ____(BaseSQLToGCSOperator):
"""
Copy data from Oracle to Google Cloud Storage in JSON, CSV or Parquet format.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:OracleToGCSOperator`
:param oracle_conn_id: Reference to a s... | OracleToGCSOperator |
python | kamyu104__LeetCode-Solutions | Python/maximum-product-of-three-elements-after-one-replacement.py | {
"start": 38,
"end": 388
} | class ____(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = 2
top = [0]*L
for x in nums:
x = abs(x)
for i in xrange(L):
if x > top[i]:
x, top[i] = top[i], x
r... | Solution |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 11811,
"end": 12168
} | class ____(GroupType):
type_id = 1006
slug = "performance_n_plus_one_db_queries"
description = "N+1 Query"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.DB_QUERY.value
noise_config = NoiseConfig()
default_priority = PriorityLevel.LOW
released = True
@dataclass(... | PerformanceNPlusOneGroupType |
python | django__django | tests/admin_views/admin.py | {
"start": 27778,
"end": 27916
} | class ____(admin.ModelAdmin):
form = FormWithVisibleAndHiddenField
fieldsets = EmptyModelVisibleAdmin.fieldsets
| EmptyModelMixinAdmin |
python | scrapy__scrapy | scrapy/settings/__init__.py | {
"start": 2446,
"end": 23760
} | class ____(MutableMapping[_SettingsKey, Any]):
"""
Instances of this class behave like dictionaries, but store priorities
along with their ``(key, value)`` pairs, and can be frozen (i.e. marked
immutable).
Key-value entries can be passed on initialization with the ``values``
argument, and they ... | BaseSettings |
python | chroma-core__chroma | sample_apps/generative_benchmarking/functions/types.py | {
"start": 325,
"end": 400
} | class ____:
doc_scores: Dict[str, QueryResultItem]
@dataclass
| QueryResults |
python | crytic__slither | slither/tools/properties/__main__.py | {
"start": 1513,
"end": 4343
} | class ____(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
logger.info(_all_properties())
parser.exit()
def parse_args() -> argparse.Namespace:
"""
Parse the u... | ListProperties |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 6448,
"end": 6741
} | class ____(Exception):
"With multi=True code must return a Python dictionary"
def __init__(self, values):
self.values = values
_COUNTS_TABLE_CREATE_SQL = """
CREATE TABLE IF NOT EXISTS "{}"(
"table" TEXT PRIMARY KEY,
count INTEGER DEFAULT 0
);
""".strip()
| BadMultiValues |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 72321,
"end": 73620
} | class ____(Response):
"""
Response of queues.move_task_backward endpoint.
:param position: The new position of the task entry in the queue (index, -1 represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_backward"
_version = "2.20"
_schema = {... | MoveTaskBackwardResponse |
python | networkx__networkx | networkx/algorithms/approximation/tests/test_treewidth.py | {
"start": 5447,
"end": 8868
} | class ____:
"""Unit tests for the treewidth_min_fill_in function."""
@classmethod
def setup_class(cls):
"""Setup for different kinds of trees"""
cls.complete = nx.Graph()
cls.complete.add_edge(1, 2)
cls.complete.add_edge(2, 3)
cls.complete.add_edge(1, 3)
cls... | TestTreewidthMinFillIn |
python | walkccc__LeetCode | solutions/3507. Minimum Pair Removal to Sort Array I/3507.py | {
"start": 0,
"end": 389
} | class ____:
def minimumPairRemoval(self, nums: list[int]) -> int:
ans = 0
while any(x > y for x, y in itertools.pairwise(nums)):
pairSums = [x + y for x, y in itertools.pairwise(nums)]
minPairSum = min(pairSums)
minPairIndex = pairSums.index(minPairSum)
nums[minPairIndex] = minPairSum... | Solution |
python | django__django | tests/model_forms/tests.py | {
"start": 132891,
"end": 132973
} | class ____(forms.ModelForm, metaclass=CustomMetaclass):
pass
| CustomMetaclassForm |
python | urllib3__urllib3 | src/urllib3/response.py | {
"start": 15703,
"end": 44048
} | class ____(BaseHTTPResponse):
"""
HTTP Response container.
Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is
loaded and decoded on-demand when the ``data`` property is accessed. This
class is also compatible with the Python standard library's :mod:`io`
mo... | HTTPResponse |
python | PyCQA__flake8 | tests/integration/subdir/aplugin.py | {
"start": 115,
"end": 326
} | class ____:
"""Extension test plugin in its own directory."""
def __init__(self, tree):
"""Construct an instance of test plugin."""
def run(self):
"""Do nothing."""
| ExtensionTestPlugin2 |
python | huggingface__transformers | examples/modular-transformers/modeling_test_detr.py | {
"start": 10384,
"end": 13590
} | class ____(nn.Module):
"""
Convolutional backbone, using either the AutoBackbone API or one from the timm library.
nn.BatchNorm2d layers are replaced by TestDetrFrozenBatchNorm2d as defined above.
"""
def __init__(self, config):
super().__init__()
self.config = config
# ... | TestDetrConvEncoder |
python | ray-project__ray | python/ray/dashboard/memory_utils.py | {
"start": 7235,
"end": 18614
} | class ____:
def __init__(
self,
entries: List[MemoryTableEntry],
group_by_type: GroupByType = GroupByType.NODE_ADDRESS,
sort_by_type: SortingType = SortingType.PID,
):
self.table = entries
# Group is a list of memory tables grouped by a group key.
self.gro... | MemoryTable |
python | zarr-developers__zarr-python | tests/conftest.py | {
"start": 4705,
"end": 15035
} | class ____:
shape: tuple[int, ...]
dtype: str
order: MemoryOrder
@pytest.fixture
def array_fixture(request: pytest.FixtureRequest) -> npt.NDArray[Any]:
array_request: ArrayRequest = request.param
return (
np.arange(np.prod(array_request.shape))
.reshape(array_request.shape, order=a... | ArrayRequest |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 59070,
"end": 59781
} | class ____(_LoopTypesTester):
_ufuncs = [np.power] # issue #757
_required_types = 'bBhHiIlLqQfdFD'
_skip_types = 'mMO' + _LoopTypesTester._skip_types
def _arg_for_type(self, a_letter_type, index=0):
res = super(self.__class__, self)._arg_for_type(a_letter_type,
... | TestLoopTypesPower |
python | doocs__leetcode | solution/2300-2399/2360.Longest Cycle in a Graph/Solution.py | {
"start": 0,
"end": 579
} | class ____:
def longestCycle(self, edges: List[int]) -> int:
n = len(edges)
vis = [False] * n
ans = -1
for i in range(n):
if vis[i]:
continue
j = i
cycle = []
while j != -1 and not vis[j]:
vis[j] = True
... | Solution |
python | huggingface__transformers | tests/models/chameleon/test_modeling_chameleon.py | {
"start": 1452,
"end": 7358
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=35,
is_training=False,
use_input_mask=True,
use_labels=True,
vocab_size=99,
image_token_id=4,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=2,
... | ChameleonModelTester |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB156.py | {
"start": 843,
"end": 931
} | class ____:
def method(self):
"01234567"
def function():
"""01234567"""
| C |
python | pandas-dev__pandas | pandas/io/formats/format.py | {
"start": 55458,
"end": 55905
} | class ____(_Datetime64Formatter):
values: DatetimeArray
def _format_strings(self) -> list[str]:
"""we by definition have a TZ"""
ido = self.values._is_dates_only
values = self.values.astype(object)
formatter = self.formatter or get_format_datetime64(
ido, date_format... | _Datetime64TZFormatter |
python | django__django | tests/get_or_create/models.py | {
"start": 629,
"end": 713
} | class ____(models.Model):
text = models.CharField(max_length=255, unique=True)
| Tag |
python | pandas-dev__pandas | pandas/tests/io/test_parquet.py | {
"start": 10934,
"end": 11473
} | class ____:
def check_error_on_write(self, df, engine, exc, err_msg, temp_file_path):
# check that we are raising the exception on writing
with pytest.raises(exc, match=err_msg):
to_parquet(df, temp_file_path, engine, compression=None)
def check_external_error_on_write(self, df, eng... | Base |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 5757,
"end": 5878
} | class ____(WeaviateBaseError):
"""Is raised if weaviate is not available on the given url+port."""
| WeaviateStartUpError |
python | huggingface__transformers | src/transformers/models/superglue/modeling_superglue.py | {
"start": 6370,
"end": 8072
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
Loss computed during training.
matches (`torch.FloatTensor` of shape `(batch_size, 2, num_matches)`):
Index of keypoint matched in the other image.
matching_scores (`torch.FloatTensor` of shape `(batch_... | SuperGlueKeypointMatchingOutput |
python | huggingface__transformers | src/transformers/models/biogpt/modeling_biogpt.py | {
"start": 14195,
"end": 14484
} | class ____(PreTrainedModel):
config: BioGptConfig
base_model_prefix = "biogpt"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = True
@auto_docstring
| BioGptPreTrainedModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.