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
pyqtgraph__pyqtgraph
pyqtgraph/imageview/ImageView.py
{ "start": 1290, "end": 1523 }
class ____(ROI): def __init__(self, size): ROI.__init__(self, pos=[0,0], size=size) #, scaleSnap=True, translateSnap=True) self.addScaleHandle([1, 1], [0, 0]) self.addRotateHandle([0, 0], [0.5, 0.5])
PlotROI
python
pandas-dev__pandas
asv_bench/benchmarks/frame_ctor.py
{ "start": 3345, "end": 3817 }
class ____: def setup(self): self.nrows = 100_000 def time_frame_from_scalar_ea_float64(self): DataFrame( 1.0, index=range(self.nrows), columns=list("abc"), dtype=Float64Dtype(), ) def time_frame_from_scalar_ea_float64_na(self): ...
FromScalar
python
optuna__optuna
optuna/storages/_rdb/alembic/versions/v2.4.0.a.py
{ "start": 2070, "end": 6407 }
class ____(BaseModel): __tablename__ = "trial_intermediate_values" __table_args__: Any = (UniqueConstraint("trial_id", "step"),) trial_intermediate_value_id = Column(Integer, primary_key=True) trial_id = Column(Integer, ForeignKey("trials.trial_id"), nullable=False) step = Column(Integer, nullable=F...
TrialIntermediateValueModel
python
pandas-dev__pandas
pandas/tests/indexes/test_any_index.py
{ "start": 4842, "end": 5041 }
class ____: def test_str(self, index): # test the string repr index.name = "foo" assert "'foo'" in str(index) assert type(index).__name__ in str(index)
TestRendering
python
mlflow__mlflow
tests/tracing/test_fluent.py
{ "start": 1362, "end": 1793 }
class ____: @mlflow.trace() def predict(self, x, y): z = x + y z = self.add_one(z) z = mlflow.trace(self.square)(z) return z # noqa: RET504 @mlflow.trace(span_type=SpanType.LLM, name="add_one_with_custom_name", attributes={"delta": 1}) def add_one(self, z): retu...
DefaultTestModel
python
ray-project__ray
python/ray/tune/examples/cifar10_pytorch.py
{ "start": 1623, "end": 9332 }
class ____(nn.Module): def __init__(self, l1=120, l2=84): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, l1) self.fc2 = nn.Linear(l1, l2) self.fc3 = n...
Net
python
wandb__wandb
wandb/vendor/pygments/lexers/pascal.py
{ "start": 666, "end": 26923 }
class ____(Lexer): """ For `Delphi <http://www.borland.com/delphi/>`_ (Borland Object Pascal), Turbo Pascal and Free Pascal source code. Additional options accepted: `turbopascal` Highlight Turbo Pascal specific keywords (default: ``True``). `delphi` Highlight Borland Delphi sp...
DelphiLexer
python
numpy__numpy
numpy/testing/tests/test_utils.py
{ "start": 1956, "end": 11302 }
class ____(_GenericTest): def _assert_func(self, *args, **kwargs): assert_array_equal(*args, **kwargs) def test_generic_rank1(self): """Test rank 1 array for all dtypes.""" def foo(t): a = np.empty(2, t) a.fill(1) b = a.copy() c = a.copy(...
TestArrayEqual
python
huggingface__transformers
src/transformers/models/pvt/modeling_pvt.py
{ "start": 13963, "end": 17787 }
class ____(nn.Module): def __init__(self, config: PvtConfig): super().__init__() self.config = config # stochastic depth decay rule drop_path_decays = torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").tolist() # patch embeddings embeddings =...
PvtEncoder
python
scipy__scipy
benchmarks/benchmarks/integrate.py
{ "start": 3504, "end": 3878 }
class ____(Benchmark): def setup(self) -> None: x, self.dx = np.linspace(0, 5, 1000, retstep=True) self.y = np.sin(2*np.pi*x) self.y2 = np.tile(self.y, (100, 100, 1)) def time_1d(self) -> None: cumulative_simpson(self.y, dx=self.dx) def time_multid(self) -> None: c...
CumulativeSimpson
python
doocs__leetcode
solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/Solution.py
{ "start": 0, "end": 267 }
class ____: def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int: cnt = Counter() for row in matrix: t = tuple(row) if row[0] == 0 else tuple(x ^ 1 for x in row) cnt[t] += 1 return max(cnt.values())
Solution
python
catalyst-team__catalyst
catalyst/metrics/_segmentation.py
{ "start": 18063, "end": 23214 }
class ____(RegionBasedMetric): """ Trevsky Metric, trevsky score = tp / (tp + fp * beta + fn * alpha) Args: alpha: false negative coefficient, bigger alpha bigger penalty for false negative. if beta is None, alpha must be in (0, 1) beta: false positive coefficient, bigger al...
TrevskyMetric
python
kamyu104__LeetCode-Solutions
Python/maximum-69-number.py
{ "start": 32, "end": 387 }
class ____(object): def maximum69Number (self, num): """ :type num: int :rtype: int """ curr, base, change = num, 3, 0 while curr: if curr%10 == 6: change = base base *= 10 curr //= 10 return num+change # T...
Solution
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 4348, "end": 5770 }
class ____: pass @pytest.mark.parametrize( "typ,coll_type", [ (_Set[Elem], set), (_FrozenSet[Elem], frozenset), (_Dict[Elem, None], dict), (set[Elem], set), (frozenset[Elem], frozenset), # (dict[Elem, None], dict), # FIXME this should work (typing.D...
Elem
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 205544, "end": 205899 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "repository") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") repository = sgqlc.types.Field("Repository", graphql_name="...
ArchiveRepositoryPayload
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 3809, "end": 3899 }
class ____(Proto_ContraSelf): def m(self, x: Self) -> None: ...
Impl_ContraSelfExplicit2
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/selection.py
{ "start": 1941, "end": 2674 }
class ____(Expr): __slots__ = () _non_child = ("dtype",) def __init__(self, dtype: DataType, values: Expr, indices: Expr): self.dtype = dtype self.children = (values, indices) self.is_pointwise = False def do_evaluate( self, df: DataFrame, *, context: ExecutionContext =...
Filter
python
RaRe-Technologies__gensim
gensim/test/test_text_analysis.py
{ "start": 4952, "end": 5075 }
class ____(BaseTestCases.TextAnalyzerTestBase): accumulator_cls = WordOccurrenceAccumulator
TestWordOccurrenceAccumulator
python
PyCQA__flake8
src/flake8/exceptions.py
{ "start": 345, "end": 980 }
class ____(Flake8Exception): """Exception raised when a plugin fails to load.""" FORMAT = 'Flake8 failed to load plugin "%(name)s" due to %(exc)s.' def __init__(self, plugin_name: str, exception: Exception) -> None: """Initialize our FailedToLoadPlugin exception.""" self.plugin_name = plug...
FailedToLoadPlugin
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 21844, "end": 21962 }
class ____(BaseModel, extra="forbid"): create_alias: "CreateAlias" = Field(..., description="")
CreateAliasOperation
python
gevent__gevent
src/gevent/tests/test__order.py
{ "start": 704, "end": 742 }
class ____(Test): count = 1000
TestM
python
pytorch__pytorch
test/inductor/test_fxir_backend.py
{ "start": 27649, "end": 40917 }
class ____(InductorTestCase): device = GPU_TYPE def check( self, model, inp, dynamic_shapes=None, strict=False ) -> torch.fx.GraphModule: with torch.no_grad(): ep = torch.export.export( model, inp, dynamic_shapes=dynamic_shapes, strict=strict ) ...
AOTFxirTestCase
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/graph_provides_config.py
{ "start": 23, "end": 144 }
class ____(dg.Config): n: float @dg.op def add_n(config: AddNConfig, number): return number + config.n
AddNConfig
python
gevent__gevent
src/gevent/tests/test__signal.py
{ "start": 285, "end": 3813 }
class ____(greentest.TestCase): error_fatal = False __timeout__ = greentest.LARGE_TIMEOUT def test_handler(self): with self.assertRaises(TypeError): gevent.signal_handler(signal.SIGALRM, 1) def test_alarm(self): sig = gevent.signal_handler(signal.SIGALRM, raise_Expected) ...
TestSignal
python
bokeh__bokeh
src/bokeh/models/widgets/inputs.py
{ "start": 9630, "end": 10038 }
class ____(Widget): """ Base class for toggleable (boolean) input widgets. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) active = Bool(default=False, help=""" The state of the widget. """) ...
ToggleInput
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/string.py
{ "start": 986, "end": 1259 }
class ____(TypedDict): """ Configuration for a fixed-length string data type in Zarr V3. Attributes ---------- length_bytes : int The length in bytes of the data associated with this configuration. """ length_bytes: int
LengthBytesConfig
python
doocs__leetcode
lcof2/剑指 Offer II 115. 重建序列/Solution.py
{ "start": 0, "end": 633 }
class ____: def sequenceReconstruction( self, nums: List[int], sequences: List[List[int]] ) -> bool: n = len(nums) g = [[] for _ in range(n)] indeg = [0] * n for seq in sequences: for a, b in pairwise(seq): a, b = a - 1, b - 1 g...
Solution
python
getsentry__sentry
src/sentry/sentry_metrics/consumers/indexer/parallel.py
{ "start": 1297, "end": 2751 }
class ____(ProcessingStep[Union[FilteredPayload, IndexerOutputMessageBatch]]): def __init__( self, next_step: ProcessingStep[KafkaPayload | RoutingPayload | InvalidMessage | FilteredPayload], ) -> None: self.__next_step = next_step self.__closed = False self.__messages: D...
Unbatcher
python
Netflix__metaflow
metaflow/_vendor/click/exceptions.py
{ "start": 284, "end": 1076 }
class ____(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception exit_code = 1 def __init__(self, message): ctor_msg = message if PY2: if ctor_msg is not None: ctor_msg = ctor_msg.encode("utf-8") ...
ClickException
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_util.py
{ "start": 1071, "end": 1866 }
class ____(enum.Enum): """Cross device communication implementation. Warning: The alias `tf.distribute.experimental.CollectiveCommunication` is deprecated and will be removed in a future version. Use `tf.distribute.experimental.CommunicationImplementation` instead. * `AUTO`: Automatically chosen by Tensorfl...
CommunicationImplementation
python
django__django
tests/composite_pk/test_order_by.py
{ "start": 109, "end": 2372 }
class ____(TestCase): maxDiff = None @classmethod def setUpTestData(cls): cls.tenant_1 = Tenant.objects.create() cls.tenant_2 = Tenant.objects.create() cls.tenant_3 = Tenant.objects.create() cls.user_1 = User.objects.create( tenant=cls.tenant_1, id=1,...
CompositePKOrderByTests
python
doocs__leetcode
solution/1500-1599/1547.Minimum Cost to Cut a Stick/Solution2.py
{ "start": 0, "end": 436 }
class ____: def minCost(self, n: int, cuts: List[int]) -> int: cuts.extend([0, n]) cuts.sort() m = len(cuts) f = [[0] * m for _ in range(m)] for i in range(m - 1, -1, -1): for j in range(i + 2, m): f[i][j] = inf for k in range(i + 1...
Solution
python
openai__openai-python
src/openai/resources/responses/responses.py
{ "start": 158207, "end": 160326 }
class ____: def __init__(self, responses: AsyncResponses) -> None: self._responses = responses self.create = async_to_streamed_response_wrapper( responses.create, ) self.retrieve = async_to_streamed_response_wrapper( responses.retrieve, ) self...
AsyncResponsesWithStreamingResponse
python
ansible__ansible
test/lib/ansible_test/_internal/completion.py
{ "start": 3117, "end": 4105 }
class ____(CompletionConfig): """Base class for completion configuration of remote environments provisioned through Ansible Core CI.""" provider: t.Optional[str] = None arch: t.Optional[str] = None @property def platform(self) -> str: """The name of the platform.""" return self.nam...
RemoteCompletionConfig
python
sphinx-doc__sphinx
tests/roots/test-ext-coverage/grog/coverage_missing.py
{ "start": 53, "end": 165 }
class ____: """An undocumented class.""" def missing_a(self): """An undocumented method."""
Missing
python
numba__numba
numba/cuda/tests/cudapy/test_frexp_ldexp.py
{ "start": 315, "end": 2024 }
class ____(CUDATestCase): def template_test_frexp(self, nptype, nbtype): compiled = cuda.jit(void(nbtype[:], int32[:], nbtype))(simple_frexp) arg = 3.1415 aryx = np.zeros(1, dtype=nptype) aryexp = np.zeros(1, dtype=np.int32) compiled[1, 1](aryx, aryexp, arg) np.testin...
TestCudaFrexpLdexp
python
huggingface__transformers
src/transformers/models/markuplm/modeling_markuplm.py
{ "start": 10214, "end": 10881 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden stat...
MarkupLMPooler
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock.py
{ "start": 6185, "end": 7583 }
class ____(TestBedrockCustomWaitersBase): WAITER_NAME = "batch_inference_scheduled" SENSOR = BedrockBatchInferenceSensor( task_id="task_id", job_arn="job_arn", success_state=BedrockBatchInferenceSensor.SuccessState.SCHEDULED, ) @pytest.fixture def mock_get_job(self): ...
TestBatchInferenceScheduledWaiter
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/event/base.py
{ "start": 12187, "end": 13914 }
class ____(_HasEventsDispatch[_ET]): """Define event listening functions for a particular target type.""" @classmethod def _accept_with( cls, target: Union[_ET, Type[_ET]], identifier: str ) -> Optional[Union[_ET, Type[_ET]]]: def dispatch_is(*types: Type[Any]) -> bool: retu...
Events
python
apache__airflow
providers/ftp/src/airflow/providers/ftp/hooks/ftp.py
{ "start": 1047, "end": 9857 }
class ____(BaseHook): """ Interact with FTP. Errors that may occur throughout but should be handled downstream. You can specify mode for data transfers in the extra field of your connection as ``{"passive": "true"}``. You can also specify encoding for the FTP connection as ``{"encoding": "cp125...
FTPHook
python
huggingface__transformers
src/transformers/models/bert_generation/modeling_bert_generation.py
{ "start": 12542, "end": 13252 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forwa...
BertGenerationOutput
python
matplotlib__matplotlib
lib/matplotlib/colors.py
{ "start": 80071, "end": 82001 }
class ____(BivarColormap): """ BivarColormap object generated by supersampling a regular grid. Parameters ---------- patch : np.array Patch is required to have a shape (k, l, 3), and will get supersampled to a lut of shape (N, N, 4). N : int The number of RGB quantizatio...
SegmentedBivarColormap
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed8.py
{ "start": 273, "end": 773 }
class ____(TypedDict, extra_items="str | int | Typed | Named"): name: str td2_1: Named = { "name": "Fred", "birth": { "type": "date", "year": 2000, "month": 12, "day": 31, }, } td2_2: Named = { "name": "Fred", "extra": { "name": "test", "value":...
Named
python
pypa__warehouse
tests/conftest.py
{ "start": 21830, "end": 23598 }
class ____(_webtest.TestApp): def xmlrpc(self, path, method, *args): body = xmlrpc.client.dumps(args, methodname=method) resp = self.post(path, body, headers={"Content-Type": "text/xml"}) return xmlrpc.client.loads(resp.body) @pytest.fixture def tm(): # Create a new transaction manager...
_TestApp
python
getsentry__sentry
tests/sentry/integrations/bitbucket/test_repository.py
{ "start": 564, "end": 5865 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.base_url = "https://api.bitbucket.org" self.shared_secret = "234567890" self.subject = "connect:1234567" self.integration, _ = self.create_provider_integration_for( self.organization, ...
BitbucketRepositoryProviderTest
python
donnemartin__interactive-coding-challenges
graphs_trees/graph_shortest_path/test_shortest_path.py
{ "start": 18, "end": 1321 }
class ____(unittest.TestCase): def test_shortest_path(self): graph = Graph() graph.add_edge('a', 'b', weight=5) graph.add_edge('a', 'c', weight=3) graph.add_edge('a', 'e', weight=2) graph.add_edge('b', 'd', weight=2) graph.add_edge('c', 'b', weight=1) graph.a...
TestShortestPath
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 70885, "end": 71396 }
class ____(torch.nn.Module): def __init__(self, with_bn=True): super().__init__() self.linear = nn.Linear(5, 5) self.bn1d = nn.BatchNorm1d(5) self.leaky_relu = nn.LeakyReLU(0.01) self.with_bn = with_bn def forward(self, x): x = self.linear(x) if self.with...
LinearBnLeakyReluModel
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 17275, "end": 17631 }
class ____(_HTTPMove): """ subclass of :class:`~_HTTPMove` This indicates that the requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. code: 301, title: Moved Permanently """ code = 301 title = 'M...
HTTPMovedPermanently
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 23819, "end": 25182 }
class ____: @mock.patch( "airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook", **{"return_value.get_entry.return_value": TEST_ENTRY}, ) def test_assert_valid_hook_call(self, mock_hook) -> None: with pytest.warns(AirflowProviderDeprecationWarning): t...
TestCloudDataCatalogGetEntryOperator
python
huggingface__transformers
tests/models/llava_next_video/test_processing_llava_next_video.py
{ "start": 958, "end": 5127 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = LlavaNextVideoProcessor @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") tokenizer = tokenizer_class.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf") ...
LlavaNextVideoProcessorTest
python
tensorflow__tensorflow
tensorflow/python/keras/engine/keras_tensor.py
{ "start": 18032, "end": 20845 }
class ____(KerasTensor): """A specialized KerasTensor representation for `tf.RaggedTensor`s. Specifically, it: 1. Specializes the conversion to a placeholder in order to maintain shape information for non-ragged dimensions. 2. Overloads the KerasTensor's operators with the RaggedTensor versions when they ...
RaggedKerasTensor
python
PrefectHQ__prefect
tests/server/models/test_filters.py
{ "start": 22211, "end": 27808 }
class ____: params = [ [{}, 10], [dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1", "f-2"]))), 6], [dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1", "f-100"]))), 3], [dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1"]))), 3], [dict(flow_filter=filte...
TestCountTaskRunsModels
python
ipython__ipython
IPython/lib/pretty.py
{ "start": 14965, "end": 15057 }
class ____: def output(self, stream, output_width): return output_width
Printable
python
ray-project__ray
doc/external/test_hashes.py
{ "start": 152, "end": 1304 }
class ____(TypedDict): file: str digest: str ref: str # Files here are referenced on external pages as examples, and are tested # to make sure exteranl referenced Ray examples are working with latest version # of Ray. If you need to make changes, make sure to update the external examples # too, and then u...
ExternalDoc
python
getsentry__sentry
src/sentry/api/serializers/models/event.py
{ "start": 21034, "end": 23552 }
class ____(EventSerializer): """ Simple event serializer that renders a basic outline of an event without most interfaces/breadcrumbs. This can be used for basic event list queries where we don't need the full detail. The side effect is that, if the serialized events are actually SnubaEvents, we can...
SimpleEventSerializer
python
pyca__cryptography
tests/hazmat/primitives/test_hkdf.py
{ "start": 527, "end": 5834 }
class ____: def test_overflow_protection_enormous_digest_size(self, backend): enormous_digest_size = sys.maxsize >> 3 dummy_hash = DummyHashAlgorithm(enormous_digest_size) with pytest.raises( ValueError, match="Digest size too large, would cause overflow" ): ...
TestHKDF
python
python-openxml__python-docx
tests/text/test_paragraph.py
{ "start": 593, "end": 14793 }
class ____: """Unit-test suite for `docx.text.run.Paragraph`.""" @pytest.mark.parametrize( ("p_cxml", "expected_value"), [ ("w:p/w:r", False), ('w:p/w:r/w:t"foobar"', False), ('w:p/w:hyperlink/w:r/(w:t"abc",w:lastRenderedPageBreak,w:t"def")', True), ...
DescribeParagraph
python
skorch-dev__skorch
skorch/hf.py
{ "start": 22855, "end": 29739 }
class ____(_HuggingfaceTokenizerBase): """Wraps a pretrained Huggingface tokenizer to work as an sklearn transformer From the `tokenizers docs <https://huggingface.co/docs/tokenizers/python/latest/index.html>`_: :: 🤗 Tokenizers provides an implementation of today’s most used toke...
HuggingfacePretrainedTokenizer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictReadOnly1.py
{ "start": 637, "end": 746 }
class ____(TypedDict): a: Required[int] b: ReadOnly[NotRequired[int]] c: ReadOnly[Required[int]]
F1
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 34365, "end": 39193 }
class ____: def test_airy(self): # This tests the airy function to ensure 8 place accuracy in computation x = special.airy(.99) assert_allclose(x, array([0.13689066, -0.16050153, 1.19815925, 0.92046818]), atol=1.5e-8, rtol=0) x = special.airy(.41) ass...
TestAiry
python
pytorch__pytorch
test/test_mps.py
{ "start": 24038, "end": 26432 }
class ____(TestCaseMPS): def _npRelu(self, np_features): return np.maximum(np_features, np.zeros(np_features.shape)).astype(np_features.dtype) def testNpRelu(self): torch.testing.assert_close( np.array([[0., 0.7, 0.0, 0.3, 0.0], [0.1, 0.0, 0.5, 0.0, 0.9]]), self._npRelu(...
MPSReluTest
python
falconry__falcon
examples/things_advanced.py
{ "start": 2134, "end": 2749 }
class ____: def process_request(self, req, resp): if not req.client_accepts_json: raise falcon.HTTPNotAcceptable( description='This API only supports responses encoded as JSON.', href='http://docs.examples.com/api/json', ) if req.method in ('P...
RequireJSON
python
pypa__pipenv
pipenv/patched/pip/_internal/utils/temp_dir.py
{ "start": 998, "end": 2086 }
class ____: """Manages temp directory behavior""" def __init__(self) -> None: self._should_delete: Dict[str, bool] = {} def set_delete(self, kind: str, value: bool) -> None: """Indicate whether a TempDirectory of the given kind should be auto-deleted. """ self._shou...
TempDirectoryTypeRegistry
python
pydata__xarray
asv_bench/benchmarks/rolling.py
{ "start": 3486, "end": 4352 }
class ____(RollingMemory): @parameterized(["func", "use_bottleneck"], (["sum", "max", "mean"], [True, False])) def peakmem_ndrolling_reduce(self, func, use_bottleneck): with xr.set_options(use_bottleneck=use_bottleneck): roll = self.ds.var1.rolling(x=10, y=4) getattr(roll, func)(...
DataArrayRollingMemory
python
great-expectations__great_expectations
tests/integration/data_sources_and_expectations/expectations/test_expect_column_values_to_be_between.py
{ "start": 6880, "end": 13735 }
class ____: # expect a standard error message, but exclude the column type string, which is backend specific EXPECTED_ERROR = "ColumnValuesBetween metrics cannot be computed on column of type" @parameterize_batch_for_data_sources( data_source_configs=SQL_DATA_SOURCES, data=DATA, ) d...
TestColumnValuesBetweenAgainstInvalidColumn
python
sphinx-doc__sphinx
sphinx/builders/_epub_base.py
{ "start": 2322, "end": 2391 }
class ____(NamedTuple): type: str title: str uri: str
Guide
python
python__mypy
mypy/test/teststubgen.py
{ "start": 33072, "end": 57376 }
class ____(unittest.TestCase): """Unit tests for stub generation from C modules using introspection. Note that these don't cover a lot! """ def test_infer_hash_sig(self) -> None: assert_equal(infer_c_method_args("__hash__"), [self_arg]) assert_equal(infer_method_ret_type("__hash__"), "...
StubgencSuite
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 12705, "end": 12775 }
class ____(FirstLevelInheritedModel): pass
SecondLevelInheritedModel
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 204426, "end": 216169 }
class ____(sparse_test_class(getset=False, slicing=False, slicing_assign=False, fancy_indexing=False, fancy_assign=False, nnz_axis=False)): spcreator = bsr_array math_dtypes = [np.int_, np.float64, np.complex128] ...
TestBSR
python
ansible__ansible
lib/ansible/module_utils/facts/timeout.py
{ "start": 887, "end": 2453 }
class ____(Exception): pass def timeout(seconds=None, error_message="Timer expired"): """ Timeout decorator to expire after a set number of seconds. This raises an ansible.module_utils.facts.TimeoutError if the timeout is hit before the function completes. """ def decorator(func): ...
TimeoutError
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/repository/github_client.py
{ "start": 3875, "end": 4735 }
class ____(Protocol): def get_all_endpoints(self) -> Dict[str, str]: ... async def request( self, endpoint: str, method: str, headers: Dict[str, Any] = {}, **kwargs: Any, ) -> Any: ... async def get_tree( self, owner: str, repo: str, ...
BaseGithubClient
python
PyCQA__pylint
tests/functional/e/enum_subclasses.py
{ "start": 773, "end": 827 }
class ____(OrderedEnum): red = 0 green = 1
Color
python
streamlit__streamlit
lib/tests/streamlit/elements/echo_test.py
{ "start": 2826, "end": 4288 }
class ____: def do_x(self): pass def do_y(self): pass""" element = self.get_delta_from_queue(echo_index).new_element assert echo_str == element.code.code_text element = self.get_delta_from_queue(output_index).new_element assert element.markdown.body == "Hello" ...
MyClass
python
pytorch__pytorch
test/inductor/test_minifier_isolate.py
{ "start": 524, "end": 1998 }
class ____(MinifierTestBase): def _test_after_aot_runtime_error(self, device, expected_error): run_code = f"""\ @torch.compile() def inner(x): x = torch.relu(x) x = torch.cos(x) return x inner(torch.randn(2, 2).to("{device}")) """ # These must isolate because they crash the process ...
MinifierIsolateTests
python
py-pdf__pypdf
pypdf/generic/_appearance_stream.py
{ "start": 584, "end": 749 }
class ____(IntEnum): """Defines the alignment options for text within a form field's appearance stream.""" LEFT = 0 CENTER = 1 RIGHT = 2
TextAlignment
python
django-compressor__django-compressor
compressor/filters/template.py
{ "start": 124, "end": 370 }
class ____(FilterBase): def input(self, filename=None, basename=None, **kwargs): template = Template(self.content) context = Context(settings.COMPRESS_TEMPLATE_FILTER_CONTEXT) return template.render(context)
TemplateFilter
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1018407, "end": 1018945 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "from_repository", "issue") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(Da...
TransferredEvent
python
ray-project__ray
python/ray/tune/utils/util.py
{ "start": 903, "end": 4352 }
class ____(Thread): """Class for system usage utilization monitoring. It keeps track of CPU, RAM, GPU, VRAM usage (each gpu separately) by pinging for information every x seconds in a separate thread. Requires psutil and GPUtil to be installed. Can be enabled with Tuner(param_space={"log_sys_usage...
UtilMonitor
python
kamyu104__LeetCode-Solutions
Python/right-triangles.py
{ "start": 689, "end": 1170 }
class ____(object): def numberOfRightTriangles(self, grid): """ :type grid: List[List[int]] :rtype: int """ n, m = len(grid), len(grid[0]) cnt1 = [sum(grid[i][j] for j in xrange(m)) for i in xrange(n)] cnt2 = [sum(grid[i][j] for i in xrange(n)) for j in xrange...
Solution2
python
pydantic__pydantic
pydantic/experimental/pipeline.py
{ "start": 2245, "end": 2483 }
class ____: constraint: _ConstraintAnnotation _Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint] _InT = TypeVar('_InT') _OutT = TypeVar('_OutT') _NewOutT = TypeVar('_NewOutT')
_Constraint
python
milvus-io__pymilvus
pymilvus/settings.py
{ "start": 1104, "end": 1341 }
class ____: def format_col(self, message_str: str, level_name: str): if level_name in COLORS: message_str = COLORS.get(level_name) + message_str + COLORS.get("ENDC") return message_str
ColorFulFormatColMixin
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F401_14.py
{ "start": 136, "end": 193 }
class ____: datetime: "Optional[datetime.datetime]"
Class
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/shaders.py
{ "start": 10848, "end": 10972 }
class ____(Shader): def __init__(self, code): Shader.__init__(self, GL.GL_VERTEX_SHADER, code)
VertexShader
python
celery__celery
t/unit/backends/test_redis.py
{ "start": 12661, "end": 12720 }
class ____(CredentialProvider): pass
MyCredentialProvider
python
getsentry__sentry
src/bitfield/models.py
{ "start": 2251, "end": 5323 }
class ____(BigIntegerField): def contribute_to_class(self, cls: type[Model], name: str, private_only: bool = False) -> None: super().contribute_to_class(cls, name, private_only=private_only) setattr(cls, self.name, BitFieldCreator(self)) def __init__(self, flags, default=None, *args, **kwargs):...
BitField
python
numba__numba
numba/core/typing/builtins.py
{ "start": 30147, "end": 31128 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws if len(args) == 1: [arg] = args if arg not in types.number_domain: raise errors.NumbaTypeError("complex() only support for numbers") if arg == types.float32: ...
Complex
python
ray-project__ray
python/ray/tests/unit/test_runtime_env_validation.py
{ "start": 16956, "end": 19930 }
class ____: def test_validate_pip_invalid_types(self): with pytest.raises(TypeError): validation.parse_and_validate_pip(1) with pytest.raises(TypeError): validation.parse_and_validate_pip(True) def test_validate_pip_invalid_path(self): with pytest.raises(ValueEr...
TestValidatePip
python
ipython__ipython
IPython/core/magics/code.py
{ "start": 1573, "end": 5112 }
class ____(ValueError): pass ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$") # To match, e.g. 8-10 1:5 :10 3- range_re = re.compile(r""" (?P<start>\d+)? ((?P<sep>[\-:]) (?P<end>\d+)?)? $""", re.VERBOSE) def extract_code_ranges(ranges_str): """Turn a string of range for %%load into 2-tuples...
MacroToEdit
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_response_format.py
{ "start": 1165, "end": 1262 }
class ____: """Weather response.""" temperature: float condition: str
WeatherDataclass
python
instagram__MonkeyType
monkeytype/tracing.py
{ "start": 627, "end": 2510 }
class ____: """CallTrace contains the types observed during a single invocation of a function""" def __init__( self, func: Callable[..., Any], arg_types: Dict[str, type], return_type: Optional[type] = None, yield_type: Optional[type] = None, ) -> None: """ ...
CallTrace
python
huggingface__transformers
tests/models/bert_japanese/test_tokenization_bert_japanese.py
{ "start": 14323, "end": 17885 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "cl-tohoku/bert-base-japanese" tokenizer_class = BertJapaneseTokenizer test_rust_tokenizer = False @classmethod def setUpClass(cls): super().setUpClass() # Create a separate temp directory for the vocab file ...
BertJapaneseCharacterTokenizationTest
python
Pylons__pyramid
src/pyramid/url.py
{ "start": 1516, "end": 36622 }
class ____: """Request methods mixin for BaseRequest having to do with URL generation""" def _partial_application_url(self, scheme=None, host=None, port=None): """ Construct the URL defined by request.application_url, replacing any of the default scheme, host, or port portions with ...
URLMethodsMixin
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 8707, "end": 11611 }
class ____(str, Enum): """ * `CREATING`: Indicates that the cluster is being created. * `DID_NOT_EXPAND_DISK`: Indicates that a disk is low on space, but adding disks would put it over the max capacity. * `EXPANDED_DISK`: Indicates that a disk was low on space and the disks were expanded. * `FAI...
ClusterEventType
python
ray-project__ray
release/llm_tests/serve/test_llm_serve_integration.py
{ "start": 6623, "end": 8791 }
class ____: """Tests for remote code model loading behavior.""" @pytest.mark.parametrize("remote_model_app", [False], indirect=True) def test_remote_code_failure(self, remote_model_app): """ Tests that a remote code model fails to load when trust_remote_code=False. If it loads succ...
TestRemoteCode
python
apache__avro
lang/py/avro/errors.py
{ "start": 3874, "end": 3996 }
class ____(NotImplementedError, AvroException): """Raised when the compression named cannot be used."""
UnsupportedCodec
python
google__python-fire
fire/test_components.py
{ "start": 6588, "end": 6752 }
class ____(NamedTuplePoint): """Used for verifying subclasses of namedtuples behave as intended.""" def coordinate_sum(self): return self.x + self.y
SubPoint
python
spyder-ide__spyder
spyder/plugins/help/plugin.py
{ "start": 744, "end": 849 }
class ____: # Documentation related ShowSpyderTutorialAction = "spyder_tutorial_action"
HelpActions
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/integration/test_videos.py
{ "start": 2588, "end": 8279 }
class ____(TestCase): @staticmethod def _read(config_: ConfigBuilder, expecting_exception: bool = False, json_schema: Optional[Dict[str, any]] = None) -> EntrypointOutput: return read_output( config_builder=config_, stream_name=_STREAM_NAME, sync_mode=SyncMode.full_re...
TestFullRefresh
python
apache__airflow
scripts/in_container/verify_providers.py
{ "start": 1948, "end": 2082 }
class ____(NamedTuple): entities: list[str] new_entities_table: str wrong_entities: list[tuple[type, str]]
EntityTypeSummary
python
google__pytype
pytype/blocks/blocks_test.py
{ "start": 9126, "end": 14666 }
class ____(BaseBlocksTest): """Test the add_pop_block_targets function.""" def assertTargets(self, code, targets): co = self.make_code(code) bytecode = opcodes.dis(co) blocks.add_pop_block_targets(bytecode) for i in range(len(bytecode)): op = bytecode[i] actual_target = op.target ...
BlockStackTest