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 | walkccc__LeetCode | solutions/2714. Find Shortest Path with K Hops/2714.py | {
"start": 0,
"end": 1172
} | class ____:
# Similar to 787. Cheapest Flights Within K Stops
def shortestPathWithHops(
self,
n: int,
edges: list[list[int]],
s: int,
d: int,
k: int,
) -> int:
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, ... | Solution |
python | dagster-io__dagster | examples/project_analytics/dagster_pypi/resources.py | {
"start": 942,
"end": 1321
} | class ____(PyPiResource):
input_file: str = Field(description="Path to the sample pypi input file")
def get_pypi_download_counts(self, date) -> pd.DataFrame:
print("Pretending to fetch for a given date: ", date)
df = pd.read_csv(self.input_file)
df["download_date"] = datetime.datetime.s... | PyPiLocalResource |
python | Textualize__textual | docs/examples/widgets/progress_bar_isolated.py | {
"start": 171,
"end": 1047
} | class ____(App[None]):
BINDINGS = [("s", "start", "Start")]
progress_timer: Timer
"""Timer to simulate progress happening."""
def compose(self) -> ComposeResult:
with Center():
with Middle():
yield ProgressBar()
yield Footer()
def on_mount(self) -> None... | IndeterminateProgressBar |
python | kamyu104__LeetCode-Solutions | Python/sum-of-consecutive-subsequences.py | {
"start": 94,
"end": 746
} | class ____(object):
def getSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def count(d):
result = 0
cnt = collections.defaultdict(int)
prefix = collections.defaultdict(int)
for x in nums:
c = (cnt[x-d]... | Solution |
python | sphinx-doc__sphinx | sphinx/domains/python/__init__.py | {
"start": 1699,
"end": 1823
} | class ____(NamedTuple):
docname: str
node_id: str
synopsis: str
platform: str
deprecated: bool
| ModuleEntry |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 837506,
"end": 839069
} | class ____(sgqlc.types.Type):
"""A curatable list of repositories relating to a repository owner,
which defaults to showing the most popular repositories they own.
"""
__schema__ = github_schema
__field_names__ = ("has_pinned_items", "items")
has_pinned_items = sgqlc.types.Field(sgqlc.types.non... | ProfileItemShowcase |
python | pola-rs__polars | py-polars/src/polars/_utils/udfs.py | {
"start": 1483,
"end": 10357
} | class ____:
BINARY: ClassVar[dict[str, str]] = {
"BINARY_ADD": "+",
"BINARY_AND": "&",
"BINARY_FLOOR_DIVIDE": "//",
"BINARY_LSHIFT": "<<",
"BINARY_RSHIFT": ">>",
"BINARY_MODULO": "%",
"BINARY_MULTIPLY": "*",
"BINARY_OR": "|",
"BINARY_POWER": "*... | OpNames |
python | skorch-dev__skorch | skorch/hf.py | {
"start": 29739,
"end": 42162
} | class ____:
"""Mixin class to add support for Hugging Face accelerate
This is an *experimental* feature.
Use this mixin class with one of the neural net classes (e.g. ``NeuralNet``,
``NeuralNetClassifier``, or ``NeuralNetRegressor``) and pass an instance of
``Accelerator`` for mixed precision, mul... | AccelerateMixin |
python | huggingface__transformers | src/transformers/models/kosmos2_5/modeling_kosmos2_5.py | {
"start": 68900,
"end": 75303
} | class ____(Kosmos2_5PreTrainedModel):
config_class = Kosmos2_5TextConfig
input_modalities = ("text",)
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config: Kosmos2_5TextConfig):
super().__init__(config)
self.model = Kosmos2_5TextTransformer(con... | Kosmos2_5TextForCausalLM |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/serdes/serdes.py | {
"start": 27782,
"end": 29256
} | class ____(ObjectSerializer[T_NamedTuple]):
def object_as_mapping(self, value: T_NamedTuple) -> Mapping[str, Any]:
if is_record(value):
return as_dict_for_new(value)
# Value is always a NamedTuple, we just can't express that in the type of T_NamedTuple.
return value._asdict() #... | NamedTupleSerializer |
python | fastai__fastai | fastai/data/core.py | {
"start": 8293,
"end": 12395
} | class ____(GetAttr):
"Basic wrapper around several `DataLoader`s."
_default='train'
def __init__(self,
*loaders, # `DataLoader` objects to wrap
path:str|Path='.', # Path to store export objects
device=None # Device to put `DataLoaders`
):
self.loaders,self.path = list(lo... | DataLoaders |
python | getsentry__sentry | tests/sentry/api/endpoints/test_system_options.py | {
"start": 213,
"end": 5344
} | class ____(APITestCase):
url = reverse("sentry-api-0-system-options")
def test_without_superuser(self) -> None:
self.login_as(user=self.user, superuser=False)
response = self.client.get(self.url)
assert response.status_code == 403
def test_simple(self) -> None:
self.login_a... | SystemOptionsTest |
python | python__mypy | mypy/moduleinspect.py | {
"start": 234,
"end": 1306
} | class ____:
# Note that all __init__ args must have default values
def __init__(
self,
name: str = "",
file: str | None = None,
path: list[str] | None = None,
all: list[str] | None = None,
is_c_module: bool = False,
subpackages: list[str] | None = None,
... | ModuleProperties |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_compute_log_manager.py | {
"start": 6244,
"end": 6574
} | class ____(TestComputeLogManager):
__test__ = True
@pytest.fixture(name="compute_log_manager")
def compute_log_manager(self): # pyright: ignore[reportIncompatibleMethodOverride]
with tempfile.TemporaryDirectory() as tmpdir_path:
return LocalComputeLogManager(tmpdir_path)
| TestLocalComputeLogManager |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_search_tool_result_block_param.py | {
"start": 454,
"end": 803
} | class ____(TypedDict, total=False):
content: Required[BetaWebSearchToolResultBlockParamContentParam]
tool_use_id: Required[str]
type: Required[Literal["web_search_tool_result"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
| BetaWebSearchToolResultBlockParam |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 84482,
"end": 85421
} | class ____(UserFunctionVariable):
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if not kwargs and len(args) == 1:
def wraps(fn: Any) -> VariableTracker:
... | FunctoolsWrapsVariable |
python | PrefectHQ__prefect | src/prefect/_experimental/sla/objects.py | {
"start": 1995,
"end": 2491
} | class ____(ServiceLevelAgreement):
"""An SLA that triggers when a flow run does not start within the specified window.
For example, if you schedule the deployment to run every day at 2:00pm and you pass
within=timedelta(minutes=10) to this SLA, if a run hasn't started by 2:10pm the SLA
violation will b... | LatenessSla |
python | numba__numba | numba/core/typing/context.py | {
"start": 5428,
"end": 6332
} | class ____(object):
"""
A compile-time call frame
"""
def __init__(self, target, typeinfer, func_id, args):
self.typeinfer = typeinfer
self.func_id = func_id
self.args = args
self.target = target
self._inferred_retty = set()
def __repr__(self):
return... | CallFrame |
python | ray-project__ray | python/ray/tune/tests/execution/utils.py | {
"start": 3558,
"end": 4916
} | class ____(Trial):
def __init__(self, *args, **kwargs):
kwargs.setdefault("storage", mock_storage_context())
super().__init__(*args, **kwargs)
def get_trainable_cls(self):
return self.trainable_name
def create_placement_group_factory(self):
self.placement_group_factory = se... | TestingTrial |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter04.py | {
"start": 315,
"end": 1462
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/operators/test_produce.py | {
"start": 1444,
"end": 2834
} | class ____:
"""
Test ConsumeFromTopic
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="kafka_d",
conn_type="kafka",
extra=json.dumps(
... | TestProduceToTopic |
python | django__django | tests/migrations/test_migrations/0001_initial.py | {
"start": 43,
"end": 1019
} | class ____(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug", models.SlugField(null=True)),
... | Migration |
python | huggingface__transformers | tests/models/phimoe/test_modeling_phimoe.py | {
"start": 3832,
"end": 7536
} | class ____(unittest.TestCase):
model = None
@classmethod
def get_model(cls):
if cls.model is None:
cls.model = PhimoeForCausalLM.from_pretrained(
"microsoft/Phi-3.5-MoE-instruct", dtype="auto", device_map="auto"
)
return cls.model
@classmethod
... | PhimoeIntegrationTest |
python | Pylons__pyramid | tests/test_renderers.py | {
"start": 22742,
"end": 24040
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _callFUT(self, renderer_name, **kw):
from pyramid.renderers import get_renderer
return get_renderer(renderer_name, **kw)
def test_it_no_package(sel... | Test_get_renderer |
python | pytorch__pytorch | torch/utils/_pytree.py | {
"start": 37889,
"end": 47418
} | class ____:
type: Any
_context: Context
_children: list[Self]
num_nodes: int = dataclasses.field(init=False)
num_leaves: int = dataclasses.field(init=False)
num_children: int = dataclasses.field(init=False)
def __init__(
self,
type: Any,
context: Context, # keep fo... | TreeSpec |
python | readthedocs__readthedocs.org | readthedocs/builds/storage.py | {
"start": 574,
"end": 5780
} | class ____:
"""
A mixin for Storage classes needed to write build artifacts.
This adds and modifies some functionality to Django's File Storage API.
By default, classes mixing this in will now overwrite files by default instead
of finding an available name.
This mixin also adds convenience meth... | BuildMediaStorageMixin |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/conjecture/test_provider.py | {
"start": 9033,
"end": 9419
} | class ____(PrimitiveProvider):
def draw_integer(self, *args, **constraints):
return 1
def draw_boolean(self, *args, **constraints):
return True
def draw_float(self, *args, **constraints):
return 1.0
def draw_bytes(self, *args, **constraints):
return b""
def draw_s... | TrivialProvider |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generic3.py | {
"start": 352,
"end": 708
} | class ____(Iterable[_T2], Generic[_T1, _T2]):
def __init__(self, a: _T1, b: _T2):
pass
def foo(self, a: _T1, b: _T2) -> _T2:
return b
def __iter__(self) -> Iterator[int]: ...
a: Foo[int, str] = Foo(2, "")
b: str = a.foo(4, "")
# This should generate an error because a class shouldn't
#... | Foo |
python | getsentry__sentry | src/sentry/integrations/slack/requests/options_load.py | {
"start": 277,
"end": 1969
} | class ____(SlackRequest):
"""
An Options Load request sent from Slack.
"""
@property
def group_id(self) -> int:
if self.data.get("container", {}).get("is_app_unfurl"):
return int(
orjson.loads(
self.data["app_unfurl"]["blocks"][0]["block_id"],... | SlackOptionsLoadRequest |
python | django__django | tests/mutually_referential/models.py | {
"start": 401,
"end": 606
} | class ____(models.Model):
name = models.CharField(max_length=100)
# You can also explicitly specify the related app.
parent = models.ForeignKey("mutually_referential.Parent", models.CASCADE)
| Child |
python | tiangolo__fastapi | tests/test_security_api_key_cookie_description.py | {
"start": 250,
"end": 2172
} | class ____(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: User = Depends(get_current_user)):
return current_user
def test_security_api_key():
client ... | User |
python | google__jax | jax/_src/pallas/fuser/block_spec.py | {
"start": 20077,
"end": 20139
} | class ____(enum.Enum):
REGULAR = 0
SCALAR_PREFETCH = 1
| Usage |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 13783,
"end": 16535
} | class ____:
"""Takes a group of renderables and returns a renderable object that renders the group.
Args:
renderables (Iterable[RenderableType]): An iterable of renderable objects.
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
"""
... | Group |
python | pytorch__pytorch | tools/linter/adapters/testowners_linter.py | {
"start": 854,
"end": 4996
} | 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 get_pytorch_labels() -> Any:
url = "https://ossci-metrics.s3.amazonaws.com/pytorch_labe... | LintMessage |
python | neetcode-gh__leetcode | python/0072-edit-distance.py | {
"start": 0,
"end": 650
} | class ____:
def minDistance(self, word1: str, word2: str) -> int:
dp = [[float("inf")] * (len(word2) + 1) for i in range(len(word1) + 1)]
for j in range(len(word2) + 1):
dp[len(word1)][j] = len(word2) - j
for i in range(len(word1) + 1):
dp[i][len(word2)] = len(word1)... | Solution |
python | joke2k__faker | faker/providers/currency/ru_RU/__init__.py | {
"start": 46,
"end": 6141
} | class ____(CurrencyProvider):
# Format: (code, name)
# See currency names in Russian: https://ru.wikipedia.org/wiki/Список_существующих_валют#Валюты
currencies = (
("AED", "Дирхам ОАЭ"),
("AFN", "Афгани"),
("ALL", "Лек"),
("AMD", "Армянский драм"),
("ANG", "Нидерландс... | Provider |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_search_tool_search_result_block_param.py | {
"start": 342,
"end": 546
} | class ____(TypedDict, total=False):
tool_references: Required[Iterable[BetaToolReferenceBlockParam]]
type: Required[Literal["tool_search_tool_search_result"]]
| BetaToolSearchToolSearchResultBlockParam |
python | gevent__gevent | src/greentest/3.10/test_smtpd.py | {
"start": 31731,
"end": 33987
} | class ____(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((socket_helper.HOST, 0), ('b', 0),
decode_... | SMTPDChannelWithDataSizeLimitTest |
python | huggingface__transformers | tests/models/convnext/test_modeling_convnext.py | {
"start": 1408,
"end": 5648
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=32,
num_channels=3,
num_stages=4,
hidden_sizes=[10, 20, 30, 40],
depths=[2, 2, 3, 2],
is_training=True,
use_labels=True,
intermediate_size=37,
hidden_act=... | ConvNextModelTester |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 156,
"end": 340
} | class ____(ValueError):
"""Validation error. If a rule converter raises this exception the rule
does not match the current URL and the next URL is tried.
"""
| ValidationError |
python | getsentry__sentry | src/sentry/backup/helpers.py | {
"start": 1303,
"end": 1631
} | class ____(Enum):
"""
Used to identify the "side" in backup operations which perform comparisons between two sets of exports JSONs. The "left" side is usually the older of the two states (ie, "left" is roughly synonymous with "before", and "right" with "after").
"""
left = 1
right = 2
T = TypeVar... | Side |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py | {
"start": 7820,
"end": 8148
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
name: str = Field(..., description="The secret name in the secret store")
fileName: Optional[str] = Field(
None,
description="The name of the file to which the secret value would be persisted",
)
secretStore: SecretSt... | Secret |
python | walkccc__LeetCode | solutions/2895. Minimum Processing Time/2895.py | {
"start": 0,
"end": 272
} | class ____:
def minProcessingTime(
self,
processorTime: list[int],
tasks: list[int],
) -> int:
return max(time + task
for (time, task) in zip(
sorted(processorTime),
sorted(tasks)[:: -4]))
| Solution |
python | django__django | tests/postgres_tests/test_ranges.py | {
"start": 3301,
"end": 6564
} | class ____(PostgreSQLTestCase):
def test_all_fields(self):
now = timezone.now()
instance = RangesModel(
ints=NumericRange(0, 10),
bigints=NumericRange(10, 20),
decimals=NumericRange(20, 30),
timestamps=DateTimeTZRange(now - datetime.timedelta(hours=1),... | TestSaveLoad |
python | google__jax | jax/_src/lax/lax.py | {
"start": 94799,
"end": 236225
} | class ____():
"""Describes ragged, group, and dot dimensions for ragged dot general.
Args:
dot_dimension_numbers: a tuple of tuples of sequences of ints of the form
`((lhs_contracting_dims, rhs_contracting_dims), (lhs_batch_dims,
rhs_batch_dims))`.
lhs_ragged_dimensions: a sequence of ints indi... | RaggedDotDimensionNumbers |
python | run-llama__llama_index | llama-index-core/llama_index/core/graph_stores/simple.py | {
"start": 390,
"end": 2071
} | class ____(DataClassJsonMixin):
"""
Simple Graph Store Data container.
Args:
graph_dict (Optional[dict]): dict mapping subject to
"""
graph_dict: Dict[str, List[List[str]]] = field(default_factory=dict)
def get_rel_map(
self, subjs: Optional[List[str]] = None, depth: int = 2,... | SimpleGraphStoreData |
python | getsentry__sentry | src/sentry/backup/crypto.py | {
"start": 7877,
"end": 9547
} | class ____(Decryptor):
"""
Decrypt using a private key stored on the local machine.
"""
def __init__(self, fp: IO[bytes]):
self.__key = fp.read()
@classmethod
def from_bytes(cls, b: bytes) -> LocalFileDecryptor:
return cls(io.BytesIO(b))
def decrypt_data_encryption_key(sel... | LocalFileDecryptor |
python | ansible__ansible | test/units/plugins/action/test_action.py | {
"start": 32705,
"end": 33334
} | class ____(unittest.TestCase):
def test(self):
data = {'ansible_playbook_python': '/usr/bin/python',
'ansible_python_interpreter': '/usr/bin/python',
'ansible_ssh_some_var': 'whatever',
'ansible_ssh_host_key_somehost': 'some key here',
'some_ot... | TestActionBaseCleanReturnedData |
python | django__django | tests/model_inheritance/models.py | {
"start": 2203,
"end": 2298
} | class ____(Restaurant):
serves_gnocchi = models.BooleanField(default=False)
| ItalianRestaurant |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassTransform2.py | {
"start": 821,
"end": 1081
} | class ____(ModelBase, frozen=True):
id: int = model_field()
name: str = model_field()
name2: str = model_field(alias="other_name", default="None")
# This should generate an error because a non-frozen class cannot
# derive from a frozen one.
| Customer1 |
python | scipy__scipy | scipy/optimize/tests/test__basinhopping.py | {
"start": 1136,
"end": 1693
} | class ____(RandomDisplacement):
"""use a copy of displace, but have it set a special parameter to
make sure it's actually being used."""
def __init__(self):
self.been_called = False
super().__init__()
def __call__(self, x):
self.been_called = True
return super().__call__... | MyTakeStep1 |
python | Netflix__metaflow | metaflow/client/core.py | {
"start": 37453,
"end": 63842
} | class ____(MetaflowObject):
"""
A `Task` represents an execution of a `Step`.
It contains all `DataArtifact` objects produced by the task as
well as metadata related to execution.
Note that the `@retry` decorator may cause multiple attempts of
the task to be present. Usually you want the lates... | Task |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 16820,
"end": 17625
} | 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... | VisualBertPredictionHeadTransform |
python | PrefectHQ__prefect | src/prefect/client/schemas/schedules.py | {
"start": 1149,
"end": 3855
} | class ____(PrefectBaseModel):
"""
A schedule formed by adding `interval` increments to an `anchor_date`. If no
`anchor_date` is supplied, the current UTC time is used. If a
timezone-naive datetime is provided for `anchor_date`, it is assumed to be
in the schedule's timezone (or UTC). Even if suppli... | IntervalSchedule |
python | pytorch__pytorch | torchgen/model.py | {
"start": 14088,
"end": 41921
} | class ____:
# The namespace for this operator. For example, if we have "at::add"
# then the namespace would be "at". This enables ops to be registered
# through the same DSL with a custom namespace. If not specified, the
# default namespace would be "at".
namespace: str
# The function schema of... | NativeFunction |
python | getsentry__sentry | src/sentry/hybridcloud/outbox/category.py | {
"start": 8878,
"end": 12575
} | class ____(IntEnum):
ORGANIZATION_SCOPE = scope_categories(
0,
{
OutboxCategory.ORGANIZATION_MEMBER_UPDATE,
OutboxCategory.MARK_INVALID_SSO,
OutboxCategory.RESET_IDP_FLAGS,
OutboxCategory.ORGANIZATION_UPDATE,
OutboxCategory.PROJECT_UPDATE,
... | OutboxScope |
python | doocs__leetcode | solution/0200-0299/0283.Move Zeroes/Solution.py | {
"start": 0,
"end": 211
} | class ____:
def moveZeroes(self, nums: List[int]) -> None:
k = 0
for i, x in enumerate(nums):
if x:
nums[k], nums[i] = nums[i], nums[k]
k += 1
| Solution |
python | falconry__falcon | tests/test_httperror.py | {
"start": 4453,
"end": 4580
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPGone(description='Gone with the wind')
| GoneResourceWithBody |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 3801,
"end": 4127
} | class ____(str, _Action, Enum):
MANAGE = "manage_roles" # backward compatibility, remove in a bit
CREATE = "create_roles"
READ = "read_roles"
UPDATE = "update_roles"
DELETE = "delete_roles"
@staticmethod
def values() -> List[str]:
return [action.value for action in RolesAction]
| RolesAction |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_plugins_command.py | {
"start": 1769,
"end": 1886
} | class ____(AirflowPlugin):
name = "test-plugin-cli"
global_operator_extra_links = [AirflowNewLink()]
| TestPlugin |
python | google__jax | jax/_src/hijax.py | {
"start": 5299,
"end": 6954
} | class ____(MutableHiType):
has_qdd = True
# forwarded to value
get = core.aval_method(box_get)
set = core.aval_method(box_set)
# aval interface: hashability and str_short
def __hash__(self): return hash(BoxTy)
def __eq__(self, other): return isinstance(other, BoxTy)
def str_short(self, short_dtypes=F... | BoxTy |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor12.py | {
"start": 216,
"end": 499
} | class ____(Generic[T]):
def return_from_variable(self) -> "ClassA[T]":
value = ClassA[T]()
reveal_type(value, expected_text="ClassA[T@ClassA]")
return value
x = ClassA[int]()
v1 = x.return_from_variable()
reveal_type(v1, expected_text="ClassA[int]")
| ClassA |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/properties/snippets.py | {
"start": 1506,
"end": 1629
} | class ____(ndb.Model):
name = ndb.StringProperty()
addresses = ndb.StructuredProperty(Address, repeated=True)
| Contact |
python | openai__openai-python | src/openai/resources/moderations.py | {
"start": 894,
"end": 3835
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> ModerationsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.gith... | Moderations |
python | pandas-dev__pandas | asv_bench/benchmarks/join_merge.py | {
"start": 6441,
"end": 7158
} | class ____:
# outer join of non-unique
# GH 6329
def setup(self):
date_index = date_range("01-Jan-2013", "23-Jan-2013", freq="min")
daily_dates = date_index.to_period("D").to_timestamp("s", "s")
self.fracofday = date_index.values - daily_dates.values
self.fracofday = self.fra... | JoinNonUnique |
python | lxml__lxml | src/lxml/html/tests/test_html5parser.py | {
"start": 1739,
"end": 3096
} | class ____(unittest.TestCase):
def call_it(self, *args, **kwargs):
if html5lib is None:
raise unittest.SkipTest("html5lib is not installed")
from lxml.html.html5parser import document_fromstring
return document_fromstring(*args, **kwargs)
def test_basic(self):
parser... | Test_document_fromstring |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 226077,
"end": 228969
} | class ____(Request):
"""
Delete task configuration items
:param task: Task ID
:type task: str
:param configuration: List of configuration itemss to delete
:type configuration: Sequence[str]
:param force: If set to True then both new and running task configuration can
be deleted. Oth... | DeleteConfigurationRequest |
python | PyCQA__pylint | tests/functional/u/unused/unused_argument.py | {
"start": 2946,
"end": 3238
} | class ____(Ancestor):
def set_thing(self, thing, *, other=None):
"""Subclass does not raise unused-argument"""
self.thing = thing
# Test that Class with both `__init__` and `__new__` don't check
# on `__new__` for unused arguments
# pylint: disable=invalid-name
| Descendant |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/context.py | {
"start": 743,
"end": 6839
} | class ____(ConnectorContext):
def __init__(
self,
connector: ConnectorWithModifiedFiles,
pre_release: bool,
spec_cache_gcs_credentials: Secret,
spec_cache_bucket_name: str,
metadata_service_gcs_credentials: Secret,
metadata_bucket_name: str,
docker_hub... | PublishConnectorContext |
python | tiangolo__fastapi | fastapi/params.py | {
"start": 24596,
"end": 27724
} | class ____(Form): # type: ignore[misc]
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
media_type: str = "multipart/form-data",
alias: Optional[str] = None,
a... | File |
python | getsentry__sentry | tests/sentry/toolbar/views/test_login_success_view.py | {
"start": 185,
"end": 1394
} | class ____(APITestCase):
view_name = "sentry-toolbar-login-success"
def setUp(self) -> None:
super().setUp()
self.url = reverse(self.view_name, args=(self.organization.slug, self.project.slug))
# Note no login
def test_get_requires_auth(self) -> None:
"""Unauthenticated req... | LoginSuccessViewTest |
python | sympy__sympy | sympy/matrices/exceptions.py | {
"start": 91,
"end": 174
} | class ____(ValueError, MatrixError):
"""Wrong matrix shape"""
pass
| ShapeError |
python | scrapy__scrapy | scrapy/pipelines/files.py | {
"start": 14283,
"end": 25796
} | class ____(MediaPipeline):
"""Abstract pipeline that implement the file downloading
This pipeline tries to minimize network transfers and file processing,
doing stat of the files and determining if file is new, up-to-date or
expired.
``new`` files are those that pipeline never processed and needs ... | FilesPipeline |
python | google__pytype | pytype/tests/test_attributes1.py | {
"start": 151,
"end": 8951
} | class ____(test_base.BaseTest):
"""Tests for strict attribute checking on None."""
def test_module_constant(self):
errors = self.CheckWithErrors("""
x = None
def f():
return x.upper() # attribute-error[e]
""")
self.assertErrorRegexes(errors, {"e": r"upper.*None"})
def test_class... | TestStrictNone |
python | django__django | tests/migrations/migrations_test_apps/unmigrated_app/models.py | {
"start": 31,
"end": 243
} | class ____(models.Model):
silly_field = models.BooleanField(default=False)
silly_tribble = models.ForeignKey("migrations.Tribble", models.CASCADE)
is_trouble = models.BooleanField(default=True)
| SillyModel |
python | Textualize__textual | src/textual/css/query.py | {
"start": 1054,
"end": 1135
} | class ____(QueryError):
"""Query did not parse correctly."""
| InvalidQueryFormat |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 566129,
"end": 567704
} | class ____(sgqlc.types.Type):
"""A protection rule."""
__schema__ = github_schema
__field_names__ = ("database_id", "reviewers", "timeout", "type")
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
reviewers = sgqlc.types.Field(... | DeploymentProtectionRule |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 7692,
"end": 7805
} | class ____(graphene.InputObjectType):
experiment_ids = graphene.List(graphene.String)
| MlflowSearchDatasetsInput |
python | ray-project__ray | python/ray/tune/stopper/stopper.py | {
"start": 97,
"end": 1723
} | class ____(abc.ABC):
"""Base class for implementing a Tune experiment stopper.
Allows users to implement experiment-level stopping via ``stop_all``. By
default, this class does not stop any trials. Subclasses need to
implement ``__call__`` and ``stop_all``.
Examples:
>>> import time
... | Stopper |
python | ansible__ansible | test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py | {
"start": 662,
"end": 881
} | class ____(BaseInventoryPlugin, Cacheable):
NAME = 'testns.content_adj.statichost'
def verify_file(self, path):
pass
def parse(self, inventory, loader, path, cache=None):
pass
| InventoryModule |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/observers/ecs.py | {
"start": 3050,
"end": 4628
} | class ____:
def __init__(self):
self.ecs_client: "ECSClient | None" = None
self._cache: LRUCache[str, dict[str, str]] = LRUCache(maxsize=100)
async def read_tags(self, cluster_arn: str, task_arn: str) -> dict[str, str]:
if not self.ecs_client:
raise RuntimeError("ECS client ... | EcsTaskTagsReader |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/query_expectation_template.py | {
"start": 784,
"end": 4806
} | class ____(QueryExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/query_expectation_template.py docstring">
"""TODO: Add a docstring here"""
# </snippet>
# This is the id string of the Metric(s) used by this Expectation.
# <sni... | ExpectQueryToMatchSomeCriteria |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 9428,
"end": 9583
} | class ____(models.Model):
a = models.IntegerField()
j_field = JSONField()
class Meta:
app_label = "django_extensions"
| JSONFieldTestModel |
python | getsentry__sentry | tests/apidocs/endpoints/organizations/test_org_index.py | {
"start": 136,
"end": 577
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
self.create_organization(owner=self.user, name="Rowdy Tiger")
self.url = reverse(
"sentry-api-0-organizations",
)
self.login_as(user=self.user)
def test_get(self) -> None:
response = self.client.get(self... | OrganizationIndexDocs |
python | PrefectHQ__prefect | tests/server/models/test_flows.py | {
"start": 3750,
"end": 10151
} | class ____:
@pytest.fixture
async def flows(self, session):
flow_1 = await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-1")
)
flow_2 = await models.flows.create_flow(
session=session, flow=schemas.core.Flow(name="my-flow-2")
... | TestReadFlows |
python | huggingface__transformers | src/transformers/models/markuplm/modeling_markuplm.py | {
"start": 20765,
"end": 25678
} | class ____(MarkupLMPreTrainedModel):
# Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->MarkupLM
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
... | MarkupLMModel |
python | MongoEngine__mongoengine | tests/fields/test_uuid_field.py | {
"start": 112,
"end": 176
} | class ____(Document):
api_key = UUIDField(binary=False)
| Person |
python | realpython__materials | python-getter-setter/point.py | {
"start": 0,
"end": 251
} | class ____:
def __init__(self, x, y):
self.x = x
self.y = y
def __getattr__(self, name: str):
return self.__dict__[f"_{name}"]
def __setattr__(self, name, value):
self.__dict__[f"_{name}"] = float(value)
| Point |
python | scrapy__scrapy | scrapy/core/downloader/handlers/s3.py | {
"start": 651,
"end": 3821
} | class ____:
def __init__(
self,
settings: BaseSettings,
*,
crawler: Crawler,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
httpdownloadhandler: type[HTTP11DownloadHandler] = HTTP11... | S3DownloadHandler |
python | apache__airflow | airflow-core/tests/unit/utils/test_memray_utils.py | {
"start": 1064,
"end": 6182
} | class ____:
"""Test suite for enable_memray_trace decorator functionality."""
def setup_method(self):
self.mock_function = Mock(return_value="test_result")
self.mock_function.__name__ = "mock_function"
# Set up memray module mock
self.mock_memray_module = MagicMock()
se... | TestEnableMemrayTrackDecorator |
python | getsentry__sentry | src/sentry/users/api/serializers/userip.py | {
"start": 544,
"end": 1039
} | class ____(Serializer):
def serialize(
self,
obj: UserIP,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> UserIPSerializerResponse:
return {
"id": str(obj.id),
"ipAddress": obj.ip_address,
"co... | UserIPSerializer |
python | realpython__materials | html-css-python/python_scripts/parse_image_links.py | {
"start": 96,
"end": 452
} | class ____(HTMLParser):
def handle_starttag(self, tag, attrs):
for attr, val in attrs:
if attr == "src" and tag == "img":
print(f"Found Image: {val!r}")
with open("gallery.html", mode="r", encoding="utf-8") as html_file:
html_content = html_file.read()
parser = ImageParser... | ImageParser |
python | wandb__wandb | wandb/vendor/pygments/lexers/installers.py | {
"start": 6882,
"end": 9485
} | class ____(RegexLexer):
"""
For RPM ``.spec`` files.
.. versionadded:: 1.6
"""
name = 'RPMSpec'
aliases = ['spec']
filenames = ['*.spec']
mimetypes = ['text/x-rpm-spec']
_directives = ('(?:package|prep|build|install|clean|check|pre[a-z]*|'
'post[a-z]*|trigger[a-... | RPMSpecLexer |
python | ipython__ipython | IPython/core/magics/osm.py | {
"start": 927,
"end": 30695
} | class ____(Magics):
"""Magics to interact with the underlying OS (shell-type functionality).
"""
cd_force_quiet = Bool(False,
help="Force %cd magic to be quiet even if -q is not passed."
).tag(config=True)
def __init__(self, shell=None, **kwargs):
# Now define isexec in a cross pl... | OSMagics |
python | joke2k__faker | tests/providers/test_geo.py | {
"start": 2571,
"end": 3214
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("sk_SK")
Faker.seed(0)
def test_location_on_land(self):
loc = self.fake.location_on_land()
assert isinstance(loc, tuple)
assert len(loc) == 5
assert Decimal(loc[0]) # Should be able to cast first ... | TestSkSk |
python | gevent__gevent | src/greentest/3.14/test_smtplib.py | {
"start": 27703,
"end": 28876
} | class ____(unittest.TestCase):
def setUp(self):
self.msg = EmailMessage()
self.msg['From'] = 'Páolo <főo@bar.com>'
self.smtp = smtplib.SMTP()
self.smtp.ehlo = Mock(return_value=(200, 'OK'))
self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
def testSendMessage(self... | DefaultArgumentsTests |
python | wandb__wandb | wandb/vendor/pygments/lexers/webmisc.py | {
"start": 776,
"end": 1786
} | class ____(RegexLexer):
"""
Lexer for Duel Views Engine (formerly JBST) markup with JavaScript code blocks.
See http://duelengine.org/.
See http://jsonml.org/jbst/.
.. versionadded:: 1.4
"""
name = 'Duel'
aliases = ['duel', 'jbst', 'jsonml+bst']
filenames = ['*.duel', '*.jbst']
... | DuelLexer |
python | Textualize__rich | tests/test_inspect.py | {
"start": 1664,
"end": 1758
} | class ____(Exception):
def __str__(self) -> str:
return "INSPECT ERROR"
| InspectError |
python | pallets__jinja | tests/test_ext.py | {
"start": 7132,
"end": 10520
} | class ____:
def test_extend_late(self):
env = Environment()
t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')
assert t.render() == "<test>"
def test_loop_controls(self):
env = Environment(extensions=["jinja2.ext.loopcontrols"])
tmpl = e... | TestExtensions |
python | django__django | tests/auth_tests/test_forms.py | {
"start": 33414,
"end": 36265
} | class ____(TestDataMixin, TestCase):
def test_incorrect_password(self):
user = User.objects.get(username="testclient")
data = {
"old_password": "test",
"new_password1": "abc123",
"new_password2": "abc123",
}
form = PasswordChangeForm(user, data)
... | PasswordChangeFormTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.