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
ansible__ansible
lib/ansible/module_utils/_internal/_ambient_context.py
{ "start": 339, "end": 2579 }
class ____: """ An abstract base context manager that, once entered, will be accessible via its `current` classmethod to any code in the same `contextvars` context (e.g. same thread/coroutine), until it is exited. """ __slots__ = ('_contextvar_token',) # DTFIX-FUTURE: subclasses need to be abl...
AmbientContextBase
python
automl__auto-sklearn
autosklearn/pipeline/components/data_preprocessing/feature_type_text.py
{ "start": 650, "end": 5315 }
class ____(BasePipeline): """This class implements a pipeline for data preprocessing of text features. It assumes that the data to be transformed is made only of text features. The steps of this pipeline are: 1 - Vectorize: Fits a *Vecotrizer object and apply this 2 - text feature reduction:...
TextPreprocessingPipeline
python
walkccc__LeetCode
solutions/1830. Minimum Number of Operations to Make String Sorted/1830.py
{ "start": 0, "end": 720 }
class ____: def makeStringSorted(self, s: str) -> int: MOD = 1_000_000_007 ans = 0 count = [0] * 26 @functools.lru_cache(None) def fact(i: int) -> int: return 1 if i <= 1 else i * fact(i - 1) % MOD @functools.lru_cache(None) def inv(i: int) -> int: return pow(i, MOD - 2, MOD)...
Solution
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 9394, "end": 9608 }
class ____(Where): """Logical OR of multiple where conditions""" conditions: List[Where] def to_dict(self) -> Dict[str, Any]: return {"$or": [c.to_dict() for c in self.conditions]} @dataclass
Or
python
encode__django-rest-framework
rest_framework/permissions.py
{ "start": 1658, "end": 2145 }
class ____: def __init__(self, op1, op2): self.op1 = op1 self.op2 = op2 def has_permission(self, request, view): return ( self.op1.has_permission(request, view) and self.op2.has_permission(request, view) ) def has_object_permission(self, request, vie...
AND
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 14842, "end": 15145 }
class ____(_GenerativeProvider): generative: Union[GenerativeSearches, _EnumLikeStr] = Field( default=GenerativeSearches.AWS, frozen=True, exclude=True ) region: str service: str model: Optional[str] endpoint: Optional[str] maxTokens: Optional[int]
_GenerativeAWSConfig
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 22149, "end": 22271 }
class ____(AbstractModelCallable1): name = models.CharField(max_length=15, unique=True)
OverrideModelNameUsingBaseModel1
python
sympy__sympy
sympy/functions/elementary/integers.py
{ "start": 9664, "end": 16094 }
class ____(RoundFunction): """ Ceiling is a univariate function which returns the smallest integer value not less than its argument. This implementation generalizes ceiling to complex numbers by taking the ceiling of the real and imaginary parts separately. Examples ======== >>> from s...
ceiling
python
cython__cython
Demos/benchmarks/chaos.py
{ "start": 4607, "end": 9903 }
class ____(object): @cython.locals(splines=list, thickness=cython.double, maxlength=cython.double, length=cython.double, curr=GVector, last=GVector, p=GVector, spl=Spline, t=cython.double, i=int) def __init__(self, splines, thickness=0.1): self.splines = splines self.thickness...
Chaosgame
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/report_check_status_response_builder.py
{ "start": 277, "end": 836 }
class ____(HttpResponseBuilder): @classmethod def check_status_response(cls) -> "ReportCheckStatusResponseBuilder": return cls(find_template("report_status_response", __file__), DictTemplatePath(), None) def with_record(self, record: RecordBuilder) -> HttpResponseBuilder: self._records = re...
ReportCheckStatusResponseBuilder
python
tensorflow__tensorflow
tensorflow/python/profiler/profiler_v2.py
{ "start": 6608, "end": 7426 }
class ____(object): """Context-manager profile API. Profiling will start when entering the scope, and stop and save the results to the logdir when exits the scope. Open TensorBoard profile tab to view results. Example usage: ```python with tf.profiler.experimental.Profile("/path/to/logdir"): # do some...
Profile
python
run-llama__llama_index
llama-index-core/tests/tools/tool_spec/test_base.py
{ "start": 296, "end": 354 }
class ____(BaseModel): arg1: str arg2: int
FooSchema
python
great-expectations__great_expectations
docs/sphinx_api_docs_source/public_api_report.py
{ "start": 18977, "end": 28813 }
class ____: """Bring together various parsing and filtering tools to build a filtered set of Definitions. Also adds the capability of filtering and including whole files or entities manually. """ DEFAULT_INCLUDES = public_api_includes.DEFAULT_INCLUDES DEFAULT_EXCLUDES = public_api_excludes.DEFAULT...
CodeReferenceFilter
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
{ "start": 57107, "end": 57342 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.String) groupName = graphene.NonNull(graphene.String) assetKeys = non_null_list(GrapheneAssetKey) class Meta: name = "AssetGroup"
GrapheneAssetGroup
python
scrapy__scrapy
tests/test_spidermiddleware_httperror.py
{ "start": 4654, "end": 6220 }
class ____: @pytest.fixture def mw(self) -> HttpErrorMiddleware: crawler = get_crawler(DefaultSpider, {"HTTPERROR_ALLOW_ALL": True}) crawler.spider = crawler._create_spider() return HttpErrorMiddleware.from_crawler(crawler) def test_process_spider_input( self, mw: Ht...
TestHttpErrorMiddlewareHandleAll
python
python-pillow__Pillow
src/PIL/ImageFile.py
{ "start": 23897, "end": 25976 }
class ____: fd: IO[bytes] | None def __init__(self, mode: str, *args: Any) -> None: self.im: Image.core.ImagingCore | None = None self.state = PyCodecState() self.fd = None self.mode = mode self.init(args) def init(self, args: tuple[Any, ...]) -> None: """ ...
PyCodec
python
getsentry__sentry
src/sentry/rules/processing/delayed_processing.py
{ "start": 4700, "end": 9003 }
class ____: """ LogConfig efficiently caches the results of features.has calls; these are project/org based, should be stable within our task, and caching them helps avoid generating excessive spans and saves a bit of time. """ # Cached value of features.has("projects:num-events-issue-debugging...
LogConfig
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/inprocess.py
{ "start": 1892, "end": 2240 }
class ____(QtKernelClientMixin, InProcessKernelClient): """ An in-process KernelManager with signals and slots. """ iopub_channel_class = Type(QtInProcessChannel) shell_channel_class = Type(QtInProcessChannel) stdin_channel_class = Type(QtInProcessChannel) hb_channel_class = Type(QtInProcessHBC...
QtInProcessKernelClient
python
milvus-io__pymilvus
tests/test_milvus_lite.py
{ "start": 316, "end": 2649 }
class ____: @pytest.mark.skip("Milvus Lite is now an optional dependency. This test will be fixed later.") def test_milvus_lite(self): with TemporaryDirectory(dir="./") as root: db_file = pathlib.Path(root).joinpath("test.db") client = MilvusClient(db_file.as_posix()) ...
TestMilvusLite
python
facebookresearch__faiss
tests/test_index_accuracy.py
{ "start": 18657, "end": 19682 }
class ____(unittest.TestCase): def test_flat_1d(self): rs = np.random.RandomState(123545) k = 10 xb = rs.uniform(size=(100, 1)).astype("float32") # make sure to test below and above xq = rs.uniform(size=(1000, 1)).astype("float32") * 1.1 - 0.05 ref = faiss.IndexFlatL...
TestFlat1D
python
google__pytype
pytype/tests/test_methods2.py
{ "start": 3457, "end": 5422 }
class ____(test_base.BaseTest): """Test python3-specific method features.""" def test_init_subclass_classmethod(self): """__init_subclass__ should be promoted to a classmethod.""" self.Check(""" from typing import Type _REGISTERED_BUILDERS = {} class A(): def __init_subclass__(...
TestMethodsPy3
python
faif__python-patterns
patterns/behavioral/mediator.py
{ "start": 335, "end": 487 }
class ____: """Mediator class""" def display_message(self, user: User, message: str) -> None: return f"[{user} says]: {message}"
ChatRoom
python
facelessuser__pymdown-extensions
pymdownx/blocks/definition.py
{ "start": 1407, "end": 1754 }
class ____(BlocksExtension): """Definition Blocks Extension.""" def extendMarkdownBlocks(self, md, block_mgr): """Extend Markdown blocks.""" block_mgr.register(Definition, self.getConfigs()) def makeExtension(*args, **kwargs): """Return extension.""" return DefinitionExtension(*args...
DefinitionExtension
python
getsentry__sentry
src/sentry/models/organizationonboardingtask.py
{ "start": 905, "end": 1315 }
class ____(enum.IntEnum): FIRST_PROJECT = 1 FIRST_EVENT = 2 INVITE_MEMBER = 3 SECOND_PLATFORM = 4 RELEASE_TRACKING = 6 SOURCEMAPS = 7 ALERT_RULE = 10 FIRST_TRANSACTION = 11 SESSION_REPLAY = 14 REAL_TIME_NOTIFICATIONS = 15 LINK_SENTRY_TO_SOURCE_CODE = 16 @classmethod ...
OnboardingTask
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
{ "start": 1894, "end": 2112 }
class ____: @pytest.fixture(autouse=True) def mock_conn(self, monkeypatch): self.client = boto3.client("bedrock") monkeypatch.setattr(BedrockHook, "conn", self.client)
TestBedrockCustomWaitersBase
python
pypa__pipenv
pipenv/patched/pip/_internal/utils/temp_dir.py
{ "start": 2137, "end": 6612 }
class ____: """Helper class that owns and cleans up a temporary directory. This class can be used as a context manager or as an OO representation of a temporary directory. Attributes: path Location to the created temporary directory delete Whether the directory ...
TempDirectory
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/92_qual_class_in_class.py
{ "start": 0, "end": 40 }
class ____: class Foo: pass
Bar
python
readthedocs__readthedocs.org
readthedocs/organizations/filters.py
{ "start": 1470, "end": 3088 }
class ____(OrderingFilter): """Organization list sort ordering django_filters filter.""" SORT_NAME = "name" SORT_CREATE_DATE = "pub_date" def __init__(self, *args, **kwargs): # The default filtering operation will be `name`, so we omit it # from choices to avoid showing it on the list ...
OrganizationSortOrderingFilter
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 39102, "end": 40733 }
class ____(system_info): #variables to override section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw3', 'libs':['fftw3'], 'includes':['fftw3.h'], 'macros':[('SCIPY_FFTW3_H', None)]}, ...
fftw_info
python
Pylons__pyramid
tests/test_response.py
{ "start": 6010, "end": 6352 }
class ____(unittest.TestCase): def test_get_factory(self): from pyramid.registry import Registry from pyramid.response import Response, _get_response_factory registry = Registry() response = _get_response_factory(registry)(None) self.assertTrue(isinstance(response, Response)...
TestGetResponseFactory
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 1392, "end": 1470 }
class ____(TypedDict): role: str scope: NotRequired[str]
PermissionRoles
python
Netflix__metaflow
metaflow/plugins/env_escape/configurations/test_lib_impl/test_lib.py
{ "start": 148, "end": 415 }
class ____(MyBaseException): def __init__(self, *args): super().__init__(*args) def method_on_exception(self): return "method_on_exception" def __str__(self): return "ExceptionAndClass Str: %s" % super().__str__()
ExceptionAndClass
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/bigquery_to_postgres.py
{ "start": 1445, "end": 5242 }
class ____(BigQueryToSqlBaseOperator): """ Fetch data from a BigQuery table (alternatively fetch selected columns) and insert into PostgreSQL table. Due to constraints of the PostgreSQL's ON CONFLICT clause both `selected_fields` and `replace_index` parameters need to be specified when using the operat...
BigQueryToPostgresOperator
python
getsentry__sentry
tests/sentry/integrations/github/test_issues.py
{ "start": 3680, "end": 26450 }
class ____(TestCase, PerformanceIssueTestCase, IntegratedApiTestCase): @cached_property def request(self): return RequestFactory() def setUp(self) -> None: self.user = self.create_user() self.organization = self.create_organization(owner=self.user) self.integration = self.cr...
GitHubIssueBasicTest
python
pydata__xarray
xarray/namedarray/_typing.py
{ "start": 5833, "end": 6083 }
class ____( _array[_ShapeType_co, _DType_co], Protocol[_ShapeType_co, _DType_co] ): """ Minimal chunked duck array. Corresponds to np.ndarray. """ @property def chunks(self) -> _Chunks: ... @runtime_checkable
_chunkedarray
python
getsentry__sentry
src/sentry/api/endpoints/relay/project_ids.py
{ "start": 431, "end": 1509 }
class ____(Endpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } authentication_classes = (RelayAuthentication,) permission_classes = (RelayPermission,) owner = ApiOwner.OWNERS_INGEST def post(self, request: Request) -> Response: relay = request.relay assert ...
RelayProjectIdsEndpoint
python
kamyu104__LeetCode-Solutions
Python/palindrome-permutation-ii.py
{ "start": 1164, "end": 1633 }
class ____(object): def generatePalindromes(self, s): """ :type s: str :rtype: List[str] """ cnt = collections.Counter(s) mid = tuple(k for k, v in cnt.iteritems() if v % 2) chars = ''.join(k * (v / 2) for k, v in cnt.iteritems()) return [''.join(half_...
Solution2
python
imageio__imageio
imageio/plugins/swf.py
{ "start": 1892, "end": 11755 }
class ____(Format): """See :mod:`imageio.plugins.swf`""" def _can_read(self, request): tmp = request.firstbytes[0:3].decode("ascii", "ignore") if tmp in ("FWS", "CWS"): return True def _can_write(self, request): if request.extension in self.extensions: retur...
SWFFormat
python
huggingface__transformers
tests/models/pop2piano/test_modeling_pop2piano.py
{ "start": 25264, "end": 29613 }
class ____(unittest.TestCase): @slow def test_mel_conditioner_integration(self): composer = "composer1" model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") input_embeds = torch.ones([10, 100, 512]) composer_value = model.generation_config.composer_t...
Pop2PianoModelIntegrationTests
python
gevent__gevent
src/gevent/tests/test__makefile_ref.py
{ "start": 19065, "end": 19536 }
class ____(Closing): def __init__(self, task, listener, *other_sockets): super(CleaningUp, self).__init__(listener, *other_sockets) self.task = task self.listener = listener def __enter__(self): return self.accept(self.listener) def __exit__(self, t, v, tb): try: ...
CleaningUp
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 23914, "end": 24200 }
class ____(PrefectBaseModel): """Filter by `BlockDocument.is_anonymous`.""" eq_: Optional[bool] = Field( default=None, description=( "Filter block documents for only those that are or are not anonymous." ), )
BlockDocumentFilterIsAnonymous
python
jazzband__prettytable
tests/test_prettytable.py
{ "start": 45248, "end": 45562 }
class ____: def test_default_repr(self, row_prettytable: PrettyTable) -> None: assert row_prettytable.__str__() == row_prettytable.__repr__() def test_jupyter_repr(self, row_prettytable: PrettyTable) -> None: assert row_prettytable._repr_html_() == row_prettytable.get_html_string()
TestRepr
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 5198, "end": 5695 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.layer1 = BasicModule() self.layer2 = BasicModule() self.scale = torch.randn(1, 10) @classmethod def call_and_scale(cls, scale, mod, x): x = mod(x) return x * scale def forwa...
ModuleClassMethodCall
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/bijector_test.py
{ "start": 7468, "end": 7946 }
class ____(bijector.Bijector): """Only used for jacobian calculations.""" def __init__(self, forward_min_event_ndims=0): super().__init__( validate_args=False, is_constant_jacobian=True, forward_min_event_ndims=forward_min_event_ndims, name="c") def _inverse_log_det_jacobian(...
ConstantJacobian
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/step.py
{ "start": 3033, "end": 6529 }
class ____( # pyright: ignore[reportIncompatibleVariableOverride] NamedTuple( "_ExecutionStep", [ ("handle", Union[StepHandle, ResolvedFromDynamicStepHandle]), ("job_name", str), ("step_input_dict", Mapping[str, StepInput]), ("step_output_dict", Mappi...
ExecutionStep
python
getsentry__sentry
src/sentry/discover/translation/mep_to_eap.py
{ "start": 8725, "end": 17939 }
class ____(NodeVisitor): def __init__(self): self.dropped_fields = [] super().__init__() def visit_field_value(self, node, children): if node.text in COLUMNS_TO_DROP: self.dropped_fields.append(node.text) return node.text return column_switcheroo(node.tex...
ArithmeticTranslationVisitor
python
matplotlib__matplotlib
lib/matplotlib/colorbar.py
{ "start": 5106, "end": 5887 }
class ____(mspines.Spine): def __init__(self, axes): self._ax = axes super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2)))) mpatches.Patch.set_transform(self, axes.transAxes) def get_window_extent(self, renderer=None): # This Spine has no Axis associated with it, and d...
_ColorbarSpine
python
ray-project__ray
python/ray/data/_internal/execution/operators/map_transformer.py
{ "start": 12349, "end": 14161 }
class ____(MapTransformFn): """A block-to-block MapTransformFn.""" def __init__( self, block_fn: MapTransformCallable[Block, Block], *, is_udf: bool = False, disable_block_shaping: bool = False, output_block_size_option: Optional[OutputBlockSizeOption] = None, ...
BlockMapTransformFn
python
jupyterlab__jupyterlab
jupyterlab/handlers/build_handler.py
{ "start": 530, "end": 4095 }
class ____: building = False executor = ThreadPoolExecutor(max_workers=5) canceled = False _canceling = False _kill_event = None _future = None def __init__(self, core_mode, app_options=None): app_options = _ensure_options(app_options) self.log = app_options.logger s...
Builder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F842.py
{ "start": 76, "end": 125 }
class ____: name: str = "Bob" age: int = 18
B
python
arrow-py__arrow
tests/test_locales.py
{ "start": 69153, "end": 69622 }
class ____: def test_format_timeframe(self): assert self.locale._format_timeframe("hours", 2) == "2 horoj" assert self.locale._format_timeframe("hour", 0) == "un horo" assert self.locale._format_timeframe("hours", -2) == "2 horoj" assert self.locale._format_timeframe("now", 0) == "nu...
TestEsperantoLocale
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_dataspec.py
{ "start": 2666, "end": 4036 }
class ____: def test_default_value(self) -> None: class Foo(HasProps): x = bcpd.AngleSpec(default=14) a = Foo() assert a.x == 14 assert a.x_units == 'rad' def test_setting_dict_sets_units(self) -> None: class Foo(HasProps): x = bcpd.AngleSpec(de...
Test_AngleSpec
python
pandas-dev__pandas
pandas/core/groupby/ops.py
{ "start": 40846, "end": 41195 }
class ____(DataSplitter): def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame: # Fastpath equivalent to: # return sdata.iloc[slice_obj] mgr = sdata._mgr.get_slice(slice_obj, axis=1) df = sdata._constructor_from_mgr(mgr, axes=mgr.axes) return df.__finalize__(sdata...
FrameSplitter
python
doocs__leetcode
solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/Solution.py
{ "start": 0, "end": 461 }
class ____: def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: n = len(nums) f = [[-inf] * (target + 1) for _ in range(n + 1)] f[0][0] = 0 for i, x in enumerate(nums, 1): for j in range(target + 1): f[i][j] = f[i - 1][j] ...
Solution
python
lazyprogrammer__machine_learning_examples
ab_testing/ucb1.py
{ "start": 630, "end": 2198 }
class ____: def __init__(self, p): # p: the win rate self.p = p self.p_estimate = 0. self.N = 0. # num samples collected so far def pull(self): # draw a 1 with probability p return np.random.random() < self.p def update(self, x): self.N += 1. self.p_estimate = ((self.N - 1)*self....
Bandit
python
pytorch__pytorch
torch/distributed/_symmetric_memory/__init__.py
{ "start": 57158, "end": 70707 }
class ____(_Work): def __init__(self) -> None: super().__init__() self.event = torch.cuda.Event() self.event.record() def wait(self, timeout: timedelta = timedelta(seconds=0)) -> bool: self.event.wait() return True """ NOTE [low-contention collectives] When a collectiv...
Work
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/overrides.py
{ "start": 4017, "end": 4207 }
class ____(BaseWithDeclaration): def return_source(self): pass def test_overrides_with_declaration(b: BaseWithDeclaration): _test_sink(b.return_source())
DerivedWithDeclaration
python
pytorch__pytorch
test/distributed/optim/test_named_optimizer.py
{ "start": 1153, "end": 15000 }
class ____(unittest.TestCase): def _compare_state_dict_group(self, group, named_group, assert_equal=True): for key, val in group.items(): if key != "params": self.assertTrue( key in named_group, f"{key} not in named optimizer state dict" ) ...
NamedOptimizerTest
python
Textualize__textual
src/textual/events.py
{ "start": 1943, "end": 2210 }
class ____(Event, bubble=False): """Sent when there are no more items in the message queue. This is a pseudo-event in that it is created by the Textual system and doesn't go through the usual message queue. - [ ] Bubbles - [ ] Verbose """
Idle
python
apache__airflow
providers/google/tests/unit/google/cloud/utils/gcp_authenticator.py
{ "start": 2534, "end": 8694 }
class ____(CommandExecutor): """ Initialises the authenticator. :param gcp_key: name of the key to use for authentication (see GCP_*_KEY values) :param project_extra: optional extra project parameter passed to google cloud connection """ original_account: str | None = None def ...
GcpAuthenticator
python
django-haystack__django-haystack
test_haystack/test_templatetags.py
{ "start": 800, "end": 4922 }
class ____(TemplateTagTestCase): def setUp(self): super().setUp() self.sample_entry = """ Registering indexes in Haystack is very similar to registering models and ModelAdmin classes in the Django admin site. If you want to override the default indexing behavior for your model you can specify your o...
HighlightTestCase
python
huggingface__transformers
src/transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py
{ "start": 4833, "end": 5919 }
class ____(DepthAnythingDepthEstimationHead): def forward(self, hidden_states: list[torch.Tensor], patch_height: int, patch_width: int) -> torch.Tensor: hidden_states = hidden_states[-1] predicted_depth = self.conv1(hidden_states) target_height = torch_int(patch_height * self.patch_size) ...
PromptDepthAnythingDepthEstimationHead
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 125358, "end": 125798 }
class ____(str, Enum): """ Defines source of truth for snapshot recovery: `NoSync` means - restore snapshot without *any* additional synchronization. `Snapshot` means - prefer snapshot data over the current state. `Replica` means - prefer existing data over the snapshot. """ def __str__(self) -> str: ...
SnapshotPriority
python
pytorch__pytorch
torch/fx/experimental/symbolic_shapes.py
{ "start": 105022, "end": 105122 }
class ____(_ShapeGuardsHelper): source_to_symbol: dict[Source, sympy.Symbol]
_CppShapeGuardsHelper
python
kamyu104__LeetCode-Solutions
Python/power-grid-maintenance.py
{ "start": 87, "end": 1424 }
class ____(object): def processQueries(self, c, connections, queries): """ :type c: int :type connections: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ def iter_dfs(i): stk = [i] while stk: u = st...
Solution
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 4626, "end": 5853 }
class ____(Projection): """Base class for all Pix2Sky projections.""" n_inputs = 2 n_outputs = 2 _input_units_strict = True _input_units_allow_dimensionless = True def __new__(cls, *args, **kwargs): long_name = cls.name.split("_")[1] cls.prj_code = _PROJ_NAME_CODE_MAP[long_nam...
Pix2SkyProjection
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
{ "start": 20171, "end": 23913 }
class ____(TestTaskInstanceEndpoint): def test_should_respond_200_mapped_task_instance_with_rtif(self, test_client, session): """Verify we don't duplicate rows through join to RTIF""" tis = self.create_task_instances(session) old_ti = tis[0] for idx in (1, 2): ti = TaskIn...
TestGetMappedTaskInstance
python
PrefectHQ__prefect
tests/client/test_prefect_client.py
{ "start": 99385, "end": 105633 }
class ____: @pytest.fixture async def deployment(self, prefect_client): foo = flow(lambda: None, name="foo") flow_id = await prefect_client.create_flow(foo) schedule = IntervalSchedule( interval=timedelta(days=1), anchor_date=DateTime(2020, 1, 1) ) deployment...
TestPrefectClientDeploymentSchedules
python
kubernetes-client__python
kubernetes/client/models/v1beta2_network_device_data.py
{ "start": 383, "end": 6504 }
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...
V1beta2NetworkDeviceData
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 110231, "end": 111372 }
class ____(nn.Module): def __init__( self, d_model, nhead, dropout=0.1, layer_norm_eps=1e-05, ): super().__init__() self.self_attn = OneFormerTextMapperAttention(d_model, nhead, proj_drop=dropout) self.cross_attn = OneFormerTextMapperAttention(d_mo...
OneFormerTextTransformerDecoderLayer
python
getsentry__sentry
src/sentry/eventtypes/security.py
{ "start": 1142, "end": 1471 }
class ____(SecurityEvent): key = "csp" def extract_metadata(self, data): metadata = SecurityEvent.extract_metadata(self, data) metadata["uri"] = csp.normalize_value(data["csp"].get("blocked_uri") or "") metadata["directive"] = data["csp"].get("effective_directive") return metada...
CspEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 346014, "end": 347007 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateEnterpriseProfile""" __schema__ = github_schema __field_names__ = ("enterprise_id", "name", "description", "website_url", "location", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enter...
UpdateEnterpriseProfileInput
python
pandas-dev__pandas
pandas/tests/indexing/test_indexing.py
{ "start": 655, "end": 20753 }
class ____: """pure get/set item & fancy indexing""" def test_setitem_ndarray_1d(self): # GH5508 # len of indexer vs length of the 1d ndarray df = DataFrame(index=Index(np.arange(1, 11), dtype=np.int64)) df["foo"] = np.zeros(10, dtype=np.float64) df["bar"] = np.zeros(10...
TestFancy
python
ray-project__ray
rllib/models/preprocessors.py
{ "start": 12332, "end": 16616 }
class ____(Preprocessor): """Pads and batches the variable-length list value.""" @override(Preprocessor) def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: assert isinstance(self._obs_space, Repeated) child_space = obs_space.child_space self.child_preprocessor ...
RepeatedValuesPreprocessor
python
plotly__plotly.py
plotly/graph_objs/volume/_colorbar.py
{ "start": 233, "end": 61447 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "volume" _path_str = "volume.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "...
ColorBar
python
sympy__sympy
sympy/tensor/array/sparse_ndim_array.py
{ "start": 3073, "end": 4221 }
class ____(SparseNDimArray, ImmutableNDimArray): # type: ignore def __new__(cls, iterable=None, shape=None, **kwargs): shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) shape = Tuple(*map(_sympify, shape)) cls._check_special_bounds(flat_list, shape) l...
ImmutableSparseNDimArray
python
getsentry__sentry
src/sentry/api/serializers/models/userrollback.py
{ "start": 254, "end": 427 }
class ____(TypedDict): organization: RollbackOrganizationSerializerResponse user: RollbackUserSerializerResponse data: dict # JSON Blob
RollbackSerializerResponse
python
google__jax
jax/_src/pallas/mosaic/sc_primitives.py
{ "start": 15166, "end": 28851 }
class ____(jax_core.Effect): pass effects.control_flow_allowed_effects.add_type(MemoryEffect) effects.lowerable_effects.add_type(MemoryEffect) _memory_effect = MemoryEffect() barrier_p = jax_core.Primitive("barrier") barrier_p.multiple_results = True @barrier_p.def_effectful_abstract_eval def _barrier_abstract_ev...
MemoryEffect
python
django__django
django/db/models/lookups.py
{ "start": 22597, "end": 22713 }
class ____(PatternLookup): lookup_name = "startswith" param_pattern = "%s%%" @Field.register_lookup
StartsWith
python
google__jax
jax/_src/interpreters/mlir.py
{ "start": 25829, "end": 26330 }
class ____: traceback_to_location_cache: Any # jax_mlir_ext.TracebackToLocationCache canonical_name_cache: dict[str, str] def __init__(self): frame_limit = config.traceback_in_locations_limit.value frame_limit = frame_limit if frame_limit >= 0 else 1000 self.traceback_to_location_cache = jax_mlir_ex...
TracebackCaches
python
facebook__pyre-check
tools/upgrade/commands/targets_to_configuration.py
{ "start": 898, "end": 1930 }
class ____(libcst.CSTTransformer): @override def leave_Call( self, original_node: libcst.Call, updated_node: libcst.Call ) -> libcst.Call: check_types = False uses_pyre = True updated_fields = [] for field in original_node.args: name = field.keyword ...
TargetPyreRemover
python
google__jax
tests/error_check_test.py
{ "start": 1201, "end": 11591 }
class ____(jtu.JaxTestCase): @parameterized.product(jit=[True, False]) def test_error_check(self, jit): def f(x): error_check.set_error_if(x <= 0, "x must be greater than 0") return x + 1 if jit: f = jax.jit(f) x = jnp.full((4,), -1, dtype=jnp.int32) f(x) with self.assertRai...
ErrorCheckTests
python
ray-project__ray
python/ray/data/preprocessors/scaler.py
{ "start": 564, "end": 5039 }
class ____(SerializablePreprocessorBase): r"""Translate and scale each column by its mean and standard deviation, respectively. The general formula is given by .. math:: x' = \frac{x - \bar{x}}{s} where :math:`x` is the column, :math:`x'` is the transformed column, :math:`\bar{x}` is...
StandardScaler
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink46.py
{ "start": 306, "end": 1401 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink46.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with hyperlinks.""" workbook = Wor...
TestCompareXLSXFiles
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_statistical_events.py
{ "start": 1618, "end": 7841 }
class ____: def __eq__(self, other): return True def __ne__(self, other): return False def __hash__(self): return 0 def __str__(self): seen.append(self) global counter counter += 1 return f"COUNTER {counter}" def test_formats_are_evaluated_onl...
Foo
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 117870, "end": 118458 }
class ____(Operation): def call(self, x): return backend.numpy.imag(x) def compute_output_spec(self, x): sparse = getattr(x, "sparse", False) return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse) @keras_export(["keras.ops.imag", "keras.ops.numpy.imag"]) def imag(x): """Return ...
Imag
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 5576, "end": 5681 }
class ____(MetafieldShopifySubstream): parent_stream_class = SmartCollections
MetafieldSmartCollections
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/compute.py
{ "start": 1884, "end": 2171 }
class ____(BaseGoogleLink): """Helper class for constructing Compute Instance Group Manager details Link.""" name = "Compute Instance Group Manager" key = "compute_instance_group_manager_details" format_str = COMPUTE_GROUP_MANAGER_LINK
ComputeInstanceGroupManagerDetailsLink
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/override1.py
{ "start": 534, "end": 1551 }
class ____(ClassA, ClassB): @property @override # This should generate an error because prop_a doesn't # override anything in its base class. def prop_a(self) -> int: raise NotImplementedError @override def method1(self) -> None: pass def method2(self) -> None: ...
ClassC
python
FactoryBoy__factory_boy
factory/faker.py
{ "start": 341, "end": 2006 }
class ____(declarations.BaseDeclaration): """Wrapper for 'faker' values. Args: provider (str): the name of the Faker field locale (str): the locale to use for the faker All other kwargs will be passed to the underlying provider (e.g ``factory.Faker('ean', length=10)`` c...
Faker
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-construct/test_flow_except.py
{ "start": 5333, "end": 6918 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) raise Exception @pytest.mark.repeat(10) @pytest.mark.timeout(10) @pytest.mark.parametrize('protocol', ['websocket', 'grpc', 'http']) def test_flow_startup_exception_not_hanging2(protocol): f = Flow(pro...
ExceptionExecutor2
python
matplotlib__matplotlib
lib/matplotlib/widgets.py
{ "start": 113262, "end": 113516 }
class ____(enum.Enum): ROTATE = enum.auto() MOVE = enum.auto() RESIZE = enum.auto() CREATE = enum.auto() @_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace( '__ARTIST_NAME__', 'rectangle'))
_RectangleSelectorAction
python
django__django
tests/settings_tests/tests.py
{ "start": 18191, "end": 22187 }
class ____(SimpleTestCase): """ The override_settings context manager restore settings if one of the receivers of "setting_changed" signal fails. Check the three cases of receiver failure detailed in receiver(). In each case, ALL receivers are called when exiting the context manager. """ de...
OverrideSettingsIsolationOnExceptionTests
python
ansible__ansible
test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/action/win_reboot.py
{ "start": 717, "end": 3875 }
class ____(ActionBase): TRANSFERS_FILES = False _VALID_ARGS = frozenset(( 'boot_time_command', 'connect_timeout', 'connect_timeout_sec', 'msg', 'post_reboot_delay', 'post_reboot_delay_sec', 'pre_reboot_delay', 'pre_reboot_delay_sec', 'reboo...
ActionModule
python
pytorch__pytorch
torch/_inductor/fx_passes/group_batch_fusion.py
{ "start": 50483, "end": 59332 }
class ____: def __init__(self, param=None) -> None: if param: self.rep = OrderedDict(dict.fromkeys(param)) else: self.rep = OrderedDict() def __contains__(self, o) -> bool: return o in self.rep def __len__(self) -> int: return self.rep.__len__() ...
_OrderedSet
python
dask__distributed
distributed/scheduler.py
{ "start": 336882, "end": 338096 }
class ____(Exception): def __init__( self, task: Key, host_restrictions: set[str], worker_restrictions: set[str], resource_restrictions: dict[str, float], timeout: float, ): super().__init__( task, host_restrictions, worker_restrictions, resour...
NoValidWorkerError
python
huggingface__transformers
src/transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py
{ "start": 2004, "end": 4368 }
class ____(LlamaAttention): def __init__(self, config: HunYuanDenseV1Config, layer_idx: int): super().__init__(config, layer_idx) self.query_layernorm = HunYuanDenseV1RMSNorm(self.head_dim, eps=config.rms_norm_eps) self.key_layernorm = HunYuanDenseV1RMSNorm(self.head_dim, eps=config.rms_norm...
HunYuanDenseV1Attention
python
django__django
tests/backends/base/test_schema.py
{ "start": 138, "end": 672 }
class ____(SimpleTestCase): def test_effective_default_callable(self): """ SchemaEditor.effective_default() shouldn't call callable defaults. """ class MyStr(str): def __call__(self): return self class MyCharField(models.CharField): d...
SchemaEditorTests
python
pypa__warehouse
warehouse/email/services.py
{ "start": 4589, "end": 4969 }
class ____(SMTPEmailSender): def send(self, recipient, message): super().send(recipient=recipient, message=message) print( f"""Email sent Subject: {message.subject} From: {self.sender if message.sender is None else message.sender} To: {recipient} HTML: Visualize at http://localhost:1080 ...
ConsoleAndSMTPEmailSender
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 8110, "end": 8617 }
class ____: def __init__(self, realtime: AsyncRealtime) -> None: self._realtime = realtime @cached_property def sessions(self) -> AsyncSessionsWithStreamingResponse: return AsyncSessionsWithStreamingResponse(self._realtime.sessions) @cached_property def transcription_sessions(self)...
AsyncRealtimeWithStreamingResponse