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 | getsentry__sentry | src/sentry/auth/providers/dummy.py | {
"start": 1120,
"end": 2268
} | class ____(Provider):
name = "Dummy"
key = "dummy"
def get_auth_pipeline(self) -> Sequence[AuthView]:
return [AskEmail()]
def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
return {
"id": MigratingIdentityId(
id=state.get("id", state["e... | DummyProvider |
python | readthedocs__readthedocs.org | readthedocs/api/v2/admin.py | {
"start": 173,
"end": 318
} | class ____(APIKeyModelAdmin):
raw_id_fields = ["project"]
search_fields = [*APIKeyModelAdmin.search_fields, "project__slug"]
| BuildAPIKeyAdmin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink45.py | {
"start": 315,
"end": 959
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink45.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/endpoints-frameworks-v2/iata/main.py | {
"start": 1272,
"end": 1480
} | class ____(messages.Message):
airports = messages.MessageField(Airport, 1, repeated=True)
# [END endpoints_iata_messages]
# [START endpoints_iata_api]
@endpoints.api(name="iata", version="v1")
| AirportList |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 404,
"end": 5411
} | class ____(NonStrictDataModel):
"""
:param label: Lucene format query (see lucene query syntax). Default search
field is label.keyword and default operator is AND, so searching for:
'Bus Stop' Blue
is equivalent to:
Label.keyword:'Bus Stop' AND label.keyword:'Blue'
:type labe... | FilterLabelRule |
python | scikit-learn__scikit-learn | sklearn/neighbors/_base.py | {
"start": 26005,
"end": 38763
} | class ____:
"""Mixin for k-neighbors searches."""
def _kneighbors_reduce_func(self, dist, start, n_neighbors, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
---------... | KNeighborsMixin |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/natural_language.py | {
"start": 7872,
"end": 10919
} | class ____(GoogleCloudBaseOperator):
"""
Analyzes the sentiment of the provided text.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageAnalyzeSentimentOperator`
:param document: Input document.
If ... | CloudNaturalLanguageAnalyzeSentimentOperator |
python | ipython__ipython | IPython/terminal/embed.py | {
"start": 4167,
"end": 4323
} | class ____:
def __init__(self, repr):
assert isinstance(repr, str)
self.repr = repr
def __repr__(self):
return repr
| _Sentinel |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 12961,
"end": 13911
} | class ____(hp.HasProps):
foo = Int(default=lambda: 10)
def test_HasProps_apply_theme_func_default() -> None:
# check applying multiple themes
c = IntFuncDefault()
assert c.foo == 10
theme = dict(foo=20)
c.apply_theme(theme)
assert c.foo == 20
theme = dict(foo=30)
c.apply_theme(th... | IntFuncDefault |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/debugger_cli_common.py | {
"start": 16724,
"end": 27447
} | class ____:
"""Registry of command handlers for CLI.
Handler methods (callables) for user commands can be registered with this
class, which then is able to dispatch commands to the correct handlers and
retrieve the RichTextLines output.
For example, suppose you have the following handler defined:
def ec... | CommandHandlerRegistry |
python | getsentry__sentry | src/sentry/tasks/auth/auth.py | {
"start": 6769,
"end": 8047
} | class ____(OrganizationComplianceTask):
log_label = "2FA"
def is_compliant(self, user: RpcUser) -> bool:
if user:
return user.has_2fa()
return False
def call_to_action(self, org: Organization, user: RpcUser, member: OrganizationMember):
# send invite to setup 2fa
... | TwoFactorComplianceTask |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_coding_agents.py | {
"start": 13668,
"end": 22484
} | class ____(BaseOrganizationCodingAgentsTest):
"""Test class for POST endpoint parameter validation."""
def test_feature_flag_disabled(self):
"""Test POST endpoint when feature flag is disabled."""
data = {"integration_id": "123", "run_id": 123}
response = self.get_error_response(
... | OrganizationCodingAgentsPostParameterValidationTest |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 25417,
"end": 25601
} | class ____(RuntimeError):
"""
Exception raised when clipboard functionality is unsupported.
Raised by ``to_clipboard()`` and ``read_clipboard()``.
"""
| PyperclipException |
python | numba__numba | numba/tests/test_jitclasses.py | {
"start": 871,
"end": 1164
} | class ____(object):
def __init__(self, x, y, z=1, *args, a=5):
self.x = x
self.y = y
self.z = z
self.args = args
self.a = a
def _get_meminfo(box):
ptr = _box.box_get_meminfoptr(box)
mi = MemInfo(ptr)
mi.acquire()
return mi
| TestClass2 |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/envs/unity_parallel_env.py | {
"start": 229,
"end": 1594
} | class ____(UnityPettingzooBaseEnv, ParallelEnv):
"""
Unity Parallel (PettingZoo) environment wrapper.
"""
def __init__(self, env: BaseEnv, seed: Optional[int] = None):
"""
Initializes a Unity Parallel environment wrapper.
:param env: The UnityEnvironment that is being wrapped.
... | UnityParallelEnv |
python | tensorflow__tensorflow | tensorflow/lite/python/optimize/calibrator.py | {
"start": 1642,
"end": 9760
} | class ____:
"""Calibrates a floating point model and then quantizes it.
This is an internal class, not a public interface.
"""
def __init__(
self,
model_content,
custom_op_registerers_by_name=None,
custom_op_registerers_by_func=None,
):
"""Constructor.
Args:
model_cont... | Calibrator |
python | doocs__leetcode | solution/3200-3299/3296.Minimum Number of Seconds to Make Mountain Height Zero/Solution.py | {
"start": 0,
"end": 348
} | class ____:
def minNumberOfSeconds(self, mountainHeight: int, workerTimes: List[int]) -> int:
def check(t: int) -> bool:
h = 0
for wt in workerTimes:
h += int(sqrt(2 * t / wt + 1 / 4) - 1 / 2)
return h >= mountainHeight
return bisect_left(range(10... | Solution |
python | pdm-project__pdm | src/pdm/exceptions.py | {
"start": 196,
"end": 244
} | class ____(PdmException):
pass
| ResolutionError |
python | realpython__materials | inheritance-and-composition/choosing/productivity.py | {
"start": 0,
"end": 625
} | class ____:
def __init__(self):
self._roles = {
"manager": ManagerRole,
"secretary": SecretaryRole,
"sales": SalesRole,
"factory": FactoryRole,
}
def get_role(self, role_id):
role_type = self._roles.get(role_id)
if not role_type:
... | _ProductivitySystem |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 20650,
"end": 25090
} | class ____:
def setup(self, *args, **kwargs):
"""
The custom backend does the bare minimum to be considered a lazy backend. But
the data in it is still in memory so slow file reading shouldn't affect the
results.
"""
requires_dask()
@dataclass
class P... | IOReadCustomEngine |
python | doocs__leetcode | solution/2400-2499/2451.Odd String Difference/Solution.py | {
"start": 0,
"end": 274
} | class ____:
def oddString(self, words: List[str]) -> str:
d = defaultdict(list)
for s in words:
t = tuple(ord(b) - ord(a) for a, b in pairwise(s))
d[t].append(s)
return next(ss[0] for ss in d.values() if len(ss) == 1)
| Solution |
python | huggingface__transformers | src/transformers/models/zamba2/modeling_zamba2.py | {
"start": 60031,
"end": 61249
} | class ____(PreTrainedModel):
config: Zamba2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Zamba2AttentionDecoderLayer", "Zamba2MambaDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_flex_attn ... | Zamba2PreTrainedModel |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/protocol.py | {
"start": 1174,
"end": 1378
} | class ____:
Inactive = "inactive"
Connecting = "connecting"
Connected = "connected"
Starting = "starting"
Active = "active"
Stopping = "stopping"
Error = "error"
| ConnectionStatus |
python | doocs__leetcode | solution/1000-1099/1099.Two Sum Less Than K/Solution.py | {
"start": 0,
"end": 293
} | class ____:
def twoSumLessThanK(self, nums: List[int], k: int) -> int:
nums.sort()
ans = -1
for i, x in enumerate(nums):
j = bisect_left(nums, k - x, lo=i + 1) - 1
if i < j:
ans = max(ans, x + nums[j])
return ans
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_utilities.py | {
"start": 3665,
"end": 7019
} | class ____:
def test_succeeded_responds_true(self):
"""Desired behavior: `succeeded()` should return true if execution.status
contains a list element that is a dict with a key "type" and a value of
"Completed" and a key "status" and a value of "True"
"""
execution = Execution... | TestExecution |
python | Textualize__textual | src/textual/validation.py | {
"start": 17642,
"end": 18715
} | class ____(Validator):
"""Validator that checks if a URL is valid (ensuring a scheme is present)."""
class InvalidURL(Failure):
"""Indicates that the URL is not valid."""
def validate(self, value: str) -> ValidationResult:
"""Validates that `value` is a valid URL (contains a scheme).
... | URL |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 12295,
"end": 12666
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
text_document: TextDocumentItem
@staticmethod
def from_json_rpc_parameters(
parameters: json_rpc.Parameters,
) -> "DidOpenTextDocumentParameters":
return _parse_parameters(parameters, target=DidOpenTextDocumentParameters)
@dataclass... | DidOpenTextDocumentParameters |
python | pytorch__pytorch | test/mobile/lightweight_dispatch/tests_setup.py | {
"start": 1960,
"end": 2278
} | class ____(torch.nn.Upsample):
def __init__(self) -> None:
super().__init__(
scale_factor=(2.0,),
mode="linear",
align_corners=False,
recompute_scale_factor=True,
)
# index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
@save_model
| ModelWithFloatList |
python | google__jax | jax/experimental/jax2tf/tests/model_harness.py | {
"start": 1568,
"end": 13870
} | class ____:
name: str
apply: Callable[..., Any]
variables: dict[str, Any]
inputs: Sequence[np.ndarray]
rtol: float = 1e-4
polymorphic_shapes: Sequence[str | None] | None = None
tensor_spec: Sequence[tf.TensorSpec] | None = None
def __post_init__(self):
# When providing polymorphic shapes, tensor_sp... | ModelHarness |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_comm_hooks.py | {
"start": 2506,
"end": 3901
} | class ____:
def dummy_hook_for_no_shard_fsdp(self, state: DummyState, grad: torch.Tensor):
"""
This communication hook is for illustration and testing purpose only.
This communication hook is used during FSDP ``NO_SHARD`` training. It adds some noise to
the provided ``grad`` paramete... | DummyHook |
python | getsentry__sentry | tests/sentry/db/models/fields/test_slug.py | {
"start": 1698,
"end": 3859
} | class ____(TestCase):
def setUp(self) -> None:
self.compiler = Mock()
# Simulate the quoting behavior for simplicity in tests
self.compiler.quote_name_unless_alias = lambda name: (
f"{name}" if '"' in name else f'"{name}"'
)
self.connection = Mock()
@patch("s... | IdOrSlugLookupTests |
python | django__django | tests/db_functions/math/test_ln.py | {
"start": 267,
"end": 2227
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_ln=Ln("normal")).first()
self.assertIsNone(obj.null_ln)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6"))
obj = Deci... | LnTests |
python | getsentry__sentry | src/sentry/middleware/integrations/integration_control.py | {
"start": 461,
"end": 1958
} | class ____:
classifications: list[type[BaseClassification]] = [
IntegrationClassification,
PluginClassification,
]
"""
Classifications to determine whether request must be parsed, sorted in priority order.
getsentry expands this list on django initialization.
"""
def __init_... | IntegrationControlMiddleware |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/await1.py | {
"start": 325,
"end": 925
} | class ____:
id: int
async def func1(check: "Callable[[AnyMsg], bool]") -> AnyMsg: ...
async def func2():
_: Msg[Request] = await func1(check=lambda msg: (msg.body.id == 12345))
async def func3() -> AsyncIterator[int]:
yield 1
async def func4() -> int:
return await anext(func3())
async def func... | Request |
python | django__django | tests/staticfiles_tests/test_views.py | {
"start": 954,
"end": 1186
} | class ____(TestDefaults, TestServeStatic):
"""
Test static asset serving view with manually configured URLconf.
"""
@override_settings(DEBUG=True, ROOT_URLCONF="staticfiles_tests.urls.helper")
| TestServeStaticWithDefaultURL |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_templatetags.py | {
"start": 2509,
"end": 9568
} | class ____(Base):
restore_settings = ['THUMBNAIL_DEBUG', 'TEMPLATE_DEBUG']
def testTagInvalid(self):
# No args, or wrong number of args
src = '{% thumbnail %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
src = '{% thumbnail source %}'
self.assertRai... | ThumbnailTagTest |
python | apache__airflow | providers/docker/src/airflow/providers/docker/exceptions.py | {
"start": 1335,
"end": 1718
} | class ____(AirflowSkipException):
"""
Raised when a Docker container returns an error and task should be skipped.
:param logs: The log output of the failed Docker container
"""
def __init__(self, message: str | None = None, logs: list[str | bytes] | None = None) -> None:
super().__init__(m... | DockerContainerFailedSkipException |
python | mlflow__mlflow | mlflow/tensorflow/__init__.py | {
"start": 37846,
"end": 62734
} | class ____(NamedTuple):
location: str
is_temp: bool
def _setup_callbacks(callbacks, log_every_epoch, log_every_n_steps):
"""
Adds TensorBoard and MlfLowTfKeras callbacks to the
input list, and returns the new list and appropriate log directory.
"""
from mlflow.tensorflow.autologging import... | _TensorBoardLogDir |
python | openai__gym | tests/utils/test_play.py | {
"start": 567,
"end": 799
} | class ____(gym.Wrapper):
def __init__(self, env, keys_to_action):
super().__init__(env)
self.keys_to_action = keys_to_action
def get_keys_to_action(self):
return self.keys_to_action
| KeysToActionWrapper |
python | pdm-project__pdm | src/pdm/pytest.py | {
"start": 1712,
"end": 3711
} | class ____(httpx.BaseTransport):
"""
A local file transport for HTTPX.
Allows to mock some HTTP requests with some local files
"""
def __init__(
self,
aliases: dict[str, Path],
overrides: IndexOverrides | None = None,
strip_suffix: bool = False,
):
super... | LocalIndexTransport |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 66593,
"end": 69489
} | class ____(_LazyConvXdMixin, Conv3d): # type: ignore[misc]
r"""A :class:`torch.nn.Conv3d` module with lazy initialization of the ``in_channels`` argument.
The ``in_channels`` argument of the :class:`Conv3d` that is inferred from
the ``input.size(1)``.
The attributes that will be lazily initialized are... | LazyConv3d |
python | kamyu104__LeetCode-Solutions | Python/counting-words-with-a-given-prefix.py | {
"start": 42,
"end": 259
} | class ____(object):
def prefixCount(self, words, pref):
"""
:type words: List[str]
:type pref: str
:rtype: int
"""
return sum(x.startswith(pref) for x in words)
| Solution |
python | getsentry__sentry | src/sentry_plugins/twilio/client.py | {
"start": 123,
"end": 1089
} | class ____(ApiClient):
plugin_name = "twilio"
allow_redirects = False
twilio_messages_endpoint = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json"
def __init__(self, account_sid, auth_token, sms_from, sms_to):
self.account_sid = account_sid
self.auth_token = auth_token
... | TwilioApiClient |
python | milvus-io__pymilvus | tests/test_bulk_writer_stage.py | {
"start": 6013,
"end": 7994
} | class ____:
"""Test StageManager class."""
@pytest.fixture
def stage_manager(self) -> StageManager:
"""Create a StageManager instance."""
return StageManager(
cloud_endpoint="https://api.cloud.zilliz.com",
api_key="test_api_key",
)
@patch("pymilvus.bulk_... | TestStageManager |
python | walkccc__LeetCode | solutions/3247. Number of Subsequences with Odd Sum/3247.py | {
"start": 0,
"end": 652
} | class ____:
def subsequenceCount(self, nums: list[int]) -> int:
MOD = 1_000_000_007
even = 0 # the number of subsequences with even sum
odd = 0 # the number of subsequences with odd sum
for num in nums:
if num % 2 == 0:
# Appending an even number to a subsequence doesn't change the pa... | Solution |
python | tornadoweb__tornado | tornado/gen.py | {
"start": 24376,
"end": 25823
} | class ____:
"""_NullFuture resembles a Future that finished with a result of None.
It's not actually a `Future` to avoid depending on a particular event loop.
Handled as a special case in the coroutine runner.
We lie and tell the type checker that a _NullFuture is a Future so
we don't have to leak... | _NullFuture |
python | h5py__h5py | h5py/tests/test_h5z.py | {
"start": 508,
"end": 1972
} | class ____(Structure):
"""H5Z_class2_t structure defining a filter"""
_fields_ = [
("version", c_int),
("id_", c_int),
("encoder_present", c_uint),
("decoder_present", c_uint),
("name", c_char_p),
("can_apply", c_void_p),
("set_local", c_void_p),
... | H5ZClass2T |
python | django-extensions__django-extensions | tests/test_sqldiff.py | {
"start": 544,
"end": 6392
} | class ____(TestCase):
def setUp(self):
self.parser = Command().create_parser("test", "sqldiff")
self.args = ["-a"]
self.options = self.parser.parse_args(args=self.args)
self.tmp_out = StringIO()
self.tmp_err = StringIO()
def _include_proxy_models_testing(self, should_inc... | SqlDiffTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass4.py | {
"start": 634,
"end": 705
} | class ____:
aa: C1
bb: C2 = C2()
cc: C3 = C3()
@dataclass
| DC3 |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 2495,
"end": 2573
} | class ____(models.Model):
base_name = models.CharField(max_length=100)
| BaseM |
python | run-llama__llama_index | llama-index-core/llama_index/core/output_parsers/selection.py | {
"start": 808,
"end": 3360
} | class ____(BaseOutputParser):
REQUIRED_KEYS = frozenset(Answer.__annotations__)
def _filter_dict(self, json_dict: dict) -> dict:
"""Filter recursively until a dictionary matches all REQUIRED_KEYS."""
output_dict = json_dict
for key, val in json_dict.items():
if key in self.R... | SelectionOutputParser |
python | catalyst-team__catalyst | catalyst/callbacks/metrics/recsys.py | {
"start": 12141,
"end": 16186
} | class ____(BatchMetricCallback):
"""NDCG metric callback.
Computes NDCG@topk for the specified values of `topk`.
Args:
input_key: input key to use for metric calculation, specifies our `y_pred`
target_key: output key to use for metric calculation, specifies our `y_true`
prefix: key... | NDCGCallback |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 840935,
"end": 841325
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("ProjectColumn", graphql_n... | ProjectColumnEdge |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py | {
"start": 525,
"end": 1879
} | class ____(BaseModel):
url: str = Field(..., title="Public Endpoint", description="Public Endpoint of the Qdrant cluser", order=0)
auth_method: Union[ApiKeyAuth, NoAuth] = Field(
default="api_key_auth",
title="Authentication Method",
description="Method to authenticate with the Qdrant In... | QdrantIndexingConfigModel |
python | django__django | tests/order_with_respect_to/base_tests.py | {
"start": 194,
"end": 11561
} | class ____:
databases = {"default", "other"}
# Hook to allow subclasses to run these tests with alternate models.
Answer = None
Post = None
Question = None
@classmethod
def setUpTestData(cls):
cls.q1 = cls.Question.objects.create(
text="Which Beatle starts with the lett... | BaseOrderWithRespectToTests |
python | huggingface__transformers | src/transformers/models/vit_msn/modeling_vit_msn.py | {
"start": 8499,
"end": 10890
} | class ____(nn.Module):
def __init__(self, config: ViTMSNConfig):
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 ... | ViTMSNSelfAttention |
python | pennersr__django-allauth | allauth/account/internal/flows/phone_verification.py | {
"start": 806,
"end": 2910
} | class ____(AbstractCodeVerificationProcess):
def __init__(self, user, state):
super().__init__(
user=user,
state=state,
timeout=app_settings.PHONE_VERIFICATION_TIMEOUT,
max_attempts=app_settings.PHONE_VERIFICATION_MAX_ATTEMPTS,
)
@property
def... | PhoneVerificationProcess |
python | django__django | tests/prefetch_related/tests.py | {
"start": 70492,
"end": 76898
} | class ____(TestCase):
"""
prefetch_related() reuses objects fetched in _prefetched_objects_cache.
When objects are prefetched and not stored as an instance attribute (often
intermediary relationships), they are saved to the
_prefetched_objects_cache attribute. prefetch_related() takes
_prefetch... | DirectPrefetchedObjectCacheReuseTests |
python | keras-team__keras | keras/src/distillation/distillation_loss.py | {
"start": 9661,
"end": 14752
} | class ____(DistillationLoss):
"""Distillation loss that transfers knowledge from final model outputs.
This distillation loss applies temperature scaling to the teacher's logits
before computing the loss between teacher and student predictions. It's the
most common approach for knowledge distillation.
... | LogitsDistillation |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 14263,
"end": 14459
} | class ____(logging.Logger):
def __init__(self, context: "PipesContext") -> None:
super().__init__(name="dagster-pipes")
self.addHandler(_PipesLoggerHandler(context))
| _PipesLogger |
python | spack__spack | lib/spack/spack/llnl/util/lock.py | {
"start": 27982,
"end": 28262
} | class ____(LockTransaction):
"""LockTransaction context manager that does a read and releases it."""
def _enter(self):
return self._lock.acquire_read(self._timeout)
def _exit(self, release_fn):
return self._lock.release_read(release_fn)
| ReadTransaction |
python | sphinx-doc__sphinx | sphinx/util/docfields.py | {
"start": 1389,
"end": 6216
} | class ____:
"""A doc field that is never grouped. It can have an argument or not, the
argument can be linked using a specified *rolename*. Field should be used
for doc fields that usually don't occur more than once.
The body can be linked using a specified *bodyrolename* if the content is
just a ... | Field |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_kueue.py | {
"start": 7134,
"end": 9108
} | class ____:
def test_template_fields(self):
expected_template_fields = {"queue_name"} | set(KubernetesJobOperator.template_fields)
assert set(KubernetesStartKueueJobOperator.template_fields) == expected_template_fields
def test_init(self):
operator = KubernetesStartKueueJobOperator(
... | TestKubernetesStartKueueJobOperator |
python | simonw__datasette | datasette/utils/__init__.py | {
"start": 6801,
"end": 8065
} | class ____(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, sqlite3.Row):
return tuple(obj)
if isinstance(obj, sqlite3.Cursor):
return list(obj)
if isinstance(obj, bytes):
# Does it encode to utf8?
try:
return obj.d... | CustomJSONEncoder |
python | pandas-dev__pandas | pandas/tests/series/test_unary.py | {
"start": 72,
"end": 1620
} | class ____:
# __neg__, __pos__, __invert__
def test_neg(self):
ser = Series(range(5), dtype="float64", name="series")
tm.assert_series_equal(-ser, -1 * ser)
def test_invert(self):
ser = Series(range(5), dtype="float64", name="series")
tm.assert_series_equal(-(ser < 0), ~(se... | TestSeriesUnaryOps |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_indexing.py | {
"start": 2286,
"end": 3375
} | class ____:
def test_get_loc_key_unit_mismatch(self):
idx = to_timedelta(["0 days", "1 days", "2 days"])
key = idx[1].as_unit("ms")
loc = idx.get_loc(key)
assert loc == 1
def test_get_loc_key_unit_mismatch_not_castable(self):
tdi = to_timedelta(["0 days", "1 days", "2 da... | TestGetLoc |
python | Pylons__pyramid | tests/test_scripts/test_common.py | {
"start": 18,
"end": 436
} | class ____(unittest.TestCase):
def test_parse_vars_good(self):
from pyramid.scripts.common import parse_vars
vars = ['a=1', 'b=2']
result = parse_vars(vars)
self.assertEqual(result, {'a': '1', 'b': '2'})
def test_parse_vars_bad(self):
from pyramid.scripts.common import ... | TestParseVars |
python | jupyterlab__jupyterlab | jupyterlab/tests/test_registry.py | {
"start": 319,
"end": 4323
} | class ____(AppHandlerTest):
def test_node_not_available(self):
# patch should be applied on `jupyterlab.commands` and not on `jupyterlab_server.process`
# See https://docs.python.org/3/library/unittest.mock.html#where-to-patch
with patch("jupyterlab.commands.which") as which:
whi... | TestAppHandlerRegistry |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 116397,
"end": 116811
} | class ____(sgqlc.types.Enum):
"""The possible states of a subscription.
Enumeration Choices:
* `IGNORED`: The User is never notified.
* `SUBSCRIBED`: The User is notified of all conversations.
* `UNSUBSCRIBED`: The User is only notified when participating or
@mentioned.
"""
__schema... | SubscriptionState |
python | plotly__plotly.py | plotly/graph_objs/histogram/_stream.py | {
"start": 233,
"end": 3521
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram"
_path_str = "histogram.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set t... | Stream |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_drypython_returns.py | {
"start": 2577,
"end": 2661
} | class ____(_FirstBase[A, B], _SecondBase[float, bool]):
pass
| OneGenericOneConrete2 |
python | google__jax | jax/_src/linear_util.py | {
"start": 3427,
"end": 4082
} | class ____:
"""Storage for a value, with checks for overwriting or reading empty store."""
__slots__ = ("_val",)
def __init__(self):
self._val = _EMPTY_STORE_VALUE
def store(self, val):
if self._val is not _EMPTY_STORE_VALUE:
raise StoreException("Store occupied")
self._val = val
def rese... | Store |
python | dask__distributed | distributed/process.py | {
"start": 1621,
"end": 1700
} | class ____:
is_alive = False
pid = None
exitcode = None
| _ProcessState |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 2055,
"end": 2289
} | class ____(unittest.TestCase):
def setUp(self):
models.Base.metadata.create_all(models.engine)
def tearDown(self):
models.session.remove()
models.Base.metadata.drop_all(models.engine)
| TransactionTestCase |
python | huggingface__transformers | src/transformers/models/d_fine/modular_d_fine.py | {
"start": 33384,
"end": 33442
} | class ____(RTDetrDecoderOutput):
pass
| DFineDecoderOutput |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/async/guestbook.py | {
"start": 669,
"end": 790
} | class ____(ndb.Model):
content = ndb.StringProperty()
post_date = ndb.DateTimeProperty(auto_now_add=True)
| Guestbook |
python | pytorch__pytorch | torch/_inductor/codegen/halide.py | {
"start": 19654,
"end": 61617
} | class ____(SIMDKernel):
overrides = HalideOverrides # type: ignore[assignment]
kexpr: Callable[[sympy.Expr], str] = texpr
def __init__(
self,
tiling: dict[str, sympy.Expr],
**kwargs,
) -> None:
super().__init__(tiling, **kwargs)
# For halide, we just write direc... | HalideKernel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_search_query_performance_report.py | {
"start": 15986,
"end": 23456
} | class ____(TestBaseProductSearchQueryPerformanceReport):
stream_name = "product_search_query_performance_report_weekly"
report_file = "product_search_query_performance_report_weekly"
records_number = 5
incremental_report_file = "product_search_query_performance_report_weekly_incremental"
incremental... | TestProductSearchQueryPerformanceReportWeeklyStream |
python | celery__celery | t/unit/utils/test_term.py | {
"start": 266,
"end": 2842
} | class ____:
@pytest.fixture(autouse=True)
def preserve_encoding(self, patching):
patching('sys.getdefaultencoding', 'utf-8')
@pytest.mark.parametrize('name,color', [
('black', term.BLACK),
('red', term.RED),
('green', term.GREEN),
('yellow', term.YELLOW),
('... | test_colored |
python | gevent__gevent | src/greentest/3.12/test_weakref.py | {
"start": 34839,
"end": 39033
} | class ____(unittest.TestCase):
def _subclass(self):
"""Return an Object subclass overriding `some_method`."""
class C(Object):
def some_method(self):
return 6
return C
def test_alive(self):
o = Object(1)
r = weakref.WeakMethod(o.some_method)
... | WeakMethodTestCase |
python | ray-project__ray | python/ray/tests/test_actor_group.py | {
"start": 151,
"end": 2932
} | class ____:
def return_arg(self, arg):
return arg
def get_actor_metadata(self):
return "metadata"
# Use default filterwarnings behavior for this test
@pytest.mark.filterwarnings("default")
def test_actor_creation(ray_start_2_cpus):
assert ray.available_resources()["CPU"] == 2
with war... | DummyActor |
python | joerick__pyinstrument | pyinstrument/renderers/speedscope.py | {
"start": 1229,
"end": 1495
} | class ____:
"""
Data class to store speedscope's concept of a "profile".
"""
name: str
events: list[SpeedscopeEvent]
end_value: float
start_value: float = 0.0
type: str = "evented"
unit: str = "seconds"
@dataclass
| SpeedscopeProfile |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 23642,
"end": 25619
} | class ____(Expr):
""" A Meijer G-function. """
def __new__(cls, an, ap, bm, bq):
obj = super().__new__(cls)
obj.an = Tuple(*list(map(expand, an)))
obj.ap = Tuple(*list(map(expand, ap)))
obj.bm = Tuple(*list(map(expand, bm)))
obj.bq = Tuple(*list(map(expand, bq)))
... | G_Function |
python | jazzband__django-pipeline | tests/utils.py | {
"start": 204,
"end": 599
} | class ____(override_settings):
def __init__(self, **kwargs):
if django.VERSION[:2] >= (1, 10):
# Django 1.10's override_settings inherits from TestContextDecorator
# and its __init__ method calls its superclass' __init__ method too,
# so we must do the same.
s... | pipeline_settings |
python | openai__openai-python | src/openai/cli/_api/audio.py | {
"start": 1976,
"end": 3757
} | class ____:
@staticmethod
def transcribe(args: CLITranscribeArgs) -> None:
with open(args.file, "rb") as file_reader:
buffer_reader = BufferReader(file_reader.read(), desc="Upload progress")
model = cast(
"Transcription | str",
get_client().audio.transcriptio... | CLIAudio |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 22105,
"end": 22898
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.h... | YosoPredictionHeadTransform |
python | pandas-dev__pandas | pandas/tests/indexes/test_indexing.py | {
"start": 5353,
"end": 6980
} | class ____:
def test_get_loc_non_hashable(self, index):
with pytest.raises(InvalidIndexError, match="[0, 1]"):
index.get_loc([0, 1])
def test_get_loc_non_scalar_hashable(self, index):
# GH52877
from enum import Enum
class E(Enum):
X1 = "x1"
asse... | TestGetLoc |
python | huggingface__transformers | src/transformers/generation/continuous_batching/cache_manager.py | {
"start": 11812,
"end": 15444
} | class ____(CacheAllocator):
"""Cache manager for a group of full attention layers."""
def __init__(self, index: int, block_size: int) -> None:
"""Initializes the cache manager for a group of full attention layers.
Args:
- index: the index of the associated layer group
- ... | FullAttentionCacheAllocator |
python | ray-project__ray | python/ray/serve/tests/test_util.py | {
"start": 2286,
"end": 2543
} | class ____:
def __call__(self, *args):
return "reached decorated_actor"
def gen_func():
@serve.deployment
def f():
pass
return f
def gen_class():
@serve.deployment
class A:
pass
return A
| DecoratedActor |
python | openai__openai-python | src/openai/types/evals/create_eval_jsonl_run_data_source_param.py | {
"start": 1025,
"end": 1285
} | class ____(TypedDict, total=False):
source: Required[Source]
"""Determines what populates the `item` namespace in the data source."""
type: Required[Literal["jsonl"]]
"""The type of data source. Always `jsonl`."""
| CreateEvalJSONLRunDataSourceParam |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 119163,
"end": 120231
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.Model.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = DeleteModelVersionOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
... | TestVertexAIDeleteModelVersionOperator |
python | sqlalchemy__sqlalchemy | examples/versioned_history/test_versioning.py | {
"start": 29825,
"end": 29901
} | class ____(TestVersioning, unittest.TestCase):
pass
| TestVersioningUnittest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 276027,
"end": 277346
} | class ____(
ConditionalValueDefstringnullExprRef
):
"""
ConditionalPredicateValueDefstringnullExprRef schema wrapper.
Parameters
----------
test : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :class:... | ConditionalPredicateValueDefstringnullExprRef |
python | tiangolo__fastapi | docs_src/security/tutorial003_an.py | {
"start": 968,
"end": 2571
} | class ____(User):
hashed_password: str
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
def fake_decode_token(token):
# This doesn't provide any security at all
# Check the next version
user = get_user(fake_users_db, token)... | UserInDB |
python | mitmproxy__pdoc | test/testdata/demopackage/child_c.py | {
"start": 46,
"end": 175
} | class ____(child_b.B):
"""This class is defined in .child_c and inherits from .child_b.B."""
def c(self):
return 2
| C |
python | python-pillow__Pillow | src/PIL/Jpeg2KImagePlugin.py | {
"start": 7899,
"end": 13932
} | class ____(ImageFile.ImageFile):
format = "JPEG2000"
format_description = "JPEG 2000 (ISO 15444)"
def _open(self) -> None:
sig = self.fp.read(4)
if sig == b"\xff\x4f\xff\x51":
self.codec = "j2k"
self._size, self._mode = _parse_codestream(self.fp)
self._pa... | Jpeg2KImageFile |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/batch_apis.py | {
"start": 1837,
"end": 2050
} | class ____(TypedDict, total=False):
"""Represent the parameters of ``is_authorized_variable`` API in the auth manager."""
method: ResourceMethod
details: VariableDetails | None
| IsAuthorizedVariableRequest |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 3596,
"end": 5652
} | class ____(test_lib.TestCase, parameterized.TestCase):
def _softmax(self, x):
assert len(x.shape) == 2
if x.shape[1] == 0:
return x
m = x.max(1)[:, np.newaxis]
u = np.exp(x - m)
z = u.sum(1)[:, np.newaxis]
return u / z
def testSoftmax(self):
x_shape = [5, 10]
x_np = np.random... | SoftmaxTest |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 1751,
"end": 1970
} | class ____(analytics.Event):
organization_id: int
project_id: int
user_id: int | None = None
artifact_count: int
@analytics.eventclass("preprod_artifact.api.delete")
| PreprodArtifactApiAdminBatchDeleteEvent |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 35725,
"end": 37148
} | class ____:
""" Comparison numbers are found using R v.1.5.1
note that length(testcase) = 4
"""
testcase = ma.fix_invalid([1,2,3,4,np.nan])
def test_sem(self):
# This is not in R, so used: sqrt(var(testcase)*3/4) / sqrt(3)
y = mstats.sem(self.testcase)
assert_almost_eq... | TestVariability |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.