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
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 66970, "end": 68054 }
class ____(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): reason = self.request.arguments.get("reason", []) self.set_status( int(self.get_argument("code")), reason=to_unicode(reason[0]) if reason else None, ) def...
StatusReasonTest
python
PrefectHQ__prefect
src/prefect/client/orchestration/_automations/client.py
{ "start": 5561, "end": 10931 }
class ____(BaseAsyncClient): async def create_automation(self, automation: "AutomationCore") -> "UUID": """Creates an automation in Prefect Cloud.""" response = await self.request( "POST", "/automations/", json=automation.model_dump(mode="json"), ) ...
AutomationAsyncClient
python
ray-project__ray
python/ray/tests/test_task_events_2.py
{ "start": 11278, "end": 11587 }
class ____: def children(self, pid_actor): ray.get(pid_actor.report_pid.remote("children", os.getpid())) ray.get(task_finish_child.options(name="task_finish_child").remote(pid_actor)) ray.get(task_sleep_child.options(name="task_sleep_child").remote(pid_actor)) @ray.remote
ChildActor
python
numpy__numpy
numpy/lib/tests/test_type_check.py
{ "start": 6991, "end": 7847 }
class ____: def test_goodvalues(self): z = np.array((-1., 0., 1.)) res = np.isnan(z) == 0 assert_all(np.all(res, axis=0)) def test_posinf(self): with np.errstate(divide='ignore'): assert_all(np.isnan(np.array((1.,)) / 0.) == 0) def test_neginf(self): wi...
TestIsnan
python
mlflow__mlflow
mlflow/genai/labeling/stores.py
{ "start": 1438, "end": 7491 }
class ____(metaclass=ABCMeta): """ Abstract class defining the interface for labeling store implementations. This class defines the API interface for labeling operations that can be implemented by different backend stores (e.g., MLflow tracking store, Databricks API). """ def __init__(self, tr...
AbstractLabelingStore
python
has2k1__plotnine
plotnine/scales/scale_xy.py
{ "start": 8391, "end": 8570 }
class ____(scale_x_continuous): """ Continuous x position for timedelta data points """ trans: TransUser = "pd_timedelta" @dataclass(kw_only=True)
scale_x_timedelta
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 119836, "end": 121403 }
class ____(ASTBase): def __init__(self, type: ASTType, init: ASTInitializer) -> None: self.type = type self.init = init def __eq__(self, other: object) -> bool: if not isinstance(other, ASTTypeWithInit): return NotImplemented return self.type == other.type and self.i...
ASTTypeWithInit
python
pydata__xarray
xarray/tests/arrays.py
{ "start": 1171, "end": 4322 }
class ____(utils.NDArrayMixin): """Array-like that prevents casting to array. Modeled after cupy.""" def __init__(self, array: np.ndarray): self.array = array def __getitem__(self, key): return type(self)(self.array[key]) def to_numpy(self) -> np.ndarray: """Allow explicit...
DuckArrayWrapper
python
django__django
django/forms/fields.py
{ "start": 45624, "end": 46291 }
class ____(CharField): def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 ) kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH) ...
GenericIPAddressField
python
langchain-ai__langchain
libs/text-splitters/langchain_text_splitters/base.py
{ "start": 11755, "end": 12989 }
class ____: """Tokenizer data class.""" chunk_overlap: int """Overlap in tokens between chunks""" tokens_per_chunk: int """Maximum number of tokens per chunk""" decode: Callable[[list[int]], str] """ Function to decode a list of token IDs to a string""" encode: Callable[[str], list[int]...
Tokenizer
python
astropy__astropy
astropy/convolution/kernels.py
{ "start": 11936, "end": 14039 }
class ____(Kernel2D): """ 2D Ring filter kernel. The Ring filter kernel is the difference between two Tophat kernels of different width. This kernel is useful for, e.g., background estimation. The generated kernel is normalized so that it integrates to 1. Parameters ---------- radius_...
Ring2DKernel
python
getsentry__sentry
src/sentry/releases/endpoints/project_releases_token.py
{ "start": 1080, "end": 2000 }
class ____(ProjectEndpoint): publish_status = { "GET": ApiPublishStatus.UNKNOWN, "POST": ApiPublishStatus.UNKNOWN, } permission_classes = (StrictProjectPermission,) def _regenerate_token(self, project): token = uuid1().hex ProjectOption.objects.set_value(project, "sentry...
ProjectReleasesTokenEndpoint
python
joke2k__faker
faker/providers/address/de_AT/__init__.py
{ "start": 47, "end": 6422 }
class ____(AddressProvider): city_formats = ("{{city_name}}",) city_with_postcode_formats = ("{{postcode}} {{city}}",) street_name_formats = ( "{{first_name}}-{{last_name}}-{{street_suffix_long}}", "{{last_name}}{{street_suffix_short}}", ) street_address_formats = ("{{street_name}}...
Provider
python
sanic-org__sanic
sanic/exceptions.py
{ "start": 22514, "end": 23080 }
class ____(SanicException): def __init__( self, file, status_code: Optional[int] = None, *, quiet: Optional[bool] = None, context: Optional[dict[str, Any]] = None, extra: Optional[dict[str, Any]] = None, headers: Optional[dict[str, Any]] = None, ):...
PyFileError
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py
{ "start": 3262, "end": 5175 }
class ____(cfg.GraphVisitor): """CFG visitor that determines reaching definitions at statement level.""" def __init__(self, graph, definition_factory): self._definition_factory = definition_factory super(Analyzer, self).__init__(graph) self.gen_map = {} def init_state(self, _): return _NodeState...
Analyzer
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 22641, "end": 25025 }
class ____(Operation): def __init__(self, axis=-1, *, name=None): super().__init__(name=name) self.axis = axis def call(self, x): return backend.nn.softmax(x, axis=self.axis) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["kera...
Softmax
python
lazyprogrammer__machine_learning_examples
rl2/cartpole/td_lambda.py
{ "start": 663, "end": 949 }
class ____: def __init__(self, D): self.w = np.random.randn(D) / np.sqrt(D) def partial_fit(self, x, y, e, lr=1e-1): self.w += lr*(y - x.dot(self.w))*e def predict(self, X): X = np.array(X) return X.dot(self.w) # Holds one SGDRegressor for each action
SGDRegressor
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 57354, "end": 57698 }
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["GroupsResult"] = Field(default=None, descripti...
InlineResponse20018
python
pydata__xarray
xarray/backends/h5netcdf_.py
{ "start": 1587, "end": 3072 }
class ____(BaseNetCDF4Array): def get_array(self, needs_lock=True): ds = self.datastore._acquire(needs_lock) return ds.variables[self.variable_name] def __getitem__(self, key): return indexing.explicit_indexing_adapter( key, self.shape, indexing.IndexingSupport.OUTER_1VECTOR...
H5NetCDFArrayWrapper
python
encode__django-rest-framework
tests/test_utils.py
{ "start": 5471, "end": 6028 }
class ____(TestCase): """ Internally, wrapped json functions should adhere to strict float handling """ def test_dumps(self): with self.assertRaises(ValueError): json.dumps(float('inf')) with self.assertRaises(ValueError): json.dumps(float('nan')) def test_...
JsonFloatTests
python
dateutil__dateutil
src/dateutil/tz/tz.py
{ "start": 28028, "end": 33828 }
class ____(tzrangebase): """ The ``tzrange`` object is a time zone specified by a set of offsets and abbreviations, equivalent to the way the ``TZ`` variable can be specified in POSIX-like systems, but using Python delta objects to specify DST start, end and offsets. :param stdabbr: The...
tzrange
python
google__jax
tests/debug_info_test.py
{ "start": 2915, "end": 3740 }
class ____: """Use to inspect tracers. We can `append` tracers from tracing contexts to this object. We collect the tracer, along with the error message we get when we try to concretize it. This is meant to simulate errors like concretization or leaking. """ tracers: list[tuple[core.Tracer, Exception]] d...
TracerSpy
python
eventlet__eventlet
tests/mock.py
{ "start": 35170, "end": 52471 }
class ____: attribute_name = None _active_patches = set() def __init__( self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ): if new_callable is not None: if new is not DEFAULT: raise ValueError( ...
_patch
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 225323, "end": 225717 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, ): """Airbyte Source for Whisky Hunter. Documentation can be found at https://docs.airbyte.io/integrations/sources/whisky-hunter Args: name (str): The name of the destination. ...
WhiskyHunterSource
python
gevent__gevent
src/gevent/tests/test__queue.py
{ "start": 15869, "end": 15948 }
class ____(TestGetInterrupt): kind = queue.LifoQueue
TestGetInterruptLifoQueue
python
Lightning-AI__lightning
tests/tests_fabric/plugins/precision/test_xla_integration.py
{ "start": 801, "end": 2382 }
class ____(nn.Module): def __init__(self, expected_dtype): super().__init__() self.expected_dtype = expected_dtype self.layer = torch.nn.Linear(32, 2) def forward(self, x): # TODO: These should be float16/bfloat16 assert x.dtype == torch.float32 assert torch.tens...
BoringPrecisionModule
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/templates/render.py
{ "start": 1335, "end": 7558 }
class ____: column: str title: str formatter: Optional[Callable[[Any], str]] = None def dataframe_to_table_html(df: pd.DataFrame, column_mapping: List[ColumnInfo]) -> str: """ Convert a dataframe to an HTML table. """ # convert true and false to checkmarks and x's df.replace({True: "✅...
ColumnInfo
python
huggingface__transformers
src/transformers/models/omdet_turbo/modeling_omdet_turbo.py
{ "start": 4045, "end": 7766 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor`): The loss value. decoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`): The predicted coordinates logits of the objects. decoder_class_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num...
OmDetTurboObjectDetectionOutput
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 61637, "end": 79888 }
class ____(TestFeedExportBase): items = [{"foo": "bar"}] expected = b"foo\r\nbar\r\n" class MyPlugin1: def __init__(self, file, feed_options): self.file = file self.feed_options = feed_options self.char = self.feed_options.get("plugin1_char", b"") def wr...
TestFeedPostProcessedExports
python
scikit-learn__scikit-learn
sklearn/utils/deprecation.py
{ "start": 171, "end": 3531 }
class ____: """Decorator to mark a function or class as deprecated. Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring. The optional extra argument will be appended to the deprecation message and the docstring. Note: to use this with the defau...
deprecated
python
matplotlib__matplotlib
doc/sphinxext/redirect_from.py
{ "start": 2523, "end": 4301 }
class ____(SphinxDirective): required_arguments = 1 def run(self): redirected_doc, = self.arguments domain = self.env.get_domain('redirect_from') current_doc = self.env.path2doc(self.state.document.current_source) redirected_reldoc, _ = self.env.relfn2path(redirected_doc, curren...
RedirectFrom
python
rq__rq
rq/dependency.py
{ "start": 136, "end": 1000 }
class ____: @classmethod def get_jobs_with_met_dependencies(cls, jobs: Iterable['Job'], pipeline: Pipeline): jobs_with_met_dependencies = [] jobs_with_unmet_dependencies = [] for job in jobs: while True: try: pipeline.watch(*[Job.key_for(de...
Dependency
python
pytorch__pytorch
test/onnx/test_models_quantized_onnxruntime.py
{ "start": 988, "end": 1600 }
class ____(nn.Module): def __init__(self, base_model): super().__init__() self.base_model = base_model def forward(self, x): x = self.base_model(x) _, topk_id = torch.topk(x[0], 1) return topk_id # TODO: All torchvision quantized model test can be written as single par...
_TopPredictor
python
fluentpython__example-code-2e
23-descriptor/bulkfood/bulkfood_v3.py
{ "start": 780, "end": 1279 }
class ____: # <1> def __init__(self, storage_name): self.storage_name = storage_name # <2> def __set__(self, instance, value): # <3> if value > 0: instance.__dict__[self.storage_name] = value # <4> else: msg = f'{self.storage_name} must be > 0' r...
Quantity
python
joke2k__faker
faker/providers/job/cs_CZ/__init__.py
{ "start": 41, "end": 15462 }
class ____(JobProvider): """Translated from Super class""" jobs = ( "Administrátor, umění", "Administrátor, státní služba", "Advokát", "Advokát pro ochranné známky", "Akademický knihovník", "Akupunkturista", "Analytický chemik", "Analytik finanční...
Provider
python
mwaskom__seaborn
tests/test_categorical.py
{ "start": 26809, "end": 40413 }
class ____(SharedAxesLevelTests, SharedPatchArtistTests): func = staticmethod(boxplot) @pytest.fixture def common_kws(self): return {"saturation": 1} def get_last_color(self, ax): colors = [b.get_facecolor() for b in ax.containers[-1].boxes] unique_colors = np.unique(colors, ...
TestBoxPlot
python
dagster-io__dagster
python_modules/dagster/dagster/_core/events/__init__.py
{ "start": 3443, "end": 9964 }
class ____(str, Enum): """The types of events that may be yielded by op and job execution.""" STEP_OUTPUT = "STEP_OUTPUT" STEP_INPUT = "STEP_INPUT" STEP_FAILURE = "STEP_FAILURE" STEP_START = "STEP_START" STEP_SUCCESS = "STEP_SUCCESS" STEP_SKIPPED = "STEP_SKIPPED" # The process carrying...
DagsterEventType
python
huggingface__transformers
src/transformers/models/glm4v_moe/modular_glm4v_moe.py
{ "start": 2241, "end": 11217 }
class ____(Glm4MoeConfig, RotaryEmbeddingConfigMixin): r""" This is the configuration class to store the configuration of a [`Glm4vMoeModel`]. It is used to instantiate a GLM-4.5V model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults...
Glm4vMoeTextConfig
python
PyCQA__pylint
tests/functional/s/slots_checks.py
{ "start": 1669, "end": 1729 }
class ____: # [invalid-slots] __slots__ = None
EleventhBad
python
doocs__leetcode
solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/Solution.py
{ "start": 0, "end": 154 }
class ____: def minOperations(self, nums: List[int]) -> int: return sum(v.bit_count() for v in nums) + max(0, max(nums).bit_length() - 1)
Solution
python
django-haystack__django-haystack
haystack/fields.py
{ "start": 7152, "end": 7565 }
class ____(SearchField): field_type = "string" def __init__(self, **kwargs): if kwargs.get("facet_class") is None: kwargs["facet_class"] = FacetCharField super().__init__(**kwargs) def prepare(self, obj): return self.convert(super().prepare(obj)) def convert(self,...
CharField
python
falconry__falcon
tests/test_alias.py
{ "start": 241, "end": 1314 }
class ____: def on_get(self, req, resp): resp.set_cookie('foo', 'bar') @pytest.fixture def alias_client(): with pytest.warns(DeprecatedWarning, match='API class will be removed'): api = falcon.API() api.add_route('/get-cookie', CookieResource()) return testing.TestClient(api) @pytest...
CookieResource
python
PrefectHQ__prefect
src/integrations/prefect-snowflake/tests/test_database.py
{ "start": 2538, "end": 3095 }
class ____: def __enter__(self): return self def __exit__(self, *exc): return False def execute_async(self, query, params): query_id = "1234" self.result = {query_id: [(query, params)]} return {"queryId": query_id} def get_results_from_sfqid(self, query_id): ...
SnowflakeCursor
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-spread-stones-over-grid.py
{ "start": 3444, "end": 4302 }
class ____(object): def minimumMoves(self, grid): """ :type grid: List[List[int]] :rtype: int """ def dist(a, b): return abs(a[0]-b[0])+abs(a[1]-b[1]) def backtracking(curr): if curr == len(zero): return 0 result = ...
Solution3
python
django__django
tests/staticfiles_tests/test_storage.py
{ "start": 33463, "end": 36663 }
class ____(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 old_umask = os.umask(self.umask) self.addCleanup(os.umask, old_umask) super().setUp() ...
TestStaticFilePermissions
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 39379, "end": 40910 }
class ____(Response): """ Response of models.create endpoint. :param id: ID of the model :type id: str :param created: Was the model created :type created: bool """ _service = "models" _action = "create" _version = "2.23" _schema = { "definitions": {}, "prop...
CreateResponse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/unit_tests/integration/test_api.py
{ "start": 1469, "end": 4088 }
class ____(TestCase): @staticmethod def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput: return read_output( config_builder=config_, stream_name=_STREAM_NAME, sync_mode=SyncMode.full_refresh, expecting_exception=expecti...
TestFullRefresh
python
ray-project__ray
python/ray/data/_internal/execution/interfaces/physical_operator.py
{ "start": 9817, "end": 10669 }
class ____(OpTask): """Represents an OpTask that only handles metadata, instead of Block data.""" def __init__( self, task_index: int, object_ref: ray.ObjectRef, task_done_callback: Callable[[], None], task_resource_bundle: Optional[ExecutionResources] = None, ): ...
MetadataOpTask
python
apache__airflow
airflow-core/tests/unit/utils/test_module_loading.py
{ "start": 895, "end": 1371 }
class ____: def test_import_string(self): cls = import_string("airflow.utils.module_loading.import_string") assert cls == import_string # Test exceptions raised with pytest.raises(ImportError): import_string("no_dots_in_path") msg = 'Module "airflow.utils" does n...
TestModuleImport
python
joke2k__faker
faker/providers/address/vi_VN/__init__.py
{ "start": 203, "end": 7391 }
class ____(AddressProvider): """Provider for generating Vietnamese addresses. Sources: # https://vi.wikipedia.org/wiki/B%E1%BA%A3n_m%E1%BA%ABu:K%C3%BD_hi%E1%BB%87u_quy_%C6%B0%E1%BB%9Bc_c%C3%A1c_t%E1%BB%89nh_th%C3%A0nh_Vi%E1%BB%87t_Nam """ city_prefixes = ("Thành phố", "Quận", "Huyện", "Thị xã") ...
Provider
python
ray-project__ray
python/ray/util/multiprocessing/pool.py
{ "start": 12770, "end": 14564 }
class ____: """An asynchronous interface to task results. This should not be constructed directly. """ def __init__( self, chunk_object_refs, callback=None, error_callback=None, single_result=False ): self._single_result = single_result self._result_thread = ResultThread( ...
AsyncResult
python
tensorflow__tensorflow
tensorflow/python/data/ops/scan_op.py
{ "start": 1358, "end": 7068 }
class ____(dataset_ops.UnaryDataset): """A dataset that scans a function across its input.""" def __init__(self, input_dataset, initial_state, scan_func, use_default_device=None, name=None): """See `scan()` for details.""" self._inp...
_ScanDataset
python
keras-team__keras
keras/src/layers/core/embedding_test.py
{ "start": 365, "end": 21555 }
class ____(test_case.TestCase): @pytest.mark.requires_trainable_backend def test_embedding_basics(self): self.run_layer_test( layers.Embedding, {"input_dim": 4, "output_dim": 3}, input_shape=(2,), input_dtype="int32", expected_output_shape=(2, ...
EmbeddingTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py
{ "start": 4226, "end": 4364 }
class ____: def m[_T](self: _T) -> _T: x = cast('list[_\x54]', self) return x
ButStrangeStringizedReferencesCannotBeFixed
python
walkccc__LeetCode
solutions/718. Maximum Length of Repeated Subarray/718-2.py
{ "start": 0, "end": 314 }
class ____: def findLength(self, nums1: list[int], nums2: list[int]) -> int: ans = 0 dp = [0] * (len(nums2) + 1) for a in reversed(nums1): for j, b in enumerate(nums2): # The order is important. dp[j] = dp[j + 1] + 1 if a == b else 0 ans = max(ans, dp[j]) return ans
Solution
python
weaviate__weaviate-python-client
weaviate/users/async_.py
{ "start": 305, "end": 400 }
class ____(_UsersOIDCExecutor[ConnectionAsync]): pass @executor.wrap("async")
_UsersOIDCAsync
python
Farama-Foundation__Gymnasium
gymnasium/envs/phys2d/cartpole.py
{ "start": 1233, "end": 8130 }
class ____( FuncEnv[StateType, jax.Array, int, float, bool, RenderStateType, CartPoleParams] ): """Cartpole but in jax and functional.""" observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(4,), dtype=np.float32) action_space = gym.spaces.Discrete(2) def initial( self, rng: PRNGKeyT...
CartPoleFunctional
python
Netflix__metaflow
test/core/metaflow_test/__init__.py
{ "start": 2290, "end": 3870 }
class ____(MetaflowException): headline = "Testing retry" def __init__(self): super(TestRetry, self).__init__("This is not an error. " "Testing retry...") def get_card_container(id=None): """ Safetly try to load the card_container object. """ try: return get_cards(current.path...
TestRetry
python
xlwings__xlwings
xlwings/_xlmac.py
{ "start": 50049, "end": 53483 }
class ____(base_classes.Chart): def __init__(self, parent, key): self._parent = parent if isinstance(parent, Sheet): self.xl_obj = parent.xl.chart_objects[key] self.xl = self.xl_obj.chart else: self.xl_obj = None self.xl = self.charts[key] ...
Chart
python
davidhalter__jedi
jedi/inference/value/function.py
{ "start": 6257, "end": 6961 }
class ____(FunctionValue): def __init__(self, inference_state, class_context, *args, **kwargs): super().__init__(inference_state, *args, **kwargs) self.class_context = class_context def get_default_param_context(self): return self.class_context def get_qualified_names(self): ...
MethodValue
python
huggingface__transformers
src/transformers/models/zamba2/modeling_zamba2.py
{ "start": 61249, "end": 70704 }
class ____(Zamba2PreTrainedModel): """ Model consisting of *config.num_hidden_layers* layers. Args: config: Zamba2Config """ def __init__(self, config: Zamba2Config): super().__init__(config) self.config = config self.padding_idx = config.pad_token_id self.v...
Zamba2Model
python
apache__airflow
scripts/in_container/verify_providers.py
{ "start": 2082, "end": 32296 }
class ____(NamedTuple): all_entities: set[str] wrong_entities: list[tuple[type, str]] ENTITY_NAMES = { EntityType.Operators: "Operators", EntityType.Transfers: "Transfer Operators", EntityType.Sensors: "Sensors", EntityType.Hooks: "Hooks", EntityType.Secrets: "Secrets", EntityType.Trig...
VerifiedEntities
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 20888, "end": 21651 }
class ____(TestEdgeView): @classmethod def setup_class(cls): cls.G = nx.path_graph(9, nx.DiGraph()) cls.eview = nx.reportviews.InEdgeView def test_repr(self): ev = self.eview(self.G) rep = ( "InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), " + "(4, 5), (5...
TestInEdgeView
python
giampaolo__psutil
tests/test_windows.py
{ "start": 21806, "end": 24333 }
class ____(WindowsTestCase): """Compare Process API results with WMI.""" @classmethod def setUpClass(cls): cls.pid = spawn_subproc().pid @classmethod def tearDownClass(cls): terminate(cls.pid) def test_name(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] ...
TestProcessWMI
python
run-llama__llama_index
llama-index-core/llama_index/core/node_parser/node_utils.py
{ "start": 364, "end": 3566 }
class ____(Protocol): def __call__(self, i: int, doc: BaseNode) -> str: ... def default_id_func(i: int, doc: BaseNode) -> str: return str(uuid.uuid4()) def build_nodes_from_splits( text_splits: List[str], document: BaseNode, ref_doc: Optional[BaseNode] = None, id_func: Optional[IdFuncCallabl...
IdFuncCallable
python
Farama-Foundation__Gymnasium
gymnasium/envs/phys2d/pendulum.py
{ "start": 8286, "end": 9298 }
class ____(FunctionalJaxVectorEnv, EzPickle): """Jax-based implementation of the vectorized CartPole environment.""" metadata = {"render_modes": ["rgb_array"], "render_fps": 50, "jax": True} def __init__( self, num_envs: int, render_mode: str | None = None, max_episode_step...
PendulumJaxVectorEnv
python
pypa__pipenv
pipenv/patched/pip/_internal/metadata/__init__.py
{ "start": 2946, "end": 5753 }
class ____(Protocol): NAME: 'Literal["importlib", "pkg_resources"]' Distribution: Type[BaseDistribution] Environment: Type[BaseEnvironment] @functools.lru_cache(maxsize=None) def select_backend() -> Backend: if _should_use_importlib_metadata(): from . import importlib return cast(Back...
Backend
python
optuna__optuna
optuna/visualization/_timeline.py
{ "start": 474, "end": 651 }
class ____(NamedTuple): number: int start: datetime.datetime complete: datetime.datetime state: TrialState hovertext: str infeasible: bool
_TimelineBarInfo
python
django__django
tests/forms_tests/tests/tests.py
{ "start": 1358, "end": 2230 }
class ____(TestCase): """ The return values of ModelMultipleChoiceFields are QuerySets """ def test_empty_queryset_return(self): """ If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned. """ option = ChoiceOptionModel.obje...
TestTicket14567
python
huggingface__transformers
tests/models/timm_wrapper/test_image_processing_timm_wrapper.py
{ "start": 1021, "end": 4011 }
class ____(unittest.TestCase): image_processing_class = TimmWrapperImageProcessor if is_vision_available() else None def setUp(self): super().setUp() self.temp_dir = tempfile.TemporaryDirectory() config = TimmWrapperConfig.from_pretrained("timm/resnet18.a1_in1k") config.save_pre...
TimmWrapperImageProcessingTest
python
huggingface__transformers
src/transformers/integrations/bitsandbytes.py
{ "start": 695, "end": 2204 }
class ____(ConversionOps): def __init__(self, hf_quantizer): self.hf_quantizer = hf_quantizer def convert( self, input_dict: dict[str, list[torch.Tensor]], full_layer_name: str | None = None, model: torch.nn.Module | None = None, **kwargs, ) -> dict[str, torc...
Bnb4bitQuantize
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 156970, "end": 170069 }
class ____(test.TestCase): def _batch_norm(self, x, mean, var, offset, scale, epsilon): # We compute the batch norm manually in this function because # nn_impl.batch_normalization does not support float16 yet. # TODO(reedwm): Add float16 support to nn_impl.batch_normalization. inv = math_ops.rsqrt(va...
BatchNormTest
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/contexts/pipeline_context.py
{ "start": 1100, "end": 15339 }
class ____: """The pipeline context is used to store configuration for a specific pipeline run.""" _dagger_client: Optional[Client] _report: Optional[Report | ConnectorReport] dockerd_service: Optional[Service] started_at: Optional[datetime] stopped_at: Optional[datetime] secrets_to_mask: ...
PipelineContext
python
getsentry__sentry
src/sentry/integrations/discord/webhooks/handler.py
{ "start": 369, "end": 1346 }
class ____: """ Abstract class defining the shared interface of interaction handlers, along with some helper methods. """ def __init__(self, request: DiscordRequest) -> None: """ Request must be *verified*. """ self.request: DiscordRequest = request def send_mes...
DiscordInteractionHandler
python
gevent__gevent
src/greentest/3.9/test_socket.py
{ "start": 109638, "end": 112106 }
class ____(SendmsgTests): # Tests for sendmsg() which require a stream socket and do not # involve recvmsg() or recvmsg_into(). def testSendmsgExplicitNoneAddr(self): # Check that peer address can be specified as None. self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) def _testSendm...
SendmsgStreamTests
python
django__django
tests/file_uploads/models.py
{ "start": 31, "end": 119 }
class ____(models.Model): testfile = models.FileField(upload_to="test_upload")
FileModel
python
viewflow__viewflow
viewflow/jsonstore.py
{ "start": 6635, "end": 6699 }
class ____(JSONFieldMixin, fields.EmailField): pass
EmailField
python
fluentpython__example-code
21-class-metaprog/evaltime.py
{ "start": 402, "end": 527 }
class ____(): print('<[7]> ClassThree body') def method_y(self): print('<[8]> ClassThree.method_y')
ClassThree
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 20484, "end": 20727 }
class ____(RowAggregator): ''' Largest value across multiple rows. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
MaxAggregator
python
doocs__leetcode
solution/3400-3499/3477.Fruits Into Baskets II/Solution.py
{ "start": 0, "end": 382 }
class ____: def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int: n = len(fruits) vis = [False] * n ans = n for x in fruits: for i, y in enumerate(baskets): if y >= x and not vis[i]: vis[i] = True ...
Solution
python
falconry__falcon
falcon/media/urlencoded.py
{ "start": 291, "end": 3097 }
class ____(BaseHandler): """URL-encoded form data handler. This handler parses ``application/x-www-form-urlencoded`` HTML forms to a ``dict``, similar to how URL query parameters are parsed. An empty body will be parsed as an empty dict. When deserializing, this handler will raise :class:`falcon.M...
URLEncodedFormHandler
python
OmkarPathak__pygorithm
pygorithm/geometry/rect2.py
{ "start": 349, "end": 19378 }
class ____(object): """ A rectangle. Uses SAT collision against polygons and broad-phase collision against other rectangles. Rectangles are fast to construct and have very fast rectangle-rectangle collision detection. Rect2 is designed to have almost exactly the opposite performance ...
Rect2
python
doocs__leetcode
solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/Solution.py
{ "start": 0, "end": 441 }
class ____: __slots__ = ["n", "c"] def __init__(self, n: int): self.n = n self.c = [inf] * (n + 1) def update(self, x: int, v: int): while x <= self.n: self.c[x] = min(self.c[x], v) x += x & -x def query(self, x: int) -> int: mi = inf wh...
BinaryIndexedTree
python
pandas-dev__pandas
asv_bench/benchmarks/algorithms.py
{ "start": 254, "end": 1901 }
class ____: params = [ [True, False], [True, False], [ "int64", "uint64", "float64", "object", "object_str", "datetime64[ns]", "datetime64[ns, tz]", "Int64", "boolean", "st...
Factorize
python
getsentry__sentry
tests/sentry/api/serializers/test_organization_member_invite.py
{ "start": 202, "end": 2122 }
class ____(TestCase): def setUp(self) -> None: self.org = self.create_organization() self.email = "user@email.com" def test_simple(self) -> None: member_invite = self.create_member_invite( organization=self.org, email=self.email, organization_member_team_data=[] ) ...
OrganizationMemberInviteSerializerTest
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/90_docstring_class.py
{ "start": 0, "end": 27 }
class ____: "docstring"
Foo
python
pypa__pip
src/pip/_vendor/rich/segment.py
{ "start": 22710, "end": 24743 }
class ____: def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None: """A simple renderable containing a number of lines of segments. May be used as an intermediate in rendering process. Args: lines (Iterable[List[Segment]]): Lists of segments forming...
SegmentLines
python
pytorch__pytorch
torch/utils/checkpoint.py
{ "start": 69925, "end": 71948 }
class ____: """Any checkpointed regions encountered by backward under the same instance of this context manager will trigger recompute at most once, even if there are multiple calls to backward. Backward calls under the same instance of this context manager must execute over non-overlapping regions...
GraphExecGroup
python
great-expectations__great_expectations
great_expectations/metrics/column/aggregate_non_null_count.py
{ "start": 265, "end": 432 }
class ____(ColumnMetric[ColumnAggregateNonNullCountResult]): """Count of non-null values in a column""" name = "column.non_null_count"
ColumnAggregateNonNullCount
python
ray-project__ray
rllib/algorithms/iql/iql.py
{ "start": 704, "end": 8230 }
class ____(MARWILConfig): """Defines a configuration class from which a new IQL Algorithm can be built .. testcode:: :skipif: True from ray.rllib.algorithms.iql import IQLConfig # Run this from the ray directory root. config = IQLConfig().training(actor_lr=0.00001, gamma=0.99) ...
IQLConfig
python
realpython__materials
solid-principles-python/app_dip.py
{ "start": 431, "end": 634 }
class ____: def __init__(self, data_source): self.data_source = data_source def display_data(self): data = self.data_source.get_data() print("Display data:", data)
FrontEnd
python
google__pytype
pytype/pytd/pytd_visitors.py
{ "start": 622, "end": 2452 }
class ____(base_visitor.Visitor): """Visitor for converting ASTs back to canonical (sorted) ordering. Note that this visitor intentionally does *not* sort a function's signatures, as the signature order determines lookup order. """ def VisitTypeDeclUnit(self, node): return pytd.TypeDeclUnit( nam...
CanonicalOrderingVisitor
python
scrapy__scrapy
tests/test_scheduler.py
{ "start": 3753, "end": 4780 }
class ____(SchedulerHandler): def test_length(self): assert not self.scheduler.has_pending_requests() assert len(self.scheduler) == 0 for url in _URLS: self.scheduler.enqueue_request(Request(url)) assert self.scheduler.has_pending_requests() assert len(self.sche...
TestSchedulerInMemoryBase
python
redis__redis-py
redis/commands/search/field.py
{ "start": 4473, "end": 5935 }
class ____(Field): """ Allows vector similarity queries against the value in this attribute. See https://oss.redis.com/redisearch/Vectors/#vector_fields. """ def __init__(self, name: str, algorithm: str, attributes: dict, **kwargs): """ Create Vector Field. Notice that Vector cannot...
VectorField
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 44588, "end": 45215 }
class ____(TimeSeriesBaseModel, ObjectBaseModel): """An ORM representation of log data.""" name: str = Field(default=..., description="The logger name.") level: int = Field(default=..., description="The log level.") message: str = Field(default=..., description="The log message.") timestamp: DateTi...
Log
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-bedrock/llama_index/embeddings/bedrock/base.py
{ "start": 571, "end": 645 }
class ____(str, Enum): AMAZON = "amazon" COHERE = "cohere"
PROVIDERS
python
astropy__astropy
astropy/cosmology/_src/tests/io/base.py
{ "start": 500, "end": 915 }
class ____: """Base class for Cosmology I/O tests. This class will not be directly called by :mod:`pytest` since its name does not begin with ``Test``. To activate the contained tests this class must be inherited in a subclass. Subclasses must define a :func:`pytest.fixture` ``cosmo`` that returns/...
IOTestBase
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image17.py
{ "start": 315, "end": 1449 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image17.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_cr...
TestCompareXLSXFiles
python
python-openxml__python-docx
src/docx/text/hyperlink.py
{ "start": 577, "end": 5257 }
class ____(Parented): """Proxy object wrapping a `<w:hyperlink>` element. A hyperlink occurs as a child of a paragraph, at the same level as a Run. A hyperlink itself contains runs, which is where the visible text of the hyperlink is stored. """ def __init__(self, hyperlink: CT_Hyperlink, pare...
Hyperlink
python
google__pytype
pytype/tests/test_errors1.py
{ "start": 34945, "end": 36379 }
class ____(test_base.BaseTest): """Test operations with no native symbol.""" def test_getitem(self): errors = self.CheckWithErrors(""" def f(): v = []; return v['foo'] # unsupported-operands[e] """) self.assertErrorRegexes( errors, {"e": r"item retrieval.*list.*str.*__getitem__ o...
NoSymbolOperationsTest