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 | tensorflow__tensorflow | tensorflow/python/training/session_run_hook.py | {
"start": 7995,
"end": 9485
} | class ____:
"""Provides information about the `session.run()` call being made.
Provides information about original request to `Session.Run()` function.
SessionRunHook objects can stop the loop by calling `request_stop()` of
`run_context`. In the future we may use this object to add more information
about run... | SessionRunContext |
python | encode__django-rest-framework | rest_framework/authtoken/models.py | {
"start": 135,
"end": 1553
} | class ____(models.Model):
"""
The default authorization token model.
"""
key = models.CharField(_("Key"), max_length=40, primary_key=True)
user = models.OneToOneField(
settings.AUTH_USER_MODEL, related_name='auth_token',
on_delete=models.CASCADE, verbose_name=_("User")
)
crea... | Token |
python | apache__airflow | providers/cohere/tests/unit/cohere/hooks/test_cohere.py | {
"start": 964,
"end": 1595
} | class ____:
"""
Test for CohereHook
"""
def test__get_api_key(self):
api_key = "test"
base_url = "http://some_host.com"
timeout = 150
with (
patch.object(
CohereHook,
"get_connection",
return_value=Connection(co... | TestCohereHook |
python | pytorch__pytorch | test/dynamo/test_autograd_function.py | {
"start": 496,
"end": 694
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, foo):
return foo + foo
@staticmethod
def backward(ctx, grad_output):
return grad_output
| CustomFunc1 |
python | doocs__leetcode | solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/Solution.py | {
"start": 0,
"end": 303
} | class ____:
def minSwaps(self, nums: List[int]) -> int:
k = nums.count(1)
mx = cnt = sum(nums[:k])
n = len(nums)
for i in range(k, n + k):
cnt += nums[i % n]
cnt -= nums[(i - k + n) % n]
mx = max(mx, cnt)
return k - mx
| Solution |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 35069,
"end": 35639
} | class ____(IntegrationMixin, DetailView):
model = HttpExchange
lookup_url_kwarg = "exchange_pk"
template_name = "projects/integration_exchange_detail.html"
def get_queryset(self):
# NOTE: We are explicitly using the id instead of the the object
# to avoid a bug where the id is wrongly c... | IntegrationExchangeDetail |
python | pytorch__pytorch | tools/test/gen_oplist_test.py | {
"start": 213,
"end": 1242
} | class ____(unittest.TestCase):
def setUp(self) -> None:
pass
def test_throw_if_any_op_includes_overloads(self) -> None:
selective_builder = MagicMock()
selective_builder.operators = MagicMock()
selective_builder.operators.items.return_value = [
("op1", MagicMock(incl... | GenOplistTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 37555,
"end": 39695
} | class ____(RegisterOp):
"""result = function(arg0, arg1, ...)
Call a C function that is not a compiled/native function (for
example, a Python C API function). Use Call to call native
functions.
"""
def __init__(
self,
function_name: str,
args: list[Value],
ret_t... | CallC |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 4629,
"end": 6624
} | class ____(IncrementalRkiCovidStream):
"""Docs: https://api.corona-zahlen.org/germany/germany/history/cases/:days"""
primary_key = None
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.start_date = config.get("start_date")
@property
def source_defined_cursor(s... | GermanyHistoryCases |
python | PrefectHQ__prefect | src/prefect/client/cloud.py | {
"start": 2005,
"end": 7973
} | class ____:
account_id: Optional[str] = None
workspace_id: Optional[str] = None
def __init__(
self,
host: str,
api_key: str,
httpx_settings: Optional[dict[str, Any]] = None,
) -> None:
httpx_settings = httpx_settings or dict()
httpx_settings.setdefault("h... | CloudClient |
python | TheAlgorithms__Python | machine_learning/automatic_differentiation.py | {
"start": 4715,
"end": 10307
} | class ____:
"""
Class contains methods to compute partial derivatives of Variable
based on the computation graph.
Examples:
>>> with GradientTracker() as tracker:
... a = Variable([2.0, 5.0])
... b = Variable([1.0, 2.0])
... m = Variable([1.0, 2.0])
... c = a + b
... | GradientTracker |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 949323,
"end": 949914
} | class ____(sgqlc.types.Type):
"""Choose which environments must be successfully deployed to before
branches can be merged into a branch that matches this rule.
"""
__schema__ = github_schema
__field_names__ = ("required_deployment_environments",)
required_deployment_environments = sgqlc.types.F... | RequiredDeploymentsParameters |
python | python-poetry__poetry | tests/types.py | {
"start": 3098,
"end": 3215
} | class ____(Protocol):
def __call__(self, relative_path: str, target: Path | None = None) -> Path: ...
| FixtureCopier |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 1501,
"end": 4190
} | class ____(unittest.TestCase):
def trivial_signal_handler(self, *args):
pass
def test_out_of_range_signal_number_raises_error(self):
self.assertRaises(ValueError, signal.getsignal, 4242)
self.assertRaises(ValueError, signal.signal, 4242,
self.trivial_signal_ha... | PosixTests |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 91066,
"end": 91143
} | class ____(BinOpSeries):
operation = M.gt
_operator_repr = ">"
| GTSeries |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 26461,
"end": 30408
} | class ____(PipesLogWriterChannel):
"""A base class for log writer channels that capture stdout and stderr of the current process."""
WAIT_FOR_TEE_SECONDS: float = 1.0
def __init__(self, stream: Literal["stdout", "stderr"], interval: float, name: str):
self.stream: Literal["stdout", "stderr"] = str... | PipesStdioLogWriterChannel |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_write_ext.py | {
"start": 297,
"end": 788
} | class ____(unittest.TestCase):
"""
Test the Drawing _write_ext() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_xdr_ext(self):
"""Test the _write_ext() method"""
self.drawing.... | TestWriteXdrext |
python | sqlalchemy__sqlalchemy | test/orm/test_joins.py | {
"start": 78521,
"end": 80762
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
__dialect__ = "default"
def _inherits_fixture(self):
m = MetaData()
base = Table("base", m, Column("id", Integer, primary_key=True))
a = Table(
"a",
m,
Column("id", Integer, ForeignKey("base.id"), p... | CreateJoinsTest |
python | coleifer__peewee | playhouse/hybrid.py | {
"start": 183,
"end": 613
} | class ____(ModelDescriptor):
def __init__(self, func, expr=None):
self.func = func
self.expr = expr or func
def __get__(self, instance, instance_type):
if instance is None:
return self.expr.__get__(instance_type, instance_type.__class__)
return self.func.__get__(inst... | hybrid_method |
python | pypa__pip | tests/lib/__init__.py | {
"start": 6875,
"end": 14816
} | class ____:
__test__ = False
def __init__(self, impl: ProcResult, verbose: bool = False) -> None:
self._impl = impl
if verbose:
print(self.stdout)
if self.stderr:
print("======= stderr ========")
print(self.stderr)
print("... | TestPipResult |
python | doocs__leetcode | solution/3000-3099/3011.Find if Array Can Be Sorted/Solution.py | {
"start": 0,
"end": 501
} | class ____:
def canSortArray(self, nums: List[int]) -> bool:
pre_mx = 0
i, n = 0, len(nums)
while i < n:
cnt = nums[i].bit_count()
j = i + 1
mi = mx = nums[i]
while j < n and nums[j].bit_count() == cnt:
mi = min(mi, nums[j])
... | Solution |
python | fastai__fastai | fastai/learner.py | {
"start": 24717,
"end": 29405
} | class ____(Callback):
"Callback that registers statistics (lr, loss and metrics) during training"
_stateattrs=('lrs','iters','losses','values')
remove_on_fetch,order = True,50
def __init__(self, add_time=True, train_metrics=False, valid_metrics=True, beta=0.98):
store_attr('add_time,train_metri... | Recorder |
python | fabric__fabric | tests/config.py | {
"start": 6992,
"end": 12849
} | class ____:
"ssh_config loading"
# NOTE: actual _behavior_ of loaded SSH configs is tested in Connection's
# tests; these tests just prove that the loading itself works & the data is
# correctly available.
_system_path = join(support, "ssh_config", "system.conf")
_user_path = join(support, "ss... | ssh_config_loading |
python | pandas-dev__pandas | asv_bench/benchmarks/categoricals.py | {
"start": 7409,
"end": 8506
} | class ____:
params = ["monotonic_incr", "monotonic_decr", "non_monotonic"]
param_names = ["index"]
def setup(self, index):
N = 10**6
categories = ["a", "b", "c"]
if index == "monotonic_incr":
codes = np.repeat([0, 1, 2], N)
elif index == "monotonic_decr":
... | CategoricalSlicing |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 40428,
"end": 46017
} | class ____(Qwen3VLMoePreTrainedModel):
config: Qwen3VLMoeTextConfig
_no_split_modules = ["Qwen3VLMoeTextDecoderLayer"]
def __init__(self, config: Qwen3VLMoeTextConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.... | Qwen3VLMoeTextModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/cursor.py | {
"start": 45122,
"end": 50232
} | class ____(CursorFetchStrategy):
"""A cursor fetch strategy with row buffering behavior.
This strategy buffers the contents of a selection of rows
before ``fetchone()`` is called. This is to allow the results of
``cursor.description`` to be available immediately, when
interfacing with a DB-API tha... | BufferedRowCursorFetchStrategy |
python | doocs__leetcode | solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/Solution.py | {
"start": 0,
"end": 1384
} | class ____:
def minArea(self, image: List[List[str]], x: int, y: int) -> int:
m, n = len(image), len(image[0])
left, right = 0, x
while left < right:
mid = (left + right) >> 1
c = 0
while c < n and image[mid][c] == '0':
c += 1
i... | Solution |
python | mwaskom__seaborn | tests/test_base.py | {
"start": 1411,
"end": 10770
} | class ____:
def test_plotter_default_init(self, long_df):
p = VectorPlotter(
data=long_df,
variables=dict(x="x", y="y"),
)
assert not hasattr(p, "_hue_map")
p = VectorPlotter(
data=long_df,
variables=dict(x="x", y="y", hue="a"),
... | TestHueMapping |
python | cython__cython | tests/run/posonly.py | {
"start": 10706,
"end": 11203
} | class ____(object):
"""
>>> TestPosonlyMethods().f(1,2)
(1, 2)
>>> TestPosonlyMethods.f(TestPosonlyMethods(), 1, 2)
(1, 2)
>>> try:
... TestPosonlyMethods.f(1,2)
... except TypeError:
... print("Got type error")
Got type error
>>> TestPosonlyMethods().f(1, b=2) # doct... | TestPosonlyMethods |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-milvus/integration_tests/milvus_integration_test.py | {
"start": 566,
"end": 5387
} | class ____(BaseIntegrationTest):
"""
Zilliz call to create the collection: /v1/vector/collections/create
{
"collectionName": "test2",
"dimension": 1536,
"metricType": "L2",
"vectorField": "vector",
"primaryField": "pk"
}
"""
def _init_milvus(self):
... | MilvusIntegrationTest |
python | huggingface__transformers | src/transformers/models/vitdet/configuration_vitdet.py | {
"start": 883,
"end": 7541
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VitDetModel`]. It is used to instantiate an
VitDet model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will y... | VitDetConfig |
python | apache__avro | lang/py/avro/compatibility.py | {
"start": 2185,
"end": 3877
} | class ____:
def __init__(
self,
compatibility: SchemaCompatibilityType = SchemaCompatibilityType.recursion_in_progress,
incompatibilities: Optional[List[SchemaIncompatibilityType]] = None,
messages: Optional[Set[str]] = None,
locations: Optional[Set[str]] = None,
):
... | SchemaCompatibilityResult |
python | pytorch__pytorch | torch/jit/frontend.py | {
"start": 22307,
"end": 22778
} | class ____(Builder):
@staticmethod
def build_withitem(ctx, item):
lineno = item.context_expr.lineno
start = item.context_expr.col_offset
end = start + len(pretty_node_names[ast.With])
op_vars = item.optional_vars
r = ctx.make_range(lineno, start, end)
return With... | WithItemBuilder |
python | getsentry__sentry | tests/sentry/grouping/test_strategies.py | {
"start": 368,
"end": 3757
} | class ____(TestCase):
def _get_new_context(self, initial_context: dict[str, Any] | None = None) -> GroupingContext:
strategy_class = create_strategy_configuration_class(
id="doggity_dogs_dogs", initial_context=initial_context
)
strategy_instance = strategy_class()
event ... | GroupingContextTest |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 10119,
"end": 11690
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Construct a layernorm module in the LongT5 style. No bias and no subtraction of mean.
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def ... | LongT5LayerNorm |
python | getsentry__sentry | src/sentry/models/project.py | {
"start": 4713,
"end": 7006
} | class ____(BaseManager["Project"]):
def get_by_users(self, users: Iterable[User | RpcUser]) -> dict[int, set[int]]:
"""Given a list of users, return a mapping of each user to the projects they are a member of."""
project_rows = self.filter(
projectteam__team__organizationmemberteam__is_a... | ProjectManager |
python | numba__numba | numba/core/typing/templates.py | {
"start": 33732,
"end": 36311
} | class ____(object):
"""Mixin for helper methods that assist with target/registry resolution"""
def _get_target_registry(self, reason):
"""Returns the registry for the current target.
Parameters
----------
reason: str
Reason for the resolution. Expects a noun.
... | _TemplateTargetHelperMixin |
python | huggingface__transformers | tests/models/cvt/test_modeling_cvt.py | {
"start": 1614,
"end": 5210
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=64,
num_channels=3,
embed_dim=[16, 32, 48],
num_heads=[1, 2, 3],
depth=[1, 2, 10],
patch_sizes=[7, 3, 3],
patch_stride=[4, 2, 2],
patch_padding=[2, 1, 1],
... | CvtModelTester |
python | getsentry__sentry | src/sentry/issues/search.py | {
"start": 1966,
"end": 9552
} | class ____(Protocol):
@property
def key(self) -> SearchKey: ...
@property
def is_negation(self) -> bool: ...
@property
def value(self) -> _IssueSearchFilterValue: ...
def _is_issue_type_filter(search_filter: SearchFilter) -> TypeGuard[_IssueSearchFilter]:
# via sentry.issues.issue_search
... | _IssueSearchFilter |
python | mlflow__mlflow | tests/store/artifact/test_artifact_repo.py | {
"start": 1075,
"end": 1699
} | class ____(ArtifactRepository):
"""Implementation of ArtifactRepository which simulates large artifact download."""
def log_artifact(self, local_file, artifact_path=None):
raise NotImplementedError()
def log_artifacts(self, local_dir, artifact_path=None):
raise NotImplementedError()
d... | SlowArtifactRepositoryImpl |
python | python__mypy | mypy/stubtest.py | {
"start": 88553,
"end": 97608
} | class ____:
modules: list[str]
concise: bool
ignore_missing_stub: bool
ignore_positional_only: bool
ignore_disjoint_bases: bool
allowlist: list[str]
generate_allowlist: bool
ignore_unused_allowlist: bool
mypy_config_file: str | None
custom_typeshed_dir: str | None
check_types... | _Arguments |
python | numba__numba | numba/cuda/tests/cudapy/test_slicing.py | {
"start": 277,
"end": 3156
} | class ____(CUDATestCase):
def test_slice_as_arg(self):
global cufoo
cufoo = cuda.jit("void(int32[:], int32[:])", device=True)(foo)
cucopy = cuda.jit("void(int32[:,:], int32[:,:])")(copy)
inp = np.arange(100, dtype=np.int32).reshape(10, 10)
out = np.zeros_like(inp)
c... | TestCudaSlicing |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 2255,
"end": 2643
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
month = indexes.CharField(indexed=False)
pub_date = indexes.DateTimeField(model_attr="pub_date")
def prepare_month(self, obj):
return "%02d" % obj.pub_date.month
def get_model(sel... | Elasticsearch5MaintainTypeMockSearchIndex |
python | mahmoud__glom | glom/reduction.py | {
"start": 4467,
"end": 4795
} | class ____(Fold):
"""
takes a count of how many values occurred
>>> glom([1, 2, 3], Count())
3
"""
__slots__ = ()
def __init__(self):
super().__init__(
subspec=T, init=int, op=lambda cur, val: cur + 1)
def __repr__(self):
return '%s()' % self.__class__.__na... | Count |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_reflection.py | {
"start": 21137,
"end": 23861
} | class ____(fixtures.TestBase):
__only_on__ = "oracle"
__sparse_driver_backend__ = True
@testing.only_on(enterprise_edition_or_version(18))
def test_reflect_basic_compression(self, metadata, connection):
tbl = Table(
"test_compress",
metadata,
Column("data", I... | TableReflectionTest |
python | pydantic__pydantic | tests/mypy/modules/plugin_optional_inheritance.py | {
"start": 62,
"end": 108
} | class ____(BaseModel):
id: Optional[int]
| Foo |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 32610,
"end": 34021
} | class ____(Interface):
"""Interface representing the type of object returned from
``IRoutesMapper.get_route``"""
name = Attribute('The route name')
pattern = Attribute('The route pattern')
factory = Attribute(
'The :term:`root factory` used by the :app:`Pyramid` router '
'when this ... | IRoute |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_compile.py | {
"start": 43053,
"end": 51639
} | class ____(DTensorTestBase):
@property
def world_size(self):
return 4
# multiprocess relies on pickling the source code
# so compiled autograd tests can't dynamically wrap this class
def _bwd_ctx(self, use_ca):
if not use_ca:
return contextlib.nullcontext()
retur... | TestDTensorCompileE2E |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 12985,
"end": 13835
} | class ____:
def maybe_positional_argument(self, include_star=True):
options = [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
if include_star:
options.append(Parameter.VAR_POSITIONAL)
return self.get_kind() in options
def maybe_keyword_argument(self, include_sta... | _ParamMixin |
python | jupyterlab__jupyterlab | jupyterlab/extensions/manager.py | {
"start": 11013,
"end": 26633
} | class ____(PluginManager):
"""Base abstract extension manager.
Note:
Any concrete implementation will need to implement the five
following abstract methods:
- :ref:`metadata`
- :ref:`get_latest_version`
- :ref:`list_packages`
- :ref:`install`
- :ref:`unin... | ExtensionManager |
python | ipython__ipython | tests/test_magic.py | {
"start": 10137,
"end": 19344
} | class ____(TestCase):
def test_reset_redefine(self):
@magics_class
class KernelMagics(Magics):
@line_magic
def less(self, shell):
pass
_ip.register_magics(KernelMagics)
with self.assertLogs() as cm:
# hack, we want to just capture... | TestResetErrors |
python | getsentry__sentry | tests/acceptance/test_member_list.py | {
"start": 181,
"end": 1267
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.create_m... | ListOrganizationMembersTest |
python | huggingface__transformers | src/transformers/models/glm4v/configuration_glm4v.py | {
"start": 11972,
"end": 15522
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar config... | Glm4vConfig |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 33172,
"end": 33448
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"COMMIT",
"ISSUE",
"PULL_REQUEST",
"PULL_REQUEST_REVIEW",
"REPOSITORY",
)
| RepositoryContributionType |
python | pytorch__pytorch | test/custom_operator/model.py | {
"start": 438,
"end": 1098
} | class ____(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.p = torch.nn.Parameter(torch.eye(5))
@torch.jit.script_method
def forward(self, input):
return torch.ops.custom.op_with_defaults(input)[0] + 1
def main():
parser = argparse.ArgumentParser(
... | Model |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/auth/managers/simple/routes/test_login.py | {
"start": 912,
"end": 4321
} | class ____:
@patch("airflow.api_fastapi.auth.managers.simple.routes.login.SimpleAuthManagerLogin")
def test_create_token(
self,
mock_simple_auth_manager_login,
test_client,
auth_manager,
):
mock_simple_auth_manager_login.create_token.return_value = "DUMMY_TOKEN"
... | TestLogin |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 20083,
"end": 20172
} | class ____(TestMaskedArrayCopyFilled, QuantitySetup):
pass
| TestMaskedQuantityCopyFilled |
python | pytorch__pytorch | test/jit/test_isinstance.py | {
"start": 456,
"end": 11462
} | class ____(JitTestCase):
def test_int(self):
def int_test(x: Any):
assert torch.jit.isinstance(x, int)
assert not torch.jit.isinstance(x, float)
x = 1
self.checkScript(int_test, (x,))
def test_float(self):
def float_test(x: Any):
assert torch... | TestIsinstance |
python | pypa__pip | src/pip/_vendor/pygments/lexers/python.py | {
"start": 48085,
"end": 53853
} | class ____(PythonLexer):
"""
A Python lexer recognizing Numerical Python builtins.
"""
name = 'NumPy'
url = 'https://numpy.org/'
aliases = ['numpy']
version_added = '0.10'
# override the mimetypes to not inherit them from python
mimetypes = []
filenames = []
EXTRA_KEYWORDS... | NumPyLexer |
python | dagster-io__dagster | python_modules/automation/automation/eval/cli.py | {
"start": 1362,
"end": 10109
} | class ____:
"""Configuration for evaluation."""
metrics: list[Metric]
def load_config(eval_dir: Path) -> EvalConfig:
"""Load and validate the evaluation configuration."""
config_path = eval_dir / "eval.yaml"
if not config_path.exists():
raise click.UsageError(f"Configuration file {config_... | EvalConfig |
python | ray-project__ray | doc/source/ray-overview/examples/e2e-multimodal-ai-workloads/doggos/doggos/serve.py | {
"start": 490,
"end": 1700
} | class ____:
def __init__(self, model_id, artifacts_dir, device="cuda"):
"""Initialize the model."""
# Embedding model
self.processor = CLIPProcessor.from_pretrained(model_id)
self.model = CLIPModel.from_pretrained(model_id)
self.model.to(device=device)
self.device = d... | ClassPredictor |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 69992,
"end": 73660
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
generation. See [Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904) for more information.
Args:
prefix_allowed_tokens_fn (`Callable... | PrefixConstrainedLogitsProcessor |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_repr_returned.py | {
"start": 308,
"end": 421
} | class ____:
"""__repr__ returns <type 'str'>"""
def __repr__(self):
return str(123)
| SecondGoodRepr |
python | walkccc__LeetCode | solutions/3389. Minimum Operations to Make Character Frequencies Equal/3389.py | {
"start": 0,
"end": 1539
} | class ____:
def makeStringGood(self, s: str) -> int:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
return min(self._getMinOperations(count, target)
for target in range(1, max(count) + 1))
def _getMinOperations(self, count: list[int], target: int) -> int:
# dp[i] re... | Solution |
python | mlflow__mlflow | mlflow/entities/run_outputs.py | {
"start": 217,
"end": 1316
} | class ____(_MlflowObject):
"""RunOutputs object."""
def __init__(self, model_outputs: list[LoggedModelOutput]) -> None:
self._model_outputs = model_outputs
def __eq__(self, other: _MlflowObject) -> bool:
if type(other) is type(self):
return self.__dict__ == other.__dict__
... | RunOutputs |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py | {
"start": 38594,
"end": 44688
} | class ____:
"""Tests for the automatic eviction loop in PrefixTreeActor"""
async def test_eviction_loop_triggers_automatically(
self, tree_actor: PrefixTreeActor
) -> None:
"""Test that the eviction loop automatically evicts data when threshold is exceeded."""
# Set up eviction para... | TestPrefixTreeActorEvictionLoop |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance3.py | {
"start": 926,
"end": 1805
} | class ____(Generic[_T]):
v1: _T
v2: Type[_T]
@property
@abstractmethod
def _elem_type_(self) -> Union[Type[_T], Tuple[Type[_T], ...]]:
raise NotImplementedError
def check_type(self, var: Any) -> bool:
return isinstance(var, self._elem_type_)
def execute(self, var: Union[_T... | ClassA |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/window.py | {
"start": 1986,
"end": 2064
} | class ____:
Outline = "outline"
Toolbars = "toolbars"
| WindowMenuSections |
python | networkx__networkx | networkx/classes/tests/test_subgraphviews.py | {
"start": 7932,
"end": 9828
} | class ____:
@classmethod
def setup_class(cls):
cls.K3 = G = nx.complete_graph(3)
G.graph["foo"] = []
G.nodes[0]["foo"] = []
G.remove_edge(1, 2)
ll = []
G.add_edge(1, 2, foo=ll)
G.add_edge(2, 1, foo=ll)
def test_full_graph(self):
G = self.K3
... | TestInducedSubGraph |
python | walkccc__LeetCode | solutions/455. Assign Cookies/455.py | {
"start": 0,
"end": 211
} | class ____:
def findContentChildren(self, g: list[int], s: list[int]) -> int:
g.sort()
s.sort()
i = 0
for cookie in s:
if i < len(g) and g[i] <= cookie:
i += 1
return i
| Solution |
python | coleifer__peewee | peewee.py | {
"start": 52963,
"end": 53217
} | class ____(Node):
def __init__(self, node, in_function=True):
self.node = node
self.in_function = in_function
def __sql__(self, ctx):
with ctx(in_function=self.in_function):
return ctx.sql(self.node)
| _InFunction |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/distlib/util.py | {
"start": 44405,
"end": 52379
} | class ____(object):
unknown = 'UNKNOWN'
def __init__(self, minval=0, maxval=100):
assert maxval is None or maxval >= minval
self.min = self.cur = minval
self.max = maxval
self.started = None
self.elapsed = 0
self.done = False
def update(self, curval):
... | Progress |
python | pytorch__pytorch | test/distributed/checkpoint/test_async_process_executor.py | {
"start": 5818,
"end": 7318
} | class ____(TestCase):
@skip_if_win32()
@retry_on_connect_failures
def test_checkpoint_save_with_prefix_store_enabled(self) -> None:
"""Test that checkpoint save works when DCP_USE_PREFIX_STORE is enabled."""
test_state_dict = {
"model": {"weight": torch.randn(4, 4), "bias": torc... | TestAsyncProcessExecutorPrefixStore |
python | tiangolo__fastapi | docs_src/request_form_models/tutorial001.py | {
"start": 84,
"end": 228
} | class ____(BaseModel):
username: str
password: str
@app.post("/login/")
async def login(data: FormData = Form()):
return data
| FormData |
python | scikit-learn__scikit-learn | sklearn/utils/_param_validation.py | {
"start": 12628,
"end": 13103
} | class ____(Options):
"""Constraint representing a finite set of strings.
Parameters
----------
options : set of str
The set of valid strings.
deprecated : set of str or None, default=None
A subset of the `options` to mark as deprecated in the string
representation of the co... | StrOptions |
python | django__django | tests/generic_views/views.py | {
"start": 359,
"end": 616
} | class ____(generic.TemplateView):
template_name = "generic_views/about.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({"key": "value"})
return context
| CustomTemplateView |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 323837,
"end": 325835
} | class ____(Request):
"""
Get the list of task configuration items names
:param tasks: Task IDs
:type tasks: Sequence[str]
:param skip_empty: If set to 'true' then the names for configurations with
missing values are not returned
:type skip_empty: bool
"""
_service = "tasks"
... | GetConfigurationNamesRequest |
python | joke2k__faker | faker/providers/address/cs_CZ/__init__.py | {
"start": 45,
"end": 26466
} | class ____(AddressProvider):
city_formats = ("{{city_name}}",)
street_name_formats = ("{{street_name}}",)
street_address_formats = ("{{street_name}} {{building_number}}",)
address_formats = ("{{street_address}}\n{{postcode}} {{city}}",)
building_number_formats = ("%", "%#", "%##")
street_suff... | Provider |
python | django-haystack__django-haystack | test_haystack/test_managers.py | {
"start": 997,
"end": 1102
} | class ____(BasicMockModelSearchIndex):
another = CustomManager()
| CustomMockModelIndexWithAnotherManager |
python | wandb__wandb | wandb/sdk/data_types/graph.py | {
"start": 6188,
"end": 12845
} | class ____(Media):
"""W&B class for graphs.
This class is typically used for saving and displaying neural net models.
It represents the graph as an array of nodes and edges. The nodes can have
labels that can be visualized by wandb.
Attributes:
format (string): Format to help wandb display... | Graph |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/base.py | {
"start": 6567,
"end": 6806
} | class ____:
"""Internal representation of an planned materialization event, containing storage_id / run_id.
Users should not invoke this class directly.
"""
storage_id: int
run_id: str
@record
| PlannedMaterializationInfo |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/optimization/filter_fusion_test.py | {
"start": 2263,
"end": 4347
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
_test_combinations()))
def testFilterFusion(self, function, predicates):
dataset = dataset_ops.Dataset.range(5).apply(
testing.... | FilterFusionTest |
python | crytic__slither | slither/solc_parsing/declarations/using_for_top_level.py | {
"start": 827,
"end": 8066
} | class ____(CallerContextExpression): # pylint: disable=too-few-public-methods
"""
UsingFor class
"""
def __init__(
self,
uftl: UsingForTopLevel,
top_level_data: Dict,
slither_parser: "SlitherCompilationUnitSolc",
) -> None:
self._type_name = top_level_data["... | UsingForTopLevelSolc |
python | getsentry__sentry | src/sentry/hybridcloud/services/replica/impl.py | {
"start": 5792,
"end": 11805
} | class ____(RegionReplicaService):
def upsert_replicated_api_token(self, *, api_token: RpcApiToken, region_name: str) -> None:
organization: Organization | None = None
if api_token.organization_id is not None:
try:
organization = Organization.objects.get(id=api_token.organ... | DatabaseBackedRegionReplicaService |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType9.py | {
"start": 280,
"end": 489
} | class ____(Generic[_T1]):
@staticmethod
def func1(value: _T1) -> "ClassA[_T1]":
return ClassA[_T1]()
@classmethod
def func2(cls, value: _T1) -> "ClassA[_T1]":
return cls()
| ClassA |
python | doocs__leetcode | solution/3300-3399/3392.Count Subarrays of Length Three With a Condition/Solution.py | {
"start": 0,
"end": 188
} | class ____:
def countSubarrays(self, nums: List[int]) -> int:
return sum(
(nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1)
)
| Solution |
python | coleifer__peewee | tests/models.py | {
"start": 181957,
"end": 183729
} | class ____(ModelTestCase):
requires = [User, Tweet]
def test_bind_to(self):
for i in (1, 2, 3):
user = User.create(username='u%s' % i)
Tweet.create(user=user, content='t%s' % i)
# Alias to a particular field-name.
name = Case(User.username, [
('u1', ... | TestBindTo |
python | huggingface__transformers | tests/models/kosmos2/test_modeling_kosmos2.py | {
"start": 6556,
"end": 9243
} | class ____:
def __init__(self, parent, text_kwargs=None, vision_kwargs=None, latent_query_num=3, is_training=True):
if text_kwargs is None:
text_kwargs = {}
if vision_kwargs is None:
vision_kwargs = {}
self.parent = parent
self.text_model_tester = Kosmos2Text... | Kosmos2ModelTester |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/scalar_pointwise.py | {
"start": 2331,
"end": 3311
} | class ____(ScalarPointwiseOperator):
"""Operator for scalar division."""
def __init__(self):
super().__init__("scalar_div", "/")
def codegen(
self, output_name: str, input_names: list[str], output_spec: Spec
) -> str:
"""Generate code for scalar division with zero-denominator g... | ScalarDivOperator |
python | google__jax | jax/experimental/colocated_python/func.py | {
"start": 1643,
"end": 17703
} | class ____:
"""Specialization for a colocated_python function."""
in_specs_treedef: tree_util.PyTreeDef | None = None
in_specs_leaves: tuple[api.ShapeDtypeStruct, ...] | None = None
out_specs_fn: Callable[..., ShapeDtypeStructTree] | None = None
out_specs_treedef: tree_util.PyTreeDef | None = None
out_spec... | Specialization |
python | doocs__leetcode | solution/0100-0199/0198.House Robber/Solution.py | {
"start": 0,
"end": 242
} | class ____:
def rob(self, nums: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(nums):
return 0
return max(nums[i] + dfs(i + 2), dfs(i + 1))
return dfs(0)
| Solution |
python | encode__django-rest-framework | rest_framework/management/commands/generateschema.py | {
"start": 299,
"end": 2931
} | class ____(BaseCommand):
help = "Generates configured API schema for project."
def get_mode(self):
return COREAPI_MODE if coreapi.is_enabled() else OPENAPI_MODE
def add_arguments(self, parser):
parser.add_argument('--title', dest="title", default='', type=str)
parser.add_argument('... | Command |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 1195,
"end": 1293
} | class ____:
try:
...
finally:
def __eq__(self, other): ...
| MaybeEqTryFinally |
python | great-expectations__great_expectations | great_expectations/render/view/view.py | {
"start": 1244,
"end": 16184
} | class ____:
"""
Defines a method for converting a document to human-consumable form
Dependencies
~~~~~~~~~~~~
* Font Awesome 5.10.1
* Bootstrap 4.3.1
* jQuery 3.2.1
* Vega 5
* Vega-Lite 4
* Vega-Embed 6
"""
_template: ClassVar[str]
def __init__(self, custom_styles... | DefaultJinjaView |
python | scipy__scipy | scipy/interpolate/tests/test_bsplines.py | {
"start": 74783,
"end": 78305
} | class ____:
# Test row-by-row QR factorization, used for the LSQ spline construction.
# This is implementation detail; still test it separately.
def _get_xyt(self, n):
k = 3
x = np.arange(n, dtype=float)
y = x**3 + 1/(1+x)
t = _not_a_knot(x, k)
return x, y, t, k
... | TestGivensQR |
python | sanic-org__sanic | sanic/worker/process.py | {
"start": 7105,
"end": 8772
} | class ____:
WORKER_PREFIX = "Sanic"
def __init__(
self,
ident: str,
name: str,
serve,
server_settings,
context: BaseContext,
worker_state: dict[str, Any],
num: int = 1,
restartable: bool = False,
tracked: bool = True,
auto_... | Worker |
python | dagster-io__dagster | examples/airlift-migration-tutorial/tutorial_example/airflow_dags/dags.py | {
"start": 654,
"end": 1652
} | class ____(BaseOperator):
def __init__(
self,
table_name: str,
csv_path: Path,
duckdb_path: Path,
column_names: list[str],
duckdb_schema: str,
duckdb_database_name: str,
*args,
**kwargs,
):
self._table_name = table_name
self... | LoadCSVToDuckDB |
python | getsentry__sentry | src/sentry/notifications/types.py | {
"start": 7435,
"end": 7712
} | class ____(Enum):
ISSUE_OWNERS = "IssueOwners"
TEAM = "Team"
MEMBER = "Member"
ACTION_CHOICES = [
(ActionTargetType.ISSUE_OWNERS.value, "Issue Owners"),
(ActionTargetType.TEAM.value, "Team"),
(ActionTargetType.MEMBER.value, "Member"),
]
| ActionTargetType |
python | huggingface__transformers | tests/models/falcon_mamba/test_modeling_falcon_mamba.py | {
"start": 16631,
"end": 23426
} | class ____(unittest.TestCase):
def setUp(self):
self.model_id = "tiiuae/falcon-mamba-7b"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.text = "Hello today"
cleanup(torch_device, gc_collect=True)
def tearDown(self):
cleanup(torch_device, gc_collect=T... | FalconMambaIntegrationTests |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/fields.py | {
"start": 783,
"end": 1377
} | class ____:
params = [
_sizes,
[
"Y",
"M",
"D",
"h",
"m",
"s",
"us",
"ns",
"doy",
"dow",
"woy",
"q",
"dim",
"is_leap_year",
... | TimeGetDateField |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.