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
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/retrieval/evaluator.py
{ "start": 506, "end": 1834 }
class ____(BaseRetrievalEvaluator): """ Retriever evaluator. This module will evaluate a retriever using a set of metrics. Args: metrics (List[BaseRetrievalMetric]): Sequence of metrics to evaluate retriever: Retriever to evaluate. node_postprocessors (Optional[List[BaseNodePos...
RetrieverEvaluator
python
ansible__ansible
test/units/plugins/filter/test_mathstuff.py
{ "start": 3893, "end": 4474 }
class ____: def test_root_non_number(self): with pytest.raises(AnsibleError, match="root\\(\\) can only be used on numbers: could not convert string to float: 'a'"): ms.inversepower(10, 'a') with pytest.raises(AnsibleError, match="root\\(\\) can only be used on numbers: must be real num...
TestInversePower
python
realpython__materials
emacs-the-best-python-editor/PyEval/expr_test.py
{ "start": 115, "end": 4153 }
class ____(unittest.TestCase): """ Validation of Expression and Operator classes. No setup function is needed """ def test_positive_operand_expression(self): """ Tests a single positive operand expression """ expr = Expression("53") self.assertEqual("53 ", ex...
TestPyEval
python
pytorch__pytorch
torch/_inductor/test_operators.py
{ "start": 450, "end": 861 }
class ____(Function): @staticmethod # pyrefly: ignore [bad-override] def forward(ctx: object, x: Tensor) -> Tensor: return torch.ops._inductor_test.realize(x) @staticmethod # types need to stay consistent with _SingleLevelFunction def backward(ctx: Any, *grad_output: Any) -> Any: ...
Realize
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/dynamic_args/test_multiple_eval_dataloaders.py
{ "start": 1005, "end": 2222 }
class ____(Dataset): def __init__(self, size, length): self.len = length self.data = torch.randn(length, size) def __getitem__(self, index): return torch.ones(1) def __len__(self): return self.len @pytest.mark.parametrize("seq_type", [tuple, list]) def test_multiple_eval_...
RandomDatasetB
python
pytest-dev__pytest
testing/_py/test_local.py
{ "start": 37186, "end": 40690 }
class ____: OPTS = {"ensuresyspath": "importlib"} def test_pyimport(self, path1): obj = path1.join("execfile.py").pyimport(**self.OPTS) assert obj.x == 42 assert obj.__name__ == "execfile" def test_pyimport_dir_fails(self, tmpdir): p = tmpdir.join("hello_123") p.ens...
TestImportlibImport
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/formats.py
{ "start": 2411, "end": 2829 }
class ____: """YXYX contains axis indices for the YXYX format. All values in the YXYX format should be absolute pixel values. The YXYX format consists of the following required indices: - TOP: top of the bounding box - LEFT: left of the bounding box - BOTTOM: bottom of the bounding box - ...
YXYX
python
pytransitions__transitions
transitions/experimental/utils.py
{ "start": 3907, "end": 4954 }
class ____(metaclass=ABCMeta): {model_attribute}: "StateIdentifier" = "" def trigger(self, name: str) -> bool: {_placeholder_body} {trigger_block} {state_block}\ {callback_block}""" return template def with_model_definitions(cls): add_model = getattr(cls, "add_model") def add_model_override(sel...
BaseModel
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 49911, "end": 50731 }
class ____(Operation): def call(self, x, y): return backend.numpy.bitwise_and(x, y) def compute_output_spec(self, x, y): dtype = dtypes.result_type(x.dtype, y.dtype) return KerasTensor(x.shape, dtype=dtype) @keras_export(["keras.ops.bitwise_and", "keras.ops.numpy.bitwise_and"]) def bi...
BitwiseAnd
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_bash_code_execution_result_block_param.py
{ "start": 361, "end": 646 }
class ____(TypedDict, total=False): content: Required[Iterable[BetaBashCodeExecutionOutputBlockParam]] return_code: Required[int] stderr: Required[str] stdout: Required[str] type: Required[Literal["bash_code_execution_result"]]
BetaBashCodeExecutionResultBlockParam
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 25062, "end": 27400 }
class ____(BiffRecord): """ Record FORMAT, BIFF8: Offset Size Contents 0 2 Format index used in other records 2 var. Number format string (Unicode string, 16-bit string length) From BIFF5 on, the built-in number formats will be omitted. The built-in formats are ...
NumberFormatRecord
python
django__django
tests/contenttypes_tests/models.py
{ "start": 1688, "end": 1807 }
class ____(models.Model): text = models.CharField(max_length=200) answer_set = GenericRelation("Answer")
Question
python
cython__cython
Cython/Compiler/FlowControl.py
{ "start": 13034, "end": 13937 }
class ____(list): # Keeps track of Node's entry assignments # # cf_is_null [boolean] It is uninitialized # cf_maybe_null [boolean] May be uninitialized # is_single [boolean] Has only one assignment at this point cf_maybe_null = False cf_is_null = False is_single = Fal...
ControlFlowState
python
pytorch__pytorch
torch/utils/_sympy/value_ranges.py
{ "start": 1062, "end": 3674 }
class ____(RuntimeError): pass # Like sympify, but supports less stuff, and also ensures that direct # sympy expressions don't have free variables def simple_sympify(e): if isinstance(e, bool): return sympy.true if e else sympy.false elif isinstance(e, int): return sympy.Integer(e) eli...
ValueRangeError
python
run-llama__llama_index
llama-index-core/llama_index/core/agent/workflow/workflow_events.py
{ "start": 650, "end": 758 }
class ____(Event): """Agent setup.""" input: list[ChatMessage] current_agent_name: str
AgentSetup
python
pytorch__pytorch
torch/_functorch/pyfunctorch.py
{ "start": 5231, "end": 6510 }
class ____(FuncTorchInterpreter): def __init__(self, cdata: CInterpreter): assert cdata.key() == TransformType.Grad # See NOTE: [Interpreter cdata vs cptr] self._cdata = cdata @cached_property # pyrefly: ignore [bad-override] def _cptr(self): return CGradInterpreterPtr(s...
GradInterpreter
python
huggingface__transformers
src/transformers/models/siglip2/modeling_siglip2.py
{ "start": 27662, "end": 29202 }
class ____(nn.Module): """Multihead Attention Pooling.""" def __init__(self, config: Siglip2VisionConfig): super().__init__() self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, ba...
Siglip2MultiheadAttentionPoolingHead
python
pytorch__pytorch
test/test_utils.py
{ "start": 35912, "end": 36301 }
class ____(TestCase): def test_deprecated(self): with self.assertWarnsRegex(Warning, "is DEPRECATED"): deprecated_api(1, 2) # noqa: F821 with self.assertWarnsRegex(Warning, "is DEPRECATED"): deprecated_api(1, y=2) # noqa: F821 _deprecated_api(1, 2) _deprecat...
TestDeprecate
python
matplotlib__matplotlib
lib/matplotlib/backend_bases.py
{ "start": 25186, "end": 35672 }
class ____: """An abstract base class that provides color, line styles, etc.""" def __init__(self): self._alpha = 1.0 self._forced_alpha = False # if True, _alpha overrides A from RGBA self._antialiased = 1 # use 0, 1 not True, False for extension code self._capstyle = CapStyl...
GraphicsContextBase
python
ray-project__ray
python/ray/experimental/collective/conftest.py
{ "start": 280, "end": 2124 }
class ____(Communicator): """ A dummy NCCL group for testing. """ def __init__(self, actor_handles: List[ray.actor.ActorHandle]): self._actor_handles = actor_handles self._rank = None def initialize(self, rank: int) -> None: self._rank = rank def get_rank(self, actor: ...
AbstractNcclGroup
python
run-llama__llama_index
llama-index-experimental/llama_index/experimental/nudge/base.py
{ "start": 659, "end": 6180 }
class ____: """ The algorithm implemented here and the current state of the art is called [NUDGE](https://www.arxiv.org/abs/2409.02343). If a validation dataset is provided, the best model is evaluated and saved based on the validation loss at the end of every epoch. Args: train_dataset (Embedd...
Nudge
python
tensorflow__tensorflow
tensorflow/python/types/core.py
{ "start": 4654, "end": 5545 }
class ____(Callable): """Base class for graph functions. An `AtomicFunction` encapsulates a single graph function definition. `AtomicFunction` can be called directly only if no captures are needed according to the `FunctionType`. If captures are present, please use `call_with_captures` instead. `AtomicFu...
AtomicFunction
python
celery__celery
t/unit/tasks/test_trace.py
{ "start": 19969, "end": 21585 }
class ____(TraceCase): class TI(TraceInfo): __slots__ = TraceInfo.__slots__ + ('__dict__',) def test_handle_error_state(self): x = self.TI(states.FAILURE) x.handle_failure = Mock() x.handle_error_state(self.add_cast, self.add_cast.request) x.handle_failure.assert_called_...
test_TraceInfo
python
coleifer__peewee
tests/models.py
{ "start": 1257, "end": 1445 }
class ____(TestModel): content = TextField(column_name='Content') timestamp = DateTimeField(column_name='TimeStamp', default=datetime.datetime.now)
Post
python
xlwings__xlwings
tests/reports/test_report.py
{ "start": 6409, "end": 11970 }
class ____(unittest.TestCase): def tearDown(self): xw.Book(this_dir / "output.xlsx").app.quit() def test_one_frame(self): df = pd.DataFrame( [[1.0, 2.0], [3.0, 4.0]], columns=["c1", "c2"], index=["r1", "r2"] ) wb = render_template( this_dir / "template_on...
TestFrames
python
huggingface__transformers
src/transformers/models/dinov2/modeling_dinov2.py
{ "start": 1435, "end": 5113 }
class ____(nn.Module): """ Construct the CLS token, mask token, position and patch embeddings. """ def __init__(self, config: Dinov2Config) -> None: super().__init__() self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size)) if config.use_mask_token: sel...
Dinov2Embeddings
python
apache__airflow
providers/common/messaging/src/airflow/providers/common/messaging/triggers/msg_queue.py
{ "start": 1520, "end": 6112 }
class ____(BaseEventTrigger): """ ``MessageQueueTrigger`` serves as a unified trigger for monitoring message queues from different providers. It abstracts away provider-specific details, allowing users to monitor a queue with a single trigger, regardless of the underlying provider. This makes it e...
MessageQueueTrigger
python
viewflow__viewflow
viewflow/views/update.py
{ "start": 1012, "end": 5452 }
class ____( FormLayoutMixin, FormDependentSelectMixin, FormAjaxCompleteMixin, generic.UpdateView ): viewset = None layout = None form_widgets = None page_actions = None def has_change_permission(self, request, obj=None): if self.viewset is not None and hasattr(self.viewset, "has_change_...
UpdateModelView
python
dagster-io__dagster
python_modules/libraries/dagster-duckdb-pandas/dagster_duckdb_pandas/duckdb_pandas_type_handler.py
{ "start": 6023, "end": 9068 }
class ____(DuckDBIOManager): """An I/O manager definition that reads inputs from and writes Pandas DataFrames to DuckDB. When using the DuckDBPandasIOManager, any inputs and outputs without type annotations will be loaded as Pandas DataFrames. Returns: IOManagerDefinition Examples: ...
DuckDBPandasIOManager
python
apache__airflow
helm-tests/tests/helm_tests/other/test_flower.py
{ "start": 25966, "end": 27507 }
class ____: """Tests flower service account.""" def test_should_add_component_specific_labels(self): docs = render_chart( values={ "flower": { "enabled": True, "labels": {"test_label": "test_label_value"}, }, ...
TestFlowerServiceAccount
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/result.py
{ "start": 61496, "end": 66118 }
class ____(FilterResult[_R], util.TypingOnly): """A :class:`_engine.Result` that's typed as returning plain Python tuples instead of rows. Since :class:`_engine.Row` acts like a tuple in every way already, this class is a typing only class, regular :class:`_engine.Result` is still used at runtime. ...
TupleResult
python
eth-brownie__brownie
brownie/typing.py
{ "start": 2538, "end": 2891 }
class ____(_ContractBuildJson): type: Literal["contract"] language: Literal["Vyper"] ContractBuildJson = SolidityBuildJson | VyperBuildJson BuildJson = ContractBuildJson | InterfaceBuildJson # Compiler Language = Literal["Solidity", "Vyper"] EvmVersion = NewType("EvmVersion", str) Source = Tuple[Start, Stop...
VyperBuildJson
python
google__jax
jax/_src/interpreters/partial_eval.py
{ "start": 54012, "end": 54067 }
class ____: pass Recompute = RecomputeType()
RecomputeType
python
wandb__wandb
landfill/functional_tests/artifacts/use-and-link-model.py
{ "start": 187, "end": 1474 }
class ____(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10...
Net
python
pyinstaller__pyinstaller
bootloader/waflib/TaskGen.py
{ "start": 292, "end": 12755 }
class ____(object): mappings = Utils.ordered_iter_dict() prec = Utils.defaultdict(set) def __init__(self, *k, **kw): self.source = [] self.target = '' self.meths = [] self.features = [] self.tasks = [] if not 'bld' in kw: self.env = ConfigSet.Conf...
task_gen
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 14506, "end": 15309 }
class ____(Element): """ A base class for simple elements, such as FIELD, PARAM and INFO that don't require any special parsing or outputting machinery. """ def __init__(self): Element.__init__(self) def __repr__(self): buff = io.StringIO() SimpleElement.to_xml(self, XM...
SimpleElement
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/type_api.py
{ "start": 3387, "end": 3525 }
class ____(Protocol[_T]): def __call__( self, expr: ColumnElement[_T] ) -> TypeEngine.Comparator[_T]: ...
_ComparatorFactory
python
matplotlib__matplotlib
lib/matplotlib/sphinxext/plot_directive.py
{ "start": 17031, "end": 18169 }
class ____: def __init__(self, basename, dirname): self.basename = basename self.dirname = dirname self.formats = [] def filename(self, format): return os.path.join(self.dirname, f"{self.basename}.{format}") def filenames(self): return [self.filename(fmt) for fmt in...
ImageFile
python
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 9231, "end": 10583 }
class ____(AtomicRule): """integrate(poly(x)/sqrt(a+b*x+c*x**2), x)""" a: Expr b: Expr c: Expr coeffs: list[Expr] def eval(self) -> Expr: a, b, c, coeffs, x = self.a, self.b, self.c, self.coeffs.copy(), self.variable # Integrate poly/sqrt(a+b*x+c*x**2) using recursion. #...
SqrtQuadraticDenomRule
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 14743, "end": 16871 }
class ____(LossFunctionWrapper): """Computes the mean absolute percentage error between `y_true` and `y_pred`. `loss = 100 * abs(y_true - y_pred) / y_true` Standalone usage: >>> y_true = [[2., 1.], [2., 3.]] >>> y_pred = [[1., 1.], [1., 0.]] >>> # Using 'auto'/'sum_over_batch_size' reduction type. >>> ...
MeanAbsolutePercentageError
python
django__django
django/contrib/admindocs/views.py
{ "start": 15866, "end": 19572 }
class ____(BaseAdminDocsView): template_name = "admin_doc/template_detail.html" def get_context_data(self, **kwargs): template = self.kwargs["template"] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial T...
TemplateDetailView
python
django__django
django/contrib/messages/storage/fallback.py
{ "start": 195, "end": 2093 }
class ____(BaseStorage): """ Try to store all messages in the first backend. Store any unstored messages in each subsequent backend. """ storage_classes = (CookieStorage, SessionStorage) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.storages = [ ...
FallbackStorage
python
openai__openai-python
src/openai/resources/containers/files/content.py
{ "start": 3033, "end": 5492 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncContentWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.gi...
AsyncContent
python
pytest-dev__pytest
testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_module_class.py
{ "start": 127, "end": 279 }
class ____: @pytest.fixture def spam(self, spam): return spam * 2 def test_spam(self, spam): assert spam == "spamspam"
TestSpam
python
django__django
tests/gis_tests/geoapp/test_regress.py
{ "start": 288, "end": 3961 }
class ____(TestCase): fixtures = ["initial"] def test_update(self): "Testing QuerySet.update() (#10411)." pueblo = City.objects.get(name="Pueblo") bak = pueblo.point.clone() pueblo.point.y += 0.005 pueblo.point.x += 0.005 City.objects.filter(name="Pueblo").updat...
GeoRegressionTests
python
run-llama__llama_index
llama-index-core/llama_index/core/storage/kvstore/simple_kvstore.py
{ "start": 248, "end": 1812 }
class ____(MutableMappingKVStore[dict]): """ Simple in-memory Key-Value store. Args: data (Optional[DATA_TYPE]): data to initialize the store with """ def __init__( self, data: Optional[DATA_TYPE] = None, ) -> None: """Init a SimpleKVStore.""" super()._...
SimpleKVStore
python
chroma-core__chroma
chromadb/telemetry/opentelemetry/grpc.py
{ "start": 698, "end": 3731 }
class ____( grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor, grpc.StreamUnaryClientInterceptor, grpc.StreamStreamClientInterceptor, ): def _intercept_call(self, continuation, client_call_details, request_or_iterator): from chromadb.telemetry.opentelemetry import tracer ...
OtelInterceptor
python
numba__numba
numba/tests/test_ir.py
{ "start": 17395, "end": 20239 }
class ____(TestCase): def test_var_in_scope_assumption(self): # Create a pass that clears ir.Scope in ir.Block @register_pass(mutates_CFG=False, analysis_only=False) class RemoveVarInScope(FunctionPass): _name = "_remove_var_in_scope" def __init__(self): ...
TestIRPedanticChecks
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_semiprime.py
{ "start": 1822, "end": 4107 }
class ____(ColumnMapExpectation): """Expect column values to be valid semiprime codes.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_semiprime": [ ...
ExpectColumnValuesToBeValidSemiprime
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 1144, "end": 3639 }
class ____(ASTBaseBase): def __init__(self, name: str) -> None: if not isinstance(name, str) or len(name) == 0: raise AssertionError self.name = sys.intern(name) self.is_anonymous = name[0] == '@' # ASTBaseBase already implements this method, # but specialising it here i...
ASTIdentifier
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 97082, "end": 97295 }
class ____(AccessControlRequestForUser, AccessControlRequestForGroup): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True)
AccessControlRequest
python
ansible__ansible
lib/ansible/parsing/vault/__init__.py
{ "start": 17076, "end": 21529 }
class ____(ScriptVaultSecret): VAULT_ID_UNKNOWN_RC = 2 def __init__(self, filename=None, encoding=None, loader=None, vault_id=None): super(ClientScriptVaultSecret, self).__init__(filename=filename, encoding=encoding, ...
ClientScriptVaultSecret
python
pytorch__pytorch
test/distributed/_shard/sharding_plan/test_sharding_plan.py
{ "start": 1696, "end": 5399 }
class ____(ShardedTensorTestBase): @with_comms(init_rpc=False) @skip_if_lt_x_gpu(TEST_GPU_NUM) @requires_nccl() def test_sharding_plan_errors(self): rowwise_sharding_spec = generate_chunk_sharding_specs_for_test(1)[0] sharding_plan_wrong_plan = ShardingPlan( plan={ ...
TestShardingPlan
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 108860, "end": 118388 }
class ____(TestCase): def test_all(self): iterable = ['0', '1', '2', '3', '4', '5'] indexes = [*range(-4, 10), None] steps = [1, 2, 3, 4, -1, -2, -3, -4] for slice_args in product(indexes, indexes, steps): with self.subTest(slice_args=slice_args): actual =...
IsliceExtendedTests
python
scipy__scipy
scipy/integrate/tests/test_cubature.py
{ "start": 31476, "end": 32601 }
class ____: """ Tests related to the general Rule interface (currently private). """ @pytest.mark.parametrize("problem", [ ( # 2D problem, 1D rule [0, 0], [1, 1], GaussKronrodQuadrature, (21,), ), ( # 1D pro...
TestRules
python
doocs__leetcode
solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/Solution.py
{ "start": 0, "end": 304 }
class ____: def rearrangeArray(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) m = (n + 1) // 2 ans = [] for i in range(m): ans.append(nums[i]) if i + m < n: ans.append(nums[i + m]) return ans
Solution
python
pandas-dev__pandas
pandas/tests/indexes/timedeltas/test_timedelta.py
{ "start": 147, "end": 1938 }
class ____: def test_misc_coverage(self): rng = timedelta_range("1 day", periods=5) result = rng.groupby(rng.days) assert isinstance(next(iter(result.values()))[0], Timedelta) def test_map(self): # test_map_dictlike generally tests rng = timedelta_range("1 day", periods...
TestTimedeltaIndex
python
python-pillow__Pillow
src/PIL/XVThumbImagePlugin.py
{ "start": 972, "end": 2115 }
class ____(ImageFile.ImageFile): format = "XVThumb" format_description = "XV thumbnail image" def _open(self) -> None: # check magic assert self.fp is not None if not _accept(self.fp.read(6)): msg = "not an XV thumbnail file" raise SyntaxError(msg) ...
XVThumbImageFile
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 108560, "end": 110231 }
class ____(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with...
OneFormerTextMapperAttention
python
jazzband__django-oauth-toolkit
tests/test_auth_backends.py
{ "start": 3483, "end": 5881 }
class ____(BaseTest): def dummy_get_response(self, request): return HttpResponse() def test_middleware_wrong_headers(self): m = OAuth2TokenMiddleware(self.dummy_get_response) request = self.factory.get("/a-resource") m(request) self.assertFalse(hasattr(request, "user")) ...
TestOAuth2Middleware
python
has2k1__plotnine
plotnine/scales/scale_xy.py
{ "start": 6776, "end": 6955 }
class ____(scale_position_discrete): """ Discrete x position """ _aesthetics = ["x", "xmin", "xmax", "xend", "xintercept"] @dataclass(kw_only=True)
scale_x_discrete
python
falconry__falcon
tests/test_testing.py
{ "start": 167, "end": 7030 }
class ____: def items(self): return [('foo', 'bar'), ('baz', 'foo')] def another_dummy_wsgi_app(environ, start_response): start_response(status_codes.HTTP_OK, [('Content-Type', 'text/plain')]) yield b'It works!' def test_testing_client_handles_wsgi_generator_app(): client = testing.TestClie...
CustomCookies
python
getsentry__sentry
src/sentry/new_migrations/monkey/state.py
{ "start": 275, "end": 344 }
class ____(Enum): MOVE_TO_PENDING = 0 DELETE = 1
DeletionAction
python
getlogbook__logbook
benchmark/bench_enabled_introspection.py
{ "start": 130, "end": 347 }
class ____(NullHandler): blackhole = False def run(): with Flags(introspection=True): with DummyHandler(): for _ in range(500): log.warning("this is not handled")
DummyHandler
python
astropy__astropy
astropy/cosmology/_src/io/builtin/model.py
{ "start": 1867, "end": 10627 }
class ____(FittableModel, Generic[_CosmoT]): """Base class for Cosmology redshift-method Models. .. note:: This class is not publicly scoped so should not be used directly. Instead, from a Cosmology instance use ``.to_format("astropy.model")`` to create an instance of a subclass of thi...
_CosmologyModel
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/pooling_ops_test.py
{ "start": 6210, "end": 97295 }
class ____(test.TestCase, parameterized.TestCase): def _isMaxPool(self, func): return func in (nn_ops.max_pool, nn_ops.max_pool_v2) def _VerifyOneType( self, pool_func, input_sizes, ksize, strides, padding, data_format, data_type, expected, use_gpu, ...
PoolingTest
python
psf__black
tests/data/cases/fmtonoff5.py
{ "start": 2810, "end": 3253 }
class ____: async def call(param): if param: # fmt: off if param[0:4] in ( "ABCD", "EFGH" ) : # fmt: on print ( "This won't be formatted" ) elif param[0:4] in ("ZZZZ",): print ( "This won't be f...
A
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v2_utils.py
{ "start": 30723, "end": 38542 }
class ____(_Optimizer): """Optimization parameters for FTRL with TPU embeddings. See Algorithm 1 of this [paper](https://research.google.com/pubs/archive/41159.pdf). Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` argument to set the global optimizer and its parameters: ```p...
FTRL
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hparams.py
{ "start": 2351, "end": 2603 }
class ____(BoringModel): """Tests that a model can take an object.""" @decorate @decorate def __init__(self, hparams, *my_args, **my_kwargs): super().__init__() self.save_hyperparameters(hparams)
SaveHparamsDecoratedModel
python
pytorch__pytorch
torch/ao/nn/quantized/dynamic/modules/linear.py
{ "start": 209, "end": 6487 }
class ____(nnq.Linear): r""" A dynamic quantized linear module with floating point tensor as inputs and outputs. We adopt the same interface as `torch.nn.Linear`, please see https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation. Similar to :class:`torch.nn.Linear`, attributes wi...
Linear
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1438604, "end": 1449693 }
class ____(TopLevelSpec): """ TopLevelConcatSpec schema wrapper. Parameters ---------- concat : Sequence[dict, :class:`FacetSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, :class:`FacetedUnitSpec`, :class:`LayerRepeatSpec`, :class:`NonNormalizedSpec`, :class:`NonLayerRepeatSpec`, :class:`ConcatSpec...
TopLevelConcatSpec
python
Textualize__textual
tests/command_palette/test_run_on_select.py
{ "start": 159, "end": 651 }
class ____(Provider): async def search(self, _: str) -> Hits: def goes_nowhere_does_nothing(selection: int) -> None: assert isinstance(self.app, CommandPaletteRunOnSelectApp) self.app.selection = selection for n in range(100): yield Hit( n + 1 / 1...
SimpleSource
python
keras-team__keras
keras/src/callbacks/lambda_callback.py
{ "start": 146, "end": 3459 }
class ____(Callback): """Callback for creating simple, custom callbacks on-the-fly. This callback is constructed with anonymous functions that will be called at the appropriate time (during `Model.{fit | evaluate | predict}`). Note that the callbacks expects positional arguments, as: - `on_epoch_b...
LambdaCallback
python
pytorch__pytorch
test/dynamo/test_python_autograd.py
{ "start": 6338, "end": 8882 }
class ____(TestCase): def _common(self, fn, expected_ops): args1 = [torch.randn(10), torch.randn(10)] args2 = [torch.randn(10), torch.randn(10)] cnt = CompileCounter() fn_dynamo = torch._dynamo.optimize_assert(cnt)(fn) reset_tape() res1 = fn_dynamo(*args1) res...
TestPythonAutograd
python
tensorflow__tensorflow
tensorflow/core/tfrt/saved_model/tests/gen_saved_model_v2.py
{ "start": 1386, "end": 2152 }
class ____(module.Module): """Defines a toy module.""" def __init__(self): super(ToyModule, self).__init__() self.w = variables.Variable(constant_op.constant([[1], [2], [3]]), name='w') @def_function.function(input_signature=[ tensor_spec.TensorSpec([1, 3], dtypes.int32, name='input') ]) def t...
ToyModule
python
kamyu104__LeetCode-Solutions
Python/earliest-possible-day-of-full-bloom.py
{ "start": 33, "end": 477 }
class ____(object): def earliestFullBloom(self, plantTime, growTime): """ :type plantTime: List[int] :type growTime: List[int] :rtype: int """ order = range(len(growTime)) order.sort(key=lambda x: growTime[x], reverse=True) result = curr = 0 fo...
Solution
python
apache__airflow
providers/ydb/tests/unit/ydb/operators/test_ydb.py
{ "start": 2964, "end": 5152 }
class ____: def setup_method(self): dag_id = "test_dag" self.dag = DAG( dag_id, default_args={ "owner": "airflow", "start_date": datetime.today(), "end_date": datetime.today() + timedelta(days=1), }, sche...
TestYDBExecuteQueryOperator
python
mlflow__mlflow
mlflow/models/utils.py
{ "start": 6373, "end": 76692 }
class ____: """ Represents an input example for MLflow model. Contains jsonable data that can be saved with the model and meta data about the exported format that can be saved with :py:class:`Model <mlflow.models.Model>`. The _Example is created from example data provided by user. The example(s) c...
_Example
python
scipy__scipy
scipy/stats/_sampling.py
{ "start": 12113, "end": 12267 }
class ____: def __init__(self, pdf, args): self._pdf = lambda x: pdf(x, *args) def pdf(self, x): return self._pdf(x)
CustomDistPINV
python
celery__celery
t/smoke/operations/worker_restart.py
{ "start": 110, "end": 1369 }
class ____: """Restarts a worker in different ways.""" class Method(Enum): POOL_RESTART = auto() DOCKER_RESTART_GRACEFULLY = auto() DOCKER_RESTART_FORCE = auto() def restart_worker( self, worker: CeleryTestWorker, method: WorkerRestart.Method, asserti...
WorkerRestart
python
getsentry__sentry
src/sentry/api/endpoints/project_transaction_threshold_override.py
{ "start": 778, "end": 2179 }
class ____(serializers.Serializer): transaction = serializers.CharField(required=True, max_length=200) threshold = serializers.IntegerField(required=True, max_value=MAX_VALUE) metric = serializers.CharField(required=True) def validate_metric(self, metric): for key, value in TRANSACTION_METRICS....
ProjectTransactionThresholdOverrideSerializer
python
rq__rq
rq/worker.py
{ "start": 2908, "end": 65525 }
class ____: redis_worker_namespace_prefix = 'rq:worker:' redis_workers_keys = worker_registration.REDIS_WORKER_KEYS death_penalty_class = get_default_death_penalty_class() queue_class = Queue job_class = Job # `log_result_lifespan` controls whether "Result is kept for XXX seconds" # message...
BaseWorker
python
Pylons__pyramid
src/pyramid/security.py
{ "start": 6344, "end": 6694 }
class ____(PermitsResult): """ An instance of ``Denied`` is returned when a security-related API or other :app:`Pyramid` code denies an action unrelated to an ACL check. It evaluates equal to all boolean false types. It has an attribute named ``msg`` describing the circumstances for the deny. ...
Denied
python
celery__celery
t/unit/worker/test_consumer.py
{ "start": 32072, "end": 33174 }
class ____: def test_start(self): c = Mock() c.timer = Mock() c.event_dispatcher = Mock() with patch('celery.worker.heartbeat.Heart') as hcls: h = Heart(c) assert h.enabled assert h.heartbeat_interval is None assert c.heart is None ...
test_Heart
python
PyCQA__pylint
tests/functional/r/regression/regression_properties_in_class_context.py
{ "start": 145, "end": 291 }
class ____(metaclass=Meta): pass assert 'foo' in Parent.values # no warning for value in Parent.values: # no warning print(value)
Parent
python
pytorch__pytorch
test/inductor/test_compiled_autograd.py
{ "start": 135993, "end": 143553 }
class ____(torch.nn.Module): def forward(self, inputs, sizes, scalars, hooks, packed_data): getitem = inputs[0] getitem_1 = inputs[1]; inputs = None getitem_2 = sizes[0] getitem_3 = sizes[1] getitem_4 = sizes[2] getitem_5 = sizes[3] getitem_6 = sizes[4] ...
CompiledAutograd0
python
tornadoweb__tornado
demos/google_auth/main.py
{ "start": 1208, "end": 1977 }
class ____(BaseHandler, tornado.auth.GoogleOAuth2Mixin): @tornado.web.authenticated async def get(self): try: # This is redundant: we got the userinfo in the login handler. # But this demonstrates the usage of oauth2_request outside of # the login flow, and getting an...
IndexHandler
python
doocs__leetcode
solution/1100-1199/1188.Design Bounded Blocking Queue/Solution.py
{ "start": 34, "end": 520 }
class ____(object): def __init__(self, capacity: int): self.s1 = Semaphore(capacity) self.s2 = Semaphore(0) self.q = deque() def enqueue(self, element: int) -> None: self.s1.acquire() self.q.append(element) self.s2.release() def dequeue(self) -> int: ...
BoundedBlockingQueue
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/api.py
{ "start": 2753, "end": 2946 }
class ____: Edit = 'edit' Inspect = 'inspect' Array = 'array' Export = 'export' Clear = 'clear' Image = 'image' SVG = 'svg' Quit = 'exit'
ClientContextMenuSections
python
pytorch__pytorch
test/quantization/core/experimental/quantization_util.py
{ "start": 614, "end": 5043 }
class ____: """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0.0 self.sum = 0 self.count = 0 def update(self, val, n=...
AverageMeter
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 38744, "end": 48619 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8]", L_y_: "f32[8]"): l_x_ = L_x_ l_y_ = L_y_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_, l_y_); subgraph_0 = l_x_ = None getitem: "f32[8]" = ...
GraphModule
python
plotly__plotly.py
plotly/graph_objs/layout/slider/_step.py
{ "start": 235, "end": 12345 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.slider" _path_str = "layout.slider.step" _valid_props = { "args", "execute", "label", "method", "name", "templateitemname", "value", "visible", } @property def args(s...
Step
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 21254, "end": 22227 }
class ____(URLFetchStrategy): """The resource associated with a cache URL may be out of date.""" @_needs_stage def fetch(self): path = url_util.file_url_string_to_path(self.url) # check whether the cache file exists. if not os.path.isfile(path): raise NoCacheError(f"No ...
CacheURLFetchStrategy
python
pytorch__pytorch
test/cpp/aoti_inference/compile_model.py
{ "start": 353, "end": 671 }
class ____(torch.nn.Module): """ a simple module to be compiled """ def __init__(self) -> None: super().__init__() self.fc = torch.nn.Linear(4, 6) self.relu = torch.nn.ReLU() def forward(self, x): a = self.fc(x) b = self.relu(a) return b
SimpleModule
python
getsentry__sentry
src/sentry/notifications/notification_action/action_validation.py
{ "start": 2495, "end": 3248 }
class ____(BaseActionValidatorHandler): provider = Action.Type.MSTEAMS notify_action_form = MsTeamsNotifyServiceForm def generate_action_form_data(self) -> dict[str, Any]: return { "team": self.validated_data["integration_id"], "channel": self.validated_data["config"]["targe...
MSTeamsActionValidatorHandler
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 15568, "end": 20126 }
class ____: @classmethod def setup_class(cls): cls.G = nx.path_graph(9) cls.eview = nx.reportviews.EdgeView def test_pickle(self): import pickle ev = self.eview(self.G) pev = pickle.loads(pickle.dumps(ev, -1)) assert ev == pev assert ev.__slots__ == ...
TestEdgeView
python
google__jax
jax/_src/internal_test_util/test_harnesses.py
{ "start": 3791, "end": 10452 }
class ____: """Specifies inputs and callable for a test harness. See the module docstring for an introduction to harnesses. A harness is conceptually a callable and a list of arguments, that together exercise a use case. The harness can optionally have additional parameters that can be used by the test. ...
Harness
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 174565, "end": 177329 }
class ____(GeneratedAirbyteSource): class OAuth20: @public def __init__( self, client_id: str, client_secret: str, access_token: Optional[str] = None, refresh_token: Optional[str] = None, ): self.auth_type = "OAuth" ...
SnowflakeSource
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py
{ "start": 19300, "end": 26032 }
class ____(nn.Module): """Image embedding.""" def __init__(self, config: Phi4MultimodalConfig): super().__init__() self.config = config self.layer_idx = config.vision_config.feature_layer self.crop_size = config.vision_config.crop_size self.image_dim_out = config.vision_...
Phi4MultimodalImageEmbedding
python
openai__openai-python
src/openai/resources/realtime/realtime.py
{ "start": 34704, "end": 37422 }
class ____(BaseAsyncRealtimeConnectionResource): async def create( self, *, event_id: str | Omit = omit, response: RealtimeResponseCreateParamsParam | Omit = omit ) -> None: """ This event instructs the server to create a Response, which means triggering model inference. When in ...
AsyncRealtimeResponseResource