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/convbert/modeling_convbert.py
{ "start": 15983, "end": 18576 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = ConvBertAttention(config) self.is_decoder = config.is_decoder self.add_cross_atte...
ConvBertLayer
python
sphinx-doc__sphinx
sphinx/ext/doctest.py
{ "start": 8486, "end": 9898 }
class ____(doctest.DocTestRunner): def summarize( # type: ignore[override] self, out: Callable[[str], None], verbose: bool | None = None ) -> tuple[int, int]: string_io = StringIO() old_stdout = sys.stdout sys.stdout = string_io try: res = super().summarize(v...
SphinxDocTestRunner
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 1155, "end": 1342 }
class ____(_MultiVectorConfigCreateBase): enabled: bool = Field(default=True) @staticmethod @abstractmethod def encoding_name() -> str: ...
_MultiVectorEncodingConfigCreate
python
kamyu104__LeetCode-Solutions
Python/merge-nodes-in-between-zeros.py
{ "start": 29, "end": 124 }
class ____(object): def __init__(self, val=0, next=None): pass # linked list
ListNode
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 17953, "end": 18250 }
class ____(_Symmetric): """ Constrain to positive-semidefinite matrices. """ def check(self, value): sym_check = super().check(value) if not sym_check.all(): return sym_check return torch.linalg.eigvalsh(value).ge(0).all(-1)
_PositiveSemidefinite
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/graphql_client.py
{ "start": 10298, "end": 13938 }
class ____(HTTPAdapter): def __init__(self, *args, **kwargs): self.socket_options = kwargs.pop("socket_options", None) super().__init__(*args, **kwargs) def init_poolmanager(self, *args, **kwargs): if self.socket_options is not None: kwargs["socket_options"] = self.socket_op...
HTTPAdapterWithSocketOptions
python
encode__django-rest-framework
tests/test_routers.py
{ "start": 13009, "end": 13675 }
class ____(TestCase): """ Ensure `@action` decorator raises an except when applied to an existing route """ def test_exception_raised_when_action_applied_to_existing_route(self): class TestViewSet(viewsets.ModelViewSet): @action(methods=['post'], detail=True) def re...
TestActionAppliedToExistingRoute
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/event/base.py
{ "start": 14905, "end": 15247 }
class ____(dispatcher[_ET]): def __get__(self, obj: Any, cls: Type[Any]) -> Any: if obj is None: return self.dispatch if hasattr(obj, "_slots_dispatch"): return obj._slots_dispatch disp = self.dispatch._for_instance(obj) obj._slots_dispatch = disp re...
slots_dispatcher
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/dataform.py
{ "start": 1512, "end": 27370 }
class ____(GoogleBaseHook): """Hook for Google Cloud DataForm APIs.""" def get_dataform_client(self) -> DataformClient: """Retrieve client library object that allow access to Cloud Dataform service.""" return DataformClient(credentials=self.get_credentials()) @GoogleBaseHook.fallback_to_de...
DataformHook
python
pallets__werkzeug
src/werkzeug/datastructures/range.py
{ "start": 4707, "end": 7034 }
class ____: """Represents the content range header. .. versionadded:: 0.7 """ def __init__( self, units: str | None, start: int | None, stop: int | None, length: int | None = None, on_update: cabc.Callable[[ContentRange], None] | None = None, ) -> No...
ContentRange
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
{ "start": 30822, "end": 36137 }
class ____(ABC): @abstractmethod @contextmanager def yield_graphql_context( self, class_scoped_context ) -> Generator[WorkspaceRequestContext, None, None]: pass @contextmanager def graphql_context_for_request(self, request): check.param_invariant( isinstance(...
_GraphQLContextTestSuite
python
jina-ai__jina
jina/serve/stream/helper.py
{ "start": 120, "end": 535 }
class ____: """Class used to wrap a count integer so that it can be updated inside methods. .. code-block:: python def count_increment(i: int, rc: _RequestsCounter): i += 1 rc.count += 1 c_int = 0 c_rc = _RequestsCounter() count_increment(c_int, c_rc) ...
_RequestsCounter
python
doocs__leetcode
solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/Solution2.py
{ "start": 0, "end": 232 }
class ____: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: cnt = [0] * 102 for x in nums: cnt[x + 1] += 1 s = list(accumulate(cnt)) return [s[x] for x in nums]
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 1117175, "end": 1126906 }
class ____(FieldChannelMixin, core.SecondaryFieldDef): r""" YError schema wrapper. A field definition of a secondary channel that shares a scale with another primary channel. For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``. Parameters ---------- shorthand : ...
YError
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 28311, "end": 29483 }
class ____(AssetSelection): selected_asset_check_keys: Sequence[AssetCheckKey] def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: return set() def resolve_checks_inner( # pyright: ignore[reportIncompatibleMethodOverride] self,...
AssetCheckKeysSelection
python
walkccc__LeetCode
solutions/1896. Minimum Cost to Change the Final Value of Expression/1896.py
{ "start": 0, "end": 1787 }
class ____: def minOperationsToFlip(self, expression: str) -> int: stack = [] # [(the expression, the cost to toggle the expression)] for e in expression: if e in '(&|': # These aren't expressions, so the cost is meaningless. stack.append((e, 0)) continue if e == ')': ...
Solution
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/constants.py
{ "start": 2686, "end": 3270 }
class ____(SimpleNamespace): """Constants used by Solr clients.""" QUERY_ALL: Final[str] = "*:*" """Solr query requesting all documents to be returned.""" DEFAULT_TIMEOUT_SEC: Final[int] = 60 """Default request timeout to Solr in seconds.""" SOLR_ISO8601_DATE_FORMAT: Final[str] = "%Y-%m-%dT%H...
SolrConstants
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 60431, "end": 60720 }
class ____: #: Node ID -> summary per node #: If the data is not required to be orgnized per node, it will contain #: a single key, "cluster". node_id_to_summary: Dict[str, Union[TaskSummaries, ActorSummaries, ObjectSummaries]] @dataclass(init=not IS_PYDANTIC_2)
StateSummary
python
plotly__plotly.py
_plotly_utils/basevalidators.py
{ "start": 13335, "end": 19758 }
class ____(BaseValidator): """ "enumerated": { "description": "Enumerated value type. The available values are listed in `values`.", "requiredOpts": [ "values" ], "otherOpts": [ "dflt", "coerceNumber", "array...
EnumeratedValidator
python
scipy__scipy
benchmarks/benchmarks/spatial.py
{ "start": 2175, "end": 2493 }
class ____(PresortedDataSetup): params = PresortedDataSetup.params[:-1] param_names = PresortedDataSetup.param_names[:-1] def setup(self, *args): super().setup(*args, None) def time_build(self, mnr, balanced, order): cKDTree(self.data.get(order), balanced_tree=balanced)
BuildUnbalanced
python
tensorflow__tensorflow
tensorflow/python/distribute/experimental/dtensor_util.py
{ "start": 3962, "end": 12790 }
class ____(distribute_lib.ReplicaContext): """ReplicaContext for strategy that is backed by DTensor. Since the DTensor is operated in the global context, most of the methods from existing strategy ReplicaContext is not applicable since they need to access local values. For now most of the methods in this class...
DTensorReplicaContext
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 108378, "end": 110528 }
class ____(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmin.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) ...
TestFmin
python
doocs__leetcode
solution/3700-3799/3758.Convert Number Words to Digits/Solution.py
{ "start": 0, "end": 608 }
class ____: def convertNumber(self, s: str) -> str: d = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ] i, n = 0, len(s) ans = [...
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/strings_ops/unsorted_segment_join_op_test.py
{ "start": 1376, "end": 10885 }
class ____(UnicodeTestCase, parameterized.TestCase): def test_basic_np_array(self): inputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']] segment_ids = [1, 0, 1] num_segments = 2 separator = ':' output_array = [['Y', '6', '6'], ['Y:p', 'q:G', 'c:a']] res = self.evaluate( strin...
UnsortedSegmentJoinOpTest
python
kamyu104__LeetCode-Solutions
Python/check-if-an-original-string-exists-given-two-encoded-strings.py
{ "start": 3233, "end": 5137 }
class ____(object): def possiblyEquals(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ def memoization(s1, s2, i, j, k, lookup): if (i, j, k) not in lookup: if i == len(s1) and j == len(s2): lookup[(i, j,...
Solution2
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 115618, "end": 117943 }
class ____(Request): """ For each task, get a list of metrics for which the requested event type was reported :param tasks: Task IDs :type tasks: Sequence[str] :param event_type: Event type :type event_type: EventTypeEnum """ _service = "events" _action = "get_task_metrics" _ve...
GetTaskMetricsRequest
python
tornadoweb__tornado
tornado/locale.py
{ "start": 18832, "end": 21120 }
class ____(Locale): """Locale implementation using the `gettext` module.""" def __init__(self, code: str, translations: gettext.NullTranslations) -> None: self.ngettext = translations.ngettext self.gettext = translations.gettext # self.gettext must exist before __init__ is called, since...
GettextLocale
python
pytorch__pytorch
torch/_dynamo/variables/functions.py
{ "start": 64800, "end": 66208 }
class ____(NestedUserFunctionVariable): def __init__( self, wrapped: Any, context: "ContextWrappingVariable", **kwargs: Any, ) -> None: kwargs.pop("fn_name", None) kwargs.pop("code", None) kwargs.pop("f_globals", None) kwargs.pop("defaults", None) ...
WrappedNestedUserFunctionVariable
python
kamyu104__LeetCode-Solutions
Python/find-minimum-time-to-reach-last-room-ii.py
{ "start": 89, "end": 1282 }
class ____(object): def minTimeToReach(self, moveTime): """ :type moveTime: List[List[int]] :rtype: int """ def dijkstra(start, target): DIRECTIONS = [(1, 0), (0, 1), (-1, 0), (0, -1)] dist = [[float("inf")]*len(moveTime[0]) for _ in xrange(len(moveTim...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_bank_accounts.py
{ "start": 4675, "end": 15393 }
class ____(TestCase): @HttpMocker() def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _customers_request().with_expands(_EXPANDS).with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(), _customer...
FullRefreshTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 262, "end": 470 }
class ____(graphene.ObjectType): key = graphene.NonNull(graphene.String) value = graphene.NonNull(graphene.String) class Meta: name = "MetadataItemDefinition"
GrapheneMetadataItemDefinition
python
django__django
tests/auth_tests/urls.py
{ "start": 2964, "end": 3016 }
class ____(EmptyResponseBaseView): pass
PublicView
python
streamlit__streamlit
lib/streamlit/elements/widgets/data_editor.py
{ "start": 4059, "end": 20624 }
class ____: """DataEditorSerde is used to serialize and deserialize the data editor state.""" def deserialize(self, ui_value: str | None) -> EditingState: data_editor_state: EditingState = cast( "EditingState", { "edited_rows": {}, "added_rows": [...
DataEditorSerde
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/__init__.py
{ "start": 13976, "end": 14502 }
class ____: """Configuration for the environment.""" def __init__( self, env_vars: t.Optional[dict[str, str]] = None, ansible_vars: t.Optional[dict[str, t.Any]] = None, module_defaults: t.Optional[dict[str, dict[str, t.Any]]] = None, callback_plugins: t.Optional[list[str...
CloudEnvironmentConfig
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 219227, "end": 220043 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, datasetId: str, clean: Optional[bool] = None): """Airbyte Source for Apify Dataset. Documentation can be found at https://docs.airbyte.com/integrations/sources/apify-dataset Args: name (str): The name...
ApifyDatasetSource
python
getsentry__sentry
src/sentry/sentry_apps/api/bases/sentryapps.py
{ "start": 4355, "end": 7521 }
class ____(IntegrationPlatformEndpoint): permission_classes: tuple[type[BasePermission], ...] = (SentryAppsAndStaffPermission,) def _get_organization_slug(self, request: Request): organization_slug = request.data.get("organization") if not organization_slug or not isinstance(organization_slug, ...
SentryAppsBaseEndpoint
python
huggingface__transformers
tests/models/fuyu/test_processing_fuyu.py
{ "start": 26304, "end": 27684 }
class ____(unittest.TestCase): def setUp(self): """ Adding a mix of present and absent images. """ self.image_input = torch.randn([1, 1, 3, 64, 64]) self.image_present = torch.tensor([[1]]) self.image_unpadded_h = torch.tensor([[45]]) # Adjusted for subsequence of 1...
TestProcessImagesForModelInput
python
huggingface__transformers
tests/models/bit/test_modeling_bit.py
{ "start": 1353, "end": 5463 }
class ____: def __init__( self, parent, batch_size=3, image_size=32, num_channels=3, embeddings_size=10, hidden_sizes=[8, 16, 32, 64], depths=[1, 1, 2, 1], is_training=True, use_labels=True, hidden_act="relu", num_labels...
BitModelTester
python
ansible__ansible
lib/ansible/modules/service_facts.py
{ "start": 15438, "end": 17869 }
class ____(BaseService): def query_rcctl(self, cmd): svcs = [] rc, stdout, stderr = self.module.run_command("%s ls %s" % (self.rcctl_path, cmd)) if 'needs root privileges' in stderr.lower(): self.module.warn('rcctl requires root privileges') else: for svc in ...
OpenBSDScanService
python
tensorflow__tensorflow
tensorflow/python/data/benchmarks/benchmark_base.py
{ "start": 1076, "end": 9638 }
class ____(test.Benchmark): """Base class for dataset benchmarks.""" def _run_eager_benchmark(self, iterable, iters, warmup): """Benchmark the iterable in eager mode. Runs the iterable `iters` times. In each iteration, the benchmark measures the time it takes to go execute the iterable. Args: ...
DatasetBenchmarkBase
python
django__django
django/db/backends/sqlite3/creation.py
{ "start": 207, "end": 6784 }
class ____(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings...
DatabaseCreation
python
doocs__leetcode
solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/Solution.py
{ "start": 0, "end": 238 }
class ____: def hasAllCodes(self, s: str, k: int) -> bool: n = len(s) m = 1 << k if n - k + 1 < m: return False ss = {s[i : i + k] for i in range(n - k + 1)} return len(ss) == m
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 530037, "end": 530358 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("ProjectV2View", graphql_name="node")
ProjectV2ViewEdge
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks_test.py
{ "start": 51452, "end": 53425 }
class ____(test.TestCase): def test_not_wait_for_step_zero(self): with ops.Graph().as_default(): training_util.get_or_create_global_step() hook = basic_session_run_hooks.GlobalStepWaiterHook(wait_until_step=0) hook.begin() with session_lib.Session() as sess: # Before run should re...
GlobalStepWaiterHookTest
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 27058, "end": 28761 }
class ____(test.Benchmark): def _benchmarkAdjustSaturation(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_...
AdjustSaturationBenchmark
python
pydantic__pydantic
tests/mypy/modules/frozen_field.py
{ "start": 291, "end": 434 }
class ____(Parent): child_attr: str = Field(exclude=True) @property def parent_attr(self) -> str: return self.child_attr
Child
python
ray-project__ray
doc/source/serve/doc_code/http_guide/websockets_example.py
{ "start": 189, "end": 895 }
class ____: @app.websocket("/") async def echo(self, ws: WebSocket): await ws.accept() try: while True: text = await ws.receive_text() await ws.send_text(text) except WebSocketDisconnect: print("Client disconnected.") serve_app =...
EchoServer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/external.py
{ "start": 5398, "end": 6434 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.ID) name = graphene.NonNull(graphene.String) loadStatus = graphene.NonNull(GrapheneRepositoryLocationLoadStatus) updateTimestamp = graphene.NonNull(graphene.Float) versionKey = graphene.NonNull(graphene.String) permissions = graphe...
GrapheneWorkspaceLocationStatusEntry
python
PrefectHQ__prefect
src/prefect/server/database/configurations.py
{ "start": 1437, "end": 3523 }
class ____: """A test utility which tracks the connections given out by a connection pool, to make it easy to see which connections are currently checked out and open.""" all_connections: dict[AdaptedConnection, list[str]] open_connections: dict[AdaptedConnection, list[str]] left_field_closes: dict...
ConnectionTracker
python
tensorflow__tensorflow
tensorflow/python/framework/stack.py
{ "start": 965, "end": 4338 }
class ____(threading.local, Generic[T]): """A thread-local stack of objects for providing implicit defaults.""" def __init__(self): super().__init__() self._enforce_nesting = True self.stack: list[T] = [] def get_default(self) -> Optional[T]: return self.stack[-1] if self.stack else None def ...
DefaultStack
python
mahmoud__boltons
boltons/statsutils.py
{ "start": 6396, "end": 29923 }
class ____: """The ``Stats`` type is used to represent a group of unordered statistical datapoints for calculations such as mean, median, and variance. Args: data (list): List or other iterable containing numeric values. default (float): A value to be returned when a given ...
Stats
python
pytorch__pytorch
.github/scripts/runner_determinator.py
{ "start": 3053, "end": 3455 }
class ____(NamedTuple): rollout_perc: float = ( 0 # Percentage of workflows to experiment on when user is not opted-in. ) all_branches: bool = ( False # If True, the experiment is also enabled on the exception branches ) default: bool = ( True # If True, the experiment is ...
Experiment
python
huggingface__transformers
src/transformers/models/grounding_dino/modeling_grounding_dino.py
{ "start": 27456, "end": 32191 }
class ____(nn.Module): """ Multiscale deformable attention as proposed in Deformable DETR. """ def __init__(self, config: GroundingDinoConfig, num_heads: int, n_points: int): super().__init__() self.attn = MultiScaleDeformableAttention() if config.d_model % num_heads != 0: ...
GroundingDinoMultiscaleDeformableAttention
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_comprehend.py
{ "start": 1145, "end": 1394 }
class ____: def test_service_waiters(self): assert "pii_entities_detection_job_complete" in ComprehendHook().list_waiters() assert "create_document_classifier_complete" in ComprehendHook().list_waiters()
TestComprehendCustomWaiters
python
catalyst-team__catalyst
catalyst/contrib/data/reader.py
{ "start": 1245, "end": 3088 }
class ____(IReader): """ Numeric data reader abstraction. Reads a single float, int, str or other from data """ def __init__( self, input_key: str, output_key: Optional[str] = None, dtype: Type = np.float32, default_value: float = None, one_hot_classe...
ScalarReader
python
mahmoud__boltons
boltons/funcutils.py
{ "start": 24018, "end": 35994 }
class ____: """The FunctionBuilder type provides an interface for programmatically creating new functions, either based on existing functions or from scratch. Values are passed in at construction or set as attributes on the instance. For creating a new function based of an existing one, see the...
FunctionBuilder
python
conda__conda
tests/plugins/test_subcommands.py
{ "start": 645, "end": 5942 }
class ____: name: str summary: str configure_parser: Callable | None = None def custom_command(self, args): pass @plugins.hookimpl def conda_subcommands(self): yield CondaSubcommand( name=self.name, summary=self.summary, action=self.custom_co...
SubcommandPlugin
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 11375, "end": 11811 }
class ____(GroupType): type_id = 1004 slug = "performance_render_blocking_asset_span" description = "Large Render Blocking Asset" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.FRONTEND.value noise_config = NoiseConfig() default_priority = PriorityLevel.LOW releas...
PerformanceRenderBlockingAssetSpanGroupType
python
astropy__astropy
astropy/cosmology/_src/funcs/optimize.py
{ "start": 1181, "end": 19640 }
class ____(TypedDict): # noqa: PYI049 """Keyword arguments for :func:`~astropy.cosmology.z_at_value`. Note that :func:`~astropy.cosmology.z_at_value` can accept most of these arguments as positional arguments. This TypedDict is useful for type annotating arguments to other functions that pass them to ...
_ZAtValueKWArgs
python
google__pytype
pytype/rewrite/frame_test.py
{ "start": 2623, "end": 5477 }
class ____(FrameTestBase): def test_store_local_in_module_frame(self): frame = self._make_frame('', name='__main__') frame.step() var = self._const_var(5) frame.store_local('x', var) stored = frame.load_local('x') self.assertEqual(stored, var.with_name('x')) self.assertEqual(stored, frame...
LoadStoreTest
python
huggingface__transformers
src/transformers/models/git/modeling_git.py
{ "start": 12854, "end": 15346 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([GitLayer(config, i) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tenso...
GitEncoder
python
jpadilla__pyjwt
tests/test_compressed_jwt.py
{ "start": 49, "end": 1237 }
class ____(PyJWT): def _decode_payload(self, decoded): return json.loads( # wbits=-15 has zlib not worry about headers of crc's zlib.decompress(decoded["payload"], wbits=-15).decode("utf-8") ) def test_decodes_complete_valid_jwt_with_compressed_payload(): # Test case fr...
CompressedPyJWT
python
doocs__leetcode
solution/0700-0799/0710.Random Pick with Blacklist/Solution.py
{ "start": 0, "end": 555 }
class ____: def __init__(self, n: int, blacklist: List[int]): self.k = n - len(blacklist) self.d = {} i = self.k black = set(blacklist) for b in blacklist: if b < self.k: while i in black: i += 1 self.d[b] = i ...
Solution
python
doocs__leetcode
solution/0600-0699/0654.Maximum Binary Tree/Solution2.py
{ "start": 192, "end": 663 }
class ____: def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: def dfs(l, r): if l > r: return None val = tree.query(1, l, r) root = TreeNode(val) root.left = dfs(l, d[val] - 1) root.right = dfs(d[val] + 1,...
Solution
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_distribution_to_match_benfords_law.py
{ "start": 1326, "end": 6181 }
class ____(ColumnAggregateMetricProvider): """ MetricProvider tests whether data matches Benford's Law Fraud Detection Algorithm. Uses a Chi-Square Goodness of Fit test with an 80@ p-value """ metric_name = "column.custom.DistributionMatchesBenfordsLaw" value_keys = tuple() @column_ag...
ColumnDistributionMatchesBenfordsLaw
python
numpy__numpy
numpy/polynomial/tests/test_symbol.py
{ "start": 219, "end": 1533 }
class ____: """ Test polynomial creation with symbol kwarg. """ c = [1, 2, 3] def test_default_symbol(self): p = poly.Polynomial(self.c) assert_equal(p.symbol, 'x') @pytest.mark.parametrize(('bad_input', 'exception'), ( ('', ValueError), ('3', ValueError), ...
TestInit
python
django__django
django/views/generic/list.py
{ "start": 5177, "end": 6310 }
class ____(MultipleObjectMixin, View): """ Base view for displaying a list of objects. This requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not all...
BaseListView
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/executor_definition.py
{ "start": 1489, "end": 2687 }
class ____(PyEnum): """An ExecutorDefinition can include a list of requirements that the system uses to check whether the executor will be able to work for a particular job execution. """ # The passed in IJob must be reconstructable across process boundaries RECONSTRUCTABLE_PIPELINE = ( # This nee...
ExecutorRequirement
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 108845, "end": 109619 }
class ____(TestCase): def test_zero_dimension(self): # Test resolution to issue #5663 a = np.zeros((3, 0)) b = np.zeros((0, 4)) td = np.tensordot(a, b, (1, 0)) assert_array_equal(td, np.dot(a, b)) def test_zero_dimension_einsum(self): # Test resolution to issue #...
TestTensordot
python
numpy__numpy
numpy/lib/tests/test_io.py
{ "start": 107817, "end": 108005 }
class ____: def __init__(self, base): self.base = base def write(self, s): return self.base.write(s) def flush(self): return self.base.flush()
JustWriter
python
google__jax
jax/_src/api.py
{ "start": 71451, "end": 77723 }
class ____(NamedTuple): flat_fun: lu.WrappedFun in_tree: PyTreeDef out_tree: Callable[[], PyTreeDef] flat_args: Sequence[Any] donated_invars: Sequence[bool] in_axes_flat: Sequence[int | None] local_axis_size: int out_axes_thunk: Callable devices: Sequence[xc.Device] | None global_axis_size: int is...
PmapCallInfo
python
SmileyChris__easy-thumbnails
easy_thumbnails/management/commands/thumbnail_cleanup.py
{ "start": 5216, "end": 6342 }
class ____(BaseCommand): help = """ Deletes thumbnails that no longer have an original file. """ def add_arguments(self, parser): parser.add_argument( '--dry-run', action='store_true', dest='dry_run', default=False, help='Dry run the execution...
Command
python
tensorflow__tensorflow
tensorflow/python/dlpack/dlpack_test.py
{ "start": 1899, "end": 4492 }
class ____(parameterized.TestCase, test.TestCase): @parameterized.named_parameters(GetNamedTestParameters()) def testRoundTrip(self, dtype, shape): np.random.seed(42) if dtype == np.bool_: np_array = np.random.randint(0, 1, shape, np.bool_) else: np_array = np.random.randint(0, 10, shape) ...
DLPackTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 328753, "end": 330795 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateCheckRun""" __schema__ = github_schema __field_names__ = ( "repository_id", "check_run_id", "name", "details_url", "external_id", "status", "started_at", "conclusion", ...
UpdateCheckRunInput
python
py-pdf__pypdf
pypdf/constants.py
{ "start": 8011, "end": 8317 }
class ____: """ Table 4.4. Table 8 in the 2.0 reference. """ PREDICTOR = "/Predictor" # integer COLORS = "/Colors" # integer BITS_PER_COMPONENT = "/BitsPerComponent" # integer COLUMNS = "/Columns" # integer EARLY_CHANGE = "/EarlyChange" # integer
LzwFilterParameters
python
sphinx-doc__sphinx
sphinx/builders/linkcheck.py
{ "start": 26528, "end": 27327 }
class ____(HTMLParser): """Specialised HTML parser that looks for a specific anchor.""" def __init__(self, search_anchor: str) -> None: super().__init__() self.search_anchor = search_anchor self.found = False def handle_starttag(self, tag: Any, attrs: Any) -> None: for key...
AnchorCheckParser
python
apache__airflow
task-sdk/src/airflow/sdk/exceptions.py
{ "start": 5624, "end": 5718 }
class ____(BaseException): """Raise when the task execution times-out."""
AirflowTaskTimeout
python
mlflow__mlflow
mlflow/pyfunc/scoring_server/__init__.py
{ "start": 11426, "end": 15558 }
class ____(NamedTuple): response: str status: int mimetype: str def invocations(data, content_type, model, input_schema): type_parts = list(map(str.strip, content_type.split(";"))) mime_type = type_parts[0] parameter_value_pairs = type_parts[1:] parameter_values = { key: value for ...
InvocationsResponse
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 141897, "end": 145361 }
class ____(test.TestCase): def _testRandom(self, dtype): # Random dims of rank 5 shape = np.random.randint(1, 5, size=5) # Random number of tensors, but always > 1. num_tensors = np.random.randint(2, 10) # Random dim to concat on concat_dim = np.random.randint(5) params = {} if dtype ...
ConcatOpTest
python
getsentry__sentry
tests/sentry/tasks/test_code_owners.py
{ "start": 805, "end": 12006 }
class ____(TestCase): def setUp(self) -> None: self.login_as(user=self.user) self.team = self.create_team( organization=self.organization, slug="tiger-team", members=[self.user] ) self.project = self.project = self.create_project( organization=self.organizat...
CodeOwnersTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 925315, "end": 925882 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveEnterpriseIdentityProvider""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "identity_provider") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the c...
RemoveEnterpriseIdentityProviderPayload
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 284420, "end": 288444 }
class ____(TypedDict, total=False): """ :class:`altair.TitleConfig` ``TypedDict`` wrapper. Parameters ---------- align Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or ``"right"``. anchor The anchor position for placing the title and subtitle...
TitleConfigKwds
python
ApeWorX__ape
src/ape/pytest/warnings.py
{ "start": 111, "end": 483 }
class ____(Warning): """ Occurs when fixtures disrupt isolation causing performance degradation. """ def warn_invalid_isolation(): message = ( "Invalid isolation; Ensure session|package|module|class scoped fixtures " "run earlier. Rebasing fixtures is costly." ) warnings.warn(m...
InvalidIsolationWarning
python
scrapy__scrapy
scrapy/spidermiddlewares/referer.py
{ "start": 3313, "end": 3794 }
class ____(ReferrerPolicy): """ https://www.w3.org/TR/referrer-policy/#referrer-policy-no-referrer The simplest policy is "no-referrer", which specifies that no referrer information is to be sent along with requests made from a particular request client to any origin. The header will be omitted ent...
NoReferrerPolicy
python
ApeWorX__ape
src/ape/managers/converters.py
{ "start": 903, "end": 1549 }
class ____(ConverterAPI): """ A converter that converts ``str`` to ``HexBytes``. NOTE: This utility converter ensures that all bytes args can accept hex too """ def is_convertible(self, value: Any) -> bool: return ( (isinstance(value, str) and is_hex(value)) or isins...
HexConverter
python
google__pytype
pytype/pytd/main_test.py
{ "start": 213, "end": 2527 }
class ____(unittest.TestCase): """Test pytd/main.py.""" def setUp(self): super().setUp() # Save the value of sys.argv (which will be restored in tearDown), so that # tests can overwrite it. self._sys_argv = sys.argv def tearDown(self): super().tearDown() sys.argv = self._sys_argv def ...
TestPytdTool
python
pytorch__pytorch
torch/_inductor/runtime/triton_heuristics.py
{ "start": 141480, "end": 141951 }
class ____(GridExpr): def generate(self, meta: dict[str, int]) -> None: for candidate in self.inductor_meta["precomputed_grids"]: if all(meta.get(k) == v for k, v in candidate["config"].items()): self.x_grid, self.y_grid, self.z_grid = candidate[self.mode] return ...
PrecomputedGrid
python
google__pytype
pytype/pytd/codegen/namedtuple.py
{ "start": 133, "end": 1427 }
class ____: """Construct a class for a new named tuple.""" # This is called from the pyi parser, to convert a namedtuple constructed by a # functional constructor into a NamedTuple subclass. def __init__(self, base_name, fields, generated_classes): # Handle previously defined NamedTuples with the same name...
NamedTuple
python
python__mypy
mypy/nodes.py
{ "start": 102349, "end": 134397 }
class ____(SymbolNode): """The type structure of a single class. Each TypeInfo corresponds one-to-one to a ClassDef, which represents the AST of the class. In type-theory terms, this is a "type constructor", and if the class is generic then it will be a type constructor of higher kind. Where t...
TypeInfo
python
kamyu104__LeetCode-Solutions
Python/stable-subarrays-with-equal-boundary-and-interior-sum.py
{ "start": 75, "end": 715 }
class ____(object): def countStableSubarrays(self, capacity): """ :type capacity: List[int] :rtype: int """ L = 3 cnt = collections.defaultdict(lambda: collections.defaultdict(int)) result = prefix = prefix2 = 0 for i in xrange(len(capacity)): ...
Solution
python
numba__numba
numba/core/errors.py
{ "start": 1972, "end": 2099 }
class ____(NumbaWarning): """ Warning category for using an experimental feature. """
NumbaExperimentalFeatureWarning
python
django__django
tests/utils_tests/test_module_loading.py
{ "start": 327, "end": 2852 }
class ____(unittest.TestCase): def test_loader(self): "Normal module existence can be tested" test_module = import_module("utils_tests.test_module") test_no_submodule = import_module("utils_tests.test_no_submodule") # An importable child self.assertTrue(module_has_submodule(...
DefaultLoader
python
PrefectHQ__prefect
tests/test_schedules.py
{ "start": 3089, "end": 3826 }
class ____: def test_rrule_schedule_creation(self): rrule = "RRULE:FREQ=DAILY;INTERVAL=1" schedule = RRule(rrule) assert schedule.rrule == rrule assert schedule.timezone is None assert schedule.active is True assert schedule.parameters == {} def test_rrule_schedu...
TestRRuleSchedule
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/base.py
{ "start": 107691, "end": 107950 }
class ____(TypedDict): """Represents a reflected named type.""" name: str """Name of the type.""" schema: str """The schema of the type.""" visible: bool """Indicates if this type is in the current search path."""
ReflectedNamedType
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 42455, "end": 47941 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) dbt_commands: Optional[list[str]] = Field( None, description=( "An array of commands to execute for jobs with the dbt task, for example" ...
RunParameters
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows.py
{ "start": 214962, "end": 215846 }
class ____(object): # https://github.com/argoproj/argo-events/blob/master/api/sensor.md#argoproj.io/v1alpha1.TriggerTemplate def __init__(self, name): tree = lambda: defaultdict(tree) self.payload = tree() self.payload["name"] = name def k8s_trigger(self, k8s_trigger): self...
TriggerTemplate
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 6603, "end": 10612 }
class ____(StringField): """A field that validates input as an email address.""" USER_REGEX = LazyRegexCompiler( # `dot-atom` defined in RFC 5322 Section 3.2.3. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # `quoted-string` defined in RFC 5322 Section 3.2.4. ...
EmailField
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 42237, "end": 49556 }
class ____(QueryTest, AssertsCompiledSQL): @testing.combinations( lambda s, User: s.query(User).limit(2), lambda s, User: s.query(User).filter(User.id == 1).offset(2), lambda s, User: s.query(User).limit(2).offset(2), ) def test_no_limit_offset(self, test_case): User = self.c...
InvalidGenerationsTest
python
kubernetes-client__python
kubernetes/client/models/v1_job_list.py
{ "start": 383, "end": 6726 }
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...
V1JobList
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run_event.py
{ "start": 121, "end": 297 }
class ____(str, Enum): """Event severity levels.""" CRITICAL = "CRITICAL" ERROR = "ERROR" WARNING = "WARNING" INFO = "INFO" DEBUG = "DEBUG"
RunEventLevel