language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
django__django
django/db/models/functions/datetime.py
{ "start": 5254, "end": 6285 }
class ____(Extract): lookup_name = "second" DateField.register_lookup(ExtractYear) DateField.register_lookup(ExtractMonth) DateField.register_lookup(ExtractDay) DateField.register_lookup(ExtractWeekDay) DateField.register_lookup(ExtractIsoWeekDay) DateField.register_lookup(ExtractWeek) DateField.register_lookup(E...
ExtractSecond
python
Pylons__pyramid
tests/test_config/pkgs/scannable/__init__.py
{ "start": 1442, "end": 1662 }
class ____: def __call__(self, context, request): return 'grokked_instance' grokked_instance = Foo() grokked_instance = view_config( name='grokked_instance', renderer=null_renderer )(grokked_instance)
Foo
python
PyCQA__pylint
doc/data/messages/i/invalid-getnewargs-returned/good.py
{ "start": 0, "end": 125 }
class ____: """__getnewargs__ returns <type 'tuple'>""" def __getnewargs__(self): return (1, 2)
CustomGetNewArgs
python
bokeh__bokeh
tests/unit/bokeh/util/test_token.py
{ "start": 1936, "end": 8295 }
class ____: def test_base64_roundtrip(self) -> None: for s in [ "", "a", "ab", "abc", "abcd", "abcde", "abcdef", "abcdefg", "abcdefgh", "abcdefghi", "abcdefghijklmnopqrstuvwxyz" ]: assert s == _b64_to_utf8(_base64_encode(s)) def test_reseed_if_needed(se...
TestSessionId
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 69317, "end": 75917 }
class ____(Response): """ Response of datasets.commit_version endpoint. :param version: Committed version ID :type version: str :param parent: Committed version parent version ID :type parent: str :param dataset: Dataset ID :type dataset: str :param merged: Number of merged frames ...
CommitVersionResponse
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/_internal/expandinput.py
{ "start": 2995, "end": 3877 }
class ____(ResolveMixin): """ Stand-in stub for task-group-mapping arguments. This is very similar to an XComArg, but resolved differently. Declared here (instead of in the task group module) to avoid import cycles. """ _input: ExpandInput = attrs.field() _key: str @_input.validator ...
MappedArgument
python
spyder-ide__spyder
spyder/plugins/completion/tests/test_configdialog.py
{ "start": 634, "end": 1370 }
class ____(QMainWindow): sig_setup_finished = Signal() def __init__(self, parent): super().__init__(parent) self.statusbar = Mock() self.console = Mock() @pytest.mark.parametrize( 'config_dialog', [[MainWindowMock, [], [CompletionPlugin]]], indirect=True) def test_config_d...
MainWindowMock
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 21544, "end": 23755 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the server understood the request, but is refusing to fulfill it. code: 403, title: Forbidden Raise this exception within :term:`view` code to immediately return the :term:`forbidden view` to the in...
HTTPForbidden
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 55030, "end": 55555 }
class ____(fixtures.TestBase): __only_on__ = "postgresql" __sparse_driver_backend__ = True def test_reflection(self, connection, metadata): Table( "table", metadata, Column("x", Integer), Column("y", postgresql.OID), ) metadata.create_...
OIDTest
python
django__django
tests/migrations/test_migrations_squashed/0001_squashed_0002.py
{ "start": 43, "end": 903 }
class ____(migrations.Migration): replaces = [ ("migrations", "0001_initial"), ("migrations", "0002_second"), ] operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.Char...
Migration
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 6126, "end": 6364 }
class ____(BaseOxmlElement): """Used for ``<a:off>`` element, and perhaps others. Specifies an x, y coordinate (point). """ x = RequiredAttribute("x", ST_Coordinate) y = RequiredAttribute("y", ST_Coordinate)
CT_Point2D
python
PrefectHQ__prefect
src/prefect/server/events/ordering/__init__.py
{ "start": 1452, "end": 1599 }
class ____(Protocol): async def __call__( self, event: ReceivedEvent, depth: int = 0 ) -> None: ... # pragma: no cover
event_handler
python
scrapy__scrapy
scrapy/downloadermiddlewares/stats.py
{ "start": 1095, "end": 2876 }
class ____: def __init__(self, stats: StatsCollector): self.stats: StatsCollector = stats @classmethod def from_crawler(cls, crawler: Crawler) -> Self: if not crawler.settings.getbool("DOWNLOADER_STATS"): raise NotConfigured assert crawler.stats return cls(crawle...
DownloaderStats
python
facebook__pyre-check
pyre_extensions/tests/safe_json_test.py
{ "start": 457, "end": 507 }
class ____(Movie): rating: float
MovieWithRating
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 20295, "end": 21374 }
class ____(Operation): def __init__(self, threshold=0.5, *, name=None): super().__init__(name=name) self.threshold = threshold def call(self, x): return backend.nn.hard_shrink(x, self.threshold) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) ...
HardShrink
python
numpy__numpy
numpy/_typing/_nbit_base.py
{ "start": 2694, "end": 2828 }
class ____(_64Bit): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] pass @final @set_module("numpy._typing")
_32Bit
python
plotly__plotly.py
plotly/graph_objs/splom/_unselected.py
{ "start": 233, "end": 2420 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "splom" _path_str = "splom.unselected" _valid_props = {"marker"} @property def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_o...
Unselected
python
celery__celery
celery/platforms.py
{ "start": 17822, "end": 25610 }
class ____: """Convenience interface to :mod:`signals`. If the requested signal isn't supported on the current platform, the operation will be ignored. Example: >>> from celery.platforms import signals >>> from proj.handlers import my_handler >>> signals['INT'] = my_handler ...
Signals
python
Pylons__pyramid
tests/test_scripts/test_proutes.py
{ "start": 25691, "end": 25949 }
class ____(unittest.TestCase): def _callFUT(self, argv): from pyramid.scripts.proutes import main return main(argv, quiet=True) def test_it(self): result = self._callFUT(['proutes']) self.assertEqual(result, 2)
Test_main
python
agronholm__apscheduler
src/apscheduler/triggers/cron/expressions.py
{ "start": 4626, "end": 5563 }
class ____(RangeExpression): value_re: ClassVar[Pattern] = re.compile( r"(?P<first>[a-z]+)(?:-(?P<last>[a-z]+))?", re.IGNORECASE ) def __init__(self, first: str, last: str | None = None): try: first_num = MONTHS.index(first.lower()) + 1 except ValueError: rai...
MonthRangeExpression
python
sqlalchemy__sqlalchemy
test/dialect/test_all.py
{ "start": 112, "end": 555 }
class ____(fixtures.TestBase): def _all_dialect_packages(self): return [ getattr(__import__("sqlalchemy.dialects.%s" % d).dialects, d) for d in dialects.__all__ if not d.startswith("_") ] def test_all_import(self): for package in self._all_dialect_pac...
ImportStarTest
python
django__django
tests/shortcuts/tests.py
{ "start": 1850, "end": 2598 }
class ____(SimpleTestCase): def test_redirect_response_status_code(self): tests = [ (True, False, 301), (False, False, 302), (False, True, 307), (True, True, 308), ] for permanent, preserve_request, expected_status_code in tests: wi...
RedirectTests
python
numpy__numpy
numpy/linalg/tests/test_linalg.py
{ "start": 36211, "end": 39231 }
class ____: rshft_0 = np.eye(4) rshft_1 = rshft_0[[3, 0, 1, 2]] rshft_2 = rshft_0[[2, 3, 0, 1]] rshft_3 = rshft_0[[1, 2, 3, 0]] rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3] noninv = array([[1, 0], [0, 0]]) stacked = np.block([[[rshft_0]]] * 2) # FIXME the 'e' dtype might work in fut...
TestMatrixPower
python
redis__redis-py
redis/commands/search/__init__.py
{ "start": 318, "end": 3872 }
class ____(SearchCommands): """ Create a client for talking to search. It abstracts the API of the module and lets you just use the engine. """ class BatchIndexer: """ A batch indexer allows you to automatically batch document indexing in pipelines, flushing it every N docum...
Search
python
optuna__optuna
optuna/visualization/_edf.py
{ "start": 727, "end": 4482 }
class ____(NamedTuple): lines: list[_EDFLineInfo] x_values: np.ndarray def plot_edf( study: Study | Sequence[Study], *, target: Callable[[FrozenTrial], float] | None = None, target_name: str = "Objective Value", ) -> "go.Figure": """Plot the objective value EDF (empirical distribution func...
_EDFInfo
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/utils.py
{ "start": 9995, "end": 14268 }
class ____: pretty_printer = PrettyPrinter() def __init__(self): self.filename_cache = {} def get_source_file(self, frame): frame_filename = frame.f_code.co_filename value = self.filename_cache.get(frame_filename) if value is None: filename = inspect.getsourcef...
_StackTraceRecorder
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py
{ "start": 97, "end": 288 }
class ____(dg.ConfigurableIOManager): def handle_output(self, context: dg.OutputContext, obj): pass def load_input(self, context: dg.InputContext): pass
PandasIOManager
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 135693, "end": 140895 }
class ____(TorchHigherOrderOperatorVariable): @staticmethod def normalize_to_args(args, kwargs): # input signature is (query, key, value, score_mod, block_mask, *other_buffers), # block_mask is a tuple, and we don't want to flatten it. # only flatten kwargs into lists flat_kwargs...
FlexAttentionHigherOrderVariable
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/grid_finder.py
{ "start": 3748, "end": 4644 }
class ____(Transform): """A transform defined by two user-set functions.""" input_dims = output_dims = 2 def __init__(self, forward, backward): """ Parameters ---------- forward, backward : callable The forward and backward transforms, taking ``x`` and ``y`` as ...
_User2DTransform
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 34141, "end": 34617 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output: torch.Tensor) -> torch.Tensor: seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_sc...
MobileBertOnlyNSPHead
python
django__django
tests/admin_views/models.py
{ "start": 7374, "end": 7781 }
class ____(models.Model): """ A simple, generic account encapsulating the information shared by all types of accounts. """ username = models.CharField(blank=False, max_length=80) persona = models.ForeignKey(Persona, models.CASCADE, related_name="accounts") servicename = "generic service" ...
Account
python
dask__distributed
distributed/diagnostics/progress.py
{ "start": 10707, "end": 13908 }
class ____(SchedulerPlugin): """Keep track of high-level timing information for task group progress""" name: ClassVar[str] = "group-timing" time: list[float] compute: dict[str, list[float]] nthreads: list[float] def __init__(self, scheduler): self.scheduler = scheduler # Time ...
GroupTiming
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image04.py
{ "start": 339, "end": 2851 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image04.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_c...
TestCompareXLSXFiles
python
apache__airflow
providers/apache/hive/src/airflow/providers/apache/hive/hooks/hive.py
{ "start": 33561, "end": 44786 }
class ____(DbApiHook): """ Wrapper around the pyhive library. Notes: * the default auth_mechanism is PLAIN, to override it you can specify it in the ``extra`` of your connection in the UI * the default for run_set_variable_statements is true, if you are using impala you may need to set it t...
HiveServer2Hook
python
ray-project__ray
python/ray/llm/_internal/serve/observability/metrics/middleware.py
{ "start": 716, "end": 5169 }
class ____: """Measures and stores HTTP request metrics.""" def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope["type"] not in ("http", "websocket"): await self.app(scope, receive, send) # If the status_code isn't set by sen...
MeasureHTTPRequestMetricsMiddleware
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py
{ "start": 7207, "end": 8049 }
class ____(InotifyEmitter): """ inotify(7)-based event emitter. By default this class produces move events even if they are not matched Such move events will have a ``None`` value for the unmatched part. :param event_queue: The event queue to fill with events. :param watch: A watch ...
InotifyFullEmitter
python
boto__boto3
boto3/dynamodb/types.py
{ "start": 2006, "end": 7082 }
class ____: """This class serializes Python data types to DynamoDB types.""" def serialize(self, value): """The method to serialize the Python data types. :param value: A python value to be serialized to DynamoDB. Here are the various conversions: Python ...
TypeSerializer
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 162784, "end": 166778 }
class ____(Request): """ Add or update task configuration :param task: Task ID :type task: str :param configuration: Task configuration items. The new ones will be added and the already existing ones will be updated :type configuration: Sequence[ConfigurationItem] :param replace_con...
EditConfigurationRequest
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 1531, "end": 2031 }
class ____(resource.Resource): """ A testing resource which renders itself as the contents of the request body as long as the request body is 100 bytes long, otherwise which renders itself as C{"ERROR"}. """ def render(self, request): data = request.content.read() contentLength ...
PayloadResource
python
getsentry__sentry
src/sentry/api/endpoints/organization_trace_logs.py
{ "start": 1034, "end": 5893 }
class ____(OrganizationEventsV2EndpointBase): """Replaces a call to events that isn't possible for team plans because of projects restrictions""" publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get_projects( self, request: HttpRequest, organization: Organizati...
OrganizationTraceLogsEndpoint
python
facebookresearch__faiss
tests/test_index.py
{ "start": 3379, "end": 4351 }
class ____(unittest.TestCase): def test_indexflat_l2_sync_norms_1(self): d = 32 nb = 10000 nt = 0 nq = 16 k = 10 (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) # instantiate IndexHNSWFlat index = faiss.IndexHNSWFlat(d, 32) index.hnsw.efConstruct...
TestIndexFlatL2
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 56318, "end": 56392 }
class ____(atlas_3_10_threads_info): pass
lapack_atlas_3_10_threads_info
python
huggingface__transformers
src/transformers/models/vitdet/modeling_vitdet.py
{ "start": 12536, "end": 13445 }
class ____(nn.Module): """ A LayerNorm variant, popularized by Transformers, that performs point-wise mean and variance normalization over the channel dimension for inputs that have shape (batch_size, channels, height, width). https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2...
VitDetLayerNorm
python
astropy__astropy
astropy/utils/masked/tests/test_masked.py
{ "start": 51994, "end": 52077 }
class ____(TestMaskedArrayMethods, QuantitySetup): pass
TestMaskedQuantityMethods
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/python.py
{ "start": 705, "end": 1202 }
class ____(BuilderWithDefaults): phases = ("install",) package_methods = ("test_imports",) package_attributes = ("archive_files", "build_directory", "install_time_test_callbacks") install_time_test_callbacks = ["test_imports"] @property def build_directory(self) -> str: return self.pkg....
PythonPipBuilder
python
getsentry__sentry-python
sentry_sdk/integrations/asgi.py
{ "start": 2048, "end": 12800 }
class ____: __slots__ = ( "app", "__call__", "transaction_style", "mechanism_type", "span_origin", "http_methods_to_capture", ) def __init__( self, app, # type: Any unsafe_context_data=False, # type: bool transaction_style="e...
SentryAsgiMiddleware
python
celery__celery
t/smoke/tests/test_control.py
{ "start": 44, "end": 688 }
class ____: def test_sanity(self, celery_setup: CeleryTestSetup): r = celery_setup.app.control.ping() assert all( [ all([res["ok"] == "pong" for _, res in response.items()]) for response in r ] ) def test_shutdown_exit_with_zero(se...
test_control
python
facebook__pyre-check
client/log/tests/log_test.py
{ "start": 233, "end": 509 }
class ____(unittest.TestCase): def test_truncate(self) -> None: self.assertEqual(log.truncate("a", 10), "a") self.assertEqual(log.truncate("a" * 10, 10), "a" * 10) self.assertEqual(log.truncate("123456789", 4), "1234..[truncated 5 characters]")
LogTest
python
weaviate__weaviate-python-client
profiling/test_refs.py
{ "start": 1235, "end": 1310 }
class ____: to_class: str to_uuid: uuid_lib.UUID @dataclass
Reference
python
ray-project__ray
python/ray/serve/_private/deployment_scheduler.py
{ "start": 910, "end": 1048 }
class ____: """A scheduling policy that spreads replicas with best effort.""" pass @total_ordering
SpreadDeploymentSchedulingPolicy
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_barcode.py
{ "start": 1968, "end": 5048 }
class ____(ColumnMapExpectation): """Expect the provided barcodes are valid (barcode type passed in parameter). Barcode types: code39, ean, ean8, ean13, gtin, gtin14, gs1_datamatrix, isbn, isbn10, isbn13, upc """ # These examples will be shown in the public gallery. # They will also be executed as...
ExpectColumnValuesToBeValidBarcode
python
kamyu104__LeetCode-Solutions
Python/maximum-alternating-subarray-sum.py
{ "start": 29, "end": 543 }
class ____(object): def maximumAlternatingSubarraySum(self, nums): """ :type nums: List[int] :rtype: int """ def kadane(nums, start): result = float("-inf") curr = odd = 0 for i in xrange(start, len(nums)): curr = (curr+nums...
Solution
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 28682, "end": 30946 }
class ____(MapPartitions): _parameters = [ "frame", "func", "before", "after", "meta", "enforce_metadata", "transform_divisions", "clear_divisions", "align_dataframes", "token", "kwargs", ] _defaults: dict = { "m...
MapOverlap
python
doocs__leetcode
solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution2.py
{ "start": 0, "end": 345 }
class ____: def maxProfit(self, prices: List[int]) -> int: n = len(prices) f = [[0] * 2 for _ in range(n)] f[0][1] = -prices[0] for i in range(1, n): f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) ...
Solution
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constructors.py
{ "start": 1826, "end": 1957 }
class ____(BaseConstructor): def __init__(self, y: int) -> None: super().__init__() self.y = y
DerivedConstructor
python
apache__airflow
airflow-ctl/tests/airflow_ctl/api/test_operations.py
{ "start": 18258, "end": 19876 }
class ____: section: str = "core" option: str = "config" def test_get(self): response_config = Config( sections=[ ConfigSection( name=self.section, options=[ ConfigOption( key=sel...
TestConfigOperations
python
getsentry__sentry
tests/sentry/integrations/msteams/webhook/test_ms_teams_webhook_endpoint.py
{ "start": 157, "end": 2978 }
class ____(TestCase): def setUp(self) -> None: self._example_request_data = { "entities": [{"type": "clientInfo", "locale": "en-US"}], "timestamp": "2024-03-21T18:41:30.088Z", "action": "add", "recipient": {"name": "Sentry", "id": "28:8922afe2-d747-4ae9-9bce-f...
TestGeTeamInstallationRequestData
python
python__mypy
test-data/unit/plugins/common_api_incremental.py
{ "start": 235, "end": 1613 }
class ____(Plugin): def get_dynamic_class_hook( self, fullname: str ) -> Callable[[DynamicClassDefContext], None] | None: if fullname == "lib.declarative_base": return add_info_hook return None def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], N...
DynPlugin
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 434, "end": 525 }
class ____(UserPassesTestMixin): def test_func(self): return True
AlwaysTrueMixin
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 95288, "end": 95467 }
class ____(Structure): _fields_ = [("sessionsCount", c_uint), ("averageFPS", c_uint), ("averageLatency", c_uint) ]
c_nvmlFBCStats_t
python
facebookresearch__faiss
benchs/bench_fw/benchmark.py
{ "start": 6335, "end": 6896 }
class ____: num_threads: int distance_metric: str def __post_init__(self): if self.distance_metric == "IP": self.distance_metric_type = faiss.METRIC_INNER_PRODUCT elif self.distance_metric == "L2": self.distance_metric_type = faiss.METRIC_L2 else: ...
IndexOperator
python
lxml__lxml
src/lxml/tests/test_incremental_xmlfile.py
{ "start": 14288, "end": 15063 }
class ____(_XmlFileTestCaseBase): def setUp(self): self._tmpfile = tempfile.NamedTemporaryFile() self._file = self._tmpfile.name def tearDown(self): try: self._tmpfile.close() finally: if os.path.exists(self._tmpfile.name): os.unlink(self....
TempPathXmlFileTestCase
python
django__django
tests/queries/tests.py
{ "start": 77051, "end": 77630 }
class ____(TestCase): def test_ticket7778(self): # Model subclasses could not be deleted if a nullable foreign key # relates to a model that relates back. num_celebs = Celebrity.objects.count() tvc = TvChef.objects.create(name="Huey") self.assertEqual(Celebrity.objects.count...
SubclassFKTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeAlias7.py
{ "start": 326, "end": 383 }
class ____(Generic[TResult]): Response: TResult
Context
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 220200, "end": 221048 }
class ____(TestCase): def test_concurrent_calls(self): result = 0 result_lock = Lock() def producer(limit): 'Non-concurrent producer. A generator version of range(limit).' for x in range(limit): yield x def consumer(counter): 'Con...
TestSerialize
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/encoders.py
{ "start": 3608, "end": 4392 }
class ____(nn.Module): def __init__(self, input_size: int, normalize: bool = False): super().__init__() self.normalizer: Optional[Normalizer] = None if normalize: self.normalizer = Normalizer(input_size) def forward(self, inputs: torch.Tensor) -> torch.Tensor: if sel...
VectorInput
python
numpy__numpy
numpy/f2py/tests/test_character.py
{ "start": 5196, "end": 14990 }
class ____(util.F2PyTest): # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py'] suffix = '.f90' fprefix = 'test_character' code = textwrap.dedent(f""" subroutine {fprefix}_input(c, o) character, intent(in) :: c integer*1 o !f2py intent(out) o ...
TestCharacter
python
spack__spack
lib/spack/spack/spec_parser.py
{ "start": 4843, "end": 6991 }
class ____(TokenBase): """Enumeration of the different token kinds of tokens in the spec grammar. Order of declaration is extremely important, since text containing specs is parsed with a single regex obtained by ``"|".join(...)`` of all the regex in the order of declaration. """ # Dependency, wit...
SpecTokens
python
chroma-core__chroma
chromadb/segment/impl/vector/local_persistent_hnsw.py
{ "start": 2230, "end": 22149 }
class ____(LocalHnswSegment): METADATA_FILE: str = "index_metadata.pickle" # How many records to add to index at once, we do this because crossing the python/c++ boundary is expensive (for add()) # When records are not added to the c++ index, they are buffered in memory and served # via brute force sear...
PersistentLocalHnswSegment
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1295840, "end": 1296940 }
class ____(sgqlc.types.Type, Node): """A file in a package version.""" __schema__ = github_schema __field_names__ = ("md5", "name", "package_version", "sha1", "sha256", "size", "updated_at", "url") md5 = sgqlc.types.Field(String, graphql_name="md5") """MD5 hash of the file.""" name = sgqlc.typ...
PackageFile
python
kamyu104__LeetCode-Solutions
Python/count-special-integers.py
{ "start": 51, "end": 756 }
class ____(object): def countSpecialNumbers(self, n): """ :type n: int :rtype: int """ def P(m, n): result = 1 for _ in xrange(n): result *= m m -= 1 return result digits = map(int, str(n+1)) ...
Solution
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 154733, "end": 155320 }
class ____(IRNode): def get_reads(self) -> OrderedSet[Dep]: return OrderedSet() @cache_on_self_and_args("NoneAsConstantBuffer") def get_free_symbol_uses( self, unbacked_only: bool = False ) -> OrderedSet[sympy.Symbol]: return OrderedSet() def codegen_reference(self, writer:...
NoneAsConstantBuffer
python
davidhalter__jedi
jedi/inference/names.py
{ "start": 19546, "end": 19861 }
class ____(_ParamMixin): def __init__(self, param_name): self._wrapped_param_name = param_name def __getattr__(self, name): return getattr(self._wrapped_param_name, name) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._wrapped_param_name)
ParamNameWrapper
python
PrefectHQ__prefect
src/prefect/_versioning.py
{ "start": 1474, "end": 12380 }
class ____(VersionInfo): type: Literal["vcs:git"] = "vcs:git" version: str commit_sha: str message: str branch: str repository: str url: str async def get_github_version_info( commit_sha: Optional[str] = None, message: Optional[str] = None, branch: Optional[str] = None, rep...
GitVersionInfo
python
ansible__ansible
test/integration/targets/ansible-test-container/runme.py
{ "start": 23446, "end": 23646 }
class ____: ssh: User = None remote: User = None @property def actual(self) -> User: return self.remote or self.ssh or ROOT_USER @dataclasses.dataclass(frozen=True)
UserScenario
python
cython__cython
Cython/Distutils/old_build_ext.py
{ "start": 2303, "end": 13723 }
class ____(_build_ext.build_ext): description = "build C/C++ and Cython extensions (compile/link to build directory)" sep_by = _build_ext.build_ext.sep_by user_options = _build_ext.build_ext.user_options[:] boolean_options = _build_ext.build_ext.boolean_options[:] help_options = _build_ext.build_e...
old_build_ext
python
django__django
tests/signed_cookies_tests/tests.py
{ "start": 216, "end": 3395 }
class ____(SimpleTestCase): def test_can_set_and_read_signed_cookies(self): response = HttpResponse() response.set_signed_cookie("c", "hello") self.assertIn("c", response.cookies) self.assertTrue(response.cookies["c"].value.startswith("hello:")) request = HttpRequest() ...
SignedCookieTest
python
pyodide__pyodide
src/tests/test_typeconversions.py
{ "start": 470, "end": 55771 }
class ____(pickle.Unpickler): def find_class(self, module, name): # Only allow safe classes from builtins. if module == "hypothesis": raise pickle.UnpicklingError() return super().find_class(module, name) def no_hypothesis(x): try: NoHypothesisUnpickler(io.BytesIO(p...
NoHypothesisUnpickler
python
ray-project__ray
python/ray/tests/test_client_builder.py
{ "start": 2581, "end": 15780 }
class ____: def ping(self): return "pong" a = Foo.options(lifetime="detached", name="abc").remote() ray.get(a.ping.remote()) print("Current namespace:", ray.get_runtime_context().namespace) """ anon_driver = template.format(namespace="None") run_string_as_driver(anon_driver) # This second ...
Foo
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py
{ "start": 19112, "end": 23039 }
class ____(GoogleCloudBaseOperator): """ Delete a single backup. :param project_id: Required. The ID of the Google Cloud project that the backup belongs to. :param region: Required. The ID of the Google Cloud region that the backup belongs to. :param service_id: Required. The ID of the metastore se...
DataprocMetastoreDeleteBackupOperator
python
pydantic__pydantic
pydantic/v1/main.py
{ "start": 13188, "end": 44824 }
class ____(Representation, metaclass=ModelMetaclass): if TYPE_CHECKING: # populated by the metaclass, defined here to help IDEs only __fields__: ClassVar[Dict[str, ModelField]] = {} __include_fields__: ClassVar[Optional[Mapping[str, Any]]] = None __exclude_fields__: ClassVar[Optional...
BaseModel
python
keon__algorithms
tests/test_strings.py
{ "start": 14575, "end": 14803 }
class ____(unittest.TestCase): def test_check_pangram(self): self.assertTrue(check_pangram("The quick brown fox jumps over the lazy dog")) self.assertFalse(check_pangram("The quick brown fox"))
TestCheckPangram
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 125687, "end": 128541 }
class ____(Request): """ Set the model ready flag to True. If the model is an output model of a task then try to publish the task. :param model: Model id :type model: str :param force_publish_task: Publish the associated task (if exists) even if it is not in the 'stopped' state. Optional, t...
SetReadyRequest
python
walkccc__LeetCode
solutions/414. Third Maximum Number/414.py
{ "start": 0, "end": 467 }
class ____: def thirdMax(self, nums: list[int]) -> int: max1 = -math.inf # the maximum max2 = -math.inf # the second maximum max3 = -math.inf # the third maximum for num in nums: if num > max1: max3 = max2 max2 = max1 max1 = num elif max1 > num and num > max2: ...
Solution
python
redis__redis-py
tests/test_asyncio/test_retry.py
{ "start": 4305, "end": 5349 }
class ____: "Test the Redis client behavior with retries" async def test_get_set_retry_object(self, request): retry = Retry(NoBackoff(), 2) url = request.config.getoption("--redis-url") r = await Redis.from_url(url, retry_on_timeout=True, retry=retry) assert r.get_retry()._retri...
TestRedisClientRetry
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 276, "end": 1404 }
class ____(object): def set_input_shape(self, shape): """ Sets the shape that the layer expects of the input in the forward pass method """ self.input_shape = shape def layer_name(self): """ The name of the layer. Used in model summary. """ return self.__class__.__name_...
Layer
python
ipython__ipython
tests/test_profile.py
{ "start": 2069, "end": 5288 }
class ____(TestCase): def setUp(self): # create profile dir self.pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, "test") self.options = ["--ipython-dir", IP_TEST_DIR, "--profile", "test"] self.fname = TMP_TEST_DIR / "test.py" def tearDown(self): # We must remove ...
ProfileStartupTest
python
apache__airflow
providers/snowflake/src/airflow/providers/snowflake/hooks/snowflake.py
{ "start": 2255, "end": 30416 }
class ____(DbApiHook): """ A client to interact with Snowflake. This hook requires the snowflake_conn_id connection. The snowflake account, login, and, password field must be setup in the connection. Other inputs can be defined in the connection or hook instantiation. :param snowflake_conn_id:...
SnowflakeHook
python
fluentpython__example-code-2e
24-class-metaprog/checked/initsub/checkedlib.py
{ "start": 2078, "end": 2919 }
class ____: def __init__(self, name: str, constructor: Callable) -> None: # <2> if not callable(constructor) or constructor is type(None): # <3> raise TypeError(f'{name!r} type hint must be callable') self.name = name self.constructor = constructor def __set__(self, instan...
Field
python
walkccc__LeetCode
solutions/3484. Design Spreadsheet/3484.py
{ "start": 0, "end": 513 }
class ____: def __init__(self, rows: int) -> None: self.spreadsheet = {} def setCell(self, cell: str, value: int) -> None: self.spreadsheet[cell] = value def resetCell(self, cell: str) -> None: self.spreadsheet[cell] = 0 def getValue(self, formula: str) -> int: i = formula.find('+') retur...
Spreadsheet
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1212290, "end": 1214248 }
class ____(Sort): """ EncodingSortField schema wrapper. A sort definition for sorting a discrete scale in an encoding field definition. Parameters ---------- field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef` The data `field <https://vega.github.io/vega-lite/docs...
EncodingSortField
python
readthedocs__readthedocs.org
readthedocs/api/v2/serializers.py
{ "start": 11011, "end": 12006 }
class ____(serializers.ModelSerializer): """Remote service repository serializer.""" organization = RemoteOrganizationSerializer() # This field does create an additional query per object returned matches = serializers.SerializerMethodField() admin = serializers.SerializerMethodField("is_admin") ...
RemoteRepositorySerializer
python
mkdocs__mkdocs
mkdocs/config/defaults.py
{ "start": 296, "end": 833 }
class ____(c.OptionallyRequired[int]): levels: Mapping[str, int] = { "warn": logging.WARNING, "info": logging.INFO, "ignore": logging.DEBUG, } def run_validation(self, value: object) -> int: if not isinstance(value, str): raise base.ValidationError(f"Expected a s...
_LogLevel
python
huggingface__transformers
src/transformers/models/smollm3/modeling_smollm3.py
{ "start": 2234, "end": 8585 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: SmolLM3Config, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self...
SmolLM3RotaryEmbedding
python
pdm-project__pdm
src/pdm/cli/options.py
{ "start": 2361, "end": 15494 }
class ____(Option): """A reusable argument group object which can call `add_argument()` to add more arguments. And itself will be registered to the parser later. """ def __init__(self, name: str, is_mutually_exclusive: bool = False, required: bool = False) -> None: self.name = name self...
ArgumentGroup
python
sympy__sympy
sympy/stats/frv_types.py
{ "start": 1757, "end": 3385 }
class ____(SingleFiniteDistribution): @property def dict(self): return self.args[0] def pmf(self, x): x = Symbol('x') return Lambda(x, Piecewise(*( [(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)]))) @property def set(self): return set(s...
FiniteDistributionHandmade
python
tensorflow__tensorflow
tensorflow/python/keras/engine/base_preprocessing_layer.py
{ "start": 18795, "end": 23669 }
class ____(object): """Functional object that defines a shardable computation. This object defines functions required to create and manipulate data objects. These data objects, referred to below as 'accumulators', are computation- specific and may be implemented alongside concrete subclasses of Combiner (if ...
Combiner
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/generic_class.py
{ "start": 183, "end": 279 }
class ____(Generic[T]): """docstring for A""" def __init__(self, a, b=None): pass
A
python
walkccc__LeetCode
solutions/1860. Incremental Memory Leak/1860.py
{ "start": 0, "end": 259 }
class ____: def memLeak(self, memory1: int, memory2: int) -> list[int]: i = 1 while memory1 >= i or memory2 >= i: if memory1 >= memory2: memory1 -= i else: memory2 -= i i += 1 return [i, memory1, memory2]
Solution
python
pytorch__pytorch
torch/onnx/_internal/exporter/_tensors.py
{ "start": 169, "end": 2613 }
class ____(ir.Value): """A subclass of ir.Value that supports Python operators.""" def __init__( self, opset: onnxscript.values.Opset, name: str | None = None, shape: ir.Shape | None = None, type: ir.TypeProtocol | None = None, doc_string: str | None = None, ...
SymbolicTensor