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
src/transformers/models/nanochat/modular_nanochat.py
{ "start": 1894, "end": 4323 }
class ____(Qwen3Attention): def __init__(self, config: NanoChatConfig, layer_idx: int): super().__init__(config, layer_idx) del self.sliding_window del self.layer_type self.q_norm = NanoChatRMSNorm(eps=config.rms_norm_eps) self.k_norm = NanoChatRMSNorm(eps=config.rms_norm_ep...
NanoChatAttention
python
tensorflow__tensorflow
tensorflow/python/training/gradient_descent.py
{ "start": 1133, "end": 3408 }
class ____(optimizer.Optimizer): """Optimizer that implements the gradient descent algorithm. """ def __init__(self, learning_rate, use_locking=False, name="GradientDescent"): """Construct a new gradient descent optimizer. Args: learning_rate: A Tensor or a floating point value. The learning ...
GradientDescentOptimizer
python
google__jax
jax/experimental/pallas/ops/tpu/ragged_paged_attention/kernel.py
{ "start": 1254, "end": 31883 }
class ____: """Descriptor for async copy of multiple K/V pages from HBM.""" def __init__( self, pages_hbm_ref, # [total_num_pages, page_size, num_combined_kv_heads_per_blk, head_dim] vmem_buf, # [num_kv_pages_per_blk, page_size, num_combined_kv_heads_per_blk, head_dim] sem, page_ind...
MultiPageAsyncCopyDescriptor
python
kamyu104__LeetCode-Solutions
Python/interleaving-string.py
{ "start": 1667, "end": 2439 }
class ____(object): # @return a boolean def isInterleave(self, s1, s2, s3): self.match = {} if len(s1) + len(s2) != len(s3): return False return self.isInterleaveRecu(s1, s2, s3, 0, 0, 0) def isInterleaveRecu(self, s1, s2, s3, a, b, c): if repr([a, b]) in self.ma...
Solution3
python
facebook__pyre-check
client/commands/tests/validate_models_test.py
{ "start": 379, "end": 3417 }
class ____(testslide.TestCase): def test_parse_response(self) -> None: def assert_parsed( payload: object, expected: Iterable[error.ModelVerificationError] ) -> None: self.assertEqual( validate_models.parse_validation_errors_response(payload), ...
ValidateModelsTest
python
tensorflow__tensorflow
tensorflow/python/keras/layers/dense_attention.py
{ "start": 14387, "end": 20834 }
class ____(BaseDenseAttention): """Additive attention layer, a.k.a. Bahdanau-style attention. Inputs are `query` tensor of shape `[batch_size, Tq, dim]`, `value` tensor of shape `[batch_size, Tv, dim]` and `key` tensor of shape `[batch_size, Tv, dim]`. The calculation follows the steps: 1. Reshape `query` a...
AdditiveAttention
python
gevent__gevent
src/greentest/3.10/test_ssl.py
{ "start": 79791, "end": 81474 }
class ____(unittest.TestCase): def test_private_init(self): bio = ssl.MemoryBIO() with self.assertRaisesRegex(TypeError, "public constructor"): ssl.SSLObject(bio, bio) def test_unwrap(self): client_ctx, server_ctx, hostname = testing_context() c_in = ssl.MemoryBIO() ...
SSLObjectTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar17.py
{ "start": 630, "end": 712 }
class ____: def write(self, __buffer: ReadableBuffer) -> int: ...
BufferedWriter
python
ansible__ansible
test/units/playbook/test_helpers.py
{ "start": 15917, "end": 17417 }
class ____(unittest.TestCase, MixinForMocks): def setUp(self): self._setup() def test_ds_not_list(self): ds = {} mock_play = MagicMock(name='MockPlay') self.assertRaises(AssertionError, helpers.load_list_of_blocks, ds, mock_play, parent_block=None, role...
TestLoadListOfBlocks
python
getsentry__sentry
src/sentry/preprod/api/models/project_preprod_build_details_models.py
{ "start": 1062, "end": 1371 }
class ____(BaseModel): head_sha: str | None = None base_sha: str | None = None provider: str | None = None head_repo_name: str | None = None base_repo_name: str | None = None head_ref: str | None = None base_ref: str | None = None pr_number: int | None = None
BuildDetailsVcsInfo
python
django__django
django/db/models/fields/related.py
{ "start": 50560, "end": 54116 }
class ____(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that it always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ #...
OneToOneField
python
pandas-dev__pandas
pandas/tests/series/test_arithmetic.py
{ "start": 822, "end": 6223 }
class ____: @pytest.mark.parametrize( "ts", [ (lambda x: x, lambda x: x * 2, False), (lambda x: x, lambda x: x[::2], False), (lambda x: x, lambda x: 5, True), ( lambda x: Series(range(10), dtype=np.float64), lambda x: Se...
TestSeriesFlexArithmetic
python
huggingface__transformers
src/transformers/models/wav2vec2/modeling_wav2vec2.py
{ "start": 23208, "end": 24576 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.attention = Wav2Vec2Attention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, ...
Wav2Vec2EncoderLayer
python
ray-project__ray
python/ray/autoscaler/v2/tests/test_node_provider.py
{ "start": 2414, "end": 3917 }
class ____(CloudInstanceProviderTesterBase): def __init__(self, **kwargs): self.config_reader = FileConfigReader( get_test_config_path("test_ray_complex.yaml"), skip_content_hash=True ) self.config = self.config_reader.get_cached_autoscaling_config() self.ray_session = No...
FakeMultiNodeProviderTester
python
numba__numba
numba/tests/test_unicode.py
{ "start": 93279, "end": 97319 }
class ____(BaseTest): def test_ord(self): pyfunc = ord_usecase cfunc = njit(pyfunc) for ex in UNICODE_EXAMPLES: for a in ex: self.assertPreciseEqual(pyfunc(a), cfunc(a)) def test_ord_invalid(self): self.disable_leak_check() pyfunc = ord_usec...
TestUnicodeAuxillary
python
doocs__leetcode
solution/2300-2399/2319.Check if Matrix Is X-Matrix/Solution.py
{ "start": 0, "end": 352 }
class ____: def checkXMatrix(self, grid: List[List[int]]) -> bool: for i, row in enumerate(grid): for j, v in enumerate(row): if i == j or i + j == len(grid) - 1: if v == 0: return False elif v: retur...
Solution
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 67163, "end": 67275 }
class ____(Config): enabled = c.Type(bool, default=True) bar = c.Type(int, default=0)
_EnabledPluginConfig
python
python-openxml__python-docx
tests/test_table.py
{ "start": 23103, "end": 30059 }
class ____: """Unit-test suite for `docx.table._Row` objects.""" @pytest.mark.parametrize( ("tr_cxml", "expected_value"), [ ("w:tr", 0), ("w:tr/w:trPr", 0), ("w:tr/w:trPr/w:gridAfter{w:val=0}", 0), ("w:tr/w:trPr/w:gridAfter{w:val=4}", 4), ...
Describe_Row
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 30554, "end": 32336 }
class ____: def _test_abs_func(self, absfunc, test_dtype): x = test_dtype(-1.5) assert_equal(absfunc(x), 1.5) x = test_dtype(0.0) res = absfunc(x) # assert_equal() checks zero signedness assert_equal(res, 0.0) x = test_dtype(-0.0) res = absfunc(x) ...
TestAbs
python
huggingface__transformers
src/transformers/models/regnet/modeling_regnet.py
{ "start": 2085, "end": 2959 }
class ____(nn.Module): """ RegNet Embeddings (stem) composed of a single aggressive convolution. """ def __init__(self, config: RegNetConfig): super().__init__() self.embedder = RegNetConvLayer( config.num_channels, config.embedding_size, kernel_size=3, stride=2, activation=...
RegNetEmbeddings
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/_stubs.py
{ "start": 796, "end": 1112 }
class ____(TypedDict): Key: str LastModified: datetime ETag: Optional[str] ChecksumAlgorithm: Optional[list[ChecksumAlgorithmType]] Size: Optional[int] StorageClass: Optional[ObjectStorageClassType] Owner: Optional[OwnerTypeDef] RestoreStatus: Optional[RestoreStatusTypeDef]
ObjectTypeDef
python
ray-project__ray
rllib/utils/exploration/random_encoder.py
{ "start": 717, "end": 3810 }
class ____: """Track moving mean, std and count.""" def __init__(self, epsilon: float = 1e-4, shape: Optional[List[int]] = None): """Initialize object. Args: epsilon: Initial count. shape: Shape of the trackables mean and std. """ if not shape: ...
_MovingMeanStd
python
pandas-dev__pandas
pandas/tests/indexes/period/test_setops.py
{ "start": 248, "end": 12547 }
class ____: def test_union(self, sort): # union other1 = period_range("1/1/2000", freq="D", periods=5) rng1 = period_range("1/6/2000", freq="D", periods=5) expected1 = PeriodIndex( [ "2000-01-06", "2000-01-07", "2000-01-08",...
TestPeriodIndex
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 184659, "end": 187928 }
class ____(sparse_test_class(minmax=False)): spcreator = lil_array math_dtypes = [np.int_, np.float64, np.complex128] def test_dot(self): A = zeros((10, 10), np.complex128) A[0, 3] = 10 A[5, 6] = 20j B = self.lil_container((10, 10), dtype=np.complex128) B[0, 3] = 10...
TestLIL
python
apache__airflow
airflow-ctl/src/airflowctl/api/operations.py
{ "start": 22327, "end": 24243 }
class ____(BaseOperations): """Pool operations.""" def get(self, pool_name: str) -> PoolResponse | ServerResponseError: """Get a pool.""" try: self.response = self.client.get(f"pools/{pool_name}") return PoolResponse.model_validate_json(self.response.content) exc...
PoolsOperations
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/regression.py
{ "start": 4271, "end": 5694 }
class ____(Regression): """Linear regression model with a regularization factor which does both variable selection and regularization. Model that tries to balance the fit of the model with respect to the training data and the complexity of the model. A large regularization factor with decreases the varian...
LassoRegression
python
ZoranPandovski__al-go-rithms
data_structures/Tree/splay_tree/python/splay_tree.py
{ "start": 32, "end": 190 }
class ____: __slots__ = ('key','left','right') def __init__(self, key): self.key = key self.left = None self.right = None
Node
python
google__pytype
pytype/pytd/pytd_utils_test.py
{ "start": 10823, "end": 12752 }
class ____(parser_test_base.ParserTest): """Test pytd_utils.Print.""" def test_smoke(self): """Smoketest for printing pytd.""" ast = self.Parse(""" from typing import Any, Union c1 = ... # type: int T = TypeVar('T') class A(typing.Generic[T], object): bar = ... # type: T ...
PrintTest
python
django__django
django/db/models/functions/math.py
{ "start": 685, "end": 1819 }
class ____(NumericOutputFieldMixin, Func): function = "ATAN2" arity = 2 def as_sqlite(self, compiler, connection, **extra_context): if not getattr( connection.ops, "spatialite", False ) or connection.ops.spatial_version >= (5, 0, 0): return self.as_sql(compiler, conn...
ATan2
python
chroma-core__chroma
chromadb/test/ef/test_custom_ef.py
{ "start": 1000, "end": 3303 }
class ____(EmbeddingFunction[Embeddable]): def __call__(self, input: Embeddable) -> Embeddings: return cast(Embeddings, np.array([1, 2, 3]).tolist()) def __init__(self, *args: Any, **kwargs: Any) -> None: pass @staticmethod def name() -> str: return "custom_embedding_function_w...
CustomEmbeddingFunctionWithRegistration
python
sympy__sympy
sympy/utilities/codegen.py
{ "start": 13048, "end": 13561 }
class ____: """Base class for all "outgoing" information from a routine. Objects of this class stores a SymPy expression, and a SymPy object representing a result variable that will be used in the generated code only if necessary. """ def __init__(self, expr, result_var): self.expr = e...
ResultBase
python
plotly__plotly.py
plotly/graph_objs/mesh3d/_colorbar.py
{ "start": 233, "end": 61447 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "mesh3d" _path_str = "mesh3d.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "...
ColorBar
python
facebookresearch__faiss
tests/test_partition.py
{ "start": 5343, "end": 6861 }
class ____(unittest.TestCase, PartitionTests): def do_partition(self, n, q, maxval=65536, seed=None): #seed = 1235 if seed is None: for i in range(50): self.do_partition(n, q, maxval, i + 1234) rs = np.random.RandomState(seed) vals = rs.randint(maxval, si...
TestPartitioningUint16Min
python
google__python-fire
examples/diff/diff.py
{ "start": 1897, "end": 3189 }
class ____(object): """Provides a simple interface to the difflib module. The purpose of this simple interface is to offer a limited subset of the difflib functionality as a command line interface. """ def __init__(self, fromfile, tofile): self._fromfile = fromfile self._tofile = tofile self.fr...
DiffLibWrapper
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 17178, "end": 18239 }
class ____(graphene.Enum): TIME_WINDOW = "TIME_WINDOW" STATIC = "STATIC" MULTIPARTITIONED = "MULTIPARTITIONED" DYNAMIC = "DYNAMIC" class Meta: name = "PartitionDefinitionType" @classmethod def from_partition_def_data(cls, partition_def_data): check.inst_param(partition_def_...
GraphenePartitionDefinitionType
python
rapidsai__cudf
python/cudf_polars/cudf_polars/typing/__init__.py
{ "start": 5001, "end": 5300 }
class ____(TypedDict): kind: Literal["struct"] fields: list[_StructFieldHeader] DataTypeHeader = ( _ScalarDataTypeHeader | _DecimalDataTypeHeader | _DatetimeDataTypeHeader | _DurationDataTypeHeader | _ListDataTypeHeader | _StructDataTypeHeader )
_StructDataTypeHeader
python
dateutil__dateutil
tests/test_rrule.py
{ "start": 394, "end": 205083 }
class ____(unittest.TestCase): def _rrulestr_reverse_test(self, rule): """ Call with an `rrule` and it will test that `str(rrule)` generates a string which generates the same `rrule` as the input when passed to `rrulestr()` """ rr_str = str(rule) rrulestr_rrul...
RRuleTest
python
pydantic__pydantic
tests/test_pickle.py
{ "start": 8451, "end": 9277 }
class ____(BaseModel): model_config = ConfigDict(title='MyTitle') def model_with_config_factory() -> type: class NonImportableModelWithConfig(BaseModel): model_config = ConfigDict(title='MyTitle') return NonImportableModelWithConfig @pytest.mark.parametrize( 'model_type,use_cloudpickle', ...
ImportableModelWithConfig
python
sympy__sympy
sympy/utilities/matchpy_connector.py
{ "start": 5942, "end": 6222 }
class ____(_WildAbstract): min_length = 0 fixed_size = False def _get_srepr(expr): s = srepr(expr) s = re.sub(r"WildDot\('(\w+)'\)", r"\1", s) s = re.sub(r"WildPlus\('(\w+)'\)", r"*\1", s) s = re.sub(r"WildStar\('(\w+)'\)", r"*\1", s) return s
WildStar
python
geekcomputers__Python
Python Programs/Python Program to Reverse a linked list.py
{ "start": 249, "end": 1305 }
class ____: # Function to initialize head def __init__(self): self.head = None # Function to reverse the linked list def reverse(self): prev = None current = self.head while current is not None: next = current.next current.next = prev ...
LinkedList
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/gcp.py
{ "start": 967, "end": 1591 }
class ____(CloudEnvironment): """GCP cloud environment plugin. Updates integration test environment after delegation.""" def get_environment_config(self) -> CloudEnvironmentConfig: """Return environment configuration for use in the test environment after delegation.""" parser = configparser.Con...
GcpCloudEnvironment
python
mlflow__mlflow
mlflow/genai/scorers/builtin_scorers.py
{ "start": 2440, "end": 2553 }
class ____: messages: list["ChatMessage"] schema: type[pydantic.BaseModel] @dataclass
FieldExtractionConfig
python
doocs__leetcode
solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/Solution.py
{ "start": 0, "end": 452 }
class ____: def minTaps(self, n: int, ranges: List[int]) -> int: last = [0] * (n + 1) for i, x in enumerate(ranges): l, r = max(0, i - x), i + x last[l] = max(last[l], r) ans = mx = pre = 0 for i in range(n): mx = max(mx, last[i]) if m...
Solution
python
PyCQA__pylint
pylint/extensions/private_import.py
{ "start": 567, "end": 11194 }
class ____(BaseChecker): name = "import-private-name" msgs = { "C2701": ( "Imported private %s (%s)", "import-private-name", "Used when a private module or object prefixed with _ is imported. " "PEP8 guidance on Naming Conventions states that public attrib...
PrivateImportChecker
python
encode__django-rest-framework
rest_framework/mixins.py
{ "start": 982, "end": 1458 }
class ____: """ List a queryset. """ def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self....
ListModelMixin
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 53717, "end": 55310 }
class ____(VegaLiteSchema): """ AutoSizeParams schema wrapper. Parameters ---------- contains : Literal['content', 'padding'] Determines how size calculation should be performed, one of ``"content"`` or ``"padding"``. The default setting (``"content"``) interprets the width and heig...
AutoSizeParams
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 39135, "end": 40130 }
class ____(Blockwise): _parameters = ["frame", "other"] operation = M.combine_first @functools.cached_property def _meta(self): return make_meta( self.operation( meta_nonempty(self.frame._meta), meta_nonempty(self.other._meta), ), ...
CombineFirst
python
viewflow__viewflow
tests/fsm/test_fsm__inheritance.py
{ "start": 173, "end": 1491 }
class ____(Publication): @Publication.state.transition( source=ReviewState.NEW, target=ReviewState.APPROVED, permission=this.is_approver ) def approve(self): pass @Publication.state.transition( source=ReviewState.NEW, target=ReviewState.REJECTED, permission=this.is_approver ...
GuestPublication
python
bokeh__bokeh
src/bokeh/models/glyphs.py
{ "start": 14373, "end": 15559 }
class ____(XYGlyph, LineGlyph, FillGlyph, HatchGlyph): ''' Render ellipses. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) __example__ = "examples/reference/models/Ellipse.py" _args = ('x', '...
Ellipse
python
run-llama__llama_index
llama-index-packs/llama-index-packs-auto-merging-retriever/llama_index/packs/auto_merging_retriever/base.py
{ "start": 577, "end": 2148 }
class ____(BaseLlamaPack): """ Auto-merging Retriever pack. Build a hierarchical node graph from a set of documents, and run our auto-merging retriever. """ def __init__( self, docs: List[Document] = None, **kwargs: Any, ) -> None: """Init params.""" ...
AutoMergingRetrieverPack
python
numpy__numpy
benchmarks/benchmarks/bench_ma.py
{ "start": 6022, "end": 6696 }
class ____(Benchmark): param_names = ['margs', 'msize'] params = [[0, (0, 0), [0, -1]], ['small', 'big']] def setup(self, margs, msize): xs = np.random.uniform(-1, 1, 6).reshape(2, 3) m1 = [[True, False, False], [False, False, True]] xl = np.random.uniform(-1, 1, 100 *...
MAMethodGetItem
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/rich_jupyter_widget.py
{ "start": 1174, "end": 1279 }
class ____(JupyterWidget): """Dummy class for config inheritance. Destroyed below."""
RichIPythonWidget
python
bokeh__bokeh
tests/unit/bokeh/plotting/test__legends.py
{ "start": 3897, "end": 5353 }
class ____: @pytest.mark.parametrize('arg', [1, 2.7, None, False, [], {}]) def test_bad_arg(self, arg: Any) -> None: with pytest.raises(ValueError): bpl._handle_legend_group(arg, Legend(), GlyphRenderer()) def test_bad_source(self) -> None: with pytest.raises(ValueError): ...
Test__handle_legend_group
python
sympy__sympy
sympy/core/function.py
{ "start": 68563, "end": 73564 }
class ____(Expr): """ Lambda(x, expr) represents a lambda function similar to Python's 'lambda x: expr'. A function of several variables is written as Lambda((x, y, ...), expr). Examples ======== A simple example: >>> from sympy import Lambda >>> from sympy.abc import x >>> f ...
Lambda
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/priority_queue_test.py
{ "start": 1323, "end": 12841 }
class ____(test.TestCase): def testRoundTripInsertReadOnceSorts(self): with self.cached_session() as sess: q = data_flow_ops.PriorityQueue(2000, (dtypes.string, dtypes.string), ( (), ())) elem = np.random.randint(-5, 5, size=100).astype(np.int64) side_value_0 = np.random.rand(100).ast...
PriorityQueueTest
python
pytorch__pytorch
test/test_jit_fuser_te.py
{ "start": 101847, "end": 106964 }
class ____(TestNNCOpInfoParent): def setUp(self): super(TestNNCOpInfoParent, self).setUp() self.tensorexpr_options = TensorExprTestOptions() def tearDown(self): self.tensorexpr_options.restore() super(TestNNCOpInfoParent, self).tearDown() def te_compile(self, device, dtype,...
TestNNCOpInfo
python
PrefectHQ__prefect
src/integrations/prefect-azure/prefect_azure/workers/container_instance.py
{ "start": 7404, "end": 14106 }
class ____(BaseJobConfiguration): """ Configuration for an Azure Container Instance flow run. """ image: str = Field(default_factory=get_prefect_image_name) resource_group_name: str = Field(default=...) subscription_id: SecretStr = Field(default=...) identities: Optional[List[str]] = Field(...
AzureContainerJobConfiguration
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 5601, "end": 5955 }
class ____(BaseOperator): def execute(self, context) -> Any: pass def get_openlineage_facets_on_complete(self, task_instance) -> OperatorLineage: return OperatorLineage( inputs=INPUTS, outputs=OUTPUTS, run_facets=RUN_FACETS, job_facets=FINISHED_FA...
OperatorWithoutStart
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker_unified_studio.py
{ "start": 1221, "end": 7985 }
class ____(BaseHook): """ Interact with Sagemaker Unified Studio Workflows. This hook provides a wrapper around the Sagemaker Workflows Notebook Execution API. Examples: .. code-block:: python from airflow.providers.amazon.aws.hooks.sagemaker_unified_studio import SageMakerNotebookHook ...
SageMakerNotebookHook
python
django__django
tests/generic_views/views.py
{ "start": 7599, "end": 7682 }
class ____(BookSigningConfig, generic.DayArchiveView): pass
BookSigningDayArchive
python
ethereum__web3.py
web3/types.py
{ "start": 14043, "end": 14206 }
class ____(TypedDict): returnData: HexBytes logs: Sequence[LogReceipt] gasUsed: int status: int error: NotRequired[RPCError]
SimulateV1CallResult
python
tensorflow__tensorflow
tensorflow/python/client/session.py
{ "start": 23335, "end": 59936 }
class ____(SessionInterface): """A class for interacting with a TensorFlow computation. The BaseSession enables incremental graph building with inline execution of Operations and evaluation of Tensors. """ def __init__(self, target='', graph=None, config=None): """Constructs a new TensorFlow session. ...
BaseSession
python
doocs__leetcode
solution/2500-2599/2579.Count Total Number of Colored Cells/Solution.py
{ "start": 0, "end": 94 }
class ____: def coloredCells(self, n: int) -> int: return 2 * n * (n - 1) + 1
Solution
python
django__django
tests/admin_views/tests.py
{ "start": 69035, "end": 77144 }
class ____(AdminViewBasicTestCase): def test_custom_model_admin_templates(self): # Test custom change list template with custom extra context response = self.client.get( reverse("admin:admin_views_customarticle_changelist") ) self.assertContains(response, "var hello = 'He...
AdminCustomTemplateTests
python
ansible__ansible
lib/ansible/plugins/action/unarchive.py
{ "start": 983, "end": 4422 }
class ____(ActionBase): TRANSFERS_FILES = True def run(self, tmp=None, task_vars=None): """ handler for unarchive operations """ if task_vars is None: task_vars = dict() super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect ...
ActionModule
python
zarr-developers__zarr-python
tests/test_indexing.py
{ "start": 1402, "end": 67199 }
class ____(MemoryStore): counter: Counter[tuple[str, str]] @classmethod async def open(cls) -> CountingDict: store = await super().open() store.counter = Counter() return store async def get( self, key: str, prototype: BufferPrototype, byte_range...
CountingDict
python
jina-ai__jina
jina/importer.py
{ "start": 253, "end": 5543 }
class ____: """ A context manager for wrapping extension import and fallback. It guides the user to pip install correct package by looking up extra-requirements.txt. :param required: set to True if you want to raise the ModuleNotFound error :param logger: when not given, built-in warnings.warn will be ...
ImportExtensions
python
kamyu104__LeetCode-Solutions
Python/time-needed-to-inform-all-employees.py
{ "start": 895, "end": 1598 }
class ____(object): def numOfMinutes(self, n, headID, manager, informTime): """ :type n: int :type headID: int :type manager: List[int] :type informTime: List[int] :rtype: int """ def dfs(informTime, children, node): return (max(dfs(informT...
Solution2
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/clsregistry.py
{ "start": 10222, "end": 10998 }
class ____: __slots__ = ("__parent",) __parent: _ModuleMarker def __init__(self, parent: _ModuleMarker): self.__parent = parent def __getattr__(self, key: str) -> Union[_ModNS, Type[Any]]: try: value = self.__parent.contents[key] except KeyError: pass ...
_ModNS
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 18796, "end": 20726 }
class ____: """Check input overwrite behavior.""" real_dtypes = [np.float32, np.float64] def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw): x2 = x.copy() routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x) sig = (f"{routine.__name__}({x.dtype}{...
TestOverwrite
python
scrapy__scrapy
scrapy/core/scraper.py
{ "start": 1721, "end": 3297 }
class ____: """Scraper slot (one per running spider)""" MIN_RESPONSE_SIZE = 1024 def __init__(self, max_active_size: int = 5000000): self.max_active_size: int = max_active_size self.queue: deque[QueueTuple] = deque() self.active: set[Request] = set() self.active_size: int =...
Slot
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 28236, "end": 28830 }
class ____: """Parent class to function arguments, including both column references and values""" def __init__(self, name: str): self.name = name self.has_default = False def get_default(self, _) -> object: raise InvalidFunctionArgument(f"{self.name} has no defaults") def norm...
FunctionArg
python
facebookresearch__faiss
tests/test_rabitq.py
{ "start": 59137, "end": 61126 }
class ____(unittest.TestCase): """Test serialization/deserialization preserves behavior.""" def do_test_serialization(self, metric, nb_bits, qb): """Test that serialize/deserialize preserves search results.""" ds = create_test_dataset(d=64, nb=200, nq=10, nt=150) k = 5 # Create...
TestMultiBitRaBitQSerialization
python
great-expectations__great_expectations
great_expectations/render/renderer/column_section_renderer.py
{ "start": 17936, "end": 20435 }
class ____(ColumnSectionRenderer): def __init__(self, bullet_list_renderer=None) -> None: super().__init__() if bullet_list_renderer is None: bullet_list_renderer = {"class_name": "ExpectationSuiteBulletListContentBlockRenderer"} module_name = bullet_list_renderer.get( ...
ExpectationSuiteColumnSectionRenderer
python
PrefectHQ__prefect
src/prefect/events/schemas/automations.py
{ "start": 652, "end": 755 }
class ____(AutoEnum): Reactive = "Reactive" Proactive = "Proactive" Metric = "Metric"
Posture
python
Netflix__metaflow
metaflow/plugins/aws/step_functions/step_functions_client.py
{ "start": 125, "end": 4754 }
class ____(object): def __init__(self): from ..aws_client import get_aws_client self._client = get_aws_client("stepfunctions") def search(self, name): paginator = self._client.get_paginator("list_state_machines") return next( ( state_machine ...
StepFunctionsClient
python
getsentry__sentry
src/sentry/monitors/endpoints/project_monitor_checkin_index.py
{ "start": 786, "end": 1720 }
class ____(ProjectMonitorEndpoint, MonitorCheckInMixin): publish_status = { "GET": ApiPublishStatus.PUBLIC, } owner = ApiOwner.CRONS @extend_schema( operation_id="Retrieve Check-Ins for a Monitor by Project", parameters=[ GlobalParams.ORG_ID_OR_SLUG, Glob...
ProjectMonitorCheckInIndexEndpoint
python
ray-project__ray
rllib/offline/io_context.py
{ "start": 330, "end": 2543 }
class ____: """Class containing attributes to pass to input/output class constructors. RLlib auto-sets these attributes when constructing input/output classes, such as InputReaders and OutputWriters. """ @PublicAPI def __init__( self, log_dir: Optional[str] = None, conf...
IOContext
python
PyCQA__pylint
tests/functional/u/undefined/undefined_variable.py
{ "start": 3312, "end": 3347 }
class ____: """ No op """
Ancestor
python
readthedocs__readthedocs.org
readthedocs/projects/tests/test_views.py
{ "start": 12455, "end": 14338 }
class ____(TestCase): def setUp(self): self.user = get(User) self.project = get(Project, slug="project", users=[self.user], repo="https://github.com/user/repo") self.url = reverse("projects_edit", args=[self.project.slug]) self.client.force_login(self.user) @mock.patch("readthed...
TestProjectEditView
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 6570, "end": 6679 }
class ____(_Trimmable): """Raised when a test fails a health check. See |HealthCheck|."""
FailedHealthCheck
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 62286, "end": 63928 }
class ____(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torch.FloatTensor` of sh...
SequenceClassifierOutput
python
euske__pdfminer
pdfminer/rijndael.py
{ "start": 44715, "end": 45443 }
class ____: """ >>> key = bytes.fromhex('00010203050607080a0b0c0d0f101112') >>> ciphertext = bytes.fromhex('d8f532538289ef7d06b506a4fd5be9c9') >>> RijndaelDecryptor(key, 128).decrypt(ciphertext).hex() '506812a45f08c889b97f5980038b8359' """ def __init__(self, key, keybits=256): asse...
RijndaelDecryptor
python
getsentry__sentry
src/sentry/dashboards/endpoints/organization_dashboard_details.py
{ "start": 2725, "end": 7887 }
class ____(OrganizationDashboardBase): publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieve an Organization's Custom Dashboard", parameters=[GlobalParams.ORG_ID_...
OrganizationDashboardDetailsEndpoint
python
PrefectHQ__prefect
src/prefect/server/events/services/actions.py
{ "start": 642, "end": 1850 }
class ____(RunInEphemeralServers, Service): """Runs the actions triggered by automations""" consumer_task: asyncio.Task[None] | None = None @classmethod def service_settings(cls) -> ServicesBaseSetting: return get_current_settings().server.services.triggers async def start(self) -> NoRetu...
Actions
python
ray-project__ray
rllib/models/tf/layers/noisy_layer.py
{ "start": 305, "end": 3961 }
class ____(tf.keras.layers.Layer if tf else object): r"""A Layer that adds learnable Noise to some previous layer's outputs. Consists of: - a common dense layer: y = w^{T}x + b - a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) , where \epsilon are random variable...
NoisyLayer
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 54271, "end": 72604 }
class ____(TestDetrPreTrainedModel): def __init__(self, config: TestDetrConfig): super().__init__(config) # Create backbone + positional encoding backbone = TestDetrConvEncoder(config) position_embeddings = build_position_encoding(config) self.backbone = TestDetrConvModel(ba...
TestDetrModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/components.py
{ "start": 4445, "end": 5427 }
class ____(StateMigration): cursor_field: str config: Config cursor_format: Optional[str] = None def __init__(self, cursor_field, config: Config, cursor_format: Optional[str] = None): self.cursor_field = cursor_field self.cursor_format = cursor_format self.config = config d...
MigrateEmptyStringState
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py
{ "start": 2393, "end": 2447 }
class ____: f: F = F() g: G = G() @attr.frozen
I
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/server.py
{ "start": 13744, "end": 53923 }
class ____(DagsterApiServicer): # The loadable_target_origin is currently Noneable to support instaniating a server. # This helps us test the ping methods, and incrementally migrate each method to # the target passed in here instead of passing in a target in the argument. def __init__( self, ...
DagsterApiServer
python
facebook__pyre-check
client/error.py
{ "start": 4902, "end": 9626 }
class ____: path: Optional[Path] description: str code: int start_line: Optional[int] start_column: Optional[int] stop_line: Optional[int] stop_column: Optional[int] @staticmethod def from_json(error_json: Dict[str, Any]) -> "TaintConfigurationError": try: error_...
TaintConfigurationError
python
huggingface__transformers
src/transformers/models/falcon_h1/modular_falcon_h1.py
{ "start": 36414, "end": 36783 }
class ____(LlamaMLP): def __init__(self, config: FalconH1Config): super().__init__(config) self.gate_multiplier, self.down_multiplier = config.mlp_multipliers def forward(self, x): y = self.up_proj(x) * self.act_fn(self.gate_proj(x) * self.gate_multiplier) y = self.down_proj(y) ...
FalconH1MLP
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 18033, "end": 19493 }
class ____(TestCase): """Tests for ``random_permutation()``""" def test_full_permutation(self): """ensure every item from the iterable is returned in a new ordering 15 elements have a 1 in 1.3 * 10e12 of appearing in sorted order, so we fix a seed value just to be sure. """ ...
RandomPermutationTests
python
mlflow__mlflow
mlflow/utils/autologging_utils/events.py
{ "start": 413, "end": 2390 }
class ____: """ A wrapper around AutologgingEventLogger for DRY: - Store common arguments to avoid passing them to each logger method - Catches exceptions thrown by the logger and logs them NB: We could not modify the AutologgingEventLogger class directly because it is used in Databrick...
AutologgingEventLoggerWrapper
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 107108, "end": 111457 }
class ____(CPointerBaseType): # base_type CType Reference type is_ptr = 1 is_unowned_view = True default_value = "0" exception_value = "NULL" def __hash__(self): return hash(self.base_type) + 27 # arbitrarily chosen offset def __eq__(self, other): if isi...
CPtrType
python
tensorflow__tensorflow
tensorflow/python/keras/layers/pooling.py
{ "start": 40104, "end": 42054 }
class ____(GlobalPooling2D): """Global average pooling operation for spatial data. Examples: >>> input_shape = (2, 4, 5, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalAveragePooling2D()(x) >>> print(y.shape) (2, 3) Args: data_format: A string, one of `channels_l...
GlobalAveragePooling2D
python
marshmallow-code__marshmallow
performance/benchmark.py
{ "start": 455, "end": 787 }
class ____(Schema): id = fields.Int(dump_only=True) first = fields.Str() last = fields.Str() book_count = fields.Float() age = fields.Float() address = fields.Str() full_name = fields.Method("get_full_name") def get_full_name(self, author): return f"{author.last}, {author.first}...
AuthorSchema
python
pandas-dev__pandas
pandas/tests/arrays/sparse/test_reductions.py
{ "start": 7922, "end": 9641 }
class ____: @pytest.mark.parametrize( "arr,argmax_expected,argmin_expected", [ (SparseArray([1, 2, 0, 1, 2]), 1, 2), (SparseArray([-1, -2, 0, -1, -2]), 2, 1), (SparseArray([np.nan, 1, 0, 0, np.nan, -1]), 1, 5), (SparseArray([np.nan, 1, 0, 0, np.nan, 2]...
TestArgmaxArgmin
python
redis__redis-py
redis/connection.py
{ "start": 70692, "end": 71595 }
class ____(ABC): @abstractmethod def get_protocol(self): pass @abstractmethod def reset(self): pass @abstractmethod @deprecated_args( args_to_warn=["*"], reason="Use get_connection() without args instead", version="5.3.0", ) def get_connection( ...
ConnectionPoolInterface
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_userroles_details.py
{ "start": 170, "end": 1165 }
class ____(APITestCase): endpoint = "sentry-api-0-userroles-details" def setUp(self) -> None: super().setUp() self.user = self.create_user(is_superuser=True) self.login_as(user=self.user, superuser=True) self.add_user_permission(self.user, "users.admin") def test_fails_with...
UserRolesDetailsTest