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
django__django
django/templatetags/i18n.py
{ "start": 385, "end": 659 }
class ____(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = [ (k, translation.gettext(v)) for k, v in settings.LANGUAGES ] return ""
GetAvailableLanguagesNode
python
huggingface__transformers
src/transformers/models/bert/modeling_bert.py
{ "start": 22166, "end": 22473 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score
BertOnlyNSPHead
python
ray-project__ray
doc/source/serve/doc_code/tutorial_sklearn.py
{ "start": 1332, "end": 2231 }
class ____: def __init__(self, model_path: str, label_path: str): with open(model_path, "rb") as f: self.model = pickle.load(f) with open(label_path) as f: self.label_list = json.load(f) async def __call__(self, starlette_request: Request) -> Dict: payload = awai...
BoostingModel
python
python__mypy
mypy/plugin.py
{ "start": 8717, "end": 9479 }
class ____: """ A common plugin API (shared between semantic analysis and type checking phases) that all plugin hooks get independently of the context. """ # Global mypy options. # Per-file options can be only accessed on various # XxxPluginInterface classes. options: Options @abst...
CommonPluginApi
python
langchain-ai__langchain
libs/core/langchain_core/prompts/message.py
{ "start": 393, "end": 2636 }
class ____(Serializable, ABC): """Base class for message prompt templates.""" @classmethod def is_lc_serializable(cls) -> bool: """Return `True` as this class is serializable.""" return True @classmethod def get_lc_namespace(cls) -> list[str]: """Get the namespace of the La...
BaseMessagePromptTemplate
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_pretty.py
{ "start": 3926, "end": 4002 }
class ____: def __repr__(self): return "Breaking(\n)"
BreakingRepr
python
getsentry__sentry
src/sentry/taskworker/scheduler/schedules.py
{ "start": 1037, "end": 3100 }
class ____(Schedule): """ Task schedules defined as `datetime.timedelta` intervals If a timedelta interval loses it's last_run state, it will assume that at least one interval has been missed, and it will become due immediately. After the first spawn, the schedule will align to to the interval's d...
TimedeltaSchedule
python
tensorflow__tensorflow
tensorflow/python/ops/lookup_ops.py
{ "start": 79931, "end": 93637 }
class ____(LookupInterface): """A mutable hash table with faster lookups and higher memory usage. Data can be inserted by calling the `insert` method and removed by calling the `remove` method. It does not support initialization via the init method. Compared to `MutableHashTable`, `DenseHashTable` offers gene...
DenseHashTable
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 202520, "end": 202624 }
class ____( _Int4MultiRangeTests, _MultiRangeTypeCompilation ): pass
Int4MultiRangeCompilationTest
python
huggingface__transformers
src/transformers/models/smolvlm/modular_smolvlm.py
{ "start": 6827, "end": 6899 }
class ____(Idefics3ImageProcessorFast): pass
SmolVLMImageProcessorFast
python
ipython__ipython
IPython/core/ultratb.py
{ "start": 44962, "end": 46650 }
class ____(ListTB): """Extension which holds some state: the last exception value""" last_syntax_error: BaseException | None def __init__(self, *, theme_name): super().__init__(theme_name=theme_name) self.last_syntax_error = None def __call__(self, etype, value, elist): self.l...
SyntaxTB
python
doocs__leetcode
solution/0600-0699/0628.Maximum Product of Three Numbers/Solution.py
{ "start": 0, "end": 199 }
class ____: def maximumProduct(self, nums: List[int]) -> int: nums.sort() a = nums[-1] * nums[-2] * nums[-3] b = nums[-1] * nums[0] * nums[1] return max(a, b)
Solution
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_bases.py
{ "start": 1529, "end": 9722 }
class ____: @patch('bokeh.core.property.bases.Property.validate') def test_is_valid_supresses_validation_detail(self, mock_validate: MagicMock) -> None: p = bcpb.Property() p.is_valid(None) assert mock_validate.called assert mock_validate.call_args[0] == (None, False) def te...
TestProperty
python
oauthlib__oauthlib
oauthlib/openid/connect/core/exceptions.py
{ "start": 2506, "end": 2748 }
class ____(OpenIDClientError): """ The request parameter contains an invalid Request Object. """ error = 'invalid_request_object' description = 'The request parameter contains an invalid Request Object.'
InvalidRequestObject
python
pydata__xarray
xarray/tests/test_utils.py
{ "start": 1816, "end": 6419 }
class ____: @pytest.fixture(autouse=True) def setup(self): self.x = {"a": "A", "b": "B"} self.y = {"c": "C", "b": "B"} self.z = {"a": "Z"} def test_equivalent(self): assert utils.equivalent(0, 0) assert utils.equivalent(np.nan, np.nan) assert utils.equivalent...
TestDictionaries
python
ZoranPandovski__al-go-rithms
data_structures/heap/Python/BinaryHeaps/BinaryHeaps.py
{ "start": 2953, "end": 4074 }
class ____(Heap): def __init__(self): self.array = [-float("inf")] self.size = 0 def insert(self, el): self.array.append(el) self.size += 1 ind = self.size while el < self.array[self.parent(ind)]: self.array[ind], self.array[self.parent(ind)] = self.a...
MinHeap
python
scrapy__scrapy
tests/test_request_cb_kwargs.py
{ "start": 1656, "end": 5746 }
class ____(MockServerSpider): name = "kwargs" custom_settings = { "DOWNLOADER_MIDDLEWARES": { InjectArgumentsDownloaderMiddleware: 750, }, "SPIDER_MIDDLEWARES": { InjectArgumentsSpiderMiddleware: 750, }, } checks: list[bool] = [] async def st...
KeywordArgumentsSpider
python
gevent__gevent
src/gevent/tests/test__pool.py
{ "start": 260, "end": 4194 }
class ____(unittest.TestCase): klass = gevent.pool.Pool def test_apply_async(self): done = Event() def some_work(_): done.set() pool = self.klass(2) pool.apply_async(some_work, ('x', )) done.wait() def test_apply(self): value = 'return value' ...
TestCoroutinePool
python
pypa__setuptools
setuptools/_vendor/more_itertools/more.py
{ "start": 88959, "end": 101134 }
class ____: """ :func:`run_length.encode` compresses an iterable with run-length encoding. It yields groups of repeated items with the count of how many times they were repeated: >>> uncompressed = 'abbcccdddd' >>> list(run_length.encode(uncompressed)) [('a', 1), ('b', 2), ('c',...
run_length
python
huggingface__transformers
src/transformers/generation/configuration_utils.py
{ "start": 74064, "end": 76461 }
class ____: """ Class that holds arguments relative to `torch.compile` behavior, when using automatic compilation in `generate`. See [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html) for more details on the arguments. Args: fullgraph (`bool`, *optional*, defaults t...
CompileConfig
python
google__python-fire
fire/test_components.py
{ "start": 4378, "end": 4455 }
class ____: def as_bool(self, arg=False): return bool(arg)
BoolConverter
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/stateful_random_ops_test.py
{ "start": 1883, "end": 28763 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): super(StatefulRandomOpsTest, self).setUp() physical_devices = config.list_physical_devices("CPU") config.set_logical_device_configuration( physical_devices[0], [ context.LogicalDeviceConfiguration(), conte...
StatefulRandomOpsTest
python
kamyu104__LeetCode-Solutions
Python/minimum-total-distance-traveled.py
{ "start": 1104, "end": 1799 }
class ____(object): def minimumTotalDistance(self, robot, factory): """ :type robot: List[int] :type factory: List[List[int]] :rtype: int """ robot.sort(), factory.sort() dp = [float("inf")]*(len(robot)+1) # dp[j] at i: min of factory[:i+1] and robot[:j] ...
Solution2
python
marshmallow-code__marshmallow
src/marshmallow/validate.py
{ "start": 23138, "end": 23931 }
class ____(NoneOf): """Validator which fails if ``value`` is a sequence and any element in the sequence is a member of the sequence passed as ``iterable``. Empty input is considered valid. :param iterable: Same as :class:`NoneOf`. :param error: Same as :class:`NoneOf`. .. versionadded:: 3.6.0 ...
ContainsNoneOf
python
PyCQA__pylint
tests/regrtest_data/max_inferable_limit_for_classes/nodes/roles.py
{ "start": 160, "end": 221 }
class ____(ColumnArgumentRole): ...
ColumnArgumentOrKeyRole
python
realpython__materials
nearbyshops/shops/apps.py
{ "start": 36, "end": 85 }
class ____(AppConfig): name = "shops"
ShopsConfig
python
google__jax
jax/_src/config.py
{ "start": 57713, "end": 82605 }
class ____(enum.StrEnum): STANDARD = 'standard' STRICT = 'strict' numpy_dtype_promotion = enum_class_state( name='jax_numpy_dtype_promotion', enum_class=NumpyDtypePromotion, default=NumpyDtypePromotion.STANDARD, help=('Specify the rules used for implicit type promotion in operations ' 'be...
NumpyDtypePromotion
python
doocs__leetcode
solution/3300-3399/3335.Total Characters in String After Transformations I/Solution.py
{ "start": 0, "end": 437 }
class ____: def lengthAfterTransformations(self, s: str, t: int) -> int: f = [[0] * 26 for _ in range(t + 1)] for c in s: f[0][ord(c) - ord("a")] += 1 for i in range(1, t + 1): f[i][0] = f[i - 1][25] f[i][1] = f[i - 1][0] + f[i - 1][25] for j i...
Solution
python
aio-libs__aiohttp
aiohttp/web_runner.py
{ "start": 10502, "end": 12604 }
class ____(BaseRunner[Request]): """Web Application runner""" __slots__ = ("_app",) def __init__( self, app: Application, *, handle_signals: bool = False, access_log_class: type[AbstractAccessLogger] = AccessLogger, **kwargs: Any, ) -> None: if n...
AppRunner
python
sympy__sympy
sympy/sets/sets.py
{ "start": 65807, "end": 80353 }
class ____(Set): """ Represents the disjoint union (also known as the external disjoint union) of a finite number of sets. Examples ======== >>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol >>> A = FiniteSet(1, 2, 3) >>> B = Interval(0, 5) >>> DisjointUnion(A, B)...
DisjointUnion
python
walkccc__LeetCode
solutions/1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers/1577.py
{ "start": 0, "end": 644 }
class ____: def numTriplets(self, nums1: list[int], nums2: list[int]) -> int: def countTriplets(A: list[int], B: list[int]): """Returns the number of triplet (i, j, k) if A[i]^2 == B[j] * B[k].""" res = 0 count = collections.Counter(B) for a in A: target = a * a for b, fre...
Solution
python
ray-project__ray
python/ray/tests/test_output.py
{ "start": 13437, "end": 13552 }
class ____: def f(self): print("hi stdout") print("hi stderr", file=sys.stderr) @ray.remote
Actor1
python
keras-team__keras
keras/src/trainers/data_adapters/array_slicing.py
{ "start": 5933, "end": 6434 }
class ____(Sliceable): def __getitem__(self, indices): return self.array.iloc[indices] @classmethod def convert_to_numpy(cls, x): return x.to_numpy() @classmethod def convert_to_tf_dataset_compatible(cls, x): return cls.convert_to_numpy(x) @classmethod def convert_...
PandasSliceable
python
huggingface__transformers
src/transformers/integrations/tensor_parallel.py
{ "start": 43344, "end": 45147 }
class ____(TensorParallelLayer): """ Applies Expert Parallelism to MoE experts by loading the correct experts on each device. """ def __init__(self, **kwargs): super().__init__(**kwargs) self.use_dtensor = False def shard_tensor( self, param, param_type=None...
GroupedGemmParallel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 552638, "end": 552997 }
class ____(sgqlc.types.Type): """Autogenerated return type of DeleteBranchProtectionRule""" __schema__ = github_schema __field_names__ = ("client_mutation_id",) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutat...
DeleteBranchProtectionRulePayload
python
PyCQA__pylint
doc/data/messages/u/unsupported-membership-test/good.py
{ "start": 0, "end": 145 }
class ____: FRUITS = ["apple", "orange"] def __contains__(self, name): return name in self.FRUITS apple = "apple" in Fruit()
Fruit
python
huggingface__transformers
tests/utils/import_structures/import_structure_register_with_comments.py
{ "start": 1036, "end": 1230 }
class ____: def __init__(self): pass @requires(backends=("torch",)) # That's a statement def b2(): pass @requires( backends=( "torch", ) ) # That's a statement
B2
python
ray-project__ray
python/ray/_common/tests/test_formatters.py
{ "start": 142, "end": 4042 }
class ____: def test_empty_record(self, shutdown_only): formatter = JSONFormatter() record = logging.makeLogRecord({}) formatted = formatter.format(record) record_dict = json.loads(formatted) should_exist = [ "process", "asctime", "levelna...
TestJSONFormatter
python
ray-project__ray
python/ray/util/spark/start_hook_base.py
{ "start": 0, "end": 417 }
class ____: def __init__(self, is_global): self.is_global = is_global def get_default_temp_root_dir(self): return "/tmp" def on_ray_dashboard_created(self, port): pass def on_cluster_created(self, ray_cluster_handler): pass def on_spark_job_created(self, job_group...
RayOnSparkStartHook
python
django-import-export__django-import-export
tests/core/tests/test_widgets.py
{ "start": 9322, "end": 9752 }
class ____(TestCase): """https://github.com/django-import-export/django-import-export/pull/94""" def setUp(self): self.date = date(1868, 8, 13) self.widget = widgets.DateWidget("%d.%m.%Y") def test_render(self): self.assertEqual(self.widget.render(self.date), "13.08.1868") def...
DateWidgetBefore1900Test
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataproc.py
{ "start": 156041, "end": 158807 }
class ____: @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_execute(self, mock_hook): page_token = "page_token" page_size = 42 filter = 'batch_id=~"a-batch-id*" AND create_time>="2023-07-05T14:25:04.643818Z"' order_by = "create_time desc" op = DataprocListBatc...
TestDataprocListBatchesOperator
python
ray-project__ray
rllib/examples/envs/custom_env_render_method.py
{ "start": 3622, "end": 7876 }
class ____(gym.Env): """Example of a custom env, for which we specify rendering behavior.""" def __init__(self, config): self.end_pos = config.get("corridor_length", 10) self.max_steps = config.get("max_steps", 100) self.cur_pos = 0 self.steps = 0 self.action_space = Dis...
CustomRenderedCorridorEnv
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_types.py
{ "start": 4532, "end": 5753 }
class ____(fixtures.TestBase): __only_on__ = "mssql" __backend__ = True def test_result_processor(self): expected = datetime.date(2000, 1, 2) self._assert_result_processor(expected, "2000-01-02") def _assert_result_processor(self, expected, value): mssql_date_type = _MSDate() ...
MSDateTypeTest
python
PrefectHQ__prefect
src/integrations/prefect-docker/prefect_docker/host.py
{ "start": 212, "end": 643 }
class ____(docker.DockerClient): """ Allow context managing Docker Client, but also allow it to be instantiated without. """ def __enter__(self): """ Enters the context manager. """ return self def __exit__(self, exc_type, exc_val, exc_tb): """ Exits...
_ContextManageableDockerClient
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/view/primitives.py
{ "start": 451, "end": 739 }
class ____(NamedTuple): start: Point end: Point def draw(self, **attributes) -> str: return tag( "line", x1=self.start.x, y1=self.start.y, x2=self.end.x, y2=self.end.y, **attributes, )
Line
python
conda__conda
conda/api.py
{ "start": 6777, "end": 10278 }
class ____: """ **Beta** While in beta, expect both major and minor changes across minor releases. High-level management and usage of repodata.json for subdirs. """ def __init__(self, channel): """ **Beta** While in beta, expect both major and minor changes across minor releases. ...
SubdirData
python
huggingface__transformers
src/transformers/models/sew/modeling_sew.py
{ "start": 14393, "end": 15746 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.attention = SEWAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, co...
SEWEncoderLayer
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 39320, "end": 41183 }
class ____(BaseDataset): """ Feature: Datasets auto-created from data produce the correct types """ def assert_string_type(self, ds, cset, variable=True): tid = ds.id.get_type() self.assertEqual(type(tid), h5py.h5t.TypeStringID) self.assertEqual(tid.get_cset(), cset) ...
TestAutoCreate
python
django__django
tests/queries/tests.py
{ "start": 177974, "end": 178170 }
class ____(TestCase): def test_ticket_24278(self): School.objects.create() qs = School.objects.filter(Q(pk__in=()) | Q()) self.assertSequenceEqual(qs, [])
TestTicket24279
python
kamyu104__LeetCode-Solutions
Python/remove-linked-list-elements.py
{ "start": 128, "end": 576 }
class ____(object): # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): dummy = ListNode(float("-inf")) dummy.next = head prev, curr = dummy, dummy.next while curr: if curr.val == val: prev...
Solution
python
kamyu104__LeetCode-Solutions
Python/erect-the-fence.py
{ "start": 170, "end": 1791 }
class ____(object): def outerTrees(self, points): """ :type points: List[List[int]] :rtype: List[List[int]] """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. p...
Solution
python
pypa__warehouse
tests/unit/accounts/test_forms.py
{ "start": 15355, "end": 32300 }
class ____: def test_validate(self, metrics): captcha_service = pretend.stub( enabled=False, verify_response=pretend.call_recorder(lambda _: None), ) user_service = pretend.stub( check_password=lambda userid, password, tags=None: True, find_use...
TestRegistrationForm
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 30218, "end": 30519 }
class ____(BaseModel): dag_id: str map_index: int | None = None task_ids: list[str] | None = None task_group_id: str | None = None logical_dates: list[AwareDatetime] | None = None run_ids: list[str] | None = None type: Literal["GetTaskStates"] = "GetTaskStates"
GetTaskStates
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/preferences.py
{ "start": 955, "end": 7579 }
class ____(QDialog): """ Dialog window for setting viewing preferences of dataframe or array editor. Set the attributes `float_format`, `varying_background` and `global_algo` to set the options, if necessary. Call `exec_()` to show the dialog to the user and allow them to interact. Finally, read th...
PreferencesDialog
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 117312, "end": 128869 }
class ____( roles.SelectStatementRole, roles.DMLSelectRole, roles.CompoundElementRole, roles.InElementRole, HasCTE, SupportsCloneAnnotations, Selectable, ): """Base class for SELECT statements. This includes :class:`_expression.Select`, :class:`_expression.CompoundSelect` and ...
SelectBase
python
pytorch__pytorch
test/dynamo/test_base_hop.py
{ "start": 8991, "end": 10020 }
class ____(torch.nn.Module): def forward(self, L_y_: "f32[3, 4]"): l_y_ = L_y_ subgraph_0 = self.subgraph_0 invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_y_, scheme = 'nf4'); subgraph_0 = l_y_ = None getitem: "f32[3, 4]" = invoke_quant_test[0]; invoke_...
GraphModule
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 471486, "end": 471963 }
class ____(sgqlc.types.Type): """Autogenerated return type of AddVerifiableDomain""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "domain") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mut...
AddVerifiableDomainPayload
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_detector_count.py
{ "start": 874, "end": 1022 }
class ____(TypedDict): active: int deactive: int total: int @region_silo_endpoint @extend_schema(tags=["Workflows"])
DetectorCountResponse
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/projection_queries/snippets.py
{ "start": 1037, "end": 1187 }
class ____(ndb.Model): type = ndb.StringProperty() # E.g., 'home', 'work' street = ndb.StringProperty() city = ndb.StringProperty()
Address
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/examples/complete-scrapegraph-examples.py
{ "start": 498, "end": 6812 }
class ____(BaseModel): """Schema for news article information.""" title: str = Field(description="Article title") author: str = Field(description="Article author", default="N/A") date: str = Field(description="Publication date", default="N/A") summary: str = Field(description="Article summary", def...
NewsArticle
python
chroma-core__chroma
chromadb/errors.py
{ "start": 1906, "end": 2093 }
class ____(ChromaError): @overrides def code(self) -> int: return 404 @classmethod @overrides def name(cls) -> str: return "NotFoundError"
NotFoundError
python
neetcode-gh__leetcode
python/0678-valid-parenthesis-string.py
{ "start": 30, "end": 725 }
class ____: def checkValidString(self, s: str) -> bool: dp = {(len(s), 0): True} # key=(i, leftCount) -> isValid def dfs(i, left): if i == len(s) or left < 0: return left == 0 if (i, left) in dp: return dp[(i, left)] if s[i] == "...
Solution
python
pytorch__pytorch
torch/testing/_internal/common_pruning.py
{ "start": 6147, "end": 7112 }
class ____(nn.Module): r"""Model with only Conv2d layers, some with bias, some in a Sequential and some following. Activation function modules in between each Sequential layer, functional activations called in-between each outside layer. Used to test pruned Conv2d-Bias-Activation-Conv2d fusion.""" ...
Conv2dActivation
python
nedbat__coveragepy
tests/test_report_core.py
{ "start": 1052, "end": 2315 }
class ____(CoverageTest): """Tests of render_report.""" def test_stdout(self) -> None: fake = FakeReporter(output="Hello!\n") msgs: list[str] = [] res = render_report("-", fake, [pytest, "coverage"], msgs.append) assert res == 17.25 assert fake.morfs == [pytest, "coverag...
RenderReportTest
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/list.py
{ "start": 51, "end": 215 }
class ____(ListField): def to_internal_value(self, data): if data == "": return "" return super().to_internal_value(data)
EmptyListField
python
python-openxml__python-docx
src/docx/opc/phys_pkg.py
{ "start": 2318, "end": 3375 }
class ____(PhysPkgReader): """Implements |PhysPkgReader| interface for a zip file OPC package.""" def __init__(self, pkg_file): super(_ZipPkgReader, self).__init__() self._zipf = ZipFile(pkg_file, "r") def blob_for(self, pack_uri): """Return blob corresponding to `pack_uri`. ...
_ZipPkgReader
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/llama_index/embeddings/oci_data_science/base.py
{ "start": 541, "end": 11992 }
class ____(BaseEmbedding): """ Embedding class for OCI Data Science models. This class provides methods to generate embeddings using models deployed on Oracle Cloud Infrastructure (OCI) Data Science. It supports both synchronous and asynchronous requests and handles authentication, batching, and ot...
OCIDataScienceEmbedding
python
astropy__astropy
astropy/utils/iers/tests/test_iers.py
{ "start": 4689, "end": 7779 }
class ____: @classmethod def teardown_class(cls): iers.IERS_A.close() def test_simple(self): # Test the IERS A reader. It is also a regression tests that ensures # values do not get overridden by IERS B; see #4933. iers_tab = iers.IERS_A.open(IERS_A_EXCERPT) assert ...
TestIERS_AExcerpt
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 34770, "end": 36091 }
class ____(ModelOutput): r""" multi_scale_features (`tuple(torch.FloatTensor)`): Tuple of multi-scale features of scales [1/8, 1/16, 1/32] and shape `(batch_size, num_channels, height, width)`from the Multi-Scale Deformable Attenntion based Pixel Decoder. mask_features (`torch.FloatTensor`):...
OneFormerPixelDecoderOutput
python
paramiko__paramiko
paramiko/packet.py
{ "start": 1351, "end": 1584 }
class ____(Exception): """ Exception indicating a rekey is needed. """ pass def first_arg(e): arg = None if type(e.args) is tuple and len(e.args) > 0: arg = e.args[0] return arg
NeedRekeyException
python
scipy__scipy
scipy/_lib/tests/test__util.py
{ "start": 11496, "end": 16209 }
class ____: def test_policy(self): data = np.array([1, 2, 3, np.nan]) assert _contains_nan(data) # default policy is "propagate" assert _contains_nan(data, nan_policy="propagate") assert _contains_nan(data, nan_policy="omit") assert not _contains_nan(data[:3]) asser...
TestContainsNaN
python
buildout__buildout
src/zc/buildout/easy_install.py
{ "start": 12250, "end": 65817 }
class ____(object): _versions = {} _required_by = {} _picked_versions = {} _download_cache = None _install_from_cache = False _prefer_final = True _use_dependency_links = True _allow_picked_versions = True _store_required_by = False _allow_unknown_extras = False _namespace_p...
Installer
python
Pylons__pyramid
docs/quick_tutorial/request_response/tutorial/tests.py
{ "start": 47, "end": 969 }
class ____(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def test_home(self): from .views import TutorialViews request = testing.DummyRequest() inst = TutorialViews(request) response = inst.home() ...
TutorialViewTests
python
gwtw__py-sorting
test/heapsort_test.py
{ "start": 403, "end": 741 }
class ____(unittest.TestCase, BaseCustomComparisonSortTest, BasePositiveIntegerSortTest, BaseNegativeIntegerSortTest, BaseStringSortTest): def setUp(self): self.sort = heapsort.sort if __name__ == '__main__': unittest.m...
HeapsortSortTest
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 5045, "end": 7585 }
class ____(ToolBase): """ Toggleable tool. Every time it is triggered, it switches between enable and disable. Parameters ---------- ``*args`` Variable length argument to be used by the Tool. ``**kwargs`` `toggled` if present and True, sets the initial state of the Tool ...
ToolToggleBase
python
walkccc__LeetCode
solutions/2330. Valid Palindrome IV/2330.py
{ "start": 0, "end": 254 }
class ____: def makePalindrome(self, s: str) -> bool: change = 0 l = 0 r = len(s) - 1 while l < r: if s[l] != s[r]: change += 1 if change > 2: return False l += 1 r -= 1 return True
Solution
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/triggers/wasb.py
{ "start": 3944, "end": 7456 }
class ____(BaseTrigger): """ Check for the existence of a blob with the given prefix in the provided container. WasbPrefixSensorTrigger is fired as a deferred class with params to run the task in trigger. :param container_name: name of the container in which the blob should be searched for :param ...
WasbPrefixSensorTrigger
python
huggingface__transformers
src/transformers/models/emu3/modeling_emu3.py
{ "start": 28385, "end": 30868 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.num_resolutions = len(config.channel_multiplier) self.num_res_blocks = config.num_res_blocks quant_channels = config.embed_dim block_in = config.base_channels * config.channel_multiplier[-1] ...
Emu3VQVAEUpBlock
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/step_function.py
{ "start": 952, "end": 1514 }
class ____(BaseAwsLink): """Helper class for constructing link to State Machine details page.""" name = "State Machine Details" key = "_state_machine_details" format_str = ( BASE_AWS_CONSOLE_LINK + "/states/home?region={region_name}#/statemachines/view/{state_machine_arn}" ) def format...
StateMachineDetailsLink
python
gevent__gevent
src/gevent/_ffi/watcher.py
{ "start": 17895, "end": 17949 }
class ____(object): _watcher_type = 'idle'
IdleMixin
python
ipython__ipython
IPython/core/autocall.py
{ "start": 1319, "end": 1593 }
class ____(IPyAutocall): """An autocallable object which will be added to the user namespace so that exit, exit(), quit or quit() are all valid ways to close the shell.""" rewrite = False def __call__(self): self._ip.ask_exit()
ExitAutocall
python
huggingface__transformers
tests/generation/test_candidate_generator.py
{ "start": 4280, "end": 4760 }
class ____: """A simple mock tokenizer class that supports weak references.""" def __init__(self, vocab=None): self._vocab = vocab or {} def get_vocab(self): return self._vocab def __call__(self, text, add_special_tokens=True): # Mock implementation of the __call__ method ...
MockTokenizer
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 26598, "end": 27467 }
class ____(Projection): r"""Base class for conic projections. In conic projections, the sphere is thought to be projected onto the surface of a cone which is then opened out. In a general sense, the pixel-to-sky transformation is defined as: .. math:: \phi &= \arg\left(\frac{Y_0 - y}{R_\...
Conic
python
pandas-dev__pandas
pandas/tests/indexes/numeric/test_astype.py
{ "start": 134, "end": 3618 }
class ____: def test_astype_float64_to_uint64(self): # GH#45309 used to incorrectly return Index with int64 dtype idx = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64) result = idx.astype("u8") expected = Index([0, 5, 10, 15, 20], dtype=np.uint64) tm.assert_index_equal(...
TestAstype
python
PrefectHQ__prefect
src/prefect/cache_policies.py
{ "start": 10890, "end": 12749 }
class ____(CachePolicy): """ Policy that computes a cache key based on a hash of the runtime inputs provided to the task.. """ exclude: list[str] = field(default_factory=lambda: []) def compute_key( self, task_ctx: TaskRunContext, inputs: dict[str, Any], flow_parame...
Inputs
python
huggingface__transformers
src/transformers/models/tapas/modeling_tapas.py
{ "start": 21236, "end": 21934 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.transform = TapasPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_si...
TapasLMPredictionHead
python
imageio__imageio
imageio/plugins/feisem.py
{ "start": 725, "end": 3360 }
class ____(TiffFormat): """See :mod:`imageio.plugins.feisem`""" def _can_write(self, request): return False # FEI-SEM only supports reading class Reader(TiffFormat.Reader): def _get_data(self, index=0, discard_watermark=True, watermark_height=70): """Get image and metadata fro...
FEISEMFormat
python
getsentry__sentry
src/sentry/snuba/query_sources.py
{ "start": 24, "end": 129 }
class ____(Enum): FRONTEND = "frontend" API = "api" SENTRY_BACKEND = "sentry_backend"
QuerySource
python
huggingface__transformers
src/transformers/models/llava_next/image_processing_llava_next.py
{ "start": 1602, "end": 3709 }
class ____(ImagesKwargs, total=False): r""" image_grid_pinpoints (`list[list[int]]`, *optional*): A list of possible resolutions to use for processing high resolution images. The best resolution is selected based on the original size of the image. Can be overridden by `image_grid_pinpoints` in t...
LlavaNextImageProcessorKwargs
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 8949, "end": 10580 }
class ____(GeneratedAirbyteDestination): @public def __init__( self, name: str, host: str, port: int, database: str, username: str, password: Optional[str] = None, jdbc_url_params: Optional[str] = None, ssl: Optional[bool] = None, ): ...
ClickhouseDestination
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 10126, "end": 59297 }
class ____( DialectKWArgs, HasSchemaAttr, TableClause, inspection.Inspectable["Table"] ): r"""Represent a table in a database. e.g.:: mytable = Table( "mytable", metadata, Column("mytable_id", Integer, primary_key=True), Column("value", String(50)), ...
Table
python
simonw__datasette
datasette/app.py
{ "start": 77147, "end": 88408 }
class ____: def __init__(self, datasette, routes): self.ds = datasette self.routes = routes or [] async def __call__(self, scope, receive, send): # Because we care about "foo/bar" v.s. "foo%2Fbar" we decode raw_path ourselves path = scope["path"] raw_path = scope.get("ra...
DatasetteRouter
python
astropy__astropy
astropy/timeseries/binned.py
{ "start": 408, "end": 16645 }
class ____(BaseTimeSeries): """ A class to represent binned time series data in tabular form. `~astropy.timeseries.BinnedTimeSeries` provides a class for representing time series as a collection of values of different quantities measured in time bins (for time series with values sampled at spec...
BinnedTimeSeries
python
tensorflow__tensorflow
tensorflow/python/framework/composite_tensor_test.py
{ "start": 3232, "end": 17464 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ {'structure': CT(0), 'expected': [0], 'paths': [('CT',)]}, {'structure': CT('a'), 'expected': ['a'], 'paths': [('CT',)]}, {'structure': CT(['a', 'b', 'c']), 'expected': [...
CompositeTensorTest
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_not_be_null_and_column_to_not_be_empty.py
{ "start": 1260, "end": 13504 }
class ____(ColumnMapExpectation): """Expect column values to not be null and column to not be empty. To be counted as an exception, values must be explicitly null or missing, such as a NULL in PostgreSQL or an np.NaN in pandas. Empty strings don't count as null unless they have been coerced to a null type....
ExpectColumnValuesToNotBeNullAndColumnToNotBeEmpty
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/snowflake/pandas_and_pyspark.py
{ "start": 406, "end": 1648 }
class ____(SnowflakeIOManager): @staticmethod def type_handlers(): """type_handlers should return a list of the TypeHandlers that the I/O manager can use. Here we return the SnowflakePandasTypeHandler and SnowflakePySparkTypeHandler so that the I/O manager can store Pandas DataFrames and...
SnowflakePandasPySparkIOManager
python
Farama-Foundation__Gymnasium
tests/utils/test_env_checker_with_gym.py
{ "start": 281, "end": 443 }
class ____(gym.Env): def __init__(self): self.action_space = gym.spaces.Discrete(2) self.observation_space = gym.spaces.Discrete(2)
IncorrectEnv
python
airbytehq__airbyte
airbyte-integrations/connectors/source-s3/source_s3/source.py
{ "start": 199, "end": 3274 }
class ____(SourceFilesAbstractSpec, BaseModel): class Config: title = "S3 Source Spec" class S3Provider(BaseModel): class Config: title = "S3: Amazon Web Services" # SourceFilesAbstractSpec field are ordered 10 apart to allow subclasses to insert their own spec's fields ...
SourceS3Spec
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/shared.py
{ "start": 723, "end": 2214 }
class ____(SearchStrategy[Ex]): def __init__(self, base: SearchStrategy[Ex], key: Hashable | None = None): super().__init__() self.key = key self.base = base def __repr__(self) -> str: if self.key is not None: return f"shared({self.base!r}, key={self.key!r})" ...
SharedStrategy
python
xlwings__xlwings
xlwings/constants.py
{ "start": 128856, "end": 146077 }
class ____(Enum): # With Python 3.11+ you can use StrEnum generic = "Generic" accessibility = "Accessibility" airplane = "Airplane" airplane_take_off = "AirplaneTakeOff" album = "Album" alert = "Alert" alert_urgent = "AlertUrgent" animal = "Animal" animal_cat = "AnimalCat" an...
ObjectHandleIcons