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 | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 81845,
"end": 82071
} | class ____(BaseModel):
ongoing_create_snapshot_requests: int = Field(..., description="")
is_recovering: bool = Field(..., description="")
recovery_timestamp: int = Field(..., description="")
| PartialSnapshotTelemetry |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/compute.py | {
"start": 3228,
"end": 10961
} | class ____(ComputeEngineBaseOperator):
"""
Creates an Instance in Google Compute Engine based on specified parameters.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ComputeEngineInsertInstanceOperator`
:param body: Instanc... | ComputeEngineInsertInstanceOperator |
python | doocs__leetcode | solution/1100-1199/1138.Alphabet Board Path/Solution.py | {
"start": 0,
"end": 572
} | class ____:
def alphabetBoardPath(self, target: str) -> str:
i = j = 0
ans = []
for c in target:
v = ord(c) - ord("a")
x, y = v // 5, v % 5
while j > y:
j -= 1
ans.append("L")
while i > x:
i -= 1
... | Solution |
python | pytorch__pytorch | test/test_cpp_extensions_aot.py | {
"start": 14464,
"end": 15881
} | class ____(common.TestCase):
def setUp(self):
super().setUp()
@xfailIfTorchDynamo
def test_rng(self):
fourty_two = torch.full((10,), 42, dtype=torch.int64)
t = torch.empty(10, dtype=torch.int64).random_()
self.assertNotEqual(t, fourty_two)
gen = torch.Generator(dev... | TestRNGExtension |
python | kubernetes-client__python | kubernetes/client/models/apiextensions_v1_webhook_client_config.py | {
"start": 383,
"end": 8076
} | 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... | ApiextensionsV1WebhookClientConfig |
python | joke2k__faker | faker/providers/automotive/it_IT/__init__.py | {
"start": 48,
"end": 312
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``it_IT`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Italy
"""
license_formats = (
# 1994-present
"??###??",
)
| Provider |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_spans_fields_stats.py | {
"start": 182,
"end": 6580
} | class ____(BaseSpansTestCase, APITestCase):
is_eap = True
view = "sentry-api-0-organization-spans-fields-stats"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def do_request(self, query=None, features=None, **kwargs):
if features is None:
fea... | OrganizationSpansFieldsStatsEndpointTest |
python | facebookresearch__faiss | tests/test_search_params.py | {
"start": 13308,
"end": 17320
} | class ____(unittest.TestCase):
def do_test_with_param(
self, index_key, ps_params, params):
"""
Test equivalence between setting
1. param_name_2 = value with ParameterSpace
2. pass in a SearchParameters with param_name = value
"""
ds = datasets.SyntheticD... | TestSearchParams |
python | ray-project__ray | python/ray/data/_internal/logical/operators/from_operators.py | {
"start": 2922,
"end": 3010
} | class ____(AbstractFrom):
"""Logical operator for `from_arrow`."""
pass
| FromArrow |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 9526,
"end": 11014
} | class ____(nn.Module):
r"""
This corresponds to the depthwise convolution phase of each block in the original implementation.
"""
def __init__(
self,
config: AlignVisionConfig,
in_dim: int,
stride: int,
kernel_size: int,
adjust_padding: bool,
):
... | AlignVisionDepthwiseLayer |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 112195,
"end": 112321
} | class ____:
xlScaleLinear = -4132 # from enum XlScaleType
xlScaleLogarithmic = -4133 # from enum XlScaleType
| ScaleType |
python | has2k1__plotnine | plotnine/scales/scale_identity.py | {
"start": 2350,
"end": 2410
} | class ____(scale_color_identity):
pass
| scale_colour_identity |
python | plotly__plotly.py | tests/test_core/test_figure_widget_backend/test_validate_no_frames.py | {
"start": 196,
"end": 1038
} | class ____(TestCase):
if figure_widget_available:
def test_no_frames_in_constructor_kwarg(self):
with pytest.raises(ValueError):
go.FigureWidget(frames=[{}])
def test_emtpy_frames_ok_as_constructor_kwarg(self):
go.FigureWidget(frames=[])
def test_no... | TestNoFrames |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 875072,
"end": 875484
} | 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("PullRequestReviewComment"... | PullRequestReviewCommentEdge |
python | ray-project__ray | python/ray/tests/test_async_compat.py | {
"start": 481,
"end": 549
} | class ____:
def sync_fn(self) -> None:
pass
| NoAsyncMethods |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/blobstore/wsgi/main.py | {
"start": 867,
"end": 1533
} | class ____:
def __call__(self, environ, start_response):
upload_url = blobstore.create_upload_url("/upload_photo")
response = """
<html><body>
<form action="{}" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name=... | UploadFormHandler |
python | ray-project__ray | python/ray/data/_internal/logical/rules/configure_map_task_memory.py | {
"start": 2591,
"end": 3709
} | class ____(ConfigureMapTaskMemoryRule):
def estimate_per_task_memory_requirement(self, op: MapOperator) -> Optional[int]:
# Typically, this configuration won't make a difference because
# `average_bytes_per_output` is usually ~128 MiB and each core usually has
# 4 GiB of memory. However, if ... | ConfigureMapTaskMemoryUsingOutputSize |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict16.py | {
"start": 140,
"end": 173
} | class ____(TD0):
value: str
| TD1 |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 80,
"end": 120
} | class ____(
object,
#
):
...
| A |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/test_external_execution_plan.py | {
"start": 10098,
"end": 12112
} | class ____(CacheableAssetsDefinition):
_cacheable_data = AssetsDefinitionCacheableData(
keys_by_output_name={"result": dg.AssetKey("foo")},
metadata_by_output_name={
"result": {
"some_val": MetadataValue.table_schema(
schema=dg.TableSchema(columns=[dg.... | MyCacheableAssetsDefinition |
python | sympy__sympy | sympy/plotting/series.py | {
"start": 81513,
"end": 96570
} | class ____(BaseSeries):
"""Representation for 2D Implicit plot."""
is_implicit = True
use_cm = False
_N = 100
def __init__(self, expr, var_start_end_x, var_start_end_y, label="", **kwargs):
super().__init__(**kwargs)
self.adaptive = kwargs.get("adaptive", False)
self.expr =... | ImplicitSeries |
python | pytorch__pytorch | test/export/test_lift_unlift.py | {
"start": 14455,
"end": 15620
} | class ____(TestCase):
def setUp(self):
super().setUp()
load_torchbind_test_lib()
def test_dict_api(self):
constant_attr_map = ConstantAttrMap()
const_obj = torch.classes._TorchScriptTesting._Foo(10, 20)
const_tensor = torch.ones(2, 3)
constant_attr_map.add(const_... | ConstantAttrMapTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 349989,
"end": 350298
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field(GitActor, graphql_name="node")
| GitActorEdge |
python | pypa__packaging | tests/test_metadata.py | {
"start": 253,
"end": 10108
} | class ____:
@pytest.mark.parametrize("raw_field", sorted(metadata._STRING_FIELDS))
def test_non_repeating_fields_only_once(self, raw_field: str) -> None:
data = "VaLuE"
header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
single_header = f"{header_field}: {data}"
raw, unparse... | TestRawMetadata |
python | getsentry__sentry | src/sentry/uptime/models.py | {
"start": 6985,
"end": 10572
} | class ____(DataSourceTypeHandler[UptimeSubscription]):
@override
@staticmethod
def bulk_get_query_object(
data_sources: list[DataSource],
) -> dict[int, UptimeSubscription | None]:
uptime_subscription_ids: list[int] = []
for ds in data_sources:
try:
u... | UptimeSubscriptionDataSourceHandler |
python | django__django | tests/dbshell/tests.py | {
"start": 202,
"end": 613
} | class ____(SimpleTestCase):
def test_command_missing(self):
msg = (
"You appear not to have the %r program installed or on your path."
% connection.client.executable_name
)
with self.assertRaisesMessage(CommandError, msg):
with mock.patch("subprocess.run",... | DbshellCommandTestCase |
python | ethereum__web3.py | web3/_utils/ens.py | {
"start": 1053,
"end": 1294
} | class ____:
def __init__(self, name_addr_pairs: dict[str, ChecksumAddress]) -> None:
self.registry = dict(name_addr_pairs)
def address(self, name: str) -> ChecksumAddress:
return self.registry.get(name, None)
| StaticENS |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 302963,
"end": 323837
} | class ____(Response):
"""
Response of tasks.get_by_id endpoint.
:param task: Task info
:type task: Task
"""
_service = "tasks"
_action = "get_by_id"
_version = "2.20"
_schema = {
"definitions": {
"artifact": {
"properties": {
... | GetByIdResponse |
python | Textualize__textual | docs/examples/styles/max_height.py | {
"start": 112,
"end": 509
} | class ____(App):
CSS_PATH = "max_height.tcss"
def compose(self):
yield Horizontal(
Placeholder("max-height: 10w", id="p1"),
Placeholder("max-height: 999", id="p2"),
Placeholder("max-height: 50%", id="p3"),
Placeholder("max-height: 10", id="p4"),
)... | MaxHeightApp |
python | pyodide__pyodide | src/py/pyodide/webloop.py | {
"start": 5750,
"end": 35124
} | class ____(asyncio.AbstractEventLoop):
"""A custom event loop for use in Pyodide.
Schedules tasks on the browser event loop. Does no lifecycle management and
runs forever.
:py:meth:`~asyncio.loop.run_forever` and
:py:meth:`~asyncio.loop.run_until_complete` cannot block like a normal event
loop... | WebLoop |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 132131,
"end": 134333
} | class ____(nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), leaky_relu_slope=0.1):
super().__init__()
self.leaky_relu_slope = leaky_relu_slope
self.convs1 = nn.ModuleList(
[
nn.Conv1d(
channels,
c... | HifiGanResidualBlock |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py | {
"start": 37712,
"end": 51541
} | class ____(TestConnectionEndpoint):
@pytest.mark.parametrize(
("actions", "expected_results"),
[
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [
... | TestBulkConnections |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 17188,
"end": 17738
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "test_with_context"
expected_hash = ["8b4a7452e1c5", "55b3123e884c", "bfc63829cc58"]
additional_test_settings = {
"COMPRESS_OFFLINE_CONTEXT": list(offline_context_generator())
}
def _prepare_contexts(self, engine):
if engin... | OfflineCompressTestCaseWithContextList |
python | pytorch__pytorch | torch/utils/flop_counter.py | {
"start": 24452,
"end": 29476
} | class ____:
"""
``FlopCounterMode`` is a context manager that counts the number of flops within its context.
It does this using a ``TorchDispatchMode``.
It also supports hierarchical output by passing a module (or list of
modules) to FlopCounterMode on construction. If you do not need hierarchical... | FlopCounterMode |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 38769,
"end": 39090
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"CANCELLED_SPONSORSHIP",
"NEW_SPONSORSHIP",
"PENDING_CHANGE",
"REFUND",
"SPONSOR_MATCH_DISABLED",
"TIER_CHANGE",
)
| SponsorsActivityAction |
python | pytorch__pytorch | torch/_dynamo/variables/distributed.py | {
"start": 6074,
"end": 9963
} | class ____(DistributedVariable):
@staticmethod
def is_placement(value: object) -> bool:
# we can't rely on importing/accessing torch distributed, it is not always built.
if not DistributedVariable.is_available():
return False
from torch.distributed.tensor.placement_types impo... | PlacementVariable |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 58426,
"end": 60062
} | class ____:
"""
Tests for DatabricksHook when auth is done with AAD token for SP as user inside workspace.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_... | TestDatabricksHookAadToken |
python | wandb__wandb | wandb/sdk/integration_utils/auto_logging.py | {
"start": 388,
"end": 596
} | class ____(Protocol[K, V]):
def __getitem__(self, key: K) -> V: ... # pragma: no cover
def get(
self, key: K, default: Optional[V] = None
) -> Optional[V]: ... # pragma: no cover
| Response |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/decorator_assets_definition_builder.py | {
"start": 8667,
"end": 9718
} | class ____(NamedTuple):
output_name: str
output: Out
def make_keys_by_output_name(
asset_outs: Mapping[AssetKey, tuple[str, Out]],
) -> Mapping[str, AssetKey]:
return {output_name: asset_key for asset_key, (output_name, _) in asset_outs.items()}
def compute_required_resource_keys(
required_resou... | NamedOut |
python | astropy__astropy | astropy/coordinates/representation/geodetic.py | {
"start": 6544,
"end": 6735
} | class ____(BaseGeodeticRepresentation):
"""Representation of points in WGS72 3D geodetic coordinates."""
_ellipsoid = "WGS72"
@format_doc(geodetic_base_doc)
| WGS72GeodeticRepresentation |
python | django__django | tests/m2m_regress/models.py | {
"start": 1212,
"end": 1346
} | class ____(SelfRefer):
pass
# Many-to-Many relation between models, where one of the PK's isn't an
# Autofield
| SelfReferChildSibling |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format09.py | {
"start": 315,
"end": 1675
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format09.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 12289,
"end": 12660
} | class ____(Rule):
subfunctions: Sequence[tuple[Rule, bool | Boolean]]
def eval(self) -> Expr:
return Piecewise(*[(substep.eval(), cond)
for substep, cond in self.subfunctions])
def contains_dont_know(self) -> bool:
return any(substep.contains_dont_know() for subs... | PiecewiseRule |
python | jd__tenacity | tenacity/__init__.py | {
"start": 5741,
"end": 6470
} | class ____:
"""Manage attempt context."""
def __init__(self, retry_state: "RetryCallState"):
self.retry_state = retry_state
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: t.Optional[t.Type[BaseException]],
exc_value: t.Optional[BaseException],
... | AttemptManager |
python | joke2k__faker | faker/providers/phone_number/pl_PL/__init__.py | {
"start": 49,
"end": 895
} | class ____(PhoneNumberProvider):
formats = (
# Mobile
# Government website: http://www.uke.gov.pl/numeracja-843
"50# ### ###",
"51# ### ###",
"53# ### ###",
"57# ### ###",
"60# ### ###",
"66# ### ###",
"69# ### ###",
"72# ### ###",
... | Provider |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_version.py | {
"start": 230,
"end": 2743
} | class ____:
@pytest.fixture
def mock_connector(self, mocker, tmp_path):
connector = mocker.Mock(code_directory=str(tmp_path), technical_name="mock-connector")
return connector
def _get_version_increment_check(self, mocker, master_version="1.0.0", current_version="1.0.1"):
mocker.pat... | TestVersionIncrementCheck |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_searches.py | {
"start": 879,
"end": 4725
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ISSUES
permission_classes = (OrganizationSearchPermission,)
def get(self, request: Request, organization: Organization) -> Response:
"""... | OrganizationSearchesEndpoint |
python | getsentry__sentry | src/sentry/notifications/notification_action/issue_alert_registry/handlers/pagerduty_issue_alert_handler.py | {
"start": 407,
"end": 800
} | class ____(BaseIssueAlertHandler):
@classmethod
def get_target_display(cls, action: Action, mapping: ActionFieldMapping) -> dict[str, Any]:
return {}
@classmethod
def get_additional_fields(cls, action: Action, mapping: ActionFieldMapping) -> dict[str, Any]:
blob = OnCallDataBlob(**actio... | PagerDutyIssueAlertHandler |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 249551,
"end": 256680
} | class ____(TypedDict, total=False):
"""
:class:`altair.ScaleConfig` ``TypedDict`` wrapper.
Parameters
----------
animationDuration
Default animation duration (in seconds) for time encodings, except for `band
<https://vega.github.io/vega-lite/docs/scale.html#band>`__ scales.
... | ScaleConfigKwds |
python | django__django | django/contrib/sessions/exceptions.py | {
"start": 69,
"end": 171
} | class ____(SuspiciousOperation):
"""Invalid characters in session key"""
pass
| InvalidSessionKey |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_managed_kafka.py | {
"start": 2615,
"end": 2990
} | class ____:
def test_class_attributes(self):
assert ApacheKafkaClusterListLink.key == EXPECTED_MANAGED_KAFKA_CLUSTER_LIST_LINK_KEY
assert ApacheKafkaClusterListLink.name == EXPECTED_MANAGED_KAFKA_CLUSTER_LIST_LINK_NAME
assert ApacheKafkaClusterListLink.format_str == EXPECTED_MANAGED_KAFKA_CL... | TestApacheKafkaClusterListLink |
python | doocs__leetcode | solution/3500-3599/3578.Count Partitions With Max-Min Difference at Most K/Solution.py | {
"start": 0,
"end": 514
} | class ____:
def countPartitions(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
sl = SortedList()
n = len(nums)
f = [1] + [0] * n
g = [1] + [0] * n
l = 1
for r, x in enumerate(nums, 1):
sl.add(x)
while sl[-1] - sl[0] > k:
... | Solution |
python | bokeh__bokeh | src/bokeh/document/modules.py | {
"start": 1478,
"end": 4952
} | class ____:
''' Keep track of and clean up after modules created while building Bokeh
Documents.
'''
_document: weakref.ReferenceType[Document]
_modules: list[ModuleType]
def __init__(self, document: Document):
'''
Args:
document (Document): A Document to manage m... | DocumentModuleManager |
python | bokeh__bokeh | src/bokeh/models/tickers.py | {
"start": 11868,
"end": 13286
} | class ____(CompositeTicker):
''' Generate nice ticks across different date and time scales.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
num_minor_ticks = Override(default=0)
# TODO: (bev) ... | DatetimeTicker |
python | Pylons__pyramid | src/pyramid/config/assets.py | {
"start": 3165,
"end": 6700
} | class ____:
# pkg_resources arg in kw args below for testing
def __init__(self, package, pkg_resources=pkg_resources):
loader = self._real_loader = getattr(package, '__loader__', None)
if isinstance(loader, self.__class__):
self._real_loader = None
# We register ourselves as ... | PackageOverrides |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 3389,
"end": 3540
} | class ____:
def __call__(self, config_uri, global_conf):
self.config_uri = config_uri
self.defaults = global_conf
| dummy_setup_logging |
python | aio-libs__aiohttp | aiohttp/web_server.py | {
"start": 673,
"end": 4206
} | class ____(Generic[_Request]):
request_factory: _RequestFactory[_Request]
@overload
def __init__(
self: "Server[BaseRequest]",
handler: Callable[[_Request], Awaitable[StreamResponse]],
*,
debug: bool | None = None,
handler_cancellation: bool = False,
**kwargs... | Server |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 12079,
"end": 12784
} | class ____(Value):
__slots__ = ('loc', 'value',)
_fields = ('value',)
def __init__(self, value, loc=None):
self.loc = loc
self.value = value
def __eq__(self, other):
return (
self is other or (
isinstance(other, FloatValue) and
# self... | FloatValue |
python | apache__airflow | providers/edge3/src/airflow/providers/edge3/worker_api/datamodels.py | {
"start": 4235,
"end": 5317
} | class ____(WorkerQueuesBase):
"""Details of the worker state sent to the scheduler."""
state: Annotated[EdgeWorkerState, Field(description="State of the worker from the view of the worker.")]
jobs_active: Annotated[int, Field(description="Number of active jobs the worker is running.")] = 0
queues: Anno... | WorkerStateBody |
python | airbytehq__airbyte | airbyte-integrations/bases/base-normalization/normalization/transform_catalog/table_name_registry.py | {
"start": 788,
"end": 1231
} | class ____:
"""
A record summary of a name conflict detected and resolved in TableNameRegistry
"""
def __init__(self, schema: str, json_path: List[str], table_name_conflict: str, table_name_resolved: str):
self.schema: str = schema
self.json_path: List[str] = json_path
self.tabl... | ConflictedNameMetadata |
python | scrapy__scrapy | scrapy/downloadermiddlewares/retry.py | {
"start": 4752,
"end": 6809
} | class ____:
crawler: Crawler
def __init__(self, settings: BaseSettings):
if not settings.getbool("RETRY_ENABLED"):
raise NotConfigured
self.max_retry_times = settings.getint("RETRY_TIMES")
self.retry_http_codes = {int(x) for x in settings.getlist("RETRY_HTTP_CODES")}
... | RetryMiddleware |
python | doocs__leetcode | lcci/01.02.Check Permutation/Solution2.py | {
"start": 0,
"end": 114
} | class ____:
def CheckPermutation(self, s1: str, s2: str) -> bool:
return sorted(s1) == sorted(s2)
| Solution |
python | PrefectHQ__prefect | src/prefect/events/clients.py | {
"start": 4334,
"end": 5372
} | class ____(abc.ABC):
"""The abstract interface for all Prefect Events clients"""
@property
def client_name(self) -> str:
return self.__class__.__name__
async def emit(self, event: Event) -> None:
"""Emit a single event"""
if not hasattr(self, "_in_context"):
raise T... | EventsClient |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 8082,
"end": 9427
} | class ____(nn.Module):
def __init__(self, config, layer_id=0):
super().__init__()
if layer_id == 0:
in_conv_dim = config.num_mel_bins
else:
in_conv_dim = config.speech_decoder_postnet_units
if layer_id == config.speech_decoder_postnet_layers - 1:
... | FastSpeech2ConformerBatchNormConvLayer |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 18926,
"end": 20069
} | class ____(nn.Module):
"""DAC Encoder"""
def __init__(self, config: DacConfig):
super().__init__()
strides = config.downsampling_ratios
# Create first convolution
self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3)
self.block = []
# ... | DacEncoder |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_index.py | {
"start": 459,
"end": 3645
} | class ____(unittest.TestCase):
def test_ivfflat_search_preassigned(self):
res = faiss.StandardGpuResources()
d = 50
nb = 50000
nq = 100
nlist = 128
nprobe = 10
k = 50
config = faiss.GpuIndexIVFFlatConfig()
config.use_cuvs = False
idx_g... | TestIVFSearchPreassigned |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 576805,
"end": 577191
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "verification_token")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
verification_token = sgqlc.types.Field(String, grap... | RegenerateVerifiableDomainTokenPayload |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/endpoints/resource.py | {
"start": 315,
"end": 3243
} | class ____(BaseEndpoint):
"""Authorizes access to protected resources.
The client accesses protected resources by presenting the access
token to the resource server. The resource server MUST validate the
access token and ensure that it has not expired and that its scope
covers the requested resou... | ResourceEndpoint |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 35673,
"end": 36368
} | class ____(BaseLinksSerializer):
_self = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
def get__self(self, obj):
path = reverse(
"projects-environmentvariables-detail",
kwargs={
"parent_lookup_project__slug": obj.project.sl... | EnvironmentVariableLinksSerializer |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_team_details.py | {
"start": 2784,
"end": 3140
} | class ____(Serializer):
def serialize(
self, obj: OrganizationMemberTeam, attrs: Mapping[Any, Any], user: Any, **kwargs: Any
) -> OrganizationMemberTeamSerializerResponse:
return {
"isActive": obj.is_active,
"teamRole": obj.role, # type:ignore[typeddict-item]
}
... | OrganizationMemberTeamDetailsSerializer |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/stats.py | {
"start": 4449,
"end": 7581
} | class ____:
cprofile_stats: pstats.Stats
def __init__(self, fixture, iterations, options):
self.name = fixture.name
self.fullname = fixture.fullname
self.group = fixture.group
self.param = fixture.param
self.params = fixture.params
self.extra_info = fixture.extra... | Metadata |
python | Textualize__textual | docs/examples/styles/outline.py | {
"start": 384,
"end": 553
} | class ____(App):
CSS_PATH = "outline.tcss"
def compose(self):
yield Label(TEXT)
if __name__ == "__main__":
app = OutlineApp()
app.run()
| OutlineApp |
python | encode__starlette | starlette/templating.py | {
"start": 987,
"end": 2065
} | class ____(HTMLResponse):
def __init__(
self,
template: Any,
context: dict[str, Any],
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
):
self.template = temp... | _TemplateResponse |
python | django__django | tests/view_tests/models.py | {
"start": 681,
"end": 941
} | class ____(BaseArticle):
"""
An Article class with a get_absolute_url defined.
"""
date_created = models.DateTimeField()
def get_absolute_url(self):
return "/urlarticles/%s/" % self.slug
get_absolute_url.purge = True
| UrlArticle |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 987615,
"end": 989329
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for StatusCheckRollupContext."""
__schema__ = github_schema
__field_names__ = (
"check_run_count",
"check_run_counts_by_state",
"edges",
"nodes",
"page_info",
"status_context_count",
"st... | StatusCheckRollupContextConnection |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataflow.py | {
"start": 10332,
"end": 13399
} | class ____:
@pytest.fixture
def sync_operator(self):
return DataflowStartFlexTemplateOperator(
task_id="start_flex_template_streaming_beam_sql",
body={"launchParameter": TEST_FLEX_PARAMETERS},
do_xcom_push=True,
project_id=TEST_PROJECT,
locatio... | TestDataflowStartFlexTemplateOperator |
python | tensorflow__tensorflow | tensorflow/python/keras/losses.py | {
"start": 35337,
"end": 37170
} | class ____(LossFunctionWrapper):
"""Computes the Poisson loss between `y_true` and `y_pred`.
`loss = y_pred - y_true * log(y_pred)`
Standalone usage:
>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [0., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> p = tf.keras.losses.Pois... | Poisson |
python | openai__openai-python | src/openai/resources/beta/threads/messages.py | {
"start": 27314,
"end": 28524
} | class ____:
def __init__(self, messages: AsyncMessages) -> None:
self._messages = messages
self.create = ( # pyright: ignore[reportDeprecated]
_legacy_response.async_to_raw_response_wrapper(
messages.create, # pyright: ignore[reportDeprecated],
)
)
... | AsyncMessagesWithRawResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 13637,
"end": 13751
} | class ____(AdsInsights):
breakdowns = ["age"]
action_breakdowns = ["action_type"]
| AdsInsightsDemographicsAge |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_gtin_variable_measure_trade_item.py | {
"start": 1031,
"end": 2075
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.gtin_variable_measure_trade_item"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)... | ColumnValuesToBeGtinVariableMeasureTradeItem |
python | tensorflow__tensorflow | tensorflow/python/autograph/impl/api.py | {
"start": 3568,
"end": 3690
} | class ____(AutoGraphError):
"""Raised during the staging (i.e. Python execution) of converted code."""
pass
| StagingError |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 114840,
"end": 117694
} | class ____(Request):
"""
Move models to a project
:param ids: Models to move
:type ids: Sequence[str]
:param project: Target project ID. If not provided, `project_name` must be
provided. Use null for the root project
:type project: str
:param project_name: Target project name. If pr... | MoveRequest |
python | getsentry__sentry | src/sentry/search/events/builder/spans_indexed.py | {
"start": 1612,
"end": 3607
} | class ____(BaseQueryBuilder):
requires_organization_condition = True
uuid_fields = SPAN_UUID_FIELDS
span_id_fields = SPAN_ID_FIELDS
duration_fields = DURATION_FIELDS
size_fields = SIZE_FIELDS
config_class = SpansEAPDatasetConfig
def get_field_type(self, field: str) -> str | None:
ta... | SpansEAPQueryBuilder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataflow.py | {
"start": 8066,
"end": 20959
} | class ____(GoogleCloudBaseOperator):
"""
Start a Dataflow job with a classic template; the parameters of the operation will be passed to the job.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataflowTemplatedJobStartOperator`
... | DataflowTemplatedJobStartOperator |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 48135,
"end": 49697
} | class ____(BaseModel):
"""
DAG Run serializer for responses.
"""
dag_run_id: Annotated[str, Field(title="Dag Run Id")]
dag_id: Annotated[str, Field(title="Dag Id")]
logical_date: Annotated[datetime | None, Field(title="Logical Date")] = None
queued_at: Annotated[datetime | None, Field(title... | DAGRunResponse |
python | huggingface__transformers | tests/quantization/gptq/test_gptq.py | {
"start": 2485,
"end": 11828
} | class ____(unittest.TestCase):
model_name = "bigscience/bloom-560m"
input_text = "Hello my name is"
EXPECTED_OUTPUTS = set()
# flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions
EXPECTED_OUTPUTS.add("Hello my na... | GPTQTest |
python | Lightning-AI__lightning | src/lightning/pytorch/loggers/wandb.py | {
"start": 1716,
"end": 25507
} | class ____(Logger):
r"""Log using `Weights and Biases <https://docs.wandb.ai/guides/integrations/lightning>`_.
**Installation and set-up**
Install with pip:
.. code-block:: bash
pip install wandb
Create a `WandbLogger` instance:
.. code-block:: python
from lightning.pytorc... | WandbLogger |
python | django__django | tests/auth_tests/test_remote_user.py | {
"start": 16062,
"end": 16838
} | class ____(RemoteUserTest):
"""Backend that allows inactive users."""
backend = "django.contrib.auth.backends.AllowAllUsersRemoteUserBackend"
def test_inactive_user(self):
user = User.objects.create(username="knownuser", is_active=False)
response = self.client.get("/remote_user/", **{self.... | AllowAllUsersRemoteUserBackendTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/tridiagonal_solve_op_test.py | {
"start": 2189,
"end": 27584
} | class ____(test.TestCase):
def _test(self,
diags,
rhs,
expected,
diags_format="compact",
transpose_rhs=False,
conjugate_rhs=False):
with self.cached_session():
pivoting = True
if hasattr(self, "pivoting"):
pivoting = self... | TridiagonalSolveOpTest |
python | getsentry__sentry | src/sentry/types/region.py | {
"start": 4042,
"end": 12950
} | class ____:
"""A set of regions in a Sentry environment.
This is a singleton class. It is immutable in a production environment,
but affords overrides by the subclass TestEnvRegionDirectory.
"""
def __init__(self, regions: Collection[Region]) -> None:
self._regions = frozenset(regions)
... | RegionDirectory |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_present_in_other_table.py | {
"start": 719,
"end": 9999
} | class ____(QueryExpectation):
"""Expect the values in a column to be present in another table.
This is an Expectation that allows for the validation of referential integrity, that a foreign key exists in
another table.
In the following example, order table has a foreign key to customer table, and refe... | ExpectColumnValuesToBePresentInOtherTable |
python | sympy__sympy | sympy/stats/crv.py | {
"start": 1554,
"end": 2210
} | class ____(ContinuousDomain, SingleDomain):
"""
A univariate domain with continuous support
Represented using a single symbol and interval.
"""
def compute_expectation(self, expr, variables=None, **kwargs):
if variables is None:
variables = self.symbols
if not variables:... | SingleContinuousDomain |
python | readthedocs__readthedocs.org | readthedocs/analytics/apps.py | {
"start": 84,
"end": 280
} | class ____(AppConfig):
"""Analytics app init code."""
default_auto_field = "django.db.models.BigAutoField"
name = "readthedocs.analytics"
verbose_name = "Analytics"
| AnalyticsAppConfig |
python | huggingface__transformers | src/transformers/models/deberta_v2/modeling_deberta_v2.py | {
"start": 18870,
"end": 20465
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
kernel_size = getattr(config, "conv_kernel_size", 3)
groups = getattr(config, "conv_groups", 1)
self.conv_act = getattr(config, "conv_act", "tanh")
self.conv = nn.Conv1d(
config.hidden_size, con... | ConvLayer |
python | keras-team__keras | keras/src/layers/regularization/gaussian_dropout.py | {
"start": 192,
"end": 2072
} | class ____(layers.Layer):
"""Apply multiplicative 1-centered Gaussian noise.
As it is a regularization layer, it is only active at training time.
Args:
rate: Float, drop probability (as with `Dropout`).
The multiplicative noise will have
standard deviation `sqrt(rate / (1 -... | GaussianDropout |
python | sympy__sympy | sympy/stats/matrix_distributions.py | {
"start": 4196,
"end": 5088
} | class ____:
"""Returns the sample from numpy of the given distribution"""
### TODO: Add tests after adding matrix distributions in numpy_rv_map
def __new__(cls, dist, size, seed=None):
return cls._sample_numpy(dist, size, seed)
@classmethod
def _sample_numpy(cls, dist, size, seed):
... | SampleMatrixNumpy |
python | google__jax | jax/_src/api.py | {
"start": 109631,
"end": 142062
} | class ____:
fun: Callable
in_tree: PyTreeDef
out_tree: PyTreeDef
args_res: list[Any]
opaque_residuals: list[Any]
jaxpr = property(lambda self: self.fun.args[2]) # type: ignore
def __call__(self, out_ct, *extra_args):
if extra_args:
name, *_ = self.jaxpr.debug_info.func_src_info.split(' ')
... | VJP |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/backfill.py | {
"start": 29463,
"end": 29722
} | class ____(graphene.Union):
class Meta:
types = (GraphenePartitionBackfills, GraphenePythonError)
name = "PartitionBackfillsOrError"
GrapheneBackfillPolicyType = graphene.Enum.from_enum(BackfillPolicyType)
| GraphenePartitionBackfillsOrError |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 13349,
"end": 13788
} | class ____(ChainedSource):
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen(self.base)
codegen.extend_output(codegen.create_load_attrs("__code__"))
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
return f"{self.base.... | CodeSource |
python | huggingface__transformers | src/transformers/models/bloom/modeling_bloom.py | {
"start": 37979,
"end": 43425
} | class ____(BloomPreTrainedModel):
def __init__(self, config: BloomConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = BloomModel(config)
self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
# Initialize weights and ap... | BloomForSequenceClassification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.