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 | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/LinearRegionItem.py | {
"start": 198,
"end": 14081
} | class ____(GraphicsObject):
"""
**Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>`
Used for marking a horizontal or vertical region in plots.
The region can be dragged and is bounded by lines which can be dragged individually.
=============================== ===================... | LinearRegionItem |
python | getsentry__sentry | src/sentry/api/endpoints/relay/register_response.py | {
"start": 976,
"end": 4053
} | class ____(Endpoint):
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.OWNERS_INGEST
authentication_classes = ()
permission_classes = ()
enforce_rate_limit = True
rate_limits = RELAY_AUTH_RATE_LIMITS
def post(self, request: Request) -> Response:
"... | RelayRegisterResponseEndpoint |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_chisquare_simple_test_p_value_to_be_greater_than.py | {
"start": 2172,
"end": 5008
} | class ____(BatchExpectation):
"""Expect the chi-squared of 2 columns to have a p-value greater than the provided threshold."""
examples = [
{
"data": {"x": [30, 45, 25, 20], "y": [40, 40, 20, 20]},
"only_for": ["pandas"],
"tests": [
{
... | ExpectColumnChisquareSimpleTestPValueToBeGreaterThan |
python | pytorch__pytorch | test/dynamo/test_torchrec.py | {
"start": 603,
"end": 2367
} | class ____(torch.nn.Module):
def __init__(self, feature_boundaries: dict[str, list[float]]):
super().__init__()
self.bucket_w = torch.nn.ParameterDict()
self.boundaries_dict = {}
for key, boundaries in feature_boundaries.items():
self.bucket_w[key] = torch.nn.Parameter(
... | BucketizeMod |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/_unselected.py | {
"start": 233,
"end": 3445
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary"
_path_str = "scatterternary.unselected"
_valid_props = {"marker", "textfont"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An inst... | Unselected |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_parent_decorator.py | {
"start": 566,
"end": 903
} | class ____(TestC):
def __init__(self, foo, bar, baz):
_test_sink(foo)
_test_sink(bar)
_test_sink(baz)
def setup():
TestC_1(0, 0, 0)
TestC_1(0, 0, 0)
TestC_1(0, 0, 0)
TestC_2(0, 0, 0)
TestC_2(0, 0, 0)
TestC_2(0, 0, 0)
TestC_3(0, 0, 0)
TestC_3(0, 0, 0)
Tes... | TestC_3 |
python | django__django | tests/admin_changelist/admin.py | {
"start": 856,
"end": 1001
} | class ____(admin.ModelAdmin):
list_filter = ["child__name"]
search_fields = ["child__name"]
list_select_related = ["child"]
| ParentAdmin |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_parser.py | {
"start": 3077,
"end": 89636
} | class ____(BaseParser):
@property
def language(self) -> str:
return 'C++'
@property
def id_attributes(self) -> Sequence[str]:
return self.config.cpp_id_attributes
@property
def paren_attributes(self) -> Sequence[str]:
return self.config.cpp_paren_attributes
def _pa... | DefinitionParser |
python | pytorch__pytorch | test/inductor/test_codecache.py | {
"start": 107619,
"end": 116439
} | class ____(TestCase):
device_type = GPU_TYPE
def setUp(self):
super().setUp()
counters.clear()
PatchCaches.setUp()
def tearDown(self):
super().tearDown()
PatchCaches.tearDown()
def reset(self):
PyCodeCache.cache_clear(purge=True)
torch._dynamo.r... | TestAutotuneCache |
python | jina-ai__jina | tests/integration/deployments/test_deployment.py | {
"start": 11600,
"end": 12613
} | class ____(Executor):
@requests(on='/foo')
def foo(self, docs, **kwargs): ...
@pytest.mark.parametrize(
'uses', [DummyExecutor, 'executor.yml']
)
def test_deployment_uses(uses):
depl = Deployment(uses=uses)
with depl:
pass
@pytest.mark.parametrize(
'config_file,expected_replicas,ex... | DummyExecutor |
python | pytorch__pytorch | torch/_classes.py | {
"start": 55,
"end": 459
} | class ____(types.ModuleType):
def __init__(self, name: str) -> None:
super().__init__("torch.classes" + name)
self.name = name
def __getattr__(self, attr: str) -> Any:
proxy = torch._C._get_custom_class_python_wrapper(self.name, attr)
if proxy is None:
raise RuntimeE... | _ClassNamespace |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 13504,
"end": 14103
} | class ____(EnhancementMatch):
def __init__(self, inner: FrameMatch):
self.inner = inner
@property
def description(self) -> str:
return f"[ {self.inner.description} ] |"
def _to_config_structure(self, version: int) -> str:
return f"[{self.inner._to_config_structure(version)}]|"
... | CallerMatch |
python | ray-project__ray | python/ray/data/_internal/stats.py | {
"start": 35441,
"end": 43246
} | class ____:
"""Holds the execution times for a given Dataset.
This object contains a reference to the parent Dataset's stats as well,
but not the Dataset object itself, to allow its blocks to be dropped from
memory."""
def __init__(
self,
*,
metadata: StatsDict,
par... | DatasetStats |
python | gevent__gevent | src/gevent/queue.py | {
"start": 22127,
"end": 22657
} | class ____(Queue):
# A specialization of Queue that knows it can never
# be bound. Changing its maxsize has no effect.
__slots__ = ()
def __init__(self, maxsize=None, items=()):
if maxsize is not None:
raise ValueError("UnboundQueue has no maxsize")
Queue.__init__(self, max... | UnboundQueue |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_test_fire_action.py | {
"start": 1380,
"end": 1868
} | class ____(CamelSnakeSerializer):
actions = serializers.ListField(required=True)
def validate_actions(self, value):
validated_actions = []
for action in value:
action_validator = BaseActionValidator(data=action, context=self.context)
action_validator.is_valid(raise_excep... | TestActionsValidator |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 306589,
"end": 307217
} | class ____(torch.Tensor):
elem: torch.Tensor
__slots__ = ['elem', 'other']
@staticmethod
def __new__(cls, elem, *args, **kwargs):
# The wrapping tensor (TestSubclass) is just a meta tensor, so it
# doesn't hold any memory (meta tensor is generally the preferred type
# of tensor ... | TestWrapperSubclass |
python | astral-sh__uv | crates/uv-python/fetch-download-metadata.py | {
"start": 5479,
"end": 5643
} | class ____:
implementation: ImplementationName
@abc.abstractmethod
async def find(self) -> list[PythonDownload]:
raise NotImplementedError
| Finder |
python | pandas-dev__pandas | pandas/tests/plotting/test_groupby.py | {
"start": 261,
"end": 5732
} | class ____:
def test_series_groupby_plotting_nominally_works(self):
n = 10
weight = Series(np.random.default_rng(2).normal(166, 20, size=n))
gender = np.random.default_rng(2).choice(["male", "female"], size=n)
weight.groupby(gender).plot()
def test_series_groupby_plotting_nomin... | TestDataFrameGroupByPlots |
python | pypa__twine | tests/test_auth.py | {
"start": 9977,
"end": 13871
} | class ____:
def __init__(
self,
get_response_list: t.List[MockResponse],
post_response_list: t.List[MockResponse],
) -> None:
self.post_counter = self.get_counter = 0
self.get_response_list = get_response_list
self.post_response_list = post_response_list
def ... | MockSession |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 29441,
"end": 30597
} | class ____:
def __init__(
self,
organization: str | None,
notice_numbers: Iterable[int],
) -> None:
self._organization = organization
notice_numbers = list(notice_numbers)
if not all(isinstance(x, int) for x in notice_numbers):
raise TypeError("notice_... | NoticeReference |
python | apache__airflow | providers/redis/tests/unit/redis/log/test_redis_task_handler.py | {
"start": 1729,
"end": 5951
} | class ____:
@staticmethod
def clear_db():
clear_db_dags()
clear_db_runs()
if AIRFLOW_V_3_0_PLUS:
clear_db_dag_bundles()
@pytest.fixture
def ti(self):
date = timezone.datetime(2020, 1, 1)
dag = DAG(dag_id="dag_for_testing_redis_task_handler", schedule=... | TestRedisTaskHandler |
python | huggingface__transformers | src/transformers/integrations/integration_utils.py | {
"start": 76485,
"end": 89003
} | class ____(TrainerCallback):
"""
A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/).
Environment:
- **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`):
ClearML project name.
- **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`):
... | ClearMLCallback |
python | spack__spack | lib/spack/spack/util/timer.py | {
"start": 825,
"end": 1224
} | class ____:
def start(self, name=None):
pass
def stop(self, name=None):
pass
def duration(self, name=None):
return 0.0
@contextmanager
def measure(self, name):
yield self
@property
def phases(self):
return []
def write_json(self, out=sys.stdou... | BaseTimer |
python | PyCQA__pylint | tests/functional/a/arguments_renamed.py | {
"start": 2685,
"end": 3161
} | class ____(FruitConditional):
fruit = "orange"
override_condiment = True
if fruit == "orange":
def brew(self, orange_name: str): # [arguments-renamed]
print(f"Brewing an orange named {orange_name}")
if override_condiment:
def eat_with_condiment(self, fruit_name: st... | FruitOverrideConditional |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-dashscope/llama_index/indices/managed/dashscope/transformations.py | {
"start": 3028,
"end": 3804
} | class ____(BaseModel, Generic[T]):
"""
A class containing metadata & implementation for a transformation in a dashscope pipeline.
"""
name: str
component: T = Field(description="Component that implements the transformation")
@classmethod
def from_component(cls, component: BaseComponent) ->... | DashScopeConfiguredTransformation |
python | pytorch__pytorch | torch/backends/_coreml/preprocess.py | {
"start": 490,
"end": 894
} | class ____:
Float = 0
Double = 1
Int = 2
Long = 3
Undefined = 4
# Supported Tensor types in coremltools:
# https://github.com/apple/coremltools/blob/main/coremltools/converters/mil/frontend/torch/converter.py#L28
torch_to_mil_types = {
ScalarType.Float: types.fp32,
ScalarType.Double: types... | ScalarType |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 3370,
"end": 3829
} | class ____(vLLMTranscriptionRequest):
model_config = ConfigDict(arbitrary_types_allowed=True)
request_id: str = Field(
default_factory=lambda: f"{random_uuid()}",
description=(
"The request_id related to this request. If the caller does "
"not set it, a random_uuid will ... | TranscriptionRequest |
python | dagster-io__dagster | python_modules/libraries/dagster-mysql/dagster_mysql/run_storage/run_storage.py | {
"start": 1197,
"end": 7456
} | class ____(SqlRunStorage, ConfigurableClass):
"""MySQL-backed run storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in
``$DAGSTER_HOME``. Configura... | MySQLRunStorage |
python | google__jax | jax/_src/source_info_util.py | {
"start": 982,
"end": 2359
} | class ____(NamedTuple):
file_name: str
function_name: str
start_line: int
start_column: int
end_line: int
end_column: int
_exclude_paths: list[str] = [
# Attach the separator to make sure that .../jax does not end up matching
# .../jax_triton and other packages that might have a jax prefix.
os... | Frame |
python | google__jax | tests/debugging_primitives_test.py | {
"start": 1262,
"end": 1365
} | class ____:
def __init__(self, platform, id):
self.platform = platform
self.id = id
| DummyDevice |
python | cherrypy__cherrypy | cherrypy/test/test_plugins.py | {
"start": 62,
"end": 341
} | class ____:
def test_file_for_file_module_when_None(self):
"""No error when ``module.__file__`` is :py:data:`None`."""
class test_module:
__file__ = None
assert plugins.Autoreloader._file_for_file_module(test_module) is None
| TestAutoreloader |
python | ray-project__ray | python/ray/data/tests/unit/test_expressions.py | {
"start": 6183,
"end": 7785
} | class ____:
"""Test enhanced binary expression functionality."""
@pytest.mark.parametrize(
"expr, expected_op",
[
(col("age") != lit(25), Operation.NE),
(col("status").is_in(["active", "pending"]), Operation.IN),
(col("status").not_in(["inactive", "deleted"])... | TestBinaryExpressions |
python | realpython__materials | python-enum/disk_player.py | {
"start": 30,
"end": 132
} | class ____(Enum):
EMPTY = auto()
STOPPED = auto()
PAUSED = auto()
PLAYING = auto()
| State |
python | apache__airflow | providers/amazon/tests/system/amazon/aws/utils/__init__.py | {
"start": 4665,
"end": 6650
} | class ____:
"""
Stores metadata about a variable to be fetched for AWS System Tests.
:param name: The name of the variable to be fetched.
:param to_split: If True, the input is a string-formatted List and needs to be split. Defaults to False.
:param delimiter: If to_split is true, this will be used... | Variable |
python | getsentry__sentry | src/sentry/relay/projectconfig_debounce_cache/base.py | {
"start": 44,
"end": 1841
} | class ____(Service):
"""A cache for debouncing updates for the relay projectconfig cache.
Whenever a project or organization option changes, we schedule a task
that updates the relay configuration in the projectconfig cache.
However, at the same time we want to debounce this task in case multiple
o... | ProjectConfigDebounceCache |
python | optuna__optuna | optuna/storages/_in_memory.py | {
"start": 15186,
"end": 15632
} | class ____:
def __init__(self, name: str, directions: list[StudyDirection]) -> None:
self.trials: list[FrozenTrial] = []
self.param_distribution: dict[str, distributions.BaseDistribution] = {}
self.user_attrs: dict[str, Any] = {}
self.system_attrs: dict[str, Any] = {}
self.na... | _StudyInfo |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/utils/misc.py | {
"start": 19194,
"end": 23745
} | class ____(BuildBackendHookCaller):
def __init__(
self,
config_holder: Any,
source_dir: str,
build_backend: str,
backend_path: Optional[str] = None,
runner: Optional[Callable[..., None]] = None,
python_executable: Optional[str] = None,
):
super()._... | ConfiguredBuildBackendHookCaller |
python | tensorflow__tensorflow | tensorflow/compiler/tests/clustering_test.py | {
"start": 1152,
"end": 3694
} | class ____(xla_test.XLATestCase):
def testAdd(self):
val1 = np.array([4, 3, 2, 1], dtype=np.float32)
val2 = np.array([5, 6, 7, 8], dtype=np.float32)
expected = val1 + val2
with self.session():
with self.test_scope():
input1 = constant_op.constant(val1, name="const1")
input2 = co... | ClusteringTest |
python | pytorch__pytorch | test/test_utils.py | {
"start": 26994,
"end": 28732
} | class ____(TestCase):
def test_load_standalone(self):
build_dir = tempfile.mkdtemp()
try:
src_path = os.path.join(build_dir, "main.cpp")
src = textwrap.dedent(
"""\
#include <iostream>
#include <torch/torch.h>
in... | TestStandaloneCPPJIT |
python | lepture__authlib | authlib/jose/rfc7516/models.py | {
"start": 827,
"end": 1552
} | class ____(JWEAlgorithmBase, metaclass=ABCMeta):
"""Interface for JWE algorithm with tag-aware key agreement (in key agreement
with key wrapping mode).
ECDH-1PU is an example of such an algorithm.
"""
def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None):
raise ... | JWEAlgorithmWithTagAwareKeyAgreement |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 16623,
"end": 16891
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "test_with_context"
expected_hash = "c6bf81bca7ad"
additional_test_settings = {
"COMPRESS_OFFLINE_CONTEXT": {
"content": "OK!",
}
}
| OfflineCompressTestCaseWithContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 348626,
"end": 349503
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateEnterpriseTwoFactorAuthenticationRequiredSetting
"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "setting_value", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name... | UpdateEnterpriseTwoFactorAuthenticationRequiredSettingInput |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_write_path.py | {
"start": 289,
"end": 1362
} | class ____(unittest.TestCase):
"""
Test the Vml _write_path() method.
"""
def setUp(self):
self.fh = StringIO()
self.vml = Vml()
self.vml._set_filehandle(self.fh)
def test_write_comment_path_1(self):
"""Test the _write_comment_path() method"""
self.vml._wr... | TestWriteVpath |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/serve.py | {
"start": 35749,
"end": 35839
} | class ____(SettingsOverrideObject):
_default_class = ServeSitemapXMLBase
| ServeSitemapXML |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 142168,
"end": 145227
} | class ____(DialectKWArgs):
"""Defines options for a named database sequence or an identity column.
.. seealso::
:class:`.Sequence`
"""
def __init__(
self,
start: Optional[int] = None,
increment: Optional[int] = None,
minvalue: Optional[int] = None,
max... | IdentityOptions |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg.py | {
"start": 1132,
"end": 1807
} | class ____(core.FigureManagerWebAgg):
_toolbar2_class = core.NavigationToolbar2WebAgg
@classmethod
def pyplot_show(cls, *, block=None):
WebAggApplication.initialize()
url = "http://{address}:{port}{prefix}".format(
address=WebAggApplication.address,
port=WebAggAppli... | FigureManagerWebAgg |
python | kamyu104__LeetCode-Solutions | Python/greatest-sum-divisible-by-three.py | {
"start": 29,
"end": 316
} | class ____(object):
def maxSumDivThree(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0, 0, 0]
for num in nums:
for i in [num+x for x in dp]:
dp[i%3] = max(dp[i%3], i)
return dp[0]
| Solution |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 59426,
"end": 59783
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["SearchMatrixPairsResponse"] = Field(default=No... | InlineResponse20023 |
python | astropy__astropy | astropy/constants/constant.py | {
"start": 8842,
"end": 9418
} | class ____(Constant):
"""An electromagnetic constant."""
@property
def cgs(self):
"""Overridden for EMConstant to raise a `TypeError`
emphasizing that there are multiple EM extensions to CGS.
"""
raise TypeError(
"Cannot convert EM constants to cgs because there ... | EMConstant |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 4933,
"end": 8095
} | class ____(URLPatternsTestCase, APITestCase):
included = [
path('namespaced/', dummy_view, name='another'),
path('example/<int:pk>/', dummy_pk_view, name='example-detail')
]
urlpatterns = [
path('v1/', include((included, 'v1'), namespace='v1')),
path('another/', dummy_view, ... | TestURLReversing |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 9543,
"end": 12433
} | class ____(ReturnsRows):
"""Mark a class as being selectable."""
__visit_name__ = "selectable"
is_selectable = True
def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
raise NotImplementedError()
def lateral(self, name: Optional[str] = None) -> LateralFromClause:
... | Selectable |
python | getsentry__sentry | tests/sentry/issues/test_issue_search.py | {
"start": 16279,
"end": 17228
} | class ____(TestCase):
def test_user(self) -> None:
assert convert_actor_or_none_value(
["me"], [self.project], self.user, None
) == convert_user_value(["me"], [self.project], self.user, None)
def test_my_team(self) -> None:
assert convert_actor_or_none_value(
["m... | ConvertActorOrNoneValueTest |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event.py | {
"start": 883,
"end": 1051
} | class ____(BaseModel):
expires_after: Optional[SessionClientSecretExpiresAfter] = None
"""Configuration for the ephemeral token expiration."""
| SessionClientSecret |
python | ansible__ansible | test/integration/targets/protomatter/lookup_plugins/synthetic_plugin_info.py | {
"start": 137,
"end": 359
} | class ____(LookupBase):
def run(self, terms, variables=None, **kwargs):
return [_messages.PluginInfo(
resolved_name='ns.col.module',
type=_messages.PluginType.MODULE,
)]
| LookupModule |
python | pypa__warehouse | warehouse/oidc/models/github.py | {
"start": 5913,
"end": 11874
} | class ____:
"""
Common functionality for both pending and concrete GitHub OIDC publishers.
"""
repository_name: Mapped[str] = mapped_column(String, nullable=False)
repository_owner: Mapped[str] = mapped_column(String, nullable=False)
repository_owner_id: Mapped[str] = mapped_column(String, null... | GitHubPublisherMixin |
python | Textualize__textual | src/textual/widgets/_placeholder.py | {
"start": 1613,
"end": 1720
} | class ____(Exception):
"""Raised when an invalid Placeholder variant is set."""
| InvalidPlaceholderVariant |
python | Pylons__pyramid | src/pyramid/static.py | {
"start": 531,
"end": 11395
} | class ____:
"""An instance of this class is a callable which can act as a
:app:`Pyramid` :term:`view callable`; this view will serve
static files from a directory on disk based on the ``root_dir``
you provide to its constructor.
The directory may contain subdirectories (recursively); the static
... | static_view |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 38064,
"end": 51892
} | class ____(LxmertPreTrainedModel):
# help saving them
_tied_weights_keys = {
"cls.predictions.decoder.weight": "lxmert.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
# Configuration
self.config = config
self.num_qa_labe... | LxmertForPreTraining |
python | tensorflow__tensorflow | tensorflow/tools/compatibility/ast_edits_test.py | {
"start": 1643,
"end": 1891
} | class ____(ast_edits.NoUpdateSpec):
"""A specification which deprecates 'a.b'."""
def __init__(self):
ast_edits.NoUpdateSpec.__init__(self)
self.module_deprecations.update({"a.b": (ast_edits.ERROR, "a.b is evil.")})
| ModuleDeprecationSpec |
python | pytorch__pytorch | torch/distributions/relaxed_bernoulli.py | {
"start": 590,
"end": 4255
} | class ____(Distribution):
r"""
Creates a LogitRelaxedBernoulli distribution parameterized by :attr:`probs`
or :attr:`logits` (but not both), which is the logit of a RelaxedBernoulli
distribution.
Samples are logits of values in (0, 1). See [1] for more details.
Args:
temperature (Tenso... | LogitRelaxedBernoulli |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc8628/errors.py | {
"start": 950,
"end": 1235
} | class ____(OAuth2Error):
"""
A variant of "authorization_pending", the authorization request is
still pending and polling should continue, but the interval MUST
be increased by 5 seconds for this and all subsequent requests.
"""
error = "slow_down"
| SlowDownError |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/polymorphic_function_xla_test.py | {
"start": 1000,
"end": 1663
} | class ____(xla_test.XLATestCase):
def testVarInitializedInFunction(self):
with self.test_scope():
v_holder = []
@polymorphic_function.function
def add_var(x):
if not v_holder:
v = variables.Variable([1., 2.])
v_holder.append(v)
already_initialized = variab... | FunctionTests |
python | huggingface__transformers | src/transformers/models/tapas/modeling_tapas.py | {
"start": 1588,
"end": 2648
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` (and possibly `answer`, `aggregation_labels`, `numeric_values` and `numeric_values_scale` are provided)):
Total loss as the sum of the hierarchical cell selection log-likelihood loss and (optional... | TableQuestionAnsweringOutput |
python | getsentry__sentry | src/sentry/api/serializers/models/actor.py | {
"start": 100,
"end": 232
} | class ____(TypedDict):
type: Literal["user", "team"]
id: str
name: str
email: NotRequired[str]
| ActorSerializerResponse |
python | mlflow__mlflow | tests/helper_functions.py | {
"start": 19458,
"end": 27085
} | class ____(str):
def __eq__(self, other):
return self in other
def assert_array_almost_equal(actual_array, desired_array, rtol=1e-6):
import numpy as np
elem0 = actual_array[0]
if isinstance(elem0, numbers.Number) or (
isinstance(elem0, (list, np.ndarray)) and isinstance(elem0[0], num... | AnyStringWith |
python | plotly__plotly.py | plotly/graph_objs/isosurface/legendgrouptitle/_font.py | {
"start": 233,
"end": 9942
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.legendgrouptitle"
_path_str = "isosurface.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"... | Font |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/base.py | {
"start": 26584,
"end": 31561
} | class ____(metaclass=_MetaOptions):
"""A cacheable option dictionary with defaults."""
__slots__ = ()
_cache_attrs: Tuple[str, ...]
def __init_subclass__(cls) -> None:
dict_ = cls.__dict__
cls._cache_attrs = tuple(
sorted(
d
for d in dict_
... | Options |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/fake_renderer.py | {
"start": 2132,
"end": 3343
} | class ____(FakeRenderer):
"""
Renderer with the full complement of methods.
When the following are left undefined, they will be implemented via
other methods in the class. They can be defined explicitly for
more efficient or specialized use within the renderer implementation.
"""
def draw... | FullFakeRenderer |
python | dagster-io__dagster | .buildkite/dagster-buildkite/dagster_buildkite/steps/packages.py | {
"start": 2584,
"end": 38558
} | class ____:
"""Main spec for testing Dagster Python packages using tox.
Args:
directory (str): Python directory to test, relative to the repository root. Should contain a
tox.ini file.
name (str, optional): Used in the buildkite label. Defaults to None
(uses the package ... | PackageSpec |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 49902,
"end": 53574
} | class ____(GoogleCloudBaseOperator):
"""
Creates a Memcached instance based on the specified tier and memory size.
By default, the instance is accessible from the project's `default network
<https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__.
.. seealso::
For more in... | CloudMemorystoreMemcachedCreateInstanceOperator |
python | readthedocs__readthedocs.org | readthedocs/core/forms.py | {
"start": 6916,
"end": 7440
} | class ____(forms.Select):
"""
Rich content dropdown field widget type used for complex content.
This class is mostly used for special casing in Crispy form templates, it
doesn't do anything special. This widget type requires use of the
:py:class:`RichChoice` data class. Usage might look something c... | RichSelect |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dep_with_variants_if_develop_root/package.py | {
"start": 216,
"end": 441
} | class ____(Package):
"""Package that adds a dependency with many variants only at @develop"""
homepage = "https://dev.null"
version("1.0")
depends_on("dep-with-variants-if-develop")
| DepWithVariantsIfDevelopRoot |
python | tensorflow__tensorflow | tensorflow/python/framework/tensor_util_test.py | {
"start": 50788,
"end": 52542
} | class ____(test.TestCase):
@contextlib.contextmanager
def disableSetStaticShape(self):
flag_old = shape_util._ENABLE_MAYBE_SET_STATIC_SHAPE
shape_util._ENABLE_MAYBE_SET_STATIC_SHAPE = False
try:
yield
finally:
shape_util._ENABLE_MAYBE_SET_STATIC_SHAPE = flag_old
def testMaybeSetStati... | MaybeSetStaticShapeTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/langchain_helpers/agents/tools.py | {
"start": 1114,
"end": 1383
} | class ____(BaseModel):
"""Configuration for LlamaIndex index tool."""
model_config = ConfigDict(arbitrary_types_allowed=True)
query_engine: BaseQueryEngine
name: str
description: str
tool_kwargs: Dict = Field(default_factory=dict)
| IndexToolConfig |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 4954,
"end": 5092
} | class ____(GroupBatchFusionBase):
"""
Fuse ops in a batch way, e.g, fuse mm/addmm of same input shapes with bmm.
"""
| BatchFusion |
python | mlflow__mlflow | mlflow/types/schema.py | {
"start": 30063,
"end": 32218
} | class ____:
"""
Representation of the shape and type of a Tensor.
"""
def __init__(self, dtype: np.dtype, shape: tuple[Any, ...] | list[Any]):
if not isinstance(dtype, np.dtype):
raise TypeError(
f"Expected `dtype` to be instance of `{np.dtype}`, received `{dtype.__c... | TensorInfo |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_errorbars01.py | {
"start": 315,
"end": 1569
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_errorbars01.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with error bars."""
workbook = Wor... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/prefect_gcp/deployments/steps.py | {
"start": 530,
"end": 7927
} | class ____(TypedDict):
"""
The output of the `pull_from_gcs` step.
"""
bucket: str
folder: str
directory: str
def push_to_gcs(
bucket: str,
folder: str,
project: Optional[str] = None,
credentials: Optional[Dict] = None,
ignore_file=".prefectignore",
) -> PushToGcsOutput:
... | PullFromGcsOutput |
python | getlogbook__logbook | src/logbook/queues.py | {
"start": 12736,
"end": 16109
} | class ____(SubscriberBase):
"""A helper that acts as ZeroMQ subscriber and will dispatch received
log records to the active handler setup. There are multiple ways to
use this class.
It can be used to receive log records from a queue::
subscriber = ZeroMQSubscriber("tcp://127.0.0.1:5000")
... | ZeroMQSubscriber |
python | getsentry__sentry | src/sentry/migrations/0912_make_organizationmemberteam_replica_is_active_true.py | {
"start": 155,
"end": 1488
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | getsentry__sentry | src/sentry/utils/assets.py | {
"start": 201,
"end": 2526
} | class ____:
commit_sha: str
"""
The commit SHA of the currently deployed frontend version.
"""
entrypoints: dict[str, str]
"""
A mapping of unversioned entrypoint names to versioned entrypoints,
containing a content-hash suffix.
"""
@ttl_cache(ttl=60)
def _frontend_versions() -> Fr... | FrontendVersions |
python | walkccc__LeetCode | solutions/3013. Divide an Array Into Subarrays With Minimum Cost II/3013.py | {
"start": 42,
"end": 1559
} | class ____:
def minimumCost(self, nums: list[int], k: int, dist: int) -> int:
# Equivalently, the problem is to find nums[0] + the minimum sum of the top
# k - 1 numbers in nums[i..i + dist], where i > 0 and i + dist < n.
windowSum = sum(nums[i] for i in range(1, dist + 2))
selected = SortedList(nums[... | Solution |
python | keras-team__keras | keras/src/regularizers/regularizers.py | {
"start": 8769,
"end": 11799
} | class ____(Regularizer):
"""Regularizer that encourages input vectors to be orthogonal to each other.
It can be applied to either the rows of a matrix (`mode="rows"`) or its
columns (`mode="columns"`). When applied to a `Dense` kernel of shape
`(input_dim, units)`, rows mode will seek to make the featu... | OrthogonalRegularizer |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/combinatory_ports.py | {
"start": 614,
"end": 671
} | class ____:
def method(self) -> None:
pass
| Base |
python | python__mypy | mypyc/annotate.py | {
"start": 4164,
"end": 9082
} | class ____:
"""Annotations for a single compiled source file."""
def __init__(self, path: str, annotations: dict[int, list[Annotation]]) -> None:
self.path = path
self.annotations = annotations
def generate_annotated_html(
html_fnam: str, result: BuildResult, modules: dict[str, ModuleIR],... | AnnotatedSource |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-weaviate/destination_weaviate/indexer.py | {
"start": 655,
"end": 744
} | class ____(Exception):
pass
CLOUD_DEPLOYMENT_MODE = "cloud"
| WeaviatePartialBatchError |
python | bokeh__bokeh | src/bokeh/core/property/instance.py | {
"start": 1783,
"end": 4156
} | class ____(Property[T]):
""" Accept values that are instances of any class.
.. note::
This is primarily useful for validation purpose. Non-serializable
objects will fail regardless during the serialization process.
"""
_instance_type: type[T] | Callable[[], type[T]] | str
... | Object |
python | Netflix__metaflow | metaflow/datastore/flow_datastore.py | {
"start": 289,
"end": 14552
} | class ____(object):
default_storage_impl = None
def __init__(
self,
flow_name,
environment=None,
metadata=None,
event_logger=None,
monitor=None,
storage_impl=None,
ds_root=None,
):
"""
Initialize a Flow level datastore.
... | FlowDataStore |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 1684,
"end": 31311
} | class ____(object):
@unittest.skipIf(not ALSO_RUN_BENCHMARKS, 'Benchmarks are disabled.')
def testDescriptorPoolBenchmark(self):
if ALSO_RUN_BENCHMARKS:
n_trials = 100
# FindFileByName
name = 'google/protobuf/internal/factory_test1.proto'
duration = timeit.timeit(
lambda: sel... | DescriptorPoolTestBase |
python | doocs__leetcode | solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution.py | {
"start": 152,
"end": 449
} | class ____:
def preorder(self, root: "Node") -> List[int]:
def dfs(root):
if root is None:
return
ans.append(root.val)
for child in root.children:
dfs(child)
ans = []
dfs(root)
return ans
| Solution |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_timeseries_trace_metrics.py | {
"start": 390,
"end": 6090
} | class ____(OrganizationEventsEndpointTestBase):
endpoint = "sentry-api-0-organization-events-timeseries"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.start = self.day_ago = before_now(days=1).replace(
hour=10, minute=0, second=0, microsecond=0
... | OrganizationEventsStatsTraceMetricsEndpointTest |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 26281,
"end": 26669
} | class ____(TestSimpleHttpsBase):
# above tests use a server certificate for "localhost",
# client connection to "localhost" too.
# here we test that even if the server certificate is for another domain,
# "www.example.com" in this case,
# the tests still pass
keyfile = "keys/example-com.key.pem"... | TestHttpsWrongHostnameBase |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/init.py | {
"start": 538,
"end": 5064
} | class ____:
"""The context object available as the argument to the initialization function of a :py:class:`dagster.ResourceDefinition`.
Users should not instantiate this object directly. To construct an `InitResourceContext` for testing purposes, use :py:func:`dagster.build_init_resource_context`.
Example... | InitResourceContext |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/state.py | {
"start": 2424,
"end": 4337
} | class ____(Store):
def __init__(self, statedir: str):
self.statedir = os.path.abspath(statedir)
self.location_file_prefix = "location-"
if not os.path.isdir(self.statedir):
os.makedirs(self.statedir)
def __repr__(self):
return f"<FileStore(statedir={self.statedir!r})... | FileStore |
python | langchain-ai__langchain | libs/langchain/langchain_classic/indexes/vectorstore.py | {
"start": 7042,
"end": 9788
} | class ____(BaseModel):
"""Logic for creating indexes."""
vectorstore_cls: type[VectorStore] = Field(
default_factory=_get_in_memory_vectorstore,
)
embedding: Embeddings
text_splitter: TextSplitter = Field(default_factory=_get_default_text_splitter)
vectorstore_kwargs: dict = Field(defau... | VectorstoreIndexCreator |
python | python-openxml__python-docx | tests/image/test_jpeg.py | {
"start": 16221,
"end": 17864
} | class ____:
def it_can_construct_from_a_stream(self, stream_, _MarkerFinder__init_):
marker_finder = _MarkerFinder.from_stream(stream_)
_MarkerFinder__init_.assert_called_once_with(ANY, stream_)
assert isinstance(marker_finder, _MarkerFinder)
def it_can_find_the_next_marker_after_a_giv... | Describe_MarkerFinder |
python | pypa__warehouse | warehouse/macaroons/caveats/__init__.py | {
"start": 2756,
"end": 3356
} | class ____(Caveat):
user_id: StrictStr
def verify(self, request: Request, context: Any, permission: str) -> Result:
if not isinstance(request.identity, UserContext):
return Failure("token with user restriction without a user")
if request.identity.macaroon is None:
retur... | RequestUser |
python | huggingface__transformers | src/transformers/models/lfm2_vl/image_processing_lfm2_vl_fast.py | {
"start": 6053,
"end": 6578
} | class ____(ImagesKwargs, total=False):
"""
downsample_factor (`int`, *optional*, defaults to `2`):
The downsampling factor for images used when resizing the image.
"""
downsample_factor: int
do_image_splitting: bool
min_tiles: int
max_tiles: int
use_thumbnail: bool
min_image... | Lfm2VlImageProcessorKwargs |
python | xlwings__xlwings | xlwings/pro/utils.py | {
"start": 871,
"end": 7439
} | class ____:
@staticmethod
def get_cipher():
try:
return Fernet(os.getenv("XLWINGS_LICENSE_KEY_SECRET"))
except (TypeError, ValueError):
raise xlwings.LicenseError(
"Couldn't validate xlwings license key."
) from None
@staticmethod
def ... | LicenseHandler |
python | wandb__wandb | wandb/apis/public/artifacts.py | {
"start": 30409,
"end": 33997
} | class ____(SizedRelayPaginator["FileFragment", "File"]):
"""A paginator for files in an artifact.
<!-- lazydoc-ignore-init: internal -->
"""
QUERY: Document # Must be set per-instance
last_response: ArtifactFileConnection | None
def __init__(
self,
client: Client,
art... | ArtifactFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.