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 | huggingface__transformers | tests/models/qwen3_moe/test_modeling_qwen3_moe.py | {
"start": 1387,
"end": 4220
} | class ____(CausalLMModelTest, unittest.TestCase):
test_all_params_have_gradient = False
model_tester_class = Qwen3MoeModelTester
# TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146
def is_... | Qwen3MoeModelTest |
python | networkx__networkx | networkx/algorithms/tests/test_cluster.py | {
"start": 17600,
"end": 18450
} | class ____:
@classmethod
def setup_class(cls):
pytest.importorskip("numpy")
def test_empty(self):
G = nx.DiGraph()
with pytest.raises(ZeroDivisionError):
nx.average_clustering(G)
def test_average_clustering(self):
G = nx.cycle_graph(3, create_using=nx.DiGrap... | TestDirectedAverageClustering |
python | optuna__optuna | optuna/storages/journal/_redis.py | {
"start": 465,
"end": 3929
} | class ____(BaseJournalBackend, BaseJournalSnapshot):
"""Redis storage class for Journal log backend.
Args:
url:
URL of the redis storage, password and db are optional.
(ie: ``redis://localhost:6379``)
use_cluster:
Flag whether you use the Redis cluster. If th... | JournalRedisBackend |
python | astropy__astropy | astropy/cosmology/_src/traits/photoncomponent.py | {
"start": 380,
"end": 1338
} | class ____:
"""The cosmology has attributes and methods for the photon density."""
Ogamma0: float | np.floating
"""Omega gamma; the density/critical density of photons at z=0."""
inv_efunc: Callable[[NDArray[Any]], NDArray[Any]]
def Ogamma(self, z: Quantity | ArrayLike, /) -> FArray:
"""R... | PhotonComponent |
python | django__django | django/db/migrations/operations/models.py | {
"start": 21996,
"end": 23383
} | class ____(ModelOptionOperation):
def __init__(self, name, table_comment):
self.table_comment = table_comment
super().__init__(name)
def deconstruct(self):
kwargs = {
"name": self.name,
"table_comment": self.table_comment,
}
return (self.__class__... | AlterModelTableComment |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_timedelta_range.py | {
"start": 5562,
"end": 6537
} | class ____:
def test_timedelta_range_unit_inference_matching_unit(self, unit):
start = Timedelta(0).as_unit(unit)
end = Timedelta(days=1).as_unit(unit)
tdi = timedelta_range(start, end, freq="D")
assert tdi.unit == unit
def test_timedelta_range_unit_inference_mismatched_unit(se... | TestTimedeltaRangeUnitInference |
python | ansible__ansible | lib/ansible/module_utils/facts/system/systemd.py | {
"start": 897,
"end": 1633
} | class ____(BaseFactCollector):
name = "systemd"
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
systemctl_bin = module.get_bin_path("systemctl")
systemd_facts = {}
if systemctl_bin and ServiceMgrFactCollector.is_systemd_managed(module):
... | SystemdFactCollector |
python | huggingface__transformers | src/transformers/models/dbrx/modeling_dbrx.py | {
"start": 11872,
"end": 12962
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.hidden_size = config.hidden_size
self.ffn_hidden_size = config.ffn_hidden_size
self.moe_num_experts = config.moe_num_experts
self.w1 = nn.Parameter(torch.empty(self.moe_num_experts * self.ffn_hidden_s... | DbrxExpertGLU |
python | facebookresearch__faiss | tests/test_fast_scan_ivf.py | {
"start": 5040,
"end": 6392
} | class ____(unittest.TestCase):
""" Verify implem 1 (search from original invlists)
against IndexIVFPQ """
def do_test(self, by_residual, metric_type=faiss.METRIC_L2,
use_precomputed_table=0):
ds = datasets.SyntheticDataset(32, 2000, 5000, 1000)
index = faiss.index_factory(... | TestIVFImplem1 |
python | getsentry__sentry | src/sentry/ratelimits/sliding_windows.py | {
"start": 5455,
"end": 6969
} | class ____(SlidingWindowRateLimiter):
def __init__(self, **options: Any) -> None:
self.cluster_key = options.get("cluster", "default")
self._client: RedisCluster[str] | StrictRedis[str] | None = None
self._impl: RedisSlidingWindowRateLimiterImpl | None = None
super().__init__(**optio... | RedisSlidingWindowRateLimiter |
python | modin-project__modin | modin/core/storage_formats/pandas/parsers.py | {
"start": 24468,
"end": 29943
} | class ____(PandasParser):
@staticmethod
def _read_row_group_chunk(
f, row_group_start, row_group_end, columns, filters, engine, to_pandas_kwargs
): # noqa: GL08
if engine == "pyarrow":
if filters is not None:
import pyarrow.dataset as ds
from pyar... | PandasParquetParser |
python | google__pytype | pytype/utils.py | {
"start": 5844,
"end": 6161
} | class ____:
"""A decorator for storing function attributes.
Attributes:
lookup: maps functions to their attributes.
"""
def __init__(self):
self.lookup = {}
def __call__(self, value):
def decorate(f):
self.lookup[f.__name__] = value
return f
return decorate
| AnnotatingDecorator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_errorbars05.py | {
"start": 315,
"end": 1568
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_errorbars05.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with error bars."""
workbook = Wor... | TestCompareXLSXFiles |
python | crytic__slither | slither/printers/summary/contract.py | {
"start": 348,
"end": 3461
} | class ____(AbstractPrinter):
ARGUMENT = "contract-summary"
HELP = "Print a summary of the contracts"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#contract-summary"
def output(self, _filename: str) -> Output: # pylint: disable=too-many-locals
"""
_filename ... | ContractSummary |
python | django__django | tests/model_inheritance_regress/tests.py | {
"start": 747,
"end": 25525
} | class ____(TestCase):
def test_model_inheritance(self):
# Regression for #7350, #7202
# When you create a Parent object with a specific reference to an
# existent child instance, saving the Parent doesn't duplicate the
# child. This behavior is only activated during a raw save - it i... | ModelInheritanceTest |
python | pyinstaller__pyinstaller | bootloader/waflib/Task.py | {
"start": 27668,
"end": 28095
} | class ____(object):
def __init__(self, num):
self.num = num
self.locking = set()
self.waiting = set()
def is_locked(self):
return len(self.locking) >= self.num
def acquire(self, tsk):
if self.is_locked():
raise IndexError('Cannot lock more %r' % self.loc... | TaskSemaphore |
python | mozilla__bleach | bleach/_vendor/html5lib/html5parser.py | {
"start": 117091,
"end": 117164
} | class ____(Exception):
"""Error in parsed document"""
pass
| ParseError |
python | dask__distributed | distributed/lock.py | {
"start": 170,
"end": 3529
} | class ____(Semaphore):
"""Distributed Centralized Lock
.. warning::
This is using the ``distributed.Semaphore`` as a backend, which is
susceptible to lease overbooking. For the Lock this means that if a
lease is timing out, two or more instances could acquire the lock at the
sa... | Lock |
python | getsentry__sentry | src/sentry/api/endpoints/broadcast_details.py | {
"start": 798,
"end": 4382
} | class ____(Endpoint):
owner = ApiOwner.UNOWNED
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
permission_classes = (SentryIsAuthenticated,)
def _get_broadcast(self, request: Request, broadcast_id):
if request.access.has_permission("bro... | BroadcastDetailsEndpoint |
python | getsentry__sentry | src/sentry/monitors/migrations/0007_monitors_json_field.py | {
"start": 285,
"end": 1985
} | 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 | realpython__materials | python-guitar-synthesizer/source_code_final/src/tablature/models.py | {
"start": 700,
"end": 1066
} | class ____(BaseModel):
time_signature: constr(pattern=r"\d+/\d+")
notes: Optional[tuple[Note, ...]] = tuple()
@cached_property
def beats_per_measure(self) -> int:
return int(self.time_signature.split("/")[0])
@cached_property
def note_value(self) -> Fraction:
return Fraction(1,... | Measure |
python | python-attrs__attrs | tests/test_filters.py | {
"start": 184,
"end": 231
} | class ____:
a = attr.ib()
b = attr.ib()
| C |
python | python-attrs__attrs | typing-examples/baseline.py | {
"start": 1801,
"end": 2228
} | class ____:
a: int
b: str = attrs.field(on_setattr=attrs.setters.NO_OP)
c: bool = attrs.field(on_setattr=attrs.setters.frozen)
d: int = attrs.field(
on_setattr=[attrs.setters.convert, attrs.setters.validate]
)
e: bool = attrs.field(
on_setattr=attrs.setters.pipe(
attr... | ValidatedSetter2 |
python | doocs__leetcode | solution/0100-0199/0179.Largest Number/Solution.py | {
"start": 0,
"end": 238
} | class ____:
def largestNumber(self, nums: List[int]) -> str:
nums = [str(v) for v in nums]
nums.sort(key=cmp_to_key(lambda a, b: 1 if a + b < b + a else -1))
return "0" if nums[0] == "0" else "".join(nums)
| Solution |
python | chroma-core__chroma | chromadb/auth/__init__.py | {
"start": 1611,
"end": 5316
} | class ____(Component):
"""
ServerAuthenticationProvider is responsible for authenticating requests. If
a ServerAuthenticationProvider is configured, it will be called by the
server to authenticate requests. If no ServerAuthenticationProvider is
configured, all requests will be authenticated.
Th... | ServerAuthenticationProvider |
python | readthedocs__readthedocs.org | readthedocs/settings/test.py | {
"start": 94,
"end": 6936
} | class ____(CommunityBaseSettings):
"""Settings for testing environment (e.g. tox)"""
SLUMBER_API_HOST = "http://localhost:8000"
# A bunch of our tests check this value in a returned URL/Domain
PRODUCTION_DOMAIN = "readthedocs.org"
PUBLIC_DOMAIN = "readthedocs.io"
DONT_HIT_DB = False
# Di... | CommunityTestSettings |
python | langchain-ai__langchain | libs/partners/huggingface/langchain_huggingface/llms/huggingface_pipeline.py | {
"start": 895,
"end": 14788
} | class ____(BaseLLM):
"""HuggingFace Pipeline API.
To use, you should have the `transformers` python package installed.
Only supports `text-generation`, `text2text-generation`, `image-text-to-text`,
`summarization` and `translation` for now.
Example using from_model_id:
```python
... | HuggingFacePipeline |
python | mlflow__mlflow | dev/clint/src/clint/rules/use_walrus_operator.py | {
"start": 48,
"end": 3450
} | class ____(Rule):
def _message(self) -> str:
return (
"Use the walrus operator `:=` when a variable is assigned and only used "
"within an `if` block that tests its truthiness. "
"For example, replace `a = ...; if a: use_a(a)` with `if a := ...: use_a(a)`."
)
... | UseWalrusOperator |
python | ray-project__ray | python/ray/tune/tests/test_logger.py | {
"start": 1743,
"end": 10217
} | class ____(unittest.TestCase):
"""Test built-in loggers."""
def setUp(self):
self.test_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def testLegacyCSV(self):
config = {"a": 2, "b": 5, "c": {"c": {"D": 123}, "e": None}}
t ... | LoggerSuite |
python | getsentry__sentry | src/sentry/sentry_apps/services/hook/impl.py | {
"start": 591,
"end": 8752
} | class ____(HookService):
def update_webhook_and_events(
self,
*,
organization_id: int,
application_id: int | None,
webhook_url: str | None,
events: list[str],
) -> list[RpcServiceHook]:
with transaction.atomic(router.db_for_write(ServiceHook)):
... | DatabaseBackedHookService |
python | openai__openai-python | src/openai/resources/beta/realtime/sessions.py | {
"start": 21650,
"end": 21867
} | class ____:
def __init__(self, sessions: Sessions) -> None:
self._sessions = sessions
self.create = to_streamed_response_wrapper(
sessions.create,
)
| SessionsWithStreamingResponse |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 18985,
"end": 19497
} | class ____(BaseActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.PLUGIN
@property
def required_fields(self) -> list[str]:
# NotifyEventAction doesn't appear to have any required fields
# beyond the standard id and uuid
return []
@pr... | PluginActionTranslator |
python | PrefectHQ__prefect | tests/cli/transfer/test_blocks.py | {
"start": 540,
"end": 6673
} | class ____:
async def test_construct_creates_new_instance(
self, transfer_block_type_x: BlockType
):
"""Test that construct creates a new MigratableBlockType instance."""
migratable = await MigratableBlockType.construct(transfer_block_type_x)
assert isinstance(migratable, Migrat... | TestMigratableBlockType |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/base_env.py | {
"start": 19926,
"end": 22873
} | class ____(ABC):
@abstractmethod
def step(self) -> None:
"""
Signals the environment that it must move the simulation forward
by one step.
"""
@abstractmethod
def reset(self) -> None:
"""
Signals the environment that it must reset the simulation.
... | BaseEnv |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 20446,
"end": 20788
} | class ____(BaseModel):
bar: Bar[str] | None = None
# The `int | str` here differs from the previous test and requires the backport.
# At the same time, `PydanticRecursiveRef.__or__` means that the second `|` works normally,
# which actually triggered a bug in the backport that needed fixing.
bar2: i... | Foo |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/property_graph/sub_retrievers/cypher_template.py | {
"start": 468,
"end": 3029
} | class ____(BasePGRetriever):
"""
A Cypher retriever that fills in params for a cypher query using an LLM.
Args:
graph_store (PropertyGraphStore):
The graph store to retrieve data from.
output_cls (Type[BaseModel]):
The output class to use for the LLM.
Sho... | CypherTemplateRetriever |
python | sympy__sympy | sympy/polys/agca/modules.py | {
"start": 30214,
"end": 33190
} | class ____(SubModule):
"""
Submodule of a quotient module.
Equivalently, quotient module of a submodule.
Do not instantiate this, instead use the submodule or quotient_module
constructing methods:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_mo... | SubQuotientModule |
python | pytorch__pytorch | test/distributed/tensor/test_random_ops.py | {
"start": 1392,
"end": 12154
} | class ____(DTensorTestBase):
def _run_init_op(self, init_op, *args, **kwargs):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
input_size = (8, 4)
# NOTE: currently random initialization on gpu device has different
# behavior from other devices. Unify the test... | DistTensorRandomInitTest |
python | matplotlib__matplotlib | lib/matplotlib/offsetbox.py | {
"start": 38188,
"end": 40181
} | class ____(OffsetBox):
def __init__(self, arr, *,
zoom=1,
cmap=None,
norm=None,
interpolation=None,
origin=None,
filternorm=True,
filterrad=4.0,
resample=False,
d... | OffsetImage |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/final5.py | {
"start": 351,
"end": 383
} | class ____:
x: Final[int]
| ClassB |
python | anthropics__anthropic-sdk-python | src/anthropic/pagination.py | {
"start": 2276,
"end": 2997
} | class ____(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
data: List[_T]
has_more: Optional[bool] = None
next_page: Optional[str] = None
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data
@override
def has... | SyncTokenPage |
python | Pylons__pyramid | tests/test_config/test_init.py | {
"start": 46597,
"end": 47977
} | class ____(unittest.TestCase):
def _makeOne(self):
from pyramid.config import Configurator
return Configurator()
def test_factory_as_object(self):
config = self._makeOne()
def _fakeAction(
discriminator,
callable=None,
args=(),
k... | TestConfigurator__add_predicate |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_views.py | {
"start": 3257,
"end": 8934
} | class ____(GroupSearchViewAPITestCase):
endpoint = "sentry-api-0-organization-group-search-views"
method = "get"
def setUp(self) -> None:
self.user_1 = self.user
self.user_2 = self.create_user()
self.create_member(organization=self.organization, user=self.user_2)
# Create v... | OrganizationGroupSearchViewsGetTest |
python | keon__algorithms | tests/test_dp.py | {
"start": 1718,
"end": 1916
} | class ____(unittest.TestCase):
def test_edit_distance(self):
self.assertEqual(edit_distance('food', 'money'), 4)
self.assertEqual(edit_distance('horse', 'ros'), 3)
| TestEditDistance |
python | huggingface__transformers | src/transformers/models/cohere2_vision/modular_cohere2_vision.py | {
"start": 12833,
"end": 13737
} | class ____(ImagesKwargs, total=False):
"""
crop_to_patches (`bool`, *optional*, defaults to `False`):
Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the
`preprocess` method.
min_patches (`int`, *optional*, defaults to 1):
The minimum num... | Cohere2VisionFastImageProcessorKwargs |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-helicone/llama_index/llms/helicone/base.py | {
"start": 560,
"end": 4097
} | class ____(OpenAILike):
"""
Helicone (OpenAI-compatible) LLM.
Route OpenAI-compatible requests through Helicone for observability and control.
Authentication:
- Set your Helicone API key via the `api_key` parameter or `HELICONE_API_KEY`.
No OpenAI/third-party provider keys are required when ... | Helicone |
python | pydantic__pydantic | pydantic/_internal/_generate_schema.py | {
"start": 12361,
"end": 12438
} | class ____(Exception):
"""The core schema is invalid."""
| InvalidSchemaError |
python | getsentry__sentry | src/sentry/integrations/bitbucket_server/client.py | {
"start": 818,
"end": 3321
} | class ____(ApiClient):
"""
Client for making requests to Bitbucket Server to follow OAuth1 flow.
"""
request_token_url = "{}/plugins/servlet/oauth/request-token"
access_token_url = "{}/plugins/servlet/oauth/access-token"
authorize_url = "{}/plugins/servlet/oauth/authorize?oauth_token={}"
in... | BitbucketServerSetupClient |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 30593,
"end": 31029
} | class ____(FunctionArg):
date_format = "%Y-%m-%dT%H:%M:%S"
def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> str:
try:
datetime.strptime(value, self.date_format)
except ValueError:
raise InvalidFunctionArgument(
f"{valu... | DateArg |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/pull_request/organization_pullrequest_size_analysis_download.py | {
"start": 938,
"end": 3700
} | class ____(OrganizationEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self, request: Request, organization: Organization, artifact_id: str
) -> HttpResponseBase:
"""
Download size analysis results for a pr... | OrganizationPullRequestSizeAnalysisDownloadEndpoint |
python | Pylons__pyramid | src/pyramid/config/predicates.py | {
"start": 2704,
"end": 2932
} | class ____:
def __init__(self, package, registry, settings, maybe_dotted):
self.package = package
self.registry = registry
self.settings = settings
self.maybe_dotted = maybe_dotted
| PredicateInfo |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 203552,
"end": 203668
} | class ____(
_DateTimeTZMultiRangeTests, _MultiRangeTypeCompilation
):
pass
| DateTimeTZMultiRangeCompilationTest |
python | Textualize__textual | docs/examples/styles/keyline.py | {
"start": 121,
"end": 488
} | class ____(App):
CSS_PATH = "keyline.tcss"
def compose(self) -> ComposeResult:
with Grid():
yield Placeholder(id="foo")
yield Placeholder(id="bar")
yield Placeholder()
yield Placeholder(classes="hidden")
yield Placeholder(id="baz")
if __name... | KeylineApp |
python | google__pytype | pytype/pytd/visitors_test.py | {
"start": 40211,
"end": 40517
} | class ____(unittest.TestCase):
def test_any_replacement(self):
union = pytd.UnionType((pytd.NamedType("a"), pytd.NamedType("b")))
self.assertEqual(
union.Visit(visitors.ReplaceUnionsWithAny()), pytd.AnythingType()
)
if __name__ == "__main__":
unittest.main()
| ReplaceUnionsWithAnyTest |
python | pypa__hatch | tests/index/test_core.py | {
"start": 1447,
"end": 2659
} | class ____:
def test_default(self, mocker):
mock = mocker.patch("httpx._transports.default.create_ssl_context")
index = PackageIndex("https://foo.internal/a/b/")
_ = index.client
mock.assert_called_once_with(verify=True, cert=None, trust_env=True)
def test_ca_cert(self, mocker)... | TestTLS |
python | langchain-ai__langchain | libs/langchain/langchain_classic/memory/entity.py | {
"start": 2753,
"end": 6395
} | class ____(BaseEntityStore):
"""Upstash Redis backed Entity store.
Entities get a TTL of 1 day by default, and
that TTL is extended by 3 days every time the entity is read back.
"""
def __init__(
self,
session_id: str = "default",
url: str = "",
token: str = "",
... | UpstashRedisEntityStore |
python | kamyu104__LeetCode-Solutions | Python/remove-interval.py | {
"start": 29,
"end": 400
} | class ____(object):
def removeInterval(self, intervals, toBeRemoved):
"""
:type intervals: List[List[int]]
:type toBeRemoved: List[int]
:rtype: List[List[int]]
"""
A, B = toBeRemoved
return [[x, y] for a, b in intervals
for x, y in ((a, min(A, ... | Solution |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 34144,
"end": 34747
} | class ____(FieldValues):
"""
Valid and invalid values for `IPAddressField`
"""
valid_inputs = {
'2001:0db8:85a3:0042:1000:8a2e:0370:7334': '2001:db8:85a3:42:1000:8a2e:370:7334',
'2001:cdba:0:0:0:0:3257:9652': '2001:cdba::3257:9652',
'2001:cdba::3257:9652': '2001:cdba::3257:9652'
... | TestIPv6AddressField |
python | protocolbuffers__protobuf | python/google/protobuf/internal/well_known_types_test.py | {
"start": 1942,
"end": 26342
} | class ____(TimeUtilTestBase):
def testTimestampSerializeAndParse(self):
message = timestamp_pb2.Timestamp()
# Generated output should contain 3, 6, or 9 fractional digits.
message.seconds = 0
message.nanos = 0
self.CheckTimestampConversion(message, '1970-01-01T00:00:00Z')
message.nanos = 1000... | TimeUtilTest |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/secrets/key_vault.py | {
"start": 1347,
"end": 9051
} | class ____(BaseSecretsBackend, LoggingMixin):
"""
Retrieves Airflow Connections or Variables from Azure Key Vault secrets.
The Azure Key Vault can be configured as a secrets backend in the ``airflow.cfg``:
.. code-block:: ini
[secrets]
backend = airflow.providers.microsoft.azure.secre... | AzureKeyVaultBackend |
python | pydantic__pydantic | tests/benchmarks/test_attribute_access.py | {
"start": 116,
"end": 260
} | class ____(BaseModel):
model_config = ConfigDict(validate_assignment=True)
inner_field1: str
inner_field2: int
| InnerValidateAssignment |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/assets/model_assets.py | {
"start": 13810,
"end": 18139
} | class ____(dg.Config):
"""Configuration for model evaluation."""
batch_size: int = DEFAULT_BATCH_SIZE
accuracy_threshold: float = ACCURACY_THRESHOLD
# start_model_evaluation
@dg.asset(
description="Evaluate model performance on test set",
group_name="model_pipeline",
required_resource_keys={"... | ModelEvaluationConfig |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_divider.py | {
"start": 295,
"end": 9416
} | class ____:
"""
An Axes positioning class.
The divider is initialized with lists of horizontal and vertical sizes
(:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given
rectangular area will be divided.
The `new_locator` method then creates a callable object
that can be used as ... | Divider |
python | kamyu104__LeetCode-Solutions | Python/append-characters-to-string-to-make-subsequence.py | {
"start": 52,
"end": 414
} | class ____(object):
def appendCharacters(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
i = -1
for j, c in enumerate(t):
for i in xrange(i+1, len(s)):
if s[i] == c:
break
else:
... | Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 9204,
"end": 9694
} | class ____:
def setup(self):
N = 1_000_000
self.ser = Series(
np.random.randn(
N,
)
)
def time_to_numpy(self):
self.ser.to_numpy()
def time_to_numpy_double_copy(self):
self.ser.to_numpy(dtype="float64", copy=True)
def tim... | ToNumpy |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 4649,
"end": 5542
} | class ____(TorchDynamoException):
def __init__(
self,
msg: str,
*,
case_name: Optional[str] = None,
real_stack: None | StackSummary = None,
) -> None:
super().__init__(msg)
if not real_stack:
real_stack = torch._guards.TracingContext.extract_st... | Unsupported |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 7774,
"end": 7955
} | class ____(BadRequest):
"""Raised if something triggers a security error. This is otherwise
exactly like a bad request error.
.. versionadded:: 0.9
"""
| SecurityError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/utils.py | {
"start": 9118,
"end": 18567
} | class ____:
"""
The `RunAsThread` decorator is designed to run a generator function in a separate thread with a specified timeout.
This is particularly useful when dealing with functions that involve potentially time-consuming operations,
and you want to enforce a time limit for their execution.
"""... | RunAsThread |
python | pypa__setuptools | setuptools/build_meta.py | {
"start": 9899,
"end": 17425
} | class ____(_ConfigSettingsTranslator):
def _get_build_requires(
self, config_settings: _ConfigSettings, requirements: list[str]
):
sys.argv = [
*sys.argv[:1],
*self._global_args(config_settings),
"egg_info",
]
try:
with Distribution... | _BuildMetaBackend |
python | kamyu104__LeetCode-Solutions | Python/count-good-nodes-in-binary-tree.py | {
"start": 221,
"end": 749
} | class ____(object):
def goodNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = 0
stk = [(root, root.val)]
while stk:
node, curr_max = stk.pop()
if not node:
continue
curr_max = max(curr_max,... | Solution |
python | kamyu104__LeetCode-Solutions | Python/single-threaded-cpu.py | {
"start": 48,
"end": 741
} | class ____(object):
def getOrder(self, tasks):
"""
:type tasks: List[List[int]]
:rtype: List[int]
"""
idx = range(len(tasks))
idx.sort(key=lambda x: tasks[x][0])
result, min_heap = [], []
i, time = 0, tasks[idx[0]][0]
while i < len(idx) or min_... | Solution |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 63979,
"end": 64543
} | class ____(torch.nn.Module):
def __init__(self, qengine):
super().__init__()
self.qconfig = torch.ao.quantization.get_default_qconfig(qengine)
self.conv = torch.nn.ConvTranspose2d(3, 5, 3, bias=False).to(dtype=torch.float)
self.quant = QuantStub()
self.dequant = DeQuantStub()... | AnnotatedConvTransposeModel |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 24816,
"end": 24938
} | class ____(UncompressedTestMixin):
def get_server_compression_options(self):
return {}
| ServerOnlyCompressionTest |
python | walkccc__LeetCode | solutions/410. Split Array Largest Sum/410.py | {
"start": 0,
"end": 483
} | class ____:
def splitArray(self, nums: list[int], k: int) -> int:
prefix = list(itertools.accumulate(nums, initial=0))
@functools.lru_cache(None)
def dp(i: int, k: int) -> int:
"""
Returns the minimum of the maximum sum to split the first i numbers into
k groups.
"""
if k ==... | Solution |
python | oauthlib__oauthlib | tests/openid/connect/core/endpoints/test_userinfo_endpoint.py | {
"start": 311,
"end": 2522
} | class ____(TestCase):
def setUp(self):
self.claims = {
"sub": "john",
"fruit": "banana"
}
# Can't use MagicMock/wraps below.
# Triggers error when endpoint copies to self.bearer.request_validator
self.validator = RequestValidator()
self.validat... | UserInfoEndpointTest |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 3552,
"end": 4041
} | class ____(TypedDict):
type: "PipesMetadataType"
raw_value: PipesMetadataRawValue
# Infer the type from the raw value on the orchestration end
PIPES_METADATA_TYPE_INFER = "__infer__"
PipesMetadataType = Literal[
"__infer__",
"text",
"url",
"path",
"notebook",
"json",
"md",
"fl... | PipesMetadataValue |
python | sympy__sympy | sympy/stats/drv.py | {
"start": 9675,
"end": 11994
} | class ____(DiscretePSpace, SinglePSpace):
""" Discrete probability space over a single univariate variable """
is_real = True
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return SingleDiscreteDomain(self.symbol, self.set)
def sample(sel... | SingleDiscretePSpace |
python | hynek__structlog | src/structlog/typing.py | {
"start": 2033,
"end": 2730
} | class ____(Protocol):
"""
**Protocol:** A callable that transforms an `ExcInfo` into another
datastructure.
The result should be something that your renderer can work with, e.g., a
``str`` or a JSON-serializable ``dict``.
Used by `structlog.processors.format_exc_info()` and
`structlog.proc... | ExceptionTransformer |
python | tensorflow__tensorflow | tensorflow/python/module/module.py | {
"start": 1156,
"end": 17024
} | class ____(autotrackable.AutoTrackable):
"""Base neural network module class.
A module is a named container for `tf.Variable`s, other `tf.Module`s and
functions which apply to user input. For example a dense layer in a neural
network might be implemented as a `tf.Module`:
>>> class Dense(tf.Module):
... ... | Module |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 178949,
"end": 179795
} | class ____(TypedDict, total=False):
"""
:class:`altair.MultiPolygon` ``TypedDict`` wrapper.
Parameters
----------
coordinates
type
Specifies the type of GeoJSON object.
bbox
Bounding box of the coordinate range of the object's Geometries, Features, or
Feature Collec... | MultiPolygonKwds |
python | django__django | tests/sites_framework/models.py | {
"start": 413,
"end": 507
} | class ____(AbstractArticle):
site = models.ForeignKey(Site, models.CASCADE)
| ExclusiveArticle |
python | Netflix__metaflow | metaflow/plugins/metadata_providers/service.py | {
"start": 552,
"end": 609
} | class ____(object):
RUN = 1
TASK = 2
| HeartbeatTypes |
python | pandas-dev__pandas | asv_bench/benchmarks/inference.py | {
"start": 2280,
"end": 2677
} | class ____:
# maybe_convert_objects depends _almost_ exclusively on _libs, but
# does have some run-time imports from outside of _libs
def setup(self):
N = 10**5
data = list(range(N))
data[0] = NaT
data = np.array(data)
self.data = data
def time_maybe_convert_... | MaybeConvertObjects |
python | tornadoweb__tornado | tornado/web.py | {
"start": 79199,
"end": 80712
} | class ____(ReversibleRuleRouter):
"""Routing implementation used internally by `Application`.
Provides a binding between `Application` and `RequestHandler`.
This implementation extends `~.routing.ReversibleRuleRouter` in a couple of ways:
* it allows to use `RequestHandler` subclasses as `~.routing... | _ApplicationRouter |
python | falconry__falcon | tests/test_httpstatus.py | {
"start": 7037,
"end": 9171
} | class ____:
def test_data_is_set(self, body_client):
res = body_client.simulate_get('/status')
assert res.status == falcon.HTTP_745
assert res.status_code == 745
assert res.content == b''
def test_media_is_set(self, body_client):
res = body_client.simulate_post('/status'... | TestNoBodyWithStatus |
python | Netflix__metaflow | metaflow/plugins/datatools/s3/s3.py | {
"start": 3288,
"end": 3389
} | class ____(MetaflowException):
headline = "Insufficient disk space"
| MetaflowS3InsufficientDiskSpace |
python | doocs__leetcode | solution/1700-1799/1713.Minimum Operations to Make a Subsequence/Solution.py | {
"start": 0,
"end": 418
} | class ____:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
res = 0
while x... | BinaryIndexedTree |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 1395,
"end": 1496
} | class ____(SQLRole):
__slots__ = ()
_role_name = "Cacheable Core or ORM object"
| HasCacheKeyRole |
python | scikit-image__scikit-image | src/skimage/feature/util.py | {
"start": 127,
"end": 421
} | class ____:
def __init__(self):
self.keypoints_ = np.array([])
def detect(self, image):
"""Detect keypoints in image.
Parameters
----------
image : 2D array
Input image.
"""
raise NotImplementedError()
| FeatureDetector |
python | jazzband__django-oauth-toolkit | oauth2_provider/migrations/0005_auto_20211222_2352.py | {
"start": 109,
"end": 1665
} | class ____(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('oauth2_provider', '0004_auto_20200902_2022'),
]
operations = [
migrations.AlterField(
model_name='accesstoken',
name='user',
field=mod... | Migration |
python | pydantic__pydantic | pydantic/fields.py | {
"start": 3108,
"end": 3287
} | class ____(_FromFieldInfoInputs, total=False):
"""This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
default: Any
| _FieldInfoInputs |
python | matplotlib__matplotlib | lib/matplotlib/table.py | {
"start": 1017,
"end": 7800
} | class ____(Rectangle):
"""
A cell is a `.Rectangle` with some associated `.Text`.
As a user, you'll most likely not creates cells yourself. Instead, you
should use either the `~matplotlib.table.table` factory function or
`.Table.add_cell`.
"""
PAD = 0.1
"""Padding between text and rect... | Cell |
python | pyenv__pyenv | plugins/python-build/scripts/add_miniconda.py | {
"start": 2580,
"end": 2660
} | class ____(StrEnum):
ANACONDA = "Anaconda"
MINICONDA = "Miniconda"
| TFlavor |
python | ray-project__ray | python/ray/tune/execution/tune_controller.py | {
"start": 79008,
"end": 80319
} | class ____:
"""Wraps around TrialExecutor class, intercepts API calls and warns users
of restricted API access.
This is meant to facilitate restricting
the current API exposure of TrialExecutor by TrialScheduler.
"""
def __init__(
self,
trial_executor: "_FakeRayTrialExecutor",
... | _TrialExecutorWrapper |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 3104,
"end": 3863
} | class ____(Token):
""" Represents a module in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import Module
>>> from sympy import fcode
>>> print(fcode(Module('signallib', ['implicit none'], []), source_format='free'))
module signallib
implicit none
<BLANKLINE>
contain... | Module |
python | jackfrued__Python-100-Days | Day31-35/code/example17.py | {
"start": 331,
"end": 563
} | class ____():
"""自定义混入类"""
__slots__ = ()
def __setitem__(self, key, value):
if key in self:
raise KeyError(str(key) + ' already set')
return super().__setitem__(key, value)
| SetOnceMappingMixin |
python | ansible__ansible | test/units/config/test_manager.py | {
"start": 854,
"end": 1154
} | class ____(c.Mapping):
def __init__(self, values: c.Mapping) -> None:
self._values = values
def __getitem__(self, key, /):
return self._values[key]
def __len__(self):
return len(self._values)
def __iter__(self):
return iter(self._values)
| CustomMapping |
python | PyCQA__pylint | tests/functional/r/regression/regression_no_value_for_parameter.py | {
"start": 90,
"end": 1320
} | class ____(Unknown):
RENAMED_SECTIONS = {
'permissions': 'content'
}
def test(self):
self.RENAMED_SECTIONS.items() #@
def items(self, sectname, raw=True):
pass
def func(*, key=None):
return key
def varargs_good(*parts):
"""All good"""
return os.path.join(*part... | ConfigManager |
python | celery__celery | t/unit/backends/test_database.py | {
"start": 8461,
"end": 13394
} | class ____():
def setup_method(self):
self.uri = 'sqlite:///' + DB_PATH
self.app.conf.result_serializer = 'pickle'
self.app.conf.result_extended = True
@pytest.mark.parametrize(
'result_serializer, args, kwargs',
[
('pickle', (SomeClass(1), SomeClass(2)), {'f... | test_DatabaseBackend_result_extended |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 25164,
"end": 25313
} | class ____(RunInput):
"""Represents a parameter input to a task run."""
input_type: Literal["parameter"] = "parameter"
name: str
| Parameter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.