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
sympy__sympy
sympy/stats/symbolic_probability.py
{ "start": 15062, "end": 19536 }
class ____(Expr): """ Symbolic expression for the covariance. Examples ======== >>> from sympy.stats import Covariance >>> from sympy.stats import Normal >>> X = Normal("X", 3, 2) >>> Y = Normal("Y", 0, 1) >>> Z = Normal("Z", 0, 1) >>> W = Normal("W", 0, 1) >>> cexpr = Cova...
Covariance
python
facelessuser__soupsieve
tests/test_level4/test_attribute.py
{ "start": 96, "end": 2480 }
class ____(util.TestCase): """Test attribute selectors.""" MARKUP = """ <div> <p type="TEST" id="0" class="somewordshere">Some text <span id="1"> in a paragraph</span>.</p> <a type="test" id="2" href="http://google.com">Link</a> <span id="3" class="herewords">Direct child</span> <pre id="pr...
TestAttribute
python
ray-project__ray
release/ray_release/tests/test_buildkite.py
{ "start": 1238, "end": 1649 }
class ____: return_dict = {} def __getattribute__(self, item): return_dict = object.__getattribute__(self, "return_dict") if item in return_dict: mocked = return_dict[item] if isinstance(mocked, Callable): return mocked() else: ...
MockReturn
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py
{ "start": 598, "end": 800 }
class ____(Generic[T, SupportsRichComparisonT]): var: T compare: SupportsRichComparisonT # typing.AnyStr is a common external type variable, so treat it specially as a # known TypeVar
ExternalType
python
run-llama__llama_index
llama-index-core/tests/agent/workflow/test_code_act_agent.py
{ "start": 684, "end": 5594 }
class ____: events: list[Event] context: Context def mock_context(workflow: Workflow) -> MockContext: ctx = Context(workflow) events = [] def write_event_to_stream(event): events.append(event) ctx.write_event_to_stream = write_event_to_stream return MockContext(events=events, con...
MockContext
python
python-pillow__Pillow
Tests/test_pyarrow.py
{ "start": 4605, "end": 8122 }
class ____(NamedTuple): dtype: pyarrow.DataType # Strictly speaking, elt should be a pixel or pixel component, so # list[uint8][4], float, int, uint32, uint8, etc. But more # correctly, it should be exactly the dtype from the line above. elt: Any elts_per_pixel: int UINT_ARR = DataShape( ...
DataShape
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 17487, "end": 20410 }
class ____: def test_passing_model(self) -> None: p1 = SomeModel() d = Document() d.add_root(p1) docs_json, render_items = beu.standalone_docs_json_and_render_items([p1]) doc = next(iter(docs_json.values())) assert doc['title'] == "Bokeh Application" assert do...
Test_standalone_docs_json_and_render_items
python
ray-project__ray
python/ray/serve/tests/test_deploy_app_2.py
{ "start": 1402, "end": 30633 }
class ____: def get_deploy_config(self, model_within_logging_config: bool = False): if model_within_logging_config: path = "ray.serve.tests.test_config_files.logging_config_test.model2" else: path = "ray.serve.tests.test_config_files.logging_config_test.model" return ...
TestDeploywithLoggingConfig
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/transform_observation.py
{ "start": 19556, "end": 21959 }
class ____( TransformObservation[WrapperObsType, ActType, ObsType], gym.utils.RecordConstructorArgs, ): """Modifies the dtype of an observation array to a specified dtype. Note: This is only compatible with :class:`Box`, :class:`Discrete`, :class:`MultiDiscrete` and :class:`MultiBinary` observa...
DtypeObservation
python
davidhalter__parso
parso/python/tree.py
{ "start": 10701, "end": 12577 }
class ____(Scope): """ The top scope, which is always a module. Depending on the underlying parser this may be a full module or just a part of a module. """ __slots__ = ('_used_names',) type = 'file_input' def __init__(self, children): super().__init__(children) self._us...
Module
python
huggingface__transformers
src/transformers/models/blip/modeling_blip_text.py
{ "start": 21720, "end": 33016 }
class ____(BlipTextPreTrainedModel): """ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in [Attention is all you need](https://huggingface.co/pap...
BlipTextModel
python
pytorch__pytorch
torch/utils/_python_dispatch.py
{ "start": 1591, "end": 14843 }
class ____: """ A ``TorchDispatchMode`` allows you to override the meaning of all ``__torch_dispatch__`` overrideable functions within a dynamic scope, without having to actually create a tensor subclass or manually monkey-patch functions in the PyTorch API. Some common situations where you sho...
TorchDispatchMode
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-lancedb/llama_index/vector_stores/lancedb/base.py
{ "start": 2646, "end": 20847 }
class ____(BasePydanticVectorStore): """ The LanceDB Vector Store. Stores text and embeddings in LanceDB. The vector store will open an existing LanceDB dataset or create the dataset if it does not exist. Args: uri (str, required): Location where LanceDB will store its files. t...
LanceDBVectorStore
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 30974, "end": 34215 }
class ____(Operation): def __init__( self, pool_size, strides=None, padding="valid", data_format=None, *, name=None, ): super().__init__(name=name) self.pool_size = pool_size self.strides = strides self.padding = padding.low...
AveragePool
python
ageron__handson-ml
future_encoders.py
{ "start": 8047, "end": 29846 }
class ____(_BaseEncoder): """Encode categorical integer features as a one-hot numeric array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka 'one-of-K' or 'dummy'...
OneHotEncoder
python
pennersr__django-allauth
allauth/account/views.py
{ "start": 30611, "end": 36013 }
class ____(NextRedirectMixin, FormView): template_name = ( "account/confirm_email_verification_code." + app_settings.TEMPLATE_EXTENSION ) form_class = ConfirmEmailVerificationCodeForm def dispatch(self, request, *args, **kwargs): self.stage = LoginStageController.enter(request, EmailVer...
ConfirmEmailVerificationCodeView
python
pandas-dev__pandas
pandas/tests/arrays/categorical/test_api.py
{ "start": 300, "end": 15397 }
class ____: def test_ordered_api(self): # GH 9347 cat1 = Categorical(list("acb"), ordered=False) tm.assert_index_equal(cat1.categories, Index(["a", "b", "c"])) assert not cat1.ordered cat2 = Categorical(list("acb"), categories=list("bca"), ordered=False) tm.assert_in...
TestCategoricalAPI
python
PyCQA__pylint
tests/regrtest_data/max_inferable_limit_for_classes/nodes/roles.py
{ "start": 635, "end": 717 }
class ____(AllowsLambdaRole, UsesInspection, StructuralRole): ...
JoinTargetRole
python
pytest-dev__pytest
testing/test_doctest.py
{ "start": 38613, "end": 43831 }
class ____: SCOPES = ["module", "session", "class", "function"] def test_doctest_module_session_fixture(self, pytester: Pytester): """Test that session fixtures are initialized for doctest modules (#768).""" # session fixture which changes some global data, which will # be accessed by d...
TestDoctestAutoUseFixtures
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 371881, "end": 376435 }
class ____(Request): """ Reset tasks :param ids: IDs of the tasks to reset :type ids: Sequence[str] :param force: If not true, call fails if the task status is 'completed' :type force: bool :param clear_all: Clear script and execution sections completely :type clear_all: bool :param...
ResetManyRequest
python
ray-project__ray
python/ray/serve/_private/deployment_scheduler.py
{ "start": 9084, "end": 25036 }
class ____(ABC): """A centralized scheduler for all Serve deployments. It makes a batch of scheduling decisions in each update cycle. """ def __init__( self, cluster_node_info_cache: ClusterNodeInfoCache, head_node_id: str, create_placement_group_fn: Callable, ): ...
DeploymentScheduler
python
PrefectHQ__prefect
tests/test_flow_engine.py
{ "start": 75421, "end": 79943 }
class ____: async def test_no_lease_renewal_sync( self, prefect_client: PrefectClient, monkeypatch: pytest.MonkeyPatch ): mock_maintain_concurrency_lease = MagicMock() monkeypatch.setattr( "prefect.flow_engine.maintain_concurrency_lease", mock_maintain_concurrency...
TestLeaseRenewal
python
walkccc__LeetCode
solutions/1660. Correct a Binary Tree/1660.py
{ "start": 0, "end": 388 }
class ____: def __init__(self): self.seen = set() def correctBinaryTree(self, root: TreeNode | None) -> TreeNode | None: if root == None: return None if root.right and root.right.val in self.seen: return None self.seen.add(root.val) root.right = self.correctBinaryTree(root.right) ...
Solution
python
pyca__cryptography
tests/x509/verification/test_verification.py
{ "start": 4192, "end": 6633 }
class ____: def test_build_client_verifier_missing_store(self): with pytest.raises( ValueError, match="A client verifier must have a trust store" ): PolicyBuilder().build_client_verifier() def test_verify(self): # expires 2018-11-16 01:15:03 UTC leaf = _l...
TestClientVerifier
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_excel2003_style06.py
{ "start": 315, "end": 1171 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("excel2003_style06.xlsx") self.ignore_elements = { "xl/drawings/drawing1.xml": [ "<xdr:cNvPr", "<a:p...
TestCompareXLSXFiles
python
django__django
tests/template_tests/syntax_tests/test_for.py
{ "start": 13096, "end": 13447 }
class ____(SimpleTestCase): def test_repr(self): node = ForNode( "x", "sequence", is_reversed=True, nodelist_loop=["val"], nodelist_empty=["val2"], ) self.assertEqual( repr(node), "<ForNode: for x in sequence, tail_len: ...
ForNodeTests
python
has2k1__plotnine
tests/test_geom_ribbon_area.py
{ "start": 3008, "end": 4145 }
class ____: x = np.arange(10) d = 5 data = pd.DataFrame( {"x": x, "y1": x, "y2": x + 2 * d, "y3": x + 4 * d, "y4": x + 6 * d} ) p = ( ggplot(data, aes("x", ymax=after_stat("ymin + d"))) + geom_ribbon( aes(ymin="y1"), size=1, fill="bisque",...
TestOutlineType
python
streamlit__streamlit
lib/tests/streamlit/components/v2/test_bidi_component.py
{ "start": 8834, "end": 12327 }
class ____(DeltaGeneratorTestCase): """Validate bi-directional component mixin behavior. This suite verifies: - Parsing of ``on_<event>_change`` kwargs into an event-to-callback mapping - Registration of the per-run aggregator trigger widget with ``value_type`` equal to ``"json_trigger_value"`` ...
BidiComponentMixinTest
python
pyca__cryptography
tests/x509/test_x509.py
{ "start": 257976, "end": 259851 }
class ____: def test_eq(self): attr1 = x509.Attribute( x509.oid.AttributeOID.CHALLENGE_PASSWORD, b"value", ) attr2 = x509.Attribute( x509.oid.AttributeOID.CHALLENGE_PASSWORD, b"value", ) assert attr1 == attr2 def test_ne(se...
TestAttribute
python
kamyu104__LeetCode-Solutions
Python/single-number-ii.py
{ "start": 50, "end": 307 }
class ____(object): # @param A, a list of integer # @return an integer def singleNumber(self, A): one, two = 0, 0 for x in A: one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) return one
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 13138, "end": 13917 }
class ____(test.TestCase): def testLogCombinationsBinomial(self): n = [2, 5, 12, 15] k = [1, 2, 4, 11] if not special: return log_combs = np.log(special.binom(n, k)) n = np.array(n, dtype=np.float32) counts = [[1., 1], [2., 3], [4., 8], [11, 4]] log_binom = du.log_combinations(n,...
LogCombinationsTest
python
sqlalchemy__sqlalchemy
test/engine/test_execute.py
{ "start": 9465, "end": 13609 }
class ____(fixtures.TablesTest): @classmethod def define_tables(cls, metadata): cls.table = Table( "exec_test", metadata, Column("a", Integer), Column("b", Integer), test_needs_acid=True, ) def _trans_fn(self, is_transaction=False...
ConvenienceExecuteTest
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 208603, "end": 213170 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[4, 3]", L_y_: "f32[3, 4]"): l_x_ = L_x_ l_y_ = L_y_ tensor: "i64[1]" = torch.tensor((12,)) cumsum: "i64[1]" = tensor.cumsum(dim = 0); tensor = None getitem: "i64[0]" = cumsum[slice(None, -1, None)]; cumsum = None ...
GraphModule
python
pytorch__pytorch
test/inductor/test_provenance_tracing.py
{ "start": 20731, "end": 32113 }
class ____(TestCase): @contextlib.contextmanager def _setup_provenance_capture(self): """Helper to turn on and capture the 'inductor_tlparse_runtime' structured trace.""" payload_buffer = io.StringIO() payload_handler = logging.StreamHandler(payload_buffer) payload_handler.setLev...
TestProvenanceTracingStackTraces
python
optuna__optuna
optuna/samplers/_tpe/parzen_estimator.py
{ "start": 1055, "end": 1370 }
class ____(NamedTuple): prior_weight: float consider_magic_clip: bool consider_endpoints: bool weights: Callable[[int], np.ndarray] multivariate: bool categorical_distance_func: dict[ str, Callable[[CategoricalChoiceType, CategoricalChoiceType], float] ]
_ParzenEstimatorParameters
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-airtable/llama_index/readers/airtable/base.py
{ "start": 178, "end": 905 }
class ____(BaseReader): """ Airtable reader. Reads data from a table in a base. Args: api_key (str): Airtable API key. """ def __init__(self, api_key: str) -> None: """Initialize Airtable reader.""" self.api_key = api_key def load_data(self, base_id: str, table_id: st...
AirtableReader
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/74_class_kwargs_2.py
{ "start": 0, "end": 31 }
class ____(int, x=42): pass
Foo
python
openai__openai-python
src/openai/types/responses/response_mcp_call_failed_event.py
{ "start": 203, "end": 582 }
class ____(BaseModel): item_id: str """The ID of the MCP tool call item that failed.""" output_index: int """The index of the output item that failed.""" sequence_number: int """The sequence number of this event.""" type: Literal["response.mcp_call.failed"] """The type of the event. A...
ResponseMcpCallFailedEvent
python
faif__python-patterns
patterns/behavioral/catalog.py
{ "start": 220, "end": 1368 }
class ____: """catalog of multiple static methods that are executed depending on an init parameter """ def __init__(self, param: str) -> None: # dictionary that will be used to determine which static method is # to be executed but that will be also used to store possible param # val...
Catalog
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 31063, "end": 31989 }
class ____(Node): __slots__ = ('loc', 'name', 'directives',) _fields = ('name',) def __init__(self, name, loc=None, directives=None): self.loc = loc self.name = name self.directives = directives def __eq__(self, other): return ( self is other or ( ...
EnumValueDefinition
python
walkccc__LeetCode
solutions/2323. Find Minimum Time to Finish All Jobs II/2323.py
{ "start": 0, "end": 239 }
class ____: def minimumTime(self, jobs: list[int], workers: list[int]) -> int: ans = 0 jobs.sort() workers.sort() for job, worker in zip(jobs, workers): ans = max(ans, (job - 1) // worker + 1) return ans
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 108761, "end": 109431 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "enterprise_id", "invitee", "email", "role", "client_mutation_id", ) enterprise_id = sgqlc.types.Field( sgqlc.types.non_null(...
InviteEnterpriseAdminInput
python
ApeWorX__ape
src/ape/managers/project.py
{ "start": 1591, "end": 12387 }
class ____(BaseManager): """ A manager of a local-project's source-paths. Access via ``project.sources``. Allows source-access from both ``source_id`` and ``path``. Handles detecting modified sources as well as excluded sources. Is meant to resemble a PackageManifest's source dict but with m...
SourceManager
python
networkx__networkx
networkx/algorithms/centrality/tests/test_katz_centrality.py
{ "start": 52, "end": 3716 }
class ____: def test_K5(self): """Katz centrality: K5""" G = nx.complete_graph(5) alpha = 0.1 b = nx.katz_centrality(G, alpha) v = math.sqrt(1 / 5.0) b_answer = dict.fromkeys(G, v) for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1...
TestKatzCentrality
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_bigquery.py
{ "start": 34372, "end": 34797 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.bigquery._BigQueryDbHookMixin.get_db_hook") def test_get_db_hook( self, mock_get_db_hook, operator_class, kwargs, ): operator = operator_class(task_id=TASK_ID, gcp_conn_id="google_cloud_default", **kwar...
TestBigQueryCheckOperators
python
django__django
tests/admin_views/admin.py
{ "start": 17433, "end": 17621 }
class ____(admin.ModelAdmin): list_display = ("reference", "driver", "restaurant") list_editable = ("driver", "restaurant") show_facets = admin.ShowFacets.NEVER
FoodDeliveryAdmin
python
run-llama__llama_index
llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/df.py
{ "start": 551, "end": 762 }
class ____(BaseModel): """Column in a DataFrame.""" column_name: str = Field(..., description="Column name.") column_desc: Optional[str] = Field(..., description="Column description.")
DataFrameColumn
python
arrow-py__arrow
arrow/locales.py
{ "start": 136237, "end": 137612 }
class ____(Locale): names = ["ur", "ur-pk"] past = "پہلے {0}" future = "میں {0}" and_word = "اور" timeframes = { "now": "ابھی", "second": "ایک سیکنڈ", "seconds": "{0} سیکنڈ", "minute": "ایک منٹ", "minutes": "{0} منٹ", "hour": "ایک گھنٹے", "ho...
UrduLocale
python
huggingface__transformers
tests/models/dinov3_vit/test_modeling_dinov3_vit.py
{ "start": 9628, "end": 11486 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( AutoImageProcessor.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m") if is_vision_available() else None ) @slow def test_inference_no_head(self): ...
DINOv3ViTModelIntegrationTest
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial002_py39.py
{ "start": 104, "end": 407 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: list[str] = [] @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
Item
python
pytorch__pytorch
test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_autograd.py
{ "start": 217, "end": 1041 }
class ____(TestCase): # Support MPS and Windows platform later and fix torchdynamo issue @skipIfMPS @skipIfWindows() @skipIfTorchDynamo() def test_autograd_init(self): # Make sure autograd is initialized torch.ones(2, requires_grad=True, device="openreg").sum().backward() pi...
TestAutograd
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_model_checkpoint_edge_cases.py
{ "start": 305, "end": 837 }
class ____(Dataset): def __init__(self, n: int = 8): self.x = torch.arange(n, dtype=torch.float32).view(-1, 1) self.y = self.x.clone() def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx], self.y[idx] def _make_loaders(n=8, batch_size=2): ...
TinyDataset
python
optuna__optuna
optuna/trial/_trial.py
{ "start": 29607, "end": 30143 }
class ____(UserDict): def __init__(self, trial_id: int, storage: optuna.storages.BaseStorage) -> None: super().__init__() self._trial_id = trial_id self._storage = storage self._initialized = False def __getattribute__(self, key: str) -> Any: if key == "data": ...
_LazyTrialSystemAttrs
python
getsentry__sentry
tests/sentry/issue_detection/test_consecutive_http_detector.py
{ "start": 782, "end": 16996 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self._settings = get_detection_settings() def find_problems(self, event: dict[str, Any]) -> list[PerformanceProblem]: detector = ConsecutiveHTTPSpanDetector(self._settings, event) run_detector_on_data(detector, event...
ConsecutiveHTTPSpansDetectorTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/workspace/context.py
{ "start": 4096, "end": 28037 }
class ____(LoadingContext): """This class is a request-scoped object that stores (1) a reference to all repository locations that exist on the `IWorkspaceProcessContext` at the start of the request and (2) a snapshot of the workspace at the start of the request. This object is needed because a process ...
BaseWorkspaceRequestContext
python
pytorch__pytorch
test/distributed/_composable/test_composability/test_2d_composability.py
{ "start": 25607, "end": 39242 }
class ____(DTensorTestBase): @property def backend(self): # need to specify gloo backend for testing cpu offload return "cpu:gloo,xpu:xccl" if TEST_XPU else "cpu:gloo,cuda:nccl" @with_comms @skip_if_lt_x_gpu(4) def test_fsdp_2d_extension(self): """ Test whether _fsdp...
TestNew2dParallelStateDict
python
getsentry__sentry
src/sentry/types/actor.py
{ "start": 10217, "end": 11696 }
class ____(Protocol): """Protocol for objects that are owned by Actor but need to store ownership in discrete columns""" @property def owner(self) -> Actor | None: ... @owner.setter def owner(self, actor: Actor | None) -> None: ... def parse_and_validate_actor(actor_identifier: str | None, organ...
ActorOwned
python
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 41271, "end": 44344 }
class ____(OutbrainAmplifyStream, HttpSubStream): primary_key = None def __init__(self, authenticator, config, parent: Marketers, **kwargs): super().__init__(parent=parent, **kwargs) self.config = config self._authenticator = authenticator self._session = requests.sessions.Sessi...
PerformanceReportMarketersCampaignsByGeo
python
scrapy__scrapy
tests/test_command_version.py
{ "start": 53, "end": 678 }
class ____: def test_output(self) -> None: _, out, _ = proc("version") assert out.strip() == f"Scrapy {scrapy.__version__}" def test_verbose_output(self) -> None: _, out, _ = proc("version", "-v") headers = [line.partition(":")[0].strip() for line in out.strip().splitlines()] ...
TestVersionCommand
python
huggingface__transformers
src/transformers/models/sew_d/modeling_sew_d.py
{ "start": 14698, "end": 15142 }
class ____(nn.Module): def __init__(self, num_conv_pos_embeddings): super().__init__() self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0 def forward(self, hidden_states): if self.num_pad_remove > 0: hidden_states = hidden_states[:, :, : -self.num_pad_remove]...
SEWDSamePadLayer
python
django__django
django/test/testcases.py
{ "start": 65162, "end": 67864 }
class ____(TransactionTestCase): """ Do basically the same as TransactionTestCase but also launch a live HTTP server in a separate thread so that the tests may use another testing framework, such as Selenium for example, instead of the built-in dummy client. It inherits from TransactionTestCase ...
LiveServerTestCase
python
psf__black
tests/data/cases/preview_long_strings__regression.py
{ "start": 11333, "end": 11919 }
class ____: class B: def foo(): if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the mai...
A
python
google__jax
jax/_src/export/shape_poly.py
{ "start": 68502, "end": 72072 }
class ____: comp: Comparator left: DimSize right: DimSize # `error_message_pieces` is a list of strings and DimSize. The error message # is formed by evaluating the DimSize and concatenating the sequence. error_message_pieces: Sequence[str | DimSize] def check_statically(self, eval: ShapeEvaluator) -> N...
ShapeConstraint
python
sympy__sympy
sympy/polys/agca/modules.py
{ "start": 33500, "end": 41088 }
class ____(SubModule): """ Submodule of a free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of FreeModule instead: >>> from sympy.abc import x, y >>> from sympy import QQ >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> F.submodule([x, y],...
SubModulePolyRing
python
astropy__astropy
astropy/io/ascii/basic.py
{ "start": 5984, "end": 6123 }
class ____(core.DefaultSplitter): """ Split on comma for CSV (comma-separated-value) tables. """ delimiter = ","
CsvSplitter
python
scipy__scipy
scipy/linalg/tests/test_decomp_update.py
{ "start": 47698, "end": 47761 }
class ____(BaseQRinsert): dtype = np.dtype('D')
TestQRinsert_D
python
pandas-dev__pandas
pandas/io/pytables.py
{ "start": 90243, "end": 90345 }
class ____(DataIndexableCol): """represent a generic pytables data column"""
GenericDataIndexableCol
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/skills/skills.py
{ "start": 23756, "end": 24375 }
class ____: def __init__(self, skills: Skills) -> None: self._skills = skills self.create = to_streamed_response_wrapper( skills.create, ) self.retrieve = to_streamed_response_wrapper( skills.retrieve, ) self.list = to_streamed_response_wrappe...
SkillsWithStreamingResponse
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/autoVariance4.py
{ "start": 797, "end": 855 }
class ____(Generic[T_contra]): pass
Parent_Contravariant
python
huggingface__transformers
src/transformers/models/layoutlmv3/modeling_layoutlmv3.py
{ "start": 8360, "end": 8834 }
class ____(PreTrainedModel): config: LayoutLMv3Config base_model_prefix = "layoutlmv3" input_modalities = ("image", "text") @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" super()._init_weights(module) if isinstance(module, LayoutLMv3Model): ...
LayoutLMv3PreTrainedModel
python
walkccc__LeetCode
solutions/2391. Minimum Amount of Time to Collect Garbage/2391.py
{ "start": 0, "end": 488 }
class ____: def garbageCollection(self, garbage: list[str], travel: list[int]) -> int: prefix = list(itertools.accumulate(travel)) def getTime(c: str) -> int: characterCount = 0 lastIndex = -1 for i, s in enumerate(garbage): if any(g == c for g in s): lastIndex = i ...
Solution
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 83948, "end": 85514 }
class ____(ModelOutput): """ Base class for outputs of image super resolution models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Reconstruction loss. reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, h...
ImageSuperResolutionOutput
python
pytorch__pytorch
test/inductor/test_inductor_freezing.py
{ "start": 3766, "end": 4280 }
class ____(torch.nn.Module): def __init__(self, in_channels, out_channels, bias=False, **kwargs): super().__init__() self.conv = torch.nn.Conv2d(in_channels, out_channels, bias=bias, **kwargs) self.bn = torch.nn.BatchNorm2d(out_channels, eps=0.001, dtype=torch.float) self.bn2 = torch...
ConvMultiBN
python
huggingface__transformers
src/transformers/models/ijepa/modeling_ijepa.py
{ "start": 9874, "end": 10517 }
class ____(nn.Module): """ The residual connection is defined in IJepaLayer instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: IJepaConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, ...
IJepaSelfOutput
python
doocs__leetcode
solution/0000-0099/0083.Remove Duplicates from Sorted List/Solution.py
{ "start": 151, "end": 448 }
class ____: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: cur = head while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next return head
Solution
python
huggingface__transformers
tests/pipelines/test_pipelines_any_to_any.py
{ "start": 1165, "end": 15166 }
class ____(unittest.TestCase): model_mapping = MODEL_FOR_MULTIMODAL_LM_MAPPING # We only need `processor` but the Mixin will pass all possible preprocessing classes for a model. # So we add them all in signature def get_test_pipeline( self, model, tokenizer, processor, image_processor=None, fea...
AnyToAnyPipelineTests
python
simonw__datasette
datasette/filters.py
{ "start": 9528, "end": 15261 }
class ____: _filters = ( [ # key, display, sql_template, human_template, format=, numeric=, no_argument= TemplatedFilter( "exact", "=", '"{c}" = :{p}', lambda c, v: "{c} = {v}" if v.isdigit() else '{c} = "{v}"', ...
Filters
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/proxied_state.py
{ "start": 6369, "end": 8412 }
class ____(Exception): pass def load_proxied_state_from_yaml(proxied_yaml_path: Path) -> AirflowProxiedState: """Loads the proxied state from a directory of yaml files. Expects the directory to contain yaml files, where each file corresponds to the id of a dag (ie: `dag_id.yaml`). This directory is t...
ProxiedStateParsingError
python
spack__spack
lib/spack/spack/vendor/jinja2/sandbox.py
{ "start": 13937, "end": 14561 }
class ____(Formatter): def __init__(self, env: Environment, **kwargs: t.Any) -> None: self._env = env super().__init__(**kwargs) # type: ignore def get_field( self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any] ) -> t.Tuple[t.Any, str]: first, rest...
SandboxedFormatter
python
walkccc__LeetCode
solutions/131. Palindrome Partitioning/131.py
{ "start": 0, "end": 445 }
class ____: def partition(self, s: str) -> list[list[str]]: ans = [] def isPalindrome(s: str) -> bool: return s == s[::-1] def dfs(s: str, j: int, path: list[str], ans: list[list[str]]) -> None: if j == len(s): ans.append(path) return for i in range(j, len(s)): ...
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/live-tests/src/live_tests/report.py
{ "start": 915, "end": 1026 }
class ____(Enum): INITIALIZING = "initializing" RUNNING = "running" FINISHED = "finished"
ReportState
python
coleifer__peewee
tests/base.py
{ "start": 4808, "end": 6574 }
class ____(unittest.TestCase): def setUp(self): self._qh = QueryLogHandler() logger.setLevel(logging.DEBUG) logger.addHandler(self._qh) def tearDown(self): logger.removeHandler(self._qh) def assertIsNone(self, value): self.assertTrue(value is None, '%r is not None' ...
BaseTestCase
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 414685, "end": 416705 }
class ____(ExprNode, ModuleNameMixin): # Helper class used in the implementation of Python # class definitions. Constructs a class object given # a name, tuple of bases and class dictionary. # # name EncodedString Name of the class # class_def_node PyClassDefNode PyClassDefNo...
ClassNode
python
getsentry__sentry
src/sentry/sentry_metrics/querying/data/execution.py
{ "start": 11221, "end": 19072 }
class ____: """ Represents the result of a ScheduledQuery containing its associated series and totals results. Attributes: has_more: True if the query has more groups stored than they were returned. This is used in conjunction with dynamic limiting. """ series_query: ScheduledQ...
QueryResult
python
kamyu104__LeetCode-Solutions
Python/maximum-size-of-a-set-after-removals.py
{ "start": 486, "end": 989 }
class ____(object): def maximumSetSize(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ lookup1, lookup2 = set(nums1), set(nums2) n, c = len(nums1), len(lookup1&lookup2) d1, d2 = min(len(lookup1)-c, n//2), min(len(...
Solution2
python
mlflow__mlflow
tests/pyfunc/test_pyfunc_model_with_type_hints.py
{ "start": 16973, "end": 17455 }
class ____(mlflow.pyfunc.PythonModel): def predict(self, context, model_input: {type_hint}, params=None) -> {type_hint}: return model_input set_model(TestModel()) """ file_content = f""" import mlflow from mlflow.models import set_model import datetime import pydantic from typing import Any, Optional,...
TestModel
python
wandb__wandb
wandb/vendor/pygments/lexers/textfmts.py
{ "start": 525, "end": 2817 }
class ____(RegexLexer): """ Lexer for IRC logs in *irssi*, *xchat* or *weechat* style. """ name = 'IRC logs' aliases = ['irc'] filenames = ['*.weechatlog'] mimetypes = ['text/x-irclog'] flags = re.VERBOSE | re.MULTILINE timestamp = r""" ( # irssi / xchat and other...
IrcLogsLexer
python
dagster-io__dagster
python_modules/libraries/dagster-dlt/dagster_dlt/components/dlt_load_collection/scaffolder.py
{ "start": 545, "end": 626 }
class ____(NamedTuple): pipeline_src: str source_src: str
PipelineAndSource
python
kamyu104__LeetCode-Solutions
Python/ugly-number-ii.py
{ "start": 43, "end": 1442 }
class ____(object): # @param {integer} n # @return {integer} def nthUglyNumber(self, n): ugly_number = 0 heap = [] heapq.heappush(heap, 1) for _ in xrange(n): ugly_number = heapq.heappop(heap) if ugly_number % 2 == 0: heapq.heappush(he...
Solution
python
astropy__astropy
astropy/table/tests/test_table.py
{ "start": 54069, "end": 65010 }
class ____: def test_convert_numpy_array(self, table_types): d = table_types.Table([[1, 2], [3, 4]], names=("a", "b")) np_data = np.array(d) if table_types.Table is not MaskedTable: assert np.all(np_data == d.as_array()) assert np_data is not d.as_array() assert ...
TestConvertNumpyArray
python
doocs__leetcode
solution/2400-2499/2438.Range Product Queries of Powers/Solution.py
{ "start": 0, "end": 412 }
class ____: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: powers = [] while n: x = n & -n powers.append(x) n -= x mod = 10**9 + 7 ans = [] for l, r in queries: x = 1 for i in range(l, r + 1...
Solution
python
fluentpython__example-code
06-dp-1class-func/classic_strategy.py
{ "start": 2228, "end": 2468 }
class ____(Promotion): # first Concrete Strategy """5% discount for customers with 1000 or more fidelity points""" def discount(self, order): return order.total() * .05 if order.customer.fidelity >= 1000 else 0
FidelityPromo
python
getlogbook__logbook
src/logbook/base.py
{ "start": 5040, "end": 5547 }
class ____: """Helper for exception caught blocks.""" def __init__(self, logger, args, kwargs): self.logger = logger self.args = args self.kwargs = kwargs def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is not None: ...
_ExceptionCatcher
python
celery__celery
t/unit/worker/test_consumer.py
{ "start": 40528, "end": 49197 }
class ____: def test_init(self): c = self.Consumer() c.app.connection_for_read = _amqp_connection() g = Gossip(c) assert g.enabled assert c.gossip is g def test_callbacks(self): c = self.Consumer() c.app.connection_for_read = _amqp_connection() g...
test_Gossip
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 179220, "end": 185212 }
class ____(Response): """ Response of tasks.delete_many endpoint. :param deleted: Number of tasks deleted :type deleted: int :param updated_children: Number of child tasks whose parent property was updated :type updated_children: int :param updated_models: Number of models whose tas...
DeleteManyResponse
python
spyder-ide__spyder
spyder/utils/stylesheet.py
{ "start": 23017, "end": 24340 }
class ____(SpecialTabBarStyleSheet, SpyderFontsMixin): """Style for tab bars in our Preferences dialog.""" # This is necessary because this class needs to access fonts SET_STYLESHEET_AT_INIT = False def set_stylesheet(self): super().set_stylesheet() # Main constants css = self...
PreferencesTabBarStyleSheet
python
huggingface__transformers
examples/modular-transformers/modeling_super.py
{ "start": 10820, "end": 12602 }
class ____(GradientCheckpointingLayer): def __init__(self, config: SuperConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = SuperAttention(config=config, layer_idx=layer_idx) self.mlp = SuperMLP(config) self.input_layernorm = S...
SuperDecoderLayer
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 182255, "end": 186630 }
class ____(TreeVisitor): """ Used by finalExceptClauseNode to work out if the body needs to handle exceptions at all. This includes: 1. Can raise an exception. 2. May try to access the traceback. """ def __init__(self): self.uses_no_exceptions = True self.assignment_lhs = No...
HasNoExceptionHandlingVisitor
python
sympy__sympy
sympy/polys/matrices/tests/test_xxm.py
{ "start": 11456, "end": 29778 }
class ____: def __getitem__(self, item): return item _slice = _Sliced() @pytest.mark.parametrize('DM', DMZ_all) def test_XXM_extract_slice(DM): A = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert A.extract_slice(*_slice[:,:]) == A assert A.extract_slice(*_slice[1:,:]) == DM([[4, 5, 6], [7, 8, 9...
_Sliced
python
scrapy__scrapy
tests/test_downloader_handlers.py
{ "start": 1198, "end": 2734 }
class ____: def test_enabled_handler(self): handlers = {"scheme": DummyDH} crawler = get_crawler(settings_dict={"DOWNLOAD_HANDLERS": handlers}) dh = DownloadHandlers(crawler) assert "scheme" in dh._schemes assert "scheme" in dh._handlers assert "scheme" not in dh._not...
TestLoad