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
kamyu104__LeetCode-Solutions
Python/most-profit-assigning-work.py
{ "start": 121, "end": 699 }
class ____(object): def maxProfitAssignment(self, difficulty, profit, worker): """ :type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int """ jobs = zip(difficulty, profit) jobs.sort() worker.sort() resu...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 986596, "end": 987119 }
class ____(sgqlc.types.Type): """Autogenerated return type of StartRepositoryMigration""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "repository_migration") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client...
StartRepositoryMigrationPayload
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 55589, "end": 60475 }
class ____(test_util.TensorFlowTestCase): def _testContrast(self, x_np, y_np, contrast_factor): with self.cached_session(): x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_contrast(x, contrast_factor) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, 1e-6) d...
AdjustContrastTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_dms.py
{ "start": 10316, "end": 22693 }
class ____: def setup_method(self): self.dms = DmsHook() def test_init(self): assert self.dms.aws_conn_id == "aws_default" @mock.patch.object(DmsHook, "get_conn") def test_describe_replication_tasks_with_no_tasks_found(self, mock_conn): mock_conn.return_value.describe_replicati...
TestDmsHook
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertsql.py
{ "start": 818, "end": 861 }
class ____(AssertRule): pass
SQLMatchRule
python
PyCQA__pyflakes
pyflakes/test/test_code_segment.py
{ "start": 222, "end": 4496 }
class ____(TestCase): """ Tests for segments of a module """ def test_function_segment(self): self.flakes(''' def foo(): def bar(): pass ''', is_segment=True) self.flakes(''' def foo(): def bar(): x = 0 ...
TestCodeSegments
python
oauthlib__oauthlib
tests/openid/connect/core/grant_types/test_authorization_code.py
{ "start": 588, "end": 854 }
class ____(AuthorizationCodeGrantTest): """Test that OpenID don't interfere with normal OAuth 2 flows.""" def setUp(self): super().setUp() self.auth = AuthorizationCodeGrant(request_validator=self.mock_validator)
OpenIDAuthCodeInterferenceTest
python
psf__requests
src/requests/exceptions.py
{ "start": 2158, "end": 2375 }
class ____(RequestException): """The request timed out. Catching this error will catch both :exc:`~requests.exceptions.ConnectTimeout` and :exc:`~requests.exceptions.ReadTimeout` errors. """
Timeout
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassKwOnly1.py
{ "start": 124, "end": 320 }
class ____: a: str _: KW_ONLY b: int = 0 DC1("hi") DC1(a="hi") DC1(a="hi", b=1) DC1("hi", b=1) # This should generate an error because "b" is keyword-only. DC1("hi", 1) @dataclass
DC1
python
huggingface__transformers
src/transformers/models/eomt/image_processing_eomt.py
{ "start": 7676, "end": 40441 }
class ____(BaseImageProcessor): r""" Constructs a EoMT image processor. The image processor can be used to prepare image(s) and optional targets for the model. This image processor inherits from [`BaseImageProcessor`] which contains most of the main methods. Users should refer to this superclass fo...
EomtImageProcessor
python
altair-viz__altair
altair/datasets/_typing.py
{ "start": 2097, "end": 6614 }
class ____(TypedDict, total=False): """ Full schema for ``metadata.parquet``. Parameters ---------- dataset_name Name of the dataset from the resource name field. suffix File extension/`Path.suffix`_. file_name Equivalent to `Path.name`_. bytes File size ...
Metadata
python
nryoung__algorithms
tests/test_searching.py
{ "start": 1229, "end": 1590 }
class ____(unittest.TestCase): """ Tests BMH search on string "ABCDE FG ABCDEABCDEF" """ def test_bmhsearch(self): self.string = "ABCDE FG ABCDEABCDEF" rv1 = bmh_search.search(self.string, "ABCDEA") rv2 = bmh_search.search(self.string, "ABCDER") self.assertIs(rv1[0], 9) ...
TestBMHSearch
python
ray-project__ray
python/ray/autoscaler/v2/tests/test_node_provider.py
{ "start": 3917, "end": 4630 }
class ____(CloudInstanceProviderTesterBase): def __init__(self, **kwargs): self.config_reader = FileConfigReader( get_test_config_path("test_ray_complex.yaml"), skip_content_hash=True ) self.config = self.config_reader.get_cached_autoscaling_config() self.base_provider = ...
MockProviderTester
python
django__django
tests/contenttypes_tests/test_models.py
{ "start": 430, "end": 12509 }
class ____(TestCase): def setUp(self): ContentType.objects.clear_cache() self.addCleanup(ContentType.objects.clear_cache) def test_lookup_cache(self): """ The content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model, ...
ContentTypesTests
python
ansible__ansible
test/lib/ansible_test/_internal/docker_util.py
{ "start": 28581, "end": 28855 }
class ____(DockerError): """The container identified by `identifier` was not found.""" def __init__(self, identifier: str) -> None: super().__init__('The container "%s" was not found.' % identifier) self.identifier = identifier
ContainerNotFoundError
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/responses.py
{ "start": 2786, "end": 5128 }
class ____(BaseModel): """ Solr search response. See `Solr documentation <https://solr.apache.org/guide/solr/latest/query-guide/response-writers.html#json-response-writer>`_ for details. """ response: SolrSelectResponseBody """The response contents for the input query, containing docum...
SolrSelectResponse
python
ansible__ansible
test/lib/ansible_test/_internal/cli/argparsing/parsers.py
{ "start": 6230, "end": 6406 }
class ____: """State of the composite argument parser's generated documentation.""" sections: dict[str, str] = dataclasses.field(default_factory=dict)
DocumentationState
python
ray-project__ray
rllib/evaluation/tests/test_episode_v2.py
{ "start": 380, "end": 720 }
class ____(Policy): @override(Policy) def compute_actions( self, obs_batch, state_batches=None, prev_action_batch=None, prev_reward_batch=None, episodes=None, explore=None, timestep=None, **kwargs ): return obs_batch.argmax(axis...
EchoPolicy
python
mlflow__mlflow
tests/pyfunc/test_pyfunc_schema_enforcement.py
{ "start": 3909, "end": 121690 }
class ____(mlflow.pyfunc.PythonModel): def predict(self, context, model_input, params=None): assert isinstance(params, dict) assert all(isinstance(x, int) for x in params["int_array"]) assert all(isinstance(x, float) for x in params["double_array"]) assert all(isinstance(x, float) fo...
PythonModelWithArrayParams
python
pytorch__pytorch
.github/scripts/trymerge.py
{ "start": 47707, "end": 91249 }
class ____: name: str patterns: list[str] approved_by: list[str] mandatory_checks_name: Optional[list[str]] ignore_flaky_failures: bool = True def gen_new_issue_link( org: str, project: str, labels: list[str], template: str = "bug-report.yml" ) -> str: labels_str = ",".join(labels) ret...
MergeRule
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/notifications/test_sns.py
{ "start": 1189, "end": 4640 }
class ____: def test_class_and_notifier_are_same(self): assert send_sns_notification is SnsNotifier @pytest.mark.parametrize( "aws_conn_id", [ pytest.param("aws_test_conn_id", id="custom-conn"), pytest.param(None, id="none-conn"), pytest.param(NOTSET,...
TestSnsNotifier
python
django__django
tests/select_related_regress/models.py
{ "start": 2499, "end": 2527 }
class ____(Fowl): pass
Hen
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_protect06.py
{ "start": 315, "end": 2055 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("protect06.xlsx") def test_create_file(self): """Test the a simple XlsxWriter file with worksheet protection.""" workbook = Workboo...
TestCompareXLSXFiles
python
crytic__slither
slither/vyper_parsing/ast/types.py
{ "start": 423, "end": 501 }
class ____(ASTNode): name: str body: List[AnnAssign] @dataclass
EventDef
python
pytorch__pytorch
torch/_dynamo/variables/nn_module.py
{ "start": 39047, "end": 54739 }
class ____(UserDefinedObjectVariable): _nonvar_fields = { "value_type", "is_state_mutated", "nn_module_stack_source", *UserDefinedObjectVariable._nonvar_fields, } """ The above class will specialize on the id() of a module and place parameters on the torch.fx.GraphMo...
UnspecializedNNModuleVariable
python
huggingface__transformers
src/transformers/models/vjepa2/video_processing_vjepa2.py
{ "start": 875, "end": 1754 }
class ____(BaseVideoProcessor): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD size = {"shortest_edge": int(256 * 256 / 224)} crop_size = 256 do_resize = True do_rescale = True do_center_crop = True do_normalize = True ...
VJEPA2VideoProcessor
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py
{ "start": 9629, "end": 12530 }
class ____(BaseOperator): """ Creates a report. .. seealso:: Check official API docs: `https://developers.google.com/doubleclick-advertisers/rest/v4/reports/insert` .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/oper...
GoogleCampaignManagerInsertReportOperator
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 250825, "end": 258981 }
class ____( DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefnumber ): """ FillOpacityDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned...
FillOpacityDatum
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dependency_install/package.py
{ "start": 217, "end": 610 }
class ____(Package): """Dependency which has a working install method""" homepage = "http://www.example.com" url = "http://www.example.com/a-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") version("2.0", md5="abcdef0123456789abcdef0123456789") def install(self, spec, prefix...
DependencyInstall
python
redis__redis-py
tests/test_asyncio/test_command_policies.py
{ "start": 2972, "end": 6658 }
class ____: async def test_resolves_correctly_policies(self, r: RedisCluster, monkeypatch): # original nodes selection method determine_nodes = r._determine_nodes determined_nodes = [] primary_nodes = r.get_primaries() calls = iter(list(range(len(primary_nodes)))) as...
TestClusterWithPolicies
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/widgets/menus.py
{ "start": 937, "end": 12785 }
class ____: """ :param floats: List of extra Float objects to display. :param menu_items: List of `MenuItem` objects. """ def __init__( self, body: AnyContainer, menu_items: list[MenuItem], floats: list[Float] | None = None, key_bindings: KeyBindingsBase | No...
MenuContainer
python
tensorflow__tensorflow
tensorflow/python/tpu/feature_column_v2.py
{ "start": 38467, "end": 44496 }
class ____(_TPUEmbeddingColumnV2): """TPUEmbeddingColumn which allows serving on TensorCore.""" def __new__(cls, *args, **kwargs): # For __new__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: cls._tensor_core_shape = kwargs['tensor_core_shape'] del kw...
_TPUDeviceSpecificEmbeddingColumnV2
python
django__django
tests/modeladmin/test_checks.py
{ "start": 9983, "end": 12492 }
class ____(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", "admin.E01...
FilterVerticalCheckTests
python
ray-project__ray
python/ray/data/datasource/file_meta_provider.py
{ "start": 1616, "end": 4151 }
class ____(FileMetadataProvider): """Abstract callable that provides metadata for :class:`~ray.data.datasource.file_based_datasource.FileBasedDatasource` implementations that reuse the base :meth:`~ray.data.Datasource.prepare_read` method. Also supports file and file size discovery in input directo...
BaseFileMetadataProvider
python
PyCQA__pylint
doc/data/messages/u/unnecessary-pass/bad.py
{ "start": 0, "end": 141 }
class ____(Exception): """This exception is raised when a user has provided incorrect data.""" pass # [unnecessary-pass]
DataEntryError
python
apache__airflow
task-sdk/src/airflow/sdk/bases/sensor.py
{ "start": 2119, "end": 15216 }
class ____(BaseOperator): """ Sensor operators are derived from this class and inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param soft_fail: Set to true to mark the task as SKIPPED on failure. ...
BaseSensorOperator
python
django__django
django/contrib/postgres/fields/array.py
{ "start": 10508, "end": 10599 }
class ____(ArrayRHSMixin, lookups.Overlap): pass @ArrayField.register_lookup
ArrayOverlap
python
google__jax
jax/_src/test_multiprocess.py
{ "start": 3701, "end": 13964 }
class ____: """Add a signal handler that sets a flag if SIGINT or SIGTERM are caught.""" # From https://stackoverflow.com/a/31464349 kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, ...
GracefulKiller
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 24275, "end": 26311 }
class ____(TypedDict, total=False): type: Required[Literal['float']] allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True multiple_of: float le: float ge: float lt: float gt: float strict: bool ref: str metadata: dict[str, Any] serialization...
FloatSchema
python
doocs__leetcode
solution/1300-1399/1394.Find Lucky Integer in an Array/Solution.py
{ "start": 0, "end": 161 }
class ____: def findLucky(self, arr: List[int]) -> int: cnt = Counter(arr) return max((x for x, v in cnt.items() if x == v), default=-1)
Solution
python
plotly__plotly.py
plotly/graph_objs/histogram/_unselected.py
{ "start": 233, "end": 3380 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram" _path_str = "histogram.unselected" _valid_props = {"marker", "textfont"} @property def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :c...
Unselected
python
pypa__warehouse
tests/unit/accounts/test_services.py
{ "start": 69257, "end": 69873 }
class ____: def test_verify_service(self): assert verifyClass(IEmailBreachedService, services.NullEmailBreachedService) def test_check_email(self): svc = services.NullEmailBreachedService() assert svc.get_email_breach_count("foo@example.com") == 0 def test_factory(self): co...
TestNullEmailBreachedService
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 182692, "end": 183847 }
class ____(TestCase): def test_invalid_n(self): with self.assertRaises(ValueError): list(mi.unique_in_window([], 0)) def test_basic(self): for iterable, n, expected in [ (range(9), 10, list(range(9))), (range(20), 10, list(range(20))), ([1, 2, 3, ...
UniqueInWindowTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 266663, "end": 267194 }
class ____(sgqlc.types.Input): """Ways in which lists of issues can be ordered upon return.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(PullRequestOrderField), graphql_name="field") """The field in which to order pull request...
PullRequestOrder
python
ZoranPandovski__al-go-rithms
puzzles/Rubik's Cube/rubik's cube simulator.py
{ "start": 5477, "end": 5840 }
class ____: def __init__(self, id): self.id = id self.piece = None locations1D[id] = self def setPiece(self, piece): self.piece = piece piece.location = self return self @staticmethod def getLocation(id): if id in locations1D: return...
Location
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol41.py
{ "start": 1335, "end": 1602 }
class ____: @overload def to_csv(self, p: WriteBuffer[bytes]) -> None: ... @overload def to_csv(self, p: None = ...) -> str: ... def to_csv(self, p: Any = None) -> Any: ... def test3(b: BytesIO) -> None: df = NDFrame() df.to_csv(b)
NDFrame
python
allegroai__clearml
clearml/utilities/gpu/pynvml.py
{ "start": 165286, "end": 165884 }
class ____(Structure): _fields_ = [ ("lowPwrThreshold", c_uint), ] def nvmlDeviceSetNvLinkDeviceLowPowerThreshold(device, l1threshold): c_info = c_nvmlNvLinkPowerThres_t() c_info.lowPwrThreshold = l1threshold fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvLinkDeviceLowPowerThreshold") re...
c_nvmlNvLinkPowerThres_t
python
dagster-io__dagster
python_modules/automation/automation/dagster_docs/validator.py
{ "start": 10525, "end": 15347 }
class ____: """Handles dynamic importing of Python symbols from dotted paths.""" @staticmethod def import_symbol(dotted_path: str) -> SymbolInfo: """Import a symbol from a dotted path like 'dagster.asset' or 'dagster.OpDefinition'. Args: dotted_path: The full dotted path to the...
SymbolImporter
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py
{ "start": 7817, "end": 8639 }
class ____: def test_serialization(self): application_id = "test_application_id" waiter_delay = 30 waiter_max_attempts = 60 aws_conn_id = "aws_default" trigger = EmrServerlessStopApplicationTrigger( application_id=application_id, waiter_delay=waiter_d...
TestEmrServerlessStopApplicationTrigger
python
mlflow__mlflow
dev/clint/src/clint/config.py
{ "start": 842, "end": 2798 }
class ____: select: set[str] = field(default_factory=set) exclude: list[str] = field(default_factory=list) # Path -> List of modules that should not be imported globally under that path forbidden_top_level_imports: dict[str, list[str]] = field(default_factory=dict) typing_extensions_allowlist: list[...
Config
python
run-llama__llama_index
llama-index-integrations/retrievers/llama-index-retrievers-pathway/llama_index/retrievers/pathway/base.py
{ "start": 3722, "end": 5111 }
class ____(BaseRetriever): """ Pathway retriever. Pathway is an open data processing framework. It allows you to easily develop data transformation pipelines that work with live data sources and changing data. This is the client that implements Retriever API for PathwayVectorServer. """ ...
PathwayRetriever
python
plotly__plotly.py
tests/test_core/test_update_objects/test_update_layout.py
{ "start": 66, "end": 2067 }
class ____(TestCase): def setUp(self): import plotly.io as pio pio.templates.default = None def test_update_layout_kwargs(self): # Create initial figure fig = go.Figure() fig.layout.title.font.size = 10 # Grab copy of original figure orig_fig = go.Figur...
TestUpdateLayout
python
Netflix__metaflow
test/test_config/helloconfig.py
{ "start": 575, "end": 818 }
class ____(FlowMutator): def mutate(self, mutable_flow): for name, s in mutable_flow.steps: if name in mutable_flow.config.run_on_titus: s.add_decorator(titus, cpu=mutable_flow.config.cpu_count)
TitusOrNot
python
doocs__leetcode
solution/3000-3099/3044.Most Frequent Prime/Solution.py
{ "start": 0, "end": 975 }
class ____: def mostFrequentPrime(self, mat: List[List[int]]) -> int: def is_prime(x: int) -> int: return all(x % i != 0 for i in range(2, isqrt(x) + 1)) m, n = len(mat), len(mat[0]) cnt = Counter() for i in range(m): for j in range(n): for a ...
Solution
python
google__jax
tests/pallas/mosaic_gpu_test.py
{ "start": 193440, "end": 200853 }
class ____(PallasTest, jtu.CudaArchSpecificTest): def test_multiple_wg(self): @functools.partial( self.kernel, out_shape=jnp.zeros((2, 128), np.int32), num_threads=2, thread_name="wg", ) def kernel(o_ref): wg_idx = jax.lax.axis_index("wg") o_ref[wg_idx] = jnp....
CoreMapTest
python
mlflow__mlflow
mlflow/haystack/autolog.py
{ "start": 2571, "end": 8091 }
class ____(SimpleSpanProcessor): def __init__(self): self.span_exporter = SpanExporter() self._pipeline_io: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {} def on_start(self, span: OTelSpan, parent_context: Context | None = None): tracer = _get_tracer(__name__) tracer.span...
HaystackSpanProcessor
python
doocs__leetcode
lcof/面试题11. 旋转数组的最小数字/Solution.py
{ "start": 0, "end": 349 }
class ____: def minArray(self, numbers: List[int]) -> int: l, r = 0, len(numbers) - 1 while l < r: m = (l + r) >> 1 if numbers[m] > numbers[r]: l = m + 1 elif numbers[m] < numbers[r]: r = m else: r -= 1 ...
Solution
python
huggingface__transformers
src/transformers/models/vit_mae/modeling_vit_mae.py
{ "start": 20851, "end": 21393 }
class ____(nn.Module): def __init__(self, config: ViTMAEConfig): super().__init__() self.config = config self.layer = nn.ModuleList([ViTMAELayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, hidden_states: torch.Tensor) ...
ViTMAEEncoder
python
pypa__pipenv
pipenv/vendor/tomlkit/container.py
{ "start": 25928, "end": 29694 }
class ____(_CustomDict): @staticmethod def validate(container: Container, indices: tuple[int, ...]) -> None: """Validate out of order tables in the given container""" # Append all items to a temp container to see if there is any error temp_container = Container(True) for i in ind...
OutOfOrderTableProxy
python
encode__starlette
starlette/applications.py
{ "start": 789, "end": 10347 }
class ____: """Creates an Starlette application.""" def __init__( self: AppType, debug: bool = False, routes: Sequence[BaseRoute] | None = None, middleware: Sequence[Middleware] | None = None, exception_handlers: Mapping[Any, ExceptionHandler] | None = None, on_s...
Starlette
python
django__django
django/contrib/gis/db/backends/spatialite/features.py
{ "start": 231, "end": 876 }
class ____(BaseSpatialFeatures, SQLiteDatabaseFeatures): can_alter_geometry_field = False # Not implemented supports_3d_storage = True @cached_property def supports_area_geodetic(self): return bool(self.connection.ops.geom_lib_version()) @cached_property def django_test_skips(self): ...
DatabaseFeatures
python
sphinx-doc__sphinx
sphinx/util/cfamily.py
{ "start": 5402, "end": 6047 }
class ____(ASTAttribute): def __init__(self, attrs: list[ASTGnuAttribute]) -> None: self.attrs = attrs def __eq__(self, other: object) -> bool: if not isinstance(other, ASTGnuAttributeList): return NotImplemented return self.attrs == other.attrs def __hash__(self) -> in...
ASTGnuAttributeList
python
getlogbook__logbook
src/logbook/ticketing.py
{ "start": 452, "end": 1624 }
class ____: """Represents a ticket from the database.""" level_name = level_name_property() def __init__(self, db, row): self.db = db self.__dict__.update(row._mapping) @cached_property def last_occurrence(self): """The last occurrence.""" if rv := self.get_occurre...
Ticket
python
jupyterlab__jupyterlab
jupyterlab/utils.py
{ "start": 137, "end": 303 }
class ____(Warning): # noqa """Create our own deprecation class, since Python >= 2.7 silences deprecations by default. """ pass
jupyterlab_deprecation
python
scrapy__scrapy
tests/test_spidermiddleware_httperror.py
{ "start": 2001, "end": 3212 }
class ____: @pytest.fixture def mw(self) -> HttpErrorMiddleware: crawler = get_crawler(DefaultSpider) crawler.spider = crawler._create_spider() return HttpErrorMiddleware.from_crawler(crawler) def test_process_spider_input( self, mw: HttpErrorMiddleware, res200: Response, re...
TestHttpErrorMiddleware
python
numba__numba
numba/cuda/tests/cudapy/test_sync.py
{ "start": 2231, "end": 7837 }
class ____(CUDATestCase): def _test_useless(self, kernel): compiled = cuda.jit("void(int32[::1])")(kernel) nelem = 10 ary = np.empty(nelem, dtype=np.int32) exp = np.arange(nelem, dtype=np.int32) compiled[1, nelem](ary) np.testing.assert_equal(ary, exp) def test_u...
TestCudaSync
python
sympy__sympy
sympy/holonomic/holonomic.py
{ "start": 3129, "end": 5333 }
class ____: r""" An Ore Algebra is a set of noncommutative polynomials in the intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`. It follows the commutation rule: .. math :: Dxa = \sigma(a)Dx + \delta(a) for :math:`a \subset A`. Where :math:`\sigma: A \Rightar...
DifferentialOperatorAlgebra
python
django__django
tests/admin_views/models.py
{ "start": 2554, "end": 2905 }
class ____(models.Model): title = models.CharField(max_length=100, verbose_name="¿Title?") content = models.TextField() book = models.ForeignKey(Book, models.CASCADE) class Meta: # Use a utf-8 bytestring to ensure it works (see #11710) verbose_name = "¿Chapter?" def __str__(self): ...
Chapter
python
Netflix__metaflow
metaflow/_vendor/yaml/constructor.py
{ "start": 18086, "end": 27622 }
class ____(SafeConstructor): # 'extend' is blacklisted because it is used by # construct_python_object_apply to add `listitems` to a newly generate # python instance def get_state_keys_blacklist(self): return ['^extend$', '^__.*__$'] def get_state_keys_blacklist_regexp(self): if not...
FullConstructor
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-google-genai/tests/test_llms_google_genai.py
{ "start": 1241, "end": 1445 }
class ____(BaseModel): """A model of a table in a database.""" name: str = Field(description="Table name field") columns: List[Column] = Field(description="List of random Column objects")
Table
python
getsentry__sentry
tests/sentry/users/models/test_authenticator.py
{ "start": 617, "end": 2724 }
class ____(TestCase): def test_user_has_2fa(self) -> None: user = self.create_user("foo@example.com") assert user.has_2fa() is False assert Authenticator.objects.filter(user=user).count() == 0 RecoveryCodeInterface().enroll(user) assert user.has_2fa() is False asser...
AuthenticatorTest
python
numba__numba
numba/core/typing/mathdecl.py
{ "start": 3118, "end": 3190 }
class ____(Math_predicate): pass @infer_global(math.pow)
Math_isfinite
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py
{ "start": 1395, "end": 1525 }
class ____: match ...: case int(): ... case _: def __eq__(self, other): ...
MaybeEqMatchCaseWildcard
python
apache__airflow
providers/http/src/airflow/providers/http/sensors/http.py
{ "start": 1713, "end": 8563 }
class ____(BaseSensorOperator): """ Execute HTTP GET statement; return False on failure 404 Not Found or `response_check` returning False. HTTP Error codes other than 404 (like 403) or Connection Refused Error would raise an exception and fail the sensor itself directly (no more poking). To avoid f...
HttpSensor
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 58413, "end": 58684 }
class ____(BaseModel): """ Queued Event Collection serializer for responses. """ queued_events: Annotated[list[QueuedEventResponse], Field(title="Queued Events")] total_entries: Annotated[int, Field(title="Total Entries")]
QueuedEventCollectionResponse
python
doocs__leetcode
solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/Solution.py
{ "start": 0, "end": 494 }
class ____: def countRectangles( self, rectangles: List[List[int]], points: List[List[int]] ) -> List[int]: d = defaultdict(list) for x, y in rectangles: d[y].append(x) for y in d.keys(): d[y].sort() ans = [] for x, y in points: ...
Solution
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 54533, "end": 54649 }
class ____(Elemwise): _parameters = ["frame"] operation = M.notnull _projection_passthrough = True
NotNull
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/texteditor.py
{ "start": 1186, "end": 7012 }
class ____(BaseDialog, SpyderWidgetMixin, SpyderFontsMixin): """Array Editor Dialog""" CONF_SECTION = 'variable_explorer' def __init__(self, text, title='', parent=None, readonly=False): super().__init__(parent) # Destroying the C++ object right after closing the dialog box, # othe...
TextEditor
python
pytorch__pytorch
test/dynamo/test_functions.py
{ "start": 83596, "end": 84877 }
class ____(torch.nn.Module): def forward(self, s9: "Sym(s9)", L_lambda0_keywords_y_: "f32[s9, s9]"): l_lambda0_keywords_y_ = L_lambda0_keywords_y_ mul: "f32[s9, s9]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_ add: "f32[s9, s9]" = l_lambda0_keywords_y_ + l_lambda0_keywords_y_; l_lambd...
GraphModule
python
fastai__fastai
fastai/vision/augment.py
{ "start": 42466, "end": 43393 }
class ____(RandTransform): "Apply `fs` to the logits" order = 40 def __init__(self, fs:Callable|MutableSequence, # Transformation functions applying in a space space_fn:Callable, # Function converting rgb to a space and back to rgb after appying `fs` **kwargs ): super()....
SpaceTfm
python
doocs__leetcode
solution/2300-2399/2337.Move Pieces to Obtain a String/Solution2.py
{ "start": 0, "end": 592 }
class ____: def canChange(self, start: str, target: str) -> bool: n = len(start) i = j = 0 while 1: while i < n and start[i] == '_': i += 1 while j < n and target[j] == '_': j += 1 if i >= n and j >= n: retur...
Solution
python
django__django
tests/migrations/test_add_many_to_many_field_initial/0002_initial.py
{ "start": 43, "end": 351 }
class ____(migrations.Migration): initial = True dependencies = [ ("migrations", "0001_initial"), ] operations = [ migrations.AddField( model_name="task", name="projects", field=models.ManyToManyField(to="Project"), ), ]
Migration
python
pytorch__pytorch
torch/testing/_internal/common_optimizers.py
{ "start": 2403, "end": 6972 }
class ____: """Optimizer information to be used in testing.""" def __init__( self, optim_cls: Optimizer, # Class object for the Optimizer under test *, # Function to generate optimizer inputs EXCLUDING params. We delegate params responsibility # to the test using the Op...
OptimizerInfo
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/summarize/chain.py
{ "start": 861, "end": 8361 }
class ____(Protocol): """Interface for loading the combine documents chain.""" def __call__( self, llm: BaseLanguageModel, **kwargs: Any, ) -> BaseCombineDocumentsChain: """Callable to load the combine documents chain.""" def _load_stuff_chain( llm: BaseLanguageModel, ...
LoadingCallable
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 16249, "end": 17882 }
class ____(FunctionMixin, ValueWrapper): def __init__(self, instance, class_context, function): super().__init__(function) self.instance = instance self._class_context = class_context def is_bound_method(self): return True @property def name(self): return Functi...
BoundMethod
python
google__pytype
pytype/pytd/optimize.py
{ "start": 21852, "end": 22439 }
class ____(visitors.Visitor): """Simplifies containers whose type parameters are all Any. For example, this will change def f() -> List[any] to def f() -> list Note that we don't simplify TupleType or CallableType, since they have variable-length parameters, and the parameter length is meaningful eve...
SimplifyContainers
python
kamyu104__LeetCode-Solutions
Python/find-score-of-an-array-after-marking-all-elements.py
{ "start": 64, "end": 609 }
class ____(object): def findScore(self, nums): """ :type nums: List[int] :rtype: int """ idxs = range(len(nums)) idxs.sort(key=lambda x: (nums[x], x)) lookup = [False]*len(nums) result = 0 for i in idxs: if lookup[i]: ...
Solution
python
huggingface__transformers
tests/models/kosmos2_5/test_modeling_kosmos2_5.py
{ "start": 4009, "end": 6498 }
class ____: def __init__( self, parent, batch_size=6, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, ffn_dim=64, num_hidden_layers=2, num_attention_heads=4, d...
Kosmos2_5TextModelTester
python
cython__cython
Cython/Compiler/Symtab.py
{ "start": 55049, "end": 59077 }
class ____(Scope): # The builtin namespace. is_builtin_scope = True def __init__(self): if Options.pre_import is None: Scope.__init__(self, "__builtin__", None, None) else: Scope.__init__(self, "__builtin__", PreImportScope(), None) self.type_names = {} ...
BuiltinScope
python
pytorch__pytorch
torch/_higher_order_ops/invoke_subgraph.py
{ "start": 17208, "end": 30690 }
class ____(torch.autograd.Function): """ Saves the subgraph, i.e. original callable, in the forward method. And then traces out a joint graph in the backward. This delaying of tracing in backward, also called as lazy backward, ensures that the assumptions about the grad_out strides and tensor-subcla...
InvokeSubgraphAutogradOp
python
spack__spack
lib/spack/spack/vendor/attr/exceptions.py
{ "start": 1185, "end": 1371 }
class ____(RuntimeError): """ A class with ``auto_attribs=True`` has an ``attr.ib()`` without a type annotation. .. versionadded:: 17.3.0 """
UnannotatedAttributeError
python
getsentry__sentry
src/sentry/issues/escalating/escalating_issues_alg.py
{ "start": 136, "end": 221 }
class ____(TypedDict): forecasted_date: str forecasted_value: int
IssueForecast
python
kamyu104__LeetCode-Solutions
Python/maximum-containers-on-a-ship.py
{ "start": 36, "end": 259 }
class ____(object): def maxContainers(self, n, w, maxWeight): """ :type n: int :type w: int :type maxWeight: int :rtype: int """ return min(maxWeight//w, n*n)
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/autoVariance3.py
{ "start": 3243, "end": 3804 }
class ____(dict[K, V]): pass # This should generate an error based on variance. vinv3_1: ShouldBeInvariant3[float, str] = ShouldBeInvariant3[int, str]() # This should generate an error based on variance. vinv3_2: ShouldBeInvariant3[int, str] = ShouldBeInvariant3[float, str]() # This should generate an error bas...
ShouldBeInvariant3
python
pytorch__pytorch
test/inductor/test_kernel_optimization.py
{ "start": 305, "end": 892 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward( self, input: torch.Tensor, weights: torch.Tensor, bias: torch.Tensor, input2: torch.Tensor, weights2: torch.Tensor, bias2: torch.Tensor, ) -> torch.Tensor...
TestEinsumtoPointwise
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 58387, "end": 58598 }
class ____(_PrintableStructure): _fields_ = [ ('bar1Total', c_ulonglong), ('bar1Free', c_ulonglong), ('bar1Used', c_ulonglong), ] _fmt_ = {'<default>': "%d B"}
c_nvmlBAR1Memory_t
python
fastapi__sqlmodel
docs_src/tutorial/code_structure/tutorial002_py310/hero_model.py
{ "start": 149, "end": 488 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) team_id: int | None = Field(default=None, foreign_key="team.id") team: Optional["Team"] = Relationship(back_p...
Hero
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 55274, "end": 55612 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional["Record"] = Field(default=None, description="")...
InlineResponse20012
python
django__django
django/db/models/functions/datetime.py
{ "start": 4946, "end": 5079 }
class ____(Extract): """Return Monday=1 through Sunday=7, based on ISO-8601.""" lookup_name = "iso_week_day"
ExtractIsoWeekDay
python
ray-project__ray
python/ray/util/actor_group.py
{ "start": 662, "end": 1806 }
class ____: def __init__(self, actor_group: "ActorGroup", method_name: str): self.actor_group = weakref.ref(actor_group) self._method_name = method_name def __call__(self, *args, **kwargs): raise TypeError( "ActorGroup methods cannot be called directly. " "Instea...
ActorGroupMethod