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
doocs__leetcode
solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/Solution.py
{ "start": 0, "end": 235 }
class ____: def sumZero(self, n: int) -> List[int]: ans = [] for i in range(n >> 1): ans.append(i + 1) ans.append(-(i + 1)) if n & 1: ans.append(0) return ans
Solution
python
astropy__astropy
astropy/coordinates/errors.py
{ "start": 510, "end": 602 }
class ____(ValueError): """ Raised if units are missing or invalid. """
UnitsError
python
scipy__scipy
scipy/stats/tests/test_mstats_basic.py
{ "start": 55310, "end": 55629 }
class ____: def test_result_attributes(self): x = [1, 3, 5, 7, 9] y = [2, 4, 6, 8, 10] res = mstats.kruskal(x, y) attributes = ('statistic', 'pvalue') check_named_results(res, attributes, ma=True) # TODO: for all ttest functions, add tests with masked array inputs
TestKruskal
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 2839, "end": 2912 }
class ____(ParentNonOpen7): a: NotRequired[ReadOnly[str]]
ChildNotClosed7
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/duplicateDeclaration1.py
{ "start": 112, "end": 1995 }
class ____: # This should generate an error. def f(self): return 0 # This should generate an error. def f(self): return 0 def f(self): return 1 # This should generate an error. def g(self): return 0 g: int @property def h(self) -> int: ...
C
python
PyCQA__pylint
tests/functional/i/invalid/invalid_enum_extension.py
{ "start": 536, "end": 744 }
class ____(Enum): red: int green: int blue: int def __init__(self, red: int, green: int, blue: int) -> None: self.red = red self.green = green self.blue = blue
ColorEnum
python
langchain-ai__langchain
libs/core/langchain_core/indexing/base.py
{ "start": 14597, "end": 15556 }
class ____(TypedDict): """A generic response for upsert operations. The upsert response will be used by abstractions that implement an upsert operation for content that can be upserted by ID. Upsert APIs that accept inputs with IDs and generate IDs internally will return a response that includes t...
UpsertResponse
python
sanic-org__sanic
sanic/middleware.py
{ "start": 251, "end": 331 }
class ____(IntEnum): REQUEST = auto() RESPONSE = auto()
MiddlewareLocation
python
huggingface__transformers
tests/models/vitpose_backbone/test_modeling_vitpose_backbone.py
{ "start": 7315, "end": 7609 }
class ____(unittest.TestCase, BackboneTesterMixin): all_model_classes = (VitPoseBackbone,) if is_torch_available() else () config_class = VitPoseBackboneConfig has_attentions = False def setUp(self): self.model_tester = VitPoseBackboneModelTester(self)
VitPoseBackboneTest
python
ray-project__ray
rllib/utils/tests/test_tf_utils.py
{ "start": 2422, "end": 9137 }
class ____: def __init__(self): # Almost the same as above, but now returns the placeholders and # gradient. with tf.Graph().as_default(): loss, init, x_data, y_data = make_linear_network() sess = tf.Session() variables = tf_utils.TensorFlowVariables(loss,...
TrainActor
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 50708, "end": 51375 }
class ____(URLFetchStrategy): """FetchStrategy that pulls from an S3 bucket.""" url_attr = "s3" @_needs_stage def fetch(self): if not self.url.startswith("s3://"): raise spack.error.FetchError( f"{self.__class__.__name__} can only fetch from s3:// urls." ...
S3FetchStrategy
python
pytorch__pytorch
benchmarks/framework_overhead_benchmark/SimpleAddModule.py
{ "start": 180, "end": 371 }
class ____(torch.nn.Module): def __init__(self, add_op): super().__init__() self.add_op = add_op def forward(self, x, y): return self.add_op(x, y)
SimpleAddModule
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 72835, "end": 73372 }
class ____(_PrintableStructure): _fields_ = [ ("version", c_uint), ("isNvleEnabled", c_uint), ] def __init__(self): super(c_nvmlNvLinkInfo_v1_t, self).__init__(version=nvmlNvLinkInfo_v1) NVML_NVLINK_FIRMWARE_UCODE_TYPE_MSE = 0x1 NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR = 0...
c_nvmlNvLinkInfo_v1_t
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 22339, "end": 23211 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("es_ES") Faker.seed(0) def test_vat_id(self): for _ in range(100): assert re.search(r"^ES\w\d{8}$|^ES\d{8}\w$|^ES\w\d{7}\w$", self.fake.vat_id()) def test_nie(self): for _ in range(100): ...
TestEsES
python
fluentpython__example-code-2e
15-more-types/cafeteria/covariant.py
{ "start": 282, "end": 1266 }
class ____(Generic[T_co]): # <2> def __init__(self, beverage: T_co) -> None: self.beverage = beverage def dispense(self) -> T_co: return self.beverage def install(dispenser: BeverageDispenser[Juice]) -> None: # <3> """Install a fruit juice dispenser.""" # end::BEVERAGE_TYPES[] #########...
BeverageDispenser
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_middleware.py
{ "start": 9126, "end": 9655 }
class ____(TestCase): def setUp(self): self.factory = RequestFactory() self.middleware = NullCharactersMiddleware(None) def test_request_with_null_chars(self): request = self.factory.get("/?language=en\x00es&project_slug=myproject") response = self.middleware(request) se...
TestNullCharactersMiddleware
python
redis__redis-py
redis/multidb/healthcheck.py
{ "start": 1247, "end": 1904 }
class ____(HealthCheckPolicy): def __init__(self, health_check_probes: int, health_check_delay: float): if health_check_probes < 1: raise ValueError("health_check_probes must be greater than 0") self._health_check_probes = health_check_probes self._health_check_delay = health_che...
AbstractHealthCheckPolicy
python
apache__airflow
providers/common/sql/tests/unit/common/sql/sensors/test_sql.py
{ "start": 1189, "end": 11014 }
class ____: def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} self.dag = DAG(TEST_DAG_ID, schedule=None, default_args=args) @pytest.mark.db_test def test_unsupported_conn_type(self): op = SqlSensor( task_id="sql_sensor_check", co...
TestSqlSensor
python
dask__dask
dask/dataframe/dask_expr/_reductions.py
{ "start": 41502, "end": 41615 }
class ____(NFirst): reduction_chunk = staticmethod(_nlast) reduction_aggregate = staticmethod(_nlast)
NLast
python
Pylons__pyramid
tests/test_traversal.py
{ "start": 43587, "end": 44051 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.traversal import DefaultRootFactory return DefaultRootFactory def _makeOne(self, environ): return self._getTargetClass()(environ) def test_it(self): class DummyRequest: pass root = ...
TestDefaultRootFactory
python
huggingface__transformers
src/transformers/models/llama/modeling_llama.py
{ "start": 12919, "end": 14701 }
class ____(GradientCheckpointingLayer): def __init__(self, config: LlamaConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx) self.mlp = LlamaMLP(config) self.input_layernorm = L...
LlamaDecoderLayer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 85734, "end": 86909 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "name", "owner_id", "description", "visibility", "template", "homepage_url", "has_wiki_enabled", "has_issues_enabled"...
CreateRepositoryInput
python
neetcode-gh__leetcode
python/1905-count-sub-islands.py
{ "start": 0, "end": 935 }
class ____: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: ROWS, COLS = len(grid1), len(grid1[0]) visit = set() def dfs(r, c): if ( r < 0 or c < 0 or r == ROWS or c == COLS ...
Solution
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/stats.py
{ "start": 2042, "end": 3921 }
class ____(abc.ABC): """ A StatsWriter abstract class. A StatsWriter takes in a category, key, scalar value, and step and writes it out by some method. """ def on_add_stat( self, category: str, key: str, value: float, aggregation: StatsAggregationMethod = Sta...
StatsWriter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format05.py
{ "start": 315, "end": 1561 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format05.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = ...
TestCompareXLSXFiles
python
ray-project__ray
rllib/offline/dataset_reader.py
{ "start": 7195, "end": 11719 }
class ____(InputReader): """Reader object that loads data from Ray Dataset. Examples: config = { "input": "dataset", "input_config": { "format": "json", # A single data file, a directory, or anything # that ray.data.dataset recogni...
DatasetReader
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 21980, "end": 22941 }
class ____( IHaveNew, MetadataValue[Optional[Union[Sequence[Any], Mapping[str, Any]]]], ): """Container class for JSON metadata entry data. Args: data (Union[Sequence[Any], Dict[str, Any]]): The JSON data. """ data: PublicAttr[Optional[Union[Sequence[Any], Mapping[str, Any]]]] def...
JsonMetadataValue
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_organization_invite_request.py
{ "start": 504, "end": 1563 }
class ____(View): def get(self, request: HttpRequest) -> HttpResponse: org = Organization(id=1, slug="default", name="Default") requester = User(name="Rick Swan", id=2, email="rick@gmail.com") OrganizationMember(user_id=requester.id, organization=org, email="james@gmail.com") pending...
DebugOrganizationInviteRequestEmailView
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 33348, "end": 36641 }
class ____: def test_repr(self): if self.repr is not None: self.assertEqual(repr(self.set), self.repr) def check_repr_against_values(self): text = repr(self.set) self.assertTrue(text.startswith('{')) self.assertTrue(text.endswith('}')) result = text[1:-1].s...
_TestBasicOps
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 866128, "end": 866612 }
class ____(sgqlc.types.Type): """Autogenerated return type of PublishSponsorsTier""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "sponsors_tier") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing ...
PublishSponsorsTierPayload
python
huggingface__transformers
src/transformers/models/bark/modeling_bark.py
{ "start": 10956, "end": 12795 }
class ____(GradientCheckpointingLayer): def __init__(self, config, is_causal=False, layer_idx=None): super().__init__() if is_causal: # if causal, the layerNorm bias is optional to stick with Bark choice of leaving optional bias # in AutoRegressive models (corresponding to t...
BarkBlock
python
google__jax
jax/experimental/roofline/roofline.py
{ "start": 1846, "end": 2681 }
class ____: shape: tuple[int, ...] dtype: ValidRooflineDtype @classmethod def from_aval(cls, aval: core.AbstractValue) -> RooflineShape: if not isinstance(aval, core.ShapedArray): raise TypeError(f"Expected ShapedArray, got {type(aval)}.") if not isinstance(aval.dtype, ValidRooflineDtype): ...
RooflineShape
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_tk.py
{ "start": 44053, "end": 44284 }
class ____(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2Tk.save_figure( self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasTk)
SaveFigureTk
python
psf__requests
src/requests/adapters.py
{ "start": 3108, "end": 4316 }
class ____: """The Base Transport Adapter""" def __init__(self): super().__init__() def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`Prepar...
BaseAdapter
python
kamyu104__LeetCode-Solutions
Python/longest-common-subsequence.py
{ "start": 41, "end": 659 }
class ____(object): def longestCommonSubsequence(self, text1, text2): """ :type text1: str :type text2: str :rtype: int """ if len(text1) < len(text2): return self.longestCommonSubsequence(text2, text1) dp = [[0 for _ in xrange(len(text2)+1)] for ...
Solution
python
tensorflow__tensorflow
tensorflow/python/compiler/xla/tests/pjrt_autoclustering_test.py
{ "start": 1240, "end": 3060 }
class ____(test.TestCase): def test_xla_compile_and_run_on_gpu_device(self): if not test.is_gpu_available() or not test.is_built_with_gpu_support(): test.skipTest("Test only applicable on GPU") @def_function.function def arithmetic(x): return 2 * x + 1 @def_function.function def co...
PjrtAutoclusteringTest
python
ZoranPandovski__al-go-rithms
data_structures/Linked_list/Python/Swap_Nodes_Linkedlist.py
{ "start": 151, "end": 878 }
class ____: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head==None: return None if head.next==None: return head tmp1=head tmp2=head.next while tmp1: if tmp1 !=None and tmp2 !=None: print(tmp1.v...
Solution
python
django__django
tests/pagination/models.py
{ "start": 31, "end": 227 }
class ____(models.Model): headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField() def __str__(self): return self.headline
Article
python
getsentry__sentry
tests/sentry/seer/endpoints/test_seer_rpc.py
{ "start": 1376, "end": 2357 }
class ____(APITestCase): @staticmethod def _get_path(method_name: str) -> str: return reverse( "sentry-api-0-seer-rpc-service", kwargs={"method_name": method_name}, ) def auth_header(self, path: str, data: dict | str) -> str: if isinstance(data, dict): ...
TestSeerRpc
python
numba__numba
numba/tests/test_hashing.py
{ "start": 12557, "end": 14826 }
class ____(BaseTest): """ Test hashing of tuples. """ def setUp(self): if numpy_version >= (2, 0) and numpy_version <= (2, 1): # Temporarily set promotions state to legacy, # to ensure overflow logic works self.initial_state = np._get_promotion_state() ...
TestTupleHashing
python
python-poetry__poetry
src/poetry/publishing/hash_manager.py
{ "start": 309, "end": 1825 }
class ____: def __init__(self) -> None: self._sha2_hasher = hashlib.sha256() self._md5_hasher = None with suppress(ValueError): # FIPS mode disables MD5 self._md5_hasher = hashlib.md5() self._blake_hasher = None with suppress(ValueError, TypeError): ...
HashManager
python
Lightning-AI__lightning
tests/tests_pytorch/accelerators/test_xla.py
{ "start": 7646, "end": 7817 }
class ____(nn.Module): def __init__(self, layer): super().__init__() self.layer = layer def forward(self, x): return self.layer(x)
SubModule
python
pytorch__pytorch
test/quantization/core/test_top_level_apis.py
{ "start": 140, "end": 2203 }
class ____(TestCase): observers = [ "default_affine_fixed_qparams_observer", "default_debug_observer", "default_dynamic_quant_observer", "default_placeholder_observer", "default_fixed_qparams_range_0to1_observer", "default_fixed_qparams_range_neg1to1_observer", ...
TestDefaultObservers
python
gevent__gevent
src/greentest/3.14/test_subprocess.py
{ "start": 80437, "end": 149092 }
class ____(BaseTestCase): def setUp(self): super().setUp() self._nonexistent_dir = "/_this/pa.th/does/not/exist" def _get_chdir_exception(self): try: os.chdir(self._nonexistent_dir) except OSError as e: # This avoids hard coding the errno value or the OS...
POSIXProcessTestCase
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 28453, "end": 33168 }
class ____(GoogleCloudBaseOperator): """ Creates a DataScan resource. :param project_id: Required. The ID of the Google Cloud project that the lake belongs to. :param region: Required. The ID of the Google Cloud region that the lake belongs to. :param body: Required. The Request body contains an i...
DataplexCreateOrUpdateDataQualityScanOperator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 40856, "end": 42350 }
class ____(GithubStream): """ API docs: https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#list-commits-on-a-pull-request """ primary_key = "sha" def __init__(self, parent: HttpStream, **kwargs): super().__init__(**kwargs) self.parent = parent def path(self, str...
PullRequestCommits
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 40130, "end": 40705 }
class ____(Blockwise): _parameters = ["frame", "state_data", "frac", "replace"] operation = staticmethod(methods.sample) @functools.cached_property def _meta(self): args = [self.operands[0]._meta] + [self.operands[1][0]] + self.operands[2:] return self.operation(*args) def _task(se...
Sample
python
getsentry__sentry-python
tests/integrations/grpc/grpc_test_service_pb2_grpc.py
{ "start": 4645, "end": 7557 }
class ____(object): """Missing associated documentation comment in .proto file.""" @staticmethod def TestServe(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, ...
gRPCTestService
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 74726, "end": 75416 }
class ____(Expr): """Returns a tuple of partition lengths""" _parameters = ["frame"] @functools.cached_property def _meta(self): return tuple() def _divisions(self): return (None, None) def _simplify_down(self): if isinstance(self.frame, Elemwise): child =...
Lengths
python
huggingface__transformers
src/transformers/models/voxtral/modeling_voxtral.py
{ "start": 9614, "end": 14455 }
class ____(VoxtralPreTrainedModel): """ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`VoxtralEncoderLayer`]. Args: config: VoxtralEncoderConfig """ # Ignore copy config: VoxtralEncoderConfig main_input_name = "input_features"...
VoxtralEncoder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 952, "end": 992 }
class ____(object): ... object = A
A
python
kamyu104__LeetCode-Solutions
Python/race-car.py
{ "start": 64, "end": 1202 }
class ____(object): def racecar(self, target): dp = [0] * (target+1) for i in xrange(1, target+1): # 2^(k-1) <= i < 2^k k = i.bit_length() # case 1. drive exactly i at best # seq(i) = A^k if i == 2**k-1: dp[i] = k ...
Solution
python
getsentry__sentry
src/sentry/issues/auto_source_code_config/task.py
{ "start": 1546, "end": 9744 }
class ____(StrEnum): UNEXPECTED_ERROR = "Unexpected error type while calling `get_trees_for_org()`." LOCK_FAILED = "Failed to acquire lock" EMPTY_TREES = "The trees are empty." def process_event( project_id: int, group_id: int, event_id: str ) -> tuple[list[CodeMapping], list[str]]: """ Proces...
DeriveCodeMappingsErrorReason
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 116073, "end": 116639 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, api_key: str, company: str): """Airbyte Source for Hellobaton. Args: name (str): The name of the destination. api_key (str): authentication key required to access the api endpoints comp...
HellobatonSource
python
astropy__astropy
astropy/cosmology/_src/tests/flrw/test_w0wzcdm.py
{ "start": 942, "end": 2386 }
class ____(ParameterTestMixin): """Tests for `astropy.cosmology.Parameter` wz on a Cosmology. wz is a descriptor, which are tested by mixin, here with ``TestFLRW``. These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the args and kwargs for the cosmology class, respectively. See ``Test...
ParameterwzTestMixin
python
django__django
django/db/backends/oracle/creation.py
{ "start": 283, "end": 21026 }
class ____(BaseDatabaseCreation): @cached_property def _maindb_connection(self): """ This is analogous to other backends' `_nodb_connection` property, which allows access to an "administrative" connection which can be used to manage the test databases. For Oracle, the onl...
DatabaseCreation
python
huggingface__transformers
src/transformers/models/led/modeling_led.py
{ "start": 57905, "end": 59922 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Total span extraction loss is the sum of a Cross-Entropy for the start and end positions. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `...
LEDSeq2SeqQuestionAnsweringModelOutput
python
getsentry__sentry-python
tests/integrations/starlette/test_starlette.py
{ "start": 37179, "end": 42863 }
class ____: """Wraps any container and makes it non-iterable. Used to test backwards compatibility with our old way of defining failed_request_status_codes, which allowed passing in a list of (possibly non-iterable) containers. The Python standard library does not provide any built-in non-iterable cont...
NonIterableContainer
python
vyperlang__vyper
vyper/ast/parse.py
{ "start": 4779, "end": 18806 }
class ____(python_ast.NodeTransformer): _source_code: str _pre_parser: PreParser _parents: list[python_ast.AST] def __init__( self, source_code: str, pre_parser: PreParser, source_id: int, module_path: Optional[str] = None, resolved_path: Optional[str] = ...
AnnotatingVisitor
python
dagster-io__dagster
python_modules/dagster/dagster/_core/event_api.py
{ "start": 9352, "end": 13851 }
class ____( NamedTuple( "_AssetRecordsFilter", [ ("asset_key", PublicAttr[AssetKey]), ("asset_partitions", PublicAttr[Optional[Sequence[str]]]), ("after_timestamp", PublicAttr[Optional[float]]), ("before_timestamp", PublicAttr[Optional[float]]), ...
AssetRecordsFilter
python
huggingface__transformers
src/transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py
{ "start": 14289, "end": 16715 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.num_experts = config.moe_num_experts self.hidden_dim = config.hidden_size self.intermediate_dim = config.moe_intermediate_size self.use_bias = config.use_bias self.act_fn = ACT2FN[config.hidden...
Ernie4_5_MoeExperts
python
facebook__pyre-check
tools/pysa_integration_tests/tests/runner_lib_test.py
{ "start": 453, "end": 9874 }
class ____(testslide.TestCase): def test_parse_annotations(self) -> None: self.assertEqual( test_runner_lib.parse_test_annotations_from_source( textwrap.dedent( """ def foo() -> None: pass """ ...
RunnerLibTest
python
allegroai__clearml
clearml/backend_api/services/v2_9/models.py
{ "start": 25311, "end": 27028 }
class ____(Request): """ Delete a model. :param model: Model ID :type model: str :param force: Force. Required if there are tasks that use the model as an execution model, or if the model's creating task is published. :type force: bool """ _service = "models" _action = "del...
DeleteRequest
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 26829, "end": 27472 }
class ____(TestCase): def test_inet(self): self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, socket.AF_INET) def test_unspec(self): self._test('getaddrinfo', TestGeventOrg.HOSTNAME, None, socket.AF_UNSPEC) def test_badvalue(self): self._test('getaddrinfo', TestGeventOrg.HOSTN...
TestFamily
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 15014, "end": 16162 }
class ____(nn.Module): """This module mixes the hidden feature dimension. Args: config (`PatchTSMixerConfig`): Configuration. """ def __init__(self, config: PatchTSMixerConfig): super().__init__() self.norm = PatchTSMixerNormLayer(config) self.gated_attn ...
FeatureMixerBlock
python
django__django
tests/db_functions/migrations/0001_setup_extensions.py
{ "start": 189, "end": 312 }
class ____(migrations.Migration): # Required for the SHA database functions. operations = [CryptoExtension()]
Migration
python
altair-viz__altair
altair/vegalite/v6/schema/mixins.py
{ "start": 68669, "end": 86990 }
class ____: """A mixin class that defines config methods.""" @use_signature(core.Config) def configure(self, *args, **kwargs) -> Self: copy = self.copy(deep=False) # type: ignore[attr-defined] copy.config = core.Config(*args, **kwargs) return copy @use_signature(core.RectConfi...
ConfigMethodMixin
python
bokeh__bokeh
src/bokeh/models/annotations/labels.py
{ "start": 2232, "end": 3684 }
class ____(Annotation): ''' Base class for text annotation models such as labels and titles. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) text = TextLike(default="", help=""" A text or LaTeX...
TextAnnotation
python
walkccc__LeetCode
solutions/1655. Distribute Repeating Integers/1655.py
{ "start": 0, "end": 1651 }
class ____: def canDistribute(self, nums: list[int], quantity: list[int]) -> bool: freqs = list(collections.Counter(nums).values()) # validDistribution[i][j] := True if it's possible to distribute the i-th # freq into a subset of quantity represented by the bitmask j validDistribution = self._getValid...
Solution
python
pytorch__pytorch
test/dynamo/test_repros.py
{ "start": 18166, "end": 18422 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear = torch.nn.Linear(784, 5) def forward(self, x, ignored=None, bn_training=False): return self.linear(x.view(x.shape[0], -1))
FakeMamlInner
python
django-compressor__django-compressor
compressor/tests/test_filters.py
{ "start": 9320, "end": 9619 }
class ____(TestCase): def test_calmjs_filter(self): content = """ var foo = "bar";""" output = """var foo="bar";""" self.assertEqual(output, CalmjsFilter(content).output()) @override_settings( COMPRESS_ENABLED=True, COMPRESS_URL="/static/", )
CalmjsTestCase
python
astropy__astropy
astropy/cosmology/_src/parameter/core.py
{ "start": 467, "end": 735 }
class ____(Enum): """Sentinel values for Parameter fields.""" MISSING = auto() """A sentinel value signifying a missing default.""" def __repr__(self) -> str: return f"<{self.name}>" MISSING = Sentinel.MISSING @dataclass(frozen=True)
Sentinel
python
readthedocs__readthedocs.org
readthedocs/oauth/migrations/0009_add_missing_model_change_migrations.py
{ "start": 180, "end": 1633 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("oauth", "0008_add-project-relation"), ] operations = [ migrations.AlterField( model_name="remoterepository", name="clone_url", field=models.URLField( blank...
Migration
python
doocs__leetcode
solution/1900-1999/1902.Depth of BST Given Insertion Order/Solution.py
{ "start": 0, "end": 386 }
class ____: def maxDepthBST(self, order: List[int]) -> int: sd = SortedDict({0: 0, inf: 0, order[0]: 1}) ans = 1 for v in order[1:]: lower = sd.bisect_left(v) - 1 higher = lower + 1 depth = 1 + max(sd.values()[lower], sd.values()[higher]) ans =...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 69854, "end": 70356 }
class ____(str, Enum): """ * `PERIODIC`: Schedules that periodically trigger runs, such as a cron scheduler. * `ONE_TIME`: One time triggers that fire a single run. This occurs you triggered a single run on demand through the UI or the API. * `RETRY`: Indicates a run that is triggered as a retry of ...
TriggerType
python
cython__cython
Cython/Compiler/MemoryView.py
{ "start": 15550, "end": 31485 }
class ____(SliceIter): def start_loops(self): code = self.code code.begin_block() for i in range(self.ndim): t = i, self.slice_result, i code.putln("Py_ssize_t __pyx_temp_extent_%d = %s.shape[%d];" % t) code.putln("Py_ssize_t __pyx_temp_stride_%d = %s.str...
StridedSliceIter
python
PyCQA__isort
tests/unit/test_exceptions.py
{ "start": 645, "end": 937 }
class ____(TestISortError): def setup_class(self): self.instance: exceptions.IntroducedSyntaxErrors = exceptions.IntroducedSyntaxErrors( "file_path" ) def test_variables(self): assert self.instance.file_path == "file_path"
TestIntroducedSyntaxErrors
python
SmileyChris__easy-thumbnails
demoproject/mainapp/forms.py
{ "start": 118, "end": 310 }
class ____(forms.ModelForm): class Meta: model = TestImage fields = ["title", "image"] widgets = { "image": ImageClearableFileInput, }
TestImageForm
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/cmake.py
{ "start": 365, "end": 1804 }
class ____(PackageBase): """Specialized class for packages built using CMake For more information on the CMake build system, see: https://cmake.org/cmake/help/latest/ """ build_system_class = "CMakePackage" default_buildsystem = "cmake" build_system("cmake") depends_on("cmake", type=...
CMakePackage
python
getsentry__sentry-python
tests/integrations/gcp/test_gcp.py
{ "start": 1342, "end": 17736 }
class ____(HttpTransport): def capture_envelope(self, envelope): envelope_item = envelope_processor(envelope) print("\\nENVELOPE: {}\\n".format(envelope_item.decode(\"utf-8\"))) def init_sdk(timeout_warning=False, **extra_init_args): sentry_sdk.init( dsn="https://123abc@example.com/123...
TestTransport
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 17412, "end": 17968 }
class ____(VariableResponse): type: Literal["VariableResult"] = "VariableResult" @classmethod def from_variable_response(cls, variable_response: VariableResponse) -> VariableResult: """ Get VariableResult from VariableResponse. VariableResponse is autogenerated from the API schema,...
VariableResult
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault2.py
{ "start": 1588, "end": 1693 }
class ____[*Ts = Ts1]: ... # This should generate an error because default must be unpacked tuple.
ClassTs6
python
ray-project__ray
rllib/env/wrappers/atari_wrappers.py
{ "start": 8421, "end": 9833 }
class ____(gym.Wrapper): def __init__(self, env, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None sel...
NoopResetEnv
python
PrefectHQ__prefect
src/prefect/server/schemas/sorting.py
{ "start": 2101, "end": 3221 }
class ____(AutoEnum): """Defines task run sorting options.""" ID_DESC = AutoEnum.auto() EXPECTED_START_TIME_ASC = AutoEnum.auto() EXPECTED_START_TIME_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() NEXT_SCHEDULED_START_TIME_ASC = AutoEnum.auto() END_TIME_DE...
TaskRunSort
python
python-attrs__attrs
tests/test_funcs.py
{ "start": 19391, "end": 24293 }
class ____: """ Tests for `evolve`. """ @given(slots=st.booleans(), frozen=st.booleans()) def test_empty(self, slots, frozen): """ Empty classes without changes get copied. """ @attr.s(slots=slots, frozen=frozen) class C: pass i1 = C() ...
TestEvolve
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 422, "end": 472 }
class ____: def m(self) -> Self: ...
Impl_CoSelf
python
weaviate__weaviate-python-client
weaviate/collections/classes/filters.py
{ "start": 13982, "end": 15543 }
class ____(_FilterBase): def __init__(self, target: Optional[_TargetRefs] = None) -> None: self._target = target self._property = "_id" def contains_any(self, uuids: Sequence[UUID]) -> _Filters: """Filter for objects that has one of the given IDs.""" if len(uuids) == 0: ...
_FilterById
python
realpython__materials
python-mutable-immutable/point_typing.py
{ "start": 44, "end": 208 }
class ____(NamedTuple): x: float y: float def distance(self, other: "Point") -> float: return math.dist((self.x, self.y), (other.x, other.y))
Point
python
google__pytype
pytype/overlays/special_builtins.py
{ "start": 6852, "end": 8312 }
class ____(ObjectPredicate): """The base class for builtin predicates of the form f(obj, value). Subclasses need to override the following: _call_predicate(self, node, left, right): The implementation of the predicate. """ def _call_predicate(self, node, left, right): raise NotImplementedError(self.__c...
BinaryPredicate
python
scipy__scipy
scipy/stats/_binomtest.py
{ "start": 278, "end": 13199 }
class ____: """ Result of `scipy.stats.binomtest`. Attributes ---------- k : int The number of successes (copied from `binomtest` input). n : int The number of trials (copied from `binomtest` input). alternative : str Indicates the alternative hypothesis specified in...
BinomTestResult
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/components.py
{ "start": 255, "end": 806 }
class ____(DpathExtractor): common_fields = ("itblInternal", "_type", "createdAt", "email") def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]: jsonl_records = super().extract_records(response=response) for record_dict in jsonl_records: record_dict...
EventsRecordExtractor
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_stats_v2.py
{ "start": 318, "end": 35520 }
class ____(APITestCase, OutcomesSnubaTest): endpoint = "sentry-api-0-organization-stats-v2" _now = datetime.now(UTC).replace(hour=12, minute=27, second=28, microsecond=0) def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.organization s...
OrganizationStatsTestV2
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 412534, "end": 416767 }
class ____: unif = stats.uniform(0, 1) ih1 = stats.irwinhall(1) ih10 = stats.irwinhall(10) def test_stats_ih10(self): # from Wolfram Alpha "mean variance skew kurtosis UniformSumDistribution[10]" # W|A uses Pearson's definition of kurtosis so subtract 3 # should be exact integer...
TestIrwinHall
python
davidhalter__parso
parso/python/errors.py
{ "start": 19614, "end": 19959 }
class ____(SyntaxRule): message = "'break' outside loop" def is_issue(self, leaf): in_loop = False for block in self._normalizer.context.blocks: if block.type in ('for_stmt', 'while_stmt'): in_loop = True return not in_loop @ErrorFinder.register_rule(value=...
_BreakOutsideLoop
python
pytorch__pytorch
benchmarks/dynamo/runner.py
{ "start": 20008, "end": 20609 }
class ____: def __init__( self, suites, devices, dtypes, compilers, flag_compilers, mode, output_dir ): self.suites = suites self.devices = devices self.dtypes = dtypes self.compilers = compilers self.flag_compilers = flag_compilers self.output_dir = outpu...
Parser
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 99466, "end": 99749 }
class ____(ParserElement): """Abstract :class:`ParserElement` subclass, for defining atomic matching patterns. """ def __init__(self) -> None: super().__init__(savelist=False) def _generateDefaultName(self) -> str: return type(self).__name__
Token
python
pydata__xarray
xarray/core/dtypes.py
{ "start": 556, "end": 8323 }
class ____: def __lt__(self, other): return True def __eq__(self, other): return isinstance(other, type(self)) # Equivalence to np.inf (-np.inf) for object-type INF = AlwaysGreaterThan() NINF = AlwaysLessThan() # Pairs of types that, if both found, should be promoted to object dtype # inste...
AlwaysLessThan
python
ray-project__ray
python/ray/train/v2/tests/util.py
{ "start": 4402, "end": 7193 }
class ____(ObjectRefWrapper): """Mock object that returns the object passed in without going through ray.put.""" def __init__(self, obj): self._obj = obj def get(self): return self._obj _RUN_ID = "mock_run_id" def create_mock_train_run( status: RunStatus = RunStatus.RUNNING, co...
DummyObjectRefWrapper
python
doocs__leetcode
solution/3000-3099/3023.Find Pattern in Infinite Stream I/Solution.py
{ "start": 105, "end": 797 }
class ____: def findPattern( self, stream: Optional["InfiniteStream"], pattern: List[int] ) -> int: a = b = 0 m = len(pattern) half = m >> 1 mask1 = (1 << half) - 1 mask2 = (1 << (m - half)) - 1 for i in range(half): a |= pattern[i] << (half - ...
Solution
python
coleifer__peewee
tests/base_models.py
{ "start": 911, "end": 1047 }
class ____(TestModel): user = ForeignKeyField(User, backref='tweets') content = TextField() timestamp = TimestampField()
Tweet