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 | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/model_service.py | {
"start": 11957,
"end": 16346
} | class ____(GoogleCloudBaseOperator):
r"""
Lists Models in a Location.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param retry: Designation of what errors, if any... | ListModelsOperator |
python | django__django | tests/logging_tests/tests.py | {
"start": 4353,
"end": 7738
} | class ____(
SetupDefaultLoggingMixin, LoggingAssertionMixin, LoggingCaptureMixin, SimpleTestCase
):
def test_page_found_no_warning(self):
self.client.get("/innocent/")
self.assertEqual(self.logger_output.getvalue(), "")
def test_redirect_no_warning(self):
self.client.get("/redirect/... | HandlerLoggingTests |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_weight_averaging.py | {
"start": 1816,
"end": 2178
} | class ____(BoringModel):
def __init__(self):
super().__init__()
self.layer = None
def configure_model(self):
print("XXX configure_model")
self.layer = nn.Sequential(nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 2))
def configure_optimizers(self):
return torch.optim.SG... | LargeTestModel |
python | spack__spack | lib/spack/spack/spec_parser.py | {
"start": 19008,
"end": 24424
} | class ____:
"""Parse a single spec node from a stream of tokens"""
__slots__ = "ctx", "has_version", "literal_str"
def __init__(self, ctx, literal_str):
self.ctx = ctx
self.literal_str = literal_str
self.has_version = False
def parse(
self, initial_spec: Optional["spac... | SpecNodeParser |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/connections.py | {
"start": 1151,
"end": 2222
} | class ____(BaseModel):
"""Connection serializer for responses."""
connection_id: str = Field(serialization_alias="connection_id", validation_alias="conn_id")
conn_type: str
description: str | None
host: str | None
login: str | None
schema_: str | None = Field(alias="schema")
port: int |... | ConnectionResponse |
python | bokeh__bokeh | tests/unit/bokeh/server/test_server__server.py | {
"start": 2064,
"end": 2118
} | class ____(Model):
hooks = List(String)
| HookListModel |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_stellar_address.py | {
"start": 1907,
"end": 4747
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid Stellar addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
... | ExpectColumnValuesToBeValidStellarAddress |
python | walkccc__LeetCode | solutions/3443. Maximum Manhattan Distance After K Changes/3443.py | {
"start": 0,
"end": 465
} | class ____:
def maxDistance(self, s: str, k: int) -> int:
return max(self._flip(s, k, 'NE'), self._flip(s, k, 'NW'),
self._flip(s, k, 'SE'), self._flip(s, k, 'SW'))
def _flip(self, s: str, k: int, direction: str) -> int:
res = 0
pos = 0
opposite = 0
for c in s:
if c in dir... | Solution |
python | sympy__sympy | sympy/printing/str.py | {
"start": 569,
"end": 32591
} | class ____(Printer):
printmethod = "_sympystr"
_default_settings: dict[str, Any] = {
"order": None,
"full_prec": "auto",
"sympy_integers": False,
"abbrev": False,
"perm_cyclic": True,
"min": None,
"max": None,
"dps" : None
}
_relationals: ... | StrPrinter |
python | kamyu104__LeetCode-Solutions | Python/find-the-power-of-k-size-subarrays-i.py | {
"start": 60,
"end": 570
} | class ____(object):
def resultsArray(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
result = [-1]*(len(nums)-k+1)
left = 0
for right in xrange(len(nums)):
if nums[right]-nums[left] != right-left:
... | Solution |
python | conda__conda | conda/exceptions.py | {
"start": 34409,
"end": 35582
} | class ____(CondaError, OSError):
def __init__(self, path: PathType, errno: int, **kwargs):
kwargs.update(
{
"path": path,
"errno": errno,
}
)
if on_win:
message = dals(
"""
The current user does n... | NotWritableError |
python | sympy__sympy | sympy/physics/mechanics/joint.py | {
"start": 41230,
"end": 53058
} | class ____(Joint):
"""Cylindrical Joint.
.. image:: CylindricalJoint.svg
:align: center
:width: 600
Explanation
===========
A cylindrical joint is defined such that the child body both rotates about
and translates along the body-fixed joint axis with respect to the parent
... | CylindricalJoint |
python | astropy__astropy | astropy/cosmology/_src/traits/darkenergy.py | {
"start": 300,
"end": 5238
} | class ____:
# Subclasses should use `Parameter` to make this a parameter of the cosmology.
Ode0: float | np.floating
"""Omega dark energy; dark energy density/critical density at z=0."""
@abstractmethod
def w(self, z: Quantity | ArrayLike, /) -> FArray:
r"""The dark energy equation of state... | DarkEnergyComponent |
python | numpy__numpy | numpy/_core/tests/test_umath_accuracy.py | {
"start": 1905,
"end": 5821
} | class ____:
@platform_skip
def test_validate_transcendentals(self):
with np.errstate(all='ignore'):
data_dir = path.join(path.dirname(__file__), 'data')
files = os.listdir(data_dir)
files = list(filter(lambda f: f.endswith('.csv'), files))
for filename in ... | TestAccuracy |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 117052,
"end": 120080
} | class ____(Request):
"""
Publish models
:param ids: IDs of the models to publish
:type ids: Sequence[str]
:param force_publish_task: Publish the associated tasks (if exist) even if they
are not in the 'stopped' state. Optional, the default value is False.
:type force_publish_task: bool
... | PublishManyRequest |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/views/user.py | {
"start": 4869,
"end": 6031
} | class ____(MultiResourceUserMixin, UserDBModelView):
"""Customize permission names for FAB's builtin UserDBModelView."""
_class_permission_name = permissions.RESOURCE_USER
class_permission_name_mapping = {
"resetmypassword": permissions.RESOURCE_MY_PASSWORD,
"resetpasswords": permissions.R... | CustomUserDBModelView |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/operators/teradata_compute_cluster.py | {
"start": 2319,
"end": 8021
} | class ____(BaseOperator):
"""
Teradata Compute Cluster Base Operator to set up and status operations of compute cluster.
:param compute_profile_name: Name of the Compute Profile to manage.
:param compute_group_name: Name of compute group to which compute profile belongs.
:param teradata_conn_id: Th... | _TeradataComputeClusterOperator |
python | ray-project__ray | python/ray/util/client/server/server_stubs.py | {
"start": 1007,
"end": 1346
} | class ____(ClientReferenceSentinel):
def get_remote_obj(self):
global _current_server
real_ref_id = self.get_real_ref_from_server()
if real_ref_id is None:
return None
return _current_server.lookup_or_register_actor(
real_ref_id, self.client_id, None
)... | ClientReferenceActor |
python | protocolbuffers__protobuf | python/google/protobuf/internal/well_known_types_test.py | {
"start": 26342,
"end": 37362
} | class ____(unittest.TestCase):
def testEmptyDict(self):
# in operator for empty initialized struct
msg = well_known_types_test_pb2.WKTMessage(optional_struct={})
self.assertNotIn('key', msg.optional_struct)
def testStruct(self):
struct = struct_pb2.Struct()
self.assertIsInstance(struct, collec... | StructTest |
python | python-pillow__Pillow | src/PIL/TgaImagePlugin.py | {
"start": 986,
"end": 6980
} | class ____(ImageFile.ImageFile):
format = "TGA"
format_description = "Targa"
def _open(self) -> None:
# process header
assert self.fp is not None
s = self.fp.read(18)
id_len = s[0]
colormaptype = s[1]
imagetype = s[2]
depth = s[16]
flags ... | TgaImageFile |
python | pytorch__pytorch | test/fx/test_common_passes.py | {
"start": 1576,
"end": 2801
} | class ____(TestCase):
@parametrize(
"common_pass,f,device", itertools.product(Passes, Test_Cases, Devices), name_fn
)
def test_correctness(self, common_pass, f, device):
inp = torch.randn(10, device=device)
traced_m = make_fx(f)(inp)
P = common_pass()
res = P(traced... | TestCommonPass |
python | ageron__handson-ml | future_encoders.py | {
"start": 4709,
"end": 8047
} | class ____(BaseEstimator, TransformerMixin):
"""
Base class for encoders that includes the code to categorize and
transform the input features.
"""
def _fit(self, X, handle_unknown='error'):
X_temp = check_array(X, dtype=None)
if not hasattr(X, 'dtype') and np.issubdtype(X_temp.dt... | _BaseEncoder |
python | imageio__imageio | imageio/plugins/freeimagemulti.py | {
"start": 360,
"end": 2873
} | class ____(FreeimageFormat):
"""Base class for freeimage formats that support multiple images."""
_modes = "iI"
_fif = -1
class Reader(Format.Reader):
def _open(self, flags=0):
flags = int(flags)
# Create bitmap
self._bm = fi.create_multipage_bitmap(
... | FreeimageMulti |
python | coleifer__peewee | playhouse/flask_utils.py | {
"start": 3069,
"end": 8197
} | class ____(object):
"""
Convenience wrapper for configuring a Peewee database for use with a Flask
application. Provides a base `Model` class and registers handlers to manage
the database connection during the request/response cycle.
Usage::
from flask import Flask
from peewee impo... | FlaskDB |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_page_breaks03.py | {
"start": 315,
"end": 1201
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("page_breaks03.xlsx")
self.ignore_files = [
"xl/printerSettings/printerSettings1.bin",
"xl/worksheets/_rels/sheet1.xml.r... | TestCompareXLSXFiles |
python | great-expectations__great_expectations | great_expectations/core/util.py | {
"start": 10677,
"end": 14619
} | class ____:
"""
Methods for converting Databricks Filesystem (DBFS) paths
"""
@staticmethod
def convert_to_file_semantics_version(path: str) -> str:
if re.search(r"^dbfs:", path):
return path.replace("dbfs:", "/dbfs", 1)
if re.search("^/dbfs", path):
return ... | DBFSPath |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_tasks.py | {
"start": 2125,
"end": 2303
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Task Link."""
name = "Cloud Tasks"
key = "cloud_task"
format_str = CLOUD_TASKS_LINK
| CloudTasksLink |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_asb.py | {
"start": 20614,
"end": 24348
} | class ____:
def test_init(self):
"""
Test init by creating ASBReceiveSubscriptionMessageOperator with task id, topic_name,
subscription_name, batch and asserting with values
"""
asb_subscription_receive_message = ASBReceiveSubscriptionMessageOperator(
task_id="as... | TestASBSubscriptionReceiveMessageOperator |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/unsupervised_learning/apriori.py | {
"start": 313,
"end": 7906
} | class ____():
"""A method for determining frequent itemsets in a transactional database and
also for generating rules for those itemsets.
Parameters:
-----------
min_sup: float
The minimum fraction of transactions an itemets needs to
occur in to be deemed frequent
min_conf: flo... | Apriori |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 7018,
"end": 8434
} | class ____:
def test_flow_decorator_initializes(self):
# TODO: We should cover initialization with a task runner once introduced
@flow(name="foo", version="B", flow_run_name="hi")
def my_flow():
return "bar"
assert isinstance(my_flow, Flow)
assert my_flow.name ==... | TestDecorator |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 35148,
"end": 35800
} | class ____(CythonCommand):
"""
Go up a Cython, Python or relevant C frame.
"""
name = 'cy up'
_command = 'up'
@libpython.dont_suppress_errors
def invoke(self, *args):
try:
gdb.execute(self._command, to_string=True)
while not self.is_relevant_function(gdb.sele... | CyUp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_bundle_selections.py | {
"start": 512,
"end": 1844
} | class ____(StreamTestCase):
_STREAM_NAME = "bundle_selections"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_stre... | TestFullRefresh |
python | sanic-org__sanic | sanic/server/websockets/frame.py | {
"start": 356,
"end": 11484
} | class ____:
"""
Assemble a message from frames.
Code borrowed from aaugustin/websockets project:
https://github.com/aaugustin/websockets/blob/6eb98dd8fa5b2c896b9f6be7e8d117708da82a39/src/websockets/sync/messages.py
"""
__slots__ = (
"protocol",
"read_mutex",
"write_mutex... | WebsocketFrameAssembler |
python | django__django | django/core/checks/messages.py | {
"start": 70,
"end": 1654
} | class ____:
def __init__(self, level, msg, hint=None, obj=None, id=None):
if not isinstance(level, int):
raise TypeError("The first argument should be level.")
self.level = level
self.msg = msg
self.hint = hint
self.obj = obj
self.id = id
def __eq__(s... | CheckMessage |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 16597,
"end": 17027
} | class ____(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `HtmlLexer`.
.. versionadded:: 0.6
"""
name = 'HTML+Myghty'
aliases = ['html+myghty']
mimetypes = ['text/html+myghty']
def __init__(self, **options):
super(MyghtyHtmlLexer,... | MyghtyHtmlLexer |
python | readthedocs__readthedocs.org | readthedocs/api/v2/permissions.py | {
"start": 1676,
"end": 2597
} | class ____(BaseHasAPIKey):
"""
Custom permission to inject the build API key into the request.
We completely override the ``has_permission`` method
to avoid having to parse and validate the key again on each view.
The key is injected in the ``request.build_api_key`` attribute
only if it's valid... | HasBuildAPIKey |
python | gevent__gevent | src/gevent/tests/test__local.py | {
"start": 10727,
"end": 11306
} | class ____(greentest.TestCase):
__timeout__ = None
@greentest.ignores_leakcheck
def test_provides(self):
# https://github.com/gevent/gevent/issues/1122
# pylint:disable=inherit-non-class
class IFoo(interface.Interface):
pass
@interface.implementer(IFoo)
... | TestLocalInterface |
python | keras-team__keras | keras/src/backend/torch/optimizers/torch_adagrad.py | {
"start": 147,
"end": 1041
} | class ____(
torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adagrad
):
def _parallel_update_step(
self,
grads,
variables,
learning_rate,
):
keras_variables = variables
variables = [v.value for v in variables]
dtype = variables[0].dtype
... | Adagrad |
python | aio-libs__aiohttp | aiohttp/client_middleware_digest_auth.py | {
"start": 734,
"end": 4775
} | class ____(TypedDict, total=False):
realm: str
nonce: str
qop: str
algorithm: str
opaque: str
domain: str
stale: str
DigestFunctions: dict[str, Callable[[bytes], "hashlib._Hash"]] = {
"MD5": hashlib.md5,
"MD5-SESS": hashlib.md5,
"SHA": hashlib.sha1,
"SHA-SESS": hashlib.sha1... | DigestAuthChallenge |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/models/secrets.py | {
"start": 4507,
"end": 5133
} | class ____:
name: str
secret_store: SecretStore
file_name: str | None = None
def __post_init__(self) -> None:
self.value: str = self.secret_store.fetch_secret(self.name)
self.value_hash: str = self._get_value_hash(self.value)
@staticmethod
def _get_value_hash(value: str) -> str... | Secret |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 14231,
"end": 15315
} | class ____(__TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = closing.__doc__
obj = closing(None)
self.assertEqual(obj.__doc__, cm_docstring)
def test_closing(self):
... | ClosingTestCase |
python | gevent__gevent | src/gevent/lock.py | {
"start": 5180,
"end": 6173
} | class ____(_AtomicSemaphoreMixin, BoundedSemaphore):
__doc__ = BoundedSemaphore.__doc__
__slots__ = (
'_lock_lock',
)
def release(self): # pylint:disable=useless-super-delegation
# This method is duplicated here so that it can get
# properly documented.
return super(_Ato... | _AtomicBoundedSemaphore |
python | ray-project__ray | python/ray/data/_internal/execution/operators/actor_pool_map_operator.py | {
"start": 26638,
"end": 27488
} | class ____(abc.ABC):
def __init__(self, actor_pool: "_ActorPool"):
"""Initialize the actor task selector.
Args:
actor_pool: The actor pool to select tasks from.
"""
self._actor_pool = actor_pool
@abstractmethod
def select_actors(
self, input_queue: Bundl... | _ActorTaskSelector |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/extractors/base.py | {
"start": 3129,
"end": 6449
} | class ____(BaseExtractor):
"""Extractor that uses `get_openlineage_facets_on_start/complete/failure` methods."""
@classmethod
def get_operator_classnames(cls) -> list[str]:
"""
Assign this extractor to *no* operators.
Default extractor is chosen not on the classname basis, but
... | DefaultExtractor |
python | getsentry__sentry | tests/sentry/api/endpoints/test_custom_rules.py | {
"start": 6476,
"end": 12623
} | class ____(APITestCase):
"""
Tests that calling the endpoint converts the query to a rule returns it and saves it in the db
"""
endpoint = "sentry-api-0-organization-dynamic_sampling-custom_rules"
method = "post"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.... | CustomRulesEndpoint |
python | SmileyChris__easy-thumbnails | demoproject/mainapp/apps.py | {
"start": 36,
"end": 146
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "mainapp"
| MainappConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vision.py | {
"start": 21981,
"end": 25335
} | class ____(GoogleCloudBaseOperator):
"""
Get information associated with a ``Product``.
Possible errors:
- Returns `NOT_FOUND` if the `Product` does not exist.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudVision... | CloudVisionGetProductOperator |
python | getsentry__sentry | src/sentry/models/rule.py | {
"start": 5479,
"end": 5611
} | class ____(Enum):
CREATED = 1
DELETED = 2
UPDATED = 3
ENABLED = 4
DISABLED = 5
@region_silo_model
| RuleActivityType |
python | xlwings__xlwings | xlwings/main.py | {
"start": 90704,
"end": 92316
} | class ____(Ranges):
"""
Represents the columns of a range. Do not construct this class directly, use
:attr:`Range.columns` instead.
Example
-------
.. code-block:: python
import xlwings as xw
wb = xw.Book("MyFile.xlsx")
sheet1 = wb.sheets[0]
myrange = sheet1.r... | RangeColumns |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_recent_searches.py | {
"start": 7466,
"end": 8990
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-recent-searches"
method = "post"
@cached_property
def organization(self):
return self.create_organization()
@cached_property
def user(self):
user = self.create_user("test@test.com")
self.create_team(members=... | RecentSearchesCreateTest |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/top_level.py | {
"start": 253,
"end": 274
} | class ____(Bar): ...
| Foo |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 33895,
"end": 33979
} | class ____(MaskedOperatorTests, LongitudeSetup):
pass
| TestMaskedLongitudeOperators |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/build_image/steps/java_connectors.py | {
"start": 665,
"end": 2963
} | class ____(BuildConnectorImagesBase):
"""
A step to build Java connector images using the distTar Gradle task.
"""
async def _run(self, dist_dir: Directory) -> StepResult:
dist_tar: File
try:
dir_files = await dist_dir.entries()
tar_files = [f for f in dir_files ... | BuildConnectorImages |
python | google__pytype | pytype/tests/test_abc2.py | {
"start": 129,
"end": 6909
} | class ____(test_base.BaseTest):
"""Tests for @abc.abstractmethod."""
def test_no_skip_call(self):
self.Check(
"""
import abc
class Example(metaclass=abc.ABCMeta):
@abc.abstractmethod
def foo(self) -> int:
return None
""",
skip_repeat_calls=False,
)
... | AbstractMethodTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E70.py | {
"start": 893,
"end": 944
} | class ____: ...
#:
def f(): ...
#: E701:1:8 E702:1:13
| C |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 272177,
"end": 273130
} | class ____(GenericTypeCompiler):
def process(self, type_, **kw):
try:
_compiler_dispatch = type_._compiler_dispatch
except AttributeError:
return self._visit_unknown(type_, **kw)
else:
return _compiler_dispatch(self, **kw)
def __getattr__(self, key):
... | StrSQLTypeCompiler |
python | django__django | tests/ordering/models.py | {
"start": 1888,
"end": 2051
} | class ____(models.Model):
parent = models.ForeignKey(OrderedByExpression, models.CASCADE)
class Meta:
ordering = ["parent"]
| OrderedByExpressionChild |
python | django__django | tests/get_or_create/tests.py | {
"start": 23113,
"end": 29256
} | class ____(TransactionTestCase):
available_apps = ["get_or_create"]
@skipUnlessDBFeature("has_select_for_update")
@skipUnlessDBFeature("supports_transactions")
def test_updates_in_transaction(self):
"""
Objects are selected and updated in a transaction to avoid race
conditions. ... | UpdateOrCreateTransactionTests |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/state.py | {
"start": 474,
"end": 1250
} | class ____:
"""Ongoing state of an active worker group.
Attributes:
start_time: The time when the worker group was started.
workers: The workers in the worker group.
These should always be in sorted order by world rank.
placement_group: The placement group for the worker gro... | WorkerGroupState |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 42665,
"end": 43659
} | class ____:
"""
Wrapper around a dictionary that will hash SymInts with their nodes
"""
def __init__(self) -> None:
self.sym_node_dict: dict[PySymType, _PySymProxyType] = {}
def __setitem__(self, key: PySymType, value: _PySymProxyType) -> None:
self.sym_node_dict[key.node] = value
... | _SymNodeDict |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 428775,
"end": 428961
} | class ____(VegaLiteSchema):
"""FontStyle schema wrapper."""
_schema = {"$ref": "#/definitions/FontStyle"}
def __init__(self, *args):
super().__init__(*args)
| FontStyle |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 6760,
"end": 11416
} | class ____(AbstractInstanceValue):
@property
def array_type(self):
name = self.class_value.py__name__()
if name in ['list', 'set', 'dict'] \
and self.parent_context.get_root_context().is_builtins_module():
return name
return None
@property
def name(se... | _BaseTreeInstance |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 11013,
"end": 11317
} | class ____(_GenerativeProvider):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.MISTRAL, frozen=True, exclude=True
)
temperature: Optional[float]
model: Optional[str]
maxTokens: Optional[int]
baseURL: Optional[str]
| _GenerativeMistral |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type.py | {
"start": 21123,
"end": 23520
} | class ____:
"""Codec for `tf.ExtensionTypeSpec`."""
def can_encode(self, pyobj):
"""Returns true if `pyobj` can be encoded as an ExtensionTypeSpec."""
if isinstance(pyobj, ExtensionTypeSpec):
try:
type_spec_registry.get_name(type(pyobj))
return True
except ValueError:
re... | _ExtensionTypeSpecCodec |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/combined_loader.py | {
"start": 6430,
"end": 7226
} | class ____(_ModeIterator):
@override
def __next__(self) -> _ITERATOR_RETURN:
n = len(self.iterators)
out = [None] * n
all_exhausted = True
for i in range(n):
with contextlib.suppress(StopIteration):
out[i] = next(self.iterators[i])
all_... | _MaxSize |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 107482,
"end": 107750
} | class ____(BaseModel):
direction: "ReshardingDirection" = Field(..., description="")
shard_id: int = Field(..., description="")
peer_id: int = Field(..., description="")
shard_key: Optional["ShardKey"] = Field(default=None, description="")
| ReshardingInfo |
python | wandb__wandb | wandb/vendor/pygments/lexers/html.py | {
"start": 3374,
"end": 6000
} | class ____(RegexLexer):
"""
A lexer for DTDs (Document Type Definitions).
.. versionadded:: 1.5
"""
flags = re.MULTILINE | re.DOTALL
name = 'DTD'
aliases = ['dtd']
filenames = ['*.dtd']
mimetypes = ['application/xml-dtd']
tokens = {
'root': [
include('comm... | DtdLexer |
python | python-poetry__poetry | src/poetry/console/commands/lock.py | {
"start": 269,
"end": 1136
} | class ____(InstallerCommand):
name = "lock"
description = "Locks the project dependencies."
options: ClassVar[list[Option]] = [
option(
"regenerate",
None,
"Ignore existing lock file"
" and overwrite it with a new lock file created from scratch.",
... | LockCommand |
python | pypa__pip | src/pip/_internal/operations/install/wheel.py | {
"start": 12379,
"end": 13951
} | class ____:
def __init__(
self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile
) -> None:
self.src_record_path = src_record_path
self.dest_path = dest_path
self._zip_file = zip_file
self.changed = False
def _getinfo(self) -> ZipInfo:
return se... | ZipBackedFile |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 58634,
"end": 60068
} | class ____(VarianceScaling):
"""The Glorot uniform initializer, also called Xavier uniform initializer.
It draws samples from a uniform distribution within [-limit, limit]
where `limit` is `sqrt(6 / (fan_in + fan_out))`
where `fan_in` is the number of input units in the weight tensor
and `fan_out` is the num... | GlorotUniform |
python | scipy__scipy | scipy/linalg/tests/test_matfuncs.py | {
"start": 22278,
"end": 30585
} | class ____:
def test_round_trip_random_complex(self):
rng = np.random.default_rng(1234)
for p in range(1, 5):
for n in range(1, 5):
M_unscaled = (rng.standard_normal((n, n)) +
1j * rng.standard_normal((n, n)))
for scale in np.... | TestFractionalMatrixPower |
python | numpy__numpy | numpy/f2py/_backends/_backend.py | {
"start": 38,
"end": 1151
} | class ____(ABC):
def __init__(
self,
modulename,
sources,
extra_objects,
build_dir,
include_dirs,
library_dirs,
libraries,
define_macros,
undef_macros,
f2py_flags,
sysinfo_flags,
fc_flags,
flib_flags,
... | Backend |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_security.py | {
"start": 220,
"end": 2008
} | class ____(AdminTestMixin, TestCase):
def test_csrf(self):
self._get_url_response(self.book_process_import_url, expected_status_code=405)
def test_import_file_name_in_tempdir(self):
# 65 - import_file_name form field can be use to access the filesystem
import_file_name = os.path.join(
... | ImportAdminSecurityTests |
python | altair-viz__altair | tests/utils/test_schemapi.py | {
"start": 3581,
"end": 3740
} | class ____(_TestSchema):
_schema = {
"$schema": _JSON_SCHEMA_DRAFT_URL,
"anyOf": [{"type": "integer"}, {"type": "string"}],
}
| SimpleUnion |
python | dask__distributed | distributed/diagnostics/plugin.py | {
"start": 29273,
"end": 29604
} | class ____(NannyPlugin):
restart = True
def __init__(self, environ: dict | None = None):
environ = environ or {}
self.environ = {k: str(v) for k, v in environ.items()}
async def setup(self, nanny):
nanny.env.update(self.environ)
UPLOAD_DIRECTORY_MODES = ["all", "scheduler", "work... | Environ |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 7522,
"end": 8497
} | class ____(PipError):
"""Raised when accessing a Distribution's "METADATA" or "PKG-INFO".
This signifies an inconsistency, when the Distribution claims to have
the metadata file (if not, raise ``FileNotFoundError`` instead), but is
not actually able to produce its content. This may be due to permission... | NoneMetadataError |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 55681,
"end": 57412
} | class ____(SingleContinuousDistribution):
_argnames = ('b', 'eta')
set = Interval(0, oo)
@staticmethod
def check(b, eta):
_value_check(b > 0, "b must be positive")
_value_check(eta > 0, "eta must be positive")
def pdf(self, x):
eta, b = self.eta, self.b
return b*et... | GompertzDistribution |
python | scipy__scipy | scipy/interpolate/tests/test_interpnd.py | {
"start": 8790,
"end": 15527
} | class ____:
def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False,
rescale=False, **kw):
rng = np.random.RandomState(1234)
# np.random.seed(1234)
if x is None:
x = np.array([(0, 0), (0, 1),
(1, 0), (1, 1), (0.25, 0.75... | TestCloughTocher2DInterpolator |
python | rapidsai__cudf | python/cudf/cudf/core/indexing_utils.py | {
"start": 1224,
"end": 19581
} | class ____:
"""An indexer for a scalar value."""
key: GatherMap
IndexingSpec: TypeAlias = (
EmptyIndexer | MapIndexer | MaskIndexer | ScalarIndexer | SliceIndexer
)
# Helpers for code-sharing between loc and iloc paths
def expand_key(
key: Any, frame: DataFrame | Series, method_type: Literal["iloc"... | ScalarIndexer |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/argcompletion.py | {
"start": 3503,
"end": 5167
} | class ____(CompletionFinder):
"""
Custom completion finder for argcomplete.
It provides support for running completion in list mode, which argcomplete natively handles the same as standard completion.
"""
enabled = bool(argcomplete)
def __init__(self, *args, validator=None, **kwargs) -> None:
... | OptionCompletionFinder |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_webhook_requests.py | {
"start": 2158,
"end": 5724
} | class ____(SentryAppBaseEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (SentryAppStatsPermission,)
def get(self, request: Request, sentry_app: SentryApp) -> Response:
"""
:qparam string eventType: Optiona... | SentryAppWebhookRequestsEndpoint |
python | imageio__imageio | imageio/plugins/_tifffile.py | {
"start": 176347,
"end": 182175
} | class ____(object):
"""Sequence of TIFF files.
The image data in all files must match shape, dtype, etc.
Attributes
----------
files : list
List of file names.
shape : tuple
Shape of image sequence. Excludes shape of image array.
axes : str
Labels of axes in shape.
... | TiffSequence |
python | scipy__scipy | scipy/optimize/tests/test_direct.py | {
"start": 237,
"end": 13267
} | class ____:
def setup_method(self):
self.fun_calls = threading.local()
self.bounds_sphere = 4*[(-2, 3)]
self.optimum_sphere_pos = np.zeros((4, ))
self.optimum_sphere = 0.0
self.bounds_stylinski_tang = Bounds([-4., -4.], [4., 4.])
self.maxiter = 1000
# test funct... | TestDIRECT |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_dataproc.py | {
"start": 17670,
"end": 21399
} | class ____:
def test_async_cluster_trigger_serialization_should_execute_successfully(self, operation_trigger):
classpath, kwargs = operation_trigger.serialize()
assert classpath == "airflow.providers.google.cloud.triggers.dataproc.DataprocOperationTrigger"
assert kwargs == {
"nam... | TestDataprocOperationTrigger |
python | getsentry__sentry | src/sentry/seer/explorer/custom_tool_utils.py | {
"start": 871,
"end": 976
} | class ____(BaseModel):
"""Simple boolean type."""
kind: Literal["boolean"] = "boolean"
| BooleanType |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session_test.py | {
"start": 35107,
"end": 35650
} | class ____:
"""A creator that counts the number of created sessions."""
def __init__(self, session):
self._initial_session = session
# We only have one session per test case. We can't re-create it, thus
# it shouldn't be closed.
self._initial_session.close = lambda *args: None
self._create_sess... | CountingSessionCreator |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/notifications/base.py | {
"start": 505,
"end": 2563
} | class ____(BlockSlackMessageBuilder):
def __init__(
self,
notification: BaseNotification,
context: Mapping[str, Any],
recipient: Actor,
) -> None:
super().__init__()
self.notification = notification
self.context = context
self.recipient = recipient... | SlackNotificationsMessageBuilder |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/tfr_gen.py | {
"start": 2160,
"end": 7860
} | class ____(enum.Enum):
"""All the supported types.
1-3: tfr types
4-99: mlir built-in types
100-199: TF related translator internal types
200- : Python related translator internal types
"""
TENSOR = 1
TENSOR_LIST = 2
ATTR = 3
NONE = 4
SHAPE = 5 # shape -> !shape.shape
I1 = 21
I8 = 22... | TFRTypes |
python | celery__celery | t/unit/utils/test_time.py | {
"start": 11850,
"end": 12088
} | class ____:
def test_repr(self):
x = ffwd(year=2012)
assert repr(x)
def test_radd_with_unknown_gives_NotImplemented(self):
x = ffwd(year=2012)
assert x.__radd__(object()) == NotImplemented
| test_ffwd |
python | getsentry__sentry | src/sentry/migrations/0965_gzippeddict_big_tables.py | {
"start": 188,
"end": 1892
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | astropy__astropy | astropy/coordinates/builtin_frames/hadec.py | {
"start": 3562,
"end": 5830
} | class ____(BaseCoordinateFrame):
"""
A coordinate or frame in the Hour Angle-Declination system (Equatorial
coordinates) with respect to the WGS84 ellipsoid. Hour Angle is oriented
with respect to upper culmination such that the hour angle is negative to
the East and positive to the West.
This... | HADec |
python | TheAlgorithms__Python | graphs/multi_heuristic_astar.py | {
"start": 70,
"end": 8564
} | class ____:
def __init__(self):
self.elements = []
self.set = set()
def minkey(self):
if not self.empty():
return self.elements[0][0]
else:
return float("inf")
def empty(self):
return len(self.elements) == 0
def put(self, item, priority)... | PriorityQueue |
python | getsentry__sentry | src/sentry/preprod/api/models/launchpad.py | {
"start": 490,
"end": 710
} | class ____(BaseModel):
model_config = ConfigDict()
state: Literal[PreprodArtifactSizeMetrics.SizeAnalysisState.PROCESSING] = (
PreprodArtifactSizeMetrics.SizeAnalysisState.PROCESSING
)
| PutSizeProcessing |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 66688,
"end": 69675
} | class ____(SeamlessM4Tv2PreTrainedModel):
main_input_name = "input_features"
input_modalities = "audio"
def __init__(self, config: SeamlessM4Tv2Config):
super().__init__(config)
self.feature_projection = SeamlessM4Tv2ConformerFeatureProjection(config)
self.encoder = SeamlessM4Tv2Co... | SeamlessM4Tv2SpeechEncoder |
python | getsentry__sentry | tests/sentry/runner/commands/test_backup.py | {
"start": 15325,
"end": 19565
} | class ____(TestCase):
"""
Test success cases of the `sentry sanitize` CLI command on decrypted inputs with encrypted
outputs.
"""
def test_sanitize_with_decryption_and_encryption(self) -> None:
with TemporaryDirectory() as tmp_dir:
tmp_sanitized_encrypted_path = Path(tmp_dir).jo... | GoodSanitizeCommandEncryptionTests |
python | coleifer__peewee | tests/fields.py | {
"start": 49570,
"end": 49651
} | class ____(TestModel):
text_field = TextField()
char_field = CharField()
| SM |
python | django__django | tests/urlpatterns_reverse/middleware.py | {
"start": 315,
"end": 440
} | class ____(MiddlewareMixin):
def process_request(self, request):
request.urlconf = None
| NullChangeURLconfMiddleware |
python | doocs__leetcode | lcof/面试题45. 把数组排成最小的数/Solution.py | {
"start": 0,
"end": 262
} | class ____:
def minNumber(self, nums: List[int]) -> str:
def cmp(a, b):
x, y = a + b, b + a
return -1 if x < y else 1
ans = [str(x) for x in nums]
ans.sort(key=cmp_to_key(cmp))
return "".join(ans)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/count-odd-numbers-in-an-interval-range.py | {
"start": 29,
"end": 224
} | class ____(object):
def countOdds(self, low, high):
"""
:type low: int
:type high: int
:rtype: int
"""
return (high+1)//2 - ((low-1)+1)//2
| Solution |
python | redis__redis-py | redis/connection.py | {
"start": 6375,
"end": 21483
} | class ____:
"""
Abstract class for handling maintenance notifications logic.
This class is expected to be used as base class together with ConnectionInterface.
This class is intended to be used with multiple inheritance!
All logic related to maintenance notifications is encapsulated in this class.... | MaintNotificationsAbstractConnection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.