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 | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-mixedbreadai/llama_index/embeddings/mixedbreadai/base.py | {
"start": 422,
"end": 8042
} | class ____(BaseEmbedding):
"""
Class to get embeddings using the mixedbread ai embedding API with models such as 'mixedbread-ai/mxbai-embed-large-v1'.
Args:
api_key (Optional[str]): mixedbread ai API key. Defaults to None.
model_name (str): Model for embedding. Defaults to "mixedbread-ai/mx... | MixedbreadAIEmbedding |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_instance.py | {
"start": 10280,
"end": 11656
} | class ____(ConcurrencyTestSuite):
def test_default_concurrency(self, graphql_context):
# no limits
all_limits = fetch_all_concurrency_limits(graphql_context)
assert len(all_limits) == 0
# default limits are empty
limit = fetch_concurrency_limit(graphql_context, "foo")
... | TestConcurrencyInstanceSettings |
python | google__pytype | pytype/pretty_printer.py | {
"start": 341,
"end": 3474
} | class ____(pretty_printer_base.PrettyPrinterBase):
"""Pretty print types for errors."""
def print_generic_type(self, t) -> str:
convert = self.ctx.pytd_convert
generic = pytd_utils.MakeClassOrContainerType(
t.to_pytd_type_of_instance().base_type,
t.formal_type_parameters.keys(),
Fal... | PrettyPrinter |
python | getsentry__sentry | tests/sentry/feedback/endpoints/test_error_page_embed.py | {
"start": 7644,
"end": 11156
} | class ____(TestCase):
def setUp(self) -> None:
self.project = self.create_project()
self.project.update_option("sentry:origins", ["example.com"])
self.key = self.create_project_key(self.project)
self.event_id = uuid4().hex
self.path = "{}?eventId={}&dsn={}".format(
... | ErrorPageEmbedEnvironmentTest |
python | doocs__leetcode | solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/Solution.py | {
"start": 0,
"end": 306
} | class ____:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
for i in range(n - 1):
x = target - numbers[i]
j = bisect_left(numbers, x, lo=i + 1)
if j < n and numbers[j] == x:
return [i + 1, j + 1]
| Solution |
python | psf__black | src/black/__init__.py | {
"start": 2347,
"end": 53972
} | class ____(Enum):
NO = 0
YES = 1
DIFF = 2
CHECK = 3
COLOR_DIFF = 4
@classmethod
def from_configuration(
cls, *, check: bool, diff: bool, color: bool = False
) -> "WriteBack":
if check and not diff:
return cls.CHECK
if diff and color:
retu... | WriteBack |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/baked.py | {
"start": 10083,
"end": 17658
} | class ____:
"""Invokes a :class:`.BakedQuery` against a :class:`.Session`.
The :class:`_baked.Result` object is where the actual :class:`.query.Query`
object gets created, or retrieved from the cache,
against a target :class:`.Session`, and is then invoked for results.
"""
__slots__ = "bq", "... | Result |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/transfers/hive_to_mysql.py | {
"start": 1301,
"end": 5301
} | class ____(BaseOperator):
"""
Moves data from Hive to MySQL.
Note that for now the data is loaded into memory before being pushed
to MySQL, so this operator should be used for smallish amount of data.
:param sql: SQL query to execute against Hive server. (templated)
:param mysql_table: target ... | HiveToMySqlOperator |
python | walkccc__LeetCode | solutions/1130. Minimum Cost Tree From Leaf Values/1130.py | {
"start": 0,
"end": 728
} | class ____:
def mctFromLeafValues(self, arr: list[int]) -> int:
n = len(arr)
# dp[i][j] := the minimum cost of arr[i..j]
dp = [[0] * n for _ in range(n)]
# maxVal[i][j] := the maximum value of arr[i..j]
maxVal = [[0] * n for _ in range(n)]
for i in range(n):
maxVal[i][i] = arr[i]
f... | Solution |
python | dask__distributed | distributed/tests/test_stories.py | {
"start": 2718,
"end": 5062
} | class ____(Worker):
async def get_story(self, *args, **kw):
raise CommClosedError
@gen_cluster(client=True, Worker=WorkerBrokenStory)
@pytest.mark.parametrize("on_error", ["ignore", "raise"])
async def test_client_story_failed_worker(c, s, a, b, on_error):
f = c.submit(inc, 1)
coro = c.story(f.key... | WorkerBrokenStory |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/client.py | {
"start": 730,
"end": 2782
} | class ____:
"""Class to handle SSH tunneling for a kernel connection."""
def __init__(self, ssh_connection, *, _close_conn_on_exit=False):
self.ssh_connection = ssh_connection
self._port_forwarded = {}
self._close_conn_on_exit = _close_conn_on_exit
def __del__(self):
"""Clo... | KernelClientTunneler |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 16569,
"end": 18064
} | class ____(Glyph, FillGlyph, HatchGlyph):
''' Render a horizontally directed area between two equal length sequences
of x-coordinates with the same y-coordinates using step lines.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
supe... | HAreaStep |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 72785,
"end": 74422
} | class ____:
class A:
iters = 20
def bound(self, *args):
return 0
@staticmethod
def unbound(*args):
return 0
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
@pytest.mark.skipif(NOGIL_BUILD,
reason=("Func... | TestLeaks |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 28270,
"end": 31672
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"authors": 9000, "dynamic": ["authors"]}})
with pytest.raises(
ValueError,
match="Metadata field `authors` cannot be both statically defined and listed in field `proj... | TestAuthors |
python | python-markdown__markdown | markdown/blockprocessors.py | {
"start": 13728,
"end": 19031
} | class ____(BlockProcessor):
""" Process ordered list blocks. """
TAG: str = 'ol'
""" The tag used for the the wrapping element. """
STARTSWITH: str = '1'
"""
The integer (as a string ) with which the list starts. For example, if a list is initialized as
`3. Item`, then the `ol` tag will be ... | OListProcessor |
python | spack__spack | lib/spack/spack/modules/lmod.py | {
"start": 18756,
"end": 18938
} | class ____(spack.error.SpackError, KeyError):
"""Error raised if the key ``core_compilers`` has not been specified
in the configuration file.
"""
| CoreCompilersNotFoundError |
python | ray-project__ray | python/ray/util/state/common.py | {
"start": 55497,
"end": 56560
} | class ____:
#: Group key (actor class name) -> summary
summary: Dict[str, ActorSummaryPerClass]
#: Total number of actors
total_actors: int
summary_by: str = "class"
@classmethod
def to_summary(cls, *, actors: List[Dict]):
# NOTE: The argument tasks contains a list of dictionary
... | ActorSummaries |
python | tornadoweb__tornado | tornado/netutil.py | {
"start": 15432,
"end": 15923
} | class ____(Resolver):
"""Resolver implementation using `.IOLoop.run_in_executor`.
.. versionadded:: 5.0
.. deprecated:: 6.2
Use `DefaultLoopResolver` instead.
"""
async def resolve(
self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> List[Tuple[int... | DefaultExecutorResolver |
python | jd__tenacity | tenacity/wait.py | {
"start": 5779,
"end": 7079
} | class ____(wait_base):
"""Wait strategy that applies exponential backoff.
It allows for a customized multiplier and an ability to restrict the
upper and lower limits to some maximum and minimum value.
The intervals are fixed (i.e. there is no jitter), so this strategy is
suitable for balancing ret... | wait_exponential |
python | huggingface__transformers | src/transformers/models/starcoder2/modular_starcoder2.py | {
"start": 1907,
"end": 2721
} | class ____(nn.Module):
def __init__(self, config: Starcoder2Config):
super().__init__()
embed_dim = config.hidden_size
self.c_fc = nn.Linear(embed_dim, config.intermediate_size, bias=config.use_bias)
self.c_proj = nn.Linear(config.intermediate_size, embed_dim, bias=config.use_bias)
... | Starcoder2MLP |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator.py | {
"start": 3275,
"end": 4234
} | class ____(Exception):
"""Wrapper for errors from resource building.
When a closure starts, it first checks for errors in any of its inputs, which
are RemoteValues from resource closures. If there were any errors, it wraps
the exception in this class and raises so it can be handled by the worker
failure hand... | ClosureInputError |
python | django__django | tests/messages_tests/test_mixins.py | {
"start": 280,
"end": 1106
} | class ____(TestCase):
def test_set_messages_success(self):
author = {"name": "John Doe", "slug": "success-msg"}
add_url = reverse("add_success_msg")
req = self.client.post(add_url, author)
# Uncompressed message is stored in the cookie.
value = b64_decode(
req.coo... | SuccessMessageMixinTests |
python | pennersr__django-allauth | allauth/idp/oidc/contrib/rest_framework/authentication.py | {
"start": 197,
"end": 583
} | class ____(BaseAuthentication):
"""
Use the OIDC access token to authenticate the request.
"""
def authenticate(self, request):
server = get_server()
orequest = extract_params(request)
valid, ctx = server.verify_request(*orequest, scopes=[])
if not valid:
ret... | TokenAuthentication |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 14349,
"end": 14474
} | class ____(ReturnTypeAny):
choices = [1, 2, 3]
def draw(self) -> int:
return super().draw()
| ReturnTypeNarrowed |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/ascent/package.py | {
"start": 217,
"end": 748
} | class ____(Package):
"""This packagae has the variants shared, defaulted
to True and adios2 defaulted to False"""
homepage = "https://github.com/Alpine-DAV/ascent"
url = "http://www.example.com/ascent-1.0.tar.gz"
version("0.9.2", sha256="44cd954aa5db478ab40042cd54fd6fcedf25000c3bb510ca23fcff809053... | Ascent |
python | bokeh__bokeh | examples/plotting/customjs_expr.py | {
"start": 461,
"end": 1257
} | class ____(DataModel):
amp = Float(default=0.1, help="Amplitude")
freq = Float(default=0.1, help="Frequency")
phase = Float(default=0, help="Phase")
offset = Float(default=-5, help="Offset")
params = Params(amp=2, freq=3, phase=0.4, offset=1)
x = np.linspace(0, 10, 100)
y = CustomJSExpr(args=dict(para... | Params |
python | huggingface__transformers | src/transformers/models/vjepa2/modeling_vjepa2.py | {
"start": 4360,
"end": 7647
} | class ____(nn.Module):
"""
Construct mask token, position and patch embeddings.
"""
def __init__(self, config: VJEPA2Config, hidden_size: int = 1024):
super().__init__()
self.config = config
self.hidden_size = hidden_size
self.patch_embeddings = VJEPA2PatchEmbeddings3D(... | VJEPA2Embeddings |
python | huggingface__transformers | src/transformers/models/smollm3/modeling_smollm3.py | {
"start": 11979,
"end": 12706
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
SmolLM3RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
inpu... | SmolLM3RMSNorm |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/hot_reloading_app.py | {
"start": 499,
"end": 646
} | class ____(App[None]):
CSS_PATH = CSS_PATH
def compose(self) -> ComposeResult:
yield Container(Label("Hello, world!"))
| HotReloadingApp |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 574,
"end": 636
} | class ____(Link):
class Meta:
proxy = True
| LinkProxy |
python | h5py__h5py | examples/swmr_multiprocess.py | {
"start": 921,
"end": 1900
} | class ____(Process):
def __init__(self, event, fname, dsetname, timeout = 2.0):
super().__init__()
self._event = event
self._fname = fname
self._dsetname = dsetname
self._timeout = timeout
def run(self):
self.log = logging.getLogger('reader')
self.log.inf... | SwmrReader |
python | tensorflow__tensorflow | tensorflow/python/framework/composite_tensor.py | {
"start": 991,
"end": 5665
} | class ____(metaclass=abc.ABCMeta):
"""Abstract base class for Tensor-like objects that are composed from Tensors.
Each `CompositeTensor` can be decomposed into a structured collection of
component `tf.Tensor`s, and reconstructed from those components.
The `tensorflow.python.util.nest` module has support for t... | CompositeTensor |
python | tiangolo__fastapi | docs_src/response_model/tutorial005.py | {
"start": 104,
"end": 848
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": ... | Item |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_county_name.py | {
"start": 780,
"end": 1789
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_us_county_name"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pa... | ColumnValuesToBeValidUSCountyName |
python | eth-brownie__brownie | brownie/network/contract.py | {
"start": 25295,
"end": 31794
} | class ____(_ContractBase):
"""Methods for interacting with a deployed contract.
Each public contract method is available as a ContractCall or ContractTx
instance, created when this class is instantiated.
Attributes:
bytecode: Bytecode of the deployed contract, including constructor args.
... | _DeployedContractBase |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/translate.py | {
"start": 2525,
"end": 2851
} | class ____(BaseGoogleLink):
"""
Helper class for constructing Legacy Translation Dataset link.
Legacy Datasets are created and managed by AutoML API.
"""
name = "Translation Legacy Dataset"
key = "translation_legacy_dataset"
format_str = TRANSLATION_LEGACY_DATASET_LINK
| TranslationLegacyDatasetLink |
python | huggingface__transformers | src/transformers/models/pixtral/modeling_pixtral.py | {
"start": 12118,
"end": 12845
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
PixtralRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
inpu... | PixtralRMSNorm |
python | pandas-dev__pandas | pandas/core/arrays/string_.py | {
"start": 2087,
"end": 10937
} | class ____(StorageExtensionDtype):
"""
Extension dtype for string data.
.. warning::
StringDtype is considered experimental. The implementation and
parts of the API may change without warning.
Parameters
----------
storage : {"python", "pyarrow"}, optional
If not given, ... | StringDtype |
python | pdm-project__pdm | src/pdm/models/backends.py | {
"start": 1249,
"end": 1918
} | class ____(BuildBackend):
def expand_line(self, req: str, expand_env: bool = True) -> str:
line = req.replace("file:///${PROJECT_ROOT}", self.root.as_uri())
if expand_env:
line = expand_env_vars(line)
return line
def relative_path_to_url(self, path: str) -> str:
if o... | PDMBackend |
python | tensorflow__tensorflow | tensorflow/python/framework/python_api_dispatcher_test.py | {
"start": 13612,
"end": 17461
} | class ____(test_util.TensorFlowTestCase):
def testBasicDispatch(self):
dispatcher = dispatch.PythonAPIDispatcher('tf.foo', ['x', 'y', 'name'],
(None,))
rt_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor)
f1 = lambda x, y, name=None: 'f1'
... | PythonAPIDispatcherTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-google-sheets/destination_google_sheets/buffer.py | {
"start": 181,
"end": 4315
} | class ____:
# Default instance of AirbyteLogger
logger = AirbyteLogger()
# intervals after which the records_buffer should be cleaned up for selected stream
flush_interval = 500 # records count
flush_interval_size_in_kb = 10 ^ 8 # memory allocation ~ 97656 Kb or 95 Mb
def __init__(self):
... | WriteBufferMixin |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_cache_test.py | {
"start": 2072,
"end": 2302
} | class ____(MockGenericType):
def most_specific_common_supertype(self, others):
if self._object == 2 and isinstance(others[0]._object, int):
return MockSupertypes2With3(3)
else:
return None
| MockSupertypes2With3 |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 7976,
"end": 8081
} | class ____(SluggedTestModel):
class Meta:
app_label = "django_extensions"
| ChildSluggedTestModel |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 78594,
"end": 80710
} | class ____(nn.Module):
def __init__(
self, embed_dim, num_heads, dropout=0.0, activation="relu", normalize_before=False, layer_norm_eps=1e-05
):
super().__init__()
self.self_attn = OneFormerAttention(embed_dim=embed_dim, num_heads=num_heads, dropout=dropout, is_decoder=True)
sel... | OneFormerTransformerDecoderSelfAttentionLayer |
python | lepture__authlib | authlib/integrations/flask_oauth2/requests.py | {
"start": 305,
"end": 675
} | class ____(OAuth2Payload):
def __init__(self, request: Request):
self._request = request
@property
def data(self):
return self._request.values
@cached_property
def datalist(self):
values = defaultdict(list)
for k in self.data:
values[k].extend(self.data.... | FlaskOAuth2Payload |
python | django__django | tests/generic_inline_admin/models.py | {
"start": 1651,
"end": 1693
} | class ____(Episode):
pass
| EpisodePermanent |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/reduce_join_op_test.py | {
"start": 2333,
"end": 3280
} | class ____(UnicodeTestCase):
"""Tests for helper functions."""
def testInputArray(self):
num_dims = 3
truth = ["{:03b}".format(i) for i in range(2**num_dims)]
output_array = _input_array(num_dims).reshape([-1])
self.assertAllEqualUnicode(truth, output_array)
def testJoinedArray(self):
num_di... | ReduceJoinTestHelperTest |
python | numpy__numpy | numpy/f2py/auxfuncs.py | {
"start": 14951,
"end": 26920
} | class ____:
def __init__(self, mess):
self.mess = mess
def __call__(self, var):
mess = f'\n\n var = {var}\n Message: {self.mess}\n'
raise F2PYError(mess)
def l_and(*f):
l1, l2 = 'lambda v', []
for i in range(len(f)):
l1 = '%s,f%d=f[%d]' % (l1, i, i)
l2.appen... | throw_error |
python | pytorch__pytorch | test/inductor/test_cooperative_reductions.py | {
"start": 731,
"end": 1664
} | class ____(InductorChoices):
def __init__(self, *, cooperative: bool, persistent: bool, cfg: dict[str, int]):
super().__init__()
self.cooperative = cooperative
self.persistent = persistent
self.cfg = cfg
self.call_count = 0
def triton_kernel_kwargs(
self,
... | TestingHeuristics |
python | neetcode-gh__leetcode | python/0518-coin-change-ii.py | {
"start": 0,
"end": 1456
} | class ____:
def change(self, amount: int, coins: List[int]) -> int:
# MEMOIZATION
# Time: O(n*m)
# Memory: O(n*m)
cache = {}
def dfs(i, a):
if a == amount:
return 1
if a > amount:
return 0
if i == len(coins)... | Solution |
python | facebookresearch__faiss | tests/test_build_blocks.py | {
"start": 13773,
"end": 15554
} | class ____(unittest.TestCase):
def do_test_bucket_sort(self, nt):
rs = np.random.RandomState(123)
tab = rs.randint(100, size=1000, dtype='int64')
lims, perm = faiss.bucket_sort(tab, nt=nt)
for i in range(max(tab) + 1):
assert np.all(tab[perm[lims[i]: lims[i + 1]]] == i)
... | TestBucketSort |
python | getsentry__sentry | tests/sentry/core/endpoints/test_project_details.py | {
"start": 18794,
"end": 59056
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-details"
method = "put"
def setUp(self) -> None:
super().setUp()
self.org_slug = self.project.organization.slug
self.proj_slug = self.project.slug
self.login_as(user=self.user)
def test_superuser_simple(self) -> ... | ProjectUpdateTest |
python | milvus-io__pymilvus | pymilvus/orm/schema.py | {
"start": 16746,
"end": 24620
} | class ____:
def __init__(self, name: str, dtype: DataType, description: str = "", **kwargs) -> None:
self.name = name
try:
dtype = DataType(dtype)
except ValueError:
raise DataTypeNotSupportException(message=ExceptionsMessage.FieldDtype) from None
if dtype == ... | FieldSchema |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 128999,
"end": 129500
} | class ____(Dataset):
def __init__(self, end: int, slow_index: int):
self.end = end
self.slow_index = slow_index
self._worker_id = None
def __getitem__(self, idx):
if not self._worker_id:
worker_info = torch.utils.data.get_worker_info()
self._worker_id = w... | TestSlowIndexDataset |
python | scikit-learn__scikit-learn | sklearn/impute/_knn.py | {
"start": 662,
"end": 14967
} | class ____(_BaseImputer):
"""Imputation for completing missing values using k-Nearest Neighbors.
Each sample's missing values are imputed using the mean value from
`n_neighbors` nearest neighbors found in the training set. Two samples are
close if the features that neither is missing are close.
Re... | KNNImputer |
python | getsentry__sentry | src/sentry/integrations/analytics.py | {
"start": 517,
"end": 733
} | class ____(analytics.Event):
provider: str
id: int
organization_id: int
user_id: int | None = None
default_user_id: int
@analytics.eventclass("integration.issue.linked")
| IntegrationIssueCreatedEvent |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_health/asset_materialization_health.py | {
"start": 1066,
"end": 3770
} | class ____(LoadableBy[AssetKey]):
"""Minimal object for computing the health status for the materialization state of an asset.
This object is intended to be small and quick to deserialize. Deserializing AssetMaterializationHealthState
can be slow if there is a large entity subset. Rather than storing entity... | MinimalAssetMaterializationHealthState |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/batch_apis.py | {
"start": 1171,
"end": 1392
} | class ____(TypedDict, total=False):
"""Represent the parameters of ``is_authorized_connection`` API in the auth manager."""
method: ResourceMethod
details: ConnectionDetails | None
| IsAuthorizedConnectionRequest |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 13020,
"end": 15374
} | class ____(DataModel):
def __init__(self, dmm, fe_type):
super(UniTupleModel, self).__init__(dmm, fe_type)
self._elem_model = dmm.lookup(fe_type.dtype)
self._count = len(fe_type)
self._value_type = ir.ArrayType(self._elem_model.get_value_type(),
... | UniTupleModel |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 423,
"end": 627
} | class ____:
"""old style"""
def hop(self):
"""hop"""
super(NewAaaa, self).hop() # [no-member]
def __init__(self):
super(Aaaa, self).__init__() # [bad-super-call]
| NewAaaa |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-openai/llama_index/llms/openai/base.py | {
"start": 3055,
"end": 3618
} | class ____(Protocol):
"""Tokenizers support an encode function that returns a list of ints."""
def encode(self, text: str) -> List[int]: # fmt: skip
...
def force_single_tool_call(response: ChatResponse) -> None:
tool_calls = [
block for block in response.message.blocks if isinstance(blo... | Tokenizer |
python | keras-team__keras | keras/src/utils/backend_utils.py | {
"start": 1761,
"end": 6441
} | class ____:
"""A class that can be used to switch from one backend to another.
Example:
```python
backend = DynamicBackend("tensorflow")
y = backend.square(tf.constant(...))
backend.set_backend("jax")
y = backend.square(jax.numpy.array(...))
```
Args:
backend: Initial back... | DynamicBackend |
python | pytorch__pytorch | test/test_complex.py | {
"start": 403,
"end": 14571
} | class ____(TestCase):
@dtypes(*complex_types())
def test_to_list(self, device, dtype):
# test that the complex float tensor has expected values and
# there's no garbage value in the resultant list
self.assertEqual(
torch.zeros((2, 2), device=device, dtype=dtype).tolist(),
... | TestComplexTensor |
python | django__django | tests/admin_views/admin.py | {
"start": 6765,
"end": 6873
} | class ____(admin.ModelAdmin):
def has_module_permission(self, request):
return False
| ArticleAdmin2 |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_lat_lon_coordinates_in_range_of_given_point.py | {
"start": 1410,
"end": 6156
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.coordinates.in_range"
condition_value_keys = ("center_point", "range", "unit", "projection")
# This method implements the core logic for the PandasExecutionEng... | ColumnValuesAreLatLonCoordinatesInRange |
python | tensorflow__tensorflow | tensorflow/lite/python/interpreter_test.py | {
"start": 19859,
"end": 20988
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
super().setUp()
self.interpreter = interpreter_wrapper.Interpreter(
model_path=resource_loader.get_path_to_datafile(
'testdata/permute_float.tflite'
)
)
self.interpreter.allocate_tensors()
self.input0 = self.in... | InterpreterNodeAccessTest |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 89733,
"end": 91910
} | class ____:
def setup_method(self):
self.x = _old_loggamma_rvs(5, size=500, random_state=7654321) + 5
def test_basic(self):
N = 5
svals, ppcc = stats.ppcc_plot(self.x, -10, 10, N=N)
ppcc_expected = [0.21139644, 0.21384059, 0.98766719, 0.97980182,
0.93519... | TestPpccPlot |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 142428,
"end": 143465
} | class ____(TypedDict, total=False):
type: Required[Literal['definitions']]
schema: Required[CoreSchema]
definitions: Required[list[CoreSchema]]
metadata: dict[str, Any]
serialization: SerSchema
def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema:
"""
... | DefinitionsSchema |
python | falconry__falcon | examples/things.py | {
"start": 282,
"end": 1210
} | class ____:
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override
resp.text = (
'\nTwo things awe me most, the starry sky '
'abo... | ThingsResource |
python | huggingface__transformers | src/transformers/models/parakeet/tokenization_parakeet_fast.py | {
"start": 751,
"end": 1952
} | class ____(PreTrainedTokenizerFast):
"""
Inherits all methods from [`PreTrainedTokenizerFast`]. Users should refer to this superclass for more information regarding those methods,
except for `_decode` which is overridden to adapt it to CTC decoding:
1. Group consecutive tokens
2. Filter out the blan... | ParakeetTokenizerFast |
python | Textualize__textual | src/textual/drivers/_byte_stream.py | {
"start": 830,
"end": 3286
} | class ____(Generic[TokenType]):
"""A parser to feed in binary data and generate a sequence of tokens."""
read = _Read
read1 = _Read1
def __init__(self) -> None:
"""Initialize the parser."""
self._buffer = io.BytesIO()
self._eof = False
self._tokens: Deque[TokenType] = d... | ByteStreamParser |
python | apache__avro | lang/py/avro/test/test_datafile_interop.py | {
"start": 1118,
"end": 2169
} | class ____(unittest.TestCase):
def test_interop(self) -> None:
"""Test Interop"""
datum: Optional[object] = None
for filename in _INTEROP_DATA_DIR.iterdir():
self.assertGreater(os.stat(filename).st_size, 0)
base_ext = filename.stem.split("_", 1)
if len(bas... | TestDataFileInterop |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 25020,
"end": 25209
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("CREATED_AT", "NAME", "POSITION")
| ProjectV2FieldOrderField |
python | astropy__astropy | astropy/units/tests/test_format.py | {
"start": 797,
"end": 10902
} | class ____(NamedTuple):
string: str
unit: UnitBase
def list_format_string_pairs(*test_cases: tuple[str, str]) -> list[FormatStringPair]:
return [FormatStringPair(format, string) for format, string in test_cases]
def list_string_unit_pairs(
*test_cases: tuple[Iterable[str], UnitBase],
) -> list[Strin... | StringUnitPair |
python | crytic__slither | slither/tools/properties/properties/properties.py | {
"start": 265,
"end": 483
} | class ____(Enum):
OWNER = 1
SENDER = 2
ATTACKER = 3
ALL = 4 # If all the actors should call the function. Typically if the test uses msg.sender
ANY = 5 # If the caller does not matter
| PropertyCaller |
python | Textualize__textual | src/textual/__init__.py | {
"start": 1125,
"end": 5694
} | class ____:
"""A [logger class](/guide/devtools/#logging-handler) that logs to the Textual [console](/guide/devtools#console)."""
def __init__(
self,
log_callable: LogCallable | None,
group: LogGroup = LogGroup.INFO,
verbosity: LogVerbosity = LogVerbosity.NORMAL,
app: _A... | Logger |
python | doocs__leetcode | lcof/面试题26. 树的子结构/Solution.py | {
"start": 164,
"end": 647
} | class ____:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def dfs(A, B):
if B is None:
return True
if A is None or A.val != B.val:
return False
return dfs(A.left, B.left) and dfs(A.right, B.right)
if A is None or B is... | Solution |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/testdata/generate_checkpoint.py | {
"start": 1054,
"end": 1551
} | class ____(module.Module):
"""Three vars (one in a sub-module) and compute method."""
def __init__(self):
default_value = -1
empty_key = 0
deleted_key = -1
self.lookup_table = lookup_ops.DenseHashTable(
dtypes.int64,
dtypes.int64,
default_value=default_value,
empty_k... | TableModule |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/pyodbc.py | {
"start": 19693,
"end": 19937
} | class ____(_MSUnicodeText):
def get_dbapi_type(self, dbapi):
if self.length in (None, "max") or self.length >= 2000:
return (dbapi.SQL_WVARCHAR, 0, 0)
else:
return dbapi.SQL_WVARCHAR
| _UnicodeText_pyodbc |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 14985,
"end": 15744
} | class ____(Expr):
"""Baseclass for all binary expressions."""
fields = ("left", "right")
left: Expr
right: Expr
operator: str
abstract = True
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted op... | BinExpr |
python | scipy__scipy | scipy/stats/_discrete_distns.py | {
"start": 11193,
"end": 14525
} | class ____(rv_discrete):
r"""A beta-negative-binomial discrete random variable.
%(before_notes)s
Notes
-----
The beta-negative-binomial distribution is a negative binomial
distribution with a probability of success `p` that follows a
beta distribution.
The probability mass function fo... | betanbinom_gen |
python | pypa__warehouse | tests/unit/packaging/test_views.py | {
"start": 4410,
"end": 12256
} | class ____:
def test_normalizing_name_redirects(self, db_request):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="3.0")
db_request.matchdict = {"name": project.name.swapcase()}
db_request.current_route_path = pretend.call_recorder(
... | TestReleaseDetail |
python | google__jax | tests/lax_scipy_test.py | {
"start": 2970,
"end": 27045
} | class ____(jtu.JaxTestCase):
"""Tests for LAX-backed Scipy implementation."""
@jtu.sample_product(
[dict(shapes=shapes, axis=axis, use_b=use_b)
for shape_group in compatible_shapes
for use_b in [False, True]
for shapes in itertools.product(*(
(shape_group, shape_group) if use_b else (... | LaxBackedScipyTests |
python | encode__django-rest-framework | tests/browsable_api/test_form_rendering.py | {
"start": 866,
"end": 1810
} | class ____(TestCase):
"""
POSTing a list of data to a regular view should not cause the browsable
API to fail during rendering.
Regression test for https://github.com/encode/django-rest-framework/issues/5637
"""
def test_json_response(self):
# sanity check for non-browsable API respons... | TestPostingListData |
python | django__django | tests/admin_changelist/models.py | {
"start": 3345,
"end": 3440
} | class ____(models.Model):
char_pk = models.CharField(max_length=100, primary_key=True)
| CharPK |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 208000,
"end": 210671
} | class ____(SpecfileReaderBase):
SPEC_VERSION = 1
@classmethod
def load(cls, data):
"""Construct a spec from JSON/YAML using the format version 1.
Note: Version 1 format has no notion of a build_spec, and names are
guaranteed to be unique. This function is guaranteed to read specs a... | SpecfileV1 |
python | scikit-learn__scikit-learn | sklearn/linear_model/_glm/glm.py | {
"start": 1009,
"end": 17729
} | class ____(RegressorMixin, BaseEstimator):
"""Regression via a penalized Generalized Linear Model (GLM).
GLMs based on a reproductive Exponential Dispersion Model (EDM) aim at fitting and
predicting the mean of the target y as y_pred=h(X*w) with coefficients w.
Therefore, the fit minimizes the followin... | _GeneralizedLinearRegressor |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-gemini/llama_index/embeddings/gemini/base.py | {
"start": 606,
"end": 5050
} | class ____(BaseEmbedding):
"""
Google Gemini embeddings.
Args:
model_name (str): Model for embedding.
Defaults to "models/embedding-001".
api_key (Optional[str]): API key to access the model. Defaults to None.
api_base (Optional[str]): API base to access the model. Defa... | GeminiEmbedding |
python | TheAlgorithms__Python | other/lru_cache.py | {
"start": 137,
"end": 752
} | class ____[T, U]:
"""
Double Linked List Node built specifically for LRU Cache
>>> DoubleLinkedListNode(1,1)
Node: key: 1, val: 1, has next: False, has prev: False
"""
def __init__(self, key: T | None, val: U | None):
self.key = key
self.val = val
self.next: DoubleLinke... | DoubleLinkedListNode |
python | openai__openai-python | src/openai/types/responses/response.py | {
"start": 1642,
"end": 12152
} | class ____(BaseModel):
id: str
"""Unique identifier for this Response."""
created_at: float
"""Unix timestamp (in seconds) of when this Response was created."""
error: Optional[ResponseError] = None
"""An error object returned when the model fails to generate a Response."""
incomplete_det... | Response |
python | doocs__leetcode | solution/0900-0999/0902.Numbers At Most N Given Digit Set/Solution.py | {
"start": 0,
"end": 619
} | class ____:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
@cache
def dfs(i: int, lead: int, limit: bool) -> int:
if i >= len(s):
return lead ^ 1
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
... | Solution |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial001_py39.py | {
"start": 602,
"end": 2428
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
teams: list[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
sqlite_file_name = "da... | Hero |
python | spack__spack | lib/spack/spack/detection/test.py | {
"start": 950,
"end": 1406
} | class ____(NamedTuple):
"""Data structure to construct detection tests by PATH inspection.
Packages may have a YAML file containing the description of one or more detection tests
to be performed. Each test creates a few mock executable scripts in a temporary folder,
and checks that detection by PATH gi... | DetectionTest |
python | google__pytype | pytype/tests/test_anystr2.py | {
"start": 1756,
"end": 4162
} | class ____(test_base.BaseTest):
"""Tests for issues related to AnyStr in Python 3."""
def test_anystr(self):
ty = self.Infer("""
from typing import AnyStr
def f(x: AnyStr) -> AnyStr:
return __any_object__
""")
self.assertTypesMatchPytd(
ty,
"""
from typing impo... | AnyStrTestPy3 |
python | pytorch__pytorch | test/test_matmul_cuda.py | {
"start": 2191,
"end": 42809
} | class ____(InductorTestCase):
def setUp(self):
super().setUp()
torch.backends.cuda.matmul.allow_tf32 = False
def tearDown(self):
torch.backends.cuda.matmul.allow_tf32 = True
super().tearDown()
def cublas_addmm(
self,
size: int,
dtype: torch.dtype,
... | TestMatmulCuda |
python | pytorch__pytorch | test/jit/test_save_load.py | {
"start": 532,
"end": 26001
} | class ____(JitTestCase):
def test_different_modules(self):
"""
Exercise the situation where we have the same qualified name
in two different CompilationUnits on save/load.
"""
class Foo(torch.nn.Module):
def __init__(self) -> None:
super().__init_... | TestSaveLoad |
python | allegroai__clearml | clearml/utilities/parallel.py | {
"start": 3665,
"end": 7659
} | class ____(object):
"""
FutureTaskCaller is used to create a class via a functions async, in another thread.
For example:
.. code-block:: py
future = FutureTaskCaller().call(func=max, func_cb=None, override_cls=None, 1, 2)
print('Running other code')
print(future.result()) # ... | FutureTaskCaller |
python | instagram__MonkeyType | tests/test_cli.py | {
"start": 1217,
"end": 15361
} | class ____(DefaultConfig):
@contextmanager
def cli_context(self, command: str) -> Iterator[None]:
print(f"IN SETUP: {command}")
yield
print(f"IN TEARDOWN: {command}")
@pytest.fixture
def store_data():
with tempfile.NamedTemporaryFile(prefix='monkeytype_tests') as db_file:
c... | LoudContextConfig |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 76625,
"end": 76947
} | class ____(AddMMConfigMixin, CUDAMMTemplateConfigHeuristic):
"""Addmm specific mixin for CUDA"""
# TODO(coconutruben): deprecate once autoheuristic is deprecated
@register_template_heuristic(
mm_template.uid,
"cuda",
register=torch.version.hip is None,
op_name="mm-ah",
)
| CUDAAddMMTemplateConfigHeuristic |
python | spack__spack | lib/spack/spack/buildcache_prune.py | {
"start": 19830,
"end": 19958
} | class ____(spack.error.SpackError):
"""
Raised when pruning fails irrevocably
"""
pass
| BuildcachePruningException |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.