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
walkccc__LeetCode
solutions/2769. Find the Maximum Achievable Number/2769.py
{ "start": 0, "end": 99 }
class ____: def theMaximumAchievableX(self, num: int, t: int) -> int: return num + 2 * t
Solution
python
matplotlib__matplotlib
lib/matplotlib/patches.py
{ "start": 58935, "end": 64095 }
class ____(Patch): """ An elliptical annulus. """ @_docstring.interpd def __init__(self, xy, r, width, angle=0.0, **kwargs): """ Parameters ---------- xy : (float, float) xy coordinates of annulus centre. r : float or (float, float) Th...
Annulus
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol9.py
{ "start": 120, "end": 192 }
class ____: def __call__(self, v: int): print("Received", v)
A
python
pytorch__pytorch
torch/_dynamo/test_case.py
{ "start": 4021, "end": 8571 }
class ____(TestCase): """ Test class for CPython tests located in "test/dynamo/CPython/Py_version/*". This class enables specific features that are disabled by default, such as tracing through unittest methods. """ _stack: contextlib.ExitStack dynamo_strict_nopython = True # Restore o...
CPythonTestCase
python
PyCQA__pylint
doc/data/messages/i/invalid-enum-extension/bad.py
{ "start": 75, "end": 137 }
class ____(Color): # [invalid-enum-extension] APPLE = 3
Fruit
python
huggingface__transformers
src/transformers/models/glm4v_moe/modular_glm4v_moe.py
{ "start": 26698, "end": 29667 }
class ____(Glm4vForConditionalGeneration): @auto_docstring @check_model_inputs() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[...
Glm4vMoeForConditionalGeneration
python
python__mypy
mypy/refinfo.py
{ "start": 499, "end": 2784 }
class ____(TraverserVisitor): def __init__(self, type_map: dict[Expression, Type]) -> None: super().__init__() self.type_map = type_map self.data: list[dict[str, object]] = [] def visit_name_expr(self, expr: NameExpr) -> None: super().visit_name_expr(expr) self.record_re...
RefInfoVisitor
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 480, "end": 638 }
class ____(NamedModel): line = models.LineStringField(dim=3, srid=4269) class Meta: required_db_features = {"supports_3d_storage"}
Interstate3D
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 95948, "end": 97126 }
class ____(fixtures.TestBase): def test_ascii_to_utf8(self): eq_( compat.decode_backslashreplace(util.b("hello world"), "utf-8"), "hello world", ) def test_utf8_to_utf8(self): eq_( compat.decode_backslashreplace( "some message méil".en...
BackslashReplaceTest
python
openai__openai-python
src/openai/resources/fine_tuning/jobs/checkpoints.py
{ "start": 817, "end": 3612 }
class ____(SyncAPIResource): @cached_property def with_raw_response(self) -> CheckpointsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.gith...
Checkpoints
python
dagster-io__dagster
python_modules/dagster/dagster/_core/snap/dagster_types.py
{ "start": 2302, "end": 3973 }
class ____( NamedTuple( "_DagsterTypeSnap", [ ("kind", DagsterTypeKind), ("key", str), ("name", Optional[str]), ("description", Optional[str]), ("display_name", str), ("is_builtin", bool), ("type_param_keys", Sequenc...
DagsterTypeSnap
python
apache__airflow
helm-tests/tests/helm_tests/apiserver/test_apiserver.py
{ "start": 4215, "end": 5942 }
class ____: """Tests apiserver configmap.""" def test_no_apiserver_config_configmap_by_default(self): docs = render_chart(show_only=["templates/configmaps/api-server-configmap.yaml"]) assert len(docs) == 0 def test_no_apiserver_config_configmap_with_configmap_name(self): docs = ren...
TestApiserverConfigmap
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_detector.py
{ "start": 31883, "end": 35562 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.group = self.create_group(project=self.project) self.detector = self.create_detector(project=self.project, type=MetricIssue.slug) self.error_detector = self.create_detecto...
TestGetDetectorsForEvent
python
kamyu104__LeetCode-Solutions
Python/find-the-count-of-monotonic-pairs-i.py
{ "start": 1374, "end": 2350 }
class ____(object): def countOfPairs(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 dp = [int(i <= nums[0]) for i in xrange(max(nums)+1)] # dp[j]: numbers of arr1, which is of length i+1 and arr1[i] is j for i in xrange(1, len(nums)): ...
Solution2
python
kamyu104__LeetCode-Solutions
Python/longest-balanced-substring-i.py
{ "start": 91, "end": 638 }
class ____(object): def longestBalanced(self, s): """ :type s: str :rtype: int """ result = 0 for i in xrange(len(s)): cnt = collections.defaultdict(int) mx = 0 for j in xrange(i, len(s)): cnt[s[j]] += 1 ...
Solution
python
getsentry__sentry
src/sentry/api/serializers/snuba.py
{ "start": 1631, "end": 5292 }
class ____: """ Serializer for time-series Snuba data. """ def __init__(self, organization, lookup, user): self.organization = organization self.lookup = lookup self.user = user def get_attrs(self, item_list): if self.lookup is None: return item_list ...
SnubaTSResultSerializer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1328110, "end": 1328412 }
class ____(sgqlc.types.Type, ProjectV2ItemFieldValueCommon, Node): """The value of a date field in a Project item.""" __schema__ = github_schema __field_names__ = ("date",) date = sgqlc.types.Field(Date, graphql_name="date") """Date value for the field"""
ProjectV2ItemFieldDateValue
python
instagram__MonkeyType
tests/test_typing.py
{ "start": 27905, "end": 29751 }
class ____: class Base: pass class Intermediate(Base): pass class FirstDerived(Intermediate): pass class SecondDerived(Intermediate): pass class Unrelated: pass class MoreDerived(SecondDerived): pass @pytest.mark.parametrize( 'typ...
TestRewriteMostSpecificCommonBase
python
Pylons__pyramid
tests/test_security.py
{ "start": 9492, "end": 9929 }
class ____(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def test_identity_no_security_policy(self): request = _makeRequest() self.assertEqual(request.identity, None) def test_identity(self): request = _makeRequest(...
TestIdentity
python
GoogleCloudPlatform__python-docs-samples
dataflow/conftest.py
{ "start": 11036, "end": 30994 }
class ____: uuid: str = UUID project: str = PROJECT region: str = REGION @staticmethod def hyphen_name(name: str) -> str: unique_name = f"{name}-py{PYTHON_VERSION}-{UUID}" return HYPHEN_NAME_RE.sub("-", unique_name) @staticmethod def underscore_name(name: str) -> str: ...
Utils
python
google__pytype
pytype/rewrite/stack_test.py
{ "start": 96, "end": 2998 }
class ____(test_utils.ContextfulTestBase): def _var(self, val): return self.ctx.consts[val].to_variable() def test_push(self): s = stack.DataStack() var = self._var(5) s.push(var) self.assertEqual(s._stack, [var]) def test_pop(self): s = stack.DataStack() var = self._var(5) var ...
DataStackTest
python
sdispater__pendulum
src/pendulum/tz/exceptions.py
{ "start": 430, "end": 636 }
class ____(TimezoneError): message = "The datetime {} is ambiguous." def __init__(self, dt: datetime) -> None: message = self.message.format(dt) super().__init__(message)
AmbiguousTime
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 5740, "end": 6148 }
class ____: def setup(self): self.df = DataFrame( { "a": np.arange(1_000_000, dtype=np.int32), "b": np.arange(1_000_000, dtype=np.int64), "c": np.arange(1_000_000, dtype=float), } ).astype({"a": "category", "b": "category"}) ...
CategoricalLevel
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/input_percentage_width.py
{ "start": 112, "end": 753 }
class ____(App[None]): CSS = """ Screen > *, Screen > *:focus { width: 50%; height: 1fr; border: solid red; } App #ruler { width: 1fr; height: 1; border: none; } """ def compose(self) -> ComposeResult: yield Label("[reverse]0123456789[...
InputVsTextArea
python
ray-project__ray
python/ray/llm/_internal/serve/serving_patterns/prefill_decode/builder.py
{ "start": 1396, "end": 5908 }
class ____(BaseModelExtended): """Schema for P/D serving args.""" prefill_config: Union[str, dict, LLMConfig] decode_config: Union[str, dict, LLMConfig] proxy_cls_config: Union[dict, ProxyClsConfig] = Field( default_factory=ProxyClsConfig, description="The configuration for the proxy cl...
PDServingArgs
python
google__pytype
pytype/tests/test_generic2.py
{ "start": 28457, "end": 40417 }
class ____(test_base.BaseTest): """Tests for User-defined Generic Type.""" def test_type_parameter_duplicated(self): with test_utils.Tempdir() as d: d.create_file( "a.pyi", """ from typing import Generic, Dict T = TypeVar("T") class A(Dict[T, T], Generic[T]): p...
GenericFeatureTest
python
pytorch__pytorch
test/inductor/test_provenance_tracing.py
{ "start": 20303, "end": 20603 }
class ____(logging.Filter): def filter(self, record): if "artifact" in record.metadata: return ( record.metadata["artifact"]["name"] == "inductor_provenance_tracking_kernel_stack_traces" ) return False
ProvenanceArtifactFilter
python
realpython__materials
python-mutable-immutable/person.py
{ "start": 71, "end": 329 }
class ____(Person): def __init__(self, name, major): super().__init__(name) self.major = major john = Student("John", "Computer Science") print(type(john)) john.__class__ = Person print(john.name) print(john.major) print(type(john))
Student
python
mlflow__mlflow
mlflow/pyfunc/model.py
{ "start": 56486, "end": 61469 }
class ____: """ Wrapper class that creates a predict function such that predict(model_input: pd.DataFrame) -> model's output as pd.DataFrame (pandas DataFrame) """ def __init__(self, python_model: PythonModel, context, signature): """ Args: python_model: An instance of a...
_PythonModelPyfuncWrapper
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 259558, "end": 268709 }
class ____: # fitting assumes continuous parameters skip = ['ncf', 'ksone', 'kstwo', 'irwinhall'] def setup_method(self): self.rng = np.random.default_rng(4522425749) # skip these b/c deprecated, or only loc and scale arguments fitSkipNonFinite = ['expon', 'norm', 'uniform', 'irwinhall'] ...
TestFitMethod
python
PyCQA__pylint
tests/functional/a/arguments.py
{ "start": 3527, "end": 3900 }
class ____: """ lambda needs Test instance as first argument """ lam = lambda self, icon: (self, icon) def test(self): self.lam(42) self.lam() # [no-value-for-parameter] self.lam(1, 2, 3) # [too-many-function-args] Test().lam() # [no-value-for-parameter] # Don't emit a redundant-k...
Test
python
python__mypy
mypy/nodes.py
{ "start": 99054, "end": 99430 }
class ____(Expression): """Ducktype class decorator expression _promote(...).""" __slots__ = ("type",) type: mypy.types.ProperType def __init__(self, type: mypy.types.ProperType) -> None: super().__init__() self.type = type def accept(self, visitor: ExpressionVisitor[T]) -> T: ...
PromoteExpr
python
streamlit__streamlit
lib/tests/streamlit/runtime/memory_session_storage_test.py
{ "start": 815, "end": 2435 }
class ____(unittest.TestCase): """Test MemorySessionStorage. These tests are intentionally extremely simple to ensure that we don't just end up testing cachetools.TTLCache. We try to just verify that we've wrapped TTLCache correctly, and in particular we avoid testing cache expiry functionality. ""...
MemorySessionStorageTest
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 128363, "end": 130365 }
class ____(Response): """ Response of events.get_task_single_value_metrics endpoint. :param tasks: Single value metrics grouped by task :type tasks: Sequence[dict] """ _service = "events" _action = "get_task_single_value_metrics" _version = "2.20" _schema = { "definitions":...
GetTaskSingleValueMetricsResponse
python
scipy__scipy
scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
{ "start": 1287, "end": 26594 }
class ____: """The Hessian of the Lagrangian as LinearOperator. The Lagrangian is computed as the objective function plus all the constraints multiplied with some numbers (Lagrange multipliers). """ def __init__(self, n, objective_hess, constraints_hess): self.n = n self.objective_h...
LagrangianHessian
python
gevent__gevent
src/gevent/tests/test__fileobject.py
{ "start": 16313, "end": 16919 }
class ____(CleanupMixin, unittest.TestCase): def test_default_mode_writes_linesep(self): # See https://github.com/gevent/gevent/issues/1282 # libuv 1.x interferes with the default line mode on # Windows. # First, make sure we initialize gevent gevent.get_hub() filen...
TestTextMode
python
un33k__django-uuslug
uuslug/tests/tests.py
{ "start": 469, "end": 4253 }
class ____(TestCase): """Tests for Slug - Unicode""" def test_manager(self): txt = "This is a test ---" r = slugify(txt) self.assertEqual(r, "this-is-a-test") txt = "This -- is a ## test ---" r = slugify(txt) self.assertEqual(r, "this-is-a-test") txt =...
SlugUnicodeTestCase
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/test_trainer.py
{ "start": 65610, "end": 66008 }
class ____(BoringModel): def on_train_start(self) -> None: raise Exception("Error during train") def on_validation_start(self) -> None: raise Exception("Error during validation") def on_test_start(self) -> None: raise Exception("Error during test") def on_predict_start(self) -...
TrainerStagesErrorsModel
python
numba__numba
numba/tests/test_sort.py
{ "start": 35892, "end": 40006 }
class ____(MemoryLeakMixin, TestCase): def test_01(self): a = [3, 1, 4, 1, 5, 9] @njit def external_key(z): return 1. / z @njit def foo(x, key=None): new_x = x[:] new_x.sort(key=key) return sorted(x[:], key=key), new_x ...
TestSortSlashSortedWithKey
python
ray-project__ray
python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_tree.py
{ "start": 26034, "end": 26387 }
class ____(PrefixTree): def getattr(self, attribute: str) -> Any: """ Get an attribute of the PrefixTree. Note: This method is intended to be used only in tests. """ return getattr(self, attribute) def setattr(self, attribute: str, value: Any) -> None: setattr(se...
PrefixTreeActor
python
spyder-ide__spyder
spyder/config/user.py
{ "start": 35850, "end": 36016 }
class ____(MultiUserConfig): """Plugin configuration handler with multifile support.""" def get_config_class(self): return PluginConfig
PluginMultiConfig
python
celery__celery
t/unit/backends/test_base.py
{ "start": 13423, "end": 13907 }
class ____(BaseBackend): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._data = {'can-delete': {'result': 'foo'}} def _restore_group(self, group_id): if group_id == 'exists': return {'result': 'group'} def _get_task_meta_for(self, task_id):...
DictBackend
python
PyCQA__pylint
tests/functional/s/super/super_checks.py
{ "start": 2283, "end": 3461 }
class ____(BaseClass): def __init__(self): super(InvalidSuperChecks, self).not_a_method() # [not-callable] super(InvalidSuperChecks, self).attribute_error() # [no-member] super(InvalidSuperChecks, self).function(42) super(InvalidSuperChecks, self).function() # [no-value-for-paramete...
InvalidSuperChecks
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 145227, "end": 157411 }
class ____(HasSchemaAttr, IdentityOptions, DefaultGenerator): """Represents a named database sequence. The :class:`.Sequence` object represents the name and configurational parameters of a database sequence. It also represents a construct that can be "executed" by a SQLAlchemy :class:`_engine.Engine`...
Sequence
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 88733, "end": 89049 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING AutoModelForVideoClassification = auto_class_update(AutoModelForVideoClassification, head_doc="video classification") # Private on purpose, the public class will add the deprecation warnings.
AutoModelForVideoClassification
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/groups_response_builder.py
{ "start": 228, "end": 460 }
class ____(HttpResponseBuilder): @classmethod def groups_response(cls) -> "GroupsResponseBuilder": return cls(find_template("groups", __file__), FieldPath("groups"), CursorBasedPaginationStrategy())
GroupsResponseBuilder
python
django__django
tests/db_functions/math/test_degrees.py
{ "start": 272, "end": 2476 }
class ____(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_degrees=Degrees("normal")).first() self.assertIsNone(obj.null_degrees) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) ...
DegreesTests
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 9002, "end": 9089 }
class ____(Iterator[str]): def __iter__(self: Self) -> Self: ...
GoodIterator
python
encode__django-rest-framework
tests/test_request.py
{ "start": 13341, "end": 13455 }
class ____(TestCase): def test_request_is_subscriptable(self): assert Request is Request["foo"]
TestTyping
python
simonw__sqlite-utils
sqlite_utils/db.py
{ "start": 6207, "end": 6264 }
class ____(Exception): "Record not found"
NotFoundError
python
Textualize__rich
rich/__main__.py
{ "start": 447, "end": 7592 }
class ____: def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: for y in range(0, 5): for x in range(options.max_width): h = x / options.max_width l = 0.1 + ((y / 5) * 0.7) r1, g1, b1 = colorsys.hls_...
ColorBox
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 163087, "end": 168126 }
class ____(DataplexCatalogBaseOperator): r""" List Entry resources. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataplexCatalogListEntriesOperator` :param entry_group_id: Required. EntryGroup resource name to which creat...
DataplexCatalogListEntriesOperator
python
pytorch__pytorch
torch/_dynamo/output_graph.py
{ "start": 121419, "end": 166759 }
class ____(fx.Tracer): """ Holds an FX graph that is being traced. OutputGraph owns a SubgraphTracer and the separation of responsibilities is that SubgraphTracer is responsible for building the graph while OutputGraph is responsible for compiling and executing the graph. """ def __init__( ...
SubgraphTracer
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/roles.py
{ "start": 1412, "end": 6421 }
class ____: """Service layer for FAB Auth Manager role operations (create, validate, sync).""" @staticmethod def _check_action_and_resource( security_manager: FabAirflowSecurityManagerOverride, perms: list[tuple[str, str]], ) -> None: for action_name, resource_name in perms: ...
FABAuthManagerRoles
python
facelessuser__pymdown-extensions
tests/test_extensions/test_snippets.py
{ "start": 227, "end": 2003 }
class ____(util.MdCase): """Test snippet cases.""" extension = [ 'pymdownx.snippets', 'pymdownx.superfences' ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'dedent_subsections': True } } def test_d...
TestSnippetDedent
python
pypa__pip
src/pip/_internal/models/direct_url.py
{ "start": 3968, "end": 4421 }
class ____: name: ClassVar = "dir_info" editable: bool = False @classmethod def _from_dict(cls, d: dict[str, Any] | None) -> DirInfo | None: if d is None: return None return cls(editable=_get_required(d, bool, "editable", default=False)) def _to_dict(self) -> dict[str,...
DirInfo
python
tensorflow__tensorflow
tensorflow/compiler/tests/scan_ops_test.py
{ "start": 5129, "end": 8174 }
class ____(xla_test.XLATestCase): valid_dtypes = [np.float32, np.float64] def axis_dtypes(self): return set(self.int_types).intersection([np.int32, np.int64]) def _compare(self, x, axis, exclusive, reverse): def neginf_like(x): return -np.inf * np.ones_like(x) np_out = handle_options(np.log...
CumulativeLogSumExpTest
python
getsentry__sentry
tests/sentry/integrations/bitbucket/test_webhook.py
{ "start": 6569, "end": 8839 }
class ____(WebhookBaseTest): method = "post" def setUp(self) -> None: super().setUp() with assume_test_silo_mode(SiloMode.CONTROL): integration = self.create_provider_integration( provider="bitbucket", external_id="bitbucket_external_id", ...
WebhookSignatureTest
python
jazzband__django-pipeline
pipeline/compressors/csshtmljsminify.py
{ "start": 50, "end": 507 }
class ____(CompressorBase): """ CSS, HTML and JS compressor based on the Python library css-html-js-minify (https://pypi.org/project/css-html-js-minify/). """ def compress_css(self, css): from css_html_js_minify import css_minify # noqa: PLC0415 return css_minify(css) def com...
CssHtmlJsMinifyCompressor
python
xlwings__xlwings
xlwings/pro/_xlcalamine.py
{ "start": 3233, "end": 5157 }
class ____(base_classes.Books): def __init__(self, app): self.app = app self.books = [] self._active = None @property def active(self): return self._active def open(self, filename): filename = str(Path(filename).resolve()) sheet_names = xlwingslib.get_sh...
Books
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 512242, "end": 512853 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("ProjectV2Edge"), graphql_name="edges" ) nodes = sgqlc.typ...
ProjectV2Connection
python
ansible__ansible
lib/ansible/module_utils/facts/network/linux.py
{ "start": 18392, "end": 18549 }
class ____(NetworkCollector): _platform = 'Linux' _fact_class = LinuxNetwork required_facts = set(['distribution', 'platform'])
LinuxNetworkCollector
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/translate.py
{ "start": 5532, "end": 5801 }
class ____(BaseGoogleLink): """ Helper class for constructing Translation Model link. Link for legacy and native models. """ name = "Translation Model" key = "translation_model" format_str = TRANSLATION_NATIVE_MODEL_LINK
TranslationModelLink
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001_py310.py
{ "start": 588, "end": 795 }
class ____(SQLModel): name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) team_id: int | None = Field(default=None, foreign_key="team.id")
HeroBase
python
ansible__ansible
test/integration/targets/ansible-test-container/runme.py
{ "start": 25428, "end": 25575 }
class ____: """Result from execution of a subprocess.""" command: list[str] stdout: str stderr: str status: int
SubprocessResult
python
modin-project__modin
modin/core/dataframe/base/interchange/dataframe_protocol/dataframe.py
{ "start": 1088, "end": 1877 }
class ____(TypedDict): # noqa: GL08 # first element is a buffer containing the column data; # second element is the data buffer's associated dtype data: Tuple["ProtocolBuffer", Any] # first element is a buffer containing mask values indicating missing data; # second element is the mask value buffe...
ColumnBuffers
python
wandb__wandb
wandb/vendor/pygments/lexers/grammar_notation.py
{ "start": 3686, "end": 6328 }
class ____(RegexLexer): """ For `JSpeech Grammar Format <https://www.w3.org/TR/jsgf/>`_ grammars. .. versionadded:: 2.2 """ name = 'JSGF' aliases = ['jsgf'] filenames = ['*.jsgf'] mimetypes = ['application/jsgf', 'application/x-jsgf', 'text/jsgf'] flags = re.MULTILINE | re.UNIC...
JsgfLexer
python
pyca__cryptography
tests/hazmat/primitives/test_rsa.py
{ "start": 77797, "end": 82492 }
class ____: def test_rsa_public_numbers(self): public_numbers = rsa.RSAPublicNumbers(e=1, n=15) assert public_numbers.e == 1 assert public_numbers.n == 15 def test_rsa_private_numbers(self): public_numbers = rsa.RSAPublicNumbers(e=1, n=15) private_numbers = rsa.RSAPrivat...
TestRSANumbers
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 78529, "end": 80159 }
class ____(rv_continuous): r"""A folded normal continuous random variable. %(before_notes)s Notes ----- The probability density function for `foldnorm` is: .. math:: f(x, c) = \sqrt{2/\pi} cosh(c x) \exp(-\frac{x^2+c^2}{2}) for :math:`x \ge 0` and :math:`c \ge 0`. `foldnorm...
foldnorm_gen
python
doocs__leetcode
solution/3100-3199/3178.Find the Child Who Has the Ball After K Seconds/Solution.py
{ "start": 0, "end": 147 }
class ____: def numberOfChild(self, n: int, k: int) -> int: k, mod = divmod(k, n - 1) return n - mod - 1 if k & 1 else mod
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 39255, "end": 39383 }
class ____(AutomationRuleMixin): model = RegexAutomationRule form_class = RegexAutomationRuleForm
RegexAutomationRuleMixin
python
mlflow__mlflow
dev/clint/tests/rules/test_implicit_optional.py
{ "start": 1105, "end": 1261 }
class ____: x: "Optional[str]" = None # Good - stringified with | None good3: "int | None" = None good4: "str | None" = None good5: "int|None" = None
Good1
python
getsentry__sentry
src/sentry/monitors/serializers.py
{ "start": 2699, "end": 3005 }
class ____(TypedDict): name: str status: str isMuted: bool dateCreated: datetime lastCheckIn: datetime nextCheckIn: datetime nextCheckInLatest: datetime activeIncident: MonitorIncidentSerializerResponse | None @register(MonitorEnvironment)
MonitorEnvironmentSerializerResponse
python
kamyu104__LeetCode-Solutions
Python/insert-into-a-binary-search-tree.py
{ "start": 154, "end": 749 }
class ____(object): def insertIntoBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ curr, parent = root, None while curr: parent = curr if val <= curr.val: curr = curr.left el...
Solution
python
wandb__wandb
wandb/sync/sync.py
{ "start": 12499, "end": 16125 }
class ____: def __init__( self, project=None, entity=None, run_id=None, job_type=None, mark_synced=None, app_url=None, view=None, verbose=None, sync_tensorboard=None, log_path=None, append=None, skip_console=None...
SyncManager
python
django__django
tests/update/tests.py
{ "start": 482, "end": 2374 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.a1 = A.objects.create() cls.a2 = A.objects.create() B.objects.bulk_create(B(a=cls.a1) for _ in range(20)) for x in range(20): D.objects.create(a=cls.a1) def test_nonempty_update(self): """ ...
SimpleTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder5.py
{ "start": 1555, "end": 2291 }
class ____: def identity(self, x: T) -> T: return x def test_1(self, f: Callable[[A], X]) -> Callable[[A, B, C], tuple[X, B, C]]: val = triple_1(f, self.identity, self.identity) reveal_type( val, expected_text="(A@test_1, T@identity, T(1)@identity) -> tuple[X@te...
ClassA
python
pytest-dev__pytest-xdist
src/xdist/looponfail.py
{ "start": 5998, "end": 8221 }
class ____: def __init__(self, config: pytest.Config, channel: execnet.Channel) -> None: self.config = config self.channel = channel self.recorded_failures: list[pytest.CollectReport | pytest.TestReport] = [] self.collection_failed = False config.pluginmanager.register(self) ...
WorkerFailSession
python
PrefectHQ__prefect
tests/server/orchestration/api/test_validation.py
{ "start": 7507, "end": 10079 }
class ____: async def test_work_pool_template_validation_empty_block_document( self, session, work_pool, empty_block_doc_ref_template, ): with pytest.raises(HTTPException, match="404: Block not found."): await validate_job_variable_defaults_for_work_pool( ...
TestWorkPoolValidation
python
getsentry__sentry
tests/sentry/replays/tasks/test_delete_replays_bulk.py
{ "start": 624, "end": 12388 }
class ____(APITestCase, ReplaysSnubaTestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project(name="test_project") self.range_start = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(days=1) self.range_end = datetime.datetime.now(tz=datetime.UT...
TestDeleteReplaysBulk
python
facebookresearch__faiss
tests/test_index.py
{ "start": 20047, "end": 21531 }
class ____(unittest.TestCase): def test_recons_exception(self): d = 64 # dimension nb = 1000 rs = np.random.RandomState(1234) xb = rs.rand(nb, d).astype('float32') nlist = 10 quantizer = faiss.IndexFlatL2(d) # the other index index...
TestReconsException
python
walkccc__LeetCode
solutions/1366. Rank Teams by Votes/1366.py
{ "start": 47, "end": 192 }
class ____: name: str rank: list[int] def __init__(self, name: str, teamSize: int): self.name = name self.rank = [0] * teamSize
Team
python
bokeh__bokeh
src/bokeh/models/annotations/dimensional.py
{ "start": 4203, "end": 4462 }
class ____(Metric): """ Model for defining reciprocal metric units of measurement, e.g. ``m^{-1}``. """ # explicit __init__ to support Init signatures def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs)
ReciprocalMetric
python
realpython__materials
python-callable-instances/factorial.py
{ "start": 0, "end": 238 }
class ____: def __init__(self): self.cache = {0: 1, 1: 1} def __call__(self, number): if number not in self.cache: self.cache[number] = number * self(number - 1) return self.cache[number]
Factorial
python
openai__openai-python
src/openai/resources/fine_tuning/fine_tuning.py
{ "start": 4794, "end": 5410 }
class ____: def __init__(self, fine_tuning: AsyncFineTuning) -> None: self._fine_tuning = fine_tuning @cached_property def jobs(self) -> AsyncJobsWithStreamingResponse: return AsyncJobsWithStreamingResponse(self._fine_tuning.jobs) @cached_property def checkpoints(self) -> AsyncChec...
AsyncFineTuningWithStreamingResponse
python
pydata__xarray
asv_bench/benchmarks/dataset_io.py
{ "start": 20150, "end": 20650 }
class ____(IOSingleNetCDF): def setup(self, *args, **kwargs): self.make_ds() self.filepaths = {} for engine in _ENGINES: self.filepaths[engine] = f"test_single_file_with_{engine}.nc" self.ds.to_netcdf(self.filepaths[engine], engine=engine) @parameterized(["engin...
IOReadSingleFile
python
walkccc__LeetCode
solutions/760. Find Anagram Mappings/760.py
{ "start": 0, "end": 269 }
class ____: def anagramMappings(self, nums1: list[int], nums2: list[int]) -> list[int]: numToIndices = collections.defaultdict(list) for i, num in enumerate(nums2): numToIndices[num].append(i) return [numToIndices[num].pop() for num in nums1]
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 9445, "end": 11069 }
class ____(TypedDict): """Dictionary representing the reflected elements corresponding to a :class:`_schema.Column` object. The :class:`.ReflectedColumn` structure is returned by the :class:`.Inspector.get_columns` method. """ name: str """column name""" type: TypeEngine[Any] """...
ReflectedColumn
python
google__jax
jax/experimental/mosaic/gpu/profiler.py
{ "start": 10065, "end": 10422 }
class ____: """Set of IR values referenced by the profiler logic. The profiler logic is implemented using `CustomPrimitiveOp` which requires that all IR values referenced in its body be passed as operands to the op. """ start: ir.Value is_profiling_thread: ir.Value smem_buffer: ir.Value gmem_buffer: i...
_ProfilerCtx
python
django__django
django/contrib/admin/helpers.py
{ "start": 3482, "end": 4702 }
class ____: def __init__(self, form, field, readonly_fields=None, model_admin=None): self.form = form # A django.forms.Form instance if not hasattr(field, "__iter__") or isinstance(field, str): self.fields = [field] else: self.fields = field self.has_visible_...
Fieldline
python
huggingface__transformers
src/transformers/models/rt_detr/modeling_rt_detr.py
{ "start": 69593, "end": 85583 }
class ____(RTDetrPreTrainedModel): def __init__(self, config: RTDetrConfig): super().__init__(config) # Create backbone self.backbone = RTDetrConvEncoder(config) intermediate_channel_sizes = self.backbone.intermediate_channel_sizes # Create encoder input projection layers ...
RTDetrModel
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/sftp_to_gcs.py
{ "start": 1376, "end": 10314 }
class ____(BaseOperator): """ Transfer files to Google Cloud Storage from SFTP server. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:SFTPToGCSOperator` :param source_path: The sftp remote path. This is the specified file p...
SFTPToGCSOperator
python
astropy__astropy
astropy/timeseries/sampled.py
{ "start": 414, "end": 16664 }
class ____(BaseTimeSeries): """ A class to represent time series data in tabular form. `~astropy.timeseries.TimeSeries` provides a class for representing time series as a collection of values of different quantities measured at specific points in time (for time series with finite time bins, see the...
TimeSeries
python
mlflow__mlflow
mlflow/models/evaluation/validation.py
{ "start": 5992, "end": 9517 }
class ____: """ Internal class for representing validation result per metric. Not user facing, used for organizing metric failures and generating failure message more conveniently. Args: metric_name: String representing the metric name candidate_metric_value: value of metric for can...
_MetricValidationResult
python
kamyu104__LeetCode-Solutions
Python/buildings-with-an-ocean-view.py
{ "start": 399, "end": 757 }
class ____(object): def findBuildings(self, heights): """ :type heights: List[int] :rtype: List[int] """ result = [] for i in reversed(xrange(len(heights))): if not result or heights[result[-1]] < heights[i]: result.append(i) result...
Solution2
python
pennersr__django-allauth
tests/apps/socialaccount/providers/shopify/tests.py
{ "start": 2303, "end": 3884 }
class ____(ShopifyTests): """ Shopify embedded apps (that run within an iFrame) require a JS (not server) redirect for starting the oauth2 process. See Also: https://help.shopify.com/api/sdks/embedded-app-sdk/getting-started#oauth """ def login(self, resp_mock, process="login", with_refres...
ShopifyEmbeddedTests
python
pallets__markupsafe
src/markupsafe/__init__.py
{ "start": 12090, "end": 12734 }
class ____: """Helper for :meth:`Markup.__mod__`.""" __slots__ = ("obj", "escape") def __init__(self, obj: t.Any, escape: _TPEscape) -> None: self.obj: t.Any = obj self.escape: _TPEscape = escape def __getitem__(self, key: t.Any, /) -> te.Self: return self.__class__(self.obj[k...
_MarkupEscapeHelper
python
pypa__pip
tests/functional/test_new_resolver.py
{ "start": 26213, "end": 69927 }
class ____: """ Test installing a package that depends the same package with different extras, one listed as required and the other as in extra. """ @pytest.mark.parametrize( "pkg_builder", [ _local_with_setup, _direct_wheel, _wheel_from_index, ...
TestExtraMerge
python
spack__spack
lib/spack/spack/vendor/jsonschema/exceptions.py
{ "start": 3566, "end": 3771 }
class ____(_Error): """ An instance was invalid under a provided schema. """ _word_for_schema_in_error_message = "schema" _word_for_instance_in_error_message = "instance"
ValidationError
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/conditional_languages/package.py
{ "start": 216, "end": 725 }
class ____(Package): """Conditional depends on c/cxx/fortran with a variant for each""" homepage = "https://dev.null" version("1.0") variant("c", default=False, description="depend on c") variant("cxx", default=False, description="depend on cxx") variant("fortran", default=False, description=...
ConditionalLanguages