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
run-llama__llama_index
llama-index-core/llama_index/core/tools/eval_query_engine.py
{ "start": 632, "end": 3295 }
class ____(QueryEngineTool): """ Evaluating query engine tool. A tool that makes use of a query engine and an evaluator, where the evaluation of the query engine response will determine the tool output. Args: evaluator (BaseEvaluator): A query engine. query_engine (BaseQueryEngine)...
EvalQueryEngineTool
python
pydantic__pydantic
pydantic/types.py
{ "start": 35268, "end": 35528 }
class ____(BaseModel): uuid1: UUID1 Model(uuid1=uuid.uuid1()) ``` """ UUID3 = Annotated[UUID, UuidVersion(3)] """A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 3. ```python import uuid from pydantic import UUID3, BaseModel
Model
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 143369, "end": 144341 }
class ____(TestCase): def test_basic(self): def generator(): yield 1 yield 2 sleep(0.2) yield 3 iterable = mi.time_limited(0.1, generator()) actual = list(iterable) expected = [1, 2] self.assertEqual(actual, expected) s...
TimeLimitedTests
python
walkccc__LeetCode
solutions/1309. Decrypt String from Alphabet to Integer Mapping/1309.py
{ "start": 0, "end": 303 }
class ____: def freqAlphabets(self, s: str) -> str: ans = '' i = 0 while i < len(s): if i + 2 < len(s) and s[i + 2] == '#': ans += chr(int(s[i:i + 2]) + ord('a') - 1) i += 3 else: ans += chr(int(s[i]) + ord('a') - 1) i += 1 return ans
Solution
python
euske__pdfminer
pdfminer/rijndael.py
{ "start": 45443, "end": 46223 }
class ____: """ >>> key = bytes.fromhex('00010203050607080a0b0c0d0f101112') >>> plaintext = bytes.fromhex('506812a45f08c889b97f5980038b8359') >>> RijndaelEncryptor(key, 128).encrypt(plaintext).hex() 'd8f532538289ef7d06b506a4fd5be9c9' """ def __init__(self, key, keybits=256): assert...
RijndaelEncryptor
python
ipython__ipython
IPython/core/ultratb.py
{ "start": 44622, "end": 44962 }
class ____(FormattedTB): """Deprecated since IPython 9.0.""" def __init__(self, *args, **kwargs): warnings.warn( "Deprecated since IPython 9.0 use FormattedTB directly ColorTB is just an alias", DeprecationWarning, stacklevel=2, ) super().__init__(*a...
ColorTB
python
wandb__wandb
wandb/vendor/pygments/lexers/matlab.py
{ "start": 5816, "end": 7475 }
class ____(Lexer): """ For Matlab sessions. Modeled after PythonConsoleLexer. Contributed by Ken Schutte <kschutte@csail.mit.edu>. .. versionadded:: 0.10 """ name = 'Matlab session' aliases = ['matlabsession'] def get_tokens_unprocessed(self, text): mlexer = MatlabLexer(**self...
MatlabSessionLexer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/utils.py
{ "start": 491, "end": 600 }
class ____(Enum): OWN_DRIVES = "OWN_DRIVES" SHARED_ITEMS = "SHARED_ITEMS" BOTH = "BOTH"
SearchScope
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 8137, "end": 8224 }
class ____(SelectRenderer): tag = "vf-field-select-dependent"
DependentSelectRenderer
python
python-openxml__python-docx
tests/test_table.py
{ "start": 18978, "end": 21861 }
class ____: """Unit-test suite for `docx.table._Cell` objects.""" def it_provides_access_to_its_cells(self, _index_prop_: Mock, table_prop_: Mock, table_: Mock): table_prop_.return_value = table_ _index_prop_.return_value = 4 column = _Column(cast(CT_TblGridCol, element("w:gridCol{w:w=5...
Describe_Column
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_skip/type_params.py
{ "start": 48, "end": 226 }
class ____ [ # trailing open paren comment # leading comment T # trailing type param comment # trailing type param own line comment ]: # fmt: skip pass
TestTypeParam
python
getsentry__sentry
src/sentry/integrations/source_code_management/search.py
{ "start": 1027, "end": 1224 }
class ____(serializers.Serializer[dict[str, str]]): field = serializers.CharField(required=True) query = serializers.CharField(required=True) @control_silo_endpoint
SourceCodeSearchSerializer
python
weaviate__weaviate-python-client
weaviate/collections/classes/data.py
{ "start": 763, "end": 1281 }
class ____(Generic[P, R]): """This class represents an entire object within a collection to be used when batching.""" properties: P = None # type: ignore uuid: Optional[UUID] = None vector: Optional[VECTORS] = None references: R = None # type: ignore # R is clearly bounded to Optional[Any] an...
DataObject
python
django__django
django/contrib/postgres/fields/ranges.py
{ "start": 11211, "end": 11379 }
class ____(models.Transform): lookup_name = "upper_inc" function = "UPPER_INC" output_field = models.BooleanField() @RangeField.register_lookup
UpperInclusive
python
jupyterlab__jupyterlab
examples/console/main.py
{ "start": 565, "end": 1431 }
class ____(LabServerApp): extension_url = "/example" default_url = "/example" app_url = "/example" load_other_extensions = False name = __name__ app_name = "JupyterLab Example Console" app_settings_dir = os.path.join(HERE, "build", "application_settings") schemas_dir = os.path.join(HERE,...
ExampleApp
python
huggingface__transformers
src/transformers/models/bark/modeling_bark.py
{ "start": 10324, "end": 10956 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.in_proj = nn.Linear(config.hidden_size, 4 * config.hidden_size, bias=config.bias) self.out_proj = nn.Linear(4 * config.hidden_size, config.hidden_size, bias=config.bias) self.dropout = nn.Dropout(config.dropou...
BarkMLP
python
pypa__warehouse
tests/unit/test_sessions.py
{ "start": 11406, "end": 21407 }
class ____: def test_initialize(self, monkeypatch): timestamp_signer_obj = pretend.stub() timestamp_signer_create = pretend.call_recorder( lambda secret, salt: timestamp_signer_obj ) monkeypatch.setattr(crypto, "TimestampSigner", timestamp_signer_create) strict_r...
TestSessionFactory
python
kamyu104__LeetCode-Solutions
Python/building-boxes.py
{ "start": 43, "end": 579 }
class ____(object): def minimumBoxes(self, n): """ :type n: int :rtype: int """ # find max h s.t. sum(k*(k+1)//2 for k in xrange(1, h+1)) <= n # => find max h s.t. h*(h+1)*(h+2)//6 <= n h = int((6*n)**(1.0/3)) if h*(h+1)*(h+2) > 6*n: # (h...
Solution
python
qdrant__qdrant-client
qdrant_client/local/multi_distances.py
{ "start": 1221, "end": 1630 }
class ____: def __init__(self, positive: list[list[float]], negative: list[list[float]]): self.positive: types.NumpyArray = np.array(positive) self.negative: types.NumpyArray = np.array(negative) assert not np.isnan(self.positive).any(), "Positive vector must not contain NaN" assert...
MultiContextPair
python
readthedocs__readthedocs.org
readthedocs/analytics/migrations/0006_alter_pageview_id.py
{ "start": 149, "end": 567 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("analytics", "0005_add_unique_constraint"), ] operations = [ migrations.AlterField( model_name="pageview", name="id", field=models.BigAutoField( auto_create...
Migration
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 26919, "end": 28126 }
class ____(MixinSequenceOfValues): """ x-axis tick labels Parameters ---------- theme_element : element_text Notes ----- Use the `margin` to control the gap between the ticks and the text. e.g. ```python theme(axis_text_x=element_text(margin={"t": 5, "units": "pt"})) `...
axis_text_x
python
getsentry__sentry
src/sentry_plugins/github/webhooks/events/__init__.py
{ "start": 0, "end": 666 }
class ____: def __call__(self, event, organization): raise NotImplementedError def is_anonymous_email(email): return email[-25:] == "@users.noreply.github.com" def get_external_id(username): return "github:%s" % username from .installation import InstallationEventWebhook from .installation_rep...
Webhook
python
joke2k__faker
faker/providers/address/es_MX/__init__.py
{ "start": 84, "end": 4900 }
class ____(AddressProvider): city_prefixes = ("Sur", "Norte") city_adjectives = ("Nueva", "Vieja") city_suffixes = ("de la Montaña", "los bajos", "los altos") street_prefixes = ( "Ampliación", "Andador", "Avenida", "Boulevard", "Calle", "Callejón", ...
Provider
python
huggingface__transformers
tests/models/trocr/test_modeling_trocr.py
{ "start": 5888, "end": 7057 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () pipeline_model_mapping = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} def setUp(self): self.mode...
TrOCRStandaloneDecoderModelTest
python
django__django
django/contrib/admin/widgets.py
{ "start": 15981, "end": 20109 }
class ____: """ Select widget mixin that loads options from AutocompleteJsonView via AJAX. Renders the necessary data attributes for select2 and adds the static form media. """ url_name = "%s:autocomplete" def __init__(self, field, admin_site, attrs=None, choices=(), using=None): ...
AutocompleteMixin
python
neetcode-gh__leetcode
python/0442-find-all-duplicates-in-an-array.py
{ "start": 0, "end": 269 }
class ____: def findDuplicates(self, nums: List[int]) -> List[int]: res = [] for n in nums: n = abs(n) if nums[n - 1] < 0: res.append(n) nums[n - 1] = -nums[n - 1] return res
Solution
python
django__django
django/db/backends/mysql/introspection.py
{ "start": 837, "end": 14998 }
class ____(BaseDatabaseIntrospection): data_types_reverse = { FIELD_TYPE.BLOB: "TextField", FIELD_TYPE.CHAR: "CharField", FIELD_TYPE.DECIMAL: "DecimalField", FIELD_TYPE.NEWDECIMAL: "DecimalField", FIELD_TYPE.DATE: "DateField", FIELD_TYPE.DATETIME: "DateTimeField", ...
DatabaseIntrospection
python
wandb__wandb
wandb/sdk/lib/asyncio_compat.py
{ "start": 1126, "end": 4320 }
class ____: """Runs an asyncio event loop allowing cancellation. The `run()` method is like `asyncio.run()`. The `cancel()` method may be used in a different thread, for instance in a `finally` block, to cancel all tasks, and it is a no-op if `run()` completed. Without this, it is impossible to ma...
CancellableRunner
python
PyCQA__pylint
tests/functional/i/invalid/invalid_exceptions/invalid_exceptions_caught.py
{ "start": 2358, "end": 2583 }
class ____(UnknownError): pass EXCEPTIONS = (SomeBase, ValueError) try: raise ValueError except EXCEPTIONS: pass LAMBDA = lambda x: 1, 2 try: pass except LAMBDA: # [catching-non-exception] pass
SomeBase
python
getsentry__sentry
tests/sentry/search/eap/test_spans.py
{ "start": 1078, "end": 25769 }
class ____(TestCase): def setUp(self) -> None: self.resolver = SearchResolver( params=SnubaParams(), config=SearchResolverConfig(), definitions=SPAN_DEFINITIONS ) def test_simple_query(self) -> None: where, having, _ = self.resolver.resolve_query("span.description:foo") ...
SearchResolverQueryTest
python
gevent__gevent
src/greentest/3.14/test_urllib2.py
{ "start": 19946, "end": 25772 }
class ____(unittest.TestCase): def test_add_non_handler(self): class NonHandler(object): pass self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) def test_badly_named_methods(self): # test work-around for three methods that acc...
OpenerDirectorTests
python
docker__docker-py
tests/unit/auth_test.py
{ "start": 3116, "end": 7847 }
class ____(unittest.TestCase): index_config = {'auth': encode_auth({'username': 'indexuser'})} private_config = {'auth': encode_auth({'username': 'privateuser'})} legacy_config = {'auth': encode_auth({'username': 'legacyauth'})} auth_config = auth.AuthConfig({ 'auths': auth.parse_auth({ ...
ResolveAuthTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/requirements.py
{ "start": 789, "end": 57326 }
class ____(Requirements): @property def create_table(self): """target platform can emit basic CreateTable DDL.""" return exclusions.open() @property def drop_table(self): """target platform can emit basic DropTable DDL.""" return exclusions.open() @property de...
SuiteRequirements
python
pypa__warehouse
tests/unit/api/test_simple.py
{ "start": 2592, "end": 6739 }
class ____: @pytest.mark.parametrize( ("content_type", "renderer_override"), CONTENT_TYPE_PARAMS, ) def test_no_results_no_serial(self, db_request, content_type, renderer_override): db_request.accept = content_type assert simple.simple_index(db_request) == { "meta...
TestSimpleIndex
python
falconry__falcon
falcon/bench/nuts/nuts/controllers/root.py
{ "start": 472, "end": 611 }
class ____: @expose() def _lookup(self, account_id, *remainder): return TestController(account_id), remainder
HelloController
python
huggingface__transformers
tests/models/camembert/test_modeling_camembert.py
{ "start": 958, "end": 2905 }
class ____(unittest.TestCase): @slow def test_output_embeds_base_model(self): model = CamembertModel.from_pretrained("almanach/camembert-base", attn_implementation="eager") model.to(torch_device) input_ids = torch.tensor( [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]], ...
CamembertModelIntegrationTest
python
vyperlang__vyper
vyper/venom/check_venom.py
{ "start": 845, "end": 1231 }
class ____(VenomError): message: str = "function has inconsistent return arity" def __init__(self, function: IRFunction, arities: set[int]): self.function = function self.arities = arities def __str__(self): return ( f"function {self.function.name} has inconsistent 'ret...
InconsistentReturnArity
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 11458, "end": 11598 }
class ____(sgqlc.types.Scalar): """ See source code for more info. """ __schema__ = graphql_schema ID = sgqlc.types.ID
HTML
python
pytorch__pytorch
torch/utils/benchmark/utils/timer.py
{ "start": 720, "end": 2142 }
class ____: def __init__( self, stmt: str, setup: str, global_setup: str, timer: Callable[[], float], globals: dict[str, Any], ) -> None: if timer is not timeit.default_timer: raise NotImplementedError( "PyTorch was built with a...
CPPTimer
python
pypa__pip
src/pip/_vendor/urllib3/exceptions.py
{ "start": 3509, "end": 3633 }
class ____(PoolError): """Raised when a request enters a pool after the pool has been closed.""" pass
ClosedPoolError
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/ray.py
{ "start": 3306, "end": 9798 }
class ____(RayBaseOperator): """ Create a Ray cluster on the Vertex AI. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param location: Required. The ID of the Google Cloud region that the service belongs to. :param head_node_type: The head node resourc...
CreateRayClusterOperator
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qactivation_test.py
{ "start": 1695, "end": 2467 }
class ____(op_bench.TorchBenchmarkBase): r"""Base class for all the activations.""" def _setup(self, dims, contig, dtype): # Input f_input = (torch.rand(*dims) - 0.5) * 256 self.scale = 1.0 self.zero_point = 0 # Quantize the tensor q_input = torch.quantize_per_t...
QActivationBenchmarkBase
python
tensorflow__tensorflow
tensorflow/python/training/checkpoint_utils_test.py
{ "start": 2867, "end": 17155 }
class ____(test.TestCase): def testNoCheckpoints(self): checkpoint_dir = self.get_temp_dir() + "/no_checkpoints" with self.assertRaises(errors_impl.OpError): self.assertAllEqual( checkpoint_utils.load_variable(checkpoint_dir, "var1"), []) def testNoTensor(self): checkpoint_dir = self.g...
CheckpointsTest
python
ApeWorX__ape
src/ape/types/events.py
{ "start": 944, "end": 2851 }
class ____(BaseModel): addresses: list[AddressType] = [] events: list[EventABI] = [] topic_filter: TopicFilter = [] start_block: int = 0 stop_block: Optional[int] = None # Use block height selectors: dict[str, EventABI] = {} @model_validator(mode="before") @classmethod def compute_...
LogFilter
python
cloudpipe__cloudpickle
tests/mock_local_folder/mod.py
{ "start": 476, "end": 607 }
class ____: def method(self): return "hello from a class importable locally" LocalT = typing.TypeVar("LocalT")
LocalClass
python
sqlalchemy__sqlalchemy
test/typing/plain_files/inspection_inspect.py
{ "start": 658, "end": 1334 }
class ____(BaseNoMeta): __tablename__ = "b" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] assert_type(A.__mapper__, Mapper[Any]) assert_type(B.__mapper__, Mapper[Any]) a1 = A(data="d") b1 = B(data="d") e = create_engine("sqlite://") insp_a1 = inspect(a1) t: bool = insp_a1.transi...
B
python
ray-project__ray
python/ray/llm/_internal/common/observability/telemetry_utils.py
{ "start": 123, "end": 1156 }
class ____: """Execute a function exactly once and block all callers until the function returns Same as golang's `sync.Once <https://pkg.go.dev/sync#Once>`_ Took this directly from OpenTelemetry's Python SDK: Ref: https://github.com/open-telemetry/opentelemetry-python/blob /c6fab7d4c339dc5bf9e...
Once
python
bokeh__bokeh
src/bokeh/document/locking.py
{ "start": 1560, "end": 3453 }
class ____(Protocol[F]): __call__: F nolock: Literal[True] def without_document_lock(func: F) -> NoLockCallback[F]: ''' Wrap a callback function to execute without first obtaining the document lock. Args: func (callable) : The function to wrap Returns: callable : a function wr...
NoLockCallback
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core_tests/utils_tests/test_naming.py
{ "start": 2999, "end": 3999 }
class ____: """Test how component names are processed in the scaffolding pipeline.""" def test_component_name_to_module_name_conversion(self): """Test the full pipeline from component name to module file name.""" # This simulates what happens in _parse_component_name component_names = [...
TestComponentNamingIntegration
python
pytorch__pytorch
test/distributed/_tools/test_sac_ilp.py
{ "start": 8425, "end": 10224 }
class ____(TestCase): # tests are adapted from tests in xformers # https://github.com/facebookresearch/xformers/blob/c6c0ac31f1b08542a0bc27278c6ed10f825f6963/tests/test_checkpoint.py#L222 def setUp(self): super().setUp() data = [ ("aten.copy_", 5, 0), ("aten.add", 5, ...
TestOptimalCheckpointingPolicy
python
rapidsai__cudf
python/cudf/cudf/core/series.py
{ "start": 8702, "end": 14236 }
class ____(_FrameIndexer): """ Label-based selection """ @_performance_tracking def __getitem__(self, arg: Any) -> ScalarLike | DataFrameOrSeries: if not isinstance(self._frame.index, cudf.MultiIndex): indexing_spec = indexing_utils.parse_row_loc_indexer( indexin...
_SeriesLocIndexer
python
Textualize__textual
src/textual/_compositor.py
{ "start": 1299, "end": 1724 }
class ____(NamedTuple): """The result of a reflow operation. Describes the chances to widgets.""" hidden: set[Widget] # Widgets that are hidden shown: set[Widget] # Widgets that are shown resized: set[Widget] # Widgets that have been resized # Maps a widget on to its geometry (information that des...
ReflowResult
python
matplotlib__matplotlib
galleries/examples/specialty_plots/skewt.py
{ "start": 3438, "end": 10143 }
class ____(Axes): # The projection must specify a name. This will be used be the # user to select the projection, i.e. ``subplot(projection='skewx')``. name = 'skewx' def _init_axis(self): # Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) se...
SkewXAxes
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 16375, "end": 16411 }
class ____(BaseModel): y: str
User
python
huggingface__transformers
tests/models/patchtst/test_modeling_patchtst.py
{ "start": 1589, "end": 5104 }
class ____: def __init__( self, parent, batch_size=13, prediction_length=7, context_length=14, patch_length=5, patch_stride=5, num_input_channels=1, num_time_features=1, is_training=True, hidden_size=16, num_hidden_layer...
PatchTSTModelTester
python
streamlit__streamlit
lib/streamlit/runtime/uploaded_file_manager.py
{ "start": 2842, "end": 4935 }
class ____(CacheStatsProvider, Protocol): """UploadedFileManager protocol, that should be implemented by the concrete uploaded file managers. It is responsible for: - retrieving files by session_id and file_id for st.file_uploader and st.camera_input - cleaning up uploaded files...
UploadedFileManager
python
getsentry__sentry
src/sentry/search/events/builder/metrics.py
{ "start": 2507, "end": 67828 }
class ____(BaseQueryBuilder): requires_organization_condition = True duration_fields = {"transaction.duration"} organization_column: str = "organization_id" column_remapping = { # This MetricsQueryBuilder is only used for transaction metrics. # So `message` is mapped to `transaction` b...
MetricsQueryBuilder
python
getsentry__sentry
src/sentry/notifications/notification_action/action_validation.py
{ "start": 4840, "end": 5012 }
class ____(TicketingActionValidatorHandler): provider = Action.Type.AZURE_DEVOPS @action_validator_registry.register(Action.Type.GITHUB)
AzureDevOpsActionValidatorHandler
python
huggingface__transformers
src/transformers/models/cohere2/modular_cohere2.py
{ "start": 15775, "end": 15856 }
class ____(CoherePreTrainedModel): config: Cohere2Config
Cohere2PreTrainedModel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol11.py
{ "start": 380, "end": 466 }
class ____(Generic[_TBase1]): def __iter__(self): return self
SourceProvider
python
sqlalchemy__sqlalchemy
test/sql/test_returning.py
{ "start": 9388, "end": 17798 }
class ____(fixtures.TablesTest, AssertsExecutionResults): __requires__ = ("insert_returning",) __sparse_driver_backend__ = True run_create_tables = "each" @classmethod def define_tables(cls, metadata): class GoofyType(TypeDecorator): impl = String cache_ok = True ...
InsertReturningTest
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 29766, "end": 30758 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8]", L_y_: "f32[8]"): l_x_ = L_x_ l_y_ = L_y_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_, l_y_); subgraph_0 = l_x_ = None a: "f32[8]" = invoke...
GraphModule
python
plotly__plotly.py
plotly/graph_objs/scatter3d/marker/_line.py
{ "start": 233, "end": 20147 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatter3d.marker" _path_str = "scatter3d.marker.line" _valid_props = { "autocolorscale", "cauto", "cmax", "cmid", "cmin", "color", "coloraxis", "colorscale", "colorsrc", "...
Line
python
PyCQA__pylint
tests/functional/f/function_redefined.py
{ "start": 2025, "end": 2664 }
class ____: """ABC""" # We actually *redefine* these attributes, but these shouldn't # be considered actual redefinitions. Issue #2451 @property def __module__(self): return "actual.module" @property def __doc__(self): return "Docstring" # Do not emit the error for condit...
ObjectProxy
python
walkccc__LeetCode
solutions/912. Sort an Array/912-3.py
{ "start": 0, "end": 772 }
class ____: def sortArray(self, nums: list[int]) -> list[int]: self._quickSort(nums, 0, len(nums) - 1) return nums def _quickSort(self, nums: list[int], l: int, r: int) -> None: if l >= r: return def partition(nums: list[int], l: int, r: int) -> int: randIndex = random.randint(0, r - l...
Solution
python
Netflix__metaflow
metaflow/plugins/airflow/airflow_utils.py
{ "start": 4182, "end": 6460 }
class ____: # run_id_creator is added via the `user_defined_filters` RUN_ID = "%s-{{ [run_id, dag_run.dag_id] | run_id_creator }}" % RUN_ID_PREFIX PARAMETERS = "{{ params | json_dump }}" STEPNAME = "{{ ti.task_id }}" # AIRFLOW_MACROS.TASK_ID will work for linear/branched workflows. # ti.task_i...
AIRFLOW_MACROS
python
google__jax
tests/lax_control_flow_test.py
{ "start": 6146, "end": 119108 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() lax_control_flow._initial_style_open_jaxpr.cache_clear() lax_control_flow._initial_style_jaxpr.cache_clear() lax_control_flow.common._dedup_consts.cache_clear() lax_control_flow.common._pad_constvars.cache_clear() def testCallableEr...
LaxControlFlowTest
python
tornadoweb__tornado
tornado/template.py
{ "start": 23599, "end": 23854 }
class ____(_Node): def __init__(self, statement: str, line: int) -> None: self.statement = statement self.line = line def generate(self, writer: "_CodeWriter") -> None: writer.write_line(self.statement, self.line)
_Statement
python
astropy__astropy
astropy/modeling/tests/test_parameters.py
{ "start": 4680, "end": 4730 }
class ____(M1): m2c = Parameter(default=11.0)
M2
python
automl__auto-sklearn
autosklearn/pipeline/components/data_preprocessing/rescaling/standardize.py
{ "start": 512, "end": 2168 }
class ____(Rescaling, AutoSklearnPreprocessingAlgorithm): def __init__( self, random_state: Optional[Union[int, np.random.RandomState]] = None ) -> None: from sklearn.preprocessing import StandardScaler self.preprocessor = StandardScaler(copy=False) @staticmethod def get_proper...
StandardScalerComponent
python
getsentry__sentry
src/sentry/grouping/variants.py
{ "start": 8963, "end": 9303 }
class ____(TypedDict, total=False): system: ComponentVariant app: ComponentVariant custom_fingerprint: CustomFingerprintVariant built_in_fingerprint: CustomFingerprintVariant checksum: ChecksumVariant hashed_checksum: HashedChecksumVariant default: ComponentVariant fallback: FallbackVari...
VariantsByDescriptor
python
weaviate__weaviate-python-client
weaviate/collections/classes/tenants.py
{ "start": 5271, "end": 6695 }
class ____(BaseModel): """Tenant class used to describe a tenant to create in Weaviate. Attributes: name: the name of the tenant. activity_status: TenantCreateActivityStatus, default: "HOT" """ model_config = ConfigDict(populate_by_name=True) name: str activityStatusInternal: T...
TenantCreate
python
huggingface__transformers
src/transformers/models/distilbert/tokenization_distilbert.py
{ "start": 796, "end": 1116 }
class ____(BertTokenizer): model_input_names = ["input_ids", "attention_mask"] # DistilBertTokenizerFast is an alias for DistilBertTokenizer (since BertTokenizer is already a fast tokenizer) DistilBertTokenizerFast = DistilBertTokenizer __all__ = ["DistilBertTokenizer", "DistilBertTokenizerFast"]
DistilBertTokenizer
python
scipy__scipy
scipy/interpolate/_cubic.py
{ "start": 22329, "end": 40394 }
class ____(CubicHermiteSpline): """Piecewise cubic interpolator to fit values (C2 smooth). Interpolate data with a piecewise cubic polynomial which is twice continuously differentiable [1]_. The result is represented as a `PPoly` instance with breakpoints matching the given data. Parameters --...
CubicSpline
python
matplotlib__matplotlib
lib/mpl_toolkits/mplot3d/art3d.py
{ "start": 17214, "end": 19691 }
class ____(Patch): """ 3D patch object. """ def __init__(self, *args, zs=(), zdir='z', axlim_clip=False, **kwargs): """ Parameters ---------- verts : zs : float The location along the *zdir* axis in 3D space to position the patch. ...
Patch3D
python
pytorch__pytorch
torch/_higher_order_ops/flat_apply.py
{ "start": 1941, "end": 4379 }
class ____(HigherOrderOperator): def __init__(self) -> None: super().__init__("flat_apply") def __call__(self, func, in_spec, *flat_args, **_unused): """ Functions that take in non-graphable types cannot directly be put into FX graph. Given func(*args, **kwargs), if all of the ...
FlatApply
python
modin-project__modin
modin/tests/pandas/native_df_interoperability/test_compiler_caster.py
{ "start": 8226, "end": 8420 }
class ____(NativeQueryCompiler): _MAX_SIZE_THIS_ENGINE_CAN_HANDLE = BIG_DATA_CLOUD_MIN_NUM_ROWS def __init__(self, pandas_frame): super().__init__(pandas_frame)
BaseTestAutoMover
python
pypa__virtualenv
src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py
{ "start": 496, "end": 579 }
class ____(CPython, Python3Supports, abc.ABC): """CPython 3 or later."""
CPython3
python
hynek__structlog
src/structlog/_output.py
{ "start": 708, "end": 2939 }
class ____: """ Print events into a file. Args: file: File to print to. (default: `sys.stdout`) >>> from structlog import PrintLogger >>> PrintLogger().info("hello") hello Useful if you follow `current logging best practices <logging-best-practices>`. Also very useful for...
PrintLogger
python
pytorch__pytorch
functorch/dim/_wrap.py
{ "start": 572, "end": 8286 }
class ____: """ This class wraps PyTorch operations to support first-class dimensions. """ def __init__( self, orig: Callable, wrapper_implementation: Callable, dim_name: str = "dim" ): self.orig = orig self.wrapper_implementation = wrapper_implementation self.name =...
WrappedOperator
python
catalyst-team__catalyst
catalyst/callbacks/metric.py
{ "start": 5005, "end": 6998 }
class ____(_MetricCallback): """BatchMetricCallback implements batch-based metrics update and computation over loader Args: metric: metric to calculate in callback input_key: keys of tensors that should be used as inputs in metric calculation target_key: keys of tensors that should ...
BatchMetricCallback
python
mlflow__mlflow
mlflow/bedrock/stream.py
{ "start": 6177, "end": 7875 }
class ____: """A helper class to accumulate the chunks of a streaming Converse API response.""" def __init__(self): self._role = "assistant" self._text_content_buffer = "" self._tool_use = {} self._response = {} def process_event(self, event_name: str, event_attr: dict[str,...
_ConverseMessageBuilder
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_pools.py
{ "start": 3971, "end": 5867 }
class ____(TestPoolsEndpoint): def test_get_should_respond_200(self, test_client, session): self.create_pools() response = test_client.get(f"/pools/{POOL1_NAME}") assert response.status_code == 200 assert response.json() == { "deferred_slots": 0, "description"...
TestGetPool
python
walkccc__LeetCode
solutions/2305. Fair Distribution of Cookies/2305.py
{ "start": 0, "end": 411 }
class ____: def distributeCookies(self, cookies: list[int], k: int) -> int: ans = math.inf def dfs(s: int, children: list[int]) -> None: nonlocal ans if s == len(cookies): ans = min(ans, max(children)) return for i in range(k): children[i] += cookies[s] dfs(...
Solution
python
great-expectations__great_expectations
great_expectations/render/renderer_configuration.py
{ "start": 2416, "end": 4144 }
class ____(BaseModel): """ _RendererValueBase is the base for renderer classes that need to override the default pydantic dict behavior. """ # noqa: E501 # FIXME CoP class Config: validate_assignment = True arbitrary_types_allowed = True @override def dict( # noqa: PLR0913 # ...
_RendererValueBase
python
tiangolo__fastapi
tests/test_jsonable_encoder.py
{ "start": 1159, "end": 1369 }
class ____(BaseModel): role: Optional[RoleEnum] = None if PYDANTIC_V2: model_config = {"use_enum_values": True} else: class Config: use_enum_values = True
ModelWithConfig
python
scrapy__scrapy
tests/pipelines.py
{ "start": 173, "end": 265 }
class ____: def process_item(self, item): 1 / 0
ProcessWithZeroDivisionErrorPipeline
python
huggingface__transformers
src/transformers/models/olmo2/modeling_olmo2.py
{ "start": 15925, "end": 19052 }
class ____(Olmo2PreTrainedModel): def __init__(self, config: Olmo2Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layer...
Olmo2Model
python
sqlalchemy__sqlalchemy
test/engine/test_parseconnect.py
{ "start": 29332, "end": 30840 }
class ____(fixtures.TestBase): @fixture def mock_create(self): with patch( "sqlalchemy.engine.create.create_engine", ) as p: yield p def test_url_only(self, mock_create): create_pool_from_url("sqlite://") mock_create.assert_called_once_with("sqlite://...
CreatePoolTest
python
walkccc__LeetCode
solutions/2154. Keep Multiplying Found Values by Two/2155-2.py
{ "start": 0, "end": 242 }
class ____: def findFinalValue(self, nums: list[int], original: int) -> int: seen = [False] * 1001 for num in nums: seen[num] = True while original < 1001 and seen[original]: original *= 2 return original
Solution
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py
{ "start": 18271, "end": 28811 }
class ____(RegexLexer): """ For Python 2.x source code. .. versionchanged:: 2.5 This class has been renamed from ``PythonLexer``. ``PythonLexer`` now refers to the Python 3 variant. File name patterns like ``*.py`` have been moved to Python 3 as well. """ name = 'Python 2.x'...
Python2Lexer
python
streamlit__streamlit
lib/tests/streamlit/config_util_test.py
{ "start": 10665, "end": 53628 }
class ____(unittest.TestCase): """Test theme inheritance utility functions.""" def setUp(self): self.config_template = CONFIG_OPTIONS_TEMPLATE def _get_expected_theme_options_count(self, section: str = "theme") -> int: """ Get the expected count of theme options by directly countin...
ThemeInheritanceUtilTest
python
getsentry__sentry
src/sentry/models/search_common.py
{ "start": 27, "end": 207 }
class ____(IntEnum): ISSUE = 0 EVENT = 1 SESSION = 2 REPLAY = 3 METRIC = 4 SPAN = 5 ERROR = 6 TRANSACTION = 7 LOG = 8 TRACEMETRIC = 9
SearchType
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/error_record_builder.py
{ "start": 221, "end": 1163 }
class ____(RecordBuilder): def __init__( self, template: Dict[str, Any], id_path: Optional[Path] = None, cursor_path: Optional[Union[FieldPath, NestedPath]] = None, error_message_path: Optional[Path] = None, ): super().__init__(template, id_path, cursor_path) ...
ErrorRecordBuilder
python
python__mypy
mypy/typeops.py
{ "start": 43468, "end": 49736 }
class ____(TypeTraverserVisitor): def visit_callable_type(self, t: CallableType) -> None: for v in t.variables: v.id.meta_level = 0 super().visit_callable_type(t) def custom_special_method(typ: Type, name: str, check_all: bool = False) -> bool: """Does this type have a custom speci...
FreezeTypeVarsVisitor
python
run-llama__llama_index
llama-index-utils/llama-index-utils-qianfan/llama_index/utils/qianfan/client.py
{ "start": 1418, "end": 5712 }
class ____: """ The access client for Baidu's Qianfan LLM Platform. """ def __init__(self, access_key: str, secret_key: str): """ Initialize a Client instance. :param access_key: The Access Key obtained from the Security Authentication Center of Baidu Intelligent Cloud Console....
Client
python
numpy__numpy
numpy/polynomial/tests/test_polynomial.py
{ "start": 13945, "end": 15282 }
class ____: def test_polyder(self): # check exceptions assert_raises(TypeError, poly.polyder, [0], .5) assert_raises(ValueError, poly.polyder, [0], -1) # check that zeroth derivative does nothing for i in range(5): tgt = [0] * i + [1] res = poly.poly...
TestDerivative
python
huggingface__transformers
tests/models/longformer/test_modeling_longformer.py
{ "start": 17255, "end": 32961 }
class ____(unittest.TestCase): def _get_hidden_states(self): return torch.tensor( [ [ [ 4.98332758e-01, 2.69175139e00, -7.08081422e-03, 1.04915401e00, ...
LongformerModelIntegrationTest
python
lxml__lxml
src/lxml/tests/dummy_http_server.py
{ "start": 997, "end": 1126 }
class ____(wsgiserver.WSGIServer, ThreadingMixIn): """A web server that starts a new thread for each request. """
WebServer
python
google__jax
jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py
{ "start": 2651, "end": 3350 }
class ____(nn.Module): """Applies word dropout to a batch of input IDs. This is basically the same as `nn.Dropout`, but allows specifying the value of dropped out items. """ dropout_rate: float unk_idx: int deterministic: bool | None = None @nn.compact def __call__(self, inputs: Array, deterministic...
WordDropout