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/gpt_sw3/tokenization_gpt_sw3.py
{ "start": 456, "end": 10047 }
class ____(SentencePieceBackend): """ Construct an GPTSw3 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding thos...
GPTSw3Tokenizer
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 19687, "end": 19957 }
class ____(ViewsPositionsBase): """Move forward in the view lim stack.""" description = 'Forward to next view' image = 'mpl-data/images/forward' default_keymap = property(lambda self: mpl.rcParams['keymap.forward']) _on_trigger = 'forward'
ToolForward
python
Textualize__textual
src/textual/reactive.py
{ "start": 1133, "end": 3304 }
class ____(Generic[ReactiveType]): """Initialize a reactive by calling a method parent object. Example: ```python class InitializeApp(App): def get_names(self) -> list[str]: return ["foo", "bar", "baz"] # The `names` property will call `...
Initialize
python
getsentry__sentry
src/sentry/migrations/0971_make_dashboard_widget_order_optional_field.py
{ "start": 186, "end": 1656 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
getsentry__sentry
src/sentry/api/serializers/models/event.py
{ "start": 5698, "end": 5852 }
class ____(TypedDict, total=False): startTimestamp: datetime endTimestamp: datetime measurements: Any breakdowns: Any
TransactionEventFields
python
scrapy__scrapy
tests/test_pipeline_media.py
{ "start": 14314, "end": 15549 }
class ____: def _assert_request_no3xx(self, pipeline_class, settings): pipe = pipeline_class(crawler=get_crawler(None, settings)) request = Request("http://url") pipe._modify_media_request(request) assert "handle_httpstatus_list" in request.meta for status, check in [ ...
TestMediaPipelineAllowRedirectSettings
python
getsentry__sentry-python
tests/integrations/mcp/test_mcp.py
{ "start": 2949, "end": 3135 }
class ____: """Mock PromptMessage object""" def __init__(self, role, content_text): self.role = role self.content = MockTextContent(content_text)
MockPromptMessage
python
scikit-image__scikit-image
tests/skimage/feature/test_peak.py
{ "start": 283, "end": 19291 }
class ____: def test_trivial_case(self): trivial = np.zeros((25, 25)) peak_indices = peak.peak_local_max(trivial, min_distance=1) assert type(peak_indices) is np.ndarray assert peak_indices.size == 0 def test_noisy_peaks(self): peak_locations = [(7, 7), (7, 13), (13, 7),...
TestPeakLocalMax
python
pyca__cryptography
tests/doubles.py
{ "start": 1298, "end": 1382 }
class ____(padding.AsymmetricPadding): name = "dummy-padding"
DummyAsymmetricPadding
python
pytest-dev__pytest
testing/test_collection.py
{ "start": 4509, "end": 10342 }
class ____: def test_ignored_certain_directories(self, pytester: Pytester) -> None: tmp_path = pytester.path ensure_file(tmp_path / "build" / "test_notfound.py") ensure_file(tmp_path / "dist" / "test_notfound.py") ensure_file(tmp_path / "_darcs" / "test_notfound.py") ensure_f...
TestCollectFS
python
neetcode-gh__leetcode
python/2300-successful-pairs-of-spells-and-potions.py
{ "start": 0, "end": 624 }
class ____: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: pairs = [] potions.sort() n = len(potions) for i in range(len(spells)): l, r = 0, len(potions) - 1 while l <= r: m = (l + r) ...
Solution
python
tensorflow__tensorflow
tensorflow/python/autograph/operators/variables.py
{ "start": 1687, "end": 3090 }
class ____(object): """Represents an undefined symbol in Python. This is used to reify undefined symbols, which is required to use the functional form of loops. Example: while n > 0: n = n - 1 s = n return s # Runtime error if n == 0 This is valid Python code and will not result in an ...
Undefined
python
coleifer__peewee
tests/hybrid.py
{ "start": 823, "end": 4078 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [Interval, Person] def setUp(self): super(TestHybridProperties, self).setUp() intervals = ( (1, 5), (2, 6), (3, 5), (2, 5)) for start, end in intervals: In...
TestHybridProperties
python
mahmoud__boltons
tests/test_ioutils.py
{ "start": 352, "end": 8341 }
class ____: """ A set of tests that work the same for SpooledBtyesIO and SpooledStringIO """ def test_getvalue_norollover(self): """Make sure getvalue function works with in-memory flo""" self.spooled_flo.write(self.test_str) self.assertEqual(self.spooled_flo.getvalue(), self.te...
BaseTestMixin
python
fluentpython__example-code
11-iface-abc/frenchdeck2.py
{ "start": 77, "end": 777 }
class ____(collections.MutableSequence): ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split() def __init__(self): self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] def __len__(s...
FrenchDeck2
python
ray-project__ray
python/ray/serve/tests/test_multiplex.py
{ "start": 1452, "end": 8294 }
class ____: async def test_failed_to_get_replica_context(self): async def model_load_func(model_id: str): return model_id with pytest.raises(RuntimeError, match="can only be used within a deployment"): _ModelMultiplexWrapper(model_load_func, None, max_num_models_per_replica=...
TestMultiplexWrapper
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 52894, "end": 53163 }
class ____(Hlist): """ A convenience class to create an `Hlist` whose contents are centered within its enclosing box. """ def __init__(self, elements: list[Node]): super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False)
HCentered
python
ray-project__ray
rllib/env/vector_env.py
{ "start": 486, "end": 8349 }
class ____: """An environment that supports batch evaluation using clones of sub-envs.""" def __init__( self, observation_space: gym.Space, action_space: gym.Space, num_envs: int ): """Initializes a VectorEnv instance. Args: observation_space: The observation Space of a...
VectorEnv
python
doocs__leetcode
solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/Solution.py
{ "start": 0, "end": 413 }
class ____: def minKBitFlips(self, nums: List[int], k: int) -> int: n = len(nums) d = [0] * (n + 1) ans = s = 0 for i, x in enumerate(nums): s += d[i] if s % 2 == x: if i + k > n: return -1 d[i] += 1 ...
Solution
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/triggers/data_factory.py
{ "start": 1170, "end": 4995 }
class ____(BaseTrigger): """ Trigger with params to run the task when the ADF Pipeline is running. :param run_id: The pipeline run identifier. :param azure_data_factory_conn_id: The connection identifier for connecting to Azure Data Factory. :param poke_interval: polling period in seconds to check...
ADFPipelineRunStatusSensorTrigger
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/ecs.py
{ "start": 3441, "end": 5285 }
class ____(EcsBaseSensor): """ Poll task definition until it reaches a terminal state; raise AirflowException with the failure reason. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/sensor:EcsTaskDefinitionStateSensor` :param task_d...
EcsTaskDefinitionStateSensor
python
getsentry__sentry
src/sentry/integrations/msteams/card_builder/block.py
{ "start": 751, "end": 842 }
class ____(str, Enum): SMALL = "Small" MEDIUM = "Medium" LARGE = "Large"
TextSize
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 69530, "end": 84139 }
class ____: def __init__( self, pass_name: Optional[str] = None, subsystem: Optional[str] = None, ) -> None: super().__init__() self.patterns: defaultdict[ tuple[str, torch.fx.node.Target], list[PatternEntry] ] = defaultdict(list) self.pass_nam...
PatternMatcherPass
python
django__django
django/core/management/__init__.py
{ "start": 6777, "end": 17413 }
class ____: """ Encapsulate the logic of the django-admin and manage.py utilities. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) if self.prog_name == "__main__.py": self.prog_name = "python -m djang...
ManagementUtility
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 963, "end": 1058 }
class ____(Proto_CoSelf): def m(self) -> "Impl_CoRecursExplicit2": ...
Impl_CoRecursExplicit2
python
PrefectHQ__prefect
tests/server/schemas/test_core.py
{ "start": 5572, "end": 8523 }
class ____: def test_task_run_cache_key_greater_than_user_configured_max_length(self): with temporary_settings({PREFECT_API_TASK_CACHE_KEY_MAX_LENGTH: 5}): cache_key_invalid_length = "X" * 6 with pytest.raises( ValidationError, match="Cache key exceede...
TestTaskRun
python
great-expectations__great_expectations
tests/datasource/fluent/test_type_lookup.py
{ "start": 2664, "end": 3861 }
class ____: def test_transaction_happy_path(self): t = TypeLookup({"a_list": list, "a_dict": dict}) with t.transaction(): t["a_set"] = set print(f"t\t{len(t)}") assert set in t t["a_tuple"] = tuple print(f"t\t{len(t)}") assert...
TestTransactions
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 18198, "end": 19826 }
class ____(JitTestCase): """ A common base class for JIT backend tests with compilers that contains common utility functions for output comparison. """ def setUp(self): super().setUp() lib_file_path = find_library_location("libbackend_with_compiler.so") torch.ops.load_librar...
JitBackendTestCaseWithCompiler
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_payout_balance_transactions.py
{ "start": 5823, "end": 6970 }
class ____(TestCase): @HttpMocker() def test_when_read_then_fetch_from_updated_payouts(self, http_mocker: HttpMocker) -> None: config = _config().with_start_date(_START_DATE).build() state = StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(_STATE_DATE.timestamp())}).build() ...
PayoutBalanceTransactionsIncrementalTest
python
skorch-dev__skorch
skorch/tests/callbacks/test_regularization.py
{ "start": 103, "end": 1870 }
class ____: @pytest.fixture def grad_clip_cls_and_mock(self): with patch('skorch.callbacks.regularization.clip_grad_norm_') as cgn: from skorch.callbacks import GradientNormClipping yield GradientNormClipping, cgn def test_parameters_passed_correctly_to_torch_cgn( ...
TestGradientNormClipping
python
joke2k__faker
faker/providers/automotive/es_CO/__init__.py
{ "start": 85, "end": 359 }
class ____(AutomotiveProvider): license_formats = OrderedDict( [ ("???###", 0.6), ("???##?", 0.3), ("T####", 0.03), ("??####", 0.01), ("R#####", 0.03), ("S#####", 0.03), ] )
Provider
python
walkccc__LeetCode
solutions/1425. Constrained Subsequence Sum/1425.py
{ "start": 0, "end": 589 }
class ____: def constrainedSubsetSum(self, nums: list[int], k: int) -> int: # dp[i] := the maximum the sum of non-empty subsequences in nums[0..i] dp = [0] * len(nums) # dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0 # in decreasing order. dq = collections.deque() for...
Solution
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 49064, "end": 50238 }
class ____(nn.Module): def __init__(self, config: Sam2VideoPromptEncoderConfig): super().__init__() self.scale = config.scale positional_embedding = self.scale * torch.randn((2, config.hidden_size // 2)) self.register_buffer("positional_embedding", positional_embedding) def forw...
Sam2VideoPositionalEmbedding
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1014346, "end": 1014819 }
class ____(sgqlc.types.Type): """Autogenerated return type of UnresolveReviewThread""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "thread") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the m...
UnresolveReviewThreadPayload
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 123594, "end": 129598 }
class ____(fixtures.TablesTest, ComparesTables): """test DDL and reflection of PG-specific types""" __only_on__ = ("postgresql >= 8.3.0",) __sparse_driver_backend__ = True @testing.metadata_fixture() def special_types_table(self, metadata): # create these types so that we can issue ...
SpecialTypesTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIn1.py
{ "start": 3806, "end": 5455 }
class ____(Generic[P]): def __init__(self, func: Callable[P, str]) -> None: self.func = func def __call__(self, *args: P.args, **kwargs: P.kwargs) -> str: if "data" in kwargs: raise ValueError("data is not allowed in kwargs") return self.func(*args, **kwargs) T13 = TypeVa...
Container
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 7165, "end": 7352 }
class ____(ShowFieldTypeAndContent, PolymorphicModel): blog = models.ForeignKey(BlogBase, on_delete=models.CASCADE) text = models.CharField(max_length=30)
BlogEntry_limit_choices_to
python
doocs__leetcode
solution/1000-1099/1025.Divisor Game/Solution.py
{ "start": 0, "end": 85 }
class ____: def divisorGame(self, n: int) -> bool: return n % 2 == 0
Solution
python
django__django
django/db/models/functions/text.py
{ "start": 9147, "end": 9222 }
class ____(Transform): function = "RTRIM" lookup_name = "rtrim"
RTrim
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 35673, "end": 39850 }
class ____(LogitsProcessor): r""" [`LogitsProcessor`] that performs typical decoding. Inspired on how humans use language, it prioritizes tokens whose log probability is close to the entropy of the token probability distribution. This means that the most likely tokens may be discarded in the process. ...
TypicalLogitsWarper
python
keon__algorithms
tests/test_graph.py
{ "start": 2079, "end": 2554 }
class ____(unittest.TestCase): def test_check_bipartite(self): adj_list_1 = [[0, 0, 1], [0, 0, 1], [1, 1, 0]] self.assertEqual(True, check_bipartite(adj_list_1)) adj_list_2 = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] self.assertEqual(True, check_bipartite(adj_list_2)) ...
TestCheckBipartite
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1329659, "end": 1330280 }
class ____(sgqlc.types.Type, ProjectV2ItemFieldValueCommon, Node): """The value of a single select field in a Project item.""" __schema__ = github_schema __field_names__ = ("name", "name_html", "option_id") name = sgqlc.types.Field(String, graphql_name="name") """The name of the selected single sel...
ProjectV2ItemFieldSingleSelectValue
python
huggingface__transformers
src/transformers/models/falcon_mamba/modeling_falcon_mamba.py
{ "start": 35860, "end": 42719 }
class ____(FalconMambaPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "backbone.embeddings.weight"} def __init__(self, config): super().__init__(config) self.backbone = FalconMambaModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bi...
FalconMambaForCausalLM
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_simplify/SIM115.py
{ "start": 6057, "end": 6151 }
class ____(TestCase): def setUp(self): self.enterContext(open("filename"))
ExampleTests
python
spack__spack
lib/spack/spack/error.py
{ "start": 4208, "end": 4287 }
class ____(SpackError): """Superclass for fetch-related errors."""
FetchError
python
huggingface__transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
{ "start": 64239, "end": 70989 }
class ____(Kosmos2PreTrainedModel): config: Kosmos2Config main_input_name = "pixel_values" def __init__(self, config: Kosmos2Config): super().__init__(config) self.text_model = Kosmos2TextModel(config.text_config) self.vision_model = Kosmos2VisionModel(config.vision_config) ...
Kosmos2Model
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/hstore.py
{ "start": 8838, "end": 8979 }
class ____(sqlfunc.GenericFunction): type = ARRAY(sqltypes.Text) name = "hstore_to_array" inherit_cache = True
_HStoreArrayFunction
python
Pylons__pyramid
src/pyramid/testing.py
{ "start": 8820, "end": 18708 }
class ____( URLMethodsMixin, CallbackMethodsMixin, InstancePropertyMixin, LocalizerRequestMixin, SecurityAPIMixin, AuthenticationAPIMixin, ViewMethodsMixin, ): """A DummyRequest object (incompletely) imitates a :term:`request` object. The ``params``, ``environ``, ``headers``, ``path...
DummyRequest
python
allegroai__clearml
clearml/automation/parameters.py
{ "start": 3083, "end": 5518 }
class ____(Parameter): """ Uniform randomly sampled hyperparameter object. """ def __init__( self, name: str, min_value: float, max_value: float, step_size: Optional[float] = None, include_max_value: bool = True, ) -> (): """ Create a ...
UniformParameterRange
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 20500, "end": 20819 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): kurts = helper_functions.get_value("Kurtosisses") minimum = np.nanmin(kurts) if len(kurts) > 0 else 0 return minimum if np.isfinite(minimum) else 0 @metafeatures.define("KurtosisMax", dependency="Kurtosisses")
KurtosisMin
python
langchain-ai__langchain
libs/standard-tests/tests/unit_tests/test_embeddings.py
{ "start": 484, "end": 745 }
class ____(EmbeddingsIntegrationTests): @property def embeddings_class(self) -> type[Embeddings]: return DeterministicFakeEmbedding @property def embedding_model_params(self) -> dict: return {"size": 6}
TestFakeEmbeddingsIntegration
python
numba__numba
numba/tests/test_cfunc.py
{ "start": 5090, "end": 9894 }
class ____(TestCase): """ Tests for carray() and farray(). """ def run_carray_usecase(self, pointer_factory, func): a = np.arange(10, 16).reshape((2, 3)).astype(np.float32) out = np.empty(CARRAY_USECASE_OUT_LEN, dtype=np.float32) func(pointer_factory(a), pointer_factory(out), *a...
TestCArray
python
celery__celery
t/unit/tasks/test_stamping.py
{ "start": 26617, "end": 55272 }
class ____(CanvasCase): """These tests were extracted (and fixed) from the canvas unit tests.""" def test_on_signature_gets_the_signature(self): expected_sig = self.add.s(4, 2) class CustomStampingVisitor(StampingVisitor): def on_signature(self, actual_sig, **headers) -> dict: ...
test_stamping_mechanism
python
zostera__django-bootstrap4
src/bootstrap4/renderers.py
{ "start": 2609, "end": 4502 }
class ____(BaseRenderer): """Default formset renderer.""" def __init__(self, formset, *args, **kwargs): if not isinstance(formset, BaseFormSet): raise BootstrapError('Parameter "formset" should contain a valid Django Formset.') self.formset = formset super().__init__(*args, ...
FormsetRenderer
python
pytorch__pytorch
torch/_inductor/runtime/caching/context.py
{ "start": 963, "end": 4055 }
class ____(_Context): """Context provider for runtime configuration and environment settings. Collects configuration settings that affect runtime behavior but not compilation, such as Inductor configs, determinism settings, and CUDA matmul precision configurations. """ @override @staticmet...
_RuntimeContext
python
scipy__scipy
benchmarks/benchmarks/linalg_sqrtm.py
{ "start": 166, "end": 671 }
class ____(Benchmark): params = [ ['float64', 'complex128'], [16, 32, 64, 256, 512], ] param_names = ['dtype', 'n'] def setup(self, dtype, n): n = int(n) rng = np.random.default_rng(1742808411247533) dtype = np.dtype(dtype) A = rng.uniform(size=[n, n]) ...
Sqrtm
python
ansible__ansible
test/units/vars/test_variable_manager.py
{ "start": 1356, "end": 6164 }
class ____(unittest.TestCase): def test_basic_manager(self): fake_loader = DictDataLoader({}) mock_inventory = InventoryManager(loader=fake_loader) v = VariableManager(loader=fake_loader, inventory=mock_inventory) variables = v.get_vars(use_cache=False) # Check var manager...
TestVariableManager
python
lxml__lxml
src/lxml/html/tests/test_html5parser.py
{ "start": 12876, "end": 13440 }
class ____: def __init__(self, doc=None, root=None, fragments=None, namespaceHTMLElements=True): self.doc = doc or DummyElementTree(root=root) self.fragments = fragments self.tree = DummyTreeBuilder(namespaceHTMLElements) def parse(self, *args, **kwargs): self.p...
DummyParser
python
kamyu104__LeetCode-Solutions
Python/basic-calculator-iii.py
{ "start": 1373, "end": 2791 }
class ____(object): def calculate(self, s): """ :type s: str :rtype: int """ operands, operators = [], [] operand = "" for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] if i == 0 or not s[i-1].isd...
Solution2
python
facebook__pyre-check
tools/incremental_test/specification.py
{ "start": 6615, "end": 8659 }
class ____(RepositoryState): files: Dict[str, str] def to_json(self) -> Dict[str, Any]: return {"kind": "file", "files": self.files} @contextmanager def _do_prepare(self, environment: Environment) -> Iterator[Path]: # Grab a temporary directory as the local root temporary_direc...
FileRepositoryState
python
pypa__setuptools
setuptools/_distutils/tests/test_core.py
{ "start": 1101, "end": 3829 }
class ____: def test_run_setup_provides_file(self, temp_file): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. temp_file.write_text(setup_using___file__, encoding='utf-8') distutils.core.run_setup(temp_file) def test_r...
TestCore
python
kamyu104__LeetCode-Solutions
Python/sort-the-matrix-diagonally.py
{ "start": 74, "end": 613 }
class ____(object): def diagonalSort(self, mat): """ :type mat: List[List[int]] :rtype: List[List[int]] """ lookup = collections.defaultdict(list) for i in xrange(len(mat)): for j in xrange(len(mat[0])): lookup[i-j].append(mat[i][j]) ...
Solution
python
kamyu104__LeetCode-Solutions
Python/additive-number.py
{ "start": 32, "end": 1196 }
class ____(object): def isAdditiveNumber(self, num): """ :type num: str :rtype: bool """ def add(a, b): res, carry, val = "", 0, 0 for i in xrange(max(len(a), len(b))): val = carry if i < len(a): val ...
Solution
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 27562, "end": 27655 }
class ____(BaseModel): type: Literal["ResendLoggingFD"] = "ResendLoggingFD"
ResendLoggingFD
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/sensors/dataplex.py
{ "start": 1547, "end": 1698 }
class ____: """Dataplex Task states.""" STATE_UNSPECIFIED = 0 ACTIVE = 1 CREATING = 2 DELETING = 3 ACTION_REQUIRED = 4
TaskState
python
pypa__pip
tests/unit/test_network_auth.py
{ "start": 12805, "end": 17567 }
class ____(KeyringModuleV1): """Represents the subprocess call to keyring""" returncode = 0 # Default to zero retcode def __call__( self, cmd: list[str], *, env: dict[str, str], stdin: Any | None = None, stdout: Any | None = None, input: bytes | Non...
KeyringSubprocessResult
python
keras-team__keras
integration_tests/dataset_tests/cifar100_test.py
{ "start": 92, "end": 1318 }
class ____(testing.TestCase): def test_shapes_fine_label_mode(self): (x_train, y_train), (x_test, y_test) = cifar100.load_data( label_mode="fine" ) self.assertEqual(x_train.shape, (50000, 32, 32, 3)) self.assertEqual(y_train.shape, (50000, 1)) self.assertEqual(x_t...
Cifar100LoadDataTest
python
sphinx-doc__sphinx
sphinx/directives/other.py
{ "start": 8299, "end": 8862 }
class ____(SphinxDirective): """Directive to create a centered line of bold text.""" has_content = False required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec: ClassVar[OptionSpec] = {} def run(self) -> list[Node]: if not self.arguments: ...
Centered
python
redis__redis-py
tests/test_asyncio/test_multidb/test_client.py
{ "start": 775, "end": 27664 }
class ____: @pytest.mark.asyncio @pytest.mark.parametrize( "mock_multi_db_config,mock_db, mock_db1, mock_db2", [ ( {}, {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.CLOSED}}, ...
TestMultiDbClient
python
huggingface__transformers
src/transformers/models/groupvit/modeling_groupvit.py
{ "start": 23548, "end": 23693 }
class ____(GroupViTMLP): def forward(self, x): x = super().forward(x.transpose(1, 2)) return x.transpose(1, 2)
GroupViTMixerMLP
python
getsentry__sentry
tests/sentry/middleware/integrations/parsers/test_discord.py
{ "start": 10464, "end": 11553 }
class ____(APITestCase): @override_settings(SILO_MODE=SiloMode.CONTROL) def test_validation_failure(self) -> None: response = self.client.post( reverse("sentry-integration-discord-interactions"), data={"type": DiscordRequestTypes.PING}, ) assert response.status_co...
End2EndTest
python
mlflow__mlflow
tests/genai/evaluate/test_telemetry.py
{ "start": 796, "end": 5171 }
class ____(Scorer): name: str = "is_empty" def __call__(self, *, outputs) -> bool: return outputs == "" def test_emit_custom_metric_event(): from databricks.agents.evals import metric # Legacy custom metrics @metric def not_empty(response): return response != "" scorers ...
IsEmpty
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/forms.py
{ "start": 4860, "end": 5061 }
class ____(ReprForm): _ip_both = forms.GenericIPAddressField() _ip_v4 = forms.GenericIPAddressField(protocol="IPv4") _ip_v6 = forms.GenericIPAddressField(protocol="IPv6")
InternetProtocolForm
python
huggingface__transformers
src/transformers/models/lightglue/modeling_lightglue.py
{ "start": 4281, "end": 8464 }
class ____(nn.Module): def __init__(self, config: LightGlueConfig): super().__init__() self.projector = nn.Linear(2, config.descriptor_dim // config.num_attention_heads // 2, bias=False) def forward( self, keypoints: torch.Tensor, output_hidden_states: Optional[bool] = False ) -> Un...
LightGluePositionalEncoder
python
openai__openai-python
src/openai/_response.py
{ "start": 20695, "end": 21460 }
class ____(Generic[_APIResponseT]): """Context manager for ensuring that a request is not made until it is entered and that the response will always be closed when the context manager exits """ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: self._request_func = reque...
ResponseContextManager
python
django__django
tests/forms_tests/tests/test_input_formats.py
{ "start": 17152, "end": 21316 }
class ____(SimpleTestCase): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override(None)) super().setUpClass() def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted for...
CustomDateInputFormatsTests
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/events.py
{ "start": 22637, "end": 25946 }
class ____(event.RefCollection[_ET]): """Hold onto listeners against unmapped, uninstrumented classes. Establish _listen() for that class' mapper/instrumentation when those objects are created for that class. """ all_holds: weakref.WeakKeyDictionary[Any, Any] def __init__( self, ...
_EventsHold
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_basic.py
{ "start": 7419, "end": 10549 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL ): run_setup_mappers = "once" __dialect__ = "default" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=...
PolymorphicResolutionMultiLevel
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-oxylabs/llama_index/readers/oxylabs/base.py
{ "start": 400, "end": 4204 }
class ____(BasePydanticReader, abc.ABC): """ Oxylabs Scraper base class. https://developers.oxylabs.io/scraper-apis/web-scraper-api """ top_level_header: Optional[str] = None timeout_s: int = 100 oxylabs_scraper_url: str = "https://realtime.oxyserps-dev.fun/v1/queries" oxylabs_api: Re...
OxylabsBaseReader
python
django__django
tests/distinct_on_fields/models.py
{ "start": 603, "end": 688 }
class ____(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE)
Fan
python
buildout__buildout
src/zc/buildout/_package_index.py
{ "start": 14385, "end": 42197 }
class ____(Environment): """A distribution index that scans web pages for download URLs""" def __init__( self, index_url: str = "https://pypi.org/simple/", hosts=('*',), ca_bundle=None, verify_ssl: bool = True, *args, **kw, ) -> None: super()....
PackageIndex
python
sanic-org__sanic
sanic/worker/loader.py
{ "start": 4707, "end": 5777 }
class ____: _creators = { "mkcert": MkcertCreator, "trustme": TrustmeCreator, } def __init__( self, ssl_data: Optional[ Union[SSLContext, dict[str, Union[str, os.PathLike]]] ], ): self._ssl_data = ssl_data self._creator_class = None ...
CertLoader
python
keras-team__keras
keras/src/callbacks/tensorboard_test.py
{ "start": 884, "end": 1251 }
class ____: """Yields `Event` protocol buffers from a given path.""" def __init__(self, path): self._tf_record_iterator = tf_record.tf_record_iterator(path) def __iter__(self): return self def __next__(self): r = next(self._tf_record_iterator) return event_pb2.Event.Fr...
_SummaryIterator
python
huggingface__transformers
tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py
{ "start": 19314, "end": 24608 }
class ____(EncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained( "hf-internal-testing/tiny-random-deit", "hf-internal-testing/tiny-random-roberta" ) batch_size = 13 pixel_valu...
DeiT2RobertaModelTest
python
facelessuser__pymdown-extensions
tests/test_extensions/test_inlinehilite.py
{ "start": 13977, "end": 14910 }
class ____(util.MdCase): """Test custom InlineHilite cases.""" extension = [ 'pymdownx.highlight', 'pymdownx.inlinehilite', ] extension_configs = { 'pymdownx.inlinehilite': { 'css_class': 'inlinehilite', 'custom_inline': [ { ...
TestLegacyInlineHiliteCustom3
python
tornadoweb__tornado
tornado/test/locale_test.py
{ "start": 3040, "end": 3337 }
class ____(unittest.TestCase): def test_non_ascii_name(self): name = tornado.locale.LOCALE_NAMES["es_LA"]["name"] self.assertTrue(isinstance(name, unicode_type)) self.assertEqual(name, "Espa\u00f1ol") self.assertEqual(utf8(name), b"Espa\xc3\xb1ol")
LocaleDataTest
python
tensorflow__tensorflow
tensorflow/python/training/monitored_session_test.py
{ "start": 92491, "end": 96649 }
class ____(test.TestCase): """Tests SingularMonitoredSession.""" def test_handles_initialization(self): with ops.Graph().as_default(): a_var = variable_v1.VariableV1(0) with monitored_session.SingularMonitoredSession() as session: # If it's not initialized, following statement raises an err...
SingularMonitoredSessionTest
python
getsentry__sentry
src/sentry/organizations/services/organization/service.py
{ "start": 19975, "end": 20842 }
class ____(abc.ABC): @abstractmethod def check_organization_by_slug(self, *, slug: str, only_visible: bool) -> int | None: """ If exists and matches the only_visible requirement, returns an organization's id by the slug. """ @abstractmethod def check_organization_by_id(self, *, ...
OrganizationCheckService
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 25654, "end": 26241 }
class ____(Expr): """Get an attribute or item from an expression that is a ascii-only bytestring and prefer the attribute. """ fields = ("node", "attr", "ctx") node: Expr attr: str ctx: str def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any: if self.ctx != "l...
Getattr
python
encode__httpx
httpx/_multipart.py
{ "start": 7195, "end": 9843 }
class ____(SyncByteStream, AsyncByteStream): """ Request content as streaming multipart encoded form data. """ def __init__( self, data: RequestData, files: RequestFiles, boundary: bytes | None = None, ) -> None: if boundary is None: boundary = os...
MultipartStream
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 37669, "end": 41273 }
class ____(Operation): def __init__( self, strides=1, padding="valid", data_format=None, dilation_rate=1, *, name=None, ): super().__init__(name=name) self.strides = strides self.padding = padding.lower() self.data_format = ...
DepthwiseConv
python
walkccc__LeetCode
solutions/854. K-Similar Strings/854.py
{ "start": 0, "end": 811 }
class ____: def kSimilarity(self, s1: str, s2: str) -> int: q = collections.deque([s1]) seen = {s1} step = 0 while q: for _ in range(len(q)): curr = q.popleft() if curr == s2: return step for child in self._getChildren(curr, s2): if child in seen: ...
Solution
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_abc_polymorphic.py
{ "start": 405, "end": 3644 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): global a, b, c a = Table( "a", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("adata", String(30...
ABCTest
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 18978, "end": 19847 }
class ____(ConstantPadding2D): """Adds rows and columns of zero values to the input. Expects the input to be of shape (batch_size, channels, height, width) Parameters: ----------- padding: tuple The amount of padding along the height and width dimension of the input. If (pad_h, pad_...
ZeroPadding2D
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 7944, "end": 12047 }
class ____(Layer): """A 2D Convolution Layer. Parameters: ----------- n_filters: int The number of filters that will convolve over the input matrix. The number of channels of the output shape. filter_shape: tuple A tuple (filter_height, filter_width). input_shape: tuple ...
Conv2D
python
openai__openai-python
tests/api_resources/fine_tuning/alpha/test_graders.py
{ "start": 5193, "end": 10258 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_run(self, async_client: AsyncOpenAI) -> None: grader = await async_client.fine_tuning.alph...
TestAsyncGraders
python
ray-project__ray
python/ray/actor.py
{ "start": 6203, "end": 7015 }
class ____(Generic[_Ret, _T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]): def remote( self, __arg0: "Union[_T0, ObjectRef[_T0]]", __arg1: "Union[_T1, ObjectRef[_T1]]", __arg2: "Union[_T2, ObjectRef[_T2]]", __arg3: "Union[_T3, ObjectRef[_T3]]", __arg4: "Union[_T4, Object...
_RemoteMethod8
python
astropy__astropy
astropy/convolution/tests/test_convolve_fft.py
{ "start": 2465, "end": 20220 }
class ____: @pytest.mark.parametrize("boundary", BOUNDARY_OPTIONS) @pytest.mark.parametrize("nan_treatment", NANTREATMENT_OPTIONS) @pytest.mark.parametrize("normalize_kernel", NORMALIZE_OPTIONS) @pytest.mark.parametrize("dealias", [True, False]) def test_quantity(self, boundary, nan_treatment, norma...
TestConvolve1D
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py
{ "start": 721, "end": 841 }
class ____: def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... def __init__(self, a: int) -> None: ...
Class4
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 248727, "end": 256092 }
class ____(ExprNode): # allow overriding the default 'may_be_none' behaviour may_return_none = None def infer_type(self, env): function = self.function # TODO(robertwb): Reduce redundancy with analyse_types. func_type = function.infer_type(env) if isinstance(function, NewEx...
CallNode