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
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchSequence1.py
{ "start": 10209, "end": 14282 }
class ____(Protocol): def __lt__(self, __other: Any) -> bool: ... def __le__(self, __other: Any) -> bool: ... SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) def sort(seq: List[SupportsLessThanT]) -> List[SupportsLessThanT]: match seq: case [] | [_]: reveal_...
SupportsLessThan
python
readthedocs__readthedocs.org
readthedocs/forms.py
{ "start": 228, "end": 940 }
class ____(SignupForm): """Custom signup form that includes a checkbox to subscribe to a newsletter.""" receive_newsletter = forms.BooleanField( required=False, label=("Subscribe to our newsletter to get product updates."), ) field_order = [ "email", "username", ...
SignupFormWithNewsletter
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 33325, "end": 33793 }
class ____(BaseModel): type: Literal["RecordFilter"] condition: Optional[str] = Field( "", description="The predicate to filter a record. Records will be removed if evaluated to False.", examples=[ "{{ record['created_at'] >= stream_interval['start_time'] }}", "{{...
RecordFilter
python
kamyu104__LeetCode-Solutions
Python/top-k-frequent-elements.py
{ "start": 2195, "end": 2435 }
class ____(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ return [key for key, _ in collections.Counter(nums).most_common(k)]
Solution3
python
doocs__leetcode
solution/0400-0499/0466.Count The Repetitions/Solution.py
{ "start": 0, "end": 518 }
class ____: def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: n = len(s2) d = {} for i in range(n): cnt = 0 j = i for c in s1: if c == s2[j]: j += 1 if j == n: cn...
Solution
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 37745, "end": 38444 }
class ____: @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("x", Integer), Column("y", Integer), Col...
_CompositeTestBase
python
getsentry__sentry
src/sentry/integrations/jira_server/client.py
{ "start": 1134, "end": 8903 }
class ____(ApiClient): COMMENTS_URL = "/rest/api/2/issue/%s/comment" COMMENT_URL = "/rest/api/2/issue/%s/comment/%s" STATUS_URL = "/rest/api/2/status" CREATE_URL = "/rest/api/2/issue" ISSUE_URL = "/rest/api/2/issue/%s" ISSUE_FIELDS_URL = "/rest/api/2/issue/createmeta/%s/issuetypes/%s" ISSUE_...
JiraServerClient
python
wandb__wandb
wandb/sdk/artifacts/_generated/artifact_version_files.py
{ "start": 522, "end": 654 }
class ____(GQLResult): artifact: Optional[ArtifactVersionFilesProjectArtifactTypeArtifact]
ArtifactVersionFilesProjectArtifactType
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-mongodb/llama_index/readers/mongodb/base.py
{ "start": 248, "end": 7400 }
class ____(BaseReader): """ Simple mongo reader. Concatenates each Mongo doc into Document used by LlamaIndex. Args: host (str): Mongo host. port (int): Mongo port. """ def __init__( self, host: Optional[str] = None, port: Optional[int] = None, ...
SimpleMongoReader
python
doocs__leetcode
solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution.py
{ "start": 0, "end": 188 }
class ____: def minimumPerimeter(self, neededApples: int) -> int: x = 1 while 2 * x * (x + 1) * (2 * x + 1) < neededApples: x += 1 return x * 8
Solution
python
spack__spack
lib/spack/spack/cmd/commands.py
{ "start": 2979, "end": 4216 }
class ____(ArgparseRstWriter): """RST writer tailored for spack documentation.""" def __init__( self, prog: str, out: IO = sys.stdout, aliases: bool = False, documented_commands: Set[str] = set(), rst_levels: Sequence[str] = ["-", "-", "^", "~", ":", "`"], ):...
SpackArgparseRstWriter
python
realpython__materials
python-magic-methods/bitwise_number.py
{ "start": 0, "end": 615 }
class ____: def __init__(self, value): self.value = value def __and__(self, other): return type(self)(self.value & other.value) def __or__(self, other): return type(self)(self.value | other.value) def __xor__(self, other): return type(self)(self.value ^ other.value) ...
BitwiseNumber
python
cherrypy__cherrypy
cherrypy/test/benchmark.py
{ "start": 3864, "end": 3918 }
class ____: """A null HTTP response."""
NullResponse
python
walkccc__LeetCode
solutions/1005. Maximize Sum Of Array After K Negations/1005.py
{ "start": 0, "end": 263 }
class ____: def largestSumAfterKNegations(self, nums: list[int], k: int) -> int: nums.sort() for i, num in enumerate(nums): if num > 0 or k == 0: break nums[i] = -num k -= 1 return sum(nums) - (k % 2) * min(nums) * 2
Solution
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 301714, "end": 307719 }
class ____: def test_logpdf(self): # gh-6217 y = stats.weibull_min.logpdf(0, 1) assert_equal(y, 0) def test_with_maxima_distrib(self): # Tests for weibull_min and weibull_max. # The expected values were computed using the symbolic algebra # program 'maxima' with...
TestWeibull
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 2459, "end": 2604 }
class ____(BuiltinFunctionT): # Base class for nodes which should always be folded _modifiability = Modifiability.CONSTANT
FoldedFunctionT
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/step.py
{ "start": 12167, "end": 16486 }
class ____( # pyright: ignore[reportIncompatibleVariableOverride] NamedTuple( "_UnresolvedCollectExecutionStep", [ ("handle", StepHandle), ("job_name", str), ("step_input_dict", Mapping[str, Union[StepInput, UnresolvedCollectStepInput]]), ("step_outpu...
UnresolvedCollectExecutionStep
python
openai__openai-python
src/openai/types/beta/threads/runs/file_search_tool_call_delta.py
{ "start": 230, "end": 655 }
class ____(BaseModel): file_search: object """For now, this is always going to be an empty object.""" index: int """The index of the tool call in the tool calls array.""" type: Literal["file_search"] """The type of tool call. This is always going to be `file_search` for this type of tool ...
FileSearchToolCallDelta
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_dag_runs.py
{ "start": 7371, "end": 10886 }
class ____: def setup_method(self): clear_db_runs() def teardown_method(self): clear_db_runs() def test_get_count_basic(self, client, session, dag_maker): with dag_maker("test_dag"): pass dag_maker.create_dagrun() session.commit() response = cli...
TestGetDagRunCount
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 187160, "end": 187239 }
class ____(_Int8RangeTests, _RangeTypeRoundTrip): pass
Int8RangeRoundTripTest
python
tensorflow__tensorflow
tensorflow/python/framework/type_spec_test.py
{ "start": 3119, "end": 3237 }
class ____(TwoTensorsSpec): pass @type_spec_registry.register("tf.TwoTensorsSpecVariableSerialize")
TwoTensorsSpecTwin
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_looker.py
{ "start": 1444, "end": 2000 }
class ____: @classmethod def setUpClass(cls): cls.dagbag = DagBag(dag_folder="/dev/null", include_examples=False) cls.dag = DAG(TEST_DAG_ID, default_args={"owner": "airflow", "start_date": DEFAULT_DATE}) def setup_method(self): self.mock_ti = MagicMock() self.mock_context = ...
LookerTestBase
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py
{ "start": 2152, "end": 2767 }
class ____(dg.PipesMessageReader): def __init__( self, message_writer: InProcessPipesMessageWriter, pipes_context: PipesContext, ) -> None: self.message_writer = message_writer self.pipes_context = pipes_context @contextmanager def read_messages(self, handler: Pi...
InProcessMessageReader
python
ray-project__ray
python/ray/llm/_internal/serve/core/configs/openai_api_models.py
{ "start": 2673, "end": 3144 }
class ____(vLLMEmbeddingCompletionRequest): model_config = ConfigDict(arbitrary_types_allowed=True) request_id: str = Field( default_factory=lambda: f"{random_uuid()}", description=( "The request_id related to this request. If the caller does " "not set it, a random_uuid...
EmbeddingCompletionRequest
python
scipy__scipy
scipy/cluster/hierarchy.py
{ "start": 4544, "end": 36707 }
class ____(UserWarning): pass def _warning(s): warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3) def int_floor(arr, xp): # array_api_strict is strict about not allowing `int()` on a float array. # That's typically not needed, here it is - so explicitly convert return int(xp.asar...
ClusterWarning
python
getsentry__sentry
src/sentry/integrations/vercel/integration.py
{ "start": 4008, "end": 7550 }
class ____: """ Builder for creating Vercel environment variable maps. env_var_map = ( VercelEnvVarMapBuilder() .with_organization(organization) .with_project(project) .with_project_key(project_key) .with_auth_token(auth_token) .with_framework(framework) ...
VercelEnvVarMapBuilder
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_legacy_class_based/_documenters.py
{ "start": 41564, "end": 42451 }
class ____(Documenter): """Specialized Documenter subclass for objects on module level (functions, classes, data/constants). """ def resolve_name( self, modname: str | None, parents: Any, path: str, base: str ) -> tuple[str | None, list[str]]: if modname is not None: ret...
ModuleLevelDocumenter
python
django__django
tests/prefetch_related/models.py
{ "start": 5771, "end": 6072 }
class ____(models.Model): class CustomUUIDField(models.UUIDField): def get_prep_value(self, value): return str(value) id = CustomUUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=30) # Models for lookup ordering tests
ArticleCustomUUID
python
getsentry__sentry
src/sentry/apidocs/examples/tags_examples.py
{ "start": 1533, "end": 1929 }
class ____: GROUP_TAGKEY_DETAILS = OpenApiExample( "Return a specific tag's details", value=SIMPLE_TAG_DETAILS, response_only=True, status_codes=["200"], ) GROUP_TAGKEY_VALUES = OpenApiExample( "Return all tag values for a specific tag", value=SIMPLE_TAG_VALU...
TagsExamples
python
pypa__pipenv
pipenv/patched/pip/_internal/commands/debug.py
{ "start": 5407, "end": 7067 }
class ____(Command): """ Display debug information. """ usage = """ %prog <options>""" ignore_require_venv = True def add_options(self) -> None: cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.confi...
DebugCommand
python
Lightning-AI__lightning
examples/pytorch/domain_templates/generative_adversarial_net.py
{ "start": 2851, "end": 7390 }
class ____(LightningModule): """ >>> GAN(img_shape=(1, 8, 8)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE GAN( (generator): Generator( (model): Sequential(...) ) (discriminator): Discriminator( (model): Sequential(...) ) ) """ def __init__( self, ...
GAN
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/faithfulness.py
{ "start": 3738, "end": 7460 }
class ____(BaseEvaluator): """ Faithfulness evaluator. Evaluates whether a response is faithful to the contexts (i.e. whether the response is supported by the contexts or hallucinated.) This evaluator only considers the response string and the list of context strings. Args: raise_erro...
FaithfulnessEvaluator
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 22422, "end": 26962 }
class ____(AggregateFnV2[List[Union[int, float]], float]): """Defines standard deviation aggregation. Uses Welford's online algorithm for numerical stability. This method computes the standard deviation in a single pass. Results may differ slightly from libraries like NumPy or Pandas that use a two-pas...
Std
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 148519, "end": 151250 }
class ____(fixtures.TestBase): __backend__ = True __only_on__ = "postgresql" def test_concatenation(self, connection): coltype = BIT(varying=True) q = select( literal(BitString("1111"), coltype).concat(BitString("0000")) ) r = connection.execute(q).first() ...
BitTests
python
kamyu104__LeetCode-Solutions
Python/flip-equivalent-binary-trees.py
{ "start": 66, "end": 227 }
class ____(object): def __init__(self, x): self.val = x self.left = None self.right = None import collections # bfs solution
TreeNode
python
run-llama__llama_index
llama-index-integrations/output_parsers/llama-index-output-parsers-langchain/llama_index/output_parsers/langchain/base.py
{ "start": 278, "end": 1884 }
class ____(BaseOutputParser): """Langchain output parser.""" def __init__( self, output_parser: "LCOutputParser", format_key: Optional[str] = None ) -> None: """Init params.""" self._output_parser = output_parser self._format_key = format_key def parse(self, output: str...
LangchainOutputParser
python
patrick-kidger__equinox
equinox/_ad.py
{ "start": 31163, "end": 42185 }
class ____: """As `jax.custom_vjp`, but with a nicer interface. Usage is: ```python @equinox.filter_custom_vjp def fn(vjp_arg, *args, **kwargs): # `vjp_arg` is some PyTree of arbitrary Python objects. # `args`, `kwargs` contain arbitrary Python objects. ... return ou...
filter_custom_vjp
python
streamlit__streamlit
lib/tests/streamlit/commands/navigation_test.py
{ "start": 1145, "end": 18531 }
class ____(DeltaGeneratorTestCase): """Test st.navigation""" def test_no_pages(self): """Test that an error is thrown with no pages""" with pytest.raises(StreamlitAPIException): st.navigation([]) def test_single_page(self): """Test that a single page is returned""" ...
NavigationTest
python
astropy__astropy
astropy/samp/standard_profile.py
{ "start": 4801, "end": 5707 }
class ____(socketserver.ThreadingMixIn, SimpleXMLRPCServer): """ Asynchronous multithreaded XMLRPC server. """ def __init__( self, addr, log=None, requestHandler=SAMPSimpleXMLRPCRequestHandler, logRequests=True, allow_none=True, encoding=None, ...
ThreadingXMLRPCServer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/self8.py
{ "start": 291, "end": 551 }
class ____(enum.IntEnum): def __new__(cls, value: int, doc: str) -> Self: member = int.__new__(cls, value) reveal_type(member, expected_text="Self@Enum1") member._value_ = value member.__doc__ = doc return member
Enum1
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_meid.py
{ "start": 1842, "end": 4553 }
class ____(ColumnMapExpectation): """Expect column values to be valid MEID (Mobile Equipment Identifier).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [...
ExpectColumnValuesToBeValidMeid
python
modin-project__modin
modin/core/io/column_stores/parquet_dispatcher.py
{ "start": 10012, "end": 36970 }
class ____(ColumnStoreDispatcher): """Class handles utils for reading `.parquet` files.""" index_regex = re.compile(r"__index_level_\d+__") @classmethod def get_dataset(cls, path, engine, storage_options): """ Retrieve Parquet engine specific Dataset implementation. Parameters...
ParquetDispatcher
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/test_constructors.py
{ "start": 17057, "end": 41029 }
class ____: def test_disallow_dt64_with_weird_unit(self): # GH#25611 dt64 = np.datetime64(1, "500m") msg = "np.datetime64 objects with units containing a multiplier" with pytest.raises(ValueError, match=msg): Timestamp(dt64) def test_weekday_but_no_day_raises(self): ...
TestTimestampConstructors
python
pyparsing__pyparsing
tests/test_unit.py
{ "start": 391811, "end": 392207 }
class ____(TestCase): def runTest(self): Test02_WithoutPackrat.suite_context = Test02_WithoutPackrat.save_suite_context Test02_WithoutPackrat.suite_context.restore() ParserElement.enable_packrat(cache_size_limit=16) # SAVE A NEW SUITE CONTEXT Test02_WithoutPackrat.suite_con...
Test05_EnableBoundedPackratParsing
python
python-pillow__Pillow
Tests/test_core_resources.py
{ "start": 5111, "end": 5995 }
class ____: def teardown_method(self) -> None: # Restore default values Image.core.set_alignment(1) Image.core.set_block_size(1024 * 1024) Image.core.set_blocks_max(0) Image.core.clear_cache() def test_units(self) -> None: Image._apply_env_variables({"PILLOW_BLOC...
TestEnvVars
python
pola-rs__polars
py-polars/tests/unit/io/test_scan_row_deletion.py
{ "start": 629, "end": 13023 }
class ____: # noqa: D101 def __init__(self, *, tmp_path: Path) -> None: self.tmp_path = tmp_path self.i = 0 def __call__(self, positions: pl.Series) -> str: path = self.tmp_path / f"{self.i}" ( positions.alias("pos") .to_frame() .select(pl.l...
WritePositionDeletes
python
pytorch__pytorch
torchgen/api/types/signatures.py
{ "start": 6972, "end": 9065 }
class ____: # The schema this signature is derived from func: FunctionSchema # Allows you to prepend an arbitrary prefix to the signature name. # This is useful for parts of the codegen that generate wrappers around kernels, # and need to avoid naming collisions. prefix: str = "" symint: b...
DispatcherSignature
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_text_editor_code_execution_view_result_block_param.py
{ "start": 275, "end": 603 }
class ____(TypedDict, total=False): content: Required[str] file_type: Required[Literal["text", "image", "pdf"]] type: Required[Literal["text_editor_code_execution_view_result"]] num_lines: Optional[int] start_line: Optional[int] total_lines: Optional[int]
BetaTextEditorCodeExecutionViewResultBlockParam
python
huggingface__transformers
tests/models/x_clip/test_modeling_x_clip.py
{ "start": 11536, "end": 14756 }
class ____: def __init__( self, parent, batch_size=8, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37,...
XCLIPTextModelTester
python
django__django
tests/constraints/models.py
{ "start": 86, "end": 982 }
class ____(models.Model): price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) unit = models.CharField(max_length=15, null=True) class Meta: required_db_features = { "supports_table_check_constraints", } constraints = [ ...
Product
python
Pylons__pyramid
docs/tutorials/wiki/src/tests/tests/test_views.py
{ "start": 2219, "end": 3012 }
class ____: def _callFUT(self, context, request): from tutorial.views.default import edit_page return edit_page(context, request) def test_it_notsubmitted(self): context = testing.DummyResource() request = testing.DummyRequest() info = self._callFUT(context, request) ...
Test_edit_page
python
numba__llvmlite
llvmlite/binding/ffi.py
{ "start": 3622, "end": 4029 }
class ____: def __init__(self, context): self._context = context def __enter__(self): return self._context.__enter__() def __exit__(self, exc_type, exc_value, traceback): try: return self._context.__exit__(exc_type, exc_value, traceback) except PermissionError: ...
_suppress_cleanup_errors
python
sympy__sympy
sympy/polys/multivariate_resultants.py
{ "start": 871, "end": 8257 }
class ____(): """ A class for retrieving the Dixon's resultant of a multivariate system. Examples ======== >>> from sympy import symbols >>> from sympy.polys.multivariate_resultants import DixonResultant >>> x, y = symbols('x, y') >>> p = x + y >>> q = x ** 2 + y ** 3 >>>...
DixonResultant
python
pytorch__pytorch
test/test_scaled_matmul_cuda.py
{ "start": 21942, "end": 100422 }
class ____(TestCase): def _test_tautological_mm(self, device: str = "cuda", x_dtype: torch.dtype = e4m3_type, y_dtype: torch.dtype = e4m3_type, out_dtype: Optional[torch.dtype] = None, size: int ...
TestFP8Matmul
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py
{ "start": 22175, "end": 25877 }
class ____(CloudSQLBaseOperator): """ Clone an instance to a target instance. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudSQLCloneInstanceOperator` :param instance: Database instance ID to be cloned. This does not i...
CloudSQLCloneInstanceOperator
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin_ini/plugin_strict_fields.py
{ "start": 965, "end": 1340 }
class ____(ModelStrictMode): b: int = Field(strict=False) c: int = Field(strict=True) # expected error: a, c ModelOverride2(a='1', b='2', c='3') # MYPY: error: Argument "a" to "ModelOverride2" has incompatible type "str"; expected "int" [arg-type] # MYPY: error: Argument "c" to "ModelOverride2" has incompati...
ModelOverride2
python
huggingface__transformers
src/transformers/models/swiftformer/modeling_swiftformer.py
{ "start": 4453, "end": 5633 }
class ____(nn.Module): """ `SwiftFormerConvEncoder` with 3*3 and 1*1 convolutions. Input: tensor of shape `[batch_size, channels, height, width]` Output: tensor of shape `[batch_size, channels, height, width]` """ def __init__(self, config: SwiftFormerConfig, dim: int): super().__init...
SwiftFormerConvEncoder
python
great-expectations__great_expectations
tests/actions/test_core_actions.py
{ "start": 9894, "end": 13737 }
class ____: @pytest.mark.unit def test_equality(self): """I know, this one seems silly. But this was a bug.""" a = EmailAction( name="my_action", smtp_address="test", smtp_port="587", receiver_emails="test@gmail.com", ) b = EmailAct...
TestEmailAction
python
Textualize__textual
docs/examples/guide/reactivity/validate01.py
{ "start": 169, "end": 999 }
class ____(App): CSS_PATH = "validate01.tcss" count = reactive(0) def validate_count(self, count: int) -> int: """Validate value.""" if count < 0: count = 0 elif count > 10: count = 10 return count def compose(self) -> ComposeResult: yie...
ValidateApp
python
marshmallow-code__marshmallow
examples/flask_example.py
{ "start": 570, "end": 671 }
class ____(DeclarativeBase): pass db = SQLAlchemy(app, model_class=Base) ##### MODELS #####
Base
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 93075, "end": 93865 }
class ____: def test_simple(self): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0) def test_reduce(self): assert_almost_equal(ncu.hypot.reduce([3.0, 4.0]), 5.0) assert_almost_equal(ncu.hypot.reduce([3.0, 4.0, 0]), 5.0) assert_alm...
TestHypot
python
tensorflow__tensorflow
tensorflow/compiler/tests/categorical_op_test.py
{ "start": 1294, "end": 7439 }
class ____(xla_test.XLATestCase): """Test cases for random-number generating operators.""" def output_dtypes(self): return set(self.int_types).intersection([np.int32, np.int64]) def _chi2(self, expected, actual): """Returns Chi2 GOF statistic.""" actual = np.asarray(actual) expected = np.asarray...
CategoricalTest
python
huggingface__transformers
src/transformers/models/gpt2/modeling_gpt2.py
{ "start": 16622, "end": 21669 }
class ____(nn.Module): r""" Compute a single vector summary of a sequence hidden states. Args: config ([`GPT2Config`]): The config used by the model. Relevant arguments in the config class of the model are (refer to the actual config class of your model for the default value...
GPT2SequenceSummary
python
wandb__wandb
wandb/automations/events.py
{ "start": 2342, "end": 2914 }
class ____(GQLBase): # from: RunMetricFilter event_type: Annotated[ Literal[EventType.RUN_METRIC_THRESHOLD], Field(exclude=True, repr=False), ] = EventType.RUN_METRIC_THRESHOLD threshold_filter: MetricThresholdFilter @model_validator(mode="before") @classmethod def _nest_inner...
_WrappedMetricThresholdFilter
python
mlflow__mlflow
mlflow/models/evaluation/base.py
{ "start": 24563, "end": 28428 }
class ____: """ Represents the model evaluation outputs of a `mlflow.evaluate()` API call, containing both scalar metrics and output artifacts such as performance plots. """ def __init__(self, metrics, artifacts, run_id=None): self._metrics = metrics self._artifacts = artifacts ...
EvaluationResult
python
wandb__wandb
wandb/sdk/wandb_settings.py
{ "start": 1586, "end": 73924 }
class ____(BaseModel, validate_assignment=True): """Settings for the W&B SDK. This class manages configuration settings for the W&B SDK, ensuring type safety and validation of all settings. Settings are accessible as attributes and can be initialized programmatically, through environment variables ...
Settings
python
kamyu104__LeetCode-Solutions
Python/clone-binary-tree-with-random-pointer.py
{ "start": 1647, "end": 2738 }
class ____(object): def copyRandomBinaryTree(self, root): """ :type root: Node :rtype: NodeCopy """ def dfs(node, callback): if not node: return None left_node, copy = callback(node) dfs(left_node, callback) dfs(...
Solution_Recu
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py
{ "start": 1515, "end": 1663 }
class ____: @check_permission("fake_permission") async def mutate(self, graphene_info: ResolveInfo, **_kwargs): pass
FakeMutationAsync
python
sympy__sympy
sympy/assumptions/predicates/sets.py
{ "start": 1000, "end": 1677 }
class ____(Predicate): """ Rational number predicate. Explanation =========== ``Q.rational(x)`` is true iff ``x`` belongs to the set of rational numbers. Examples ======== >>> from sympy import ask, Q, pi, S >>> ask(Q.rational(0)) True >>> ask(Q.rational(S(1)/2)) ...
RationalPredicate
python
cherrypy__cherrypy
cherrypy/_cplogging.py
{ "start": 16712, "end": 17031 }
class ____(object): """A postponed timestamp string retrieval class.""" def __str__(self): """Return datetime in RFC3339 UTC Format.""" iso_formatted_now = datetime.datetime.now( datetime.timezone.utc, ).isoformat('T') return f'{iso_formatted_now!s}Z'
LazyRfc3339UtcTime
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/core.py
{ "start": 78485, "end": 78955 }
class ____(SearchStrategy): def __init__(self, definition, args, kwargs): super().__init__() self.definition = definition self.args = args self.kwargs = kwargs def do_draw(self, data): return self.definition(data.draw, *self.args, **self.kwargs) def calc_label(self)...
CompositeStrategy
python
faif__python-patterns
patterns/structural/proxy.py
{ "start": 1144, "end": 1382 }
class ____(Subject): """ This is the main job doer. External services like payment gateways can be a good example. """ def do_the_job(self, user: str) -> None: print(f"I am doing the job for {user}")
RealSubject
python
getsentry__sentry
tests/sentry/api/bases/test_organization.py
{ "start": 24278, "end": 27857 }
class ____(BaseOrganizationEndpointTest): def setUp(self) -> None: self.team_1 = self.create_team(organization=self.org) self.project_1 = self.create_project(organization=self.org, teams=[self.team_1]) self.project_2 = self.create_project(organization=self.org, teams=[self.team_1]) s...
GetFilterParamsTest
python
scrapy__scrapy
tests/test_robotstxt_interface.py
{ "start": 6130, "end": 6374 }
class ____(BaseRobotParserTest): def setup_method(self): super()._setUp(RerpRobotParser) def test_length_based_precedence(self): pytest.skip("Rerp does not support length based directives precedence.")
TestRerpRobotParser
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_types.py
{ "start": 22086, "end": 22512 }
class ____(_DateFixture, fixtures.TablesTest): __requires__ = ("timestamp_microseconds",) __backend__ = True datatype = TIMESTAMP data = datetime.datetime(2012, 10, 15, 12, 57, 18, 396) @testing.requires.timestamp_microseconds_implicit_bound def test_select_direct(self, connection): res...
TimestampMicrosecondsTest
python
kamyu104__LeetCode-Solutions
Python/find-mirror-score-of-a-string.py
{ "start": 71, "end": 472 }
class ____(object): def calculateScore(self, s): """ :type s: str :rtype: int """ result = 0 lookup = [[] for _ in xrange(26)] for i, x in enumerate(s): x = ord(x)-ord('a') if lookup[25-x]: result += i-lookup[25-x].pop()...
Solution
python
pyca__cryptography
tests/x509/verification/test_verification.py
{ "start": 3914, "end": 4192 }
class ____: def test_store_rejects_empty_list(self): with pytest.raises(ValueError): Store([]) def test_store_rejects_non_certificates(self): with pytest.raises(TypeError): Store(["not a cert"]) # type: ignore[list-item]
TestStore
python
django__django
tests/admin_widgets/tests.py
{ "start": 14761, "end": 15603 }
class ____(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="time">' '<input aria-describedby="id_test_timezone_warning_helptext" ' 'value="09:30:00" ty...
AdminTimeWidgetTest
python
pandas-dev__pandas
pandas/tests/arithmetic/test_object.py
{ "start": 2421, "end": 12031 }
class ____: def test_add_period_to_array_of_offset(self): # GH#50162 per = pd.Period("2012-1-1", freq="D") pi = pd.period_range("2012-1-1", periods=10, freq="D") idx = per - pi expected = pd.Index([x + per for x in idx], dtype=object) result = idx + per tm.as...
TestArithmetic
python
keras-team__keras
keras/src/metrics/probabilistic_metrics.py
{ "start": 1692, "end": 2759 }
class ____(reduction_metrics.MeanMetricWrapper): """Computes the Poisson metric between `y_true` and `y_pred`. Formula: ```python metric = y_pred - y_true * log(y_pred) ``` Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric res...
Poisson
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_query.py
{ "start": 32754, "end": 42674 }
class ____(fixtures.TablesTest, AssertsCompiledSQL): __only_on__ = "postgresql >= 8.3" __backend__ = True @classmethod def define_tables(cls, metadata): Table( "cattable", metadata, Column("id", Integer, primary_key=True), Column("description", St...
MatchTest
python
django__django
django/db/models/functions/datetime.py
{ "start": 4759, "end": 4946 }
class ____(Extract): """ Return Sunday=1 through Saturday=7. To replicate this in Python: (mydatetime.isoweekday() % 7) + 1 """ lookup_name = "week_day"
ExtractWeekDay
python
google__jax
tests/pallas/tpu_splash_attention_kernel_test.py
{ "start": 10252, "end": 26638 }
class ____(PallasBaseTest): @parameterized.product( is_mqa=(False, True), is_segmented=(False, True), is_dynamic_mask=(False, True), ) @hp.given(hps.data()) def test_splash_attention(self, is_mqa, is_segmented, is_dynamic_mask, data): seed = data.draw(seed_strategy()) key = random.key(...
SplashAttentionTest
python
pytorch__pytorch
torch/onnx/_internal/exporter/_building.py
{ "start": 20862, "end": 29167 }
class ____(evaluator.Evaluator): """An onnxscript Evaluator that captures the graph into ONNX IR.""" def __init__( self, opset: onnxscript.values.Opset, constant_farm: dict[Any, ir.Value] ) -> None: self.nodes: list[ir.Node] = [] self.opset = opset self.functions: dict[ ...
OpRecorder
python
encode__django-rest-framework
rest_framework/serializers.py
{ "start": 12808, "end": 21593 }
class ____(BaseSerializer, metaclass=SerializerMetaclass): default_error_messages = { 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.') } def set_value(self, dictionary, keys, value): """ Similar to Python's built in `dictionary[key] = value`, but take...
Serializer
python
tensorflow__tensorflow
tensorflow/python/distribute/values.py
{ "start": 48918, "end": 49623 }
class ____(saveable_object.SaveableObject): """Class for defining how to restore a SyncOnReadVariable.""" def __init__(self, sync_on_read_variable, name): self._sync_on_read_variable = sync_on_read_variable tensor, spec = values_util.get_on_read_saveable( sync_on_read_variable, sync_on_read_variabl...
_SyncOnReadSaveable
python
sanic-org__sanic
sanic/asgi.py
{ "start": 595, "end": 4069 }
class ____: def __init__( self, sanic_app, scope: ASGIScope, receive: ASGIReceive, send: ASGISend ) -> None: self.sanic_app = sanic_app self.scope = scope self.receive = receive self.send = send if "server.init.before" in self.sanic_app.signal_router.name_index: ...
Lifespan
python
spack__spack
lib/spack/spack/spec_parser.py
{ "start": 28219, "end": 29468 }
class ____(spack.error.SpecSyntaxError): """Error when parsing tokens""" def __init__(self, message, token, text): message += f"\n{text}" if token: underline = f"\n{' '*token.start}{'^'*(token.end - token.start)}" message += color.colorize(f"@*r{{{underline}}}") ...
SpecParsingError
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 564, "end": 1228 }
class ____: def __init__(self, bounds, expected_x, expected_fun=None, expected_xl=None, expected_funl=None): self.bounds = bounds self.expected_x = expected_x self.expected_fun = expected_fun self.expected_xl = expected_xl self.expected_funl = expected_funl ...
StructTestFunction
python
lxml__lxml
src/lxml/tests/test_xslt.py
{ "start": 49361, "end": 67131 }
class ____(HelperTestCase): """Tests for extension elements in XSLT.""" def test_extension_element(self): tree = self.parse('<a><b>B</b></a>') style = self.parse('''\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myns="testns" extension-element...
ETreeXSLTExtElementTestCase
python
mlflow__mlflow
tests/telemetry/test_tracked_events.py
{ "start": 24510, "end": 33775 }
class ____(mlflow.pyfunc.PythonModel): def predict(self, context, model_input: list[str], params=None) -> list[str]: return model_input set_model(TestModel()) """ model_path = tmp_path / "model.py" model_path.write_text(model_def) model_info = mlflow.pyfunc.log_model( name="model", ...
TestModel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassDescriptors2.py
{ "start": 910, "end": 992 }
class ____: x: Desc[int] y: Desc[str] z: Desc[str] = Desc() @dataclass
B
python
numpy__numpy
numpy/_core/tests/test_ufunc.py
{ "start": 137219, "end": 139707 }
class ____: PARAMS_COMMON = { "casting": "same_kind", "order": "K", "dtype": None, "subok": True, "signature": None, } PARAMS_UFUNC = { "where": True, } | PARAMS_COMMON PARAMS_GUFUNC = { "axes": np._NoValue, "axis": np._NoValue, ...
TestUFuncInspectSignature
python
kamyu104__LeetCode-Solutions
Python/elimination-game.py
{ "start": 32, "end": 365 }
class ____(object): def lastRemaining(self, n): """ :type n: int :rtype: int """ start, step, direction = 1, 2, 1 while n > 1: start += direction * (step * (n//2) - step//2) n //= 2 step *= 2 direction *= -1 retu...
Solution
python
ansible__ansible
lib/ansible/_internal/_json/_profiles/_inventory_legacy.py
{ "start": 262, "end": 854 }
class ____(_legacy._LegacyVariableVisitor, _json.StateTrackingMixIn): """State-tracking visitor implementation that only applies trust to `_meta.hostvars` and `vars` inventory values.""" # DTFIX5: does the variable visitor need to support conversion of sequence/mapping for inventory? @property def _al...
_InventoryVariableVisitor
python
pandas-dev__pandas
pandas/tests/frame/test_arithmetic.py
{ "start": 1218, "end": 1923 }
class ____: def __init__(self, value, dtype) -> None: self.value = value self.dtype = np.dtype(dtype) def __array__(self, dtype=None, copy=None): return np.array(self.value, dtype=self.dtype) def __str__(self) -> str: return f"DummyElement({self.value}, {self.dtype})" ...
DummyElement
python
google__jax
jaxlib/xla_client.py
{ "start": 8790, "end": 11712 }
class ____: def __init__(self, parameter_shapes, result_shape): def parameter_shapes(self) -> [Shape]: def result_shape(self) -> Shape: def __repr__(self): """ DeviceAssignment = _xla.DeviceAssignment DeviceAssignment.__doc__ = """ A DeviceAssignment is a C++ object with the following signature. def create(as...
ProgramShape
python
walkccc__LeetCode
solutions/1363. Largest Multiple of Three/1363.py
{ "start": 0, "end": 520 }
class ____: def largestMultipleOfThree(self, digits: list[int]) -> str: ans = '' mod1 = [1, 4, 7, 2, 5, 8] mod2 = [2, 5, 8, 1, 4, 7] count = collections.Counter(digits) summ = sum(digits) while summ % 3 != 0: for digit in (mod1 if summ % 3 == 1 else mod2): if count[digit]: ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-youtube-analytics/components.py
{ "start": 3156, "end": 4066 }
class ____(StateMigration): def should_migrate(self, stream_state: Mapping[str, Any]) -> bool: return stream_state.get("state") or stream_state.get("date") def migrate(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]: if stream_state.get("date"): # old format state before...
ReportsStateMigration
python
huggingface__transformers
src/transformers/models/reformer/modeling_reformer.py
{ "start": 63727, "end": 69925 }
class ____(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.attention = ReformerAttention(config, layer_id) # dropout requires to have the same # seed for forward and backward pass self.attention_seed = None self.feed_forward_seed = None ...
ReformerLayer