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 | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/source.py | {
"start": 1744,
"end": 14837
} | class ____(AbstractSource):
# Skip exceptions on missing streams
raise_exception_on_missing_stream = True
def _validate_and_transform(self, config: Mapping[str, Any]):
config.setdefault("action_breakdowns_allow_empty", False)
if config.get("end_date") == "":
config.pop("end_date... | SourceFacebookMarketing |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 199391,
"end": 227845
} | class ____:
"""Tests 2-samples with K-S various sizes, alternatives, modes."""
def _testOne(self, x1, x2, alternative, expected_statistic, expected_prob,
mode='auto'):
result = stats.ks_2samp(x1, x2, alternative, mode=mode)
expected = np.array([expected_statistic, expected_prob... | TestKSTwoSamples |
python | encode__django-rest-framework | tests/models.py | {
"start": 2545,
"end": 2906
} | class ____(RESTFrameworkModel):
name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources',
verbose_name='Optional target object',
on_dele... | NullableForeignKeySource |
python | joke2k__faker | tests/providers/test_color.py | {
"start": 16102,
"end": 16681
} | class ____:
"""Test bg_BG color provider methods"""
def test_color_name(self, faker, num_samples):
for _ in range(num_samples):
color_name = faker.color_name()
assert isinstance(color_name, str)
assert color_name in BgBgColorProvider.all_colors.keys()
def test_s... | TestBgBg |
python | falconry__falcon | tests/test_request_media.py | {
"start": 1619,
"end": 6341
} | class ____:
def __init__(self, expected_error):
self._expected_error = expected_error
async def on_post(self, req, resp, **kwargs):
with pytest.raises(self._expected_error) as error:
await req.get_media()
self.captured_error = error
@pytest.mark.parametrize(
'media_ty... | ResourceInvalidMediaAsync |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/bigquery.py | {
"start": 1608,
"end": 9801
} | class ____(BaseTrigger):
"""
BigQueryInsertJobTrigger run on the trigger worker to perform insert operation.
:param conn_id: Reference to google cloud connection id
:param job_id: The ID of the job. It will be suffixed with hash of job configuration
:param project_id: Google Cloud Project where th... | BigQueryInsertJobTrigger |
python | pyparsing__pyparsing | tests/test_simple_unit.py | {
"start": 15369,
"end": 16217
} | class ____(PyparsingExpressionTestCase):
# do not make staticmethod
# @staticmethod
def compute_stats_parse_action(t):
# by the time this parse action is called, parsed numeric words
# have been converted to ints by a previous parse action, so
# they can be treated as ints
t[... | TestResultsModifyingParseAction |
python | sqlalchemy__sqlalchemy | test/orm/test_expire.py | {
"start": 60195,
"end": 64146
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"data",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
)
Tab... | LifecycleTest |
python | scrapy__scrapy | scrapy/utils/asyncio.py | {
"start": 7633,
"end": 9025
} | class ____:
"""An universal result for :func:`call_later`, wrapping either
:class:`asyncio.TimerHandle` or :class:`twisted.internet.base.DelayedCall`.
The provided API is close to the :class:`asyncio.TimerHandle` one: there is
no ``active()`` (as there is no such public API in
:class:`asyncio.Timer... | CallLaterResult |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 84499,
"end": 86071
} | class ____:
@pytest.mark.parametrize("stride", [-4, -2, -1, 1, 2, 4])
@pytest.mark.parametrize("dtype", ['f', 'd'])
@pytest.mark.skipif(not sys.platform.startswith('linux'),
reason="np.frexp gives different answers for NAN/INF on windows and linux")
@pytest.mark.xfail(IS_MUSL, re... | TestFRExp |
python | pypa__setuptools | pkg_resources/tests/test_working_set.py | {
"start": 1291,
"end": 8602
} | class ____:
def __init__(self, installable_dists) -> None:
self._installable_dists = installable_dists
def __call__(self, req):
return next(
iter(filter(lambda dist: dist in req, self._installable_dists)), None
)
def parametrize_test_working_set_resolve(*test_list):
id... | FakeInstaller |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring_code_examples_dynamic_line_width.py | {
"start": 8250,
"end": 10301
} | class ____:
def example2():
"""
Regular docstring of class method.
Examples
--------
>>> df = pl.DataFrame(
... {"foo": [1, 2, 3], "bar": [6, 7, 8], "ham": ["a", "b", "c"]}
... )
"""
# See: https://github.com/astral-sh/ruff/issues/9126
def docte... | DoctestExtraIndent2 |
python | tensorflow__tensorflow | third_party/xla/xla/python_api/xla_shape.py | {
"start": 801,
"end": 5042
} | class ____(object):
"""Wraps a xla_data_pb2.ShapeProto message with a convenient Python type.
Provides direct access to the underlying xla_data_pb2.ShapeProto message in
the
message attribute, along with accessor wrappers to the message's fields.
Avoid direct access to .message unless interacting directly wi... | Shape |
python | ray-project__ray | python/ray/experimental/channel/cpu_communicator.py | {
"start": 3351,
"end": 6791
} | class ____(Communicator):
"""
Uses a CPU-based communicator actor instead of an accelerator group like NCCL.
"""
def __init__(self, world_size: int, actor_handles: List["ray.actor.ActorHandle"]):
"""We use the op index to synchronize the sender and receiver at the
communicator actor."""... | CPUCommunicator |
python | patrick-kidger__equinox | equinox/internal/_loop/common.py | {
"start": 10696,
"end": 11863
} | class ____(Module):
# annotation removed because beartype can't handle the forward reference.
_array: Any # Union[Shaped[Array, "..."], _Buffer]
_pred: Bool[Array, ""]
_tag: object = field(static=True)
_makes_false_steps: bool = field(static=True)
def __getitem__(self, item):
return se... | _Buffer |
python | getsentry__sentry | src/sentry/replays/endpoints/project_replay_jobs_delete.py | {
"start": 853,
"end": 1330
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": obj.id,
"dateCreated": obj.date_added,
"dateUpdated": obj.date_updated,
"rangeStart": obj.range_start,
"rangeEnd": obj.range_end,
"environments": ob... | ReplayDeletionJobSerializer |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-resume-screener/llama_index/packs/resume_screener/base.py | {
"start": 1699,
"end": 2701
} | class ____(BaseLlamaPack):
def __init__(
self, job_description: str, criteria: List[str], llm: Optional[LLM] = None
) -> None:
self.reader = PDFReader()
llm = llm or OpenAI(model="gpt-4")
Settings.llm = llm
self.synthesizer = TreeSummarize(output_cls=ResumeScreenerDecisio... | ResumeScreenerPack |
python | getsentry__sentry | src/sentry/api/serializers/models/apiauthorization.py | {
"start": 233,
"end": 1126
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
apps = {
d["id"]: d
for d in serialize({i.application for i in item_list if i.application_id}, user)
}
attrs = {}
for item in item_list:
attrs[item] = {
"appli... | ApiAuthorizationSerializer |
python | doocs__leetcode | solution/0500-0599/0592.Fraction Addition and Subtraction/Solution.py | {
"start": 0,
"end": 617
} | class ____:
def fractionAddition(self, expression: str) -> str:
x, y = 0, 6 * 7 * 8 * 9 * 10
if expression[0].isdigit():
expression = '+' + expression
i, n = 0, len(expression)
while i < n:
sign = -1 if expression[i] == '-' else 1
i += 1
... | Solution |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-yi/llama_index/llms/yi/base.py | {
"start": 1095,
"end": 6467
} | class ____(OpenAI):
"""
Yi LLM.
Examples:
`pip install llama-index-llms-yi`
```python
from llama_index.llms.yi import Yi
# get api key from: https://platform.01.ai/
llm = Yi(model="yi-large", api_key="YOUR_API_KEY")
response = llm.complete("Hi, who are you... | Yi |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_posterization.py | {
"start": 243,
"end": 5167
} | class ____(BaseImagePreprocessingLayer):
"""Reduces the number of bits for each color channel.
**Note:** This layer is safe to use inside a `tf.data` or `grain` pipeline
(independently of which backend you're using).
References:
- [AutoAugment: Learning Augmentation Policies from Data](https://arx... | RandomPosterization |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/activation.py | {
"start": 5031,
"end": 5885
} | class ____(torch.nn.Sigmoid):
r"""This is the quantized equivalent of :class:`~torch.nn.Sigmoid`.
Args:
scale: quantization scale of the output tensor
zero_point: quantization zero point of the output tensor
"""
def __init__(self, output_scale: float, output_zero_point: int):
s... | Sigmoid |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/complete_orm_no_plugin.py | {
"start": 701,
"end": 1260
} | class ____(Base):
__table__ = Table(
"a",
Base.metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
)
__mapper_args__: Mapping[str, Any] = {
"properties": {"bs": relationship("B")}
}
id: Mapped[int]
data: Mapped[str]
bs: "Mapped... | A |
python | pallets__quart | src/quart/wrappers/response.py | {
"start": 2928,
"end": 3607
} | class ____(ResponseBody):
def __init__(self, iterable: AsyncIterable[Any] | Iterable[Any]) -> None:
self.iter: AsyncIterator[Any]
if isinstance(iterable, Iterable):
self.iter = run_sync_iterable(iter(iterable))
else:
self.iter = iterable.__aiter__() # Can't use aiter... | IterableBody |
python | apache__thrift | test/py/TestClient.py | {
"start": 13710,
"end": 13888
} | class ____(MultiplexedOptionalTest):
def get_protocol(self, transport):
return make_pedantic(TBinaryProtocol.TBinaryProtocolFactory().getProtocol(transport))
| BinaryTest |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 22532,
"end": 25541
} | class ____(MobileViTPreTrainedModel):
def __init__(self, config: MobileViTConfig, expand_output: bool = True):
r"""
expand_output (`bool`, *optional*, defaults to `True`):
Whether to expand the output of the model using a 1x1 convolution. If `True`, the model will apply an additional
... | MobileViTModel |
python | walkccc__LeetCode | solutions/2952. Minimum Number of Coins to be Added/2952.py | {
"start": 0,
"end": 510
} | class ____:
# Same as 330. Patching Array
def minimumAddedCoins(self, coins: list[int], target: int) -> int:
ans = 0
i = 0 # coins' index
miss = 1 # the minimum sum in [1, n] we might miss
coins.sort()
while miss <= target:
if i < len(coins) and coins[i] <= miss:
miss += coins[... | Solution |
python | PrefectHQ__prefect | src/prefect/blocks/abstract.py | {
"start": 6085,
"end": 11643
} | class ____(Block, ABC):
"""
An abstract block type that represents a database and
provides an interface for interacting with it.
Blocks that implement this interface have the option to accept
credentials directly via attributes or via a nested `CredentialsBlock`.
Use of a nested credentials bl... | DatabaseBlock |
python | spack__spack | lib/spack/spack/directory_layout.py | {
"start": 13668,
"end": 13853
} | class ____(SpackError):
"""Superclass for directory layout errors."""
def __init__(self, message, long_msg=None):
super().__init__(message, long_msg)
| DirectoryLayoutError |
python | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/core_models.py | {
"start": 2506,
"end": 4124
} | class ____(Resolvable, Model):
type: Literal["static"] = "static"
partition_keys: Sequence[str]
def resolve_partitions_def(context: ResolutionContext, model) -> Optional[PartitionsDefinition]:
if model is None:
return None
elif model.type == "hourly":
return HourlyPartitionsDefinition... | StaticPartitionsDefinitionModel |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/control.py | {
"start": 5388,
"end": 13378
} | class ____:
def __init__(
self,
data: ConjectureData,
*,
is_final: bool = False,
wrapped_test: Callable,
) -> None:
self.data = data
self.tasks: list[Callable[[], Any]] = []
self.is_final = is_final
self.wrapped_test = wrapped_test
... | BuildContext |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 4686,
"end": 4892
} | class ____(ClientConnectorError):
"""DNS resolution failed during client connection.
Raised in :class:`aiohttp.connector.TCPConnector` if
DNS resolution fails.
"""
| ClientConnectorDNSError |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops_test.py | {
"start": 56321,
"end": 56995
} | class ____(test_util.TensorFlowTestCase):
def testCastWithFullType(self):
@def_function.function
def test_fn():
ta = tensor_array_ops.TensorArray(dtypes.int32, size=1)
h = math_ops.cast(ta.flow, dtypes.variant)
t = full_type_pb2.FullTypeDef(
type_id=full_type_pb2.TFT_PRODUCT,
... | CastTest |
python | redis__redis-py | tests/test_retry.py | {
"start": 4425,
"end": 5737
} | class ____:
"Test that Retry calls backoff and retries the expected number of times"
def setup_method(self, test_method):
self.actual_attempts = 0
self.actual_failures = 0
def _do(self):
self.actual_attempts += 1
raise ConnectionError()
def _fail(self, error):
... | TestRetry |
python | davidhalter__jedi | test/completion/pep0484_generic_parameters.py | {
"start": 7397,
"end": 7676
} | class ____(Specialised):
pass
child_of_specialised_instance: ChildOfSpecialised = NotImplemented
#? int()
first(child_of_specialised_instance)
#? str()
values(child_of_specialised_instance)[0]
# Test that unbound generics are inferred as much as possible
| ChildOfSpecialised |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_details.py | {
"start": 2873,
"end": 3364
} | class ____:
def has_scope(self, scope):
# For the "test_as_no_org_read_user" we need a set of scopes that allows GET on the
# OrganizationDetailsEndpoint to allow high-level access, but without "org:read" scope
# to cover that branch with test. The scope "org:write" is a good candidate for t... | MockAccess |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/dock_scroll.py | {
"start": 80,
"end": 531
} | class ____(App):
BINDINGS = [("ctrl+q", "app.quit", "Quit")]
CSS = """
Label {
border: solid red;
}
Footer {
height: 4;
}
"""
def compose(self):
text = (
"this is a sample sentence and here are some words".replace(" ", "\n") * 2
)
... | TestApp |
python | great-expectations__great_expectations | great_expectations/core/batch.py | {
"start": 19836,
"end": 22421
} | class ____(BatchRequestBase):
"""A BatchRequest is the way to specify which data Great Expectations will validate.
A Batch Request is provided to a Datasource in order to create a Batch.
---Documentation---
- https://docs.greatexpectations.io/docs/guides/connecting_to_your_data/how_to_get_one_or_m... | BatchRequest |
python | dask__dask | dask/dataframe/dask_expr/_rolling.py | {
"start": 5394,
"end": 5450
} | class ____(RollingReduction):
how = "kurt"
| RollingKurt |
python | plotly__plotly.py | plotly/graph_objs/layout/smith/_domain.py | {
"start": 235,
"end": 5045
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.smith"
_path_str = "layout.smith.domain"
_valid_props = {"column", "row", "x", "y"}
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this smith subplot .... | Domain |
python | django__django | django/db/models/fields/__init__.py | {
"start": 61073,
"end": 67298
} | class ____(Field):
empty_strings_allowed = False
default_error_messages = {
"invalid": _("“%(value)s” value must be a decimal number."),
}
description = _("Decimal number")
def __init__(
self,
verbose_name=None,
name=None,
max_digits=None,
decimal_pla... | DecimalField |
python | crytic__slither | slither/core/declarations/pragma_directive.py | {
"start": 181,
"end": 1174
} | class ____(SourceMapping):
def __init__(self, directive: List[str], scope: "FileScope") -> None:
super().__init__()
self._directive = directive
self.scope: "FileScope" = scope
self._pattern = "pragma"
@property
def directive(self) -> List[str]:
"""
list(str)
... | Pragma |
python | encode__httpx | httpx/_exceptions.py | {
"start": 2238,
"end": 2845
} | class ____(HTTPError):
"""
Base class for all exceptions that may occur when issuing a `.request()`.
"""
def __init__(self, message: str, *, request: Request | None = None) -> None:
super().__init__(message)
# At the point an exception is raised we won't typically have a request
... | RequestError |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 24451,
"end": 25010
} | class ____(Dir):
def post_validation(self, config: Config, key_name: str):
if not config.config_file_path:
return
# Validate that the dir is not the parent dir of the config file.
if os.path.dirname(config.config_file_path) == config[key_name]:
raise ValidationError(... | DocsDir |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 917,
"end": 1881
} | class ____(PosixCompletionConfig):
"""Pseudo completion config for the origin."""
def __init__(self) -> None:
super().__init__(name='origin')
@property
def supported_pythons(self) -> list[str]:
"""Return a list of the supported Python versions."""
current_version = version_to_s... | OriginCompletionConfig |
python | django__django | tests/delete/tests.py | {
"start": 27653,
"end": 33076
} | class ____(TestCase):
def test_fast_delete_all(self):
with self.assertNumQueries(1) as ctx:
User.objects.all().delete()
sql = ctx.captured_queries[0]["sql"]
# No subqueries is used when performing a full delete.
self.assertNotIn("SELECT", sql)
def test_fast_delete_fk... | FastDeleteTests |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_storage_transfer_service.py | {
"start": 22133,
"end": 31036
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.gct_hook = CloudDataTransferServiceHook(gcp_conn_id="test")
@mock.patch(
... | TestGCPTransferServiceHookWithProjectIdFromConnection |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar21.py | {
"start": 315,
"end": 1660
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar21.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 48535,
"end": 49124
} | class ____(PrefectBaseModel):
healthy: bool = Field(..., description="Whether or not the work queue is healthy.")
late_runs_count: int = Field(
default=0, description="The number of late flow runs in the work queue."
)
last_polled: Optional[DateTime] = Field(
default=None, description="T... | WorkQueueStatusDetail |
python | joke2k__faker | faker/providers/internet/fa_IR/__init__.py | {
"start": 42,
"end": 328
} | class ____(BaseProvider):
safe_email_tlds = ("com", "net", "ir", "org")
free_email_domains = (
"chmail.ir",
"mailfa.com",
"gmail.com",
"hotmail.com",
"yahoo.com",
)
tlds = ("com", "com", "com", "net", "org", "ir", "ir", "ir")
| Provider |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule.py | {
"start": 2460,
"end": 6359
} | class ____(LearningRateSchedule):
"""A `LearningRateSchedule` that uses an exponential decay schedule.
When training a model, it is often useful to lower the learning rate as
the training progresses. This schedule applies an exponential decay function
to an optimizer step, given a provided initial lear... | ExponentialDecay |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/where_op_test.py | {
"start": 1269,
"end": 8394
} | class ____(test.TestCase):
def _testWhere(self, x, truth, expected_err_re=None, fn=array_ops.where):
with self.cached_session():
ans = fn(x)
self.assertTrue(ans.get_shape().is_compatible_with([None, x.ndim]))
if expected_err_re is None:
tf_ans = self.evaluate(ans)
self.assertAll... | WhereOpTest |
python | django__django | tests/requests_tests/tests.py | {
"start": 940,
"end": 1138
} | class ____(MemoryFileUploadHandler):
def handle_raw_input(
self, input_data, META, content_length, boundary, encoding=None
):
return ("_POST", "_FILES")
| CustomFileUploadHandler |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 51744,
"end": 56123
} | class ____(DefinedFunction):
r"""
Andre numbers / Andre function
The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
*alternating permutations* on `n` elements, where a permutation is alternating
if adjacent elements alternately compare "greater" and "smaller" going from
l... | andre |
python | google__jax | tests/custom_api_test.py | {
"start": 118131,
"end": 137684
} | class ____(jtu.JaxTestCase):
def test_basic(self):
@jax.custom_batching.custom_vmap
def f(x): return jnp.sin(x)
@f.def_vmap
def rule(axis_size, in_batched, xs):
xs_batched, = in_batched
self.assertEqual(xs_batched, True)
self.assertEqual(axis_size, xs.shape[0])
return jnp.cos... | CustomVmapTest |
python | getsentry__sentry | src/sentry/incidents/endpoints/bases.py | {
"start": 1447,
"end": 2340
} | class ____(OrganizationEndpoint):
permission_classes = (OrganizationAlertRulePermission,)
def convert_args(
self, request: Request, alert_rule_id: int, *args: Any, **kwargs: Any
) -> tuple[tuple[Any, ...], dict[str, Any]]:
args, kwargs = super().convert_args(request, *args, **kwargs)
... | OrganizationAlertRuleEndpoint |
python | getsentry__sentry | src/sentry/testutils/silo.py | {
"start": 3604,
"end": 4043
} | class ____(Exception):
pass
def _get_test_name_suffix(silo_mode: SiloMode) -> str:
name = silo_mode.name[0].upper() + silo_mode.name[1:].lower()
return f"__In{name}Mode"
def strip_silo_mode_test_suffix(name: str) -> str:
for silo_mode in SiloMode:
suffix = _get_test_name_suffix(silo_mode)
... | SubclassNotSiloDecoratedException |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 34175,
"end": 43201
} | class ____(PreTrainedModel):
config: MllamaConfig
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_no_split_modules = [
"MllamaVisionEncoderLayer",
"MllamaCrossAttentionDecoderLayer",
"MllamaSelfAttentionDecoderLayer",
... | MllamaPreTrainedModel |
python | django__django | tests/test_client_regress/tests.py | {
"start": 29309,
"end": 29899
} | class ____(TestDataMixin, TestCase):
def test_login(self):
"A session engine that modifies the session key can be used to log in"
login = self.client.login(username="testclient", password="password")
self.assertTrue(login, "Could not log in")
# Try to access a login protected page.
... | SessionEngineTests |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent.py | {
"start": 1919,
"end": 6871
} | class ____(BaseModel):
"""Base Single Action Agent class."""
@property
def return_values(self) -> list[str]:
"""Return values of the agent."""
return ["output"]
def get_allowed_tools(self) -> list[str] | None:
"""Get allowed tools."""
return None
@abstractmethod
... | BaseSingleActionAgent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 305020,
"end": 307436
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of StartRepositoryMigration"""
__schema__ = github_schema
__field_names__ = (
"source_id",
"owner_id",
"source_repository_url",
"repository_name",
"continue_on_error",
"git_archive_url",
"meta... | StartRepositoryMigrationInput |
python | django__django | tests/postgres_tests/models.py | {
"start": 2546,
"end": 2645
} | class ____(PostgreSQLModel):
array_of_enums = ArrayField(EnumField(max_length=20))
| ArrayEnumModel |
python | sphinx-doc__sphinx | tests/roots/test-ext-autosummary-ext/underscore_module_.py | {
"start": 52,
"end": 205
} | class ____:
"""Class"""
def method_(_arg): # NoQA: N805
"""Method"""
pass
def function_(_arg):
"""Function"""
pass
| class_ |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/loader.py | {
"start": 2412,
"end": 3162
} | class ____(
Reader,
RoundTripScanner,
RoundTripParser,
Composer,
RoundTripConstructor,
VersionedResolver,
):
def __init__(self, stream, version=None, preserve_quotes=None):
# type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
# self.reader = Reader.__init__... | RoundTripLoader |
python | pikepdf__pikepdf | src/pikepdf/form.py | {
"start": 22371,
"end": 25171
} | class ____(_FieldWrapper):
"""Represents a signature field.
Signatures are not truly supported.
"""
def stamp_overlay(
self,
overlay: Object | Page,
*,
expand_rect: int
| float
| Decimal
| Sequence[int | float | Decimal]
| None = None,
... | SignatureField |
python | dagster-io__dagster | python_modules/libraries/dagster-tableau/dagster_tableau/asset_utils.py | {
"start": 396,
"end": 6370
} | class ____(
namedtuple("_ParsedTableauAssetSpecs", ["external_asset_specs", "materializable_asset_specs"])
):
"""Used to represent the parsed Tableau asset specs
as returned by the `parse_tableau_external_and_materializable_asset_specs` function below.
"""
def __new__(cls, external_asset_specs, mat... | ParsedTableauAssetSpecs |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_skip/compound_one_liners.py | {
"start": 994,
"end": 4395
} | class ____(Generic[T]): pass # fmt: skip
# Try/except blocks
try: risky_operation() # fmt: skip
except ValueError: handle_error() # fmt: skip
except: handle_any_error() # fmt: skip
else: success_case() # fmt: skip
finally: cleanup() # fmt: skip
# Match statements (Python 3.10+)
match value:
case 1: print("o... | GenericClass |
python | crytic__slither | slither/solc_parsing/yul/parse_yul.py | {
"start": 4505,
"end": 6529
} | class ____(metaclass=abc.ABCMeta):
__slots__ = [
"_contract",
"_id",
"_yul_local_variables",
"_yul_local_functions",
"_parent_func",
]
def __init__(
self, contract: Optional[Contract], yul_id: List[str], parent_func: Function
) -> None:
self._cont... | YulScope |
python | doocs__leetcode | solution/3300-3399/3363.Find the Maximum Number of Fruits Collected/Solution.py | {
"start": 0,
"end": 810
} | class ____:
def maxCollectedFruits(self, fruits: List[List[int]]) -> int:
n = len(fruits)
f = [[-inf] * n for _ in range(n)]
f[0][n - 1] = fruits[0][n - 1]
for i in range(1, n):
for j in range(i + 1, n):
f[i][j] = max(f[i - 1][j], f[i - 1][j - 1]) + fruits... | Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/event.py | {
"start": 19912,
"end": 21034
} | class ____(EventSerializer):
def get_attrs(self, item_list, user, **kwargs):
return super().get_attrs(item_list, user, is_public=True, **kwargs)
def serialize(self, obj, attrs, user, **kwargs):
base = super().serialize(obj, attrs, user)
result: dict[str, Any] = {
k: v
... | SharedEventSerializer |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_resource_slice.py | {
"start": 383,
"end": 6872
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta2ResourceSlice |
python | fabric__fabric | fabric/runners.py | {
"start": 6284,
"end": 6392
} | class ____(Remote):
def send_start_message(self, command):
self.channel.invoke_shell()
| RemoteShell |
python | tiangolo__fastapi | docs_src/request_form_models/tutorial002_an.py | {
"start": 124,
"end": 317
} | class ____(BaseModel):
username: str
password: str
model_config = {"extra": "forbid"}
@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
return data
| FormData |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py | {
"start": 69,
"end": 1024
} | class ____(ValidationRule):
__slots__ = 'known_arg_names',
def __init__(self, context):
super(UniqueArgumentNames, self).__init__(context)
self.known_arg_names = {}
def enter_Field(self, node, key, parent, path, ancestors):
self.known_arg_names = {}
def enter_Directive(self, n... | UniqueArgumentNames |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 5495,
"end": 8411
} | class ____(Handler, StringFormatterHandlerMixin):
"""A handler that logs to twitter. Requires that you sign up an
application on twitter and request xauth support. Furthermore the
oauth2 library has to be installed.
.. deprecated:: 1.9
"""
default_format_string = TWITTER_FORMAT_STRING
fo... | TwitterHandler |
python | pytorch__pytorch | test/distributed/_shard/sharded_tensor/ops/test_tensor_ops.py | {
"start": 480,
"end": 4427
} | class ____(ShardedTensorTestBase):
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(TEST_GPU_NUM)
@requires_nccl()
def test_deep_copy(self):
spec = ChunkShardingSpec(
dim=0,
placements=[
"rank:0/cuda:0",
"rank:1/cuda:1",
"rank:... | TestTensorOps |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/urlfetch/snippets/main.py | {
"start": 965,
"end": 1438
} | class ____(webapp2.RequestHandler):
"""Demonstrates an HTTP query using urllib2."""
def get(self):
# [START gae_urlfetch_snippets_urllib2_get]
url = "http://www.google.com/humans.txt"
try:
result = urllib2.urlopen(url)
self.response.write(result.read())
e... | UrlLibFetchHandler |
python | tensorflow__tensorflow | tensorflow/python/training/warm_starting_util_test.py | {
"start": 1554,
"end": 57893
} | class ____(test.TestCase):
def _write_vocab(self, string_values, file_name):
vocab_file = os.path.join(self.get_temp_dir(), file_name)
with open(vocab_file, "w") as f:
f.write("\n".join(string_values))
return vocab_file
def _write_checkpoint(self, sess):
self.evaluate(variables.global_variab... | WarmStartingUtilTest |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/text.py | {
"start": 2976,
"end": 47561
} | class ____(JupyterMixin):
"""Text with color / style.
Args:
text (str, optional): Default unstyled text. Defaults to "".
style (Union[str, Style], optional): Base style for text. Defaults to "".
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None... | Text |
python | walkccc__LeetCode | solutions/3512. Minimum Operations to Make Array Sum Divisible by K/3512.py | {
"start": 0,
"end": 100
} | class ____:
def minOperations(self, nums: list[int], k: int) -> int:
return sum(nums) % k
| Solution |
python | apache__airflow | providers/dbt/cloud/tests/unit/dbt/cloud/operators/test_dbt.py | {
"start": 3796,
"end": 27275
} | class ____:
def setup_method(self):
self.dag = DAG("test_dbt_cloud_job_run_op", schedule=None, start_date=DEFAULT_DATE)
self.mock_ti = MagicMock()
self.mock_context = {"ti": self.mock_ti}
self.config = {
"job_id": JOB_ID,
"check_interval": 1,
"time... | TestDbtCloudRunJobOperator |
python | django__django | tests/template_tests/filter_tests/test_default.py | {
"start": 165,
"end": 1339
} | class ____(SimpleTestCase):
"""
Literal string arguments to the default filter are always treated as
safe strings, regardless of the auto-escaping state.
Note: we have to use {"a": ""} here, otherwise the invalid template
variable string interferes with the test result.
"""
@setup({"defaul... | DefaultTests |
python | getsentry__sentry | src/sentry/notifications/platform/templates/sample.py | {
"start": 558,
"end": 868
} | class ____(NotificationData):
source = "error-alert-service"
error_type: str
error_message: str
project_name: str
issue_id: str
error_count: int
first_seen: str
chart_url: str
issue_url: str
assign_url: str
@template_registry.register(ErrorAlertData.source)
| ErrorAlertData |
python | huggingface__transformers | tests/models/rembert/test_modeling_rembert.py | {
"start": 13362,
"end": 17253
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
RemBertModel,
RemBertForMaskedLM,
RemBertForCausalLM,
RemBertForMultipleChoice,
RemBertForQuestionAnswering,
RemBertForSequenceClassification,... | RemBertModelTest |
python | walkccc__LeetCode | solutions/2761. Prime Pairs With Target Sum/2761.py | {
"start": 0,
"end": 491
} | class ____:
def findPrimePairs(self, n: int) -> list[list[int]]:
isPrime = self._sieveEratosthenes(n + 1)
return [[i, n - i] for i in range(2, n // 2 + 1)
if isPrime[i] and isPrime[n - i]]
def _sieveEratosthenes(self, n: int) -> list[bool]:
isPrime = [True] * n
isPrime[0] = False
is... | Solution |
python | django__django | tests/auth_tests/models/with_unique_constraint.py | {
"start": 104,
"end": 355
} | class ____(BaseUserManager):
def create_superuser(self, username, password):
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
| CustomUserWithUniqueConstraintManager |
python | fsspec__filesystem_spec | fsspec/implementations/cached.py | {
"start": 961,
"end": 1326
} | class ____(Transaction):
def complete(self, commit=True):
rpaths = [f.path for f in self.files]
lpaths = [f.fn for f in self.files]
if commit:
self.fs.put(lpaths, rpaths)
self.files.clear()
self.fs._intrans = False
self.fs._transaction = None
self.... | WriteCachedTransaction |
python | astropy__astropy | astropy/time/formats.py | {
"start": 22268,
"end": 25732
} | class ____(TimeNumeric):
"""
Time as a decimal year, with integer values corresponding to midnight of the first
day of each year.
The fractional part represents the exact fraction of the year, considering the
precise number of days in the year (365 or 366). The following example shows
essential... | TimeDecimalYear |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_queried_column_pair_values_to_be_both_filled_or_null.py | {
"start": 485,
"end": 6137
} | class ____(QueryExpectation):
"""Expect the values of a pair of columns to be either both filled or empty simultaneously.
It checks if 2 columns are aligned - the values of each row need to either be both empty or filled.
The expectation will fail if there's at least one row where one column is filled an... | ExpectQueriedColumnPairValuesToBeBothFilledOrNull |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 1572,
"end": 3250
} | class ____:
NANFUNCS = {
np.nanmin: np.amin,
np.nanmax: np.amax,
np.nanargmin: np.argmin,
np.nanargmax: np.argmax,
np.nansum: np.sum,
np.nanprod: np.prod,
np.nancumsum: np.cumsum,
np.nancumprod: np.cumprod,
np.nanmean: np.mean,
np.nanme... | TestSignatureMatch |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/freshness.py | {
"start": 11009,
"end": 12520
} | class ____(LoadableBy[AssetKey]):
entity_key: AssetKey
freshness_state: FreshnessState
updated_at: datetime
record_body: FreshnessStateRecordBody
@staticmethod
def from_db_row(db_row):
return FreshnessStateRecord(
entity_key=check.not_none(AssetKey.from_db_string(db_row.enti... | FreshnessStateRecord |
python | openai__openai-python | src/openai/resources/responses/responses.py | {
"start": 2369,
"end": 78774
} | class ____(SyncAPIResource):
@cached_property
def input_items(self) -> InputItems:
return InputItems(self._client)
@cached_property
def input_tokens(self) -> InputTokens:
return InputTokens(self._client)
@cached_property
def with_raw_response(self) -> ResponsesWithRawResponse:
... | Responses |
python | google__jax | jax/_src/sharding_impls.py | {
"start": 18075,
"end": 18265
} | class ____(NamedTuple):
"""Represents a pmap mesh (only along the replica axes)."""
nreps: int
names: tuple[Any, ...]
sizes: tuple[int, ...]
@dataclasses.dataclass(frozen=True)
| AxisEnv |
python | walkccc__LeetCode | solutions/3094. Guess the Number Using Bitwise Questions II/3094.py | {
"start": 68,
"end": 305
} | class ____:
def findNumber(self) -> int:
ans = 0
sameCount = commonBits(0)
for i in range(31):
if commonBits(1 << i) > sameCount:
ans |= 1 << i
commonBits(1 << i) # Revert the XOR.
return ans
| Solution |
python | realpython__materials | python-class/crafts.py | {
"start": 0,
"end": 412
} | class ____:
def __init__(self, make, model, color):
self.make = make
self.model = model
self.color = color
def start(self):
print("Starting the engine...")
def stop(self):
print("Stopping the engine...")
def show_technical_specs(self):
print(f"Make: {se... | Vehicle |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 21043,
"end": 22866
} | class ____:
def __init__(self, value: int, next_node: typing.Optional["SomeClass"]) -> None:
assert value > 0
self.value = value
self.next_node = next_node
def __repr__(self) -> str:
return f"SomeClass({self.value}, next_node={self.next_node})"
def test_resolving_recursive_typ... | SomeClass |
python | walkccc__LeetCode | solutions/3169. Count Days Without Meetings/3169.py | {
"start": 0,
"end": 304
} | class ____:
def countDays(self, days: int, meetings: list[list[int]]) -> int:
freeDays = 0
prevEnd = 0
for start, end in sorted(meetings):
if start > prevEnd:
freeDays += start - prevEnd - 1
prevEnd = max(prevEnd, end)
return freeDays + max(0, days - prevEnd)
| Solution |
python | PyCQA__pylint | tests/functional/ext/no_self_use/no_self_use.py | {
"start": 2302,
"end": 2569
} | class ____:
def a(self, /): # [no-self-use]
...
# Disable with old error code
# pylint: disable=use-symbolic-message-instead
def b(self, /): # pylint: disable=R0201
...
def func_a(self): # pylint: disable=unused-argument
pass
| C |
python | getsentry__sentry | src/sentry/search/events/builder/errors.py | {
"start": 6254,
"end": 7118
} | class ____(ErrorsQueryBuilderMixin, TopEventsQueryBuilder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def time_column(self) -> SelectType:
return Column("time", entity=Entity(self.dataset.value, alias=self.dataset.value))
def get_snql_query(self) ... | ErrorsTopEventsQueryBuilder |
python | matplotlib__matplotlib | lib/matplotlib/scale.py | {
"start": 21633,
"end": 25122
} | class ____(ScaleBase):
"""
A quasi-logarithmic scale based on the inverse hyperbolic sine (asinh)
For values close to zero, this is essentially a linear scale,
but for large magnitude values (either positive or negative)
it is asymptotically logarithmic. The transition between these
linear and ... | AsinhScale |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.