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 | python__mypy | mypy/types.py | {
"start": 145047,
"end": 145643
} | class ____(TypeTranslator, SyntheticTypeVisitor[Type]):
"""A base class for type translators that need to be run during semantic analysis."""
def visit_placeholder_type(self, t: PlaceholderType, /) -> Type:
return t
def visit_callable_argument(self, t: CallableArgument, /) -> Type:
return ... | TrivialSyntheticTypeTranslator |
python | cython__cython | Cython/Compiler/Tests/TestFlowControl.py | {
"start": 397,
"end": 1783
} | class ____(TestCase):
def test_deepcopy(self):
lhs, rhs = FakeNode(), FakeNode()
entry = FakeEntry()
entry.pos = lhs.pos
name_ass = NameAssignment(lhs, rhs, entry)
ass = deepcopy(name_ass)
self.assertTrue(ass.lhs)
self.assertTrue(ass.rhs)
self.assertT... | TestGraph |
python | django__django | tests/middleware_exceptions/middleware.py | {
"start": 2749,
"end": 2952
} | class ____(BaseMiddleware):
def __call__(self, request):
response = self.get_response(request)
log.append((response.status_code, response.content))
return response
| LogMiddleware |
python | automl__auto-sklearn | autosklearn/util/logging_.py | {
"start": 8116,
"end": 10759
} | class ____(socketserver.StreamRequestHandler):
"""Handler for a streaming logging request.
This basically logs the record using whatever logging policy is
configured locally.
"""
def handle(self) -> None:
"""
Handle multiple requests - each expected to be a 4-byte length,
f... | LogRecordStreamHandler |
python | django-import-export__django-import-export | tests/core/tests/test_tmp_storages.py | {
"start": 3990,
"end": 5191
} | class ____(TestCase):
@override_settings(
STORAGES={
"import_export": {
"BACKEND": "tests.core.tests.test_tmp_storages.CustomizedStorage"
}
}
)
def test_MediaStorage_uses_custom_storage_implementation(self):
tmp_storage = TestMediaStorage()
... | CustomizedMediaStorageTestDjango |
python | vyperlang__vyper | vyper/venom/passes/sccp/sccp.py | {
"start": 627,
"end": 692
} | class ____(Enum):
TOP = 1
BOTTOM = 2
@dataclass
| LatticeEnum |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/ssh.py | {
"start": 388,
"end": 6972
} | class ____(SSHClient):
def __init__(self, client):
self.client = client
def connection_made(self, conn: SSHClientConnection) -> None:
"""Called when a connection is made
This method is called as soon as the TCP connection completes.
The `conn` parameter should be stored if need... | SpyderSSHClient |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_no_skeleton.py | {
"start": 19679,
"end": 21597
} | class ____ { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
}"""
)
assert chunks[1].metadat... | MyClass |
python | pandas-dev__pandas | pandas/tests/io/formats/test_printing.py | {
"start": 2674,
"end": 5558
} | class ____:
def test_adjoin(self):
data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]
expected = "a dd ggg\nb ee hhh\nc ff iii"
adjoined = printing.adjoin(2, *data)
assert adjoined == expected
def test_adjoin_unicode(self):
data = [["あ", "b", "c"... | TestFormatBase |
python | Pylons__pyramid | tests/test_config/test_views.py | {
"start": 109257,
"end": 120343
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.config.views import MultiView
return MultiView
def _makeOne(self, name='name'):
return self._getTargetClass()(name)
def test_class_implements_ISecuredView(self):
from zope.interface.verify import verify... | TestMultiView |
python | donnemartin__interactive-coding-challenges | bit_manipulation/draw_line/test_draw_line.py | {
"start": 18,
"end": 863
} | class ____(unittest.TestCase):
def test_draw_line(self):
bits_screen = BitsScreen()
screen = []
for _ in range(20):
screen.append(int('00000000', base=2))
bits_screen.draw_line(screen, width=32, x1=68, x2=80)
self.assertEqual(screen[8], int('00001111', base=2))
... | TestBitsScreen |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-vowel-strings-in-range.py | {
"start": 38,
"end": 377
} | class ____(object):
def vowelStrings(self, words, left, right):
"""
:type words: List[str]
:type left: int
:type right: int
:rtype: int
"""
VOWELS = {'a', 'e', 'i', 'o', 'u'}
return sum(words[i][0] in VOWELS and words[i][-1] in VOWELS for i in xrange(l... | Solution |
python | Textualize__textual | src/textual/binding.py | {
"start": 1294,
"end": 5594
} | class ____:
"""The configuration of a key binding."""
key: str
"""Key to bind. This can also be a comma-separated list of keys to map multiple keys to a single action."""
action: str
"""Action to bind to."""
description: str = ""
"""Description of action."""
show: bool = True
"""Sho... | Binding |
python | langchain-ai__langchain | libs/partners/ollama/tests/unit_tests/test_auth.py | {
"start": 5881,
"end": 6852
} | class ____:
"""Test URL authentication integration with OllamaLLM."""
@patch("langchain_ollama.llms.Client")
@patch("langchain_ollama.llms.AsyncClient")
def test_ollama_llm_url_auth_integration(
self, mock_async_client: MagicMock, mock_client: MagicMock
) -> None:
"""Test that Ollam... | TestOllamaLLMUrlAuth |
python | rapidsai__cudf | python/cudf/cudf/tests/test_doctests.py | {
"start": 2064,
"end": 3958
} | class ____:
@pytest.fixture(autouse=True)
def printoptions(cls):
# TODO: NumPy now prints scalars as `np.int8(1)`, etc. this should
# be adapted evantually.
if version.parse(np.__version__) >= version.parse("2.0"):
with np.printoptions(legacy="1.25"):
yi... | TestDoctests |
python | jazzband__django-model-utils | tests/test_fields/test_monitor_field.py | {
"start": 3323,
"end": 4089
} | class ____(TestCase):
"""
Monitor should never be updated id when is an empty list.
"""
def setUp(self) -> None:
self.instance = MonitorWhenEmpty(name='Charlie')
self.created = self.instance.name_changed
def test_save_no_change(self) -> None:
self.instance.save()
sel... | MonitorWhenEmptyFieldTests |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_class_configuration.py | {
"start": 383,
"end": 3547
} | 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... | V1beta2DeviceClassConfiguration |
python | doocs__leetcode | solution/0500-0599/0547.Number of Provinces/Solution2.py | {
"start": 0,
"end": 541
} | class ____:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
n = len(isConnected)
p = list(range(n))
ans = n
for i in range(n):
for j in rang... | Solution |
python | joke2k__faker | faker/providers/ssn/sl_SI/__init__.py | {
"start": 42,
"end": 408
} | class ____(BaseProvider):
"""
A Faker provider for the Slovenian VAT IDs
"""
vat_id_formats = ("SI########",)
def vat_id(self) -> str:
"""
http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
:return: a random Slovenian VAT ID
"""
return self.bothify(... | Provider |
python | django-guardian__django-guardian | example_project/posts/migrations/0003_alter_post_id.py | {
"start": 93,
"end": 439
} | class ____(migrations.Migration):
dependencies = [
("posts", "0002_auto_20190629_0848"),
]
operations = [
migrations.AlterField(
model_name="post",
name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID... | Migration |
python | django__django | django/contrib/postgres/apps.py | {
"start": 1989,
"end": 4062
} | class ____(AppConfig):
name = "django.contrib.postgres"
verbose_name = _("PostgreSQL extensions")
def ready(self):
setting_changed.connect(uninstall_if_needed)
# Connections may already exist before we are called.
for conn in connections.all(initialized_only=True):
if co... | PostgresConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataproc.py | {
"start": 2310,
"end": 2441
} | class ____(AirflowException):
"""Raise when resource is not ready for create Dataproc cluster."""
| DataprocResourceIsNotReadyError |
python | ijl__orjson | test/test_dataclass.py | {
"start": 665,
"end": 786
} | class ____:
a: str = field()
b: int = field(metadata={"unrelated": False})
c: float = 1.1
@dataclass
| Dataclass4 |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_not_null_m2m_app/migrations/0002_delete_without_pending.py | {
"start": 190,
"end": 530
} | class ____(CheckedMigration):
dependencies = [
("good_flow_delete_field_pending_with_not_null_m2m_app", "0001_initial"),
]
operations = [
SafeRemoveField(
model_name="testtable",
name="excluded_projects",
deletion_action=DeletionAction.MOVE_TO_PENDING,
... | Migration |
python | apache__airflow | providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py | {
"start": 1025,
"end": 1160
} | class ____(StrictBaseModel):
"""Token serializer for post bodies."""
username: str = Field()
password: str = Field()
| TokenBody |
python | HIPS__autograd | examples/rkhs.py | {
"start": 1069,
"end": 2460
} | class ____(VSpace):
def __init__(self, value):
self.kernel = value.kernel
def zeros(self):
return RKHSFun(self.kernel)
def randn(self):
# These arbitrary vectors are not analogous to randn in any meaningful way
N = npr.randint(1, 3)
return RKHSFun(self.kernel, dict(... | RKHSFunVSpace |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 8080,
"end": 11322
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
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 mu... | RobertaPreLayerNormSelfAttention |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 239152,
"end": 246309
} | class ____(
OrganizationEventsEndpointTestBase, ProfilesSnubaTestCase
):
def test_functions_dataset_simple(self) -> None:
one_hour_ago = before_now(hours=1)
three_hours_ago = before_now(hours=3)
stored_1 = self.store_functions(
[
{
"self_t... | OrganizationEventsProfileFunctionsDatasetEndpointTest |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/vae.py | {
"start": 1231,
"end": 1741
} | class ____(nn.Module):
latents: int = 20
def setup(self):
self.encoder = Encoder(self.latents)
self.decoder = Decoder()
def __call__(self, x, z_rng):
mean, logvar = self.encoder(x)
z = reparameterize(z_rng, mean, logvar)
recon_x = self.decoder(z)
return recon_x, mean, logvar
def gener... | VAE |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 69237,
"end": 69926
} | class ____(WebTestCase):
def get_handlers(self):
# note that if the handlers list is empty we get the default_host
# redirect fallback instead of a 404, so test with both an
# explicitly defined error handler and an implicit 404.
return [("/error", ErrorHandler, dict(status_code=417)... | ErrorHandlerXSRFTest |
python | getsentry__sentry | tests/sentry/hybridcloud/test_organizationmapping.py | {
"start": 8829,
"end": 9477
} | class ____(TransactionTestCase):
def test_replicates_all_flags(self) -> None:
self.organization = self.create_organization(slug="santry", region="us")
self.organization.flags = 255 # all flags set
organization_mapping_service.upsert(
organization_id=self.organization.id,
... | OrganizationMappingReplicationTest |
python | tornadoweb__tornado | demos/google_auth/main.py | {
"start": 1977,
"end": 3151
} | class ____(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
async def get(self):
redirect_uri = urllib.parse.urljoin(
self.application.settings["redirect_base_uri"],
self.reverse_url("google_oauth"),
)
if self.get_argument("code", False):
access = await self.... | LoginHandler |
python | plotly__plotly.py | plotly/graph_objs/barpolar/legendgrouptitle/_font.py | {
"start": 233,
"end": 9932
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.legendgrouptitle"
_path_str = "barpolar.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weig... | Font |
python | pytorch__pytorch | tools/linter/adapters/no_workflows_on_fork.py | {
"start": 1174,
"end": 7054
} | class ____(NamedTuple):
path: str | None
line: int | None
char: int | None
code: str
severity: LintSeverity
name: str
original: str | None
replacement: str | None
description: str | None
def load_yaml(path: Path) -> Any:
with open(path) as f:
return load(f, Loader)
de... | LintMessage |
python | joke2k__faker | faker/providers/job/ar_AA/__init__.py | {
"start": 42,
"end": 2725
} | class ____(BaseProvider):
# Source: https://learnenglish100.com/grammar/career-job/
jobs = (
"أحيائي",
"احصائي",
"اطفائي",
"بائع",
"بائع خضار وفاكهة",
"بائع زهور",
"بائعة",
"بواب",
"تاجر",
"جزار",
"جوھري",
"جيولوجي",... | Provider |
python | huggingface__transformers | src/transformers/models/mask2former/modeling_mask2former.py | {
"start": 106228,
"end": 117183
} | class ____(Mask2FormerPreTrainedModel):
main_input_name = "pixel_values"
def __init__(self, config: Mask2FormerConfig):
super().__init__(config)
self.model = Mask2FormerModel(config)
self.weight_dict: dict[str, float] = {
"loss_cross_entropy": config.class_weight,
... | Mask2FormerForUniversalSegmentation |
python | FactoryBoy__factory_boy | factory/alchemy.py | {
"start": 1601,
"end": 4679
} | class ____(base.Factory):
"""Factory for SQLAlchemy models. """
_options_class = SQLAlchemyOptions
_original_params = None
class Meta:
abstract = True
@classmethod
def _generate(cls, strategy, params):
# Original params are used in _get_or_create if it cannot build an
... | SQLAlchemyModelFactory |
python | getsentry__sentry | src/sentry/toolbar/views/login_success_view.py | {
"start": 275,
"end": 840
} | class ____(OrganizationView):
def get(self, request: HttpRequest, organization, project_id_or_slug):
delay_ms = int(request.GET.get("delay") or 3000)
return self.respond(
TEMPLATE,
status=200,
context={
"organization_slug": organization.slug,
... | LoginSuccessView |
python | scrapy__scrapy | scrapy/signalmanager.py | {
"start": 240,
"end": 3665
} | class ____:
def __init__(self, sender: Any = dispatcher.Anonymous):
self.sender: Any = sender
def connect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
"""
Connect a receiver function to a signal.
The signal can be any object, although Scrapy comes with some
... | SignalManager |
python | plotly__plotly.py | plotly/graph_objs/scattergl/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8559
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergl.marker.colorbar"
_path_str = "scattergl.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], wher... | Tickformatstop |
python | pypa__pipenv | pipenv/vendor/packaging/_manylinux.py | {
"start": 2316,
"end": 9586
} | class ____(NamedTuple):
major: int
minor: int
def _glibc_version_string_confstr() -> str | None:
"""
Primary implementation of glibc_version_string using os.confstr.
"""
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is us... | _GLibCVersion |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict1.py | {
"start": 1254,
"end": 1623
} | class ____(NotATD, TypedDict):
pass
# This should generate an error because TypedDict can't
# be used in a type annotation.
v1: TypedDict | int
# This should generate an error because TypedDict can't
# be used in a TypeVar bound.
T = TypeVar("T", bound=TypedDict | int)
# This should generate an error because T... | TD7 |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 21977,
"end": 23895
} | class ____(nn.Module):
"""Collection of expert weights stored as 3D tensors."""
def __init__(self, config: MiniMaxConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.intermediate_size
... | MiniMaxExperts |
python | langchain-ai__langchain | libs/standard-tests/langchain_tests/integration_tests/base_store.py | {
"start": 5620,
"end": 11225
} | class ____(BaseStandardTests, Generic[V]):
"""Test suite for checking the key-value API of a `BaseStore`.
This test suite verifies the basic key-value API of a `BaseStore`.
The test suite is designed for synchronous key-value stores.
Implementers should subclass this test suite and provide a fixture
... | BaseStoreAsyncTests |
python | getsentry__sentry | src/sentry/identity/vsts/provider.py | {
"start": 9197,
"end": 9679
} | class ____(OAuth2CallbackView):
def get_access_token(self, pipeline: IdentityPipeline, code: str) -> Response:
data = self.get_token_params(
code=code, redirect_uri=absolute_uri(pipeline.config.get("redirect_url"))
)
headers = {
"Content-Type": "application/x-www-form... | VSTSNewOAuth2CallbackView |
python | dask__distributed | distributed/deploy/ssh.py | {
"start": 984,
"end": 5779
} | class ____(Process):
"""A Remote Dask Worker controlled by SSH
Parameters
----------
scheduler: str
The address of the scheduler
address: str
The hostname where we should run this worker
worker_class: str
The python class to use to create the worker.
connect_options:... | Worker |
python | walkccc__LeetCode | solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py | {
"start": 0,
"end": 356
} | class ____:
def numSmallerByFrequency(
self,
queries: list[str],
words: list[str],
) -> list[int]:
ans = []
wordsFreq = sorted([word.count(min(word)) for word in words])
for q in queries:
count = q.count(min(q))
index = bisect.bisect(wordsFreq, count)
ans.append(len(... | Solution |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 788,
"end": 892
} | class ____(BaseModel):
class Config:
extra = 'forbid'
ForbidExtraModel(x=1)
| ForbidExtraModel |
python | getsentry__sentry | src/sentry/rules/age.py | {
"start": 79,
"end": 243
} | class ____(StrEnum):
OLDEST = "oldest"
NEWEST = "newest"
model_age_choices = [(ModelAgeType.OLDEST, "oldest"), (ModelAgeType.NEWEST, "newest")]
| ModelAgeType |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 93312,
"end": 109736
} | class ____(TestParforsBase):
"""
Tests miscellaneous parts of ParallelAccelerator use.
"""
def test_no_warn_if_cache_set(self):
def pyfunc():
arr = np.ones(100)
for i in prange(arr.size):
arr[i] += i
return arr
cfunc = njit(parallel=T... | TestParforsMisc |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_campaign_manager.py | {
"start": 10280,
"end": 11326
} | class ____:
@mock.patch(
"airflow.providers.google.marketing_platform.operators.campaign_manager.GoogleCampaignManagerHook"
)
@mock.patch("airflow.providers.google.marketing_platform.operators.campaign_manager.BaseOperator")
def test_execute(self, mock_base_op, hook_mock):
op = GoogleCam... | TestGoogleCampaignManagerBatchInsertConversionsOperator |
python | pypa__twine | twine/exceptions.py | {
"start": 657,
"end": 759
} | class ____(Exception):
"""Base class for all exceptions raised by twine."""
pass
| TwineException |
python | allegroai__clearml | clearml/backend_config/bucket_config.py | {
"start": 14752,
"end": 17813
} | class ____(object):
def __init__(
self,
container_configs: List[AzureContainerConfig] = None,
default_account: str = None,
default_key: str = None,
) -> None:
super(AzureContainerConfigurations, self).__init__()
self._container_configs = container_configs or []
... | AzureContainerConfigurations |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 38398,
"end": 38833
} | class ____(DelegatingLexer):
"""
Subclass of `PhpLexer` which highlights unmatched data with the `CssLexer`.
"""
name = 'CSS+PHP'
aliases = ['css+php']
alias_filenames = ['*.css']
mimetypes = ['text/css+php']
def __init__(self, **options):
super(CssPhpLexer, self).__init__(CssL... | CssPhpLexer |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 13962,
"end": 14110
} | class ____(nodes.Element):
"""Inserted to set the highlight language and line number options for
subsequent code blocks.
"""
| highlightlang |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 2112,
"end": 2229
} | class ____(SingleClass):
def __eq__(self, other):
return True
__hash__ = SingleClass.__hash__
| ChildClass |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 26450,
"end": 26811
} | class ____(RequestHandler):
def prepare(self):
self.finish(
dict(
default=self.get_arguments("foo"),
query=self.get_query_arguments("foo"),
body=self.get_body_arguments("foo"),
)
)
# This test was shared with wsgi_test.py; now... | GetArgumentsHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/function10.py | {
"start": 250,
"end": 281
} | class ____:
prop1: str
| Thing1 |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/rule.py | {
"start": 276,
"end": 4613
} | class ____(JupyterMixin):
"""A console renderable to draw a horizontal rule (line).
Args:
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
characters (str, optional): Character(s) used to draw the line. Defaults to "─".
style (StyleType, optional): Style o... | Rule |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/resource.py | {
"start": 6665,
"end": 14194
} | class ____(StateBackedDefinitionsLoader[Mapping[str, Any]]):
looker_resource: LookerResource
translator: DagsterLookerApiTranslator
looker_filter: LookerFilter
@property
def defs_key(self) -> str:
return f"{LOOKER_RECONSTRUCTION_METADATA_KEY_PREFIX}/{self.looker_resource.client_id}"
de... | LookerApiDefsLoader |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py | {
"start": 1201,
"end": 22230
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`RTDetrV2Model`]. It is used to instantiate a
RT-DETR model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar conf... | RTDetrV2Config |
python | kubernetes-client__python | kubernetes/client/models/v1_cinder_persistent_volume_source.py | {
"start": 383,
"end": 7145
} | 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... | V1CinderPersistentVolumeSource |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 37728,
"end": 48870
} | class ____(Extension):
"""Add auto link and link transformation extensions to Markdown class."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'hide_protocol': [
False,
"If 'True', links are displayed without the initial ftp:... | MagiclinkExtension |
python | pytest-dev__pytest | src/_pytest/_io/pprint.py | {
"start": 1815,
"end": 19622
} | class ____:
def __init__(
self,
indent: int = 4,
width: int = 80,
depth: int | None = None,
) -> None:
"""Handle pretty printing operations onto a stream using a set of
configured parameters.
indent
Number of spaces to indent for each level of... | PrettyPrinter |
python | bokeh__bokeh | src/bokeh/models/annotations/labels.py | {
"start": 6579,
"end": 9667
} | class ____(DataAnnotation):
''' Render multiple text labels as annotations.
``LabelSet`` will render multiple text labels at given ``x`` and ``y``
coordinates, which can be in either screen (pixel) space, or data (axis
range) space. In this case (as opposed to the single ``Label`` model),
``x`` and... | LabelSet |
python | walkccc__LeetCode | solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py | {
"start": 0,
"end": 501
} | class ____:
def maximumSubarraySum(self, nums: list[int], k: int) -> int:
ans = 0
summ = 0
distinct = 0
count = collections.Counter()
for i, num in enumerate(nums):
summ += num
count[num] += 1
if count[num] == 1:
distinct += 1
if i >= k:
count[nums[i - k]] ... | Solution |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/inspection_inspect.py | {
"start": 488,
"end": 606
} | class ____(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str]
| A |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_isomorphvf2.py | {
"start": 4252,
"end": 14484
} | class ____:
@classmethod
def setup_class(cls):
global atlas
from networkx.generators import atlas
cls.GAG = atlas.graph_atlas_g()
def test_graph_atlas(self):
rng = random.Random(42)
# Atlas = nx.graph_atlas_g()[0:208] # 208, 6 nodes or less
Atlas = self.GAG[... | TestAtlas |
python | django__django | tests/delete_regress/models.py | {
"start": 3134,
"end": 3221
} | class ____(models.Model):
name = models.CharField(max_length=64, unique=True)
| OrgUnit |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 10039,
"end": 10703
} | class ____(_IntegerType, sqltypes.BIGINT):
"""MySQL BIGINTEGER type."""
__visit_name__ = "BIGINT"
def __init__(self, display_width: Optional[int] = None, **kw: Any):
"""Construct a BIGINTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned:... | BIGINT |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 17850,
"end": 19241
} | class ____:
param_names = ["value_type", "shape", "limit"]
params = [
["scalar", "dict", "DataFrame", "Series"],
get_benchmark_shapes("TimeFillnaDataFrame"),
[None, 0.8],
]
def setup(self, value_type, shape, limit):
self.df = gen_nan_data(*shape)
columns = self.d... | TimeFillnaDataFrame |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/source.py | {
"start": 2262,
"end": 2922
} | class ____(BraintreeExtractor):
"""
Extractor for Merchant Accounts stream.
It parses output XML and finds all `Merchant Account` occurrences in it.
"""
def extract_records(
self,
response: requests.Response,
) -> List[Record]:
data = XmlUtil.dict_from_xml(response.text)... | MerchantAccountExtractor |
python | scrapy__scrapy | tests/test_core_downloader.py | {
"start": 3199,
"end": 4257
} | class ____(TestContextFactoryBase):
@deferred_f_from_coro_f
async def testPayload(self, server_url: str) -> None:
s = "0123456789" * 10
crawler = get_crawler()
settings = Settings()
client_context_factory = load_context_factory_from_settings(settings, crawler)
body = awai... | TestContextFactory |
python | wandb__wandb | wandb/agents/pyagent.py | {
"start": 13585,
"end": 14279
} | class ____(Exception):
"""Exception raised when a job fails during execution."""
pass
def _get_exception_logger_and_term_strs(exc):
if isinstance(exc, _JobError) and exc.__cause__:
# If it's a JobException, get the original exception for display
job_exc = exc.__cause__
log_str = _... | _JobError |
python | huggingface__transformers | src/transformers/models/nanochat/modeling_nanochat.py | {
"start": 12099,
"end": 12700
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
self.fc2 = nn.Linear(config.intermediate_size, config.hidde... | NanoChatMLP |
python | sphinx-doc__sphinx | sphinx/ext/apidoc/_shared.py | {
"start": 990,
"end": 1909
} | class ____:
"""Options for apidoc."""
dest_dir: Path
module_path: Path
exclude_pattern: Sequence[str] = ()
max_depth: int = 4
follow_links: bool = False
separate_modules: bool = False
include_private: bool = False
toc_file: str = 'modules'
no_headings: bool = False
module_f... | ApidocOptions |
python | python-poetry__poetry | src/poetry/inspection/lazy_wheel.py | {
"start": 17210,
"end": 29798
} | class ____(LazyFileOverHTTP):
"""File-like object mapped to a ZIP file over HTTP.
This uses HTTP range requests to lazily fetch the file's content, which should be
provided as the first argument to a ``ZipFile``.
"""
# Cache this on the type to avoid trying and failing our initial lazy wheel reque... | LazyWheelOverHTTP |
python | Netflix__metaflow | test/core/tests/card_component_refresh_test.py | {
"start": 72,
"end": 7321
} | class ____(MetaflowTest):
"""
This test will validates the card component API based for runtime updates.
"""
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach... | CardComponentRefreshTest |
python | conda__conda | conda/core/path_actions.py | {
"start": 41147,
"end": 41951
} | class ____(PathAction):
def __init__(self, transaction_context, target_prefix):
self.transaction_context = transaction_context
self.target_prefix = target_prefix
self._execute_successful = False
def verify(self):
self._verified = True
def execute(self):
log.log(TRA... | UnregisterEnvironmentLocationAction |
python | getsentry__sentry | src/sentry/sentry_apps/metrics.py | {
"start": 2538,
"end": 4545
} | class ____(StrEnum):
"""Events/features that Sentry Apps can do"""
# event webhooks
ERROR_CREATED = "error.created"
ISSUE_CREATED = "issue.created"
# issue alert webhooks
EVENT_ALERT_TRIGGERED = "event_alert.triggered"
# external request webhooks
EXTERNAL_ISSUE_CREATED = "external_iss... | SentryAppEventType |
python | kamyu104__LeetCode-Solutions | Python/jump-game-viii.py | {
"start": 46,
"end": 634
} | class ____(object):
def minCost(self, nums, costs):
"""
:type nums: List[int]
:type costs: List[int]
:rtype: int
"""
stk1, stk2 = [], []
dp = [float("inf")]*len(nums)
dp[0] = 0
for i in xrange(len(nums)):
while stk1 and nums[stk1[-1... | Solution |
python | doocs__leetcode | solution/1300-1399/1340.Jump Game V/Solution.py | {
"start": 0,
"end": 535
} | class ____:
def maxJumps(self, arr: List[int], d: int) -> int:
@cache
def dfs(i):
ans = 1
for j in range(i - 1, -1, -1):
if i - j > d or arr[j] >= arr[i]:
break
ans = max(ans, 1 + dfs(j))
for j in range(i + 1, n)... | Solution |
python | falconry__falcon | tests/test_httperror.py | {
"start": 7460,
"end": 7581
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPMissingParam('id', code='P1003')
| MissingParamResource |
python | sympy__sympy | sympy/physics/mechanics/tests/test_pathway.py | {
"start": 602,
"end": 5822
} | class ____:
def test_is_pathway_base_subclass(self):
assert issubclass(LinearPathway, PathwayBase)
@staticmethod
@pytest.mark.parametrize(
'args, kwargs',
[
((Point('pA'), Point('pB')), {}),
]
)
def test_valid_constructor(args, kwargs):
pointA, p... | TestLinearPathway |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_resolver.py | {
"start": 6353,
"end": 7242
} | class ____(ResolverBase):
"""Tests to make sure we can override resolve_path correctly."""
def test_resolver_force_language(self):
url = self.resolver.resolve_path(
project=self.pip,
filename="index.html",
language="cz",
)
self.assertEqual(url, "/cz/... | ResolverPathOverrideTests |
python | getsentry__sentry | tests/sentry/rules/processing/test_buffer_processing.py | {
"start": 10430,
"end": 13144
} | class ____(CreateEventTestCase):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.group = self.create_group(self.project)
self.group_two = self.create_group(self.project)
self.group_three = self.create_group(self.project)
self.rule =... | ProcessInBatchesTest |
python | has2k1__plotnine | plotnine/geoms/geom_errorbar.py | {
"start": 461,
"end": 2199
} | class ____(geom):
"""
Vertical interval represented as an errorbar
{usage}
Parameters
----------
{common_parameters}
width : float, default=0.5
Bar width as a fraction of the resolution of the data.
"""
DEFAULT_AES = {
"alpha": 1,
"color": "black",
... | geom_errorbar |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_sphenic_number.py | {
"start": 834,
"end": 1844
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_sphenic_number"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pa... | ColumnValuesToBeValidSphenicNumber |
python | ray-project__ray | python/ray/tests/test_placement_group_2.py | {
"start": 18316,
"end": 20326
} | class ____:
def create_pg(self):
create_pg()
ray.get(f.remote())
a = A.remote()
ray.get(a.create_pg.remote())
# Create 2 pgs to make sure multiple placement groups that belong
# to a single job will be properly cleaned.
create_pg()
create_pg()
ray.shutdown()
"""
run_string_as_driver(driver_code)
... | A |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 10027,
"end": 11900
} | class ____(TestCase):
def test_default_basename(self):
view = ActionViewSet()
view.basename = router.get_default_basename(ActionViewSet)
view.request = None
assert view.reverse_action('list') == '/api/actions/'
assert view.reverse_action('list-action') == '/api/actions/list_... | ReverseActionTests |
python | sdispater__pendulum | src/pendulum/interval.py | {
"start": 737,
"end": 12736
} | class ____(Duration, Generic[_T]):
"""
An interval of time between two datetimes.
"""
def __new__(cls, start: _T, end: _T, absolute: bool = False) -> Self:
if (isinstance(start, datetime) and not isinstance(end, datetime)) or (
not isinstance(start, datetime) and isinstance(end, dat... | Interval |
python | pexpect__pexpect | tests/test_interact.py | {
"start": 1148,
"end": 3990
} | class ____ (PexpectTestCase.PexpectTestCase):
def setUp(self):
super(InteractTestCase, self).setUp()
self.env = env = os.environ.copy()
# Ensure 'import pexpect' works in subprocess interact*.py
if 'PYTHONPATH' in env:
env['PYTHONPATH'] = os.pathsep.join((self.project_di... | InteractTestCase |
python | explosion__spaCy | spacy/lang/fr/__init__.py | {
"start": 424,
"end": 741
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
infixes = TOKENIZER_INFIXES
suffixes = TOKENIZER_SUFFIXES
token_match = TOKEN_MATCH
lex_attr_getters = LEX_ATTRS
syntax_iterators = SYNTAX_ITERATORS
stop_words = STOP_WORDS
| FrenchDefaults |
python | weaviate__weaviate-python-client | weaviate/proto/v1/v52/v1/file_replication_pb2_grpc.py | {
"start": 993,
"end": 3052
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.PauseFileActivity = channel.unary_unary(
'/weaviate.v1.FileReplicationService/Paus... | FileReplicationServiceStub |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 21129,
"end": 22498
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def name(self):
raise NotImplementedError()
@name.setter
def name(self, value):
raise NotImplementedError()
@property
def parent(self):
raise NotImplementedError()
def set_s... | Chart |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 9098,
"end": 19037
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: ModernBertConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
s... | ModernBertRotaryEmbedding |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 8789,
"end": 8835
} | class ____(SqOperator):
pass
| BosonicOperator |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/dynamodb_to_s3.py | {
"start": 1556,
"end": 2367
} | class ____(json.JSONEncoder):
"""Custom json encoder implementation."""
def default(self, obj):
"""Convert decimal objects in a json serializable format."""
if isinstance(obj, Decimal):
return float(obj)
return super().default(obj)
def _convert_item_to_json_bytes(item: dic... | JSONEncoder |
python | pytest-dev__pytest-xdist | src/xdist/workermanage.py | {
"start": 9662,
"end": 9702
} | class ____(enum.Enum):
END = -1
| Marker |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_run.py | {
"start": 892,
"end": 1091
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Run Job Logging link."""
name = "Cloud Run Job Logging"
key = "log_uri"
format_str = "{log_uri}"
| CloudRunJobLoggingLink |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.