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
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 122725, "end": 123661 }
class ____: def test_sia(self, backend): cert = _load_cert( os.path.join("x509", "custom", "sia.pem"), x509.load_pem_x509_certificate, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_INFORMATION_ACCESS ) assert ext is no...
TestSubjectInformationAccessExtension
python
pytest-dev__pytest
testing/test_cacheprovider.py
{ "start": 43218, "end": 43884 }
class ____: def check_readme(self, pytester: Pytester) -> bool: config = pytester.parseconfigure() assert config.cache is not None readme = config.cache._cachedir.joinpath("README.md") return readme.is_file() def test_readme_passed(self, pytester: Pytester) -> None: pyte...
TestReadme
python
xlwings__xlwings
xlwings/constants.py
{ "start": 62136, "end": 62309 }
class ____: xlFillWithAll = -4104 # from enum XlFillWith xlFillWithContents = 2 # from enum XlFillWith xlFillWithFormats = -4122 # from enum XlFillWith
FillWith
python
getsentry__sentry
src/sentry/issues/endpoints/browser_reporting_collector.py
{ "start": 1151, "end": 1830 }
class ____(serializers.URLField): """ A URLField that allows longer URLs than Django's default 2048 character limit. This is needed for browser reporting where URLs can be very long due to many query parameters. """ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) ...
LongURLField
python
numpy__numpy
benchmarks/benchmarks/bench_ufunc_strides.py
{ "start": 4337, "end": 4499 }
class ____(_AbstractUnary): params = [ [np.reciprocal, np.absolute, np.square, np.conjugate], [1, 2, 4], [1, 2, 4], ['F', 'D'] ]
UnaryComplex
python
patrick-kidger__equinox
equinox/nn/_pool.py
{ "start": 10516, "end": 12098 }
class ____(Pool): """Two-dimensional downsample using the maximum over a sliding window.""" def __init__( self, kernel_size: int | Sequence[int], stride: int | Sequence[int] = 1, padding: int | Sequence[int] | Sequence[tuple[int, int]] = 0, use_ceil: bool = False, ):...
MaxPool2d
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 109396, "end": 110484 }
class ____(Response): """ Response of events.scalar_metrics_iter_histogram endpoint. :param images: :type images: Sequence[dict] """ _service = "events" _action = "scalar_metrics_iter_histogram" _version = "2.13" _schema = { "definitions": {}, "properties": {"images...
ScalarMetricsIterHistogramResponse
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_settings_options.py
{ "start": 500, "end": 2551 }
class ____(UserNotificationSettingsOptionsBaseTest): def setUp(self) -> None: super().setUp() self.login_as(self.user) def test_simple(self) -> None: other_user = self.create_user() NotificationSettingOption.objects.create( user_id=self.user.id, scope_typ...
UserNotificationSettingsOptionsGetTest
python
coleifer__peewee
tests/models.py
{ "start": 160743, "end": 162474 }
class ____(ModelTestCase): requires = [User, Tweet] def test_lateral_join(self): with self.database.atomic(): for i in range(3): u = User.create(username='u%s' % i) for j in range(4): Tweet.create(user=u, content='u%s-t%s' % (i, j)) ...
TestLateralJoin
python
django__django
django/db/models/expressions.py
{ "start": 60736, "end": 63274 }
class ____(BaseExpression, Combinable): """ An explicit subquery. It may contain OuterRef() references to the outer query which will be resolved when it is applied to that query. """ template = "(%(subquery)s)" contains_aggregate = False empty_result_set_value = None subquery = True ...
Subquery
python
django__django
tests/admin_views/models.py
{ "start": 23363, "end": 23535 }
class ____(models.Model): choice = models.IntegerField( blank=True, null=True, choices=((1, "Yes"), (0, "No"), (None, "No opinion")), )
Choice
python
facelessuser__pymdown-extensions
pymdownx/blocks/details.py
{ "start": 2329, "end": 3864 }
class ____(BlocksExtension): """Admonition Blocks Extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { "types": [ [], "Generate Admonition block extensions for the given types." ] } super()...
DetailsExtension
python
tiangolo__fastapi
tests/test_validate_response_dataclass.py
{ "start": 247, "end": 1208 }
class ____: name: str price: Optional[float] = None owner_ids: Optional[List[int]] = None @app.get("/items/invalid", response_model=Item) def get_invalid(): return {"name": "invalid", "price": "foo"} @app.get("/items/innerinvalid", response_model=Item) def get_innerinvalid(): return {"name": "do...
Item
python
Netflix__metaflow
metaflow/_vendor/packaging/version.py
{ "start": 1734, "end": 4491 }
class ____: _key: CmpKey def __hash__(self) -> int: return hash(self._key) # Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: "_BaseVersion") -> bool: if not...
_BaseVersion
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_app_webhook_requests.py
{ "start": 627, "end": 18373 }
class ____(APITestCase): def setUp(self) -> None: self.superuser = self.create_user(email="superuser@example.com", is_superuser=True) self.user = self.create_user(email="user@example.com") self.org = self.create_organization( owner=self.user, region="us", ...
SentryAppWebhookRequestsGetTest
python
kamyu104__LeetCode-Solutions
Python/concatenate-non-zero-digits-and-multiply-by-sum-i.py
{ "start": 39, "end": 502 }
class ____(object): def sumAndMultiply(self, n): """ :type n: int :rtype: int """ def reverse(n): result = 0 while n: n, r = divmod(n, 10) result = result*10+r return result total = x = 0 whi...
Solution
python
h5py__h5py
h5py/tests/test_dtype.py
{ "start": 13115, "end": 14487 }
class ____(TestCase): datetime_units = [ # Dates 'Y', 'M', 'D', # Times 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as', ] def test_datetime(self): fname = self.mktemp() for dt_unit in self.datetime_units: for dt_order in ['<', '>']: ...
TestDateTime
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/ParameterTree.py
{ "start": 184, "end": 9782 }
class ____(TreeWidget): """Widget used to display or control data from a hierarchy of Parameters""" def __init__(self, parent=None, showHeader=True): """ ============== ======================================================== **Arguments:** parent (QWidget) An option...
ParameterTree
python
lazyprogrammer__machine_learning_examples
rl2/mountaincar/q_learning.py
{ "start": 1325, "end": 2489 }
class ____: def __init__(self, env, n_components=500): observation_examples = np.array([env.observation_space.sample() for x in range(10000)]) scaler = StandardScaler() scaler.fit(observation_examples) # Used to converte a state to a featurizes represenation. # We use RBF kernels with different v...
FeatureTransformer
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 69068, "end": 69433 }
class ____(TestCase): @staticmethod def application(env, start_response): raise AssertionError('should not get there') def test(self): longline = 'x' * 20000 with self.makefile() as fd: fd.write(('''GET /%s HTTP/1.0\r\nHello: world\r\n\r\n''' % longline).encode('latin-1...
Test414
python
ray-project__ray
python/ray/llm/_internal/batch/benchmark/dataset.py
{ "start": 236, "end": 1649 }
class ____(ABC): DEFAULT_RANDOM_SEED = 0 def __init__( self, dataset_path: Optional[str] = None, random_seed: int = DEFAULT_RANDOM_SEED, ) -> None: """ Abstract base class for benchmark datasets. All benchmark datasets should inherit from this class and impl...
BenchmarkDataset
python
getsentry__sentry
src/sentry/users/api/serializers/user_identity_config.py
{ "start": 4137, "end": 4512 }
class ____(TypedDict): id: str category: str provider: UserIdentityProviderSerializerResponse name: str status: str isLogin: bool organization: ControlSiloOrganizationSerializerResponse dateAdded: datetime | None dateVerified: datetime | None dateSynced: datetime | None @regist...
UserIdentityConfigSerializerResponse
python
ray-project__ray
release/train_tests/benchmark/config.py
{ "start": 1565, "end": 4707 }
class ____(BaseModel): # ScalingConfig num_workers: int = 1 # Run CPU training where train workers request a `MOCK_GPU` resource instead. mock_gpu: bool = False # FailureConfig max_failures: int = 0 task: str = "image_classification" task_config: TaskConfig = Field( default_fac...
BenchmarkConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/descriptor3.py
{ "start": 523, "end": 579 }
class ____: not_working: Desc1[int] = func1(list)
ClassA
python
langchain-ai__langchain
libs/langchain/langchain_classic/evaluation/schema.py
{ "start": 9892, "end": 13917 }
class ____(_EvalArgsMixin, ABC): """Compare the output of two models (or two outputs of the same model).""" @abstractmethod def _evaluate_string_pairs( self, *, prediction: str, prediction_b: str, reference: str | None = None, input: str | None = None, # noq...
PairwiseStringEvaluator
python
run-llama__llama_index
llama-index-core/llama_index/core/base/llms/types.py
{ "start": 16467, "end": 20318 }
class ____(BaseModel): """Chat message.""" role: MessageRole = MessageRole.USER additional_kwargs: dict[str, Any] = Field(default_factory=dict) blocks: list[ContentBlock] = Field(default_factory=list) def __init__(self, /, content: Any | None = None, **data: Any) -> None: """ Keeps...
ChatMessage
python
sqlalchemy__sqlalchemy
test/typing/plain_files/orm/dataclass_transforms_decorator_w_mixins.py
{ "start": 303, "end": 377 }
class ____: pass @unmapped_dataclass(init=False, kw_only=True)
DataModel
python
doocs__leetcode
solution/3200-3299/3294.Convert Doubly Linked List to Array II/Solution.py
{ "start": 171, "end": 419 }
class ____: def toArray(self, node: "Optional[Node]") -> List[int]: while node.prev: node = node.prev ans = [] while node: ans.append(node.val) node = node.next return ans
Solution
python
readthedocs__readthedocs.org
readthedocs/api/v3/mixins.py
{ "start": 7041, "end": 7505 }
class ____(NestedParentObjectMixin): """ Mixin to define queryset permissions for ViewSet only in one place. All APIv3 user' ViewSet should inherit this mixin, unless specific permissions required. In that case, a specific mixin for that case should be defined. """ def has_admin_permission(sel...
UserQuerySetMixin
python
fastai__fastai
fastai/callback/wandb.py
{ "start": 640, "end": 15040 }
class ____(Callback): "Saves model topology, losses & metrics" remove_on_fetch,order = True,Recorder.order+1 # Record if watch has been called previously (even in another instance) _wandb_watch_called = False def __init__(self, log:str=None, # What to log (can be `gradients`, `par...
WandbCallback
python
kubernetes-client__python
kubernetes/client/models/v1_object_field_selector.py
{ "start": 383, "end": 4735 }
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...
V1ObjectFieldSelector
python
doocs__leetcode
solution/0500-0599/0508.Most Frequent Subtree Sum/Solution.py
{ "start": 192, "end": 643 }
class ____: def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 l, r = dfs(root.left), dfs(root.right) s = l + r + root.val cnt[s] += 1 return s ...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/experimental/bundles/upload.py
{ "start": 240, "end": 3064 }
class ____(TypedDict): """ The output of the `upload_bundle_to_gcs` step. """ bucket: str key: str def upload_bundle_to_gcs( local_filepath: Path, bucket: str, key: str, gcp_credentials_block_name: str | None = None, ) -> UploadBundleToGcsOutput: """ Uploads a bundle file ...
UploadBundleToGcsOutput
python
MongoEngine__mongoengine
mongoengine/connection.py
{ "start": 17882, "end": 18536 }
class ____(threading.local): def __init__(self): self.sessions = collections.deque() def append(self, session): self.sessions.append(session) def get_current(self): if len(self.sessions): return self.sessions[-1] def clear_current(self): if len(self.session...
_LocalSessions
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 51005, "end": 51146 }
class ____(serializers.ModelSerializer): class Meta: model = Issue6110TestModel fields = ('name',)
Issue6110ModelSerializer
python
sanic-org__sanic
sanic/exceptions.py
{ "start": 6138, "end": 8176 }
class ____(HTTPException): """405 Method Not Allowed Args: message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None` then the HTTP status 'Method Not Allowed' will be sent. Defaults to `None`. method (Optional[str], optional): The HTTP method t...
MethodNotAllowed
python
sympy__sympy
sympy/physics/biomechanics/tests/test_activation.py
{ "start": 4854, "end": 13395 }
class ____: @staticmethod def test_class(): assert issubclass(FirstOrderActivationDeGroote2016, ActivationBase) assert issubclass(FirstOrderActivationDeGroote2016, _NamedMixin) assert FirstOrderActivationDeGroote2016.__name__ == 'FirstOrderActivationDeGroote2016' @pytest.fixture(au...
TestFirstOrderActivationDeGroote2016
python
sympy__sympy
sympy/functions/special/zeta_functions.py
{ "start": 21000, "end": 21990 }
class ____(DefinedFunction): r""" Riemann Xi function. Examples ======== The Riemann Xi function is closely related to the Riemann zeta function. The zeros of Riemann Xi function are precisely the non-trivial zeros of the zeta function. >>> from sympy import riemann_xi, zeta >>> f...
riemann_xi
python
euske__pdfminer
pdfminer/cmapdb.py
{ "start": 4920, "end": 6490 }
class ____: _cmap_cache = {} _umap_cache = {} class CMapNotFound(CMapError): pass @classmethod def _load_data(klass, name): filename = '%s.marshal.gz' % name logging.info('loading: %r' % name) cmap_paths = (os.environ.get('CMAP_PATH', '/usr/share/pdfminer/'), ...
CMapDB
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bandit/S105.py
{ "start": 632, "end": 1347 }
class ____: password = "s3cr3t" safe = password MyClass.password = "s3cr3t" MyClass._pass = "s3cr3t" MyClass.passwd = "s3cr3t" MyClass.pwd = "s3cr3t" MyClass.secret = "s3cr3t" MyClass.token = "s3cr3t" MyClass.secrete = "s3cr3t" password == "s3cr3t" _pass == "s3cr3t" passwd == "s3cr3t" pwd == "s3cr3t" secret ...
MyClass
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_new_jersey_zip.py
{ "start": 757, "end": 1766 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_new_jersey_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pa...
ColumnValuesToBeValidNewJerseyZip
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/utils/time_window.py
{ "start": 2189, "end": 10468 }
class ____( NamedTuple( "_PersistedTimeWindow", [("start", TimestampWithTimezone), ("end", TimestampWithTimezone)] ) ): """Internal serialized representation of a time interval that is closed at the start and open at the end. """ def __new__( cls, start: TimestampWithTim...
PersistedTimeWindow
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/pslint.py
{ "start": 605, "end": 3211 }
class ____(SanityVersionNeutral): """Sanity test using PSScriptAnalyzer.""" @property def error_code(self) -> t.Optional[str]: """Error code for ansible-test matching the format used by the underlying test program, or None if the program does not use error codes.""" return 'AnsibleTest' ...
PslintTest
python
pennersr__django-allauth
allauth/socialaccount/providers/box/views.py
{ "start": 181, "end": 1066 }
class ____(OAuth2Adapter): provider_id = "box" access_token_url = "https://api.box.com/oauth2/token" # nosec authorize_url = "https://account.box.com/api/oauth2/authorize" profile_url = "https://api.box.com/2.0/users/me" redirect_uri_protocol = None def complete_login(self, request, app, token...
BoxOAuth2Adapter
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 215524, "end": 220200 }
class ____(TestCase): def test_basics(self): extract = mi.extract data = 'abcdefghijklmnopqrstuvwxyz' # Test iterator inputs, increasing and decreasing indices, and repeats. self.assertEqual( list(extract(iter(data), iter([7, 4, 11, 11, 14]))), ['h', 'e', 'l'...
ExtractTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_set_column10.py
{ "start": 315, "end": 2274 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("set_column01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
run-llama__llama_index
llama-index-core/llama_index/core/base/base_multi_modal_retriever.py
{ "start": 330, "end": 1843 }
class ____(BaseRetriever, BaseImageRetriever): """Multi Modal base retriever.""" @abstractmethod def text_retrieve(self, str_or_query_bundle: QueryType) -> List[NodeWithScore]: """ Retrieve text nodes given text query. Implemented by the user. """ @abstractmethod ...
MultiModalRetriever
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink41.py
{ "start": 315, "end": 938 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink41.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workb...
TestCompareXLSXFiles
python
pytorch__pytorch
torch/fx/experimental/meta_tracer.py
{ "start": 4721, "end": 10776 }
class ____(torch.fx.Tracer): allow_insert_stateless_mods: bool = True _TORCH_METHODS_TO_PATCH = ["arange", "zeros", "ones", "full_like", "eye"] def create_proxy( self, kind, target, args, kwargs, name=None, type_expr=None, proxy_factory_fn=No...
MetaTracer
python
kamyu104__LeetCode-Solutions
Python/count-number-of-bad-pairs.py
{ "start": 63, "end": 392 }
class ____(object): def countBadPairs(self, nums): """ :type nums: List[int] :rtype: int """ result = len(nums)*(len(nums)-1)//2 cnt = collections.Counter() for i, x in enumerate(nums): result -= cnt[x-i] cnt[x-i] += 1 return re...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/runtime_representations.py
{ "start": 244, "end": 2339 }
class ____: webserver_url: str dag_id: str run_id: str metadata: dict[str, Any] @property def note(self) -> str: return self.metadata.get("note") or "" @property def dag_handle(self) -> "DagHandle": from dagster_airlift.core.serialization.serialized_data import DagHandl...
DagRun
python
django__django
tests/migrations/test_migrations_plan/0005_fifth.py
{ "start": 121, "end": 413 }
class ____(migrations.Migration): dependencies = [ ("migrations", "0004_fourth"), ] operations = [ migrations.RunPython(migrations.RunPython.noop), migrations.RunPython(grow_tail), migrations.RunPython(feed, migrations.RunPython.noop), ]
Migration
python
getsentry__sentry
src/sentry/hybridcloud/services/tombstone/model.py
{ "start": 280, "end": 360 }
class ____(RpcModel): table_name: str = "" identifier: int = -1
RpcTombstone
python
spyder-ide__spyder
spyder/utils/snippets/nodes.py
{ "start": 5521, "end": 6447 }
class ____(ASTNode): """Node that represents a terminal symbol.""" KIND = NodeKind.LEAF def __init__(self, name='EPSILON', value=''): ASTNode.__init__(self) self.name = name self.value = value def compute_position(self, offset): value = self.text() new_offset, ...
LeafNode
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/sensors/cloud_composer.py
{ "start": 13077, "end": 34096 }
class ____(BaseSensorOperator): """ Waits for a different DAG, task group, or task to complete for a specific composer environment. If both `composer_external_task_group_id` and `composer_external_task_id` are ``None`` (default), the sensor waits for the DAG. Values for `composer_external_task_grou...
CloudComposerExternalTaskSensor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/test_source.py
{ "start": 12900, "end": 52377 }
class ____(GoogleSheetsBaseTest): @HttpMocker() def test_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: GoogleSheetsBaseTest.get_spreadsheet_info_and_sheets(http_mocker, "read_records_meta") GoogleSheetsBaseTest.get_sheet_first_row(http_mocker, "read_records_range") ...
TestSourceRead
python
getsentry__sentry
src/sentry/explore/endpoints/serializers.py
{ "start": 4577, "end": 8786 }
class ____(serializers.Serializer): name = serializers.CharField( required=True, max_length=255, help_text="The user-defined saved query name." ) projects = ListField( child=serializers.IntegerField(), required=False, default=list, help_text="The saved projects filter...
ExploreSavedQuerySerializer
python
doocs__leetcode
solution/2200-2299/2258.Escape the Spreading Fire/Solution.py
{ "start": 0, "end": 2239 }
class ____: def maximumMinutes(self, grid: List[List[int]]) -> int: def spread(q: Deque[int]) -> Deque[int]: nq = deque() while q: i, j = q.popleft() for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m ...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/writeonly.py
{ "start": 16352, "end": 18443 }
class ____(Generic[_T]): """Virtual collection which includes append/remove methods that synchronize into the attribute event system. """ if not TYPE_CHECKING: __slots__ = () instance: _T _from_obj: Tuple[FromClause, ...] def __init__( self, attr: _WriteOnlyAttributeImpl,...
_AbstractCollectionWriter
python
doocs__leetcode
solution/1100-1199/1165.Single-Row Keyboard/Solution.py
{ "start": 0, "end": 251 }
class ____: def calculateTime(self, keyboard: str, word: str) -> int: pos = {c: i for i, c in enumerate(keyboard)} ans = i = 0 for c in word: ans += abs(pos[c] - i) i = pos[c] return ans
Solution
python
ray-project__ray
python/ray/util/annotations.py
{ "start": 122, "end": 2925 }
class ____(Enum): PUBLIC_API = "PublicAPI" DEVELOPER_API = "DeveloperAPI" DEPRECATED = "Deprecated" UNKNOWN = "Unknown" def PublicAPI(*args, **kwargs): """Annotation for documenting public APIs. Public APIs are classes and methods exposed to end users of Ray. If ``stability="alpha"``, th...
AnnotationType
python
PrefectHQ__prefect
tests/server/orchestration/api/test_deployments.py
{ "start": 1412, "end": 41882 }
class ____: async def test_create_oldstyle_deployment( self, session, hosted_api_client, flow, flow_function, storage_document_id, ): data = DeploymentCreate( name="My Deployment", version="mint", flow_id=flow.id, ...
TestCreateDeployment
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 93174, "end": 93250 }
class ____(Unaryop): operation = operator.neg _operator_repr = "-"
Neg
python
huggingface__transformers
src/transformers/models/clipseg/modeling_clipseg.py
{ "start": 12115, "end": 15419 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Union[CLIPSegVisionConfig, CLIPSegTextConfig]): super().__init__() self.config = config self.embed_dim = config.hidden_size self.num_heads = config.num_attention...
CLIPSegAttention
python
getsentry__sentry
src/sentry/mail/analytics.py
{ "start": 173, "end": 277 }
class ____(BaseNotificationSent): pass analytics.register(EmailNotificationSent)
EmailNotificationSent
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 109814, "end": 110944 }
class ____(Request): """ Convert company models to public :param ids: Ids of the models to convert :type ids: Sequence[str] """ _service = "models" _action = "make_public" _version = "2.23" _schema = { "definitions": {}, "properties": { "ids": { ...
MakePublicRequest
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/base_asset_operator.py
{ "start": 1185, "end": 13751 }
class ____(BaseOperator, ABC): """Interface for an operator which materializes dagster assets. This operator needs to implement the following methods: - get_dagster_session: Returns a requests session that can be used to make requests to the Dagster API. This is where any additional authen...
BaseDagsterAssetsOperator
python
sphinx-doc__sphinx
sphinx/transforms/__init__.py
{ "start": 11912, "end": 12242 }
class ____(ContentsFilter): """Used with BuildEnvironment.add_toc_from() to discard cross-file links within table-of-contents link nodes. """ visit_pending_xref = ContentsFilter.ignore_node_but_process_children def visit_image(self, node: nodes.image) -> None: raise nodes.SkipNode
SphinxContentsFilter
python
pyca__cryptography
tests/hazmat/primitives/test_dsa.py
{ "start": 26357, "end": 28724 }
class ____: def test_parameter_numbers_eq(self): param = dsa.DSAParameterNumbers(1, 2, 3) assert param == dsa.DSAParameterNumbers(1, 2, 3) def test_parameter_numbers_ne(self): param = dsa.DSAParameterNumbers(1, 2, 3) assert param != dsa.DSAParameterNumbers(1, 2, 4) asser...
TestDSANumberEquality
python
ray-project__ray
python/ray/tests/test_runtime_env_strong_type.py
{ "start": 190, "end": 261 }
class ____: nfield1: List[str] nfield2: bool @dataclass
ValueType
python
anthropics__anthropic-sdk-python
src/anthropic/resources/messages/messages.py
{ "start": 2432, "end": 54618 }
class ____(SyncAPIResource): @cached_property def batches(self) -> Batches: return Batches(self._client) @cached_property def with_raw_response(self) -> MessagesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response...
Messages
python
python-jsonschema__jsonschema
jsonschema/tests/test_validators.py
{ "start": 67115, "end": 67298 }
class ____(ValidatorTestMixin, TestCase): Validator = validators.Draft7Validator valid: tuple[dict, dict] = ({}, {}) invalid = {"type": "integer"}, "foo"
TestDraft7Validator
python
walkccc__LeetCode
solutions/3558. Number of Ways to Assign Edge Weights I/3558.py
{ "start": 0, "end": 538 }
class ____: def assignEdgeWeights(self, edges: list[list[int]]) -> int: MOD = 1_000_000_007 n = len(edges) + 1 graph = [[] for _ in range(n + 1)] for u, v in edges: graph[u].append(v) graph[v].append(u) q = collections.deque([1]) seen = {1} step = 0 while q: for _ ...
Solution
python
great-expectations__great_expectations
tests/datasource/fluent/test_invalid_datasource.py
{ "start": 5546, "end": 10356 }
class ____: def test_connection_raises_informative_error( self, invalid_ds_cfg: dict, invalid_datasource_factory: InvalidDSFactory, ): invalid_ds = invalid_datasource_factory(invalid_ds_cfg) print(invalid_ds) with pytest.raises(TestConnectionError) as conn_err: ...
TestInvalidDatasource
python
openai__openai-python
examples/responses/streaming_tools.py
{ "start": 821, "end": 1264 }
class ____(BaseModel): table_name: Table columns: List[Column] conditions: List[Condition] order_by: OrderBy client = OpenAI() with client.responses.stream( model="gpt-4o-2024-08-06", input="look up all my orders in november of last year that were fulfilled but not delivered on time", too...
Query
python
lepture__authlib
tests/django/test_oauth1/models.py
{ "start": 275, "end": 766 }
class ____(Model): user = ForeignKey(User, on_delete=CASCADE) client_id = CharField(max_length=48, unique=True, db_index=True) client_secret = CharField(max_length=48, blank=True) default_redirect_uri = TextField(blank=False, default="") def get_default_redirect_uri(self): return self.defau...
Client
python
python-openxml__python-docx
tests/oxml/test_xmlchemy.py
{ "start": 571, "end": 3801 }
class ____: def it_can_find_the_first_of_its_children_named_in_a_sequence(self, first_fixture): element, tagnames, matching_child = first_fixture assert element.first_child_found_in(*tagnames) is matching_child def it_can_insert_an_element_before_named_successors(self, insert_fixture): ...
DescribeBaseOxmlElement
python
falconry__falcon
tests/test_typing.py
{ "start": 296, "end": 365 }
class ____(falcon.Request): context_type = RichContext
FancyRequest
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 302765, "end": 304784 }
class ____(rv_continuous): r"""A skewed Cauchy random variable. %(before_notes)s See Also -------- cauchy : Cauchy distribution Notes ----- The probability density function for `skewcauchy` is: .. math:: f(x) = \frac{1}{\pi \left(\frac{x^2}{\left(a\, \text{sign}(x) + 1 ...
skewcauchy_gen
python
ansible__ansible
lib/ansible/_internal/_yaml/_dumper.py
{ "start": 999, "end": 2601 }
class ____(_BaseDumper): """A simple stub class that allows us to add representers for our custom types.""" @classmethod def _register_representers(cls) -> None: cls.add_multi_representer(AnsibleTaggedObject, cls.represent_ansible_tagged_object) cls.add_multi_representer(Tripwire, cls.repre...
AnsibleDumper
python
coleifer__peewee
tests/libs/mock.py
{ "start": 31066, "end": 34319 }
class ____(CallableMixin, NonCallableMock): """ Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock...
Mock
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 492370, "end": 495282 }
class ____(ExprNode): # C++ typeid operator applied to a type or variable # # operand ExprNode # arg_type ExprNode # is_variable boolean subexprs = ['operand'] arg_type = None is_variable = None is_temp = 1 def get_type_info_type(self, env): env_module...
TypeidNode
python
Lightning-AI__lightning
src/lightning/fabric/fabric.py
{ "start": 3085, "end": 56963 }
class ____: r"""Fabric accelerates your PyTorch training or inference code with minimal changes required. Key Features: - Automatic placement of models and data onto the device. - Automatic support for mixed and double precision (smaller memory footprint). - Seamless switching between h...
Fabric
python
airbytehq__airbyte
airbyte-integrations/connectors/source-gcs/source_gcs/config.py
{ "start": 348, "end": 1059 }
class ____(BaseModel): class Config(OneOfOptionConfig): title = "Authenticate via Google (OAuth)" auth_type: Literal["Client"] = Field("Client", const=True) client_id: str = Field( title="Client ID", description="Client ID", airbyte_secret=True, ) client_secret: str ...
OAuthCredentials
python
bokeh__bokeh
tests/unit/bokeh/document/test_events__document.py
{ "start": 5170, "end": 8391 }
class ____: def test_init_defaults(self) -> None: doc = Document() e = bde.ModelChangedEvent(doc, "model", "attr", "new") assert e.document == doc assert e.setter is None assert e.callback_invoker is None assert e.model == "model" assert e.attr == "attr" ...
TestModelChangedEvent
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_legacy_class_based/_sentinels.py
{ "start": 335, "end": 627 }
class ____: """A special value for :exclude-members: that never matches to any member.""" def __contains__(self, item: Any) -> bool: return False ALL = _All() EMPTY = _Empty() UNINITIALIZED_ATTR = object() INSTANCEATTR = object() SLOTSATTR = object() SUPPRESS = object()
_Empty
python
python__mypy
mypy/nodes.py
{ "start": 40030, "end": 46975 }
class ____(SymbolNode): """A variable. It can refer to global/local variable or a data attribute. """ __slots__ = ( "_name", "_fullname", "info", "type", "setter_type", "final_value", "is_self", "is_cls", "is_ready", "is_i...
Var
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/record/__init__.py
{ "start": 13176, "end": 16822 }
class ____: """Marker class to be used when overriding new in @record_custom classes to prevent type errors when calling super().__new__. """ if TYPE_CHECKING: def __new__(cls, **kwargs) -> Self: ... # let type checker know these objects are sortable (by way of being a namedtuple) ...
IHaveNew
python
django__django
django/core/serializers/base.py
{ "start": 7162, "end": 12645 }
class ____: """ A deserialized model. Basically a container for holding the pre-saved deserialized data along with the many-to-many data saved with the object. Call ``save()`` to save the object (with the many-to-many data) to the database; call ``save(save_m2m=False)`` to save just the object...
DeserializedObject
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/cloud_batch.py
{ "start": 6740, "end": 8287 }
class ____(GoogleBaseHook): """ Async hook for the Google Cloud Batch service. :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to ge...
CloudBatchAsyncHook
python
justquick__django-activity-stream
actstream/drf/serializers.py
{ "start": 3390, "end": 3635 }
class ____(DEFAULT_SERIALIZER): """ Serializer for actstream.Follow models in the "following" activity feeds """ follow_object = get_grf() class Meta: model = Follow fields = ['follow_object']
FollowingSerializer
python
pytorch__pytorch
torch/_higher_order_ops/wrap.py
{ "start": 6859, "end": 14663 }
class ____(HigherOrderOperator): """ This operator is supposed to be used only with torch.compile stack. This accepts a Fx graph module which needs to be checkpointed. This operator adds "recomputable" tag to the nodes of the Fx graph that should be recomputed. The goal is to: 1. Avoid using Dy...
TagActivationCheckpoint
python
tensorflow__tensorflow
tensorflow/python/autograph/tests/call_to_named_tuple_test.py
{ "start": 1032, "end": 1227 }
class ____(collections.namedtuple('TestNamedTuple', ('a',))): def foo(self): return self.a + 1 def namedtuple_subclass(x): nt = NamedTupleSubclass(x) return nt.foo()
NamedTupleSubclass
python
pypa__warehouse
tests/unit/legacy/api/xmlrpc/test_cache.py
{ "start": 945, "end": 2598 }
class ____: def test_redis_cache(self, monkeypatch): strict_redis_obj = pretend.stub() strict_redis_cls = pretend.stub( from_url=pretend.call_recorder(lambda url, db=None: strict_redis_obj) ) monkeypatch.setattr(redis, "StrictRedis", strict_redis_cls) redis_lru_o...
TestRedisXMLRPCCache
python
jazzband__django-oauth-toolkit
oauth2_provider/admin.py
{ "start": 1688, "end": 2724 }
class ____(admin.ModelAdmin): list_display = ("token", "user", "application") raw_id_fields = ("user", "access_token") search_fields = ("token",) + (("user__email",) if has_email else ()) list_filter = ("application",) application_model = get_application_model() access_token_model = get_access_token_m...
RefreshTokenAdmin
python
django-extensions__django-extensions
tests/management/commands/test_sqlcreate.py
{ "start": 1166, "end": 5200 }
class ____(TestCase): """Tests for sqlcreate command.""" @override_settings(DATABASES={"default": MYSQL_DATABASE_SETTINGS}) @patch("sys.stderr", new_callable=StringIO) @patch("sys.stdout", new_callable=StringIO) @patch("django_extensions.management.commands.sqlcreate.socket") def test_should_pr...
SqlCreateTests
python
scipy__scipy
scipy/_lib/_docscrape.py
{ "start": 19424, "end": 23807 }
class ____(NumpyDocString): extra_public_methods = ["__call__"] def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None): if not inspect.isclass(cls) and cls is not None: raise ValueError(f"Expected a class or None, but got {cls!r}") self._cls = cls ...
ClassDoc
python
pypa__warehouse
tests/unit/admin/views/test_prohibited_project_names.py
{ "start": 2671, "end": 4288 }
class ____: def test_no_project(self): request = pretend.stub(GET={}) with pytest.raises(HTTPBadRequest): views.confirm_prohibited_project_names(request) def test_nothing_to_delete(self, db_request): db_request.GET["project"] = "foo" result = views.confirm_prohibite...
TestConfirmProhibitedProjectName
python
ray-project__ray
python/ray/_private/accelerators/npu.py
{ "start": 354, "end": 2879 }
class ____(AcceleratorManager): """Ascend NPU accelerators.""" @staticmethod def get_resource_name() -> str: return "NPU" @staticmethod def get_visible_accelerator_ids_env_var() -> str: return ASCEND_RT_VISIBLE_DEVICES_ENV_VAR @staticmethod def get_current_process_visible_...
NPUAcceleratorManager
python
tornadoweb__tornado
tornado/test/websocket_test.py
{ "start": 27539, "end": 28067 }
class ____(WebSocketBaseTestCase): def get_app(self): class PingHandler(TestWebSocketHandler): def on_ping(self, data): self.write_message("got ping") return Application([("/", PingHandler)]) @gen_test def test_client_ping(self): ws = yield self.ws_conne...
ClientPeriodicPingTest