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
ray-project__ray
python/ray/_private/authentication/grpc_authentication_server_interceptor.py
{ "start": 1291, "end": 4360 }
class ____(aiogrpc.ServerInterceptor): """Async gRPC server interceptor that validates authentication tokens. This interceptor checks the "authorization" metadata header for a valid Bearer token when token authentication is enabled via RAY_AUTH_MODE=token. If the token is missing or invalid, the reque...
AsyncAuthenticationServerInterceptor
python
numpy__numpy
numpy/_core/_internal.py
{ "start": 7214, "end": 7377 }
class ____: def cast(self, num, obj): return num.value class c_void_p: def __init__(self, ptr): self.value = ptr
_missing_ctypes
python
doocs__leetcode
solution/0200-0299/0214.Shortest Palindrome/Solution.py
{ "start": 0, "end": 508 }
class ____: def shortestPalindrome(self, s: str) -> str: base = 131 mod = 10**9 + 7 n = len(s) prefix = suffix = 0 mul = 1 idx = 0 for i, c in enumerate(s): prefix = (prefix * base + (ord(c) - ord('a') + 1)) % mod suffix = (suffix + (or...
Solution
python
PyCQA__pylint
tests/functional/s/super/super_with_arguments.py
{ "start": 126, "end": 195 }
class ____(Foo): def __init__(self): super().__init__()
Baz
python
google__pytype
pytype/tests/test_recursive_types.py
{ "start": 71, "end": 1782 }
class ____(test_base.BaseTest): """Tests usage of recursive types in source code.""" def test_parameter(self): self.Check(""" from typing import List, Union Foo = Union[str, List['Foo']] def f(x: Foo): pass """) def test_comment(self): self.Check(""" from typing impor...
UsageTest
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_compiler.py
{ "start": 130939, "end": 139790 }
class ____( fixtures.MappedTest, AssertsCompiledSQL, fixtures.CacheKeySuite, fixtures.DistinctOnFixture, ): """Test 'DISTINCT' with SQL expression language and orm.Query with an emphasis on PG's 'DISTINCT ON' syntax. """ __dialect__ = postgresql.dialect() def setup_test(self): ...
DistinctOnTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/override2.py
{ "start": 374, "end": 574 }
class ____: @override def __init__(self): pass def method1(self): pass @property def prop_c(self) -> int: return 0 def method2(self): pass
Base
python
redis__redis-py
redis/connection.py
{ "start": 2468, "end": 4368 }
class ____: def __init__(self, buffer_cutoff, encode) -> None: self._buffer_cutoff = buffer_cutoff self.encode = encode def pack(self, *args): """Pack a series of arguments into the Redis protocol""" output = [] # the client might have included 1 or more literal argument...
PythonRespSerializer
python
pennersr__django-allauth
allauth/account/forms.py
{ "start": 23799, "end": 24887 }
class ____(forms.Form): email = EmailField(required=True) def clean_email(self): email = self.cleaned_data["email"].lower() email = get_adapter().clean_email(email) self.users = filter_users_by_email(email, is_active=True, prefer_verified=True) if not self.users and not app_sett...
ResetPasswordForm
python
python__mypy
mypy/test/testfscache.py
{ "start": 177, "end": 4465 }
class ____(unittest.TestCase): def setUp(self) -> None: self.tempdir = tempfile.mkdtemp() self.oldcwd = os.getcwd() os.chdir(self.tempdir) self.fscache = FileSystemCache() def tearDown(self) -> None: os.chdir(self.oldcwd) shutil.rmtree(self.tempdir) def test...
TestFileSystemCache
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 40547, "end": 40734 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("COMMIT_OR_PR_TITLE", "PR_TITLE")
SquashMergeCommitTitle
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 30050, "end": 128278 }
class ____: """State machine encapsulating the lifetime of all tasks on a worker. Not to be confused with :class:`distributed.scheduler.WorkerState`. .. note:: The data attributes of this class are implementation details and may be changed without a deprecation cycle. .. warning:: ...
WorkerState
python
ipython__ipython
IPython/core/completer.py
{ "start": 30548, "end": 47365 }
class ____(Configurable): greedy = Bool( False, help="""Activate greedy completion. .. deprecated:: 8.8 Use :std:configtrait:`Completer.evaluation` and :std:configtrait:`Completer.auto_close_dict_keys` instead. When enabled in IPython 8.8 or newer, changes configuratio...
Completer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 219224, "end": 219616 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("end", "start") end = sgqlc.types.Field( sgqlc.types.non_null(CheckAnnotationPosition), graphql_name="end" ) start = sgqlc.types.Field( sgqlc.types.non_nul...
CheckAnnotationSpan
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 11754, "end": 12450 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_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 forward(sel...
AltRobertaSelfOutput
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 22108, "end": 25869 }
class ____(object, metaclass=ABCMeta): """Abstract base class for External Memory Management (EMM) Plugins.""" def __init__(self, *args, **kwargs): if 'context' not in kwargs: raise RuntimeError("Memory manager requires a context") self.context = kwargs.pop('context') @abstract...
BaseCUDAMemoryManager
python
PyCQA__pylint
tests/functional/u/unsubscriptable_object.py
{ "start": 404, "end": 520 }
class ____(TypedDict): """It's the identity.""" name: str T = TypeVar("T", bound=Mapping) @dataclass
Identity
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 87036, "end": 88541 }
class ____(BaseModel, extra="forbid"): prefetch: Optional[Union[List["Prefetch"], "Prefetch"]] = Field( default=None, description="Sub-requests to perform first. If present, the query will be performed on the results of the prefetches.", ) query: Optional["QueryInterface"] = Field( d...
Prefetch
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 15190, "end": 17761 }
class ____(NonStrictDataModel): """ :param bidirectional: If set then frames retreival can go either forward or backwards. Otherwise only forward. The default is False. The limitations of bidirectional navigation: - Frames are always returned in sequential order - The iteration is finite...
FlowControl
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py
{ "start": 55, "end": 121 }
class ____[_T: (str, bytes)]: var: _T # python 3.13+ default
Foo
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py
{ "start": 1026, "end": 5369 }
class ____(NamedTuple): """Contains runtime masking information for the Splash attention kernel. The arrays data_next, mask_next and block_mask are placed in TPU scalar-memory. This is a scarse resource so the mask creation logic attempts to shrink the data-type of these arrays to the smallest possible one. ...
MaskInfo
python
django__django
django/templatetags/tz.py
{ "start": 2892, "end": 5273 }
class ____(Node): """ Template node class used by ``get_current_timezone_tag``. """ def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = timezone.get_current_timezone_name() return "" @register.tag("localtime") def loc...
GetCurrentTimezoneNode
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/tests/test_image_vision_llm.py
{ "start": 2593, "end": 8772 }
class ____: """ This double fakes the `Blip2ForConditionalGeneration` model object in order to avoid having to download checkpoints for these tests. """ def generate(self, **kwargs) -> list: """ The output is the tokenized version of the prompt "Question: describe what you s...
ModelFake
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 143054, "end": 145644 }
class ____(Token): """Token for matching words composed of characters *not* in a given set (will include whitespace in matched characters if not listed in the provided exclusion set - see example). Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exa...
CharsNotIn
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_workflows.py
{ "start": 11935, "end": 13346 }
class ____: @mock.patch(BASE_PATH.format("Execution")) @mock.patch(BASE_PATH.format("WorkflowsHook")) def test_execute(self, mock_hook, mock_object): start_date_filter = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(minutes=5) execution_mock = mock.MagicMock() ...
TestWorkflowExecutionsListExecutionsOperator
python
getsentry__sentry
src/sentry/workflow_engine/models/data_condition.py
{ "start": 3863, "end": 10565 }
class ____(DefaultFieldsModel): """ A data condition is a way to specify a logic condition, if the condition is met, the condition_result is returned. """ __relocation_scope__ = RelocationScope.Organization __repr__ = sane_repr("type", "comparison", "condition_result", "condition_group_id") # ...
DataCondition
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/types.py
{ "start": 10952, "end": 11366 }
class ____( NamedTuple("_LoadableRepositorySymbol", [("repository_name", str), ("attribute", str)]) ): def __new__(cls, repository_name: str, attribute: str): return super().__new__( cls, repository_name=check.str_param(repository_name, "repository_name"), attribute=c...
LoadableRepositorySymbol
python
keras-team__keras
keras/src/dtype_policies/dtype_policy_map.py
{ "start": 243, "end": 10840 }
class ____(DTypePolicy, MutableMapping): """Dict-like object mapping layer paths to `DTypePolicy` instances. `DTypePolicyMap` can be used in `get_config` in layers and subclasses to support a complex configurations of dtype policies. For example, we can modify `get_config` in `layers.MultiHeadAttentio...
DTypePolicyMap
python
PrefectHQ__prefect
tests/runner/test_storage.py
{ "start": 3265, "end": 5015 }
class ____(Block): """Mock GitLab credentials block for testing.""" _block_type_slug = "gitlab-credentials" token: Optional[SecretStr] = None def format_git_credentials(self, url: str) -> str: """ Format and return the full git URL with GitLab credentials embedded. Handles bot...
MockGitLabCredentials
python
apache__thrift
lib/py/src/TMultiplexedProcessor.py
{ "start": 3114, "end": 3337 }
class ____(TProtocolDecorator.TProtocolDecorator): def __init__(self, protocol, messageBegin): self.messageBegin = messageBegin def readMessageBegin(self): return self.messageBegin
StoredMessageProtocol
python
walkccc__LeetCode
solutions/1012. Numbers With Repeated Digits/1012.py
{ "start": 0, "end": 1018 }
class ____: def numDupDigitsAtMostN(self, n: int) -> int: return n - self._countSpecialNumbers(n) # Same as 2376. Count Special Integers def _countSpecialNumbers(self, n: int) -> int: s = str(n) @functools.lru_cache(None) def dp(i: int, used: int, tight: bool) -> int: """ Returns the...
Solution
python
python-markdown__markdown
markdown/extensions/abbr.py
{ "start": 4911, "end": 6600 }
class ____(BlockProcessor): """ Parse text for abbreviation references. """ RE = re.compile(r'^[*]\[(?P<abbr>[^\\]*?)\][ ]?:[ ]*\n?[ ]*(?P<title>.*)$', re.MULTILINE) def __init__(self, parser: BlockParser, abbrs: dict): self.abbrs: dict = abbrs super().__init__(parser) def test(self, ...
AbbrBlockprocessor
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/collective_ops_test.py
{ "start": 49915, "end": 52852 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): _setup_context() super().setUp() def testOrdering(self, collective_op, device, communication): dev0 = '/device:%s:0' % device dev1 = '/device:%s:1' % device group_size = 2 group_key = 100 instance_key = 100 in_tens...
OrderingTest
python
doocs__leetcode
solution/3300-3399/3339.Find the Number of K-Even Arrays/Solution2.py
{ "start": 0, "end": 550 }
class ____: def countOfArrays(self, n: int, m: int, k: int) -> int: f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n + 1)] cnt0 = m // 2 cnt1 = m - cnt0 mod = 10**9 + 7 f[0][0][1] = 1 for i in range(1, n + 1): for j in range(k + 1): f[...
Solution
python
openai__openai-python
src/openai/types/beta/realtime/response_audio_done_event.py
{ "start": 200, "end": 679 }
class ____(BaseModel): content_index: int """The index of the content part in the item's content array.""" event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item.""" output_index: int """The index of the output item in the response.""" response_...
ResponseAudioDoneEvent
python
openai__openai-python
src/openai/types/beta/realtime/input_audio_buffer_speech_started_event.py
{ "start": 212, "end": 861 }
class ____(BaseModel): audio_start_ms: int """ Milliseconds from the start of all audio written to the buffer during the session when speech was first detected. This will correspond to the beginning of audio sent to the model, and thus includes the `prefix_padding_ms` configured in the Session. ...
InputAudioBufferSpeechStartedEvent
python
streamlit__streamlit
lib/tests/streamlit/elements/radio_test.py
{ "start": 1295, "end": 16926 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall radio protos.""" def test_just_label(self): """Test that it can be called with no value.""" st.radio("the label", ("m", "f")) c = self.get_delta_from_queue().new_element.radio assert c.label == "the label" ...
RadioTest
python
sphinx-doc__sphinx
sphinx/config.py
{ "start": 2780, "end": 6204 }
class ____: __slots__ = 'default', 'rebuild', 'valid_types', 'description' default: Any rebuild: _ConfigRebuild valid_types: _OptValidTypes description: str def __init__( self, default: Any, rebuild: _ConfigRebuild, valid_types: _OptValidTypes, descripti...
_Opt
python
jazzband__django-simple-history
simple_history/tests/tests/test_models.py
{ "start": 61150, "end": 62390 }
class ____(TestCase): """Test behavior of `latest()` without any field parameters""" def setUp(self): poll = Poll.objects.create(question="Does `latest()` work?", pub_date=yesterday) poll.pub_date = today poll.save() def write_history(self, new_attributes): poll_history = H...
TestLatest
python
huggingface__transformers
src/transformers/models/gemma/modeling_gemma.py
{ "start": 2108, "end": 2782 }
class ____(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.zeros(dim)) def _norm(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) def forward(self, x): output...
GemmaRMSNorm
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 43843, "end": 44070 }
class ____(BaseModel, extra="forbid"): """ Geo point payload schema """ lon: float = Field(..., description="Geo point payload schema") lat: float = Field(..., description="Geo point payload schema")
GeoPoint
python
zarr-developers__zarr-python
src/zarr/storage/_obstore.py
{ "start": 10888, "end": 17429 }
class ____(TypedDict): """A response buffer associated with the original index that it should be restored to.""" original_request_index: int """The positional index in the original key_ranges input""" buffer: Buffer """The buffer returned from obstore's range request.""" async def _make_bounded_...
_Response
python
redis__redis-py
redis/client.py
{ "start": 52369, "end": 65624 }
class ____(Redis): """ Pipelines provide a way to transmit multiple commands to the Redis server in one transmission. This is convenient for batch processing, such as saving all the values in a list to Redis. All commands executed within a pipeline(when running in transactional mode, which is ...
Pipeline
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/scalarstring.py
{ "start": 474, "end": 1571 }
class ____(str): __slots__ = Anchor.attrib def __new__(cls, *args, **kw): # type: (Any, Any) -> Any anchor = kw.pop('anchor', None) ret_val = str.__new__(cls, *args, **kw) if anchor is not None: ret_val.yaml_set_anchor(anchor, always_dump=True) return ret_val...
ScalarString
python
pytorch__pytorch
torch/testing/_internal/common_device_type.py
{ "start": 50701, "end": 50872 }
class ____(skipIf): def __init__(self, dep, reason): super().__init__(dep, reason, device_type="meta") # Skips a test on MPS if the condition is true.
skipMetaIf
python
numba__numba
numba/core/datamodel/models.py
{ "start": 8180, "end": 9449 }
class ____(ProxyModel): """ Enum members are represented exactly like their values. """ def __init__(self, dmm, fe_type): super(EnumModel, self).__init__(dmm, fe_type) self._proxied_model = dmm.lookup(fe_type.dtype) @register_default(types.Opaque) @register_default(types.PyObject) @reg...
EnumModel
python
getsentry__sentry
src/sentry/api/serializers/models/pullrequest.py
{ "start": 441, "end": 1082 }
class ____(TypedDict): id: str title: str | None message: str | None dateCreated: datetime repository: RepositorySerializerResponse author: Author externalUrl: str def get_users_for_pull_requests(item_list, user=None): authors = list( CommitAuthor.objects.filter(id__in=[i.autho...
PullRequestSerializerResponse
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial004.py
{ "start": 109, "end": 162 }
class ____(BaseModel): url: str name: str
Image
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/plus/login_server.py
{ "start": 2278, "end": 3630 }
class ____(HTTPServer): organization: Optional[str] = None token: Optional[str] = None def __init__(self, host: tuple[str, int], nonce: str): super().__init__(host, create_token_callback_handler(nonce)) def shutdown(self): # Stop serving the token server # https://stackoverflow...
TokenServer
python
catalyst-team__catalyst
catalyst/contrib/optimizers/lookahead.py
{ "start": 194, "end": 3897 }
class ____(Optimizer): """Implements Lookahead algorithm. It has been proposed in `Lookahead Optimizer: k steps forward, 1 step back`_. Adapted from: https://github.com/alphadl/lookahead.pytorch (MIT License) .. _`Lookahead Optimizer\: k steps forward, 1 step back`: https://arxiv.org/...
Lookahead
python
getsentry__sentry
tests/sentry/search/events/builder/test_span_metrics.py
{ "start": 1364, "end": 12095 }
class ____(MetricsEnhancedPerformanceTestCase): @pytest.mark.querybuilder def test_granularity(self) -> None: # Need to pick granularity based on the period def get_granularity(start, end): params = { "organization_id": self.organization.id, "project_i...
MetricQueryBuilderTest
python
pytransitions__transitions
tests/utils.py
{ "start": 34, "end": 2169 }
class ____(object): is_false = False is_True = True def __init__(self, states=None, machine_cls=Machine, extra_kwargs=None): extra_kwargs = extra_kwargs if extra_kwargs is not None else {} self.state = None self.message = None states = ['A', 'B', 'C', 'D', 'E', 'F'] if sta...
Stuff
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 174346, "end": 181724 }
class ____: def setup_method(self): self.rng = check_random_state(1234) def test_normal(self): # When the skewness is 0 the distribution is normal x = np.linspace(-5, 5, 100) assert_array_almost_equal(stats.skewnorm.pdf(x, a=0), stats.norm.pdf(x...
TestSkewNorm
python
optuna__optuna
tests/samplers_tests/test_samplers.py
{ "start": 18080, "end": 38647 }
class ____(BaseSampler): def __init__( self, relative_search_space: dict[str, BaseDistribution], relative_params: dict[str, Any], unknown_param_value: Any, ) -> None: self.relative_search_space = relative_search_space self.relative_params = relative_params ...
FixedSampler
python
getsentry__sentry
src/sentry/integrations/pipeline.py
{ "start": 1900, "end": 3688 }
class ____(TypedDict): metadata: dict[str, Any] name: str status: int def ensure_integration(key: str, data: IntegrationData) -> Integration: defaults: _IntegrationDefaults = { "metadata": data.get("metadata", {}), "name": data.get("name", data["external_id"]), "status": Object...
_IntegrationDefaults
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 14485, "end": 19468 }
class ____(NonStrictDataModel): """ An entire plot (not single datapoint) and it's layout. Used for plotting ROC curves, confidence matrices, etc. when evaluating the net. :param timestamp: Epoch milliseconds UTC, will be set by the server if not set. :type timestamp: float :param ...
MetricsPlotEvent
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pydoclint/DOC403_google.py
{ "start": 285, "end": 1106 }
class ____: # DOC403 def foo(self) -> str: """ Do something Args: num (int): A number Yields: str: A string """ print('test') # OK def bar(self) -> str: """ Do something Args: num (int): A n...
Bar
python
boto__boto3
tests/unit/s3/test_inject.py
{ "start": 752, "end": 2425 }
class ____(unittest.TestCase): def test_inject_upload_download_file_to_client(self): class_attributes = {} inject.inject_s3_transfer_methods(class_attributes=class_attributes) assert 'upload_file' in class_attributes assert 'download_file' in class_attributes def test_upload_fil...
TestInjectTransferMethods
python
huggingface__transformers
src/transformers/models/switch_transformers/modeling_switch_transformers.py
{ "start": 30747, "end": 42570 }
class ____(SwitchTransformersPreTrainedModel): _can_record_outputs = { "hidden_states": SwitchTransformersBlock, "attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="layer.0"), "cross_attentions": OutputRecorder(SwitchTransformersAttention, index=-1, layer_name="la...
SwitchTransformersStack
python
python-markdown__markdown
markdown/inlinepatterns.py
{ "start": 13342, "end": 13658 }
class ____(InlineProcessor): """ Return a simple text of `group(1)` of a Pattern. """ def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]: """ Return string content of `group(1)` of a matching pattern. """ return m.group(1), m.start(0), m.end(0)
SimpleTextInlineProcessor
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 3233, "end": 5294 }
class ____(TestCase): def test_required(self) -> None: class Schema(Config): option = c.Choice(('python', 'node')) conf = self.get_config(Schema, {'option': 'python'}) assert_type(conf.option, str) self.assertEqual(conf.option, 'python') def test_optional(self) -> N...
ChoiceTest
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/translate.py
{ "start": 1574, "end": 5836 }
class ____: """ Translates polars-internal IR nodes and expressions to our representation. Parameters ---------- visitor Polars NodeTraverser object engine GPU engine configuration. """ def __init__(self, visitor: NodeTraverser, engine: GPUEngine): self.visitor ...
Translator
python
pandas-dev__pandas
pandas/tests/io/json/test_ujson.py
{ "start": 26855, "end": 35202 }
class ____: def test_dataframe(self, orient): dtype = np.int64 df = DataFrame( [[1, 2, 3], [4, 5, 6]], index=["a", "b"], columns=["x", "y", "z"], dtype=dtype, ) encode_kwargs = {} if orient is None else {"orient": orient} asser...
TestPandasJSONTests
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_module_loading.py
{ "start": 894, "end": 1778 }
class ____: @pytest.mark.parametrize( ("path", "expected"), [ pytest.param("valid_path", True, id="module_no_dots"), pytest.param("valid.dot.path", True, id="standard_dotpath"), pytest.param("package.sub_package.module", True, id="dotpath_with_underscores"), ...
TestModuleLoading
python
chroma-core__chroma
chromadb/segment/impl/vector/brute_force_index.py
{ "start": 331, "end": 5420 }
class ____: """A lightweight, numpy based brute force index that is used for batches that have not been indexed into hnsw yet. It is not thread safe and callers should ensure that only one thread is accessing it at a time. """ id_to_index: Dict[str, int] index_to_id: Dict[int, str] id_to_seq_id...
BruteForceIndex
python
pytorch__pytorch
torch/_export/serde/serialize.py
{ "start": 2636, "end": 5227 }
class ____(RuntimeError): pass def _reverse_map(d: dict[Any, Enum]): return {v.value: k for k, v in d.items()} MetaType = Union[ FakeTensor, int, torch.SymInt, float, torch.SymFloat, bool, torch.SymBool, ep.CustomObjArgument, ] DEFAULT_PICKLE_PROTOCOL = 2 ST_DELIMITER = ";"...
SerializeError
python
huggingface__transformers
tests/models/focalnet/test_modeling_focalnet.py
{ "start": 1538, "end": 8504 }
class ____: def __init__( self, parent, batch_size=13, image_size=32, patch_size=2, num_channels=3, embed_dim=16, hidden_sizes=[32, 64, 128], depths=[1, 2, 1], num_heads=[2, 2, 4], window_size=2, mlp_ratio=2.0, q...
FocalNetModelTester
python
pennersr__django-allauth
allauth/socialaccount/providers/meetup/provider.py
{ "start": 268, "end": 640 }
class ____(OAuth2Provider): id = "meetup" name = "Meetup" account_class = MeetupAccount oauth2_adapter_class = MeetupOAuth2Adapter def extract_uid(self, data): return str(data["id"]) def extract_common_fields(self, data): return dict(email=data.get("email"), name=data.get("name...
MeetupProvider
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 338636, "end": 339891 }
class ____(Request): """ Convert public tasks to private :param ids: Ids of the tasks to convert. Only the tasks originated by the company can be converted :type ids: Sequence[str] """ _service = "tasks" _action = "make_private" _version = "2.20" _schema = { "defini...
MakePrivateRequest
python
sympy__sympy
sympy/stats/drv_types.py
{ "start": 14464, "end": 16889 }
class ____(SingleDiscreteDistribution): _argnames = ('mu1', 'mu2') set = S.Integers @staticmethod def check(mu1, mu2): _value_check(mu1 >= 0, 'Parameter mu1 must be >= 0') _value_check(mu2 >= 0, 'Parameter mu2 must be >= 0') def pdf(self, k): (mu1, mu2) = (self.mu1, self.mu...
SkellamDistribution
python
encode__starlette
starlette/datastructures.py
{ "start": 6988, "end": 7837 }
class ____(Sequence[str]): def __init__(self, value: str | Sequence[str]): if isinstance(value, str): splitter = shlex(value, posix=True) splitter.whitespace = "," splitter.whitespace_split = True self._items = [item.strip() for item in splitter] else:...
CommaSeparatedStrings
python
python-pillow__Pillow
src/PIL/BmpImagePlugin.py
{ "start": 16772, "end": 19855 }
class ____(BmpImageFile): format = "DIB" format_description = "Windows Bitmap" def _open(self) -> None: self._bitmap() # # -------------------------------------------------------------------- # Write BMP file SAVE = { "1": ("1", 1, 2), "L": ("L", 8, 256), "P": ("P", 8, 256), "RG...
DibImageFile
python
aio-libs__aiohttp
aiohttp/abc.py
{ "start": 3555, "end": 3972 }
class ____(ABC): """Abstract DNS resolver.""" @abstractmethod async def resolve( self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET ) -> list[ResolveResult]: """Return IP address for given hostname""" @abstractmethod async def close(self) -> None: ...
AbstractResolver
python
explosion__spaCy
spacy/lang/am/__init__.py
{ "start": 324, "end": 734 }
class ____(BaseDefaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[LANG] = lambda text: "am" tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS suffixes = TOKENIZER_SUFFIXES w...
AmharicDefaults
python
langchain-ai__langchain
libs/core/langchain_core/tools/structured.py
{ "start": 844, "end": 9602 }
class ____(BaseTool): """Tool that can operate on any number of inputs.""" description: str = "" args_schema: Annotated[ArgsSchema, SkipValidation()] = Field( ..., description="The tool schema." ) """The input arguments' schema.""" func: Callable[..., Any] | None = None """The funct...
StructuredTool
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/io_ops/decode_csv_op_test.py
{ "start": 992, "end": 9476 }
class ____(test.TestCase): def _test(self, args, expected_out=None, expected_err_re=None): if expected_err_re is None: decode = parsing_ops.decode_csv(**args) out = self.evaluate(decode) for i, field in enumerate(out): if field.dtype == np.float32 or field.dtype == np.float64: ...
DecodeCSVOpTest
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/all_static_fields.py
{ "start": 2111, "end": 2208 }
class ____: """Test doc string""" def __init__(self, a: int) -> None: self.a = a
A
python
wandb__wandb
wandb/vendor/pygments/lexers/diff.py
{ "start": 453, "end": 1264 }
class ____(RegexLexer): """ Lexer for unified or context-style diffs or patches. """ name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] tokens = { 'root': [ (r' .*\n', Text), (r'\+.*\n'...
DiffLexer
python
pytest-dev__pytest
testing/example_scripts/unittest/test_unittest_asyncio.py
{ "start": 139, "end": 630 }
class ____(IsolatedAsyncioTestCase): async def asyncTearDown(self): teardowns.append(None) async def test_something_async(self): async def addition(x, y): return x + y self.assertEqual(await addition(2, 2), 4) async def test_something_async_fails(self): async d...
AsyncArguments
python
getsentry__sentry
src/sentry/apidocs/hooks.py
{ "start": 3613, "end": 12732 }
class ____(SchemaGenerator): endpoint_inspector_cls = CustomEndpointEnumerator def custom_preprocessing_hook(endpoints: Any) -> Any: # TODO: organize method, rename filtered = [] ownership_data: dict[ApiOwner, dict] = {} for path, path_regex, method, callback in endpoints: owner_team = callba...
CustomGenerator
python
pyinstaller__pyinstaller
bootloader/waflib/TaskGen.py
{ "start": 12755, "end": 15767 }
class ____(Task.Task): def force_permissions(self): if getattr(self.generator, 'chmod', None): for x in self.outputs: os.chmod(x.abspath(), self.generator.chmod) def run(self): if getattr(self.generator, 'is_copy', None): for i, x in enumerate(self.output...
subst_pc
python
spyder-ide__spyder
spyder/plugins/completion/providers/snippets/widgets/snippetsconfig.py
{ "start": 9054, "end": 16804 }
class ____(QDialog, SpyderFontsMixin): SNIPPET_VALID = _('Valid snippet') SNIPPET_INVALID = _('Invalid snippet') INVALID_CB_CSS = "QComboBox {border: 1px solid red;}" VALID_CB_CSS = "QComboBox {border: 1px solid green;}" INVALID_LINE_CSS = "QLineEdit {border: 1px solid red;}" VALID_LINE_CSS = "Q...
SnippetEditor
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/rule_based_profiler/data_assistant/growth_numeric_data_assistant.py
{ "start": 1767, "end": 39200 }
class ____(DataAssistant): """ GrowthNumericDataAssistant provides dataset exploration and validation of growing amounts of numeric columns data. Fundamentally, GrowthNumericDataAssistant is a "thematic blend of VolumeDataAssistant with several Rule definitions from OnboardingDataAssistant concerned wi...
GrowthNumericDataAssistant
python
cython__cython
tests/run/test_tstring.py
{ "start": 4037, "end": 15411 }
class ____(TestCase, TStringBaseCase): def test_string_representation(self): # Test __repr__ t = t"Hello" self.assertEqual(repr(t), "Template(strings=('Hello',), interpolations=())") name = "Python" t = t"Hello, {name}" self.assertEqual(repr(t), "Template...
TestTString
python
ZoranPandovski__al-go-rithms
data_structures/Linked_list/Python/merge_K_sorted_Lists.py
{ "start": 851, "end": 1369 }
class ____: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: res = [] for i in lists: while i != None: res.append(i.val) i = i.next # print(res) if res == []: return None res.sort() ...
Solution
python
networkx__networkx
examples/subclass/plot_printgraph.py
{ "start": 166, "end": 2286 }
class ____(Graph): """ Example subclass of the Graph class. Prints activity log to file or standard output. """ def __init__(self, data=None, name="", file=None, **attr): super().__init__(data=data, name=name, **attr) if file is None: import sys self.fh = s...
PrintGraph
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/types.py
{ "start": 26507, "end": 26639 }
class ____(sqltypes._Binary): """MySQL LONGBLOB type, for binary data up to 2^32 bytes.""" __visit_name__ = "LONGBLOB"
LONGBLOB
python
allegroai__clearml
clearml/backend_api/services/v2_13/projects.py
{ "start": 105226, "end": 106364 }
class ____(Request): """ Convert company projects to public :param ids: Ids of the projects to convert :type ids: Sequence[str] """ _service = "projects" _action = "make_public" _version = "2.13" _schema = { "definitions": {}, "properties": { "ids": { ...
MakePublicRequest
python
kubernetes-client__python
kubernetes/client/models/v1alpha3_cel_device_selector.py
{ "start": 383, "end": 8342 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1alpha3CELDeviceSelector
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/sensors.py
{ "start": 7417, "end": 7680 }
class ____(graphene.Union): class Meta: types = ( GrapheneSensor, GrapheneSensorNotFoundError, GrapheneUnauthorizedError, GraphenePythonError, ) name = "SensorOrError"
GrapheneSensorOrError
python
walkccc__LeetCode
solutions/3315. Construct the Minimum Bitwise Array II/3315.py
{ "start": 0, "end": 600 }
class ____: # Same as 3314. Construct the Minimum Bitwise Array I def minBitwiseArray(self, nums: list[int]) -> list[int]: return [-1 if num == 2 else num - self._getLeadingOneOfLastGroupOfOnes(num) for num in nums] def _getLeadingOneOfLastGroupOfOnes(self, num: int) -> int: """ Returns t...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/sensor/sensor_builder.py
{ "start": 2442, "end": 10566 }
class ____(DagsterUserCodeExecutionError): """Error raised when an error occurs in the event transformer function.""" def check_keys_for_asset_keys( repository_def: RepositoryDefinition, asset_keys: set[AssetKey] ) -> Iterable[AssetCheckKey]: for assets_def in repository_def.asset_graph.assets_defs: ...
AirliftSensorEventTransformerError
python
django__django
django/core/exceptions.py
{ "start": 647, "end": 731 }
class ____(Exception): """The user did something suspicious"""
SuspiciousOperation
python
Textualize__textual
tests/test_freeze.py
{ "start": 246, "end": 616 }
class ____(App): def on_mount(self): self.install_screen(MyScreen(), "myscreen") self.push_screen("myscreen") async def test_freeze(): """Regression test for https://github.com/Textualize/textual/issues/1608""" app = MyApp() with pytest.raises(Exception): async with app.run_tes...
MyApp
python
graphql-python__graphene
graphene/types/tests/test_scalar.py
{ "start": 1733, "end": 3136 }
class ____: def test_query(self): """ Test that a normal query works. """ result = schema.execute("{ optional { int(input: 20) } }") assert not result.errors assert result.data == {"optional": {"int": 20}} def test_optional_input(self): """ Test t...
TestInt
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 71817, "end": 72558 }
class ____(object): ''' This plugin applies the :func:`view` decorator to all routes with a `template` config parameter. If the parameter is a tuple, the second element must be a dict with additional options (e.g. `template_engine`) or default variables for the template. ''' name = 'temp...
TemplatePlugin
python
crytic__slither
slither/core/declarations/event_contract.py
{ "start": 217, "end": 721 }
class ____(Event, ContractLevel): def is_declared_by(self, contract: "Contract") -> bool: """ Check if the element is declared by the contract :param contract: :return: """ return self.contract == contract @property def canonical_name(self) -> str: ""...
EventContract
python
django__django
tests/aggregation_regress/models.py
{ "start": 2796, "end": 2862 }
class ____(Author): class Meta: proxy = True
AuthorProxy
python
getsentry__sentry
tests/sentry/incidents/test_charts.py
{ "start": 3482, "end": 5492 }
class ____(TestCase): @patch("sentry.charts.backend.generate_chart", return_value="chart-url") @patch("sentry.incidents.charts.client.get") def test_eap_alert(self, mock_client_get: MagicMock, mock_generate_chart: MagicMock) -> None: mock_client_get.return_value.data = {"data": []} alert_rul...
BuildMetricAlertChartTest
python
doocs__leetcode
solution/2300-2399/2326.Spiral Matrix IV/Solution.py
{ "start": 151, "end": 731 }
class ____: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: ans = [[-1] * n for _ in range(m)] i = j = k = 0 dirs = (0, 1, 0, -1, 0) while 1: ans[i][j] = head.val head = head.next if head is None: ...
Solution