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
realpython__materials
flask-connexion-rest-part-4/models.py
{ "start": 571, "end": 904 }
class ____(db.Model): __tablename__ = "note" note_id = db.Column(db.Integer, primary_key=True) person_id = db.Column(db.Integer, db.ForeignKey("person.person_id")) content = db.Column(db.String, nullable=False) timestamp = db.Column( db.DateTime, default=datetime.utcnow, onupdate=datetime.ut...
Note
python
pytorch__pytorch
torch/_dynamo/variables/nn_module.py
{ "start": 54739, "end": 55075 }
class ____(UnspecializedNNModuleVariable): """ Differentiates between builtin nn modules (e.g. torch.nn.Linear) and user defined nn modules. """ def _wrap_source(self, attr_source): # vt is already wrapped with the UnspecializedBuiltinNNModuleSource return attr_source
UnspecializedBuiltinNNModuleVariable
python
pytorch__pytorch
torch/backends/__init__.py
{ "start": 1319, "end": 1519 }
class ____(types.ModuleType): def __init__(self, m, name): super().__init__(name) self.m = m def __getattr__(self, attr): return self.m.__getattribute__(attr)
PropModule
python
matplotlib__matplotlib
lib/matplotlib/legend_handler.py
{ "start": 15587, "end": 18228 }
class ____(HandlerNpointsYoffsets): r"""Handler for `.RegularPolyCollection`\s.""" def __init__(self, yoffsets=None, sizes=None, **kwargs): super().__init__(yoffsets=yoffsets, **kwargs) self._sizes = sizes def get_numpoints(self, legend): if self._numpoints is None: re...
HandlerRegularPolyCollection
python
kamyu104__LeetCode-Solutions
Python/climbing-stairs-ii.py
{ "start": 34, "end": 384 }
class ____(object): def climbStairs(self, n, costs): """ :type n: int :type costs: List[int] :rtype: int """ a, b, c = float("inf"), float("inf"), 0 for i in xrange(n): a, b, c = b, c, costs[i]+min(a+3**2, b+2**2, c+1**2) return c # Time:...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/query.py
{ "start": 118118, "end": 119567 }
class ____: """State used for the orm.Query version of update() / delete(). This object is now specific to Query only. """ def __init__(self, query: Query[Any]): self.query = query.enable_eagerloads(False) self._validate_query_state() self.mapper = self.query._entity_from_pre_...
BulkUD
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 26459, "end": 34354 }
class ____(SplinterPreTrainedModel): def __init__(self, config): super().__init__(config) self.splinter = SplinterModel(config) self.splinter_qass = QuestionAwareSpanSelectionHead(config) self.question_token_id = config.question_token_id # Initialize weights and apply final...
SplinterForPreTraining
python
dagster-io__dagster
python_modules/dagster/dagster/components/utils/defs_state.py
{ "start": 262, "end": 2033 }
class ____(Model): key: Optional[str] = Field( default=None, description="The key for the state. This must be unique per deployment." ) management_type: DefsStateManagementType = Field( description="The storage type for state required for loading this object's definitions." " - `LOC...
DefsStateConfigArgs
python
ansible__ansible
test/integration/targets/old_style_vars_plugins/vars_plugins/require_enabled.py
{ "start": 86, "end": 238 }
class ____(BaseVarsPlugin): REQUIRES_ENABLED = True def get_vars(self, loader, path, entities): return {'require_enabled': True}
VarsModule
python
pytorch__pytorch
torch/optim/lr_scheduler.py
{ "start": 25654, "end": 29251 }
class ____(LRScheduler): """Decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones. Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler. When last_epoch=-1, sets initial lr as lr. ...
MultiStepLR
python
huggingface__transformers
src/transformers/models/deberta_v2/modeling_deberta_v2.py
{ "start": 33963, "end": 34670 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.transform = LegacyDebertaV2PredictionHeadTransform(config) self.embedding_size = getattr(config, "embedding_size", config.hidden_size) # The output weights are the same as the input embeddings, but there is ...
LegacyDebertaV2LMPredictionHead
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/gcs/io_manager.py
{ "start": 6027, "end": 8881 }
class ____(GCSPickleIOManager): """Renamed to GCSPickleIOManager. See GCSPickleIOManager for documentation.""" pass @dagster_maintained_io_manager @io_manager( config_schema=GCSPickleIOManager.to_config_schema(), required_resource_keys={"gcs"}, ) def gcs_pickle_io_manager(init_context): """Persis...
ConfigurablePickledObjectGCSIOManager
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item_param.py
{ "start": 314, "end": 2207 }
class ____(TypedDict, total=False): id: str """ The unique ID of the item, this can be generated by the client to help manage server-side context, but is not required because the server will generate one if not provided. """ arguments: str """The arguments of the function call (for `fun...
ConversationItemParam
python
HIPS__autograd
autograd/builtins.py
{ "start": 3502, "end": 3613 }
class ____(type_): def __instancecheck__(self, instance): return isinstance(instance, list_)
ListMeta
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum1.py
{ "start": 5945, "end": 6222 }
class ____(Enum): a = 1 b = lambda self: None c = func3 reveal_type(TestEnum12.a, expected_text="Literal[TestEnum12.a]") reveal_type(TestEnum12.b, expected_text="(self: Unknown) -> None") reveal_type(TestEnum12.c, expected_text="(self: Unknown) -> None")
TestEnum12
python
crytic__slither
slither/vyper_parsing/variables/state_variable.py
{ "start": 263, "end": 1293 }
class ____: def __init__(self, variable: StateVariable, variable_data: VariableDecl) -> None: self._variable: StateVariable = variable self._variable.name = variable_data.target.id self._variable.is_constant = variable_data.is_constant self._variable.is_immutable = variable_data.is_i...
StateVariableVyper
python
huggingface__transformers
src/transformers/models/plbart/modeling_plbart.py
{ "start": 20130, "end": 25195 }
class ____(GradientCheckpointingLayer): def __init__(self, config: PLBartConfig, layer_idx: Optional[int] = None): super().__init__() self.embed_dim = config.d_model self.self_attn = PLBartAttention( embed_dim=self.embed_dim, num_heads=config.decoder_attention_heads,...
PLBartDecoderLayer
python
huggingface__transformers
src/transformers/models/modernbert_decoder/modular_modernbert_decoder.py
{ "start": 12848, "end": 14045 }
class ____(ModernBertRotaryEmbedding): pass def eager_attention_forward( module: "ModernBertDecoderAttention", query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], dropout: float = 0.0, scaling: Optional[float] = None, sliding_window:...
ModernBertDecoderRotaryEmbedding
python
scikit-learn__scikit-learn
sklearn/model_selection/_split.py
{ "start": 72021, "end": 75728 }
class ____(_UnsupportedGroupCVMixin, BaseShuffleSplit): """Random permutation cross-validator. Yields indices to split data into training and test sets. Note: contrary to other cross-validation strategies, random splits do not guarantee that test sets across all folds will be mutually exclusive, a...
ShuffleSplit
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 3177, "end": 3406 }
class ____(GemmConfig): """ ROCm subclass for GEMMs, with AMD backend specific tuneable kernargs """ matrix_instr_nonkdim: int = 16 waves_per_eu: int = 0 kpack: int = 2 @dataclasses.dataclass
ROCmGemmConfig
python
getsentry__sentry
src/sentry/web/frontend/idp_email_verification.py
{ "start": 467, "end": 2169 }
class ____(BaseView): # the user using this endpoint is currently locked out of their account so auth isn't required. auth_required = False def handle(self, request: HttpRequest, key: str) -> HttpResponse: verification_value = get_verification_value_from_key(key) if not verification_value:...
AccountConfirmationView
python
jmcnamara__XlsxWriter
xlsxwriter/chart_title.py
{ "start": 291, "end": 3344 }
class ____: """ A class to represent an Excel chart title. This class encapsulates all title related properties and methods for the chart title and axis titles. """ def __init__(self) -> None: """ Initialize a ChartTitle instance. """ self.font: Optional[Dict[st...
ChartTitle
python
huggingface__transformers
tests/models/altclip/test_modeling_altclip.py
{ "start": 10680, "end": 12547 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (AltCLIPTextModel,) if is_torch_available() else () # TODO (@SunMarc): Fix me @unittest.skip(reason="It's broken.") def test_resize_tokens_embeddings(self): super().test_resize_tokens_embeddings() def setUp(self): ...
AltCLIPTextModelTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 23715, "end": 23806 }
class ____(DagsterError): """Error raised by invalid asset key."""
DagsterInvalidAssetKey
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E23.py
{ "start": 2033, "end": 2339 }
class ____[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]: def pep_696_bad_method[A:object="foo"[::-1], B:object =[[["foo", "bar"]]], C:object= bytes]( self, x:A = "foo"[::-1], y:B = [[["foo", "bar"]]], z:object = "fooo", ): pass
PEP696Bad
python
Farama-Foundation__Gymnasium
tests/utils/test_env_checker_with_gym.py
{ "start": 620, "end": 3207 }
class ____(gymnasium.Env): def __init__(self): self.action_space = gymnasium.spaces.Discrete(2) self.observation_space = gym.spaces.Discrete(2) def test_check_env_with_gym(): with pytest.raises( TypeError, match=re.escape( "The environment must inherit from the gymn...
IncorrectObs
python
huggingface__transformers
src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py
{ "start": 5567, "end": 8082 }
class ____(nn.Module): """ Duration predictor module. This is a module of duration predictor described in the paper 'FastSpeech: Fast, Robust and Controllable Text to Speech' https://huggingface.co/papers/1905.09263 The duration predictor predicts a duration of each frame in log domain from the hid...
FastSpeech2ConformerDurationPredictor
python
joke2k__faker
faker/providers/person/nl_NL/__init__.py
{ "start": 44, "end": 32748 }
class ____(PersonProvider): # conforming to http://nl.wikipedia.org/wiki/Achternaam#Naamswijziging and # http://en.wikipedia.org/wiki/Dutch_name#Dutch_naming_law_.28surnames.29 # by adding a "-" between the two last names when someone is married formats = ( "{{first_name_male}} {{last_name}}", ...
Provider
python
huggingface__transformers
src/transformers/distributed/configuration_utils.py
{ "start": 711, "end": 4425 }
class ____: """ Base class for distributed configs """ enable_expert_parallel: bool = False # TODO: add tp_plan, pp_plan, device_mesh etc.. @classmethod def from_dict(cls, config_dict, **kwargs): """ Constructs a DistributedConfig instance from a dictionary of parameters. ...
DistributedConfig
python
jd__tenacity
tenacity/retry.py
{ "start": 1604, "end": 1813 }
class ____(retry_base): """Retry strategy that always rejects any result.""" def __call__(self, retry_state: "RetryCallState") -> bool: return True retry_always = _retry_always()
_retry_always
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_test.py
{ "start": 173505, "end": 184428 }
class ____(test.TestCase): def test_indicator_column(self): a = fc.categorical_column_with_hash_bucket('a', 4) indicator_a = fc.indicator_column(a) self.assertEqual(indicator_a.categorical_column.name, 'a') self.assertEqual(indicator_a.name, 'a_indicator') self.assertEqual(indicator_a.variable_sh...
IndicatorColumnTest
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 17785, "end": 18507 }
class ____(Benchmark): param_names = ['sparse_type', 'density'] params = [ ['spmatrix', 'sparray'], np.arange(0, 1.1, 0.1).tolist(), ] def setup(self, sparse_type, density): warnings.simplefilter('ignore', sparse.SparseEfficiencyWarning) self.nrows = 1000 self.nc...
Random
python
doocs__leetcode
lcof/面试题66. 构建乘积数组/Solution.py
{ "start": 0, "end": 327 }
class ____: def constructArr(self, a: List[int]) -> List[int]: n = len(a) ans = [0] * n left = right = 1 for i in range(n): ans[i] = left left *= a[i] for i in range(n - 1, -1, -1): ans[i] *= right right *= a[i] return a...
Solution
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 151384, "end": 154825 }
class ____(Qwen2_5OmniPreTrainedModel): config: Qwen2_5OmniBigVGANConfig input_modalities = "audio" def __init__(self, config: Qwen2_5OmniBigVGANConfig): super().__init__(config) self.num_residual_blocks = len(config.resblock_kernel_sizes) self.num_upsample_layers = len(config.upsam...
Qwen2_5OmniToken2WavBigVGANModel
python
doocs__leetcode
solution/2500-2599/2509.Cycle Length Queries in a Tree/Solution.py
{ "start": 0, "end": 359 }
class ____: def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]: ans = [] for a, b in queries: t = 1 while a != b: if a > b: a >>= 1 else: b >>= 1 t += 1 ...
Solution
python
getsentry__sentry
src/sentry/models/rule.py
{ "start": 5611, "end": 6025 }
class ____(Model): __relocation_scope__ = RelocationScope.Organization rule = FlexibleForeignKey("sentry.Rule") user_id = HybridCloudForeignKey("sentry.User", on_delete="SET_NULL", null=True) type = models.IntegerField() date_added = models.DateTimeField(default=timezone.now) class Meta: ...
RuleActivity
python
pandas-dev__pandas
pandas/tests/indexing/test_loc.py
{ "start": 62211, "end": 71172 }
class ____: @pytest.mark.parametrize( "keys, expected", [ (["b", "a"], [["b", "b", "a", "a"], [1, 2, 1, 2]]), (["a", "b"], [["a", "a", "b", "b"], [1, 2, 1, 2]]), ((["a", "b"], [1, 2]), [["a", "a", "b", "b"], [1, 2, 1, 2]]), ((["a", "b"], [2, 1]), [["a"...
TestLocWithMultiIndex
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_X.py
{ "start": 4204, "end": 5598 }
class ____(Benchmark): r""" Xin-She Yang 4 objective function. This class defines the Xin-She Yang 4 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{XinSheYang04}}(x) = \left[ \sum_{i=1}^{n} \sin^2(x_i) ...
XinSheYang04
python
zarr-developers__zarr-python
src/zarr/experimental/cache_store.py
{ "start": 376, "end": 14127 }
class ____(WrapperStore[Store]): """ A dual-store caching implementation for Zarr stores. This cache wraps any Store implementation and uses a separate Store instance as the cache backend. This provides persistent caching capabilities with time-based expiration, size-based eviction, and flexible ca...
CacheStore
python
explosion__spaCy
spacy/pipeline/functions.py
{ "start": 2307, "end": 4374 }
class ____: def __init__(self, min_length: int = 0, split_length: int = 0): self.min_length = min_length self.split_length = split_length def __call__(self, doc: Doc) -> Doc: if self.min_length > 0 and self.split_length > 0: with doc.retokenize() as retokenizer: ...
TokenSplitter
python
getsentry__sentry
tests/sentry/seer/endpoints/test_organization_seer_explorer_update.py
{ "start": 3909, "end": 4871 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.organization = self.create_organization(owner=self.user) self.url = f"/api/0/organizations/{self.organization.slug}/seer/explorer-update/123/" @patch("sentry.seer.endpoints.organ...
TestOrganizationSeerExplorerUpdateFeatureFlags
python
ray-project__ray
python/ray/llm/_internal/batch/observability/usage_telemetry/usage.py
{ "start": 832, "end": 1605 }
class ____(str, Enum): """Telemetry tags for RayLLM Batch.""" LLM_BATCH_PROCESSOR_CONFIG_NAME = "LLM_BATCH_PROCESSOR_CONFIG_NAME" LLM_BATCH_MODEL_ARCHITECTURE = "LLM_BATCH_MODEL_ARCHITECTURE" LLM_BATCH_SIZE = "LLM_BATCH_SIZE" LLM_BATCH_ACCELERATOR_TYPE = "LLM_BATCH_ACCELERATOR_TYPE" LLM_BATCH_C...
BatchTelemetryTags
python
plotly__plotly.py
plotly/graph_objs/scattersmith/_line.py
{ "start": 233, "end": 8428 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattersmith" _path_str = "scattersmith.line" _valid_props = { "backoff", "backoffsrc", "color", "dash", "shape", "smoothing", "width", } @property def backoff(self): """ ...
Line
python
django__django
django/db/models/lookups.py
{ "start": 24140, "end": 24723 }
class ____(BuiltinLookup): lookup_name = "regex" prepare_rhs = False def as_sql(self, compiler, connection): if self.lookup_name in connection.operators: return super().as_sql(compiler, connection) else: lhs, lhs_params = self.process_lhs(compiler, connection) ...
Regex
python
bokeh__bokeh
src/bokeh/core/property/wrappers.py
{ "start": 5586, "end": 7856 }
class ____(PropertyValueContainer, list[T]): """ A list property value container that supports change notifications on mutating operations. When a Bokeh model has a ``List`` property, the ``PropertyValueLists`` are transparently created to wrap those values. These ``PropertyValueList`` values are s...
PropertyValueList
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-construct/test_flow_start_noblock.py
{ "start": 187, "end": 946 }
class ____(BaseExecutor): def post_init(self): time.sleep(4) @pytest.mark.slow def test_flow_slow_executor_intra(): f = Flow().add(uses='SlowExecutor', shards=2) with f, TimeContext('start flow') as tc: assert tc.now() < 8 @pytest.mark.slow def test_flow_slow_executor_inter(): f = F...
SlowExecutor
python
PyCQA__pycodestyle
testing/data/E30not.py
{ "start": 371, "end": 979 }
class ____: def a(): pass # comment def b(): pass @property def c(): pass try: from nonexistent import Bar except ImportError: class Bar(object): """This is a Bar replacement""" def with_feature(f): """Some decorator""" wrapper = f if has_t...
Y
python
pytorch__pytorch
.github/scripts/test_trymerge.py
{ "start": 8441, "end": 23111 }
class ____(TestCase): def test_merge_rules_valid(self, *args: Any) -> None: "Test that merge_rules.yaml can be parsed" repo = DummyGitRepo() merge_rules = read_merge_rules(repo, "pytorch", "pytorch") self.assertGreater(len(merge_rules), 1) @mock.patch("trymerge.read_merge_rules"...
TestTryMerge
python
astropy__astropy
astropy/io/fits/hdu/table.py
{ "start": 1317, "end": 9130 }
class ____(_ValidHDU): """ A class for HDUs that have table-like data. This is used for both Binary/ASCII tables as well as Random Access Group HDUs (which are otherwise too dissimilar for tables to use _TableBaseHDU directly). """ _data_type = FITS_rec _columns_type = ColDefs # TODO:...
_TableLikeHDU
python
tensorflow__tensorflow
tensorflow/python/eager/tensor_test.py
{ "start": 1848, "end": 19741 }
class ____(test_util.TensorFlowTestCase): def testScalarTensor(self): t = _create_tensor(3, dtype=dtypes.int32) self.assertAllEqual(t, _create_tensor(np.array(3))) self.assertEqual(dtypes.int32, t.dtype) self.assertEqual(0, t.shape.ndims) self.assertAllEqual([], t.shape.as_list()) self.assert...
TFETensorTest
python
great-expectations__great_expectations
great_expectations/core/expectation_diagnostics/supporting_types.py
{ "start": 411, "end": 645 }
class ____(str, Enum): """The four levels of maturity for features within Great Expectations""" CONCEPT_ONLY = "CONCEPT_ONLY" EXPERIMENTAL = "EXPERIMENTAL" BETA = "BETA" PRODUCTION = "PRODUCTION" @dataclass
Maturity
python
airbytehq__airbyte
airbyte-ci/connectors/erd/src/erd/dbml_assembler.py
{ "start": 3228, "end": 9140 }
class ____: def assemble( self, source: Source, discovered_catalog: AirbyteCatalog, relationships: Relationships, ) -> Database: database = Database() for stream in discovered_catalog.streams: if source.is_dynamic(stream.name): print(f"...
DbmlAssembler
python
dagster-io__dagster
scripts/gen_airbyte_classes.py
{ "start": 1241, "end": 2845 }
class ____(ABC): """Corresponds to the Python type of a field in a schema, has methods to generate the Python code to annotate that type or check it at runtime. """ description: Optional[str] = None @abstractmethod def get_check(self, name: str, scope: Optional[str] = None) -> str: """...
SchemaType
python
docker__docker-py
docker/types/containers.py
{ "start": 571, "end": 2925 }
class ____(DictType): """ Configure logging for a container, when provided as an argument to :py:meth:`~docker.api.container.ContainerApiMixin.create_host_config`. You may refer to the `official logging driver documentation <https://docs.docker.com/config/containers/logging/configure/>`_ for mor...
LogConfig
python
PrefectHQ__prefect
tests/runner/test_runner.py
{ "start": 76602, "end": 109759 }
class ____: @pytest.fixture def relative_file_path(self): return Path(__file__).relative_to(Path.cwd()) @pytest.fixture def dummy_flow_1_entrypoint(self, relative_file_path): return f"{relative_file_path}:dummy_flow_1" @pytest.mark.parametrize( "dummy_flow, flow_name, entry...
TestRunnerDeployment
python
getsentry__sentry
src/sentry/workflow_engine/processors/data_condition.py
{ "start": 123, "end": 655 }
class ____(NamedTuple): fast: list[DataCondition] slow: list[DataCondition] def split_conditions_by_speed( conditions: list[DataCondition], ) -> SplitConditions: fast_conditions: list[DataCondition] = [] slow_conditions: list[DataCondition] = [] for condition in conditions: if is_slow...
SplitConditions
python
celery__celery
t/unit/utils/test_platforms.py
{ "start": 5224, "end": 5575 }
class ____: def test_call(self): set_pdeathsig('SIGKILL') @t.skip.if_win32 def test_call_with_correct_parameter(self): with patch('celery.platforms._set_pdeathsig') as _set_pdeathsig: set_pdeathsig('SIGKILL') _set_pdeathsig.assert_called_once_with(signal.SIGKILL) ...
test_set_pdeathsig
python
eventlet__eventlet
tests/db_pool_test.py
{ "start": 10232, "end": 10913 }
class ____(DBConnectionPool): __test__ = False # so that nose doesn't try to execute this directly def create_pool(self, min_size=0, max_size=1, max_idle=10, max_age=10, connect_timeout=0.5, module=None): if module is None: module = self._dbmodule return db_pool...
TpoolConnectionPool
python
scipy__scipy
benchmarks/benchmarks/stats_sampling.py
{ "start": 7908, "end": 8814 }
class ____(Benchmark): param_names = ['distribution'] params = [ # a subset of discrete distributions with finite domain. [['nhypergeom', (20, 7, 1)], ['hypergeom', (30, 12, 6)], ['nchypergeom_wallenius', (140, 80, 60, 0.5)], ['binom', (5, 0.4)]] ] def setup...
DiscreteGuideTable
python
nedbat__coveragepy
tests/test_testing.py
{ "start": 9325, "end": 10835 }
class ____(CoverageTest): """Tests of the failure assertions in check_coverage.""" CODE = """\ a, b = 1, 1 def oops(x): if x % 2: raise Exception("odd") try: a = 6 oops(1) a = 8 except: b = 10 as...
CheckCoverageTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/gcs.py
{ "start": 5726, "end": 66276 }
class ____(GoogleBaseHook): """Use the Google Cloud connection to interact with Google Cloud Storage.""" _conn: storage.Client | None = None def get_conn(self) -> storage.Client: """Return a Google Cloud Storage service object.""" if not self._conn: self._conn = storage.Client(...
GCSHook
python
huggingface__transformers
src/transformers/models/afmoe/modeling_afmoe.py
{ "start": 27524, "end": 30565 }
class ____(AfmoePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = AfmoeMo...
AfmoeForCausalLM
python
huggingface__transformers
src/transformers/models/glm4v/modular_glm4v.py
{ "start": 16764, "end": 17302 }
class ____(Qwen2_5_VisionPatchEmbed): def __init__(self, config: Glm4vVisionConfig) -> None: nn.Module.__init__(self) self.patch_size = config.patch_size self.temporal_patch_size = config.temporal_patch_size self.in_channels = config.in_channels self.embed_dim = config.hidden...
Glm4vVisionPatchEmbed
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/InteractiveParameter.py
{ "start": 239, "end": 2086 }
class ____: """Just for testing purposes""" value = None def printResult(func): @wraps(func) def wrapper(*args, **kwargs): LAST_RESULT.value = func(*args, **kwargs) QtWidgets.QMessageBox.information( QtWidgets.QApplication.activeWindow(), "Function Run!", ...
LAST_RESULT
python
kamyu104__LeetCode-Solutions
Python/count-submatrices-with-equal-frequency-of-x-and-y.py
{ "start": 727, "end": 1650 }
class ____(object): def numberOfSubmatrices(self, grid): """ :type grid: List[List[str]] :rtype: int """ result = 0 dp1 = [[0]*len(grid[0]) for _ in xrange(len(grid))] dp2 = [[0]*len(grid[0]) for _ in xrange(len(grid))] for i in xrange(len(grid)): ...
Solution2
python
ansible__ansible
test/lib/ansible_test/_util/controller/sanity/pylint/plugins/string_format.py
{ "start": 1067, "end": 2453 }
class ____(BaseChecker): """Checks string formatting operations to ensure that the format string is valid and the arguments match the format string. """ name = 'string' msgs = MSGS @check_messages(*(MSGS.keys())) def visit_call(self, node): """Visit a call node.""" func = u...
AnsibleStringFormatChecker
python
huggingface__transformers
src/transformers/models/siglip2/modeling_siglip2.py
{ "start": 15545, "end": 18315 }
class ____(PreTrainedModel): config: Siglip2Config base_model_prefix = "siglip2" input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = [ "Siglip2TextEmbeddings", "Siglip2VisionEmbeddings", "Siglip2EncoderLayer", "Siglip2Multi...
Siglip2PreTrainedModel
python
django__django
tests/composite_pk/models/tenant.py
{ "start": 44, "end": 141 }
class ____(models.Model): name = models.CharField(max_length=10, default="", blank=True)
Tenant
python
django__django
tests/one_to_one/models.py
{ "start": 1983, "end": 2089 }
class ____(models.Model): other = models.OneToOneField(Target, models.CASCADE, primary_key=True)
Pointer
python
sqlalchemy__sqlalchemy
test/orm/test_events.py
{ "start": 72031, "end": 73213 }
class ____(_fixtures.FixtureTest): run_inserts = None @classmethod def setup_mappers(cls): User, users = cls.classes.User, cls.tables.users cls.mapper_registry.map_imperatively(User, users) def _fixture(self): User = self.classes.User canary = [] def load(tar...
LoadTest
python
kamyu104__LeetCode-Solutions
Python/threshold-majority-queries.py
{ "start": 120, "end": 2668 }
class ____(object): def subarrayMajority(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: List[int] """ # reference: https://cp-algorithms.com/data_structures/sqrt_decomposition.html def mo_s_algorithm(): # Time: O(QlogQ ...
Solution
python
celery__celery
celery/exceptions.py
{ "start": 7431, "end": 7529 }
class ____(TaskError): """The task has been revoked, so no result available."""
TaskRevokedError
python
huggingface__transformers
src/transformers/models/t5gemma/modular_t5gemma.py
{ "start": 15725, "end": 19653 }
class ____(Gemma2Attention): def __init__(self, config: T5GemmaModuleConfig, layer_idx: int): super().__init__(config, layer_idx) del self.sliding_window del self.layer_type self.is_causal = False if config.cross_attention_hidden_size is None: raise ValueError("C...
T5GemmaCrossAttention
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/scanner.py
{ "start": 82103, "end": 89273 }
class ____(Scanner): # RoundTripScanner Split Comments def __init__(self, *arg, **kw): # type: (Any, Any) -> None super().__init__(*arg, **kw) assert self.loader is not None # comments isinitialised on .need_more_tokens and persist on # self.loader.parsed_comments se...
RoundTripScannerSC
python
tensorflow__tensorflow
tensorflow/python/ops/linalg/linear_operator_circulant.py
{ "start": 50732, "end": 59887 }
class ____(_BaseLinearOperatorCirculant): """`LinearOperator` acting like a nested block circulant matrix. This operator acts like a block circulant matrix `A` with shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]...
LinearOperatorCirculant3D
python
scrapy__scrapy
tests/test_spidermiddleware_httperror.py
{ "start": 452, "end": 2001 }
class ____(MockServerSpider): name = "httperror" bypass_status_codes: set[int] = set() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.start_urls = [ self.mockserver.url("/status?n=200"), self.mockserver.url("/status?n=404"), s...
_HttpErrorSpider
python
python__mypy
mypyc/test-data/fixtures/ir.py
{ "start": 11341, "end": 11922 }
class ____(Generic[_T]): def __init__(self, i: Optional[Iterable[_T]] = None) -> None: pass def __iter__(self) -> Iterator[_T]: pass def __len__(self) -> int: pass def add(self, x: _T) -> None: pass def remove(self, x: _T) -> None: pass def discard(self, x: _T) -> None: pass def clear(self) ...
set
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 5880, "end": 6321 }
class ____(StructTestFunction): def f(self, x): return ( -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0)))) - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) ) g = None cons = wrap_constraints(g) test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)], ...
StructTest5
python
doocs__leetcode
solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/Solution.py
{ "start": 0, "end": 167 }
class ____: def digitCount(self, num: str) -> bool: cnt = Counter(int(x) for x in num) return all(cnt[i] == int(x) for i, x in enumerate(num))
Solution
python
sympy__sympy
sympy/series/order.py
{ "start": 422, "end": 19558 }
class ____(Expr): r""" Represents the limiting behavior of some function. Explanation =========== The order of a function characterizes the function based on the limiting behavior of the function as it goes to some limit. Only taking the limit point to be a number is currently supported. This ...
Order
python
python-excel__xlrd
tests/test_cell.py
{ "start": 177, "end": 1901 }
class ____(unittest.TestCase): def setUp(self): self.book = xlrd.open_workbook(from_sample('profiles.xls'), formatting_info=True) self.sheet = self.book.sheet_by_name('PROFILEDEF') def test_empty_cell(self): sheet = self.book.sheet_by_name('TRAVERSALCHAINAGE') cell = sheet.cell...
TestCell
python
marshmallow-code__apispec
tests/test_ext_marshmallow_openapi.py
{ "start": 15104, "end": 15183 }
class ____(Schema): offset = fields.Int() limit = fields.Int()
PageSchema
python
doocs__leetcode
solution/1200-1299/1232.Check If It Is a Straight Line/Solution.py
{ "start": 0, "end": 298 }
class ____: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x1, y1 = coordinates[0] x2, y2 = coordinates[1] for x, y in coordinates[2:]: if (x - x1) * (y2 - y1) != (y - y1) * (x2 - x1): return False return True
Solution
python
kamyu104__LeetCode-Solutions
Python/jump-game-iv.py
{ "start": 50, "end": 770 }
class ____(object): def minJumps(self, arr): """ :type arr: List[int] :rtype: int """ groups = collections.defaultdict(list) for i, x in enumerate(arr): groups[x].append(i) q = collections.deque([(0, 0)]) lookup = set([0]) while q: ...
Solution
python
redis__redis-py
redis/exceptions.py
{ "start": 550, "end": 597 }
class ____(ResponseError): pass
NoScriptError
python
getsentry__sentry
tests/sentry/integrations/jira_server/test_integration.py
{ "start": 45833, "end": 51095 }
class ____(JiraServerIntegrationBaseTest): def test_update_organization_config_sync_keys(self) -> None: integration = self.create_provider_integration(provider="jira_server", name="Example Jira") integration.add_organization(self.organization, self.user) installation = integration.get_insta...
JiraServerControlIntegrationTest
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 10414, "end": 10959 }
class ____: @property def xtype(self): """Extended data type information.""" return self._xtype @xtype.setter def xtype(self, xtype): if xtype is not None and not self._config.get("version_1_2_or_later"): warn_or_raise( W28, W28, ("xtype", self._eleme...
_XtypeProperty
python
kamyu104__LeetCode-Solutions
Python/split-and-merge-array-transformation.py
{ "start": 1311, "end": 2440 }
class ____(object): def minSplitMerge(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ def bfs(start, target): def adj(arr): for l in xrange(len(arr)): for r in xrange(l, len(arr)): ...
Solution2
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/definition/asset_graph_computation.py
{ "start": 10694, "end": 12740 }
class ____: """A graph where each node is a NodeOutputHandle corresponding to an op. There's an edge from op_output_1 to op_output_2 if op_output_2 is part of an op that has an input that's connected to op_output_1. """ op_output_handles: AbstractSet[NodeOutputHandle] upstream: Mapping[NodeOutp...
OpOutputHandleGraph
python
getsentry__sentry
src/sentry/deletions/defaults/pullrequest.py
{ "start": 256, "end": 823 }
class ____(ModelDeletionTask[PullRequest]): def get_query_filter(self) -> Q: """ Returns a Q object that filters for unused PRs. """ cutoff = datetime.now(timezone.utc) - timedelta(days=90) return PullRequest.get_unused_filter(cutoff) def get_child_relations(self, instan...
PullRequestDeletionTask
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 323283, "end": 332114 }
class ____: def test_trivial(self): # A trivial test of stats.f_oneway, with F=0. F, p = stats.f_oneway([0, 2], [0, 2]) assert_equal(F, 0.0) assert_equal(p, 1.0) def test_basic(self): # Despite being a floating point calculation, this data should # result in F b...
TestFOneWay
python
airbytehq__airbyte
airbyte-integrations/connectors/source-gcs/source_gcs/config.py
{ "start": 1059, "end": 1626 }
class ____(BaseModel): class Config(OneOfOptionConfig): title = "Service Account Authentication." auth_type: Literal["Service"] = Field("Service", const=True) service_account: str = Field( title="Service Account Information.", airbyte_secret=True, description=( '...
ServiceAccountCredentials
python
scipy__scipy
scipy/spatial/tests/test_distance.py
{ "start": 28092, "end": 57809 }
class ____: def setup_method(self): self.rnd_eo_names = ['random-float32-data', 'random-int-data', 'random-uint-data', 'random-double-data', 'random-bool-data'] self.valid_upcasts = {'bool': [np_ulong, np_long, np.float32, np.float64], ...
TestPdist
python
keon__algorithms
tests/test_sort.py
{ "start": 3449, "end": 4137 }
class ____(unittest.TestCase): def setUp(self): self.depGraph = { "a": ["b"], "b": ["c"], "c": ['e'], 'e': ['g'], "d": [], "f": ["e", "d"], ...
TestTopSort
python
neetcode-gh__leetcode
python/1582-special-positions-in-a-binary-matrix.py
{ "start": 0, "end": 545 }
class ____: def numSpecial(self, mat: List[List[int]]) -> int: m = len(mat) n = len(mat[0]) rowCount = [0] * m colCount = [0] * n res = 0 for r in range(m): for c in range(n): if mat[r][c] == 1: rowCount[r] += 1 ...
Solution
python
spyder-ide__spyder
spyder/widgets/findreplace.py
{ "start": 1623, "end": 31555 }
class ____(QWidget, SpyderShortcutsMixin): """Find widget""" # For shortcuts CONF_SECTION = 'find_replace' TOOLTIP = { 'regexp_error': _("Regular expression error"), 'no_matches': _("No matches") } visibility_changed = Signal(bool) return_shift_pressed = Signal() retur...
FindReplace
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_print_area01.py
{ "start": 315, "end": 1539 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("print_area01.xlsx") self.ignore_files = [ "xl/printerSettings/printerSettings1.bin", "xl/worksheets/_rels/sheet1.xml.re...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/got_ocr2/modular_got_ocr2.py
{ "start": 9456, "end": 9911 }
class ____(SamVisionLayer): def __init__(self, config, window_size): super().__init__(config, window_size) self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.attn = GotOcr2VisionAttention(config, window_size) self.layer_norm2 = nn.LayerNorm(config.hid...
GotOcr2VisionLayer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 45722, "end": 46290 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("assignable_id", "assignee_ids", "client_mutation_id") assignable_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="assignableId" ) assignee_ids = s...
AddAssigneesToAssignableInput
python
apache__airflow
providers/google/tests/unit/google/common/hooks/test_base_google.py
{ "start": 31582, "end": 36127 }
class ____: def setup_method(self): with mock.patch( MODULE_NAME + ".GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.instance = hook.GoogleBaseHook(gcp_conn_id="google-cloud-default") @mock.patch( "airflow.providers.google...
TestProvideAuthorizedGcloud