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/kernel_tests/data_structures/padding_fifo_queue_test.py | {
"start": 1356,
"end": 60468
} | class ____(test.TestCase):
def testConstructor(self):
with ops.Graph().as_default():
q = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((None,),), name="Q")
self.assertTrue(isinstance(q.queue_ref, tensor.Tensor))
self.assertProtoEquals("""
name:'Q' op:'PaddingFIFOQueueV2'
... | PaddingFIFOQueueTest |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 91647,
"end": 99442
} | class ____(MultiOutputMixin, RegressorMixin, _BaseRidgeCV):
"""Ridge regression with built-in cross-validation.
See glossary entry for :term:`cross-validation estimator`.
By default, it performs efficient Leave-One-Out Cross-Validation.
Read more in the :ref:`User Guide <ridge_regression>`.
Para... | RidgeCV |
python | coleifer__peewee | tests/queries.py | {
"start": 5574,
"end": 7472
} | class ____(BaseTestCase):
def test_clone_tables(self):
self._do_test_clone(User, Tweet)
def test_clone_models(self):
class User(TestModel):
username = TextField()
class Meta:
table_name = 'users'
class Tweet(TestModel):
user = ForeignK... | TestQueryCloning |
python | ray-project__ray | python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py | {
"start": 563,
"end": 14600
} | class ____(BaseCloudFileSystem):
"""PyArrow-based implementation of cloud filesystem operations.
This class provides a unified interface for cloud storage operations using
PyArrow's filesystem abstraction. It supports S3, GCS, and Azure storage
providers.
"""
@staticmethod
def get_fs_and_p... | PyArrowFileSystem |
python | lazyprogrammer__machine_learning_examples | unsupervised_class2/rbm_tf.py | {
"start": 467,
"end": 4912
} | class ____(object):
def __init__(self, D, M, an_id):
self.D = D
self.M = M
self.id = an_id
self.build(D, M)
def set_session(self, session):
self.session = session
def build(self, D, M):
# params
self.W = tf.Variable(tf.random.normal(shape=(D, M)) * n... | RBM |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_figure_properties.py | {
"start": 102,
"end": 9891
} | class ____(TestCase):
def setUp(self):
# Disable default template
pio.templates.default = None
# Construct initial scatter object
self.figure = go.Figure(
data=[go.Scatter(y=[3, 2, 1], marker={"color": "green"})],
layout={"xaxis": {"range": [-1, 4]}},
... | TestFigureProperties |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 1799,
"end": 3245
} | class ____:
def test_get_locale(self, mocker):
mock_locale = mocker.Mock()
mock_locale_cls = mocker.Mock()
mock_locale_cls.return_value = mock_locale
with pytest.raises(ValueError):
arrow.locales.get_locale("locale-name")
cls_dict = arrow.locales._locale_map
... | TestModule |
python | numba__numba | numba/core/typing/npydecl.py | {
"start": 25027,
"end": 25669
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
# Either ndindex(shape) or ndindex(*shape)
if len(args) == 1 and isinstance(args[0], types.BaseTuple):
tup = args[0]
if tup.count > 0 and not isinstance(tup, types.UniTuple):
... | NdIndex |
python | PyCQA__pylint | tests/functional/e/enum_self_defined_member_6805.py | {
"start": 582,
"end": 898
} | class ____(IntEnum):
MONDAY = (1, "Mon")
TUESDAY = (2, "Tue")
WEDNESDAY = (3, "Wed")
THURSDAY = (4, "Thu")
FRIDAY = (5, "Fri")
SATURDAY = (6, "Sat")
SUNDAY = (7, "Sun")
def __new__(cls, value, _abbr=None):
return int.__new__(cls, value)
print(Day.FRIDAY.foo) # [no-member]
| Day |
python | getsentry__sentry | src/sentry/conf/types/sdk_config.py | {
"start": 1255,
"end": 1402
} | class ____(SdkConfig):
# these get popped before sending along to the sdk
dsn: NotRequired[str]
relay_dsn: NotRequired[str]
| ServerSdkConfig |
python | pytorch__pytorch | test/distributed/tensor/test_op_strategy.py | {
"start": 19402,
"end": 23886
} | class ____(DTensorTestBase):
@with_comms
@patch(
"torch.distributed.tensor._sharding_prop.ShardingPropagator._select_strategy"
)
def test_replicate_strategy_placement(self, mock_select_strategy):
costs_from__select_strategy = []
def mock_select_func(strategy, op_schema=None):
... | DistTensorReplicateStrategyRegistrationTest |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 803,
"end": 925
} | class ____(Package):
version("2.1")
version("2.0")
depends_on("x4@4.1")
""",
)
_pkgx3 = (
"x3",
"""\
| X2 |
python | getsentry__sentry | tests/sentry/issue_detection/test_file_io_on_main_thread_detector.py | {
"start": 1214,
"end": 7034
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self._settings = get_detection_settings()
def create_proguard(self, uuid: str) -> None:
with ZipFile(BytesIO(), "w") as f:
f.writestr(f"proguard/{uuid}.txt", PROGUARD_SOURCE)
create_files_from_dif_zip... | FileIOMainThreadDetectorTest |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 155473,
"end": 156024
} | class ____(nn.Module):
"""Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
This rescales diagonally the residual outputs close to 0, with a learnt scale.
"""
def __init__(self, config):
super().__init__()
channels = config.hidden_size
initial_sca... | Qwen3OmniMoeCode2WavLayerScale |
python | doocs__leetcode | solution/3300-3399/3356.Zero Array Transformation II/Solution.py | {
"start": 0,
"end": 546
} | class ____:
def minZeroArray(self, nums: List[int], queries: List[List[int]]) -> int:
def check(k: int) -> bool:
d = [0] * (len(nums) + 1)
for l, r, val in queries[:k]:
d[l] += val
d[r + 1] -= val
s = 0
for x, y in zip(nums, d):... | Solution |
python | gevent__gevent | src/greentest/3.10/test_wsgiref.py | {
"start": 19417,
"end": 19941
} | class ____(BaseCGIHandler):
"""Simple handler subclass for testing BaseHandler"""
# BaseHandler records the OS environment at import time, but envvars
# might have been changed later by other tests, which trips up
# HandlerTests.testEnviron().
os_environ = dict(os.environ.items())
def __init__... | ErrorHandler |
python | lxml__lxml | src/lxml/tests/common_imports.py | {
"start": 5684,
"end": 6731
} | class ____:
def __init__(self, path):
self.path = path
def __fspath__(self):
return self.path
def fileInTestDir(name):
_testdir = os.path.dirname(__file__)
return os.path.join(_testdir, name)
def path2url(path):
return urlparse.urljoin(
'file://', pathname2url(path))
de... | SimpleFSPath |
python | django__django | django/contrib/gis/db/backends/base/features.py | {
"start": 101,
"end": 4106
} | class ____:
gis_enabled = True
# Does the database contain a SpatialRefSys model to store SRID
# information?
has_spatialrefsys_table = True
# Does the backend support the django.contrib.gis.utils.add_srs_entry()
# utility?
supports_add_srs_entry = True
# Does the backend introspect Ge... | BaseSpatialFeatures |
python | sympy__sympy | sympy/functions/elementary/hyperbolic.py | {
"start": 47976,
"end": 53220
} | class ____(InverseHyperbolicFunction):
"""
``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
The inverse hyperbolic tangent function.
Examples
========
>>> from sympy import atanh
>>> from sympy.abc import x
>>> atanh(x).diff(x)
1/(1 - x**2)
See Also
========
... | atanh |
python | streamlit__streamlit | lib/streamlit/elements/widgets/chat.py | {
"start": 14129,
"end": 38692
} | class ____:
@gather_metrics("chat_message")
def chat_message(
self,
name: Literal["user", "assistant", "ai", "human"] | str,
*,
avatar: Literal["user", "assistant"] | str | AtomicImage | None = None,
width: Width = "stretch",
) -> DeltaGenerator:
"""Insert a c... | ChatMixin |
python | pytorch__pytorch | torch/distributed/_composable/replicate_with_fsdp.py | {
"start": 2587,
"end": 10193
} | class ____(FSDPState):
"""
Replicate state functionality is adapted from FSDP state.
In the future, could experiment with inheriting from it instead.
"""
def __init__(self) -> None:
super().__init__()
self._state_ctx = _ReplicateStateContext() # type: ignore[assignment]
# Defi... | _ReplicateState |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/rule_based_profiler/data_assistant/data_profiler_structured_data_assistant.py | {
"start": 1481,
"end": 19608
} | class ____(DataAssistant):
"""
ProfileReportBasedColumnsDataAssistant provides dataset exploration and validation for columns of tabular data.
"""
__alias__: str = "data_profiler"
def __init__(
self,
name: str,
validator: Validator,
) -> None:
super().__init__(
... | DataProfilerStructuredDataAssistant |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate.py | {
"start": 28491,
"end": 31046
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook")
def test_minimal_green_path(self, mock_hook):
GLOSSARY_CREATION_RESULT = {
"name": f"projects/{PROJECT_ID}/locations/{LOCATION}/glossaries/{GLOSSARY_ID}",
"display_name": f"{GLOSSARY_ID}",... | TestTranslateGlossaryCreate |
python | getsentry__sentry | src/sentry/explore/models.py | {
"start": 1199,
"end": 1606
} | class ____(Model):
__relocation_scope__ = RelocationScope.Organization
project = FlexibleForeignKey("sentry.Project")
explore_saved_query = FlexibleForeignKey("explore.ExploreSavedQuery")
class Meta:
app_label = "explore"
db_table = "explore_exploresavedqueryproject"
unique_tog... | ExploreSavedQueryProject |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/utils/backward_compatibility.py | {
"start": 5321,
"end": 11894
} | class ____(BaseDiffChecker):
"""A class to perform backward compatibility checks on a connector specification diff"""
context = BackwardIncompatibilityContext.SPEC
def compute_diffs(self):
self.connection_specification_diff = DeepDiff(
self._previous["connectionSpecification"],
... | SpecDiffChecker |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 2866,
"end": 3057
} | class ____:
def test_missing(self):
data, meta = loadarff(missing)
for i in ['yop', 'yap']:
assert_array_almost_equal(data[i], expect_missing[i])
| TestMissingData |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/python_set.py | {
"start": 428,
"end": 1080
} | class ____(DagsterTypeLoader):
def __init__(self, item_dagster_type):
self._item_dagster_type = check.inst_param(
item_dagster_type, "item_dagster_type", DagsterType
)
@property
def schema_type(self):
return Array(self._item_dagster_type.loader.schema_type)
def cons... | TypedSetLoader |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call2.py | {
"start": 1504,
"end": 2958
} | class ____(str): ...
kwargs2: dict[MyStr, MyStr] = {}
func8(z=False, **kwargs2)
def func9(
x: int,
y: str,
*,
a: str = ...,
b: str,
c: str,
) -> None: ...
kwargs3: dict[str, str] = {}
func9(0, "", **kwargs3)
args4: list[str] = ["hi"]
func9(0, *args4, **kwargs3)
# This should generate an ... | MyStr |
python | Textualize__textual | src/textual/getters.py | {
"start": 547,
"end": 1801
} | class ____(Generic[AppType]):
"""Create a property to return the active app.
All widgets have a default `app` property which returns an App instance.
Type checkers will complain if you try to access attributes defined on your App class, which aren't
present in the base class. To keep the type checker h... | app |
python | streamlit__streamlit | lib/tests/streamlit/net_util_test.py | {
"start": 741,
"end": 2430
} | class ____(unittest.TestCase):
def setUp(self):
net_util._external_ip = None
def test_get_external_ip(self):
# Test success
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, text="1.2.3.4")
assert net_util.get_external_ip() == "1.2.3.4"
net_u... | UtilTest |
python | plotly__plotly.py | _plotly_utils/exceptions.py | {
"start": 2111,
"end": 2640
} | class ____(PlotlyGraphObjectError):
def __init__(self, obj, path, notes=()):
"""See PlotlyGraphObjectError.__init__ for param docs."""
format_dict = {"index": path[-1], "object_name": obj._name}
message = "Invalid entry found in '{object_name}' at index, '{index}'".format(
**form... | PlotlyListEntryError |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/test_base.py | {
"start": 15997,
"end": 16460
} | class ____:
"""Temporary directory for unit testing."""
def __init__(self):
temp_dir = tempfile.mkdtemp(dir=googletest.GetTempDir())
self._path = os.path.join(
tempfile.mkdtemp(dir=temp_dir), "tf_data_snapshot")
@property
def full_path(self) -> str:
return self._path
def __fspath__(self... | TempDir |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/run_status_sensor_definition.py | {
"start": 3595,
"end": 5129
} | class ____(
NamedTuple(
"_RunStatusSensorCursor",
[
("record_id", int),
# deprecated arg, used as a record cursor for the run-sharded sqlite implementation to
# filter records based on the update timestamp of the run. When populated, the record
# id i... | RunStatusSensorCursor |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 40353,
"end": 40547
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("BLANK", "COMMIT_MESSAGES", "PR_BODY")
| SquashMergeCommitMessage |
python | django__django | django/db/models/expressions.py | {
"start": 42372,
"end": 43588
} | class ____(Expression):
allowed_default = True
def __init__(self, sql, params, output_field=None):
if output_field is None:
output_field = fields.Field()
self.sql, self.params = sql, params
super().__init__(output_field=output_field)
def __repr__(self):
return "... | RawSQL |
python | numba__numba | numba/core/typing/templates.py | {
"start": 48639,
"end": 49513
} | class ____(object):
"""
An incremental loader for a registry. Each new call to
new_registrations() will iterate over the not yet seen registrations.
The reason for this object is multiple:
- there can be several contexts
- each context wants to install all registrations
- registrations can... | BaseRegistryLoader |
python | dask__distributed | distributed/http/scheduler/info.py | {
"start": 1343,
"end": 1953
} | class ____(RequestHandler):
@log_errors
def get(self, worker):
worker = escape.url_unescape(worker)
if worker not in self.server.workers:
self.send_error(404)
return
self.render(
"worker.html",
title="Worker: " + worker,
schedu... | Worker |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 66445,
"end": 67028
} | class ____(BaseTestCase):
def test_jira_export(self):
expected = """||first_name||last_name||gpa||
|John|Adams|90|
|George|Washington|67|
|Thomas|Jefferson|50|"""
self.assertEqual(expected, self.founders.jira)
def test_jira_export_no_headers(self):
self.assertEqual('|a|b|c|', tablib.Dat... | JiraTests |
python | pypa__warehouse | tests/common/db/oidc.py | {
"start": 406,
"end": 802
} | class ____(WarehouseFactory):
class Meta:
model = GitHubPublisher
id = factory.Faker("uuid4", cast_to=None)
repository_name = factory.Faker("pystr", max_chars=12)
repository_owner = factory.Faker("pystr", max_chars=12)
repository_owner_id = factory.Faker("pystr", max_chars=12)
workflow_... | GitHubPublisherFactory |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 7992,
"end": 9142
} | class ____(LlavaNextModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
... | LlavaNextVideoModelOutputWithPast |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 14637,
"end": 17028
} | class ____(nn.Module):
def __init__(self, config: ViTMAEConfig):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size {config.hidden_size} is not a multiple of the number ... | ViTMAESelfAttention |
python | getsentry__sentry | src/sentry/api/bases/organizationmember.py | {
"start": 2820,
"end": 4642
} | class ____(OrganizationEndpoint):
def convert_args(
self,
request: Request,
organization_id_or_slug: str | int | None = None,
member_id: str = "me",
*args: Any,
**kwargs: Any,
) -> tuple[tuple[Any, ...], dict[str, Any]]:
args, kwargs = super().convert_args... | OrganizationMemberEndpoint |
python | django-guardian__django-guardian | guardian/testapp/migrations/0001_initial.py | {
"start": 291,
"end": 10120
} | class ____(migrations.Migration):
initial = True
dependencies = [
("auth", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="CustomUser",
fields=[
("password", models.CharField(max_length=128, verbose_name="password")),
... | Migration |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 11019,
"end": 12021
} | class ____(_BaseDataclass):
"""
A tool parameter definition.
Args:
properties (Dict[str, :py:class:`ParamProperty`]): A mapping of parameter names to
their definitions.
type (str): The type of the parameter. Currently only "object" is supported.
required (List[str]): A l... | ToolParamsSchema |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 1061,
"end": 1148
} | class ____(BaseModel):
explanation: str
span_id: str
span_op: str
| SpanInsight |
python | pennersr__django-allauth | allauth/socialaccount/providers/instagram/provider.py | {
"start": 225,
"end": 417
} | class ____(ProviderAccount):
PROFILE_URL = "https://instagram.com/"
def get_profile_url(self):
return self.PROFILE_URL + self.account.extra_data.get("username")
| InstagramAccount |
python | automl__auto-sklearn | autosklearn/pipeline/components/feature_preprocessing/kitchen_sinks.py | {
"start": 462,
"end": 2777
} | class ____(AutoSklearnPreprocessingAlgorithm):
def __init__(
self,
gamma: float,
n_components: int,
random_state: Optional[Union[int, RandomState]] = None,
) -> None:
"""
Parameters
----------
gamma: float
Parameter of the rbf kernel to... | RandomKitchenSinks |
python | huggingface__transformers | tests/models/audioflamingo3/test_modeling_audioflamingo3.py | {
"start": 1280,
"end": 5355
} | class ____:
"""
Builds a tiny AudioFlamingo3 config and synthetic inputs that respect AF3's
post-pool token accounting: num <sound> tokens per sample == post-pool frame count.
"""
def __init__(
self,
parent,
audio_token_id=0,
seq_length=25,
feat_seq_length=60... | AudioFlamingo3ModelTester |
python | streamlit__streamlit | lib/tests/streamlit/elements/checkbox_test.py | {
"start": 1191,
"end": 13701
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall checkbox protos."""
def test_just_label(self):
"""Test that it can be called with no value."""
st.checkbox("the label")
c = self.get_delta_from_queue().new_element.checkbox
assert c.label == "the label"
ass... | CheckboxTest |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 11698,
"end": 11802
} | class ____(OpcodeWithArg): # Arg: Comparison operator
_FLAGS = HAS_ARGUMENT
__slots__ = ()
| COMPARE_OP |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 9114,
"end": 9180
} | class ____(VerifyPhoneForm, inputs.Input):
pass
| VerifyPhoneInput |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/workspace.py | {
"start": 1363,
"end": 1677
} | class ____:
"""Slimmer version of WorkspaceLocationEntry, containing the minimum set of information required
to know whether the workspace needs reloading.
"""
location_name: str
load_status: CodeLocationLoadStatus
update_timestamp: float
version_key: str
@record
| CodeLocationStatusEntry |
python | getsentry__sentry | src/sentry/types/grouphash_metadata.py | {
"start": 2427,
"end": 2946
} | class ____(TypedDict):
"""
Data gathered when an event is grouped based on a stacktrace found in an exception, a thread, or
diretly in the event
"""
# Either "in-app" or "system"
stacktrace_type: str
# Where in the event data the stacktrace was found - either "exception", "thread", or
#... | StacktraceHashingMetadata |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py | {
"start": 16511,
"end": 17158
} | class ____(object):
__slots__ = 'type', 'default_value', 'description', 'out_name'
def __init__(self, type, default_value=None, description=None, out_name=None):
self.type = type
self.default_value = default_value
self.description = description
self.out_name = out_name
def ... | GraphQLInputObjectField |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integration_details.py | {
"start": 865,
"end": 1906
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-integration-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.integration = self.create_provider_integration(
provider="gitlab", name="Gitlab", external_id="gitlab:1"
)... | OrganizationIntegrationDetailsTest |
python | pypa__hatch | src/hatch/cli/test/core.py | {
"start": 207,
"end": 1936
} | class ____:
def __init__(self, project_root: Path, data_dir: Path) -> None:
self.project_root = project_root
self.data_dir = data_dir
@cached_property
def user_config_path(self) -> Path:
# https://coverage.readthedocs.io/en/7.4.4/config.html#sample-file
return (
... | PatchedCoverageConfig |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 16535,
"end": 16579
} | class ____(Glm4RMSNorm):
pass
| Glm4vRMSNorm |
python | microsoft__pyright | build/generateUnicodeTables.py | {
"start": 257,
"end": 765
} | class ____:
def __init__(self, code: int, category: str, *, end: int | None = None):
self.code = code
self.category = category
self.hasSurrogate = code > 0xFFFF
if self.hasSurrogate:
unicodeChar = chr(code)
utf16 = unicodeChar.encode("utf-16")
raw... | Character |
python | huggingface__transformers | tests/pipelines/test_pipelines_fill_mask.py | {
"start": 1041,
"end": 17941
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_MASKED_LM_MAPPING
def tearDown(self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
if is_torch_available():
backend_empty_cache(torch_device)
@require_torch... | FillMaskPipelineTests |
python | ethereum__web3.py | web3/middleware/filter.py | {
"start": 17809,
"end": 22031
} | class ____(Web3Middleware):
def __init__(self, w3: Union["Web3", "AsyncWeb3[Any]"]):
self.filters: dict[str, SyncFilter] = {}
self.async_filters: dict[str, AsyncFilter] = {}
self.filter_id_counter = itertools.count()
super().__init__(w3)
def wrap_make_request(self, make_request:... | LocalFilterMiddleware |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py | {
"start": 93066,
"end": 94762
} | class ____(Qwen2_5_VLAttention):
def __init__(self, config: Qwen2_5OmniConfig, layer_idx: Optional[int] = None):
nn.Module.__init__(self)
self.config = config
self.layer_idx = layer_idx
if layer_idx is None:
logger.warning_once(
f"Instantiating {self.__cla... | Qwen2_5OmniAttention |
python | dask__distributed | distributed/scheduler.py | {
"start": 30820,
"end": 32492
} | class ____:
"""Abstract collection tracking all tasks
See Also
--------
TaskGroup
TaskPrefix
"""
#: The name of a collection of tasks.
name: str
#: The total number of bytes that tasks belonging to this collection have produced
nbytes_total: int
#: The number of tasks bel... | TaskCollection |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 19936,
"end": 21954
} | class ____(collections.abc.Mapping, collections.abc.Hashable):
"""
An immutable mapping.
>>> a = FrozenDict(a=1, b=2)
>>> b = FrozenDict(a=1, b=2)
>>> a == b
True
>>> a == dict(a=1, b=2)
True
>>> dict(a=1, b=2) == a
True
>>> 'a' in a
True
>>> type(hash(a)) is type(0... | FrozenDict |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy_test.py | {
"start": 2083,
"end": 19231
} | class ____(tf_test.TestCase, parameterized.TestCase):
def setUp(self):
super().setUp()
self.num_client = flags.FLAGS.num_clients
self.num_local_devices = flags.FLAGS.num_local_devices
tf_config = json.loads(os.environ['TF_CONFIG'])
self.client_id = int(tf_config['task']['index'])
def test_str... | MultiWorkerMirroredStrategyTest |
python | google__jax | tests/lax_vmap_test.py | {
"start": 1171,
"end": 33419
} | class ____(jtu.JaxTestCase):
def _CheckBatching(self, op, bdim_size, bdims, shapes, dtypes, rng,
rtol=None, atol=None, multiple_results=False):
batched_shapes = map(partial(lax_test_util.add_bdim, bdim_size), bdims, shapes)
args = [rng(shape, dtype) for shape, dtype in zip(batched_shapes... | LaxVmapTest |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 17471,
"end": 21669
} | class ____:
async def test_retries(
self,
session,
initialize_orchestration,
monkeypatch,
frozen_time,
):
failed_task_runs = [
mock.Mock(id="task_run_001"),
mock.Mock(id="task_run_002"),
]
read_task_runs = AsyncMock(side_eff... | TestFlowRetryingRule |
python | pypa__hatch | src/hatch/cli/application.py | {
"start": 559,
"end": 7699
} | class ____(Terminal):
def __init__(self, exit_func, *args, **kwargs):
super().__init__(*args, **kwargs)
self.platform = Platform(self.output)
self.__exit_func = exit_func
self.config_file = ConfigFile()
self.quiet = self.verbosity < 0
self.verbose = self.verbosity > ... | Application |
python | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 56184,
"end": 62835
} | class ____(SEWDPreTrainedModel):
def __init__(self, config, target_lang: Optional[str] = None):
r"""
target_lang (`str`, *optional*):
Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
adapter.<lang>.bin. Only relevant when ... | SEWDForCTC |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks_test.py | {
"start": 53425,
"end": 55602
} | class ____(test.TestCase):
def test_final_ops_is_scalar_tensor(self):
with ops.Graph().as_default():
expected_value = 4
final_ops = constant_op.constant(expected_value)
hook = basic_session_run_hooks.FinalOpsHook(final_ops)
hook.begin()
with session_lib.Session() as session:
... | FinalOpsHookTest |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 2139,
"end": 2288
} | class ____(GQLInput):
name: str = Field(max_length=128, pattern="^[-\\w]+([ ]*[-.\\w]+)*$")
description: Optional[str] = None
| ArtifactTypeInput |
python | mlflow__mlflow | mlflow/entities/run_tag.py | {
"start": 119,
"end": 890
} | class ____(_MlflowObject):
"""Tag object associated with a run."""
def __init__(self, key, value):
self._key = key
self._value = value
def __eq__(self, other):
if type(other) is type(self):
# TODO deep equality here?
return self.__dict__ == other.__dict__
... | RunTag |
python | Textualize__textual | src/textual/demo/game.py | {
"start": 17904,
"end": 19438
} | class ____(PageScreen):
"""The screen containing the game."""
DEFAULT_CSS = """
GameScreen{
#container {
align: center middle;
layers: instructions game;
}
}
"""
BINDINGS = [("n", "new_game", "New Game")]
def compose(self) -> ComposeResu... | GameScreen |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v2.4.0.a.py | {
"start": 1672,
"end": 2070
} | class ____(BaseModel):
__tablename__ = "trial_values"
__table_args__: Any = (UniqueConstraint("trial_id", "objective"),)
trial_value_id = Column(Integer, primary_key=True)
trial_id = Column(Integer, ForeignKey("trials.trial_id"), nullable=False)
objective = Column(Integer, nullable=False)
value ... | TrialValueModel |
python | allegroai__clearml | clearml/binding/click_bind.py | {
"start": 440,
"end": 6930
} | class ____:
_args = {}
_args_desc = {}
_args_type = {}
_num_commands = 0
_command_type = "click.Command"
_section_name = "Args"
_current_task = None
__remote_task_params = None
__remote_task_params_dict = {}
__patched = False
@classmethod
def patch(cls, task: Optional["T... | PatchClick |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/widgets/status.py | {
"start": 850,
"end": 5959
} | class ____(ShellConnectStatusBarWidget):
"""Status bar widget for current Matplotlib backend."""
ID = "matplotlib_status"
CONF_SECTION = 'ipython_console'
INTERACT_ON_CLICK = True
def __init__(self, parent):
super().__init__(parent)
self._gui = None
self._interactive_gui =... | MatplotlibStatus |
python | python-attrs__attrs | tests/test_validators.py | {
"start": 6255,
"end": 7386
} | class ____:
def test_in_all(self):
"""
Verify that this validator is in ``__all__``.
"""
assert and_.__name__ in validator_module.__all__
def test_success(self):
"""
Succeeds if all wrapped validators succeed.
"""
v = and_(instance_of(int), always... | TestAnd |
python | RaRe-Technologies__gensim | gensim/test/test_word2vec.py | {
"start": 53068,
"end": 54564
} | class ____(unittest.TestCase):
@unittest.skipIf(POT_EXT is False, "POT not installed")
def test_nonzero(self):
'''Test basic functionality with a test sentence.'''
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
sentence1 = ['human', 'interface', 'computer']
... | TestWMD |
python | dask__distributed | distributed/shuffle/_rechunk.py | {
"start": 31451,
"end": 37675
} | class ____(ShuffleRun[NDIndex, "np.ndarray"]):
"""State for a single active rechunk execution
This object is responsible for splitting, sending, receiving and combining
data shards.
It is entirely agnostic to the distributed system and can perform a rechunk
with other run instances using `rpc``.
... | ArrayRechunkRun |
python | weaviate__weaviate-python-client | weaviate/connect/event_loop.py | {
"start": 315,
"end": 460
} | class ____(Future, Generic[T]):
def result(self, timeout: Optional[float] = None) -> T:
return cast(T, super().result(timeout))
| _Future |
python | pallets__click | src/click/types.py | {
"start": 5750,
"end": 6436
} | class ____(ParamType):
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
self.name: str = func.__name__
self.func = func
def to_info_dict(self) -> dict[str, t.Any]:
info_dict = super().to_info_dict()
info_dict["func"] = self.func
return info_dict
def con... | FuncParamType |
python | wireservice__csvkit | csvkit/utilities/csvstack.py | {
"start": 418,
"end": 5598
} | class ____(CSVKitUtility):
description = 'Stack up the rows from multiple CSV files, optionally adding a grouping value.'
# Override 'f' because the utility accepts multiple files.
override_flags = ['f', 'L', 'I']
def add_arguments(self):
self.argparser.add_argument(
metavar='FILE',... | CSVStack |
python | django__django | django/contrib/gis/db/backends/utils.py | {
"start": 85,
"end": 789
} | class ____:
"""
Class encapsulating the behavior specific to a GIS operation (used by
lookups).
"""
sql_template = None
def __init__(self, op=None, func=None):
self.op = op
self.func = func
@property
def default_template(self):
if self.func:
return ... | SpatialOperator |
python | doocs__leetcode | lcof2/剑指 Offer II 091. 粉刷房子/Solution.py | {
"start": 0,
"end": 298
} | class ____:
def minCost(self, costs: List[List[int]]) -> int:
r, g, b = 0, 0, 0
for cost in costs:
_r, _g, _b = r, g, b
r = min(_g, _b) + cost[0]
g = min(_r, _b) + cost[1]
b = min(_r, _g) + cost[2]
return min(r, g, b)
| Solution |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-paieas/llama_index/llms/paieas/base.py | {
"start": 163,
"end": 1047
} | class ____(OpenAILike):
"""
PaiEas is a thin wrapper around the OpenAILike model that makes it compatible with
Aliyun PAI-EAS(Elastic Algorithm Service) that provide effective llm services.
"""
def __init__(
self,
model: str = DEFAULT_MODEL_NAME,
api_key: Optional[str] = Non... | PaiEas |
python | ray-project__ray | rllib/connectors/learner/add_infos_from_episodes_to_train_batch.py | {
"start": 374,
"end": 1850
} | class ____(ConnectorV2):
"""Adds the infos column to th train batch.
If provided with `episodes` data, this connector piece makes sure that the final
train batch going into the RLModule for updating (`forward_train()` call) contains
an `infos` column.
If the user wants to customize their own data ... | AddInfosFromEpisodesToTrainBatch |
python | walkccc__LeetCode | solutions/643. Maximum Average Subarray I/643.py | {
"start": 0,
"end": 236
} | class ____:
def findMaxAverage(self, nums: list[int], k: int) -> float:
summ = sum(nums[:k])
ans = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i - k]
ans = max(ans, summ)
return ans / k
| Solution |
python | spyder-ide__spyder | spyder/widgets/reporterror.py | {
"start": 1770,
"end": 4062
} | class ____(SimpleCodeEditor, SpyderFontsMixin):
"""Widget to enter error description."""
def __init__(self, parent=None):
super().__init__(parent)
# Editor options
self.setup_editor(
language='md',
font=self.get_font(
SpyderFontType.MonospaceInte... | DescriptionWidget |
python | pallets__jinja | src/jinja2/bccache.py | {
"start": 3128,
"end": 6065
} | class ____:
"""To implement your own bytecode cache you have to subclass this class
and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
these methods are passed a :class:`~jinja2.bccache.Bucket`.
A very basic bytecode cache that saves the bytecode on the file system::
from o... | BytecodeCache |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 8463,
"end": 8936
} | class ____(Event):
name: str = "invoke_custom_judge_model"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
from mlflow.metrics.genai.model_utils import _parse_model_uri
model_uri = arguments.get("model_uri")
if not model_uri:
return {"mo... | InvokeCustomJudgeModelEvent |
python | apache__airflow | airflow-core/src/airflow/dag_processing/processor.py | {
"start": 16117,
"end": 23151
} | class ____(WatchedSubprocess):
"""
Parses dags with Task SDK API.
This class provides a wrapper and management around a subprocess to parse a specific DAG file.
Since DAGs are written with the Task SDK, we need to parse them in a task SDK process such that
we can use the Task SDK definitions when ... | DagFileProcessorProcess |
python | getsentry__sentry | tests/acceptance/test_organization_releases.py | {
"start": 243,
"end": 2998
} | class ____(AcceptanceTestCase):
release_date = datetime(2020, 5, 18, 15, 13, 58, 132928, tzinfo=UTC)
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = sel... | OrganizationReleasesTest |
python | django__django | django/contrib/postgres/constraints.py | {
"start": 664,
"end": 9453
} | class ____(CheckPostgresInstalledMixin, BaseConstraint):
template = (
"CONSTRAINT %(name)s EXCLUDE USING %(index_type)s "
"(%(expressions)s)%(include)s%(where)s%(deferrable)s"
)
def __init__(
self,
*,
name,
expressions,
index_type=None,
condit... | ExclusionConstraint |
python | pytorch__pytorch | test/distributed/test_multi_threaded_pg.py | {
"start": 732,
"end": 4865
} | class ____(TestCase):
@spawn_threads_and_init_comms(world_size=4)
def test_broadcast_object_list(self):
val = 99 if dist.get_rank() == 0 else None
object_list = [val] * dist.get_world_size()
dist.broadcast_object_list(object_list=object_list)
self.assertEqual(99, object_list[0])... | TestCollectivesWithWrapper |
python | ray-project__ray | python/ray/experimental/shuffle.py | {
"start": 1426,
"end": 2278
} | class ____:
"""This class is used to stream shuffle map outputs to the object store.
It can be subclassed to optimize writing (e.g., batching together small
records into larger objects). This will be performance critical if your
input records are small (the example shuffle uses very large records, so
... | ObjectStoreWriter |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 15457,
"end": 15791
} | class ____(RequestHandler):
def initialize(self, login_url):
self.login_url = login_url
def get_login_url(self):
return self.login_url
@authenticated
def get(self):
# we'll never actually get here because the test doesn't follow redirects
self.send_error(500)
| AuthRedirectRequestHandler |
python | getsentry__sentry | tests/sentry/integrations/jira_server/test_integration.py | {
"start": 51095,
"end": 56754
} | class ____(APITestCase):
@cached_property
def integration(self):
integration = self.create_integration(
organization=self.organization,
external_id="jira_server:1",
provider="jira_server",
name="Jira Server",
metadata={
"oauth_c... | JiraMigrationIntegrationTest |
python | getsentry__sentry | src/sentry/monitors/grouptype.py | {
"start": 420,
"end": 1002
} | class ____(GroupType):
type_id = 4001
slug = "monitor_check_in_failure"
description = "Crons Monitor Failed"
category = GroupCategory.CRON.value
category_v2 = GroupCategory.OUTAGE.value
released = True
creation_quota = Quota(3600, 60, 60_000) # 60,000 per hour, sliding window of 60 seconds
... | MonitorIncidentType |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 3741,
"end": 3911
} | class ____(BaseTestFactsPlatform):
platform_id = 'AIX'
fact_class = hardware.aix.AIXHardware
collector_class = hardware.aix.AIXHardwareCollector
| TestAIXHardware |
python | pytorch__pytorch | test/fx/test_fx_traceback.py | {
"start": 345,
"end": 10625
} | class ____(TestCase):
def test_node_source(self):
node_source = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.CREATE
)
self.assertExpectedInline(
node_source.print_readable().strip(),
"""(name=, pass_name=test_pass, action=create, g... | TestFXNodeSource |
python | huggingface__transformers | src/transformers/models/zamba/modeling_zamba.py | {
"start": 9952,
"end": 13400
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
and "Generating Long Sequences with Sparse Transformers".
Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
The input dimension he... | ZambaAttention |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.