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
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_details.py
{ "start": 62, "end": 5266 }
class ____(util.MdCase): """Test Blocks details cases.""" extension = ['pymdownx.blocks.details'] extension_configs = { 'pymdownx.blocks.details': { 'types': [ 'custom', {'name': 'custom2'}, {'name': 'custom3', 'class': 'different'}, ...
TestBlocksDetails
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 32743, "end": 41795 }
class ____(WhooshTestCase): def setUp(self): super().setUp() # Stow. self.old_ui = connections["whoosh"].get_unified_index() self.ui = UnifiedIndex() self.wmmi = WhooshMockSearchIndex() self.ui.build(indexes=[self.wmmi]) self.sb = connections["whoosh"].get_ba...
LiveWhooshSearchQuerySetTestCase
python
plotly__plotly.py
plotly/graph_objs/contour/_stream.py
{ "start": 233, "end": 3511 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "contour" _path_str = "contour.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50...
Stream
python
networkx__networkx
benchmarks/benchmarks/benchmark_neighbors.py
{ "start": 178, "end": 1193 }
class ____: param_names = ["num_nodes"] params = [10, 100, 1000] def setup(self, num_nodes): self.star_graph = nx.star_graph(num_nodes) self.complete_graph = nx.complete_graph(num_nodes) self.path_graph = nx.path_graph(num_nodes) def time_star_center(self, num_nodes): s...
NonNeighbors
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/cloud_formation.py
{ "start": 1250, "end": 3030 }
class ____(AwsBaseSensor[CloudFormationHook]): """ Waits for a stack to be created successfully on AWS CloudFormation. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:CloudFormationCreateStackSensor` :param stack_name: The name ...
CloudFormationCreateStackSensor
python
pytorch__pytorch
torch/fx/graph.py
{ "start": 7180, "end": 7970 }
class ____: """ Represents all the information necessary to exec or save a graph as Python code. """ # Python source code for the forward function definition. src: str # Values in global scope during execution of `src_def`. globals: dict[str, Any] # Optional mapping from the forward fun...
PythonCode
python
keras-team__keras
keras/src/initializers/random_initializers.py
{ "start": 17358, "end": 18769 }
class ____(VarianceScaling): """He normal initializer. It draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Examples: >>> # Standalone usage: >>> initializer = HeNormal() ...
HeNormal
python
modin-project__modin
modin/core/io/column_stores/column_store_dispatcher.py
{ "start": 1316, "end": 8699 }
class ____(FileDispatcher): """ Class handles utils for reading columnar store format files. Inherits some util functions for processing files from `FileDispatcher` class. """ @classmethod def call_deploy(cls, fname, col_partitions, **kwargs): """ Deploy remote tasks to the wor...
ColumnStoreDispatcher
python
langchain-ai__langchain
libs/core/langchain_core/prompts/chat.py
{ "start": 1299, "end": 6446 }
class ____(BaseMessagePromptTemplate): """Prompt template that assumes variable is already list of messages. A placeholder which can be used to pass in a list of messages. Direct usage: ```python from langchain_core.prompts import MessagesPlaceholder prompt = MessagesPlaceholder(...
MessagesPlaceholder
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/users/main.py
{ "start": 788, "end": 1413 }
class ____(webapp2.RequestHandler): def get(self): # [START gae_users_get_details] user = users.get_current_user() if user: nickname = user.nickname() logout_url = users.create_logout_url("/") greeting = 'Welcome, {}! (<a href="{}">sign out</a>)'.format( ...
MainPage
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 18073, "end": 18130 }
class ____(BaseInheritTracking2): pass
InheritTracking2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-python-http-tutorial/source_python_http_tutorial/source.py
{ "start": 355, "end": 4012 }
class ____(HttpStream): url_base = "https://api.apilayer.com/exchangerates_data/" cursor_field = "date" primary_key = "date" def __init__(self, config: Mapping[str, Any], start_date: datetime, **kwargs): super().__init__() self.base = config["base"] self.access_key = config["acc...
ExchangeRates
python
ray-project__ray
release/ray_release/exception.py
{ "start": 3156, "end": 3239 }
class ____(ReleaseTestError): exit_code = ExitCode.COMMAND_TIMEOUT
CommandTimeout
python
ansible__ansible
lib/ansible/module_utils/facts/network/darwin.py
{ "start": 1853, "end": 1958 }
class ____(NetworkCollector): _fact_class = DarwinNetwork _platform = 'Darwin'
DarwinNetworkCollector
python
great-expectations__great_expectations
contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_have_elevation.py
{ "start": 1894, "end": 4713 }
class ____(ColumnMapExpectation): """Expect the column values to be points that have elevation.""" # These examples will be shown in the public gallery, and also executed as unit tests for your Expectation examples = [ { "data": { "elevated": [ mappin...
ExpectColumnValuesToHaveElevation
python
PyCQA__pylint
doc/data/messages/n/no-member/good.py
{ "start": 60, "end": 128 }
class ____: def meow(self): print("Meow") Cat().meow()
Cat
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/llama_index/packs/code_hierarchy/code_hierarchy.py
{ "start": 6736, "end": 6937 }
class ____(BaseModel): """The output of a chunk_node call.""" this_document: Optional[TextNode] upstream_children_documents: List[TextNode] all_documents: List[TextNode]
_ChunkNodeOutput
python
openai__gym
tests/test_core.py
{ "start": 1692, "end": 1996 }
class ____(core.Env): """This environment doesn't accept any arguments in reset, ideally we want to support this too (for now)""" def __init__(self): pass def reset(self): super().reset() return 0 def step(self, action): return 0, 0, False, {}
OldStyleEnv
python
davidhalter__jedi
jedi/inference/lazy_value.py
{ "start": 803, "end": 1498 }
class ____(AbstractLazyValue): def __init__(self, context, node, min=1, max=1): super().__init__(node, min, max) self.context = context # We need to save the predefined names. It's an unfortunate side effect # that needs to be tracked otherwise results will be wrong. self._pr...
LazyTreeValue
python
huggingface__transformers
src/transformers/models/deepseek_vl/image_processing_deepseek_vl.py
{ "start": 1934, "end": 2232 }
class ____(ImagesKwargs, total=False): r""" min_size (`int`, *optional*, defaults to 14): The minimum allowed size for the resized image. Ensures that neither the height nor width falls below this value after resizing. """ min_size: int
DeepseekVLImageProcessorKwargs
python
has2k1__plotnine
plotnine/geoms/geom_jitter.py
{ "start": 333, "end": 2291 }
class ____(geom_point): """ Scatter plot with points jittered to reduce overplotting {usage} Parameters ---------- {common_parameters} width : float, default=None Proportion to jitter in horizontal direction. The default value is that from [](`~plotnine.positions.po...
geom_jitter
python
protocolbuffers__protobuf
python/google/protobuf/internal/decoder_test.py
{ "start": 771, "end": 4787 }
class ____(parameterized.TestCase): def test_decode_varint_bytes(self): (size, pos) = decoder._DecodeVarint(_INPUT_BYTES, 0) self.assertEqual(size, _EXPECTED[0]) self.assertEqual(pos, 2) (size, pos) = decoder._DecodeVarint(_INPUT_BYTES, 2) self.assertEqual(size, _EXPECTED[1]) self.assertEqua...
DecoderTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 576368, "end": 576805 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "identity_provider") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") identity_provider = sgqlc.types.Field( "Ente...
RegenerateEnterpriseIdentityProviderRecoveryCodesPayload
python
walkccc__LeetCode
solutions/1648. Sell Diminishing-Valued Colored Balls/1648.py
{ "start": 0, "end": 1032 }
class ____: def maxProfit(self, inventory: list[int], orders: int) -> int: MOD = 1_000_000_007 ans = 0 largestCount = 1 def trapezoid(a: int, b: int) -> int: return (a + b) * (a - b + 1) // 2 for a, b in itertools.pairwise(sorted(inventory, reverse=True) + [0]): if a > b: # I...
Solution
python
pandas-dev__pandas
pandas/tests/indexes/multi/test_indexing.py
{ "start": 28824, "end": 29389 }
class ____: def test_where(self): i = MultiIndex.from_tuples([("A", 1), ("A", 2)]) msg = r"\.where is not supported for MultiIndex operations" with pytest.raises(NotImplementedError, match=msg): i.where(True) def test_where_array_like(self, listlike_box): mi = Multi...
TestWhere
python
django__django
tests/forms_tests/widget_tests/test_multiwidget.py
{ "start": 998, "end": 1608 }
class ____(MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( CharField(), MultipleChoiceField(choices=WidgetTest.beatles), SplitDateTimeField(), ) super().__init__( fields, required=required,...
ComplexField
python
pytorch__pytorch
test/inductor/test_alignment.py
{ "start": 943, "end": 8128 }
class ____: def test_unaligned_input(self): def fn(x): return torch.nn.functional.relu(x) x = torch.randn(1024 + 16, device=self.device)[1:-15] # TODO (malfet): Investigate failures on MacOS-14 with ( contextlib.nullcontext() if self.device != "mp...
CommonTemplate
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 2734, "end": 3345 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, template_name="search/indexes/core/mockmodel_template.txt", ) author = indexes.CharField(model_attr="author", weight=2.0) editor = indexes.CharField(model_attr="editor"...
WhooshBoostMockSearchIndex
python
celery__celery
t/unit/utils/test_platforms.py
{ "start": 14454, "end": 16394 }
class ____: @patch('multiprocessing.util._run_after_forkers') @patch('os.fork') @patch('os.setsid') @patch('os._exit') @patch('os.chdir') @patch('os.umask') @patch('os.close') @patch('os.closerange') @patch('os.open') @patch('os.dup2') @patch('celery.platforms.close_open_fds...
test_DaemonContext
python
ionelmc__pytest-benchmark
src/pytest_benchmark/stats.py
{ "start": 253, "end": 4449 }
class ____: fields = ( 'min', 'max', 'mean', 'stddev', 'rounds', 'median', 'iqr', 'q1', 'q3', 'iqr_outliers', 'stddev_outliers', 'outliers', 'ld15iqr', 'hd15iqr', 'ops', 'total', ) ...
Stats
python
spack__spack
lib/spack/spack/util/gpg.py
{ "start": 4656, "end": 12070 }
class ____(spack.error.SpackError): """Class raised when GPG errors are detected.""" @_autoinit def create(**kwargs): """Create a new key pair.""" r, w = os.pipe() with contextlib.closing(os.fdopen(r, "r")) as r: with contextlib.closing(os.fdopen(w, "w")) as w: w.write( ...
SpackGPGError
python
jazzband__django-oauth-toolkit
oauth2_provider/exceptions.py
{ "start": 321, "end": 422 }
class ____(OAuthToolkitError): """ Class for critical errors """ pass
FatalClientError
python
sphinx-doc__sphinx
sphinx/directives/code.py
{ "start": 2991, "end": 6347 }
class ____(SphinxDirective): """Directive for a code block with special highlighting or line numbering settings. """ has_content = True required_arguments = 0 optional_arguments = 1 final_argument_whitespace = False option_spec: ClassVar[OptionSpec] = { 'force': directives.flag,...
CodeBlock
python
getsentry__sentry
tests/sentry/sentry_apps/api/bases/test_sentryapps.py
{ "start": 8661, "end": 9550 }
class ____(TestCase): def setUp(self) -> None: self.endpoint = SentryAppInstallationBaseEndpoint() self.request = drf_request_from_request(self.make_request(user=self.user, method="GET")) self.sentry_app = self.create_sentry_app(name="foo", organization=self.organization) self.insta...
SentryAppInstallationBaseEndpointTest
python
coleifer__peewee
tests/manytomany.py
{ "start": 827, "end": 925 }
class ____(TestModel): name = TextField() CourseStudentDeferred = DeferredThroughModel()
Student
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/reduction_ops_test_big.py
{ "start": 1154, "end": 9690 }
class ____(BaseReductionTest): """Test reductions for sum and boolean all over a wide range of shapes.""" def _tf_reduce_max(self, x, reduction_axes, keepdims): return math_ops.reduce_max(x, reduction_axes, keepdims) def _tf_reduce_all(self, x, reduction_axes, keepdims): return math_ops.reduce_all(x, re...
BigReductionTest
python
doocs__leetcode
solution/3100-3199/3190.Find Minimum Operations to Make All Elements Divisible by Three/Solution.py
{ "start": 0, "end": 118 }
class ____: def minimumOperations(self, nums: List[int]) -> int: return sum(x % 3 != 0 for x in nums)
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_bigquery.py
{ "start": 17776, "end": 21292 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook") def test_execute(self, mock_hook): schema_field_updates = [ { "name": "emp_name", "description": "Name of employee", } ] operator = BigQueryU...
TestBigQueryUpdateTableSchemaOperator
python
pytorch__pytorch
tools/test/test_codegen_model.py
{ "start": 5168, "end": 6790 }
class ____(expecttest.TestCase): def test_single_alias_no_write(self) -> None: a = Annotation.parse("a") self.assertEqual(a.alias_set, tuple("a")) self.assertFalse(a.is_write) self.assertEqual(a.alias_set_after, ()) def test_single_alias_is_write(self) -> None: a = Annot...
TestAnnotation
python
sympy__sympy
sympy/stats/random_matrix_models.py
{ "start": 9846, "end": 15328 }
class ____(CircularEnsembleModel): def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S(4)) def CircularEnsemble(sym, dim): sym, dim = _symbol_converter(sym), _sympify(dim) model = CircularEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) retu...
CircularSymplecticEnsembleModel
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_ops.py
{ "start": 82844, "end": 85399 }
class ____(ControlFlowContext): """Base class for XLA and TPU control flow contexts.""" def __init__(self): super(XLAControlFlowContext, self).__init__() self._name = "XLAControlFlowContext" def to_control_flow_context_def(self, context_def, export_scope=None): # pylint: disable=useless-super-delega...
XLAControlFlowContext
python
getsentry__sentry
src/social_auth/backends/visualstudio.py
{ "start": 1066, "end": 3061 }
class ____(BaseOAuth2): """Slack OAuth authentication mechanism""" AUTHORIZATION_URL = VISUALSTUDIO_AUTHORIZATION_URL ACCESS_TOKEN_URL = VISUALSTUDIO_TOKEN_EXCHANGE_URL AUTH_BACKEND = VisualStudioBackend SETTINGS_KEY_NAME = "VISUALSTUDIO_APP_ID" SETTINGS_SECRET_NAME = "VISUALSTUDIO_APP_SECRET" ...
VisualStudioAuth
python
plotly__plotly.py
plotly/graph_objs/volume/slices/_y.py
{ "start": 233, "end": 5283 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "volume.slices" _path_str = "volume.slices.y" _valid_props = {"fill", "locations", "locationssrc", "show"} @property def fill(self): """ Sets the fill ratio of the `slices`. The default fill value of the `slices` is 1 m...
Y
python
walkccc__LeetCode
solutions/2766. Relocate Marbles/2766.py
{ "start": 0, "end": 281 }
class ____: def relocateMarbles( self, nums: list[int], moveFrom: list[int], moveTo: list[int], ) -> list[int]: numsSet = set(nums) for f, t in zip(moveFrom, moveTo): numsSet.remove(f) numsSet.add(t) return sorted(numsSet)
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType26.py
{ "start": 987, "end": 1311 }
class ____(Generic[T, S]): value: DC1[T] | DC2[S] def method1(self, val: U) -> "ClassC[U, S]": if isinstance(self.value, DC1): # This should generate an error. return ClassC(self.value) else: return ClassC(self.value) T_co = TypeVar("T_co", covariant=True) ...
ClassC
python
xlwings__xlwings
xlwings/pro/reports/markdown.py
{ "start": 555, "end": 1007 }
class ____: def __init__(self, display_name=None): if display_name: self.display_name = display_name else: self.display_name = "" def __repr__(self): s = "" for attribute in vars(self): if getattr(self, attribute) and attribute != "display_nam...
Style
python
openai__openai-python
src/openai/resources/realtime/realtime.py
{ "start": 26182, "end": 28739 }
class ____(BaseRealtimeConnectionResource): def clear(self, *, event_id: str | Omit = omit) -> None: """Send this event to clear the audio bytes in the buffer. The server will respond with an `input_audio_buffer.cleared` event. """ self._connection.send( cast(Rea...
RealtimeInputAudioBufferResource
python
huggingface__transformers
tests/utils/import_structures/import_structure_raw_register.py
{ "start": 686, "end": 799 }
class ____: def __init__(self): pass @requires() def a0(): pass @requires(backends=("torch",))
A0
python
eventlet__eventlet
tests/isolated/patcher_threading_subclass_done.py
{ "start": 32, "end": 876 }
class ____(threading.Thread): EXIT_SENTINEL = object() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.q = queue.Queue(maxsize=-1) self.daemon = True def run(self): while True: task = self.q.get() if task == self.EXIT_SENT...
Worker
python
davidhalter__parso
parso/python/tree.py
{ "start": 4892, "end": 5145 }
class ____(PythonLeaf): """ Simply here to optimize performance. """ __slots__ = () @property def end_pos(self) -> Tuple[int, int]: return self.line, self.column + len(self.value) # Python base classes
_LeafWithoutNewlines
python
getsentry__sentry
tests/sentry/incidents/models/test_incidents.py
{ "start": 1898, "end": 5262 }
class ____(TestCase): def setUp(self) -> None: self.alert_rule = self.create_alert_rule() self.trigger = self.create_alert_rule_trigger(self.alert_rule) def test_negative_cache(self) -> None: subscription = self.alert_rule.snuba_query.subscriptions.get() assert ( cac...
ActiveIncidentClearCacheTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_simple10.py
{ "start": 331, "end": 1095 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("simple01.xlsx") def test_close_file_twice(self): """Test warning when closing workbook more than once.""" workbook = Workbook(self...
TestCompareXLSXFiles
python
facebook__pyre-check
client/configuration/site_packages.py
{ "start": 1281, "end": 1647 }
class ____: name: str path: Path # NOTE: parent of this path would be the site root is_typed: bool = False def to_search_path_element(self) -> search_path.SitePackageElement: return search_path.SitePackageElement( site_root=str(self.path.parent), package_name=self.name ) ...
NonStubPackage
python
numpy__numpy
benchmarks/benchmarks/bench_overrides.py
{ "start": 876, "end": 1786 }
class ____(Benchmark): def setup(self): self.numpy_array = np.array(1) self.numpy_arrays = [np.array(1), np.array(2)] self.many_arrays = 500 * self.numpy_arrays self.duck_array = DuckArray() self.duck_arrays = [DuckArray(), DuckArray()] self.mixed_arrays = [np.array(...
ArrayFunction
python
dask__distributed
distributed/tests/test_actor.py
{ "start": 501, "end": 774 }
class ____: n = 0 def __init__(self): self.n = 0 def increment(self): self.n += 1 return self.n async def ainc(self): self.n += 1 return self.n def add(self, x): self.n += x return self.n
Counter
python
sqlalchemy__sqlalchemy
test/orm/test_relationships.py
{ "start": 47109, "end": 48823 }
class ____(fixtures.MappedTest, AssertsCompiledSQL): __dialect__ = "default" @classmethod def define_tables(cls, metadata): Table( "parent", metadata, Column("x", Integer, primary_key=True), Column("y", Integer, primary_key=True), Column("...
CompositeJoinPartialFK
python
dask__dask
dask/sizeof.py
{ "start": 1403, "end": 8844 }
class ____: """Sentinel class to mark a class to be skipped by the dispatcher. This only works if this sentinel mixin is first in the mro. Examples -------- >>> def _get_gc_overhead(): ... class _CustomObject: ... def __sizeof__(self): ... return 0 ... .....
SimpleSizeof
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 79832, "end": 83513 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[5]", L_y_: "f32[5]"): l_x_ = L_x_ l_y_ = L_y_ x: "f32[5]" = l_x_.sin(); l_x_ = None y: "f32[5]" = l_y_.sin(); l_y_ = None subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgra...
GraphModule
python
sdispater__pendulum
src/pendulum/mixins/default.py
{ "start": 107, "end": 907 }
class ____: _formatter: Formatter = _formatter def format(self, fmt: str, locale: str | None = None) -> str: """ Formats the instance using the given format. :param fmt: The format to use :param locale: The locale to use """ return self._formatter.format(self, f...
FormattableMixin
python
cherrypy__cherrypy
cherrypy/_cptools.py
{ "start": 8370, "end": 9037 }
class ____(Tool): """Tool which is used to replace the default request.error_response.""" def __init__(self, callable, name=None): """Initialize an error tool.""" Tool.__init__(self, None, callable, name) def _wrapper(self): self.callable(**self._merged_args()) def _setup(self...
ErrorTool
python
ethereum__web3.py
web3/exceptions.py
{ "start": 5071, "end": 5219 }
class ____(Web3Exception): """ Raised when a method has not retrieved the desired result within a specified timeout. """
TimeExhausted
python
getsentry__sentry
src/sentry/grouping/component.py
{ "start": 9275, "end": 9362 }
class ____(BaseGroupingComponent[int]): id: str = "code"
NSErrorCodeGroupingComponent
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_util_test.py
{ "start": 11804, "end": 12928 }
class ____(test.TestCase): def test_one_is_explicitly_adjoint_of_other_returns_true(self): x = linalg_lib.LinearOperatorFullMatrix( [[1., 2.], [3., 4.]], is_self_adjoint=False) self.assertTrue(linear_operator_util.is_adjoint_pair(x, x.H)) self.assertTrue(linear_operator_util.is_adjoint_pair(x.H, ...
IsAdjointPairTest
python
boto__boto3
tests/unit/docs/test_docstring.py
{ "start": 639, "end": 11450 }
class ____(BaseDocsTest): def test_action_help(self): with mock.patch('sys.stdout', io.StringIO()) as mock_stdout: help(self.resource.sample_operation) action_docstring = mock_stdout.getvalue() self.assert_contains_lines_in_order( [ ' **Request Syntax...
TestResourceDocstrings
python
getsentry__sentry
tests/sentry/replays/endpoints/test_project_replay_jobs_delete.py
{ "start": 551, "end": 15402 }
class ____(APITestCase): endpoint = "sentry-api-0-project-replay-deletion-jobs-index" def setUp(self) -> None: super().setUp() self.login_as(self.user) self.organization = self.create_organization(owner=self.user) self.project = self.create_project(organization=self.organization...
ProjectReplayDeletionJobsIndexTest
python
pytorch__pytorch
torch/ao/pruning/scheduler/base_scheduler.py
{ "start": 191, "end": 6625 }
class ____: def __init__(self, sparsifier, last_epoch=-1, verbose=False): # Attach sparsifier if not isinstance(sparsifier, BaseSparsifier): raise TypeError( f"{type(sparsifier).__name__} is not an instance of torch.ao.pruning.BaseSparsifier" ) self.sp...
BaseScheduler
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 416705, "end": 419782 }
class ____(ExprNode): # Helper class used in the implementation of Python3+ # class definitions. Constructs a class object given # a name, tuple of bases and class dictionary. # # name EncodedString Name of the class # module_name EncodedString Name of defining module ...
Py3ClassNode
python
tensorflow__tensorflow
tensorflow/python/ops/math_ops_test.py
{ "start": 21170, "end": 23182 }
class ____(test_util.TensorFlowTestCase): def testApproximateEqual(self): for dtype in [np.float32, np.double]: x = dtype(1) y = dtype(1.00009) z = False with test_util.device(use_gpu=True): # Default tolerance is 0.00001 z_tf = self.evaluate(math_ops.approximate_equal(x, ...
ApproximateEqualTest
python
redis__redis-py
redis/asyncio/cluster.py
{ "start": 2470, "end": 47126 }
class ____(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands): """ Create a new RedisCluster client. Pass one of parameters: - `host` & `port` - `startup_nodes` | Use ``await`` :meth:`initialize` to find cluster nodes & create connections. | Use ``await`` :meth:`close` to...
RedisCluster
python
tensorflow__tensorflow
tensorflow/python/ops/math_ops_test.py
{ "start": 15945, "end": 19127 }
class ____(test_util.TensorFlowTestCase): """Test for sampled_addmm.""" SUPPORTED_DTYPES = [ dtypes.bfloat16, dtypes.float16, dtypes.float32, dtypes.float64, ] def sampledADDMMRef( self, indices, values, dense_shape, mat1, mat2, beta=1.0, ...
SampledADDMMTest
python
astropy__astropy
astropy/coordinates/builtin_frames/ecliptic.py
{ "start": 7773, "end": 8539 }
class ____(BaseEclipticFrame): """ Heliocentric true ecliptic coordinates. These origin of the coordinates are the center of the sun, with the x axis pointing in the direction of the *true* (not mean) equinox as at the time specified by the ``equinox`` attribute (as seen from Earth), and the xy-pla...
HeliocentricTrueEcliptic
python
coleifer__peewee
tests/libs/mock.py
{ "start": 9053, "end": 9546 }
class ____(object): """Access attributes to return a named object, usable as a sentinel.""" def __init__(self): self._sentinels = {} def __getattr__(self, name): if name == '__bases__': # Without this help(mock) raises an exception raise AttributeError return...
_Sentinel
python
ray-project__ray
python/ray/train/examples/experiment_tracking/lightning_exp_tracking_model_dl.py
{ "start": 558, "end": 1236 }
class ____(pl.LightningModule): def __init__(self): super().__init__() self.layer = torch.nn.Linear(3, 1) def forward(self, x): return self.layer(x) def training_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.binary_cross_entropy_with_lo...
DummyModel
python
django__django
tests/gis_tests/geogapp/models.py
{ "start": 566, "end": 685 }
class ____(NamedModel): code = models.CharField(max_length=10) poly = models.PolygonField(geography=True)
Zipcode
python
apache__avro
lang/py/avro/ipc.py
{ "start": 2140, "end": 8568 }
class ____: """Base class for the client side of a protocol interaction.""" def __init__(self, local_protocol, transceiver): self._local_protocol = local_protocol self._transceiver = transceiver self._remote_protocol = None self._remote_hash = None self._send_protocol = ...
BaseRequestor
python
kamyu104__LeetCode-Solutions
Python/count-pairs-that-form-a-complete-day-i.py
{ "start": 48, "end": 383 }
class ____(object): def countCompleteDayPairs(self, hours): """ :type hours: List[int] :rtype: int """ result = 0 cnt = [0]*24 for x in hours: result += cnt[-x%24] cnt[x%24] += 1 return result # Time: O(n^2) # Space: O(1) # b...
Solution
python
spyder-ide__spyder
spyder/plugins/editor/widgets/codeeditor/lsp_mixin.py
{ "start": 2085, "end": 51221 }
class ____: # -- LSP constants # Timeouts (in milliseconds) to sychronize symbols and folding after # linting results arrive, according to the number of lines in the file. SYNC_SYMBOLS_AND_FOLDING_TIMEOUTS = { # Lines: Timeout 500: 600, 1500: 800, 2500: 1000, 6500...
LSPMixin
python
readthedocs__readthedocs.org
readthedocs/audit/apps.py
{ "start": 113, "end": 245 }
class ____(AppConfig): name = "readthedocs.audit" def ready(self): import readthedocs.audit.signals # noqa
AuditConfig
python
doocs__leetcode
lcof2/剑指 Offer II 089. 房屋偷盗/Solution.py
{ "start": 0, "end": 241 }
class ____: def rob(self, nums: List[int]) -> int: n = len(nums) f = [0] * (n + 1) f[1] = nums[0] for i in range(2, n + 1): f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]) return f[n]
Solution
python
kamyu104__LeetCode-Solutions
Python/longest-well-performing-interval.py
{ "start": 29, "end": 697 }
class ____(object): def longestWPI(self, hours): """ :type hours: List[int] :rtype: int """ result, accu = 0, 0 lookup = {} for i, h in enumerate(hours): accu = accu+1 if h > 8 else accu-1 if accu > 0: result = i+1 ...
Solution
python
streamlit__streamlit
lib/streamlit/runtime/session_manager.py
{ "start": 5532, "end": 13272 }
class ____(Protocol): """SessionManagers are responsible for encapsulating all session lifecycle behavior that the Streamlit Runtime may care about. A SessionManager must define the following required methods: - __init__ - connect_session - close_session - get_session_info - l...
SessionManager
python
fluentpython__example-code-2e
15-more-types/protocol/random/randompop_test.py
{ "start": 99, "end": 612 }
class ____: def __init__(self, items: Iterable) -> None: self._items = list(items) random.shuffle(self._items) def pop_random(self) -> Any: return self._items.pop() def test_issubclass() -> None: assert issubclass(SimplePopper, RandomPopper) def test_isinstance() -> None: po...
SimplePopper
python
ray-project__ray
python/ray/tune/examples/mnist_ptl_mini.py
{ "start": 435, "end": 1647 }
class ____(pl.LightningDataModule): def __init__(self, batch_size: int, data_dir: str = PATH_DATASETS): super().__init__() self.data_dir = data_dir self.transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.308...
MNISTDataModule
python
coleifer__peewee
tests/db_tests.py
{ "start": 16922, "end": 23878 }
class ____(ModelTestCase): requires = [Category, User, UniqueModel, IndexedModel, Person] def test_table_exists(self): self.assertTrue(self.database.table_exists(User._meta.table_name)) self.assertFalse(self.database.table_exists('nuggies')) self.assertTrue(self.database.table_exists(U...
TestIntrospection
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 153280, "end": 169239 }
class ____(Request): """ Gets the count of frames matching the given dataview :param dataview: Dataview specification :type dataview: Dataview """ _service = "frames" _action = "get_count_for_dataview" _version = "2.23" _schema = { "definitions": { "dataview": {...
GetCountForDataviewRequest
python
django__django
tests/admin_inlines/admin.py
{ "start": 1607, "end": 1692 }
class ____(admin.StackedInline): model = EditablePKBook
EditablePKBookStackedInline
python
tensorflow__tensorflow
tensorflow/python/ops/distributions/distribution.py
{ "start": 9682, "end": 46517 }
class ____(_BaseDistribution, metaclass=_DistributionMeta): """A generic probability distribution base class. `Distribution` is a base class for constructing and organizing properties (e.g., mean, variance) of random variables (e.g, Bernoulli, Gaussian). #### Subclassing Subclasses are expected to implemen...
Distribution
python
Textualize__textual
docs/examples/guide/reactivity/recompose02.py
{ "start": 149, "end": 613 }
class ____(App): CSS = """ Screen {align: center middle} Digits {width: auto} """ time: reactive[datetime] = reactive(datetime.now, recompose=True) def compose(self) -> ComposeResult: yield Digits(f"{self.time:%X}") def update_time(self) -> None: self.time = datetime.now(...
Clock
python
tiangolo__fastapi
docs_src/extra_models/tutorial002.py
{ "start": 220, "end": 264 }
class ____(UserBase): password: str
UserIn
python
allegroai__clearml
clearml/backend_api/session/jsonmodels/validators.py
{ "start": 1338, "end": 2520 }
class ____(object): """Validator for maximum value.""" def __init__(self, maximum_value: Any, exclusive: bool = False) -> None: """Init. :param maximum_value: Maximum value for validator. :param bool exclusive: If `True`, then validated value must be strongly bigger than gi...
Max
python
pytorch__pytorch
test/dynamo/cpython/3_13/typinganndata/ann_module5.py
{ "start": 163, "end": 202 }
class ____: value: Final = 3000
MyClass
python
huggingface__transformers
src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py
{ "start": 8043, "end": 14352 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: RecurrentGemmaConfig): super().__init__() self.config = config self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size se...
RecurrentGemmaSdpaAttention
python
doocs__leetcode
solution/0700-0799/0732.My Calendar III/Solution.py
{ "start": 205, "end": 1666 }
class ____: def __init__(self): self.root = Node(1, int(1e9 + 1)) def modify(self, l: int, r: int, v: int, node: Node = None): if l > r: return if node is None: node = self.root if node.l >= l and node.r <= r: node.v += v node.add ...
SegmentTree
python
pytest-dev__pytest
src/_pytest/main.py
{ "start": 15784, "end": 15879 }
class ____(Exception): """Signals a stop as failed test run.""" @dataclasses.dataclass
Failed
python
PrefectHQ__prefect
tests/cli/test_deploy.py
{ "start": 176990, "end": 182029 }
class ____: async def test_deploy_without_entrypoint(self, prefect_client: PrefectClient): await run_sync_in_worker_thread( invoke_and_assert, command="deploy", user_input=( # Accept first flow readchar.key.ENTER + ...
TestDeployWithoutEntrypoint
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 24060, "end": 24754 }
class ____: def test_apply_None(self) -> None: d = Document() orig = d.theme beu._set_temp_theme(d, None) assert beu._themes[d] is orig assert d.theme is orig def test_apply_theme(self) -> None: t = Theme(json={}) d = Document() orig = d.theme ...
Test__set_temp_theme
python
neetcode-gh__leetcode
python/0894-all-possible-full-binary-trees.py
{ "start": 192, "end": 780 }
class ____: def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: dp = { 0 : [], 1 : [ TreeNode() ] } def backtrack(n): if n in dp: return dp[n] res = [] for l in range(n): r = n - 1 - l leftTre...
Solution
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 262409, "end": 262714 }
class ____(_PrintableStructure): _fields_ = [ ('unit', c_uint), ('location', c_uint), ('sublocation', c_uint), ('extlocation', c_uint), ('address', c_uint), ('isParity', c_uint), ('count', c_uint) ]
c_nvmlEccSramUniqueUncorrectedErrorEntry_v1_t
python
PyCQA__pylint
tests/checkers/base/unittest_base.py
{ "start": 288, "end": 588 }
class ____(unittest.TestCase): @unittest.skip("too many dependencies need six :(") def test_no_six(self) -> None: try: has_six = True except ImportError: has_six = False self.assertFalse(has_six, "pylint must be able to run without six")
TestNoSix
python
django__django
django/contrib/admin/sites.py
{ "start": 22879, "end": 23403 }
class ____(LazyObject): def _setup(self): AdminSiteClass = import_string(apps.get_app_config("admin").default_site) self._wrapped = AdminSiteClass() def __repr__(self): return repr(self._wrapped) # This global object represents the default admin site, for the common case. # You can pr...
DefaultAdminSite