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
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 6003, "end": 32005 }
class ____: def __init__( self, connection: ConnectionSync, consistency_level: Optional[ConsistencyLevel], results: _BatchDataWrapper, batch_mode: _BatchMode, executor: ThreadPoolExecutor, vectorizer_batching: bool, objects: Optional[ObjectsBatchReques...
_BatchBase
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 63613, "end": 69788 }
class ____(WavLMPreTrainedModel): def __init__(self, config): super().__init__(config) self.wavlm = WavLMModel(config) num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings if config.use_weighted_layer_sum: self.layer_weights = nn.Parameter(t...
WavLMForXVector
python
donnemartin__interactive-coding-challenges
graphs_trees/tree_level_lists/test_tree_level_lists.py
{ "start": 18, "end": 1062 }
class ____(unittest.TestCase): def test_tree_level_lists(self): bst = BstLevelLists(Node(5)) bst.insert(3) bst.insert(8) bst.insert(2) bst.insert(4) bst.insert(1) bst.insert(7) bst.insert(6) bst.insert(9) bst.insert(10) bst.ins...
TestTreeLevelLists
python
ray-project__ray
python/ray/data/preprocessors/utils.py
{ "start": 1124, "end": 1669 }
class ____(BaseStatSpec): """Represents an AggregateFnV2 spec for a single column.""" def __init__( self, *, aggregator_fn: Union[AggregateFnV2, Callable[[str], AggregateFnV2]], post_process_fn: Callable = lambda x: x, post_key_fn: Callable[[str], str], column: O...
AggregateStatSpec
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 5512, "end": 5680 }
class ____: """Class for minimal repo.""" def method(cls) -> None: pass @classmethod def cls_method(cls) -> None: pass # end # E301
Class
python
scipy__scipy
benchmarks/benchmarks/signal.py
{ "start": 2734, "end": 3203 }
class ____(Benchmark): param_names = ['mode', 'size'] params = [ ['full', 'valid', 'same'], [(a, b) for a, b in product((40, 200, 3000), repeat=2) if b < a] ] def setup(self, mode, size): rng = np.random.default_rng(1234) self.a = rng.standard_normal(size[0]) ...
OAConvolve
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_safe_run_sql_with_run_sql_disabled_app/migrations/0001_initial.py
{ "start": 171, "end": 293 }
class ____(CheckedMigration): initial = True dependencies = [] operations = [SafeRunSQL("select 1;")]
Migration
python
scrapy__scrapy
tests/test_crawl.py
{ "start": 15329, "end": 33009 }
class ____: mockserver: MockServer @classmethod def setup_class(cls): cls.mockserver = MockServer() cls.mockserver.__enter__() @classmethod def teardown_class(cls): cls.mockserver.__exit__(None, None, None) async def _run_spider( self, spider_cls: type[Spider] ...
TestCrawlSpider
python
google__jax
docs/sphinxext/jax_list_config_options.py
{ "start": 1749, "end": 5561 }
class ____(SphinxDirective): required_arguments = 0 optional_arguments = 0 has_content = False def run(self) -> List[nodes.Node]: from jax._src.config import config as jax_config config_options = sorted(jax_config.meta.items(), key=itemgetter(0)) result = [] for name, (opt_type, meta_args, me...
ConfigOptionDirective
python
lepture__authlib
authlib/oauth1/rfc5849/errors.py
{ "start": 776, "end": 1010 }
class ____(OAuth1Error): error = "insecure_transport" description = "OAuth 2 MUST utilize https." @classmethod def check(cls, uri): if not is_secure_transport(uri): raise cls()
InsecureTransportError
python
apache__airflow
providers/asana/src/airflow/providers/asana/operators/asana_tasks.py
{ "start": 1057, "end": 2381 }
class ____(BaseOperator): """ This operator can be used to create Asana tasks. .. seealso:: For more information on Asana optional task parameters: https://developers.asana.com/docs/create-a-task .. seealso:: For more information on how to use this operator, take a look at the ...
AsanaCreateTaskOperator
python
getsentry__sentry
src/sentry/models/groupopenperiod.py
{ "start": 1419, "end": 10498 }
class ____(DefaultFieldsModel): """ A GroupOpenPeriod is a period of time where a group is considered "open", i.e. having a status that is not resolved. This is primarily used for detector-based issues to track the period of time that an issue is open for. """ __relocation_scope__ = RelocationS...
GroupOpenPeriod
python
has2k1__plotnine
plotnine/scales/scale_stroke.py
{ "start": 1657, "end": 1711 }
class ____(scale_stroke_continuous): pass
scale_stroke
python
getsentry__sentry
src/sentry/integrations/slack/views/link_team.py
{ "start": 2269, "end": 3676 }
class ____(SlackLinkageView, LinkTeamView): """ Django view for linking team to slack channel. Creates an entry on ExternalActor table. """ def notify_on_success(self, channel_id: str, integration: RpcIntegration, message: str) -> None: try: client = SlackSdkClient(integration_id=in...
SlackLinkTeamView
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py
{ "start": 2212, "end": 2512 }
class ____(Model): new_field = models.CharField(max_length=10) class Meta: abstract = True def __str__(self): return self.new_field @property def my_brand_new_property(self): return 1 def my_beautiful_method(self): return 2
AbstractTestModel3
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_checks/asset_checks_definition.py
{ "start": 485, "end": 2248 }
class ____(AssetsDefinition): """Defines a set of checks that are produced by the same op or op graph. AssetChecksDefinition should not be instantiated directly, but rather produced using the `@asset_check` decorator or `AssetChecksDefinition.create` method. """ @staticmethod def create( *...
AssetChecksDefinition
python
readthedocs__readthedocs.org
readthedocs/proxito/views/hosting.py
{ "start": 9999, "end": 10119 }
class ____(RemoveFieldsMixin, VersionSerializer): FIELDS_TO_REMOVE = [ "_links", ]
VersionAddonsSerializer
python
pydata__xarray
xarray/core/missing.py
{ "start": 2226, "end": 2588 }
class ____: """Generic interpolator class for normalizing interpolation methods""" cons_kwargs: dict[str, Any] call_kwargs: dict[str, Any] f: Callable method: str def __call__(self, x): return self.f(x, **self.call_kwargs) def __repr__(self): return f"{self.__class__.__nam...
BaseInterpolator
python
huggingface__transformers
src/transformers/models/convnextv2/modeling_convnextv2.py
{ "start": 5722, "end": 7743 }
class ____(nn.Module): """This corresponds to the `Block` class in the original implementation. There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C, H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Pe...
ConvNextV2Layer
python
walkccc__LeetCode
solutions/3381. Maximum Subarray Sum With Length Divisible by K/3381.py
{ "start": 0, "end": 414 }
class ____: def maxSubarraySum(self, nums: list[int], k: int) -> int: ans = -math.inf prefix = 0 # minPrefix[i % k] := the minimum prefix sum of the first i numbers minPrefix = [math.inf] * k minPrefix[k - 1] = 0 for i, num in enumerate(nums): prefix += num ans = max(ans, prefix -...
Solution
python
falconry__falcon
falcon/_typing.py
{ "start": 7989, "end": 8190 }
class ____(Protocol[_AReqT]): """ASGI middleware with WebSocket request handler.""" async def process_request_ws(self, req: _AReqT, ws: WebSocket) -> None: ...
AsgiMiddlewareWithProcessRequestWs
python
great-expectations__great_expectations
great_expectations/expectations/expectation.py
{ "start": 83810, "end": 85637 }
class ____(BatchExpectation, ABC): """Base class for column aggregate Expectations. These types of Expectation produce an aggregate metric for a column, such as the mean, standard deviation, number of unique values, column type, etc. --Documentation-- - https://docs.greatexpectations.io/docs/g...
ColumnAggregateExpectation
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/variables/variable_scope_test.py
{ "start": 2478, "end": 60782 }
class ____(test.TestCase): def tearDown(self): gc.collect() # This will only contain uncollectable garbage, i.e. reference cycles # involving objects with __del__ defined. self.assertEqual(0, len(gc.garbage)) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def t...
VariableScopeTest
python
sympy__sympy
bin/sympy_time_cache.py
{ "start": 55, "end": 3191 }
class ____(object): def __init__(self, name): self._name = name self._children = [] self._time = 0 def __str__(self): return "%s: %s" % (self._name, self._time) __repr__ = __str__ def add_child(self, node): self._children.append(node) def children(self): ...
TreeNode
python
matplotlib__matplotlib
lib/matplotlib/projections/polar.py
{ "start": 19003, "end": 24723 }
class ____(maxis.YTick): """ A radial-axis tick. This subclass of `.YTick` provides radial ticks with some small modification to their re-positioning such that ticks are rotated based on axes limits. This results in ticks that are correctly perpendicular to the spine. Labels are also rotated t...
RadialTick
python
airbytehq__airbyte
airbyte-integrations/connectors/source-webflow/source_webflow/webflow_to_airbyte_mapping.py
{ "start": 63, "end": 1257 }
class ____: """ The following disctionary is used for dynamically pulling the schema from Webflow, and mapping it to an Airbyte-compatible json-schema Webflow: https://developers.webflow.com/#get-collection-with-full-schema Airbyte/json-schema: https://docs.airbyte.com/understanding-airbyte/sup...
WebflowToAirbyteMapping
python
getsentry__sentry
src/sentry/models/activity.py
{ "start": 1288, "end": 3507 }
class ____(BaseManager["Activity"]): def get_activities_for_group(self, group: Group, num: int) -> Sequence[Activity]: activities = [] activity_qs = self.filter(group=group).order_by("-datetime") # Check if 'initial_priority' is available initial_priority_value = group.get_event_met...
ActivityManager
python
numba__numba
numba/core/types/npytypes.py
{ "start": 19667, "end": 19876 }
class ____(Type): def __init__(self, *args, **kwargs): super(NumPyRandomBitGeneratorType, self).__init__(*args, **kwargs) self.name = 'NumPyRandomBitGeneratorType'
NumPyRandomBitGeneratorType
python
jazzband__django-polymorphic
example/orders/migrations/0001_initial.py
{ "start": 43, "end": 5200 }
class ____(migrations.Migration): dependencies = [("contenttypes", "0002_remove_content_type_name")] operations = [ migrations.CreateModel( name="Order", fields=[ ( "id", models.AutoField( verbose_n...
Migration
python
astropy__astropy
astropy/coordinates/tests/test_representation_arithmetic.py
{ "start": 1731, "end": 18104 }
class ____: def setup_method(self): # Choose some specific coordinates, for which ``sum`` and ``dot`` # works out nicely. self.lon = Longitude(np.arange(0, 12.1, 2), u.hourangle) self.lat = Latitude(np.arange(-90, 91, 30), u.deg) self.distance = [5.0, 12.0, 4.0, 2.0, 4.0, 12....
TestArithmetic
python
doocs__leetcode
solution/2400-2499/2469.Convert the Temperature/Solution.py
{ "start": 0, "end": 135 }
class ____: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32]
Solution
python
scikit-learn__scikit-learn
sklearn/calibration.py
{ "start": 48230, "end": 61415 }
class ____(_BinaryClassifierCurveDisplayMixin): """Calibration curve (also known as reliability diagram) visualization. It is recommended to use :func:`~sklearn.calibration.CalibrationDisplay.from_estimator` or :func:`~sklearn.calibration.CalibrationDisplay.from_predictions` to create a `Calibratio...
CalibrationDisplay
python
euske__pdfminer
pdfminer/layout.py
{ "start": 7799, "end": 8177 }
class ____(LTContainer): def __init__(self): LTContainer.__init__(self, (+INF, +INF, -INF, -INF)) return def add(self, obj): LTContainer.add(self, obj) self.set_bbox((min(self.x0, obj.x0), min(self.y0, obj.y0), max(self.x1, obj.x1), max(self.y1, obj.y1)))...
LTExpandableContainer
python
getsentry__sentry
src/sentry/issues/priority.py
{ "start": 646, "end": 5988 }
class ____(StrEnum): ESCALATING = "escalating" ONGOING = "ongoing" ISSUE_PLATFORM = "issue_platform" PRIORITY_TO_GROUP_HISTORY_STATUS = { PriorityLevel.HIGH: GroupHistoryStatus.PRIORITY_HIGH, PriorityLevel.MEDIUM: GroupHistoryStatus.PRIORITY_MEDIUM, PriorityLevel.LOW: GroupHistoryStatus.PRIORI...
PriorityChangeReason
python
pytest-dev__pytest-django
pytest_django/runner.py
{ "start": 98, "end": 1393 }
class ____: """A Django test runner which uses pytest to discover and run tests when using `manage.py test`.""" def __init__( self, *, verbosity: int = 1, failfast: bool = False, keepdb: bool = False, **kwargs: Any, # noqa: ARG002 ) -> None: self.ver...
TestRunner
python
getsentry__sentry
src/sentry/backup/findings.py
{ "start": 221, "end": 864 }
class ____(NamedTuple): """Every entry in the generated backup JSON file should have a unique model+ordinal combination, which serves as its identifier.""" model: str # The order that this model appeared in the JSON inputs. Because we validate that the same # number of models of each kind are pres...
InstanceID
python
kamyu104__LeetCode-Solutions
Python/escape-the-ghosts.py
{ "start": 29, "end": 340 }
class ____(object): def escapeGhosts(self, ghosts, target): """ :type ghosts: List[List[int]] :type target: List[int] :rtype: bool """ total = abs(target[0])+abs(target[1]) return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)
Solution
python
pytorch__pytorch
torch/fx/experimental/proxy_tensor.py
{ "start": 58973, "end": 64115 }
class ____(TorchDispatchMode): # Ensure this is read-only; this exists only for legacy reasons @property def enable_tracing(self) -> bool: return True def __init__( self, tracer: _ProxyTracer, tracing_mode: str, pre_dispatch: bool = False, _allow_fake_con...
ProxyTorchDispatchMode
python
sanic-org__sanic
sanic/application/constants.py
{ "start": 594, "end": 711 }
class ____(IntEnum): """Server stages.""" STOPPED = auto() PARTIAL = auto() SERVING = auto()
ServerStage
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/namedTuple8.py
{ "start": 183, "end": 400 }
class ____(GenericNT[str]): def geturl(self) -> str: ... def func(x: SpecializedNT): reveal_type(x.__iter__, expected_text="() -> Iterator[str]") reveal_type(list(x), expected_text="list[str]")
SpecializedNT
python
vyperlang__vyper
vyper/venom/context.py
{ "start": 279, "end": 569 }
class ____: data: IRLabel | bytes # can be raw data or bytes def __str__(self): if isinstance(self.data, IRLabel): return f"@{self.data}" else: assert isinstance(self.data, bytes) return f'x"{self.data.hex()}"' @dataclass
DataItem
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/objectexplorer/tests/test_objectexplorer.py
{ "start": 8428, "end": 10234 }
class ____: contents: object def test_objectexplorer_refresh_nested(): """ Open an editor for a `Box` object containing a list, and then open another editor for the nested list. Test that refreshing the second editor works. """ old_data = Box([1, 2, 3]) new_data = Box([4, 5]) editor = ...
Box
python
keon__algorithms
tests/test_compression.py
{ "start": 1277, "end": 1698 }
class ____(unittest.TestCase): def test_encode_rle(self): self.assertEqual('12W1B12W3B24W1B14W', encode_rle('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')) def test_decode_rle(self): self.assertEqual('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWW...
TestRLECompression
python
cookiecutter__cookiecutter
cookiecutter/exceptions.py
{ "start": 3548, "end": 3730 }
class ____(CookiecutterException): """ Exception for un-importable extension. Raised when an environment is unable to import a required extension. """
UnknownExtension
python
jmcnamara__XlsxWriter
examples/http_server.py
{ "start": 447, "end": 2024 }
class ____(http.server.SimpleHTTPRequestHandler): def do_GET(self): # Create an in-memory output file for the new workbook. output = io.BytesIO() # Even though the final file will be in memory the module uses temp # files during assembly for efficiency. To avoid this on servers that...
Handler
python
sphinx-doc__sphinx
sphinx/domains/c/__init__.py
{ "start": 12008, "end": 12882 }
class ____(CObject): object_type = 'member' @property def display_object_type(self) -> str: # the distinction between var and member is only cosmetic assert self.objtype in {'member', 'var'} return self.objtype _function_doc_field_types = [ TypedField( 'parameter', ...
CMemberObject
python
numpy__numpy
numpy/lib/tests/test_shape_base.py
{ "start": 11854, "end": 17103 }
class ____: def test_integer_0_split(self): a = np.arange(10) assert_raises(ValueError, array_split, a, 0) def test_integer_split(self): a = np.arange(10) res = array_split(a, 1) desired = [np.arange(10)] compare_results(res, desired) res = array_split(a...
TestArraySplit
python
matplotlib__matplotlib
lib/matplotlib/tests/test_category.py
{ "start": 1912, "end": 4144 }
class ____: """ Based on the pandas conversion and factorization tests: ref: /pandas/tseries/tests/test_converter.py /pandas/tests/test_algos.py:TestFactorize """ test_cases = [("unicode", ["Здравствуйте мир"]), ("ascii", ["hello world"]), ("single", ['a...
TestStrCategoryConverter
python
PyCQA__pydocstyle
src/pydocstyle/violations.py
{ "start": 3554, "end": 11291 }
class ____: """A registry of all error codes, divided to groups.""" groups = [] # type: ignore class ErrorGroup: """A group of similarly themed errors.""" def __init__(self, prefix: str, name: str) -> None: """Initialize the object. `Prefix` should be the common ...
ErrorRegistry
python
pytorch__pytorch
torch/nn/utils/prune.py
{ "start": 21488, "end": 24458 }
class ____(BasePruningMethod): r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to ...
L1Unstructured
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/test_prev_dagrun_dep.py
{ "start": 1488, "end": 14226 }
class ____: def teardown_method(self): clear_db_runs() def test_first_task_run_of_new_task(self, testing_dag_bundle): """ The first task run of a new task in an old DAG should pass if the task has ignore_first_depends_on_past set to True. """ dag = DAG("test_dag"...
TestPrevDagrunDep
python
coleifer__peewee
peewee.py
{ "start": 56540, "end": 57080 }
class ____(WrappedNode): def __sql__(self, ctx): with ctx.scope_column(): return ctx.sql(self.node) def qualify_names(node): # Search a node heirarchy to ensure that any column-like objects are # referenced using fully-qualified names. if isinstance(node, Expression): retur...
QualifiedNames
python
apache__avro
lang/py/avro/ipc.py
{ "start": 17015, "end": 18284 }
class ____: """ A simple HTTP-based transceiver implementation. Useful for clients but not for servers """ def __init__(self, host, port, req_resource="/"): self.req_resource = req_resource self.conn = http.client.HTTPConnection(host, port) self.conn.connect() self.r...
HTTPTransceiver
python
scikit-learn__scikit-learn
sklearn/gaussian_process/tests/test_gpr.py
{ "start": 28956, "end": 30038 }
class ____(C): """ A custom kernel that has a diag method that returns the first column of the input matrix X. This is a helper for the test to check that the input matrix X is not mutated. """ def diag(self, X): return X[:, 0] def test_gpr_predict_input_not_modified(): """ Ch...
CustomKernel
python
arrow-py__arrow
arrow/locales.py
{ "start": 21914, "end": 23033 }
class ____(Locale): names = ["zh", "zh-cn"] past = "{0}前" future = "{0}后" timeframes = { "now": "刚才", "second": "1秒", "seconds": "{0}秒", "minute": "1分钟", "minutes": "{0}分钟", "hour": "1小时", "hours": "{0}小时", "day": "1天", "days": "{...
ChineseCNLocale
python
google__pytype
pytype/pyi/function.py
{ "start": 1677, "end": 6234 }
class ____(pytd_function.NameAndSig): """Internal representation of function signatures.""" @classmethod def from_function( cls, function: astlib.FunctionDef, props: SigProperties ) -> "NameAndSig": """Constructor from an ast.FunctionDef node.""" name = function.name decorators = cast(list[p...
NameAndSig
python
mwaskom__seaborn
tests/_marks/test_dot.py
{ "start": 730, "end": 2478 }
class ____(DotBase): def test_simple(self): x = [1, 2, 3] y = [4, 5, 2] p = Plot(x=x, y=y).add(Dot()).plot() ax = p._figure.axes[0] points, = ax.collections C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"] self.check_offsets(points, x, y) self....
TestDot
python
numba__numba
numba/tests/test_function_type.py
{ "start": 1842, "end": 2392 }
class ____(types.WrapperAddressProtocol): """An example implementation of wrapper address protocol. """ def __init__(self, func, sig): self.pyfunc = func self.cfunc = cfunc(sig)(func) self.sig = sig def __wrapper_address__(self): return self.cfunc._wrapper_address ...
WAP
python
getsentry__sentry
src/sentry/hybridcloud/rpc/resolvers.py
{ "start": 2563, "end": 3662 }
class ____(RegionResolutionStrategy): """Resolve to the only region in a single-organization environment. Calling a service method with this resolution strategy will cause an error if the environment is not configured with the "single organization" or has more than one region. """ def resolve(...
RequireSingleOrganization
python
pytorch__pytorch
benchmarks/tensorexpr/broadcast.py
{ "start": 2711, "end": 4570 }
class ____(benchmark.Benchmark): def __init__(self, mode, device, dtype, M, N, K, L): super().__init__(mode, device, dtype) self.M = M self.N = N self.K = K self.L = L self.d1 = self.rand( [M, N], device=device, dtype=dtype, requires_grad=self.requires_gr...
BroadcastThreeArgs
python
coleifer__peewee
tests/test_utils.py
{ "start": 442, "end": 2541 }
class ____(ModelTestCase): requires = [DataItem, Data] def test_count(self): with count_queries() as count: Data.create(key='k1') Data.create(key='k2') self.assertEqual(count.count, 2) with count_queries() as count: items = [item.key for item in Dat...
TestQueryCounter
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 68717, "end": 132725 }
class ____(Sam2VideoPreTrainedModel): input_modalities = ("video", "text") _can_record_outputs = {"mask_decoder_attentions": OutputRecorder(Sam2VideoTwoWayAttentionBlock, index=2)} _keys_to_ignore_on_load_unexpected = [] _tied_weights_keys = { "prompt_encoder.shared_embedding.positional_embeddin...
Sam2VideoModel
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 9896, "end": 10198 }
class ____(BaseModel): """ DagProcessor info serializer for responses. """ status: Annotated[str | None, Field(title="Status")] = None latest_dag_processor_heartbeat: Annotated[str | None, Field(title="Latest Dag Processor Heartbeat")] = ( None )
DagProcessorInfoResponse
python
OmkarPathak__pygorithm
tests/test_searching.py
{ "start": 2321, "end": 2590 }
class ____(TestSearchingAlgorithm): def test_exponential_search(self): self.assertEqual(exponential_search.search(self.array, 7), 7) alpha_result = linear_search.search(self.alphaArray, 'n') self.assertIs(alpha_result, 5)
TestExponentialSearch
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/struct_store/sql_retriever.py
{ "start": 6284, "end": 18186 }
class ____(BaseRetriever, PromptMixin): """ Text-to-SQL Retriever. Retrieves via text. Args: sql_database (SQLDatabase): SQL database. text_to_sql_prompt (BasePromptTemplate): Prompt template for text-to-sql. Defaults to DEFAULT_TEXT_TO_SQL_PROMPT. context_query_kwa...
NLSQLRetriever
python
plotly__plotly.py
plotly/graph_objs/layout/template/_data.py
{ "start": 235, "end": 49447 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.template" _path_str = "layout.template.data" _valid_props = { "bar", "barpolar", "box", "candlestick", "carpet", "choropleth", "choroplethmap", "choroplethmapbox", "cone",...
Data
python
pyca__cryptography
docs/_ext/cryptography-docs.py
{ "start": 1041, "end": 1631 }
class ____(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app...
Hazmat
python
falconry__falcon
falcon/bench/queues/stats.py
{ "start": 586, "end": 671 }
class ____: def on_get(self, req, resp, tenant_id, queue_name): pass
Resource
python
getsentry__sentry-python
sentry_sdk/integrations/threading.py
{ "start": 702, "end": 7109 }
class ____(Integration): identifier = "threading" def __init__(self, propagate_hub=None, propagate_scope=True): # type: (Optional[bool], bool) -> None if propagate_hub is not None: logger.warning( "Deprecated: propagate_hub is deprecated. This will be removed in the ...
ThreadingIntegration
python
pytorch__pytorch
torch/nn/modules/transformer.py
{ "start": 23578, "end": 28090 }
class ____(Module): r"""TransformerDecoder is a stack of N decoder layers. This TransformerDecoder layer implements the original architecture described in the `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ paper. The intent of this layer is as a reference implementation for foundationa...
TransformerDecoder
python
tensorflow__tensorflow
tensorflow/python/data/ops/options.py
{ "start": 1161, "end": 3256 }
class ____(enum.Enum): """Represents the type of autotuning algorithm to use. DEFAULT: The default behavior is implementation specific and may change over time. HILL_CLIMB: In each optimization step, this algorithm chooses the optimal parameter and increases its value by 1. GRADIENT_DESCENT: In each opti...
AutotuneAlgorithm
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 47182, "end": 47464 }
class ____( legend_frame, legend_background, panel_background, panel_border, plot_background, strip_background, ): """ All rectangle elements Parameters ---------- theme_element : element_rect """ # themeables with scalar values
rect
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 298747, "end": 299648 }
class ____(SimpleCallNode): # Python C-API Function call (only created in transforms) # By default, we assume that the call never returns None, as this # is true for most C-API functions in CPython. If this does not # apply to a call, set the following to True (or None to inherit # the default beh...
PythonCapiCallNode
python
pytorch__pytorch
benchmarks/fastrnns/bench.py
{ "start": 1079, "end": 10845 }
class ____: def __init__(self, enable_timing): pass def record(self): self.time = time.perf_counter() def elapsed_time(self, end_event): assert isinstance(end_event, Event) return end_event.time - self.time def trainbench( name, rnn_creator, nloops=100, wa...
Event
python
jazzband__django-model-utils
tests/test_fields/test_field_tracker.py
{ "start": 36195, "end": 36286 }
class ____(ModelTrackerTests): tracked_class = TrackedAbstract
AbstractModelTrackerTests
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 12226, "end": 16193 }
class ____(Base): """ Common columns and logic for FlowRun and TaskRun models """ __abstract__ = True name: Mapped[str] = mapped_column(default=lambda: generate_slug(2), index=True) state_type: Mapped[Optional[schemas.states.StateType]] = mapped_column( sa.Enum(schemas.states.StateType...
Run
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 38504, "end": 38670 }
class ____(_CreateDropBase["Constraint"]): """Represent a COMMENT ON CONSTRAINT IS statement.""" __visit_name__ = "set_constraint_comment"
SetConstraintComment
python
django__django
tests/delete/models.py
{ "start": 5354, "end": 5451 }
class ____(models.Model): r = models.ForeignKey(R, models.CASCADE, related_name="+")
HiddenUser
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 376778, "end": 394726 }
class ____(VegaLiteSchema): """ FacetedEncoding schema wrapper. Parameters ---------- angle : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumb...
FacetedEncoding
python
huggingface__transformers
src/transformers/models/codegen/configuration_codegen.py
{ "start": 816, "end": 6210 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`CodeGenModel`]. It is used to instantiate a CodeGen model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar confi...
CodeGenConfig
python
sphinx-doc__sphinx
tests/test_intl/test_intl.py
{ "start": 27060, "end": 27572 }
class ____(_MockClock): """Object for mocking :func:`time.time_ns` on Windows platforms. The result is in 'nanoseconds' but with a microsecond resolution so that the division by 1_000 does not cause rounding issues. """ def __init__(self) -> None: self.us: int = 0 # current microsecond 't...
_MockWindowsClock
python
langchain-ai__langchain
libs/langchain/langchain_classic/retrievers/document_compressors/base.py
{ "start": 261, "end": 3145 }
class ____(BaseDocumentCompressor): """Document compressor that uses a pipeline of Transformers.""" transformers: list[BaseDocumentTransformer | BaseDocumentCompressor] """List of document filters that are chained together and run in sequence.""" model_config = ConfigDict( arbitrary_types_allo...
DocumentCompressorPipeline
python
astropy__astropy
astropy/utils/console.py
{ "start": 949, "end": 9991 }
class ____: """Singleton class given access to IPython streams, etc.""" @classproperty def OutStream(cls): if not hasattr(cls, "_OutStream"): if HAS_IPYKERNEL: from ipykernel.iostream import OutStream cls._OutStream = OutStream else: ...
_IPython
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder8.py
{ "start": 212, "end": 327 }
class ____(Protocol[P, R]): @classmethod def collect(cls, *args: P.args, **kwargs: P.kwargs) -> R: ...
Proto1
python
numba__numba
numba/cuda/testing.py
{ "start": 1614, "end": 6064 }
class ____(CUDATestCase): """ For tests where the context needs to be reset after each test. Typically these inspect or modify parts of the context that would usually be expected to be internal implementation details (such as the state of allocations and deallocations, etc.). """ def tearDo...
ContextResettingTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/forLoop1.py
{ "start": 855, "end": 1158 }
class ____(object): def __getitem__(self, item) -> str: return "hello" def testGetItemIterator() -> str: objWithGetItem = ClassWithGetItem() for f in objWithGetItem: return f return "none" # This should generate a syntax error. for in range(3): pass
ClassWithGetItem
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_internal_app_token_details.py
{ "start": 397, "end": 4797 }
class ____(APITestCase): endpoint = "sentry-api-0-sentry-internal-app-token-details" method = "delete" def setUp(self) -> None: self.user = self.create_user(email="boop@example.com") self.org = self.create_organization(owner=self.user, name="My Org") self.project = self.create_proje...
SentryInternalAppTokenCreationTest
python
anthropics__anthropic-sdk-python
src/anthropic/types/citation_char_location_param.py
{ "start": 253, "end": 538 }
class ____(TypedDict, total=False): cited_text: Required[str] document_index: Required[int] document_title: Required[Optional[str]] end_char_index: Required[int] start_char_index: Required[int] type: Required[Literal["char_location"]]
CitationCharLocationParam
python
pytorch__pytorch
.github/scripts/generate_ci_workflows.py
{ "start": 737, "end": 1323 }
class ____: # For use to enable workflows to run on pytorch/pytorch-canary run_on_canary: bool = False labels: set[str] = field(default_factory=set) # Certain jobs might not want to be part of the ciflow/[all,trunk] workflow isolated_workflow: bool = False unstable: bool = False def __post_...
CIFlowConfig
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_project_monitor_checkin_index.py
{ "start": 344, "end": 516 }
class ____(BaseListMonitorCheckInsTest, BaseProjectMonitorTest): endpoint = "sentry-api-0-project-monitor-check-in-index" __test__ = True
ProjectListMonitorCheckInsTest
python
pypa__warehouse
warehouse/packaging/interfaces.py
{ "start": 3161, "end": 3407 }
class ____(ProjectNameUnavailableError): """Project name is too similar to existing project.""" def __init__(self, similar_project_name: str): self.similar_project_name: str = similar_project_name
ProjectNameUnavailableSimilarError
python
astropy__astropy
astropy/utils/metadata/merge.py
{ "start": 3633, "end": 3948 }
class ____(MergeStrategy): """ Merge ``left`` and ``right`` objects using the plus operator. This merge strategy is globally enabled by default. """ types = [(list, list), (tuple, tuple)] enabled = True @classmethod def merge(cls, left, right): return left + right
MergePlus
python
getsentry__sentry
src/sentry/sentry_apps/services/app/model.py
{ "start": 915, "end": 2109 }
class ____(RpcModel): id: int = -1 ident: str | None = None sentry_app_id: int = -1 avatar_type: int = 0 color: bool = False AVATAR_TYPES = SentryAppAvatarTypes.get_choices() url_path = "sentry-app-avatar" FILE_TYPE = "avatar.file" def __hash__(self) -> int: # Mimic the beh...
RpcSentryAppAvatar
python
pytorch__pytorch
test/test_mps.py
{ "start": 561563, "end": 572090 }
class ____(TestCaseMPS): def test_metal_arange(self): x = torch.zeros(12, device="mps", dtype=torch.half) lib = torch.mps.compile_shader(""" kernel void arange(device half* x, uint idx [[thread_position_in_grid]]) { x[idx] = idx; } """) lib.arang...
TestMetalLibrary
python
modin-project__modin
modin/tests/pandas/utils.py
{ "start": 30080, "end": 58377 }
class ____(Exception): pass def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, expected_exception=None, check_kwargs_callable=True, md_extra_kwargs=None, comparator_kwargs=None, check_for_execution_propagation=True, no_check_for_e...
NoModinException
python
getsentry__sentry
src/sentry/workflow_engine/handlers/detector/stateful.py
{ "start": 2519, "end": 11829 }
class ____: dedupe_updates: dict[DetectorGroupKey, int] counter_updates: dict[DetectorGroupKey, DetectorCounters] state_updates: dict[DetectorGroupKey, tuple[bool, DetectorPriorityLevel]] counter_names: list[DetectorCounter] detector: Detector def __init__( self, detector: Detec...
DetectorStateManager
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 75447, "end": 84796 }
class ____(GradientCheckpointingLayer): """ The Mask2FormerMaskedAttentionDecoderLayer is made up of self-attention, cross (masked) attention as well as FFN blocks. The cross attention block used as part of `Mask2FormerMaskedAttentionDecoderLayer` is actually a `masked attention` block that restricts th...
Mask2FormerMaskedAttentionDecoderLayer
python
jupyterlab__jupyterlab
jupyterlab/handlers/extension_manager_handler.py
{ "start": 369, "end": 5063 }
class ____(APIHandler): def initialize(self, manager: ExtensionManager): super().initialize() self.manager = manager @web.authenticated async def get(self): """GET query returns info on extensions Query arguments: refresh: [optional] Force refreshing the list of...
ExtensionHandler
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 2125, "end": 2549 }
class ____(TestCase): def test_some_output(self): out = StringIO() call_command("show_template_tags", stdout=out) output = out.getvalue() # Once django_extension is installed during tests it should appear with # its templatetags self.assertIn("django_extensions", outp...
ShowTemplateTagsTests
python
scrapy__scrapy
tests/test_downloadermiddleware.py
{ "start": 6134, "end": 7965 }
class ____(TestManagerBase): @deferred_f_from_coro_f async def test_invalid_process_request(self): """Invalid return value for process_request method should raise an exception""" req = Request("http://example.com/index.html") class InvalidProcessRequestMiddleware: def proces...
TestInvalidOutput