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
dagster-io__dagster
python_modules/dagster/dagster/_core/launcher/base.py
{ "start": 1691, "end": 3975 }
class ____(ABC, MayHaveInstanceWeakref[T_DagsterInstance]): @abstractmethod def launch_run(self, context: LaunchRunContext) -> None: """Launch a run. This method should begin the execution of the specified run, and may emit engine events. Runs should be created in the instance (e.g., by...
RunLauncher
python
pytorch__pytorch
test/test_testing.py
{ "start": 55695, "end": 64296 }
class ____(TestCase): supported_dtypes = dtypes( torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.float16, torch.bfloat16, torch.float32, torch.float64, torch.complex32, torch.complex64, torch.complex128, ) @supported_dtypes @parametrize(...
TestMakeTensor
python
ray-project__ray
rllib/core/models/base.py
{ "start": 653, "end": 6446 }
class ____(abc.ABC): """Framework-agnostic base class for RLlib models. Models are low-level neural network components that offer input- and output-specification, a forward method, and a get_initial_state method. Models are composed in RLModules. Usage Example together with ModelConfig: .. te...
Model
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 7170, "end": 7774 }
class ____(BadRequest): """Internal exception that is raised if Werkzeug detects a disconnected client. Since the client is already gone at that point attempting to send the error message to the client might not work and might ultimately result in another exception in the server. Mainly this is here s...
ClientDisconnected
python
django-import-export__django-import-export
tests/core/tests/test_tmp_storages.py
{ "start": 810, "end": 913 }
class ____(TempFolderStorage): def get_full_path(self): return "/tmp/f"
TestTempFolderStorage
python
PrefectHQ__prefect
tests/server/models/test_workers.py
{ "start": 15570, "end": 19994 }
class ____: @pytest.fixture(autouse=True) async def queues(self, session, work_pool): queues = {} # rename the default queue "A" queues["A"] = await models.workers.read_work_queue( session=session, work_queue_id=work_pool.default_queue_id ) queues["A"].name =...
TestUpdateWorkQueuePriorities
python
huggingface__transformers
tests/models/glpn/test_modeling_glpn.py
{ "start": 1677, "end": 5406 }
class ____: def __init__( self, parent, batch_size=13, image_size=64, num_channels=3, num_encoder_blocks=4, depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], hidden_sizes=[16, 32, 64, 128], downsampling_rates=[1, 4, 8, 16], num_atten...
GLPNModelTester
python
huggingface__transformers
src/transformers/models/longcat_flash/modular_longcat_flash.py
{ "start": 1744, "end": 1878 }
class ____(DeepseekV3RotaryEmbedding): pass # TODO remap config key ffn_hidden_size -> intermediate_size
LongcatFlashRotaryEmbedding
python
pypa__pip
src/pip/_vendor/rich/_win32_console.py
{ "start": 1544, "end": 1801 }
class ____(Structure): _fields_ = [ ("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", wintypes.WORD), ("srWindow", wintypes.SMALL_RECT), ("dwMaximumWindowSize", COORD), ]
CONSOLE_SCREEN_BUFFER_INFO
python
getsentry__sentry
src/sentry/similarity/backends/abstract.py
{ "start": 42, "end": 937 }
class ____(metaclass=ABCMeta): @abstractmethod def classify(self, scope, items, limit=None, timestamp=None): pass @abstractmethod def compare(self, scope, key, items, limit=None, timestamp=None): pass @abstractmethod def record(self, scope, key, items, timestamp=None): ...
AbstractIndexBackend
python
gevent__gevent
src/greentest/3.14/test_urllib.py
{ "start": 59133, "end": 71931 }
class ____(unittest.TestCase): """Test pathname2url() and url2pathname()""" def test_basic(self): # Make sure simple tests pass expected_path = os.path.join("parts", "of", "a", "path") expected_url = "parts/of/a/path" result = urllib.request.pathname2url(expected_path) s...
Pathname_Tests
python
milvus-io__pymilvus
pymilvus/client/interceptor.py
{ "start": 3099, "end": 3215 }
class ____(NamedTuple): method: Any timeout: Any metadata: Any credentials: Any
ClientCallDetailsTuple
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/run_request.py
{ "start": 12298, "end": 16425 }
class ____( NamedTuple( "_SensorResult", [ ("run_requests", Optional[Sequence[RunRequest]]), ("skip_reason", Optional[SkipReason]), ("cursor", Optional[str]), ( "dynamic_partitions_requests", Optional[ ...
SensorResult
python
pypa__pipenv
pipenv/vendor/click/types.py
{ "start": 6623, "end": 7427 }
class ____(ParamType): name = "text" def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: if isinstance(value, bytes): enc = _get_argv_encoding() try: value = value.decode(enc) except Unic...
StringParamType
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 63304, "end": 63847 }
class ____(SimpleTestCase): def test_noncallable_view(self): # View is not a callable (explicit import; arbitrary Python object) with self.assertRaisesMessage(TypeError, "view must be a callable"): path("uncallable-object/", views.uncallable) def test_invalid_regex(self): # ...
ErroneousViewTests
python
kubernetes-client__python
kubernetes/client/models/v1_affinity.py
{ "start": 383, "end": 5091 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1Affinity
python
numba__numba
numba/core/interpreter.py
{ "start": 839, "end": 1149 }
class ____(object): """Represents an unknown value, this is for ease of debugging purposes only. """ def __init__(self, varname): self._varname = varname def __repr__(self): return "_UNKNOWN_VALUE({})".format(self._varname) _logger = logging.getLogger(__name__)
_UNKNOWN_VALUE
python
huggingface__transformers
tests/utils/test_model_output.py
{ "start": 6221, "end": 6424 }
class ____(ModelOutput): """Invalid test subclass of ModelOutput where @dataclass decorator is not used""" a: float b: float | None = None c: float | None = None
ModelOutputTestNoDataclass
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 41956, "end": 42203 }
class ____(CacheArtifact): @override def populate_cache(self) -> None: FxGraphCache._write_to_local_cache(self.key, self.content) @override @staticmethod def type() -> str: return "inductor"
InductorCacheArtifact
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 58355, "end": 61995 }
class ____(BaseDataset): """ Feature: Compound types correctly round-trip """ def test_rt(self): """ Compound types are read back in correct order (issue 236)""" dt = np.dtype([ ('weight', np.float64), ('cputime', np.float64), ...
TestCompound
python
pytest-dev__pytest
testing/example_scripts/fixtures/fill_fixtures/test_funcarg_lookup_modulelevel.py
{ "start": 158, "end": 319 }
class ____: def test_method(self, something): assert something == "test_method" def test_func(something): assert something == "test_func"
TestClass
python
redis__redis-py
redis/asyncio/connection.py
{ "start": 29382, "end": 31812 }
class ____(Connection): """Manages SSL connections to and from the Redis server(s). This class extends the Connection class, adding SSL functionality, and making use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext) """ def __init__( self, ssl_keyfile: Op...
SSLConnection
python
plotly__plotly.py
plotly/graph_objs/isosurface/_slices.py
{ "start": 233, "end": 3891 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "isosurface" _path_str = "isosurface.slices" _valid_props = {"x", "y", "z"} @property def x(self): """ The 'x' property is an instance of X that may be specified as: - An instance of :class:`plotly.graph_objs....
Slices
python
ApeWorX__ape
src/ape_console/_cli.py
{ "start": 1910, "end": 7987 }
class ____(dict): def __init__(self, **kwargs): # Initialize the dictionary with provided keyword arguments project = kwargs.get("project", self._ape.project) kwargs["project"] = self._ape.Project(project) if isinstance(project, Path) else project super().__init__(**kwargs) def ...
ApeConsoleNamespace
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 38154, "end": 39581 }
class ____(Response): """ Response of queues.get_default endpoint. :param id: Queue id :type id: str :param name: Queue name :type name: str """ _service = "queues" _action = "get_default" _version = "2.9" _schema = { "definitions": {}, "properties": { ...
GetDefaultResponse
python
scipy__scipy
scipy/optimize/_trustregion_exact.py
{ "start": 5830, "end": 16672 }
class ____(BaseQuadraticSubproblem): """Quadratic subproblem solved by nearly exact iterative method. Notes ----- This subproblem solver was based on [1]_, [2]_ and [3]_, which implement similar algorithms. The algorithm is basically that of [1]_ but ideas from [2]_ and [3]_ were also used. ...
IterativeSubproblem
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 59263, "end": 61620 }
class ____: async def test_timeout_async_task(self): @task(timeout_seconds=0.1) async def async_task(): await asyncio.sleep(2) with pytest.raises(TimeoutError, match=".*timed out after 0.1 second(s)*"): await run_task_async(async_task) @pytest.mark.xfail( ...
TestTimeout
python
huggingface__transformers
src/transformers/models/internvl/modeling_internvl.py
{ "start": 6974, "end": 7386 }
class ____(BaseModelOutputWithPooling): r""" pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if *config.use_mean_pooling* is set to True. If set to False, then the final hidden sta...
InternVLVisionModelOutputWithPooling
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 1961, "end": 2041 }
class ____(Cuda_array_decl): key = cuda.local.array @register
Cuda_local_array
python
huggingface__transformers
src/transformers/models/bridgetower/configuration_bridgetower.py
{ "start": 857, "end": 3809 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the vision configuration of a [`BridgeTowerModel`]. Instantiating a configuration with the defaults will yield a similar configuration to that of the bridgetower-base [BridgeTower/bridgetower-base](https://huggingface.co/BridgeT...
BridgeTowerVisionConfig
python
xlwings__xlwings
xlwings/main.py
{ "start": 150109, "end": 151076 }
class ____(Apps): def __init__(self): pass _name = "Apps" @property def impl(self): if engines.active is None: if not ( sys.platform.startswith("darwin") or sys.platform.startswith("win") ): raise XlwingsError( ...
ActiveEngineApps
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/prefect_kubernetes/credentials.py
{ "start": 853, "end": 4147 }
class ____(Block): """ Stores configuration for interaction with Kubernetes clusters. See `from_file` for creation. Attributes: config: The entire loaded YAML contents of a kubectl config file context_name: The name of the kubectl context to use Example: Load a saved Kuber...
KubernetesClusterConfig
python
streamlit__streamlit
lib/tests/streamlit/watcher/event_based_path_watcher_test.py
{ "start": 799, "end": 18708 }
class ____(unittest.TestCase): """Test EventBasedPathWatcher.""" def setUp(self): # This test suite patches MultiPathWatcher. A MultiPathWatcher may # already exist (another test may have directly or indirectly created # one), so we first close any existing watcher instance here. ...
EventBasedPathWatcherTest
python
mwaskom__seaborn
seaborn/_stats/counting.py
{ "start": 389, "end": 1090 }
class ____(Stat): """ Count distinct observations within groups. See Also -------- Hist : A more fully-featured transform including binning and/or normalization. Examples -------- .. include:: ../docstrings/objects.Count.rst """ group_by_orient: ClassVar[bool] = True def ...
Count
python
kamyu104__LeetCode-Solutions
Python/number-of-students-unable-to-eat-lunch.py
{ "start": 50, "end": 484 }
class ____(object): def countStudents(self, students, sandwiches): """ :type students: List[int] :type sandwiches: List[int] :rtype: int """ count = collections.Counter(students) for i, s in enumerate(sandwiches): if not count[s]: b...
Solution
python
pytorch__pytorch
torch/testing/_internal/distributed/_shard/sharded_tensor/_test_st_common.py
{ "start": 686, "end": 1120 }
class ____(torch.nn.Module): def __init__(self, spec=None, group=None, init_rrefs=True) -> None: super().__init__() if spec is not None: self.sharded_tensor2 = sharded_tensor.rand( spec, 10, 20, process_group=group, init_rrefs=init_rrefs ) else: ...
MyShardedModel2
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/readability_web/base.py
{ "start": 585, "end": 5122 }
class ____(BaseReader): """ Readability Webpage Loader. Extracting relevant information from a fully rendered web page. During the processing, it is always assumed that web pages used as data sources contain textual content. 1. Load the page and wait for it rendered. (playwright) 2. Inject Rea...
ReadabilityWebPageReader
python
mlflow__mlflow
mlflow/types/schema.py
{ "start": 11040, "end": 17264 }
class ____(BaseType): """ Specification used to represent a json-convertible object. """ def __init__(self, properties: list[Property]) -> None: self._check_properties(properties) # Sort by name to make sure the order is stable self._properties = sorted(properties) def _che...
Object
python
mlflow__mlflow
tests/store/artifact/test_azure_data_lake_artifact_repo.py
{ "start": 1118, "end": 15727 }
class ____: def __init__(self, items, next_marker=None): self.items = items self.next_marker = next_marker def __iter__(self): return iter(self.items) @pytest.fixture def mock_data_lake_client(): mock_adls_client = mock.MagicMock(autospec=DataLakeServiceClient) with mock.patch...
MockPathList
python
PrefectHQ__prefect
tests/cli/test_profile.py
{ "start": 19109, "end": 23227 }
class ____: def test_populate_defaults(self, temporary_profiles_path: Path): default_profiles = _read_profiles_from(DEFAULT_PROFILES_PATH) assert not temporary_profiles_path.exists() invoke_and_assert( ["profile", "populate-defaults"], user_input="y", ex...
TestProfilesPopulateDefaults
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_reflection.py
{ "start": 2081, "end": 6939 }
class ____(OneConnectionTablesTest): __sparse_driver_backend__ = True run_deletes = None @classmethod def define_tables(cls, metadata): Table( "test_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(50)), ) ...
HasTableTest
python
django__django
tests/forms_tests/field_tests/test_timefield.py
{ "start": 184, "end": 2035 }
class ____(FormFieldAssertionsMixin, SimpleTestCase): def test_timefield_1(self): f = TimeField() self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14,...
TimeFieldTest
python
google__jax
jax/experimental/mosaic/gpu/examples/matmul.py
{ "start": 1450, "end": 1681 }
class ____: m: int n: int k: int # Allow access by .mk, .kn, .mn, etc. def __getattr__(self, name): if len(name) == 1: return super().__getattribute__(name) return tuple(getattr(self, d) for d in name)
Tiling
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 44178, "end": 44469 }
class ____(sgqlc.types.Scalar): """ See source code for more info. """ __schema__ = graphql_schema ######################################################################## # Input Objects ########################################################################
X509Certificate
python
kamyu104__LeetCode-Solutions
Python/count-the-number-of-powerful-integers.py
{ "start": 54, "end": 1058 }
class ____(object): def numberOfPowerfulInt(self, start, finish, limit, s): """ :type start: int :type finish: int :type limit: int :type s: str :rtype: int """ def count(x): def length(x): result = 0 while x...
Solution
python
huggingface__transformers
tests/models/bridgetower/test_modeling_bridgetower.py
{ "start": 5251, "end": 10818 }
class ____: def __init__( self, parent, text_kwargs=None, vision_kwargs=None, share_cross_modal_transformer_layers=True, share_link_tower_layers=False, link_tower_type="add", init_layernorm_from_vision_encoder=False, contrastive_hidden_size=512...
BridgeTowerModelTester
python
apache__thrift
lib/py/src/Thrift.py
{ "start": 1447, "end": 1984 }
class ____(object): """Base class for processor, which works on two streams.""" def process(self, iprot, oprot): """ Process a request. The normal behvaior is to have the processor invoke the correct handler and then it is the server's responsibility to write the response to op...
TProcessor
python
graphql-python__graphene
graphene/types/tests/test_datetime.py
{ "start": 189, "end": 7482 }
class ____(ObjectType): datetime = DateTime(_in=DateTime(name="in")) date = Date(_in=Date(name="in")) time = Time(_at=Time(name="at")) def resolve_datetime(self, info, _in=None): return _in def resolve_date(self, info, _in=None): return _in def resolve_time(self, info, _at=Non...
Query
python
walkccc__LeetCode
solutions/1862. Sum of Floored Pairs/1862.py
{ "start": 0, "end": 601 }
class ____: def sumOfFlooredPairs(self, nums: list[int]) -> int: MOD = 1_000_000_007 MAX = max(nums) ans = 0 count = [0] * (MAX + 1) for num in nums: count[num] += 1 for i in range(1, MAX + 1): count[i] += count[i - 1] for i in range(1, MAX + 1): if count[i] > count[i ...
Solution
python
spyder-ide__spyder
spyder/utils/syntaxhighlighters.py
{ "start": 73899, "end": 77215 }
class ____(BaseSH): """Markdown Syntax Highlighter""" # Syntax highlighting rules: PROG = re.compile(make_md_patterns(), re.S) NORMAL = 0 CODE = 1 def highlightBlock(self, text): text = str(text) previous_state = self.previousBlockState() if previous_state == self.CODE:...
MarkdownSH
python
chroma-core__chroma
chromadb/auth/__init__.py
{ "start": 5316, "end": 6298 }
class ____(str, Enum): """ The set of actions that can be authorized by the authorization provider. """ RESET = "system:reset" CREATE_TENANT = "tenant:create_tenant" GET_TENANT = "tenant:get_tenant" CREATE_DATABASE = "db:create_database" GET_DATABASE = "db:get_database" DELETE_DATAB...
AuthzAction
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/class_interval.py
{ "start": 9950, "end": 10302 }
class ____(A22): def m1(self, arg): return arg def no_issue_taint_transform_with_class_interval(c: C22): # Should not see an issue, due to not going through the taint transform sink_d(c.m0(_test_source())) def add_feature_c(arg): return arg def add_feature_d(arg): return arg def add_...
C22
python
FactoryBoy__factory_boy
tests/test_using.py
{ "start": 80439, "end": 86028 }
class ____(unittest.TestCase): def test_related_factory_list_of_varying_size(self): # Create our list of expected "related object counts" related_list_sizes = [5, 5, 4, 4, 3, 3, 2, 2, 1, 1] RELATED_LIST_SIZE = lambda: related_list_sizes.pop() class TestRelatedObject: def...
RelatedListFactoryTestCase
python
kamyu104__LeetCode-Solutions
Python/toss-strange-coins.py
{ "start": 31, "end": 424 }
class ____(object): def probabilityOfHeads(self, prob, target): """ :type prob: List[float] :type target: int :rtype: float """ dp = [0.0]*(target+1) dp[0] = 1.0 for p in prob: for i in reversed(xrange(target+1)): dp[i] = (d...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/typing.py
{ "start": 19447, "end": 19986 }
class ____(Generic[_DESC_co]): """a descriptor that refers to a descriptor. same as :class:`.DescriptorReference` but is read-only, so that subclasses can define a subtype as the generically contained element """ if TYPE_CHECKING: def __get__(self, instance: object, owner: Any) -> _DESC_...
RODescriptorReference
python
Textualize__textual
src/textual/css/_style_properties.py
{ "start": 22165, "end": 23788 }
class ____: """Descriptor for getting and setting layout.""" def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__( self, obj: StylesBase, objtype: type[StylesBase] | None = None ) -> Layout | None: """ Args: obj: The Sty...
LayoutProperty
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_basic.py
{ "start": 54665, "end": 60152 }
class ____(fixtures.MappedTest): """test that the 'optimized get' path accommodates deferred columns. Original issue tested is #3468, where loading of a deferred column in an inherited subclass would fail. At some point, the logic tested was no longer used and a less efficient query was used to lo...
OptimizedGetOnDeferredTest
python
getsentry__sentry
src/sentry/dynamic_sampling/rules/helpers/latest_releases.py
{ "start": 1866, "end": 2264 }
class ____(BoostedRelease): """ Class the represents a boosted release with added information that are injected after the base release is fetched from the cache. """ version: str platform: Platform def is_active(self, current_timestamp: float) -> bool: return current_timestamp <= s...
ExtendedBoostedRelease
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-bedrock/llama_index/llms/bedrock/utils.py
{ "start": 6387, "end": 6883 }
class ____(Provider): max_tokens_key = "maxTokenCount" def get_text_from_response(self, response: dict) -> str: return response["results"][0]["outputText"] def get_text_from_stream_response(self, response: dict) -> str: return response["outputText"] def get_request_body(self, prompt: ...
AmazonProvider
python
google__jax
jax/_src/interpreters/batching.py
{ "start": 18737, "end": 38346 }
class ____(Trace): def __init__(self, parent_trace, tag, axis_data): super().__init__() self.parent_trace = parent_trace assert isinstance(axis_data, AxisData) self.axis_data = axis_data self.tag = tag self.requires_low = False def to_batch_info(self, val): if isinstance(val, BatchTrac...
BatchTrace
python
joke2k__faker
faker/providers/currency/pt_BR/__init__.py
{ "start": 46, "end": 262 }
class ____(CurrencyProvider): price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"] def pricetag(self) -> str: return "R$" + self.numerify(self.random_element(self.price_formats))
Provider
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/decl_base.py
{ "start": 76833, "end": 80123 }
class ____(_ClassScanAbstractConfig): """Configurator that will produce an unmapped dataclass.""" __slots__ = ( "clsdict_view", "collected_attributes", "collected_annotations", "allow_dataclass_fields", "dataclass_setup_arguments", "is_dataclass_prior_to_mapping"...
_UnmappedDataclassConfig
python
encode__django-rest-framework
rest_framework/schemas/openapi.py
{ "start": 3954, "end": 26873 }
class ____(ViewInspector): def __init__(self, tags=None, operation_id_base=None, component_name=None): """ :param operation_id_base: user-defined name in operationId. If empty, it will be deducted from the Model/Serializer/View name. :param component_name: user-defined component's name. If ...
AutoSchema
python
getsentry__sentry
tests/sentry/uptime/endpoints/test_project_uptime_alert_details.py
{ "start": 9220, "end": 9912 }
class ____(ProjectUptimeAlertDetailsBaseEndpointTest): method = "delete" def test_user(self) -> None: detector = self.create_uptime_detector() with self.tasks(): self.get_success_response( self.organization.slug, detector.project.slug, ...
ProjectUptimeAlertDetailsDeleteEndpointTest
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/test_security.py
{ "start": 3871, "end": 4194 }
class ____(ModelView): datamodel = SQLAInterface(SomeModel) base_permissions = [ "can_list", "can_show", "can_add", permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_DELETE, ] list_columns = ["field_string", "field_integer", "field_float", "field_date"]
SomeModelView
python
numpy__numpy
numpy/distutils/fcompiler/pathf95.py
{ "start": 85, "end": 1061 }
class ____(FCompiler): compiler_type = 'pathf95' description = 'PathScale Fortran Compiler' version_pattern = r'PathScale\(TM\) Compiler Suite: Version (?P<version>[\d.]+)' executables = { 'version_cmd' : ["pathf95", "-version"], 'compiler_f77' : ["pathf95", "-fixedform"], 'c...
PathScaleFCompiler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride2.py
{ "start": 139, "end": 788 }
class ____: def f1(self, *, kwarg0: int) -> None: ... def f2(self, *, kwarg0: int) -> None: ... def f3(self, *, kwarg0: int) -> None: ... def f4(self, *, kwarg0: int) -> None: ... def g1(self, a: int, /, b: str, *, kwarg0: int) -> None: ... def g2(self, a: int, /, b: str, *, kwarg0: int) ->...
Base1
python
pypa__pipenv
pipenv/vendor/pipdeptree/_models/dag.py
{ "start": 10056, "end": 11302 }
class ____(PackageDAG): """ Representation of Package dependencies in the reverse order. Similar to it's super class `PackageDAG`, the underlying datastructure is a dict, but here the keys are expected to be of type `ReqPackage` and each item in the values of type `DistPackage`. Typically, this ob...
ReversedPackageDAG
python
walkccc__LeetCode
solutions/70. Climbing Stairs/70.py
{ "start": 0, "end": 234 }
class ____: def climbStairs(self, n: int) -> int: # dp[i] := the number of ways to climb to the i-th stair dp = [1, 1] + [0] * (n - 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]
Solution
python
imageio__imageio
imageio/plugins/simpleitk.py
{ "start": 1782, "end": 4106 }
class ____(Format): """See :mod:`imageio.plugins.simpleitk`""" def _can_read(self, request): # If the request is a format that only this plugin can handle, # we report that we can do it; a useful error will be raised # when simpleitk is not installed. For the more common formats ...
ItkFormat
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 67770, "end": 75719 }
class ____(PatchTSTPreTrainedModel): def __init__(self, config: PatchTSTConfig): super().__init__(config) # Turn off masking if config.do_mask_input: logger.warning("Setting `do_mask_input` parameter to False.") config.do_mask_input = False self.model = Patc...
PatchTSTForPrediction
python
huggingface__transformers
src/transformers/models/roc_bert/modeling_roc_bert.py
{ "start": 1857, "end": 9063 }
class ____(nn.Module): """Construct the embeddings from word, position, shape, pronunciation and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.pron...
RoCBertEmbeddings
python
ray-project__ray
python/ray/tests/runtime_env_container/test_serve_basic.py
{ "start": 653, "end": 1056 }
class ____: def __call__(self): with open("file.txt") as f: return f.read().strip() def check_application(app_handle: DeploymentHandle, expected: str): ref = app_handle.remote() assert ref.result() == expected return True h = serve.run(Model.bind()) wait_for_condition( check_...
Model
python
getsentry__sentry
tests/sentry/seer/autofix/test_autofix.py
{ "start": 970, "end": 12343 }
class ____(TestCase): def test_convert_profile_to_execution_tree(self) -> None: profile_data = { "profile": { "frames": [ { "function": "main", "module": "app.main", "filename": "main.py",...
TestConvertProfileToExecutionTree
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_spans_histogram.py
{ "start": 553, "end": 1467 }
class ____(serializers.Serializer): span = serializers.CharField(required=True, allow_null=False) query = serializers.CharField(required=False) numBuckets = serializers.IntegerField(min_value=1, max_value=100) precision = serializers.IntegerField(default=0, min_value=0, max_value=4) min = serializer...
SpansHistogramSerializer
python
pydantic__pydantic
tests/test_json_schema.py
{ "start": 94424, "end": 94531 }
class ____(BaseModel): class NestedModel(BaseModel): a: Decimal nested: NestedModel
ModelOne
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_issues_resolved_in_release.py
{ "start": 334, "end": 5535 }
class ____(APITestCase, SnubaTestCase): endpoint = "sentry-api-0-organization-release-resolved" method = "get" def setUp(self) -> None: super().setUp() self.user = self.create_user() self.org = self.create_organization() self.team = self.create_team(organization=self.org) ...
OrganizationIssuesResolvedInReleaseEndpointTest
python
huggingface__transformers
src/transformers/models/bert/modeling_bert.py
{ "start": 22473, "end": 22955 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output)...
BertPreTrainingHeads
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_model.py
{ "start": 2426, "end": 4531 }
class ____(nn.Module): def __init__(self, config: ModelArgs) -> None: super().__init__() self.config = config self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim) self.layers = nn.ModuleList( TransformerBlock(config) for _ in range(config.n_layer) ) ...
Transformer
python
plotly__plotly.py
plotly/graph_objs/layout/coloraxis/_colorbar.py
{ "start": 235, "end": 61668 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.coloraxis" _path_str = "layout.coloraxis.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "mi...
ColorBar
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/custom_reports_validator.py
{ "start": 1219, "end": 3210 }
class ____: """ ERRORS_MAPPING holds an external `Pydantic.ValidationError` types and their placeholders. { key: str = <Pydantic.ValidationError Type>, value: tuple(str, list) = (<explainable message>, <list as placeholder> } """ errors_mapping = { "value_error.missing"...
Explainer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/function7.py
{ "start": 279, "end": 497 }
class ____: def write(self, a: str, /, b: str): pass def make_writer1(w: _Writer1): pass # This should generate an error because the source function is positional-only. make_writer1(Writer1())
Writer1
python
kamyu104__LeetCode-Solutions
Python/average-value-of-even-numbers-that-are-divisible-by-three.py
{ "start": 36, "end": 344 }
class ____(object): def averageValue(self, nums): """ :type nums: List[int] :rtype: int """ total = cnt = 0 for x in nums: if x%6: continue total += x cnt += 1 return total//cnt if cnt else 0
Solution
python
getsentry__sentry
tests/sentry/api/endpoints/test_api_applications.py
{ "start": 875, "end": 1227 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(self.user) url = reverse("sentry-api-0-api-applications") response = self.client.post(url, data={}) assert response.status_code == 201 assert ApiApplication.objects.get(client_id=response.data["id"], owner=...
ApiApplicationsCreateTest
python
sphinx-doc__sphinx
sphinx/domains/index.py
{ "start": 3108, "end": 4358 }
class ____(ReferenceRole): def run(self) -> tuple[list[Node], list[system_message]]: target_id = 'index-%s' % self.env.new_serialno('index') if self.has_explicit_title: # if an explicit target is given, process it as a full entry title = self.title entries = proce...
IndexRole
python
wandb__wandb
wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py
{ "start": 378, "end": 552 }
class ____(GQLResult): artifact_memberships: FetchLinkedArtifactsArtifactArtifactMemberships = Field( alias="artifactMemberships" )
FetchLinkedArtifactsArtifact
python
scikit-learn__scikit-learn
sklearn/linear_model/_ridge.py
{ "start": 46378, "end": 55519 }
class ____(_RidgeClassifierMixin, _BaseRidge): """Classifier using Ridge regression. This classifier first converts the target values into ``{-1, 1}`` and then treats the problem as a regression task (multi-output regression in the multiclass case). Read more in the :ref:`User Guide <ridge_regress...
RidgeClassifier
python
run-llama__llama_index
llama-index-core/llama_index/core/postprocessor/node.py
{ "start": 4681, "end": 9102 }
class ____(BaseNodePostprocessor): """ Previous/Next Node post-processor. Allows users to fetch additional nodes from the document store, based on the relationships of the nodes. NOTE: this is a beta feature. Args: docstore (BaseDocumentStore): The document store. num_nodes (i...
PrevNextNodePostprocessor
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/io.py
{ "start": 30544, "end": 33219 }
class ____(DataSourceInfo): """ In-memory DataFrame source information. Parameters ---------- df In-memory DataFrame source. stats_planning Statistics planning options. """ def __init__( self, df: pl.DataFrame, stats_planning: StatsPlanningOption...
DataFrameSourceInfo
python
imageio__imageio
imageio/core/request.py
{ "start": 996, "end": 1985 }
class ____(str, enum.Enum): """Available Image modes This is a helper enum for ``Request.Mode`` which is a composite of a ``Request.ImageMode`` and ``Request.IOMode``. The image mode that tells the plugin the desired (and expected) image shape. Available values are - single_image ("i"): Return a s...
ImageMode
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 45044, "end": 45422 }
class ____(FieldValues): valid_inputs = { '0.12345': Decimal('0.12345'), } invalid_inputs = { '0.1234567': ['Ensure that there are no more than 6 digits in total.'] } outputs = { '1.2345': '1.2345', '0': '0', '1.1': '1.1', } field = serializers.Decimal...
TestNoDecimalPlaces
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_restore.py
{ "start": 9584, "end": 21845 }
class ____(Callback): callbacks = [] def on_fit_start(self, trainer, pl_module): self.callbacks = deepcopy(trainer.callbacks) @RunIf(sklearn=True) def test_callbacks_state_fit_ckpt_path(tmp_path): """Test that resuming from a checkpoint restores callbacks that persist state.""" dm = ClassifDa...
CaptureCallbacksBeforeTraining
python
apache__airflow
providers/google/tests/unit/google/marketing_platform/operators/test_display_video.py
{ "start": 1455, "end": 4264 }
class ____: @mock.patch("airflow.providers.google.marketing_platform.operators.display_video.zipfile") @mock.patch("airflow.providers.google.marketing_platform.operators.display_video.os") @mock.patch( "airflow.providers.google.marketing_platform.operators.display_video.tempfile.TemporaryDirectory" ...
TestGoogleDisplayVideo360SDFtoGCSOperator
python
huggingface__transformers
src/transformers/models/qwen3_moe/modeling_qwen3_moe.py
{ "start": 17677, "end": 20699 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Qwen3MoeConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings sel...
Qwen3MoeRotaryEmbedding
python
scikit-learn__scikit-learn
sklearn/tests/metadata_routing_common.py
{ "start": 6743, "end": 7799 }
class ____(ClassifierMixin, BaseEstimator): """A classifier which accepts no metadata on any method.""" def __init__(self, alpha=0.0): self.alpha = alpha def fit(self, X, y): self.classes_ = np.unique(y) self.coef_ = np.ones_like(X) return self def partial_fit(self, X,...
NonConsumingClassifier
python
walkccc__LeetCode
solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py
{ "start": 60, "end": 96 }
class ____: summ: int count: int
T
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_step_function.py
{ "start": 1063, "end": 3585 }
class ____: def test_get_conn_returns_a_boto3_connection(self): hook = StepFunctionHook(aws_conn_id="aws_default") assert hook.get_conn().meta.service_model.service_name == "stepfunctions" def test_start_execution(self): hook = StepFunctionHook(aws_conn_id="aws_default", region_name="us...
TestStepFunctionHook
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 10388, "end": 11759 }
class ____(nn.Module): """ Rotary Position Embedding Class for CLVP. It was proposed in the paper 'ROFORMER: ENHANCED TRANSFORMER WITH ROTARY POSITION EMBEDDING', Please see https://huggingface.co/papers/2104.09864v1.pdf . """ def __init__(self, config): super().__init__() dim = max...
ClvpRotaryPositionalEmbedding
python
google__jax
tests/multiprocess/axis_index_test.py
{ "start": 692, "end": 1023 }
class ____(jt_multiprocess.MultiProcessTest): def test(self): f = jax.pmap(lambda _: lax.axis_index("i"), axis_name="i") n = jax.local_device_count() xs = np.arange(n) out = f(xs * 0) np.testing.assert_equal(out, xs + (n * jax.process_index())) if __name__ == "__main__": jt_multiprocess.main(...
AxisIndexTest
python
wandb__wandb
wandb/sdk/launch/registry/anon.py
{ "start": 168, "end": 943 }
class ____(AbstractRegistry): def __init__(self, uri: str) -> None: """Initialize the registry.""" self.uri = uri async def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry.""" raise NotImplementedError("Anonymous registry does no...
AnonynmousRegistry