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
ray-project__ray
python/ray/autoscaler/v2/instance_manager/config.py
{ "start": 3729, "end": 4867 }
class ____: """ NodeTypeConfig is the helper class to provide node type specific configs. This maps to subset of the `available_node_types` field in the autoscaling config. """ # Node type name name: NodeType # The minimal number of worker nodes to be launched for this node type. mi...
NodeTypeConfig
python
pyca__cryptography
src/cryptography/hazmat/decrepit/ciphers/algorithms.py
{ "start": 1671, "end": 1942 }
class ____(BlockCipherAlgorithm): name = "SEED" block_size = 128 key_sizes = frozenset([128]) def __init__(self, key: bytes): self.key = _verify_key_size(self, key) @property def key_size(self) -> int: return len(self.key) * 8
SEED
python
kamyu104__LeetCode-Solutions
Python/maximum-partition-factor.py
{ "start": 1844, "end": 3644 }
class ____(object): def maxPartitionFactor(self, points): """ :type points: List[List[int]] :rtype: int """ class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n) def __init__(self, n): self.set = range(n) self.rank = [0]*n ...
Solution2
python
facebookresearch__faiss
faiss/python/extra_wrappers.py
{ "start": 8853, "end": 12936 }
class ____: def __init__(self, capacity): self.log2_capacity = int(np.log2(capacity)) assert capacity == 2 ** self.log2_capacity, "need power of 2 capacity" self.capacity = capacity self.tab = np.empty((capacity, 2), dtype='int64') faiss.hashtable_int64_to_int64_init(self.lo...
MapInt64ToInt64
python
scikit-image__scikit-image
tests/skimage/morphology/test_skeletonize.py
{ "start": 10757, "end": 13680 }
class ____: def test_all_zeros(self): result = medial_axis(np.zeros((10, 10), dtype=bool)) assert np.all(result == False) def test_all_zeros_masked(self): result = medial_axis( np.zeros((10, 10), dtype=bool), np.zeros((10, 10), dtype=bool) ) assert np.all(res...
TestMedialAxis
python
mlflow__mlflow
mlflow/server/handlers.py
{ "start": 7310, "end": 8352 }
class ____(TrackingStoreRegistry): def __init__(self): super().__init__() self.register("", self._get_file_store) self.register("file", self._get_file_store) for scheme in DATABASE_ENGINES: self.register(scheme, self._get_sqlalchemy_store) # Add support for Databr...
TrackingStoreRegistryWrapper
python
python__mypy
mypy/errors.py
{ "start": 10456, "end": 12233 }
class ____(ErrorWatcher): """Error watcher that filters and separately collects `unreachable` errors, `redundant-expr` and `redundant-casts` errors, and revealed types when analysing code sections iteratively to help avoid making too-hasty reports.""" iteration_dependent_errors: IterationDependentError...
IterationErrorWatcher
python
kamyu104__LeetCode-Solutions
Python/throne-inheritance.py
{ "start": 128, "end": 1192 }
class ____(object): def __init__(self, kingName): """ :type kingName: str """ self.__king = kingName self.__family_tree = collections.defaultdict(list) self.__dead = set() def birth(self, parentName, childName): """ :type parentName: str...
ThroneInheritance
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 25754, "end": 25869 }
class ____(Structure): _fields_ = (("name", lc_str),) def describe(self): return {}
dylinker_command
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-equal-array-elements.py
{ "start": 29, "end": 207 }
class ____(object): def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ return sum(nums) - len(nums) * min(nums)
Solution
python
aio-libs__aiohttp
aiohttp/web_urldispatcher.py
{ "start": 26659, "end": 27627 }
class ____(PrefixedSubAppResource): def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None: AbstractResource.__init__(self) self._prefix = "" self._app = app self._rule = rule @property def canonical(self) -> str: return self._rule.canonical ...
MatchedSubAppResource
python
dagster-io__dagster
python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py
{ "start": 15724, "end": 18225 }
class ____(ConstraintWithMetadata): """Similar to the base class, but now your validation functions should take in columns (pd.Series) not Dataframes. Args: description (str): description of the constraint validation_fn (Callable[[pd.Series], Tuple[bool, dict[str, Union[dict,list, str, set]]]]:...
ColumnAggregateConstraintWithMetadata
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 12185, "end": 12887 }
class ____: """Utility class, to be used to test an instructions list. See :meth:`Instruction.match`. """ cls: type[Instruction] kwargs: dict[str, Any] def __init__(self, cls: type[Instruction], **kwargs: Any): self.cls = cls self.kwargs = kwargs def __repr__(self) -> str:...
_InstructionMatch
python
OmkarPathak__pygorithm
tests/test_math.py
{ "start": 372, "end": 557 }
class ____(unittest.TestCase): def test_sieve_of_eratosthenes(self): self.assertEqual(sieve_of_eratosthenes.sieve_of_eratosthenes(11), [2, 3, 5, 7, 11])
TestSieveOfEratosthenes
python
keon__algorithms
tests/test_strings.py
{ "start": 3245, "end": 3652 }
class ____(unittest.TestCase): """[summary] Test for the file domain_extractor.py Arguments: unittest {[type]} -- [description] """ def test_valid(self): self.assertEqual(domain_name_1("https://github.com/SaadBenn"), "github") def test_invalid(self): ...
TestDomainExtractor
python
gevent__gevent
src/greentest/3.12/test_socket.py
{ "start": 189963, "end": 196624 }
class ____(ThreadedTCPSocketTest): def __init__(self, methodName='runTest'): self.event = threading.Event() ThreadedTCPSocketTest.__init__(self, methodName=methodName) def assert_sock_timeout(self, sock, timeout): self.assertEqual(self.serv.gettimeout(), timeout) blocking = (t...
NonBlockingTCPTests
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 7654, "end": 8686 }
class ____(util.MdCase): """Test custom language prefix.""" extension = ['pymdownx.highlight', 'pymdownx.superfences', 'pymdownx.inlinehilite'] extension_configs = { 'pymdownx.highlight': { 'language_prefix': 'lang-', 'use_pygments': False } } def test_custo...
TestCustomLangPrefixNoPygments
python
sphinx-doc__sphinx
sphinx/roles.py
{ "start": 13537, "end": 14124 }
class ____(SphinxRole): amp_re = re.compile(r'(?<!&)&(?![&\s])') def run(self) -> tuple[list[Node], list[system_message]]: node = nodes.inline(rawtext=self.rawtext, classes=[self.name]) spans = self.amp_re.split(self.text) node += nodes.Text(spans.pop(0)) for span in spans: ...
GUILabel
python
Netflix__metaflow
metaflow/plugins/aws/batch/batch.py
{ "start": 1139, "end": 1227 }
class ____(MetaflowException): headline = "AWS Batch task killed"
BatchKilledException
python
google__jax
jaxlib/mosaic/python/layout_defs.py
{ "start": 1155, "end": 1422 }
class ____(enum.Enum): REPLICATED = "*" def __repr__(self): return "*" __str__ = __repr__ def __bool__(self): return False # Useful because we can then say `offset or 0` REPLICATED = Replicated.REPLICATED Offset = int | Literal[REPLICATED]
Replicated
python
yaml__pyyaml
lib/yaml/emitter.py
{ "start": 426, "end": 967 }
class ____: def __init__(self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block): self.scalar = scalar self.empty = empty self.multiline = multiline self.allow_flow_plain = allow_f...
ScalarAnalysis
python
pytorch__pytorch
test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py
{ "start": 6858, "end": 16709 }
class ____(TestCase, CustomAssertMixin): def setUp(self) -> None: self._backend = FakeRendezvousBackend() mock_get_state = MagicMock(wraps=self._backend.get_state) mock_set_state = MagicMock(wraps=self._backend.set_state) self._mock_backend = Mock() self._mock_backend.get_s...
BackendRendezvousStateHolderTest
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 22886, "end": 24757 }
class ____(SingleContinuousDistribution): _argnames = ('k', 'l') @staticmethod def check(k, l): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") _value_check(l > 0, "Shift par...
ChiNoncentralDistribution
python
django__django
tests/i18n/test_extraction.py
{ "start": 35372, "end": 37350 }
class ____(ExtractorTests): PO_FILE_ES = "locale/es/LC_MESSAGES/django.po" def test_copy_plural_forms(self): management.call_command("makemessages", locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE) as fp: po_contents = fp.re...
CopyPluralFormsExtractorTests
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/test_task_concurrency.py
{ "start": 1148, "end": 2572 }
class ____: def _get_task(self, **kwargs): return BaseOperator(task_id="test_task", dag=DAG("test_dag", schedule=None), **kwargs) @pytest.mark.parametrize( ("kwargs", "num_running_tis", "is_task_concurrency_dep_met"), [ ({}, None, True), ({"max_active_tis_per_dag...
TestTaskConcurrencyDep
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 40619, "end": 41680 }
class ____(sympy.Function): is_real = True precedence: int = 35 # lower precedence than add @classmethod def eval(cls, base, divisor): # assert base.is_integer is not True, base # assert divisor.is_integer is not True, divisor if divisor.is_zero: raise ZeroDivisio...
FloatTrueDiv
python
coleifer__peewee
tests/libs/mock.py
{ "start": 62047, "end": 62774 }
class ____(object): "A helper object that compares equal to everything." def __eq__(self, other): return True def __ne__(self, other): return False def __repr__(self): return '<ANY>' ANY = _ANY() def _format_call_signature(name, args, kwargs): message = '%s(%%s)' % nam...
_ANY
python
plotly__plotly.py
plotly/graph_objs/indicator/_title.py
{ "start": 233, "end": 3789 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator" _path_str = "indicator.title" _valid_props = {"align", "font", "text"} @property def align(self): """ Sets the horizontal alignment of the title. It defaults to `center` except for bullet charts for which it...
Title
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 390587, "end": 395926 }
class ____: @pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)]) @pytest.mark.parametrize('weights', [None, True]) @pytest.mark.parametrize('keepdims', [False, True]) def test_xp_mean_basic(self, xp, axis, weights, keepdims): rng = np.random.default_rng(90359458245906) x = rng.random...
TestXP_Mean
python
docker__docker-py
docker/models/plugins.py
{ "start": 64, "end": 3374 }
class ____(Model): """ A plugin on the server. """ def __repr__(self): return f"<{self.__class__.__name__}: '{self.name}'>" @property def name(self): """ The plugin's name. """ return self.attrs.get('Name') @property def enabled(self): ""...
Plugin
python
google__jax
tests/pallas/tpu_pallas_test.py
{ "start": 137157, "end": 137959 }
class ____(MiscellaneousTest): INTERPRET: bool = True def test_async_copy_slice(self): # https://github.com/jax-ml/jax/issues/33260 def kernel(o): @functools.partial(pl.run_scoped, sem=pltpu.SemaphoreType.DMA, x=pltpu.MemorySpace.VMEM((1,), jnp.float3...
MiscellaneousInterpretTest
python
huggingface__transformers
tests/models/deit/test_modeling_deit.py
{ "start": 1770, "end": 7008 }
class ____: def __init__( self, parent, batch_size=13, image_size=30, patch_size=2, num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, ...
DeiTModelTester
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 453037, "end": 455017 }
class ____(YieldExprNode): def yield_from_func(self, code): raise NotImplementedError() def generate_evaluation_code(self, code, source_cname=None, decref_source=False): if source_cname is None: self.arg.generate_evaluation_code(code) result_temp = code.funcstate.allocate_te...
_YieldDelegationExprNode
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 4475, "end": 4572 }
class ____: name: Annotated[str, 10] graph: Annotated["Graph", 20] @dataclass
GraphArgument
python
bottlepy__bottle
bottle.py
{ "start": 77879, "end": 78563 }
class ____(HTTPResponse): """ A subclass of :class:`HTTPResponse` that triggers error handlers. """ default_status = 500 def __init__(self, status=None, body=None, exception=None, traceback=None, **more_headers): self.exception = ...
HTTPError
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows_cli.py
{ "start": 1920, "end": 2019 }
class ____(MetaflowException): headline = "Argo Workflows name too long"
ArgoWorkflowsNameTooLong
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/preserve_defaults_special_constructs.py
{ "start": 710, "end": 831 }
class ____(NamedTuple): """docstring""" a: int b: object = object() c: list[int] = [1, 2, 3]
MyNamedTuple1
python
sanic-org__sanic
sanic/cli/app.py
{ "start": 662, "end": 9793 }
class ____: DESCRIPTION = indent( f""" {get_logo(True)} To start running a Sanic application, provide a path to the module, where app is a Sanic() instance in the global scope: $ sanic path.to.server:app If the Sanic instance variable is called 'app', you can leave off the last part, and only provide...
SanicCLI
python
wandb__wandb
wandb/errors/errors.py
{ "start": 37, "end": 368 }
class ____(Exception): """Base W&B Error. <!-- lazydoc-ignore-class: internal --> """ def __init__(self, message: str, context: dict | None = None) -> None: super().__init__(message) self.message = message # sentry context capture if context: self.context = ...
Error
python
ethereum__web3.py
web3/types.py
{ "start": 5736, "end": 5804 }
class ____(TypedDict): subscription: HexBytes
SubscriptionResponse
python
django__django
tests/model_inheritance/models.py
{ "start": 2570, "end": 2613 }
class ____(Supplier): pass
CustomSupplier
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 852343, "end": 853616 }
class ____(sgqlc.types.Type, Node, RepositoryNode): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "created_at", "database_id", "discussion", "gradient_stop_colors", "pattern", "pinned_by", "preconfigure...
PinnedDiscussion
python
huggingface__transformers
src/transformers/integrations/integration_utils.py
{ "start": 50452, "end": 60634 }
class ____(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`. """ def __init__(self): if not is_mlflow_available(): raise RuntimeError("MLflowC...
MLflowCallback
python
boto__boto3
boto3/dynamodb/transform.py
{ "start": 5212, "end": 8738 }
class ____: """Injects the transformations into the user provided parameters.""" def __init__( self, transformer=None, condition_builder=None, serializer=None, deserializer=None, ): self._transformer = transformer if transformer is None: s...
TransformationInjector
python
tornadoweb__tornado
tornado/test/httpserver_test.py
{ "start": 26997, "end": 27367 }
class ____(HandlerBaseTestCase): class Handler(RequestHandler): def get(self): self.write(dict(protocol=self.request.protocol)) def get_httpserver_options(self): return dict(protocol="https") def test_manual_protocol(self): self.assertEqual(self.fetch_json("/")["protoco...
ManualProtocolTest
python
neetcode-gh__leetcode
python/0787-cheapest-flights-within-k-stops.py
{ "start": 0, "end": 598 }
class ____: def findCheapestPrice( self, n: int, flights: List[List[int]], src: int, dst: int, k: int ) -> int: prices = [float("inf")] * n prices[src] = 0 for i in range(k + 1): tmpPrices = prices.copy() for s, d, p in flights: # s=source, d=dest, p=pr...
Solution
python
langchain-ai__langchain
libs/partners/perplexity/langchain_perplexity/output_parsers.py
{ "start": 2240, "end": 3223 }
class ____( PydanticOutputParser[TBaseModel], Generic[TBaseModel] ): """A structured output parser that strips reasoning tags before parsing. This parser removes any content enclosed in <think> tags from the input text before delegating to the parent PydanticOutputParser for structured parsing. """...
ReasoningStructuredOutputParser
python
huggingface__transformers
tests/models/moshi/test_modeling_moshi.py
{ "start": 5085, "end": 16284 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (MoshiModel, MoshiForCausalLM) if is_torch_available() else () test_resize_embeddings = True pipeline_model_mapping = ( { "feature-extraction": MoshiModel, "text-...
MoshiDecoderTest
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared_tests/test_check.py
{ "start": 52303, "end": 52328 }
class ____(Foo): ...
SubFoo
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 21816, "end": 22369 }
class ____(VOTableSpecWarning): """ Version 1.0 of the VOTable specification used the ``DEFINITIONS`` element to define coordinate systems. Version 1.1 now uses ``COOSYS`` elements throughout the document. **References:** `1.1 <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-200...
W22
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/transfers/test_local_to_wasb.py
{ "start": 1018, "end": 2830 }
class ____: _config = { "file_path": "file", "container_name": "container", "blob_name": "blob", "wasb_conn_id": "wasb_default", "retries": 3, } def setup_method(self): args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1, 1)} self.dag ...
TestLocalFilesystemToWasbOperator
python
PrefectHQ__prefect
tests/server/orchestration/api/test_flows.py
{ "start": 15735, "end": 24636 }
class ____: @pytest.fixture async def flows(self, client): await client.post("/flows/", json={"name": "my-flow-1"}) await client.post("/flows/", json={"name": "my-flow-2"}) @pytest.mark.usefixtures("flows") async def test_paginate_flows(self, client): response = await client.pos...
TestPaginateFlows
python
chroma-core__chroma
chromadb/utils/embedding_functions/jina_embedding_function.py
{ "start": 411, "end": 10138 }
class ____(EmbeddingFunction[Embeddable]): """ This class is used to get embeddings for a list of texts using the Jina AI API. It requires an API key and a model name. The default model name is "jina-embeddings-v2-base-en". """ def __init__( self, api_key: Optional[str] = None, ...
JinaEmbeddingFunction
python
automl__auto-sklearn
test/test_pipeline/test_classification.py
{ "start": 1309, "end": 2027 }
class ____(AutoSklearnClassificationAlgorithm): @staticmethod def get_properties(dataset_properties=None): return { "shortname": "AB", "name": "AdaBoost Classifier", "handles_regression": False, "handles_classification": True, "handles_multicla...
DummyClassifier
python
apache__airflow
providers/standard/tests/unit/standard/sensors/test_external_task_sensor.py
{ "start": 58136, "end": 65251 }
class ____: TASK_ID = "external_task_sensor_check" EXTERNAL_DAG_ID = "child_dag" # DAG the external task sensor is waiting on EXTERNAL_TASK_ID = "child_task" # Task the external task sensor is waiting on def test_defer_and_fire_task_state_trigger(self): """ Asserts that a task is defe...
TestExternalTaskAsyncSensor
python
getsentry__sentry
src/sentry/interfaces/template.py
{ "start": 125, "end": 2638 }
class ____(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ ...
Template
python
mwaskom__seaborn
tests/test_matrix.py
{ "start": 24619, "end": 48942 }
class ____: rs = np.random.RandomState(sum(map(ord, "clustermap"))) x_norm = rs.randn(4, 8) + np.arange(8) x_norm = (x_norm.T + np.arange(4)).T letters = pd.Series(["A", "B", "C", "D", "E", "F", "G", "H"], name="letters") df_norm = pd.DataFrame(x_norm, columns=letters) ...
TestClustermap
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/decorators/graph_decorator.py
{ "start": 563, "end": 9278 }
class ____: name: Optional[str] description: Optional[str] input_defs: Sequence[InputDefinition] output_defs: Optional[Sequence[OutputDefinition]] ins: Optional[Mapping[str, GraphIn]] out: Optional[Union[GraphOut, Mapping[str, GraphOut]]] tags: Optional[Mapping[str, str]] config_mapping:...
_Graph
python
great-expectations__great_expectations
great_expectations/data_context/types/base.py
{ "start": 60860, "end": 67594 }
class ____(BaseStoreBackendDefaults): """ Default store configs for Google Cloud Storage (GCS) backends, with some accessible parameters Args: default_bucket_name: Use this bucket name for stores that do not have a bucket name provided default_project_name: Use this project name for stores t...
GCSStoreBackendDefaults
python
doocs__leetcode
solution/1100-1199/1196.How Many Apples Can You Put into the Basket/Solution.py
{ "start": 0, "end": 246 }
class ____: def maxNumberOfApples(self, weight: List[int]) -> int: weight.sort() s = 0 for i, x in enumerate(weight): s += x if s > 5000: return i return len(weight)
Solution
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/random_shear_test.py
{ "start": 258, "end": 6195 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( layers.RandomShear, init_kwargs={ "x_factor": (0.5, 1), "y_factor": (0.5, 1), "interpolation": "bilinear", ...
RandomShearTest
python
pypa__warehouse
warehouse/sessions.py
{ "start": 730, "end": 2002 }
class ____(dict): __contains__ = _invalid_method(dict.__contains__) __delitem__ = _invalid_method(dict.__delitem__) __getitem__ = _invalid_method(dict.__getitem__) __iter__ = _invalid_method(dict.__iter__) __len__ = _invalid_method(dict.__len__) __setitem__ = _invalid_method(dict.__setitem__) ...
InvalidSession
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/optimizer.py
{ "start": 560, "end": 1386 }
class ____: """Abstract class for optimizers. An optimizers transforms a DAG of operators with a list of predefined rules. """ @property def rules(self) -> List[Rule]: """List of predefined rules for this optimizer.""" raise NotImplementedError def optimize(self, plan: Plan) -...
Optimizer
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 27672, "end": 29666 }
class ____(nn.Module): def __init__(self, config: FunnelConfig) -> None: super().__init__() self.config = config self.attention_structure = FunnelAttentionStructure(config) self.layers = nn.ModuleList([FunnelLayer(config, 0) for _ in range(config.num_decoder_layers)]) def forwar...
FunnelDecoder
python
coleifer__peewee
tests/cysqlite.py
{ "start": 3936, "end": 4771 }
class ____(CyDatabaseTestCase): database = database def setUp(self): super(TestHashFunctions, self).setUp() self.database.execute_sql( 'create table users (id integer not null primary key, ' 'username text not null)') def test_md5(self): for username in ('ch...
TestHashFunctions
python
nedbat__coveragepy
tests/test_arcs.py
{ "start": 50341, "end": 54061 }
class ____(CoverageTest): """Miscellaneous arc-measuring tests.""" def test_dict_literal(self) -> None: self.check_coverage( """\ d = { 'a': 2, 'b': 3, 'c': { 'd': 5, 'e': 6, ...
MiscArcTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 60532, "end": 60677 }
class ____(AnsiFunction[datetime.datetime]): """The SYSDATE() SQL function.""" type = sqltypes.DateTime() inherit_cache = True
sysdate
python
pytorch__pytorch
torch/autograd/function.py
{ "start": 19393, "end": 26896 }
class ____(_SingleLevelFunction): r"""Base class to create custom `autograd.Function`. To create a custom `autograd.Function`, subclass this class and implement the :meth:`forward` and :meth:`backward` static methods. Then, to use your custom op in the forward pass, call the class method ``apply``. Do ...
Function
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_user_details.py
{ "start": 8776, "end": 12923 }
class ____(UserDetailsTest): method = "put" def test_superuser_can_change_is_active(self) -> None: self.user.update(is_active=True) self.login_as(user=self.superuser, superuser=True) resp = self.get_success_response( self.user.id, isActive="false", ) ...
UserDetailsSuperuserUpdateTest
python
walkccc__LeetCode
solutions/401. Binary Watch/401.py
{ "start": 0, "end": 614 }
class ____: def readBinaryWatch(self, turnedOn: int) -> list[str]: ans = [] hours = [1, 2, 4, 8] minutes = [1, 2, 4, 8, 16, 32] def dfs(turnedOn: int, s: int, h: int, m: int) -> None: if turnedOn == 0: time = str(h) + ":" + (str(m).zfill(2)) ans.append(time) return ...
Solution
python
pytorch__pytorch
tools/setup_helpers/env.py
{ "start": 1165, "end": 3504 }
class ____: """Checks build type. The build type will be given in :attr:`cmake_build_type_env`. If :attr:`cmake_build_type_env` is ``None``, then the build type will be inferred from ``CMakeCache.txt``. If ``CMakeCache.txt`` does not exist, os.environ['CMAKE_BUILD_TYPE'] will be used. Args: cmake...
BuildType
python
joke2k__faker
tests/providers/test_address.py
{ "start": 40231, "end": 40745 }
class ____: """Test hi_IN address provider methods""" def test_city_name(self, faker, num_samples): for _ in range(num_samples): city_name = faker.city_name() assert isinstance(city_name, str) assert city_name in HiInAddressProvider.cities def test_state(self, f...
TestHiIn
python
encode__django-rest-framework
tests/test_serializer_nested.py
{ "start": 1571, "end": 2498 }
class ____: def setup_method(self): class NestedSerializer(serializers.Serializer): one = serializers.IntegerField(max_value=10) class TestSerializer(serializers.Serializer): nested = NestedSerializer(required=False) self.Serializer = TestSerializer def test_js...
TestNotRequiredNestedSerializer
python
spyder-ide__spyder
spyder/api/widgets/dialogs.py
{ "start": 414, "end": 1182 }
class ____(QProxyStyle): """Style adjustments for SpyderDialogButtonBox.""" def styleHint(self, hint, option=None, widget=None, return_data=None): if hint == QStyle.SH_DialogButtonLayout: # Use the Windows buttons layout to have a uniform layout in all # platforms. We selected t...
_SpyderButtonsProxyStyle
python
tensorflow__tensorflow
tensorflow/python/keras/engine/data_adapter.py
{ "start": 22992, "end": 24904 }
class ____(DataAdapter): """Adapter that handles lists of scalars and lists of lists of scalars.""" @staticmethod def can_handle(x, y=None): handles_x = ListsOfScalarsDataAdapter._is_list_of_scalars(x) handles_y = True if y is not None: handles_y = ListsOfScalarsDataAdapter._is_list_of_scalars(...
ListsOfScalarsDataAdapter
python
realpython__materials
python-constants/strict_constants.py
{ "start": 513, "end": 615 }
class ____: PI = 3.141592653589793 EULER_NUMBER = 2.718281828459045
ConstantsNamespace_dataclass
python
ray-project__ray
python/ray/exceptions.py
{ "start": 30481, "end": 30649 }
class ____(RaySystemError): """Raised when the Compiled Graph channel's buffer is at max capacity""" pass @PublicAPI(stability="alpha")
RayCgraphCapacityExceeded
python
spack__spack
lib/spack/spack/util/file_cache.py
{ "start": 1037, "end": 1736 }
class ____: def __init__(self, path: str) -> None: self.path = path self.tmp_path = f"{self.path}.tmp" def __enter__(self) -> Tuple[Optional[IO[str]], IO[str]]: """Return (old_file, new_file) file objects, where old_file is optional.""" self.old_file = _maybe_open(self.path) ...
WriteContextManager
python
apache__airflow
providers/imap/tests/unit/imap/hooks/test_imap.py
{ "start": 2232, "end": 16462 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="imap_default", conn_type="imap", host="imap_server_address", login="imap_use...
TestImapHook
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1374026, "end": 1377332 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Minimizable, Updatable, UpdatableComment, Reactable, RepositoryNode ): """A review comment associated with a given repository pull request.""" __schema__ = github_schema __field_names__ = ( "commit", "diff_hunk", "drafted_a...
PullRequestReviewComment
python
getsentry__sentry
tests/sentry/uptime/migrations/test_0045_backfill_detector_thresholds.py
{ "start": 87, "end": 5870 }
class ____(TestMigrations): migrate_from = "0044_remove_project_uptime_subscription" migrate_to = "0045_backfill_detector_thresholds" app = "uptime" def setup_initial_state(self) -> None: # Create test organization and project self.organization = self.create_organization(name="test-org"...
BackfillDetectorThresholdsTest
python
redis__redis-py
tests/test_connect.py
{ "start": 4820, "end": 6829 }
class ____(socketserver.TCPServer): def __init__( self, *args, certfile=None, keyfile=None, minimum_ssl_version=ssl.TLSVersion.TLSv1_2, maximum_ssl_version=ssl.TLSVersion.TLSv1_3, **kw, ) -> None: self._ready_event = threading.Event() self....
_RedisTCPServer
python
django__django
django/test/runner.py
{ "start": 5001, "end": 12516 }
class ____(unittest.TestResult): """ Extend unittest.TestResult to record events in the child processes so they can be replayed in the parent process. Events include things like which tests succeeded or failed. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
RemoteTestResult
python
doocs__leetcode
solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/Solution.py
{ "start": 0, "end": 487 }
class ____: def minimumOperations(self, nums: List[int]) -> int: i, j = 0, len(nums) - 1 a, b = nums[i], nums[j] ans = 0 while i < j: if a < b: i += 1 a += nums[i] ans += 1 elif b < a: j -= 1 ...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec41.py
{ "start": 200, "end": 522 }
class ____: def __init__(self, x: int, y: int, z: str) -> None: self.a = x # This should generate an error. @classmethod def f(cls: Callable[P, Self], *args: P.args, **kwargs: P.kwargs) -> int: return cls(*args, **kwargs).a reveal_type(A.f, expected_text="(x: int, y: int, z: str) -> i...
A
python
h5py__h5py
h5py/_hl/base.py
{ "start": 13826, "end": 14068 }
class ____(MappingHDF5, MutableMapping): """ Wraps a Group or AttributeManager object to provide a mutable mapping interface, in contrast to the read-only mapping of MappingHDF5. """ pass
MutableMappingHDF5
python
facelessuser__soupsieve
tests/test_level3/test_checked.py
{ "start": 52, "end": 1001 }
class ____(util.TestCase): """Test checked selectors.""" def test_checked(self): """Test checked.""" markup = """ <body> <div> <input type="radio" name="my-input" id="yes" checked> <label for="yes">Yes</label> <input type="radio" name="my-input" i...
TestChecked
python
optuna__optuna
optuna/samplers/_qmc.py
{ "start": 869, "end": 13435 }
class ____(BaseSampler): """A Quasi Monte Carlo Sampler that generates low-discrepancy sequences. Quasi Monte Carlo (QMC) sequences are designed to have lower discrepancies than standard random sequences. They are known to perform better than the standard random sequences in hyperparameter optimization...
QMCSampler
python
eventlet__eventlet
eventlet/hubs/__init__.py
{ "start": 527, "end": 5979 }
class ____(Exception): pass def get_default_hub(): """Select the default hub implementation based on what multiplexing libraries are installed. The order that the hubs are tried is: * epoll * kqueue * poll * select .. include:: ../../doc/source/common.txt .. note :: |internal| ...
HubError
python
openai__openai-python
src/openai/types/beta/realtime/session.py
{ "start": 4272, "end": 10183 }
class ____(BaseModel): id: Optional[str] = None """Unique identifier for the session that looks like `sess_1234567890abcdef`.""" input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm1...
Session
python
cython__cython
Cython/Compiler/Symtab.py
{ "start": 134792, "end": 136762 }
class ____(Scope): # Scope holding the __get__, __set__ and __del__ methods for # a property of an extension type. # # parent_type PyExtensionType The type to which the property belongs is_property_scope = 1 def __init__(self, name, class_scope): # outer scope is None for some i...
PropertyScope
python
doocs__leetcode
solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/Solution.py
{ "start": 0, "end": 964 }
class ____: def minimumChanges(self, s: str, k: int) -> int: n = len(s) g = [[inf] * (n + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(i, n + 1): m = j - i + 1 for d in range(1, m): if m % d == 0: ...
Solution
python
huggingface__transformers
src/transformers/models/moonshine/modeling_moonshine.py
{ "start": 10579, "end": 16381 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, config: MoonshineConfig, layer_idx: int, is_causal: bool, num_attention_heads: int, num_key_value_heads: int, ): super().__init__() ...
MoonshineAttention
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 56752, "end": 58815 }
class ____: def test_polyfit(self): # Tests polyfit # On ndarrays x = np.random.rand(10) y = np.random.rand(20).reshape(-1, 2) assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3)) # ON 1D maskedarrays x = x.view(MaskedArray) x[0] = masked ...
TestPolynomial
python
kamyu104__LeetCode-Solutions
Python/word-abbreviation.py
{ "start": 73, "end": 1194 }
class ____(object): def wordsAbbreviation(self, dict): """ :type dict: List[str] :rtype: List[str] """ def isUnique(prefix, words): return sum(word.startswith(prefix) for word in words) == 1 def toAbbr(prefix, word): abbr = prefix + str(len(wo...
Solution
python
huggingface__transformers
tests/models/cpmant/test_modeling_cpmant.py
{ "start": 6234, "end": 6907 }
class ____(unittest.TestCase): @tooslow def test_inference_masked_lm(self): texts = "今天天气真好!" model_path = "openbmb/cpm-ant-10b" model = CpmAntModel.from_pretrained(model_path) tokenizer = CpmAntTokenizer.from_pretrained(model_path) inputs = tokenizer(texts, return_tensor...
CpmAntModelIntegrationTest
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 7905, "end": 8803 }
class ____: @functools.singledispatchmethod def fancymethod(self, str_or_int: str | int): """A fancy method which is capable of handling either `str` or `int`. :param str_or_int: string or integer to handle """ raise NotImplementedError(f"{type(str_or_int)=} not implemented!") ...
SingleDispatchMethodExample
python
ray-project__ray
python/ray/train/examples/pytorch/torch_fashion_mnist_example.py
{ "start": 1257, "end": 4851 }
class ____(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(28 * 28, 512), nn.ReLU(), nn.Dropout(0.25), nn.Linear(512, 512), nn.ReLU(...
NeuralNetwork
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py
{ "start": 1538, "end": 1891 }
class ____(BaseEvent): """Event emitted when attachment processing begins.""" page_id: str attachment_id: str attachment_name: str attachment_type: str attachment_size: int attachment_link: str @classmethod def class_name(cls) -> str: return "AttachmentProcessingStartedEven...
AttachmentProcessingStartedEvent
python
huggingface__transformers
src/transformers/models/fnet/modeling_fnet.py
{ "start": 39725, "end": 42787 }
class ____(FNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.fnet = FNetModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing ...
FNetForQuestionAnswering