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 | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 11750,
"end": 11896
} | class ____(_HybridNearBase):
text: Union[str, List[str]]
move_to: Optional[Move] = None
move_away: Optional[Move] = None
| _HybridNearText |
python | getsentry__sentry | src/sentry/integrations/types.py | {
"start": 1061,
"end": 1167
} | class ____(StrEnum):
SEGMENT = "segment"
SQS = "sqs"
SPLUNK = "splunk"
| DataForwarderProviderSlug |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 103045,
"end": 108378
} | class ____(Token):
"""
Token to exactly match a specified string as a keyword, that is,
it must be immediately preceded and followed by whitespace or
non-keyword characters. Compare with :class:`Literal`:
- ``Literal("if")`` will match the leading ``'if'`` in
``'ifAndOnlyIf'``.
- ``Keywor... | Keyword |
python | ray-project__ray | python/ray/train/v2/tests/util.py | {
"start": 1143,
"end": 2944
} | class ____(WorkerGroup):
_start_failure = None
_poll_failure = None
# TODO: Clean this up and use Mocks instead.
def __init__(
self,
train_run_context: TrainRunContext,
worker_group_context: WorkerGroupContext,
callbacks=None,
):
self._num_workers = worker_g... | DummyWorkerGroup |
python | google__pytype | pytype/abstract/_instances.py | {
"start": 27740,
"end": 29120
} | class ____(_base.BaseValue, mixin.HasSlots):
"""Sequence length for match statements."""
def __init__(
self, sequence: list[cfg.Variable], ctx: "context.Context"
) -> None:
super().__init__("SequenceLength", ctx)
length = 0
splat = False
for var in sequence:
if any(isinstance(x, Splat... | SequenceLength |
python | mahmoud__glom | glom/matching.py | {
"start": 24488,
"end": 28455
} | class ____:
r"""The :class:`Switch` specifier type routes data processing based on
matching keys, much like the classic switch statement.
Here is a spec which differentiates between lowercase English
vowel and consonant characters:
>>> switch_spec = Match(Switch([(Or('a', 'e', 'i', 'o', 'u'), Va... | Switch |
python | huggingface__transformers | src/transformers/models/levit/modeling_levit.py | {
"start": 18387,
"end": 20250
} | class ____(LevitPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.patch_embeddings = LevitPatchEmbeddings(config)
self.encoder = LevitEncoder(config)
# Initialize weights and apply final processing
self.post_init()
@... | LevitModel |
python | google__jax | jax/experimental/mosaic/gpu/fragmented_array.py | {
"start": 34804,
"end": 126066
} | class ____:
# An array of ir.Value, see checks in init for shapes.
registers: np.ndarray = dataclasses.field(repr=False)
layout: FragmentedLayout
is_signed: bool | None
def __init__(
self,
*,
_registers: np.ndarray,
_layout: FragmentedLayout,
_is_signed: bool | None,
):
""... | FragmentedArray |
python | django__django | tests/template_tests/filter_tests/test_escapejs.py | {
"start": 1071,
"end": 2460
} | class ____(SimpleTestCase):
def test_quotes(self):
self.assertEqual(
escapejs_filter("\"double quotes\" and 'single quotes'"),
"\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027",
)
def test_backslashes(self):
self.assertEqual(
escapejs_filt... | FunctionTests |
python | fluentpython__example-code-2e | 22-dyn-attr-prop/oscon/schedule_v5.py | {
"start": 944,
"end": 2233
} | class ____(Record):
def __repr__(self):
try:
return f'<{self.__class__.__name__} {self.name!r}>'
except AttributeError:
return super().__repr__()
# tag::SCHEDULE5_CACHED_PROPERTY[]
@cached_property
def venue(self):
key = f'venue.{self.venue_serial}'
... | Event |
python | pandas-dev__pandas | pandas/core/computation/scope.py | {
"start": 2691,
"end": 10204
} | class ____:
"""
Object to hold scope, with a few bells to deal with some custom syntax
and contexts added by pandas.
Parameters
----------
level : int
global_dict : dict or None, optional, default None
local_dict : dict or Scope or None, optional, default None
resolvers : list-like ... | Scope |
python | fastai__fastai | fastai/text/data.py | {
"start": 5734,
"end": 7688
} | class ____(ItemTransform):
def encodes(self,samples, pad_idx=1, pad_fields=0, pad_first=False, backwards=False):
"Function that collect `samples` and adds padding"
self.pad_idx = pad_idx
pad_fields = L(pad_fields)
max_len_l = pad_fields.map(lambda f: max([len(s[f]) for s in samples])... | Pad_Input |
python | kamyu104__LeetCode-Solutions | Python/4sum.py | {
"start": 2647,
"end": 3575
} | class ____(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
for i in xrange(0, len(nums) - 1):
for j in xrange(i... | Solution3 |
python | anthropics__anthropic-sdk-python | tests/api_resources/beta/test_messages.py | {
"start": 443,
"end": 19382
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@pytest.mark.skip(reason="prism validates based on the non-beta endpoint")
@parametrize
def test_method_create_overload_1(self, client: Anthropic) -> None:
message = client.beta.me... | TestMessages |
python | jina-ai__jina | tests/integration/hot_reload/my_executor_3_new.py | {
"start": 169,
"end": 313
} | class ____(A):
@requests
def y(self, docs, **kwargs):
for doc in docs:
doc.text = 'EnhancedAfterReload'
| EnhancedExecutor |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-postgresml/llama_index/indices/managed/postgresml/query.py | {
"start": 1269,
"end": 2343
} | class ____(Generator, AsyncGenerator):
def __init__(self, rag_stream_results) -> None:
self.rag_stream_results = rag_stream_results
self.rag_stream = None
def asend(self):
raise Exception("asend is not implemented")
def send(self):
raise Exception("send is not implemented")... | AsyncJsonGenerator |
python | pytorch__pytorch | .github/scripts/generate_ci_workflows.py | {
"start": 2956,
"end": 10877
} | class ____:
LINUX = "linux"
WINDOWS = "windows"
WINDOWS_ARM64 = "windows-arm64"
MACOS = "macos"
MACOS_ARM64 = "macos-arm64"
LINUX_AARCH64 = "linux-aarch64"
LINUX_S390X = "linux-s390x"
LINUX_BINARY_BUILD_WORFKLOWS = [
BinaryBuildWorkflow(
os=OperatingSystem.LINUX,
packag... | OperatingSystem |
python | getsentry__sentry | src/sentry/snuba/outcomes.py | {
"start": 3878,
"end": 5199
} | class ____(Dimension[DataCategory]):
def resolve_filter(self, raw_filter: Sequence[str]) -> list[DataCategory]:
resolved_categories = set()
for category in raw_filter:
# combine DEFAULT, ERROR, and SECURITY as errors.
# see relay: py/sentry_relay/consts.py and relay-cabi/incl... | CategoryDimension |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 29657,
"end": 31266
} | class ____(GeneratedAirbyteSource):
class OAuth20:
@public
def __init__(self, client_id: str, client_secret: str, refresh_token: str):
self.auth_type = "oauth2.0"
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client_... | OktaSource |
python | plotly__plotly.py | plotly/graph_objs/sankey/_hoverlabel.py | {
"start": 233,
"end": 11234
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sankey"
_path_str = "sankey.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
... | Hoverlabel |
python | coleifer__peewee | playhouse/postgres_ext.py | {
"start": 13226,
"end": 15308
} | class ____(PostgresqlDatabase):
def __init__(self, *args, **kwargs):
self._register_hstore = kwargs.pop('register_hstore', False)
self._server_side_cursors = kwargs.pop('server_side_cursors', False)
super(PostgresqlExtDatabase, self).__init__(*args, **kwargs)
def _connect(self):
... | PostgresqlExtDatabase |
python | django__django | tests/contenttypes_tests/test_models.py | {
"start": 12509,
"end": 12789
} | class ____:
def db_for_read(self, model, **hints):
return "other"
def db_for_write(self, model, **hints):
return "default"
def allow_relation(self, obj1, obj2, **hints):
return True
@override_settings(DATABASE_ROUTERS=[TestRouter()])
| TestRouter |
python | pytorch__pytorch | torch/_inductor/cudagraph_trees.py | {
"start": 27435,
"end": 27600
} | class ____(OutputAliasInfo):
"Singleton to mark that the graph output constructs a new alias or is None"
UnaliasedStorage = _UnaliasedStorage()
| _UnaliasedStorage |
python | davidhalter__jedi | jedi/inference/value/decorator.py | {
"start": 194,
"end": 1207
} | class ____(ValueWrapper):
def __init__(self, wrapped_value, original_value):
super().__init__(wrapped_value)
self._original_value = original_value
def py__doc__(self):
return self._original_value.py__doc__()
def py__get__(self, instance, class_value):
return ValueSet(
... | Decoratee |
python | ray-project__ray | python/ray/serve/_private/cluster_node_info_cache.py | {
"start": 206,
"end": 3379
} | class ____(ABC):
"""Provide access to cached node information in the cluster."""
def __init__(self, gcs_client: GcsClient):
self._gcs_client = gcs_client
self._cached_alive_nodes = None
self._cached_node_labels = dict()
self._cached_total_resources_per_node = dict()
self... | ClusterNodeInfoCache |
python | urllib3__urllib3 | test/test_exceptions.py | {
"start": 525,
"end": 2420
} | class ____:
@pytest.mark.parametrize(
"exception",
[
HTTPError(None),
MaxRetryError(DUMMY_POOL, "", None),
MaxRetryError(DUMMY_POOL, "", Exception("Error occured")),
LocationParseError(""),
ConnectTimeoutError(None),
HTTPError("... | TestPickle |
python | mlflow__mlflow | mlflow/system_metrics/metrics/gpu_monitor.py | {
"start": 406,
"end": 2905
} | class ____(BaseMetricsMonitor):
"""Class for monitoring GPU stats."""
def __init__(self):
if "pynvml" not in sys.modules:
# Only instantiate if `pynvml` is installed.
raise ImportError(
"`nvidia-ml-py` is not installed, to log GPU metrics please run "
... | GPUMonitor |
python | pola-rs__polars | pyo3-polars/example/derive_expression/expression_lib/expression_lib/extension.py | {
"start": 688,
"end": 1165
} | class ____:
def __init__(self, expr: pl.Expr):
self._expr = expr
def __getattr__(self, attr: str) -> Callable[..., pl.Expr]:
if attr in ("pig_latinnify", "append_args"):
def func(*args: Any, **kwargs: Any) -> pl.Expr:
return getattr(language, attr)(self._expr, *args... | Language |
python | google__pytype | pytype/directors/directors_test.py | {
"start": 13595,
"end": 15401
} | class ____(DirectorTestCase):
def test_type_comment_on_multiline_value(self):
self._create("""
v = [
("hello",
"world", # type: should_be_ignored
)
] # type: dict
""")
self.assertEqual({2: "dict"}, self._director.type_comments)
def test_type_comment_with_trailin... | LineNumbersTest |
python | doocs__leetcode | solution/1600-1699/1631.Path With Minimum Effort/Solution3.py | {
"start": 0,
"end": 682
} | class ____:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m, n = len(heights), len(heights[0])
dist = [[inf] * n for _ in range(m)]
dist[0][0] = 0
dirs = (-1, 0, 1, 0, -1)
q = [(0, 0, 0)]
while q:
t, i, j = heappop(q)
for a, b i... | Solution |
python | getsentry__sentry | src/sentry/interfaces/exception.py | {
"start": 7195,
"end": 11706
} | class ____(Interface):
"""
A standard exception with a ``type`` and value argument, and an optional
``module`` argument describing the exception class type and
module namespace. Either ``type`` or ``value`` must be present.
You can also optionally bind a stacktrace interface to an exception. The
... | SingleException |
python | pytorch__pytorch | test/export/test_export_opinfo.py | {
"start": 3400,
"end": 4067
} | class ____(TestCase):
@ops(op_db, allowed_dtypes=(torch.float,))
@skipOps(
"TestExportOpInfo", "test_fake_export", export_failures | fake_export_failures
)
def test_fake_export(self, device, dtype, op):
_test_export_helper(self, dtype, op)
instantiate_device_type_tests(TestExportOpInfo... | TestExportOpInfo |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/_utils.py | {
"start": 19213,
"end": 19574
} | class ____(LoadFromBytesImpl):
def load_from_bytes(self, byte_values: list[bytes | None]) -> pl.Series:
import polars as pl
return (
pl.Series(byte_values, dtype=pl.Binary).bin.reinterpret(
dtype=pl.Int64, endianness="little"
)
* ICEBERG_TIME_TO_N... | LoadTimeFromBytes |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_type_check.py | {
"start": 6023,
"end": 6312
} | class ____(TestCase):
def test_fail(self):
z = np.array([-1, 0, 1])
res = iscomplex(z)
assert_(not np.any(res, axis=0))
def test_pass(self):
z = np.array([-1j, 1, 0])
res = iscomplex(z)
assert_array_equal(res, [1, 0, 0])
| TestIscomplex |
python | django__django | tests/forms_tests/widget_tests/test_multiwidget.py | {
"start": 2293,
"end": 10524
} | class ____(WidgetTest):
def test_subwidgets_name(self):
widget = MultiWidget(
widgets={
"": TextInput(),
"big": TextInput(attrs={"class": "big"}),
"small": TextInput(attrs={"class": "small"}),
},
)
self.check_html(
... | MultiWidgetTest |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_random_test.py | {
"start": 1399,
"end": 2337
} | class ____(test.TestCase, parameterized.TestCase):
def _test(self, *args, **kw_args):
onp_dtype = kw_args.pop('onp_dtype', None)
allow_float64 = kw_args.pop('allow_float64', True)
old_allow_float64 = np_dtypes.is_allow_float64()
np_dtypes.set_allow_float64(allow_float64)
old_func = getattr(self, ... | RandomTestBase |
python | doocs__leetcode | solution/1100-1199/1175.Prime Arrangements/Solution.py | {
"start": 0,
"end": 469
} | class ____:
def numPrimeArrangements(self, n: int) -> int:
def count(n):
cnt = 0
primes = [True] * (n + 1)
for i in range(2, n + 1):
if primes[i]:
cnt += 1
for j in range(i + i, n + 1, i):
pri... | Solution |
python | explosion__spaCy | spacy/lang/ca/__init__.py | {
"start": 700,
"end": 1344
} | class ____(Language):
lang = "ca"
Defaults = CatalanDefaults
@Catalan.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={
"model": None,
"mode": "rule",
"overwrite": False,
"scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"},
},
default_score_w... | Catalan |
python | getsentry__sentry | src/sentry/notifications/services/model.py | {
"start": 750,
"end": 873
} | class ____(RpcModel):
is_disabled: bool
is_active: bool
has_only_inactive_subscriptions: bool
| RpcSubscriptionStatus |
python | tensorflow__tensorflow | tensorflow/python/ops/special_math_ops_test.py | {
"start": 16184,
"end": 26816
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_besseli_boundary(self):
self.assertAllClose(1., special_math_ops.bessel_i0(0.))
self.assertAllClose(1., special_math_ops.bessel_i0e(0.))
self.assertAllClose(0., special_math_ops.bessel_i1(0.))
self.a... | BesselTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py | {
"start": 7159,
"end": 7761
} | class ____(ZenloopStream):
# API Doc: https://docs.zenloop.com/reference#get-list-of-survey-groups
primary_key = None
has_date_param = False
extra_params = {"page": "1"}
use_cache = True
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next... | SurveyGroups |
python | getsentry__sentry | src/sentry/issues/endpoints/project_user_issue.py | {
"start": 5568,
"end": 5870
} | class ____(ProjectUserIssueRequestSerializer):
score = serializers.IntegerField(required=True, min_value=0, max_value=100)
vital = serializers.ChoiceField(required=True, choices=["lcp", "fcp", "cls", "inp", "ttfb"])
value = serializers.IntegerField(required=True)
| WebVitalsIssueDataSerializer |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/agent_tests/test_business_logic.py | {
"start": 5765,
"end": 9612
} | class ____:
"""Test processing of agent data structures.
This class would test any pure functions in the GraphQL adapter
that process the raw GraphQL responses into our domain models.
Since the actual GraphQL processing is done inline in the adapter
functions, these tests will verify our data model... | TestAgentDataProcessing |
python | PyCQA__bandit | tests/unit/formatters/test_custom.py | {
"start": 230,
"end": 2211
} | class ____(testtools.TestCase):
def setUp(self):
super().setUp()
conf = config.BanditConfig()
self.manager = manager.BanditManager(conf, "custom")
(tmp_fd, self.tmp_fname) = tempfile.mkstemp()
self.context = {
"filename": self.tmp_fname,
"lineno": 4,
... | CustomFormatterTests |
python | celery__celery | t/unit/events/test_events.py | {
"start": 6757,
"end": 12395
} | class ____:
def test_process(self):
message = {'type': 'world-war'}
got_event = [False]
def my_handler(event):
got_event[0] = True
connection = Mock()
connection.transport_cls = 'memory'
r = self.app.events.Receiver(
connection,
... | test_EventReceiver |
python | sphinx-doc__sphinx | tests/test_ext_napoleon/test_ext_napoleon.py | {
"start": 3888,
"end": 8261
} | class ____:
def assert_skip(
self,
what: str,
member: str,
obj: object,
expect_default_skip: bool,
config_name: str,
) -> None:
skip = True
app = mock.Mock()
app.config = Config()
setattr(app.config, config_name, True)
if ex... | TestSkipMember |
python | huggingface__transformers | tests/models/encodec/test_feature_extraction_encodec.py | {
"start": 1459,
"end": 3143
} | class ____:
def __init__(
self,
parent,
batch_size=7,
min_seq_length=400,
max_seq_length=2000,
feature_size=1,
padding_value=0.0,
sampling_rate=24000,
return_attention_mask=True,
):
self.parent = parent
self.batch_size = bat... | EnCodecFeatureExtractionTester |
python | fastai__fastai | fastai/vision/core.py | {
"start": 4953,
"end": 5106
} | class ____(PILBase):
"A RGB Pillow `Image` that can show itself and converts to `TensorImage`"
pass
# %% ../../nbs/07_vision.core.ipynb 39
| PILImage |
python | kamyu104__LeetCode-Solutions | Python/maximum-sum-score-of-array.py | {
"start": 517,
"end": 855
} | class ____(object):
def maximumSumScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
prefix = 0
result = float("-inf")
for x in nums:
prefix += x
result = max(result, prefix, total-prefix+x)
r... | Solution2 |
python | astropy__astropy | astropy/cosmology/_src/tests/funcs/test_comparison.py | {
"start": 536,
"end": 3003
} | class ____(ToFromTestMixinBase):
"""Tests for cosmology comparison functions.
This class inherits from
`astropy.cosmology._src.tests.io.base.ToFromTestMixinBase` because the cosmology
comparison functions all have a kwarg ``format`` that allow the arguments to
be converted to a |Cosmology| using th... | ComparisonFunctionTestBase |
python | PrefectHQ__prefect | src/prefect/tasks.py | {
"start": 2625,
"end": 3277
} | class ____(Protocol):
@classmethod
def is_callback_with_parameters(cls, callable: Callable[..., str]) -> TypeIs[Self]:
sig = inspect.signature(callable)
return "parameters" in sig.parameters
def __call__(self, parameters: dict[str, Any]) -> str: ...
StateHookCallable: TypeAlias = Callable... | TaskRunNameCallbackWithParameters |
python | facebookresearch__faiss | contrib/torch/clustering.py | {
"start": 1438,
"end": 1676
} | class ____(DatasetAssign):
def __init__(self, res, x):
DatasetAssign.__init__(self, x)
self.res = res
def perform_search(self, centroids):
return faiss.knn_gpu(self.res, self.x, centroids, 1)
| DatasetAssignGPU |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/layout.py | {
"start": 445,
"end": 3835
} | class ____(LayoutOperatorBase):
"""Operator for tensor.view() operation."""
def __init__(self):
"""Initialize ViewOperator."""
super().__init__("view")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.Tensor.view"
... | ViewOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/components/workspace_component/component.py | {
"start": 1869,
"end": 2657
} | class ____(pydantic.BaseModel):
by_id: Sequence[str] = pydantic.Field(
...,
description="A list of connector IDs to include in the collection.",
)
def resolve_connector_selector(
context: dg.ResolutionContext, model
) -> Optional[Callable[[FivetranConnector], bool]]:
if isinstance(mode... | FivetranConnectorSelectorById |
python | tensorflow__tensorflow | tensorflow/python/framework/composite_tensor_test.py | {
"start": 3143,
"end": 3232
} | class ____(CT):
_type_spec_class = CTSpec
@test_util.run_all_in_graph_and_eager_modes
| CT3 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/aiomysql.py | {
"start": 3549,
"end": 5614
} | class ____(AsyncAdapt_dbapi_module):
def __init__(self, aiomysql: ModuleType, pymysql: ModuleType):
super().__init__(aiomysql, dbapi_module=pymysql)
self.aiomysql = aiomysql
self.pymysql = pymysql
self.paramstyle = "format"
self._init_dbapi_attributes()
self.Cursor, s... | AsyncAdapt_aiomysql_dbapi |
python | mlflow__mlflow | mlflow/tracing/display/display_handler.py | {
"start": 2968,
"end": 6275
} | class ____:
_instance = None
disabled = False
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = IPythonTraceDisplayHandler()
return cls._instance
@classmethod
def disable(cls):
cls.disabled = True
@classmethod
def enable(... | IPythonTraceDisplayHandler |
python | huggingface__transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | {
"start": 1941,
"end": 5872
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify
them on the command line.
"""
model_name_or_path: str = field(
default="facebook/mask2fo... | Arguments |
python | ray-project__ray | python/ray/data/tests/test_auto_parallelism.py | {
"start": 301,
"end": 5880
} | class ____:
avail_cpus: int
target_max_block_size: int
data_size: int
expected_parallelism: int
MiB = 1024 * 1024
GiB = 1024 * MiB
TEST_CASES = [
TestCase(
avail_cpus=4,
target_max_block_size=DataContext.get_current().target_max_block_size,
data_size=1024,
expected... | TestCase |
python | huggingface__transformers | src/transformers/models/wavlm/modeling_wavlm.py | {
"start": 12200,
"end": 13866
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):
super().__init__()
self.attention = WavLMAttention(
embed_dim=config.hidden_size,
num_heads=config.num_attention_heads,
dropout=config.attenti... | WavLMEncoderLayer |
python | uqfoundation__dill | dill/session.py | {
"start": 10711,
"end": 23541
} | class ____:
"""lightweight stream wrapper that implements peek()"""
def __init__(self, stream):
self.stream = stream
def read(self, n):
return self.stream.read(n)
def readline(self):
return self.stream.readline()
def tell(self):
return self.stream.tell()
def close... | _PeekableReader |
python | getsentry__sentry | src/sentry/core/endpoints/organization_request_project_creation.py | {
"start": 552,
"end": 712
} | class ____(CamelSnakeSerializer):
target_user_email = serializers.EmailField(required=True)
@region_silo_endpoint
| OrganizationRequestProjectCreationSerializer |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_wrapper_gpu.py | {
"start": 36612,
"end": 36719
} | class ____:
"""Marker that we need to call .item() on the tensor"""
dtype: torch_dtype
| UnwrapUnspecArg |
python | walkccc__LeetCode | solutions/1708. Largest Subarray Length K/1708.py | {
"start": 0,
"end": 170
} | class ____:
def largestSubarray(self, nums: list[int], k: int) -> list[int]:
mx = max(nums[:len(nums) - k + 1])
i = nums.index(mx)
return nums[i:i + k]
| Solution |
python | pandas-dev__pandas | pandas/tests/groupby/test_numeric_only.py | {
"start": 297,
"end": 15298
} | class ____:
# make sure that we are passing thru kwargs to our agg functions
@pytest.fixture
def df(self):
# GH3668
# GH5724
df = DataFrame(
{
"group": [1, 1, 2],
"int": [1, 2, 3],
"float": [4.0, 5.0, 6.0],
... | TestNumericOnly |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_connections.py | {
"start": 1660,
"end": 4205
} | class ____:
def test_connection_get_from_db(self, client, session):
connection = Connection(
conn_id="test_conn",
conn_type="http",
description="description",
host="localhost",
login="root",
password="admin",
schema="http",
... | TestGetConnection |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_alloy_db.py | {
"start": 51474,
"end": 56208
} | class ____:
def setup_method(self):
self.operator = AlloyDBDeleteInstanceOperator(
task_id=TEST_TASK_ID,
instance_id=TEST_INSTANCE_ID,
cluster_id=TEST_CLUSTER_ID,
etag=TEST_ETAG,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
... | TestAlloyDBDeleteInstanceOperator |
python | apache__airflow | providers/google/tests/unit/google/ads/hooks/test_ads.py | {
"start": 2738,
"end": 5687
} | class ____:
@mock.patch("airflow.providers.google.ads.hooks.ads.GoogleAdsClient")
def test_get_customer_service(self, mock_client, mock_hook):
mock_hook._get_customer_service()
client = mock_client.load_from_dict
client.assert_called_once_with(mock_hook.google_ads_config)
client.... | TestGoogleAdsHook |
python | pytorch__pytorch | torch/_inductor/runtime/autotune_cache.py | {
"start": 2855,
"end": 3496
} | class ____(CacheArtifact):
@override
def populate_cache(self) -> None:
autotune_cache = _LocalAutotuneCacheBackend()
key = os.path.join(cache_dir(), self.key)
autotune_cache._put(key, self.content)
@override
@staticmethod
def type() -> str:
return "autotune"
@ov... | AutotuneCacheArtifact |
python | ansible__ansible | test/lib/ansible_test/_internal/ci/__init__.py | {
"start": 580,
"end": 1857
} | class ____:
"""Authentication helper."""
NAMESPACE: t.ClassVar = 'ci@core.ansible.com'
def __init__(self, key_file: pathlib.Path) -> None:
self.private_key_file = pathlib.Path(str(key_file).removesuffix('.pub'))
self.public_key_file = pathlib.Path(f'{self.private_key_file}.pub')
def s... | AuthHelper |
python | joke2k__faker | faker/providers/credit_card/pt_PT/__init__.py | {
"start": 122,
"end": 5682
} | class ____(CreditCardProvider):
"""Implementation of ``pt_PT`` locale credit card
For all methods that take ``card_type`` as an argument a random card type
will be used if the supplied value is ``None``. The list of valid card types
includes ``'visa'``, ``'mastercard'`` and ``'maestro'``.
Source: ... | Provider |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 15205,
"end": 16609
} | class ____(TestCase):
def test_init(self):
try:
foo = MultiValueField(model_attr="foo")
except:
self.fail()
self.assertRaises(SearchFieldError, MultiValueField, use_template=True)
def test_prepare(self):
mock = MockModel()
mock.sites = ["3", "4",... | MultiValueFieldTestCase |
python | pennersr__django-allauth | allauth/headless/base/views.py | {
"start": 418,
"end": 1005
} | class ____(RESTView):
client = None
@classonlymethod
def as_api_view(cls, **initkwargs):
view_func = cls.as_view(**initkwargs)
if initkwargs["client"] == Client.APP:
view_func = decorators.app_view(view_func)
else:
view_func = decorators.browser_view(view_fun... | APIView |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/conjecture/test_shrinker.py | {
"start": 18477,
"end": 25949
} | class ____(ShrinkerPass):
"""
A shrinker that really doesn't do anything at all. This is mostly a covering
test for the shrinker interface methods.
"""
def run_step(self):
return
def test_silly_shrinker_subclass():
assert BadShrinker.shrink(10, lambda _: True) == 10
numeric_nodes = ... | BadShrinker |
python | ray-project__ray | python/ray/data/tests/test_namespace_expressions.py | {
"start": 12185,
"end": 20181
} | class ____:
"""Tests for struct namespace operations."""
def test_struct_field(self, dataset_format):
"""Test struct.field() extracts field."""
# Arrow table with explicit struct types
arrow_table = pa.table(
{
"user": pa.array(
[
... | TestStructNamespace |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/sql_datasource.py | {
"start": 37000,
"end": 44910
} | class ____(_SQLAsset):
"""A class representing a table from a SQL database
Args:
table_name: The name of the database table to be added
schema_name: The name of the schema containing the database table to be added.
"""
# Instance fields
type: Literal["table"] = "table"
# TODO: ... | TableAsset |
python | eventlet__eventlet | eventlet/hubs/hub.py | {
"start": 3094,
"end": 17604
} | class ____:
""" Base hub class for easing the implementation of subclasses that are
specific to a particular underlying event architecture. """
SYSTEM_EXCEPTIONS = (KeyboardInterrupt, SystemExit)
READ = READ
WRITE = WRITE
def __init__(self, clock=None):
self.listeners = {READ: {}, WRI... | BaseHub |
python | pytorch__pytorch | torch/_dynamo/variables/distributed.py | {
"start": 3826,
"end": 4924
} | class ____(DistributedVariable):
"""
Tracks torch.distributed.GroupMember and torch.distributed.group, which are
instances of the metaclass _WorldMeta.
"""
@classmethod
def is_group_member_type(cls, value: object) -> bool:
if not cls.is_available():
return False
fro... | WorldMetaClassVariable |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 66343,
"end": 71739
} | class ____(PForTestCase):
def setUp(self):
self._enabled = control_flow_v2_toggles.control_flow_v2_enabled()
control_flow_v2_toggles.enable_control_flow_v2()
super(WhileV2Test, self).setUp()
def tearDown(self):
if not self._enabled:
control_flow_v2_toggles.disable_control_flow_v2()
super... | WhileV2Test |
python | walkccc__LeetCode | solutions/2911. Minimum Changes to Make K Semi-palindromes/2911.py | {
"start": 0,
"end": 1476
} | class ____:
def minimumChanges(self, s: str, k: int) -> int:
n = len(s)
# factors[i] := factors of i
factors = self._getFactors(n)
# cost[i][j] := changes to make s[i..j] a semi-palindrome
cost = self._getCost(s, n, factors)
# dp[i][j] := the minimum changes to split s[i:] into j valid parts
... | Solution |
python | allegroai__clearml | clearml/utilities/version.py | {
"start": 550,
"end": 1603
} | class ____(object):
def __init__(self, key: Any) -> None:
self._key = key
def __hash__(self) -> int:
return hash(self._key)
def __lt__(self, other: "_BaseVersion") -> bool:
return self._compare(other, lambda s, o: s < o)
def __le__(self, other: "_BaseVersion") -> bool:
... | _BaseVersion |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B019.py | {
"start": 2148,
"end": 2270
} | class ____(type):
@functools.lru_cache
def lru_cached_instance_method_on_metaclass(cls, x: int):
...
| Metaclass |
python | getsentry__sentry | src/sentry/buffer/redis.py | {
"start": 7887,
"end": 26018
} | class ____(Buffer):
key_expire = 60 * 60 # 1 hour
pending_key = "b:p"
def __init__(self, incr_batch_size: int = 2, **options: object):
self.is_redis_cluster, self.cluster, options = get_dynamic_cluster_from_options(
"SENTRY_BUFFER_OPTIONS", options
)
self.incr_batch_siz... | RedisBuffer |
python | modin-project__modin | modin/experimental/core/io/text/custom_text_dispatcher.py | {
"start": 1110,
"end": 4150
} | class ____(TextFileDispatcher):
"""Class handles utils for reading custom text files."""
@classmethod
def _read(cls, filepath_or_buffer, columns, custom_parser, **kwargs):
r"""
Read data from `filepath_or_buffer` according to the passed `read_custom_text` `kwargs` parameters.
Param... | ExperimentalCustomTextDispatcher |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/finetuning.py | {
"start": 13988,
"end": 21076
} | class ____(BaseFinetuning):
r"""Finetune a backbone model based on a learning rate user-defined scheduling.
When the backbone learning rate reaches the current model learning rate
and ``should_align`` is set to True, it will align with it for the rest of the training.
Args:
unfreeze_backbone_a... | BackboneFinetuning |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_auth_tokens.py | {
"start": 4062,
"end": 7623
} | class ____(APITestCase):
endpoint = "sentry-api-0-org-auth-tokens"
method = "POST"
def test_simple(self) -> None:
payload = {"name": "test token"}
self.login_as(self.user)
response = self.get_success_response(
self.organization.slug, status_code=status.HTTP_201_CREATED,... | OrganizationAuthTokenCreateTest |
python | google__pytype | pytype/rewrite/stack.py | {
"start": 210,
"end": 1885
} | class ____:
"""Data stack."""
def __init__(self):
self._stack: list[_Var] = []
def push(self, var: _Var) -> None:
self._stack.append(var)
def pop(self) -> _Var:
return self._stack.pop()
def popn(self, n: int) -> Sequence[_Var]:
if not n:
return ()
if len(self._stack) < n:
s... | DataStack |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/pythonic_config/resource.py | {
"start": 40570,
"end": 42778
} | class ____(ResourceRequirement):
class_name: str
attr_name: str
partial_resource: CoercibleToResource
def is_satisfied(self, resource_defs: Mapping[str, "ResourceDefinition"]):
from dagster._config.pythonic_config.resource import coerce_to_resource
return coerce_to_resource(self.partia... | PartialResourceDependencyRequirement |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 236118,
"end": 238652
} | class ____(Operation):
def __init__(self, mode="valid", *, name=None):
super().__init__(name=name)
self.mode = mode
def call(self, x1, x2):
return backend.numpy.correlate(x1, x2, mode=self.mode)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
... | Correlate |
python | python-openxml__python-docx | tests/test_comments.py | {
"start": 583,
"end": 6562
} | class ____:
"""Unit-test suite for `docx.comments.Comments` objects."""
@pytest.mark.parametrize(
("cxml", "count"),
[
("w:comments", 0),
("w:comments/w:comment", 1),
("w:comments/(w:comment,w:comment,w:comment)", 3),
],
)
def it_knows_how_man... | DescribeComments |
python | Pylons__pyramid | src/pyramid/threadlocal.py | {
"start": 2056,
"end": 2466
} | class ____:
def __init__(self, request):
self.request = request
def begin(self):
request = self.request
registry = request.registry
manager.push({'registry': registry, 'request': request})
return request
def end(self):
manager.pop()
def __enter__(self):... | RequestContext |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 19061,
"end": 19539
} | class ____(OrganizationRoleNameMixin, wtforms.Form):
def __init__(self, *args, orgtype, **kwargs):
super().__init__(*args, **kwargs)
if orgtype != OrganizationType.Company:
# Remove "Billing Manager" choice if organization is not a "Company"
self.role_name.choices = [
... | ChangeOrganizationRoleForm |
python | wandb__wandb | wandb/vendor/pygments/lexers/haskell.py | {
"start": 23443,
"end": 24158
} | class ____(LiterateLexer):
"""
For Literate Cryptol (Bird-style or LaTeX) source.
Additional options accepted:
`litstyle`
If given, must be ``"bird"`` or ``"latex"``. If not given, the style
is autodetected: if the first non-whitespace character in the source
is a backslash or... | LiterateCryptolLexer |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 76901,
"end": 76997
} | class ____(blas_ilp64_opt_info):
symbol_prefix = ''
symbol_suffix = '64_'
| blas64__opt_info |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_evaluation.py | {
"start": 4722,
"end": 4918
} | class ____(NamedTuple):
class_name: str
description: str
decision_type: AutoMaterializeDecisionType
@whitelist_for_serdes(serializer=BackcompatNullSerializer)
| AutoMaterializeRuleSnapshot |
python | getsentry__sentry | src/sentry/analytics/events/first_replay_sent.py | {
"start": 74,
"end": 270
} | class ____(analytics.Event):
organization_id: int
project_id: int
platform: str | None = None
user_id: int | None = None
analytics.register(FirstReplaySentEvent)
| FirstReplaySentEvent |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_plugin_deprecation_info.py | {
"start": 191,
"end": 3348
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-plugin-deprecation-info"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.plugin_name = "test-plugin"
self.organization = self.create_organization(owner=self.user)
self.project_wit... | OrganizationPluginDeprecationInfoEndpointTest |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/plugins/test_utils.py | {
"start": 2578,
"end": 26543
} | class ____(dict):
def __str__(self):
castable = []
for key, val in self.items():
try:
str(key), str(val)
castable.append((key, val))
except (TypeError, NotImplementedError):
continue
return str(dict(castable))
@patch("... | SafeStrDict |
python | Netflix__metaflow | test/core/tests/foreach_in_switch.py | {
"start": 82,
"end": 1146
} | class ____(MetaflowTest):
PRIORITY = 2
ONLY_GRAPHS = ["foreach_in_switch"]
@steps(0, ["start-foreach-in-switch"], required=True)
def step_start(self):
self.mode = "process"
@steps(0, ["process-items"], required=True)
def step_process(self):
self.items_to_process = ["item_1", "i... | ForeachInSwitchTest |
python | realpython__materials | python-type-checking/game_003.py | {
"start": 1139,
"end": 2273
} | class ____:
def __init__(self, *names):
"""Set up the deck and deal cards to 4 players"""
deck = Deck.create(shuffle=True)
self.names = (list(names) + "P1 P2 P3 P4".split())[:4]
self.hands = {
n: Player(n, h)
for n, h in zip(self.names, deck.deal(4), strict=Fa... | Game |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.