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
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 72237, "end": 85514 }
class ____(EsmPreTrainedModel): _no_split_modules = ["EsmFoldStructureModule", "EsmFoldTriangularSelfAttentionBlock"] _supports_flash_attn = False _supports_sdpa = False _supports_attention_backend = False _can_record_outputs = None def __init__(self, config): super().__init__(config) ...
EsmForProteinFolding
python
Netflix__metaflow
metaflow/_vendor/click/core.py
{ "start": 54653, "end": 63228 }
class ____(object): r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options...
Parameter
python
allegroai__clearml
clearml/backend_interface/task/repo/scriptinfo.py
{ "start": 27517, "end": 62785 }
class ____(object): _sagemaker_metadata_path = "/opt/ml/metadata/resource-metadata.json" max_diff_size_bytes = 500000 plugins = [GitEnvDetector(), HgEnvDetector(), HgDetector(), GitDetector()] """ Script info detection plugins, in order of priority """ @classmethod def _get_logger(cls) -> log...
ScriptInfo
python
apache__airflow
providers/alibaba/tests/unit/alibaba/cloud/sensors/test_analyticdb_spark.py
{ "start": 1278, "end": 2811 }
class ____: def setup_method(self): self.sensor = AnalyticDBSparkSensor( app_id=MOCK_ADB_SPARK_ID, adb_spark_conn_id=MOCK_ADB_SPARK_CONN_ID, region=MOCK_REGION, task_id=MOCK_SENSOR_TASK_ID, ) @mock.patch(ADB_SPARK_SENSOR_STRING.format("AnalyticDBS...
TestAnalyticDBSparkSensor
python
tensorflow__tensorflow
tensorflow/python/training/optimizer.py
{ "start": 7651, "end": 8882 }
class ____(_OptimizableVariable): """Processor for ordinary Tensors. Even though a Tensor can't really be updated, sometimes it is useful to compute the gradients with respect to a Tensor using the optimizer. Updating the Tensor is, of course, unsupported. """ def __init__(self, v): self._v = v def...
_TensorProcessor
python
walkccc__LeetCode
solutions/1017. Convert to Base -2/1017.py
{ "start": 0, "end": 185 }
class ____: def baseNeg2(self, n: int) -> str: ans = [] while n != 0: ans.append(str(n % 2)) n = -(n >> 1) return ''.join(reversed(ans)) if ans else '0'
Solution
python
ray-project__ray
python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py
{ "start": 2440, "end": 3069 }
class ____: def __init__(self, messages): self.messages = messages def fake_pending_request(prompt=None, messages=None) -> PendingRequest: if prompt is not None: args = [PromptRequest(prompt)] elif messages is not None: args = [ChatRequest(messages)] else: args = [] ...
ChatRequest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 945740, "end": 946134 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("RepositoryTopic", graphql...
RepositoryTopicEdge
python
getsentry__sentry
tests/sentry/auth_v2/endpoints/test_auth_merge_user_accounts.py
{ "start": 1949, "end": 5655 }
class ____(APITestCase): endpoint = "sentry-api-0-auth-merge-accounts" method = "post" def setUp(self) -> None: self.user1 = self.create_user(username="powerful mifu", email="mifu@email.com") self.user2 = self.create_user(username="transcendent mifu", email="mifu@email.com") self.us...
MergeUserAccountsWithSharedEmailTest
python
redis__redis-py
tests/test_search.py
{ "start": 1982, "end": 4577 }
class ____: @staticmethod def waitForIndex(env, idx, timeout=None): delay = 0.1 while True: try: res = env.execute_command("FT.INFO", idx) if int(res[res.index("indexing") + 1]) == 0: break except ValueError: ...
SearchTestsBase
python
ApeWorX__ape
src/ape/api/query.py
{ "start": 5641, "end": 7242 }
class ____(BaseModel, BaseInterface): """ Contract-creation metadata, such as the transaction and deployer. Useful for contract-verification, ``block_identifier=`` usage, and other use-cases. To get contract-creation metadata, you need a query engine that can provide it, such as the ``ape-ether...
ContractCreation
python
dask__dask
dask/dataframe/dask_expr/_reductions.py
{ "start": 35685, "end": 36695 }
class ____(ArrayReduction): _parameters = ["frame", "order"] @functools.cached_property def _meta(self): # Use var as proxy for result dimension return make_meta(meta_nonempty(self.frame._meta).var()) @property def chunk_kwargs(self): return dict(order=self.order) @pro...
Moment
python
django__django
tests/admin_docs/test_views.py
{ "start": 8977, "end": 9751 }
class ____(AdminDocViewTests): def test_templatefilter_index(self): # Overridden because non-trivial TEMPLATES settings aren't supported # but the page shouldn't crash (#24125). response = self.client.get(reverse("django-admindocs-filters")) self.assertContains(response, "<title>Temp...
AdminDocViewWithMultipleEngines
python
realpython__materials
python-string-interpolation/article.py
{ "start": 0, "end": 784 }
class ____: def __init__(self, title, author, pub_date): self.title = title self.author = author self.pub_date = pub_date def __str__(self): return ( f"Article: {self.title}\n" f"Author: {self.author}\n" f"Published: {self.pub_date}\n" ...
Article
python
scipy__scipy
scipy/optimize/_trustregion_dogleg.py
{ "start": 1222, "end": 4389 }
class ____(BaseQuadraticSubproblem): """Quadratic subproblem solved by the dogleg method""" def cauchy_point(self): """ The Cauchy point is minimal along the direction of steepest descent. """ if self._cauchy_point is None: g = self.jac Bg = self.hessp(g)...
DoglegSubproblem
python
pytorch__pytorch
test/nn/test_load_state_dict.py
{ "start": 22468, "end": 24632 }
class ____(TestCase): @skipIfCrossRef @skipIfTorchDynamo("Can't swap with dynamo as dynamo installs weakrefs") @swap([True]) @parametrize("assign", [True, False]) def test_swap_subclass(self, assign): def _create_model(subclass=None): m = torch.nn.Linear(2, 3, bias=False) ...
TestLoadStateDictSwap
python
fluentpython__example-code-2e
15-more-types/cafeteria/cafeteria.py
{ "start": 476, "end": 541 }
class ____(Garbage): """Biodegradable garbage."""
Biodegradable
python
huggingface__transformers
src/transformers/models/glm/modeling_glm.py
{ "start": 9769, "end": 12932 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: GlmConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", confi...
GlmAttention
python
apache__airflow
providers/apache/beam/tests/unit/apache/beam/operators/test_beam.py
{ "start": 40872, "end": 46986 }
class ____: @pytest.fixture(autouse=True) def setup_test_cases(self, default_options, pipeline_options, py_options): self.default_op_kwargs = { "task_id": TASK_ID, "py_file": PY_FILE, "py_options": copy.deepcopy(py_options), "default_pipeline_options": cop...
TestBeamRunPythonPipelineOperatorAsync
python
dask__dask
dask/dataframe/dask_expr/_merge.py
{ "start": 1293, "end": 18842 }
class ____(Expr): """Merge / join two dataframes This is an abstract class. It will be transformed into a concrete implementation before graph construction. See Also -------- BlockwiseMerge Repartition Shuffle """ _parameters = [ "left", "right", "how"...
Merge
python
doocs__leetcode
solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/Solution.py
{ "start": 0, "end": 1211 }
class ____: def minimumDifference(self, nums: List[int]) -> int: n = len(nums) >> 1 f = defaultdict(set) g = defaultdict(set) for i in range(1 << n): s = cnt = 0 s1 = cnt1 = 0 for j in range(n): if (i & (1 << j)) != 0: ...
Solution
python
django__django
django/contrib/humanize/templatetags/humanize.py
{ "start": 7417, "end": 12859 }
class ____: time_strings = { # Translators: delta will contain a string like '2 months' or # '1 month, 2 weeks' "past-day": gettext_lazy("%(delta)s ago"), # Translators: please keep a non-breaking space (U+00A0) between count # and time unit. "past-hour": ngettext_laz...
NaturalTimeFormatter
python
Pylons__pyramid
tests/test_session.py
{ "start": 87, "end": 10731 }
class ____: def test_ctor_no_cookie(self): request = testing.DummyRequest() session = self._makeOne(request) self.assertEqual(dict(session), {}) def test_instance_conforms(self): from zope.interface.verify import verifyObject from pyramid.interfaces import ISession ...
SharedCookieSessionTests
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 172229, "end": 172350 }
class ____: def test_modfresnelp(self): pass def test_modfresnelm(self): pass
TestFresnelIntegral
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/pex_builder/deploy.py
{ "start": 404, "end": 1301 }
class ____: """Inputs and outputs for each code location.""" location: parse_workspace.Location # local dependencies are packaged with the source.pex along with the main code location local_packages: deps.LocalPackages # all other dependencies are packaged in the deps.pex deps_requirements: d...
LocationBuild
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 37265, "end": 45361 }
class ____(DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefnumber): """ AngleDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the begi...
AngleDatum
python
tensorflow__tensorflow
tensorflow/python/distribute/sharded_variable.py
{ "start": 4186, "end": 6423 }
class ____(Partitioner): """Partitioner that allocates a minimum size per shard. This partitioner ensures each shard has at least `min_shard_bytes`, and tries to allocate as many shards as possible, i.e., keeping shard size as small as possible. The maximum number of such shards (upper bound) is given by `ma...
MinSizePartitioner
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 39421, "end": 41191 }
class ____(ASTDeclarator): def __init__( self, declId: ASTNestedName, arrayOps: list[ASTArray], param: ASTParameters ) -> None: self.declId = declId self.arrayOps = arrayOps self.param = param def __eq__(self, other: object) -> bool: if not isinstance(other, ASTDecla...
ASTDeclaratorNameParam
python
crytic__slither
slither/detectors/assembly/return_instead_of_leave.py
{ "start": 253, "end": 1998 }
class ____(AbstractDetector): """ Check for cases where a return(a,b) is used in an assembly function that also returns two variables """ ARGUMENT = "return-leave" HELP = "If a `return` is used instead of a `leave`." IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.M...
ReturnInsteadOfLeave
python
pyqtgraph__pyqtgraph
tests/test_stability.py
{ "start": 3340, "end": 3698 }
class ____(Exception): pass def raiseException(): p('raise exception') raise TstException("A test exception") def addReference(): p('add reference') global widgets if len(widgets) < 1: return obj1 = randItem(widgets) obj2 = randItem(widgets) p(' %s -> %s' % (obj1, obj2))...
TstException
python
django__django
tests/db_functions/models.py
{ "start": 1057, "end": 1542 }
class ____(models.Model): name = models.CharField(max_length=32) start_datetime = models.DateTimeField(null=True, blank=True) end_datetime = models.DateTimeField(null=True, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) start_t...
DTModel
python
coleifer__peewee
examples/graph.py
{ "start": 575, "end": 2131 }
class ____(Base): src = ForeignKeyField(Node, backref='outgoing_edges') dest = ForeignKeyField(Node, backref='incoming_edges') weight = FloatField() db.create_tables([Node, Edge]) nodes = [Node.create(name=c) for c in 'abcde'] g = ( ('a', 'b', -1), ('a', 'c', 4), ('b', 'c', 3), ('b', 'd'...
Edge
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 46650, "end": 48273 }
class ____(SpmConverter): handle_byte_fallback = True SpmExtractor = GemmaSentencePieceExtractor # start and end of turn tokens must be marked as special special_tokens = {"<start_of_turn>", "<end_of_turn>"} """" split_by_unicode_script: true split_by_number: true split_by_whitespace: t...
GemmaConverter
python
coleifer__peewee
tests/models.py
{ "start": 67988, "end": 71009 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [Sample] def test_coerce(self): for i in range(3): Sample.create(counter=i, value=i) counter_group = fn.GROUP_CONCAT(Sample.counter).coerce(False) query = Sample.select(counter_group.alias('counter')) ...
TestFunctionCoerce
python
django__django
tests/servers/tests.py
{ "start": 5773, "end": 6206 }
class ____(LiveServerBase): @classmethod def setUpClass(cls): super().setUpClass() # put it in a list to prevent descriptor lookups in test cls.live_server_url_test = [cls.live_server_url] def test_live_server_url_is_class_property(self): self.assertIsInstance(self.live_serv...
LiveServerAddress
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 45800, "end": 46060 }
class ____(TestSubsets, TestCase): left = OrderedSet() right = OrderedSet([1, 2]) name = "one empty, one non-empty" cases = "!=", "<", "<=" # ------------------------------------------------------------------------------
TestSubsetEmptyNonEmpty
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 212517, "end": 213189 }
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("BypassForcePushAllowanceEdge"), graphql_name="edges" ) no...
BypassForcePushAllowanceConnection
python
pypa__hatch
tests/config/test_model.py
{ "start": 22066, "end": 33120 }
class ____: def test_not_table(self, helpers): config = RootConfig({"template": 9000}) with pytest.raises( ConfigurationError, match=helpers.dedent( """ Error parsing config: template must be a table""" ...
TestTemplate
python
pytorch__pytorch
test/dynamo/test_repros.py
{ "start": 6314, "end": 7976 }
class ____: # from detectron2 poolers.py def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2). """ device = ( tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") ...
Boxes
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py
{ "start": 41147, "end": 49580 }
class ____(HourlyReportsTestWithStateChangesAfterMigration): stream_name = "campaign_impression_performance_report_hourly" report_file = "campaign_impression_performance_report_hourly" records_number = 24 state_file = "hourly_reports_state" incremental_report_file = "campaign_impression_performance_...
TestCampaignImpressionPerformanceReportHourlyStream
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 125368, "end": 127974 }
class ____(unittest.TestCase): # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests # assumptions used by sendmsg() and recvmsg[_into](), which share # code with these functions. # Match the definition in socketmodule.c try: import _testcapi except ImportError: socklen_t_lim...
CmsgMacroTests
python
huggingface__transformers
src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py
{ "start": 2323, "end": 8043 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` # Ignore copy def __init__(self, config: RecurrentGemmaConfig, device=None): super().__init__() self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: C...
RecurrentGemmaRotaryEmbedding
python
PyCQA__pylint
doc/data/messages/i/invalid-format-returned/bad.py
{ "start": 0, "end": 148 }
class ____: """__format__ returns <type 'int'>""" def __format__(self, format_spec): # [invalid-format-returned] return 1
CustomFormat
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 13048, "end": 13127 }
class ____(Instruction): __slots__ = ("key",) key: Key @dataclass
Execute
python
bokeh__bokeh
src/bokeh/io/notebook.py
{ "start": 2487, "end": 4853 }
class ____: ''' ''' _json: Any = {} _cellno: int | None _doc: Document def __init__(self, comms: Comm, cell_doc: Document) -> None: self._cellno = None try: from IPython import get_ipython ip = get_ipython() assert ip is not None ...
CommsHandle
python
aio-libs__aiohttp
tests/test_client_response.py
{ "start": 540, "end": 47547 }
class ____(mock.AsyncMock): def done(self) -> bool: return True @pytest.fixture def session() -> mock.Mock: return mock.Mock() async def test_http_processing_error(session: ClientSession) -> None: loop = mock.Mock() url = URL("http://del-cl-resp.org") response = ClientResponse( "...
WriterMock
python
apache__airflow
providers/google/tests/unit/google/suite/hooks/test_calendar.py
{ "start": 1542, "end": 3678 }
class ____: def setup_method(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = GoogleCalendarHook(api_version=API_VERSION, gcp_conn_id=GCP_CONN_ID) @m...
TestGoogleCalendarHook
python
eth-brownie__brownie
brownie/typing.py
{ "start": 3494, "end": 3614 }
class ____(TypedDict): version: NotRequired[Optional[str]] evm_version: NotRequired[EvmVersion] @final
VyperConfig
python
coleifer__peewee
tests/schema.py
{ "start": 453, "end": 516 }
class ____(TestModel): data = TextField(unique=True)
TMUnique
python
pandas-dev__pandas
pandas/tests/indexes/multi/test_indexing.py
{ "start": 348, "end": 5065 }
class ____: def test_slice_locs_partial(self, idx): sorted_idx, _ = idx.sortlevel(0) result = sorted_idx.slice_locs(("foo", "two"), ("qux", "one")) assert result == (1, 5) result = sorted_idx.slice_locs(None, ("qux", "one")) assert result == (0, 5) result = sorted_...
TestSliceLocs
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_ignored_modules.py
{ "start": 2222, "end": 2708 }
class ____(Model): """Adds a variable number of :class:`IgnoredModule` to ``self.layer1``.""" def __init__(self, num_ignored: int) -> None: assert num_ignored >= 0 super().__init__() layer1_modules = ( [torch.nn.Linear(5, 4), torch.nn.Linear(4, 4)] + [IgnoredModu...
ModelWithIgnoredModules
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-qianfan/llama_index/llms/qianfan/base.py
{ "start": 1453, "end": 3942 }
class ____(BaseModel): """ Chat response model. """ result: str def build_chat_request( stream: bool, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatRequest: """ Construct a ChatRequest. :param messages: The chat message list. :param stream: Indicate whether to respond i...
ChatResp
python
walkccc__LeetCode
solutions/360. Sort Transformed Array/360.py
{ "start": 0, "end": 858 }
class ____: def sortTransformedArray( self, nums: list[int], a: int, b: int, c: int, ) -> list[int]: n = len(nums) upward = a > 0 ans = [0] * n # The concavity of f only depends on a's sign. def f(x: int, a: int, b: int, c: int) -> int: return (a * x + b) * x...
Solution
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 25283, "end": 27498 }
class ____(Span): """Render stacked inline.""" def __init__( self, formset_field_name: str, card_desktop: int = 12, card_tablet: int = 8, card_mobile: int = 4, **kwargs, ): assert 1 <= card_desktop <= 12 self.card_desktop = card_desktop ...
FormSet
python
getsentry__sentry
src/sentry/replays/usecases/query/conditions/selector.py
{ "start": 3243, "end": 4637 }
class ____(GenericBase): """Click array condition class. Click array conditions can only be applied to click rows otherwise certain types of conditional checks will match against non-click rows and return incorrect data. For example, this query would return incorrect results without checking if the con...
ClickArray
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sqlite_datasource.py
{ "start": 1844, "end": 3406 }
class ____(_PartitionerOneColumnOneParam): """A partitioner than can be used for sql engines that represents datetimes as strings. The SQL engine that this currently supports is SQLite since it stores its datetimes as strings. The DatetimePartitioner will also work for SQLite and may be more intuitive....
PartitionerConvertedDateTime
python
python-pillow__Pillow
Tests/test_file_jpeg.py
{ "start": 813, "end": 43266 }
class ____: def roundtrip_with_bytes( self, im: Image.Image, **options: Any ) -> tuple[JpegImagePlugin.JpegImageFile, int]: out = BytesIO() im.save(out, "JPEG", **options) test_bytes = out.tell() out.seek(0) reloaded = cast(JpegImagePlugin.JpegImageFile, Image.ope...
TestFileJpeg
python
dagster-io__dagster
python_modules/dagster/dagster/_core/code_pointer.py
{ "start": 12034, "end": 12424 }
class ____(CodePointer): module: str working_directory: Optional[str] def load_target(self) -> object: from dagster.components.core.load_defs import load_defs module = load_python_module(self.module, self.working_directory) return load_defs(module) def describe(self) -> str: ...
AutoloadDefsModuleCodePointer
python
pytorch__pytorch
test/export/random_dag.py
{ "start": 6995, "end": 8618 }
class ____(Unflatten): """ Generates test that unflattens a model with several nn.Modules that call each other and access and mutate buffers. The modules are generated by calling the nn_module_generator() method. """ def nn_module_generator(self): class GenNNModule(NNModuleGenerator): ...
BufferUnflatten
python
cython__cython
tests/run/test_subclassinit.py
{ "start": 120, "end": 9480 }
class ____(unittest.TestCase): if not hasattr(unittest.TestCase, 'assertRegex'): def assertRegex(self, value, regex): self.assertTrue(re.search(regex, str(value)), "'%s' did not match '%s'" % (value, regex)) if not hasattr(unittest.TestCase, 'assertCountEqual'): ...
Test
python
kamyu104__LeetCode-Solutions
Python/evaluate-division.py
{ "start": 1635, "end": 2483 }
class ____(object): def __init__(self): self.set = {} def find_set(self, x): xp, xr = self.set.setdefault(x, (x, 1.0)) if x != xp: pp, pr = self.find_set(xp) # path compression. self.set[x] = (pp, xr*pr) # x/pp = xr*pr return self.set[x] def union_...
UnionFindPathCompressionOnly
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/handle.py
{ "start": 5014, "end": 5762 }
class ____: """Compound ID object for the two id schemes that state is recorded in the database against.""" remote_origin_id: str selector_id: str def to_string(self) -> str: return f"{self.remote_origin_id}{_DELIMITER}{self.selector_id}" @staticmethod def from_string(serialized: str)...
CompoundID
python
facebook__pyre-check
api/tests/connection_test.py
{ "start": 389, "end": 6042 }
class ____(unittest.TestCase): # pyre-ignore[56] @patch.object( PyreConnection, "_validate_query_response", side_effect=lambda response: response, ) @patch("subprocess.run") def test_query_server( self, run: MagicMock, _validate_query_response: MagicMock ) -> None...
ConnectionApiTest
python
pennersr__django-allauth
allauth/headless/spec/views.py
{ "start": 383, "end": 802 }
class ____(View): def get(self, request): import yaml spec = get_schema() content = yaml.dump(spec, Dumper=yaml.Dumper) return HttpResponse( content, content_type="application/vnd.oai.openapi", headers={"Content-Disposition": "inline; filename=all...
OpenAPIYAMLView
python
urllib3__urllib3
test/with_dummyserver/test_https.py
{ "start": 1814, "end": 46384 }
class ____(HTTPSHypercornDummyServerTestCase): tls_protocol_name: str | None = None def tls_protocol_not_default(self) -> bool: return self.tls_protocol_name in {"TLSv1", "TLSv1.1"} def tls_version(self) -> ssl.TLSVersion: if self.tls_protocol_name is None: return pytest.skip("...
BaseTestHTTPS
python
python-pillow__Pillow
src/PIL/IcnsImagePlugin.py
{ "start": 7902, "end": 12405 }
class ____(ImageFile.ImageFile): """ PIL image support for Mac OS .icns files. Chooses the best resolution, but will possibly load a different size image if you mutate the size attribute before calling 'load'. The info dictionary has a key 'sizes' that is a list of sizes that the icns file ...
IcnsImageFile
python
tensorflow__tensorflow
tensorflow/python/training/input.py
{ "start": 16565, "end": 68139 }
class ____: """Store information about the Tensor: Is it sparse?, map_op, and rank.""" def __init__(self, sparse, map_op, rank): """Create the metadata. Args: sparse: Python boolean. map_op: The `Operation` that created the `SparseTensorsMap` in question. This Op contains information a...
_SparseMetaData
python
joke2k__faker
faker/providers/ssn/ko_KR/__init__.py
{ "start": 41, "end": 252 }
class ____(SsnProvider): ssn_formats = ( "##0#0#-1######", "##0#1#-1######", "##0#2#-1######", "##0#0#-2######", "##0#1#-2######", "##0#2#-2######", )
Provider
python
simplejson__simplejson
simplejson/tests/test_speedups.py
{ "start": 740, "end": 1313 }
class ____(TestCase): @skip_if_speedups_missing def test_make_scanner(self): self.assertRaises(AttributeError, scanner.c_make_scanner, 1) @skip_if_speedups_missing def test_bad_bool_args(self): def test(value): decoder.JSONDecoder(strict=BadBool()).decode(value) self...
TestDecode
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py
{ "start": 40, "end": 123 }
class ____: def __hash__(self): return True # [invalid-hash-return]
Bool
python
hynek__structlog
tests/test_contextvars.py
{ "start": 7128, "end": 9087 }
class ____: def test_cleanup(self): """ Bindings are cleaned up """ with bound_contextvars(x=42, y="foo"): assert {"x": 42, "y": "foo"} == get_contextvars() assert {} == get_contextvars() def test_cleanup_conflict(self): """ Overwritten keys ...
TestBoundContextvars
python
pytorch__pytorch
test/mobile/model_test/tensor_ops.py
{ "start": 15, "end": 3036 }
class ____(torch.nn.Module): def forward(self): return self.tensor_general_ops() def tensor_general_ops(self): a = torch.randn(4) b = torch.tensor([1.5]) x = torch.ones((2,)) c = torch.randn(4, dtype=torch.cfloat) w = torch.rand(4, 4, 4, 4) v = torch.rand...
TensorOpsModule
python
scipy__scipy
benchmarks/benchmarks/test_functions.py
{ "start": 2827, "end": 3283 }
class ____: target_E = 0. solution = np.array([1., 3.]) xmin = np.array([-10., -10.]) xmax = np.array([10., 10.]) def fun(self, coords): x, y = coords return (x + 2. * y - 7.)**2 + (2. * x + y - 5.)**2 def der(self, coords): x, y = coords dfdx = 2. * (x + 2. * y...
Booth
python
django__django
django/contrib/gis/db/backends/oracle/models.py
{ "start": 1421, "end": 2080 }
class ____(models.Model, SpatialRefSysMixin): "Maps to the Oracle MDSYS.CS_SRS table." cs_name = models.CharField(max_length=68) srid = models.IntegerField(primary_key=True) auth_srid = models.IntegerField() auth_name = models.CharField(max_length=256) wktext = models.CharField(max_length=2046)...
OracleSpatialRefSys
python
walkccc__LeetCode
solutions/2454. Next Greater Element IV/2454.py
{ "start": 0, "end": 890 }
class ____: def secondGreaterElement(self, nums: list[int]) -> list[int]: ans = [-1] * len(nums) # a decreasing stack that stores indices that met the first greater number. prevStack = [] # a decreasing stack that stores indices. currStack = [] for i, num in enumerate(nums): # Indices i...
Solution
python
pytorch__pytorch
.ci/lumen_cli/tests/test_docker_helper.py
{ "start": 183, "end": 2973 }
class ____(unittest.TestCase): def setUp(self): # Reset the singleton in the target module patcher = mock.patch("cli.lib.common.docker_helper._docker_client", None) self.addCleanup(patcher.stop) patcher.start() def test_local_image_exists_true(self): # Mock a docker clie...
TestDockerImageHelpers
python
huggingface__transformers
src/transformers/models/lfm2/modeling_lfm2.py
{ "start": 15871, "end": 19452 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Lfm2Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size //...
Lfm2Attention
python
pytorch__pytorch
test/test_fake_tensor.py
{ "start": 44162, "end": 44849 }
class ____(TestCase): @ops(custom_op_db, dtypes=OpDTypes.any_one) def test_fake(self, device, dtype, op): sample_inputs_itr = op.sample_inputs(device, dtype, requires_grad=False) for sample_input in sample_inputs_itr: args = (sample_input.input,) + sample_input.args kwarg...
FakeTensorOpInfoTest
python
simonw__sqlite-utils
sqlite_utils/db.py
{ "start": 5839, "end": 5897 }
class ____(Exception): "Error altering table"
AlterError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 671041, "end": 672446 }
class ____(sgqlc.types.Type): """Autogenerated return type of GrantEnterpriseOrganizationsMigratorRole """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "organizations") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identif...
GrantEnterpriseOrganizationsMigratorRolePayload
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py
{ "start": 3985, "end": 4363 }
class ____(Generic[T1, *Ts2]): ... tc1 = ClassTC() reveal_type(tc1, expected_text="ClassTC[str, *tuple[str, ...]]") tc2 = ClassTC[int]() reveal_type(tc2, expected_text="ClassTC[int, *tuple[int, ...]]") tc3 = ClassTC[int, *tuple[()]]() reveal_type(tc3, expected_text="ClassTC[int]") tc4 = ClassTC[int, *tuple[None]](...
ClassTC
python
imageio__imageio
imageio/core/util.py
{ "start": 3647, "end": 6142 }
class ____(np.ndarray): """Array(array, meta=None) A subclass of np.ndarray that has a meta attribute. Get the dictionary that contains the meta data using ``im.meta``. Convert to a plain numpy array using ``np.asarray(im)``. """ def __new__(cls, array, meta=None): # Check if ...
Array
python
allegroai__clearml
clearml/backend_api/services/v2_13/projects.py
{ "start": 56227, "end": 63402 }
class ____(Response): """ Response of projects.get_all endpoint. :param projects: Projects list :type projects: Sequence[ProjectsGetAllResponseSingle] """ _service = "projects" _action = "get_all" _version = "2.13" _schema = { "definitions": { "projects_get_all_...
GetAllResponse
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 15949, "end": 26879 }
class ____: def test_division_int(self): # int division should follow Python x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) if 5 / 10 == 0.5: assert_equal(x / 100, [0.05, 0.1, 0.9, 1, -0.05, -0.1, -0.9, -1, -1.2]) else: ...
TestDivision
python
astropy__astropy
astropy/cosmology/_src/tests/io/base.py
{ "start": 915, "end": 1873 }
class ____(IOTestBase): """Tests for a Cosmology[To/From]Format with some ``format``. This class will not be directly called by :mod:`pytest` since its name does not begin with ``Test``. To activate the contained tests this class must be inherited in a subclass. Subclasses must define a :func:`pytest.f...
ToFromTestMixinBase
python
doocs__leetcode
lcof/面试题29. 顺时针打印矩阵/Solution.py
{ "start": 0, "end": 639 }
class ____: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix or not matrix[0]: return [] dirs = (0, 1, 0, -1, 0) m, n = len(matrix), len(matrix[0]) vis = [[False] * n for _ in range(m)] ans = [] i = j = k = 0 for _ in rang...
Solution
python
pytorch__pytorch
benchmarks/transformer/sdp.py
{ "start": 1462, "end": 2281 }
class ____: nn_mha_time: float compiled_nn_mha_time: Optional[float] composite_mha_time: float compiled_composite_mha_time: Optional[float] def get_entries(self) -> list: return [ f"{self.nn_mha_time:2f}", f"{self.compiled_nn_mha_time:2f}" if self.compiled_nn_mha_tim...
ExperimentResults
python
google__jax
jax/_src/linear_util.py
{ "start": 9972, "end": 10050 }
class ____: pass initial_result_paths = InitialResultPaths()
InitialResultPaths
python
getsentry__sentry
src/sentry/issues/endpoints/organization_group_search_view_details.py
{ "start": 1029, "end": 1373 }
class ____(TypedDict): id: str name: NotRequired[str] query: NotRequired[str] querySort: NotRequired[SORT_LITERALS] projects: NotRequired[list[int]] isAllProjects: NotRequired[bool] environments: NotRequired[list[str]] timeFilters: NotRequired[dict[str, Any]] @region_silo_endpoint
GroupSearchViewValidatorResponse
python
numba__numba
numba/cuda/tests/cudapy/test_fastmath.py
{ "start": 429, "end": 1117 }
class ____: fast_expected: List[str] = field(default_factory=list) fast_unexpected: List[str] = field(default_factory=list) prec_expected: List[str] = field(default_factory=list) prec_unexpected: List[str] = field(default_factory=list) def check(self, test: CUDATestCase, fast: str, prec: str): ...
FastMathCriterion
python
dagster-io__dagster
python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py
{ "start": 38852, "end": 39920 }
class ____(ColumnConstraint): """A column constraint that validates the pandas column dtypes based on the expected set of dtypes. Args: expected_dtype_set (Set[str]): The set of pandas dtypes that the pandas column dtypes must match. """ def __init__(self, expected_dtype_set): self.exp...
ColumnDTypeInSetConstraint
python
pydata__xarray
xarray/core/_typed_ops.py
{ "start": 17896, "end": 30491 }
class ____: __slots__ = () def _binary_op( self, other: DaCompatible, f: Callable, reflexive: bool = False ) -> Self: raise NotImplementedError @overload def __add__(self, other: Dataset) -> Dataset: ... @overload def __add__(self, other: DataTree) -> DataTree: ... @o...
DataArrayOpsMixin
python
bokeh__bokeh
tests/unit/bokeh/embed/test_bundle.py
{ "start": 8048, "end": 9051 }
class ____: def test_without_tables(self) -> None: assert beb._use_tables(beb._all_objs([plot()])) is False assert beb._use_tables(beb._all_objs([plot(), glplot()])) is False assert beb._use_tables(beb._all_objs([plot(), widget()])) is False d = Document() d.add_root(plot()) ...
Test__use_tables
python
spack__spack
lib/spack/spack/cmd/create.py
{ "start": 9006, "end": 9453 }
class ____(PackageTemplate): """Provides appropriate overrides for SCons-based packages""" base_class_name = "SConsPackage" package_class_import = "from spack_repo.builtin.build_systems.scons import SConsPackage" body_def = """\ def build_args(self, spec, prefix): # FIXME: Add arguments to...
SconsPackageTemplate
python
pytorch__pytorch
test/test_autograd.py
{ "start": 488099, "end": 505424 }
class ____(TestCase): def get_default_streams(self, num_devices=1): out = [] for i in range(num_devices): with _set_device_index(i): acc = torch.accelerator.current_accelerator() out.append(torch.get_device_module(acc).default_stream()) return tupl...
TestAutogradStreamSynchronization
python
keras-team__keras
keras/src/saving/saving_lib_test.py
{ "start": 3191, "end": 3569 }
class ____(keras.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.dense1 = MyDense(1) def compile(self, *args, **kwargs): super().compile(*args, **kwargs) def call(self, inputs): return self.dense1(inputs) @keras.saving.register_keras_se...
CompileOverridingModel
python
huggingface__transformers
src/transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py
{ "start": 4368, "end": 4572 }
class ____(LlamaDecoderLayer): def __init__(self, config: HunYuanDenseV1Config, layer_idx: int): super().__init__(config, layer_idx) self.layer_idx = layer_idx
HunYuanDenseV1DecoderLayer
python
graphql-python__graphene
examples/context_example.py
{ "start": 105, "end": 698 }
class ____(graphene.ObjectType): me = graphene.Field(User) def resolve_me(root, info): return info.context["user"] schema = graphene.Schema(query=Query) query = """ query something{ me { id name } } """ def test_query(): result = schema.execute(query, context...
Query
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/concurrency.py
{ "start": 9240, "end": 10314 }
class ____: """Asyncio util for test suite/ util only""" def __init__(self) -> None: self.runner = _Runner() # runner it lazy so it can be created here def run( self, fn: Callable[..., Coroutine[Any, Any, _T]], *args: Any, **kwargs: Any, ) -> _T: """Run...
_AsyncUtil
python
ray-project__ray
rllib/utils/replay_buffers/replay_buffer.py
{ "start": 822, "end": 2068 }
class ____(Enum): """Specifies how batches are structured in a ReplayBuffer. timesteps: One buffer slot per timestep. sequences: One buffer slot per sequence. episodes: One buffer slot per episode. fragemts: One buffer slot per incoming batch. """ TIMESTEPS = "timesteps" SEQUENCES = "s...
StorageUnit