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 | doocs__leetcode | solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/Solution.py | {
"start": 0,
"end": 611
} | class ____:
def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= n:
return 0
if floor[i] == "0":
return dfs(i + 1, j)
if j == 0:
return s[-1]... | Solution |
python | getsentry__sentry | src/sentry/api/event_search.py | {
"start": 23043,
"end": 23091
} | class ____(NamedTuple):
name: str
| AggregateKey |
python | walkccc__LeetCode | solutions/2398. Maximum Number of Robots Within Budget/2398.py | {
"start": 0,
"end": 676
} | class ____:
def maximumRobots(
self,
chargeTimes: list[int],
runningCosts: list[int],
budget: int,
) -> int:
cost = 0
maxQ = collections.deque() # Stores `chargeTimes[i]`.
j = 0 # window's range := [i..j], so k = i - j + 1
for i, (chargeTime, runningCost) in enumerate(
... | Solution |
python | scipy__scipy | scipy/optimize/_basinhopping.py | {
"start": 1060,
"end": 7037
} | class ____:
"""This class implements the core of the basinhopping algorithm.
x0 : ndarray
The starting coordinates.
minimizer : callable
The local minimizer, with signature ``result = minimizer(x)``.
The return value is an `optimize.OptimizeResult` object.
step_taking : callable... | BasinHoppingRunner |
python | HIPS__autograd | autograd/numpy/numpy_vspaces.py | {
"start": 911,
"end": 3673
} | class ____(ArrayVSpace):
iscomplex = True
@property
def size(self):
return np.prod(self.shape) * 2
def ones(self):
return np.ones(self.shape, dtype=self.dtype) + 1.0j * np.ones(self.shape, dtype=self.dtype)
def standard_basis(self):
for idxs in np.ndindex(*self.shape):
... | ComplexArrayVSpace |
python | coleifer__peewee | tests/models.py | {
"start": 2173,
"end": 58562
} | class ____(ModelTestCase):
def add_user(self, username):
return User.create(username=username)
def add_tweets(self, user, *tweets):
accum = []
for tweet in tweets:
accum.append(Tweet.create(user=user, content=tweet))
return accum
@requires_models(Point)
def ... | TestModelAPIs |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 11043,
"end": 11313
} | class ____(WeaviateBaseError):
"""Is raised when all objects fail to be inserted."""
def __init__(self, message: str = "") -> None:
msg = f"""Every object failed during insertion. {message}"""
super().__init__(msg)
| WeaviateInsertManyAllFailedError |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 167,
"end": 629
} | class ____(BaseSparsifier):
def __init__(self, **kwargs: dict[str, Any]) -> None:
super().__init__(defaults=kwargs)
def update_mask(self, module: nn.Module, tensor_name: str, **kwargs: dict[str, Any]) -> None:
module.parametrizations.weight[0].mask[0] = 0 # type: ignore[index, union-attr]
... | ImplementedSparsifier |
python | kamyu104__LeetCode-Solutions | Python/falling-squares.py | {
"start": 8691,
"end": 9459
} | class ____(object):
def fallingSquares(self, positions):
"""
:type positions: List[List[int]]
:rtype: List[int]
"""
heights = [0] * len(positions)
for i in xrange(len(positions)):
left_i, size_i = positions[i]
right_i = left_i + size_i
... | Solution4 |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modular_deepseek_v3.py | {
"start": 12796,
"end": 13369
} | class ____(LlamaPreTrainedModel):
_can_compile_fullgraph = False
@torch.no_grad()
def _init_weights(self, module):
PreTrainedModel._init_weights(self, module)
if isinstance(module, DeepseekV3TopkRouter):
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
... | DeepseekV3PreTrainedModel |
python | doocs__leetcode | lcci/17.24.Max Submatrix/Solution.py | {
"start": 0,
"end": 929
} | class ____:
def getMaxMatrix(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
s = [[0] * n for _ in range(m + 1)]
for i in range(m):
for j in range(n):
# 构造列前缀和
s[i + 1][j] = s[i][j] + matrix[i][j]
mx = matri... | Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_planner.py | {
"start": 25129,
"end": 26129
} | class ____(TestCase):
def _make_metadata(self, chunks, size):
storage = TensorStorageMetadata(
properties=TensorProperties(dtype=torch.float32),
size=torch.Size(size),
chunks=chunks,
)
return Metadata(state_dict_metadata={"param": storage})
def test_n... | TestValidateGlobalPlan |
python | getsentry__sentry | tests/sentry/models/test_grouphistory.py | {
"start": 1150,
"end": 2526
} | class ____(TestCase):
def test(self) -> None:
GroupAssignee.objects.assign(self.group, self.user)
proj_1_group_2 = self.store_event(data={}, project_id=self.project.id).group
GroupAssignee.objects.assign(self.group, self.team)
history = set(GroupHistory.objects.filter(group__in=[self... | FilterToTeamTest |
python | gevent__gevent | src/greentest/3.14/test_socket.py | {
"start": 27197,
"end": 81304
} | class ____(unittest.TestCase):
@unittest.skipUnless(_socket is not None, 'need _socket module')
def test_socket_type(self):
self.assertTrue(gc.is_tracked(_socket.socket))
with self.assertRaisesRegex(TypeError, "immutable"):
_socket.socket.foo = 1
def test_SocketType_is_socketob... | GeneralModuleTests |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py | {
"start": 5533,
"end": 6133
} | class ____(nn.Module):
"""A simple unidirectional LSTM."""
@functools.partial(
nn.transforms.scan,
variable_broadcast='params',
in_axes=1, out_axes=1,
split_rngs={'params': False})
@nn.compact
def __call__(self, carry, x):
return nn.OptimizedLSTMCell(features=carry[0].shape[-1])(car... | SimpleLSTM |
python | catalyst-team__catalyst | catalyst/callbacks/soft_update.py | {
"start": 140,
"end": 3382
} | class ____(Callback):
"""Callback to update `target` data inside `runner.model` with the `source`
data inside `runner.model` one smoothing by ``tau`` (inplace operation).
Args:
target_model: key to the data inside `runner.model` to update
source_model: key to the source data inside `runner.... | SoftUpdateCallaback |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_metrics_meta.py | {
"start": 4840,
"end": 10346
} | class ____(MetricsEnhancedPerformanceTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
self.two_min_ago = before_now(minutes=2)
self.features = {
"organizations:performance-use-metrics": True,
}
self.login_as(user=sel... | OrganizationEventsMetricsSums |
python | ansible__ansible | test/integration/targets/inventory/doc_fragments/fragment_with_expression.py | {
"start": 37,
"end": 256
} | class ____:
DOCUMENTATION = """
options:
fragment_expression:
description: a fragment hosted expression that must be trusted whose default resolves to 4
default: 2 + 2
"""
| ModuleDocFragment |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/utils/test_utils.py | {
"start": 3050,
"end": 62746
} | class ____(EmptyOperator):
pass
@pytest.mark.db_test
def test_get_airflow_job_facet():
with DAG(dag_id="dag", schedule=None, start_date=datetime.datetime(2024, 6, 1)) as dag:
task_0 = BashOperator(task_id="task_0", bash_command="exit 0;")
with TaskGroup("section_1", prefix_group_id=True):
... | CustomOperatorFromEmpty |
python | apache__airflow | providers/postgres/src/airflow/providers/postgres/dialects/postgres.py | {
"start": 965,
"end": 5332
} | class ____(Dialect):
"""Postgres dialect implementation."""
@property
def name(self) -> str:
return "postgresql"
@lru_cache(maxsize=None)
def get_primary_keys(self, table: str, schema: str | None = None) -> list[str] | None:
"""
Get the table's primary key.
:param ... | PostgresDialect |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py | {
"start": 15911,
"end": 20667
} | class ____(nn.Module):
def __init__(self, config: RTDetrV2Config):
super().__init__()
# self-attention
self.self_attn = RTDetrV2MultiheadAttention(
embed_dim=config.d_model,
num_heads=config.decoder_attention_heads,
dropout=config.attention_dropout,
... | RTDetrV2DecoderLayer |
python | fluentpython__example-code | 20-descriptor/bulkfood/model_v5.py | {
"start": 540,
"end": 861
} | class ____(abc.ABC, AutoStorage): # <3>
def __set__(self, instance, value):
value = self.validate(instance, value) # <4>
super().__set__(instance, value) # <5>
@abc.abstractmethod
def validate(self, instance, value): # <6>
"""return validated value or raise ValueError"""
| Validated |
python | jazzband__django-polymorphic | example/pexp/admin.py | {
"start": 403,
"end": 843
} | class ____(PolymorphicChildModelAdmin):
base_model = Project # Can be set explicitly.
# On purpose, only have the shared fields here.
# The fields of the derived model should still be displayed.
base_fieldsets = (("Base fields", {"fields": ("topic",)}),)
admin.site.register(Project, ProjectAdmin)
ad... | ProjectChildAdmin |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 18834,
"end": 19386
} | class ____(_WeaviateInput):
link_on: str
include_vector: INCLUDE_VECTOR = Field(default=False)
return_metadata: Optional[MetadataQuery] = Field(default=None)
return_properties: Union["PROPERTIES", bool, None] = Field(default=None)
return_references: Optional["REFERENCES"] = Field(default=None)
... | _QueryReference |
python | openai__openai-python | src/openai/cli/_cli.py | {
"start": 701,
"end": 6779
} | class ____(BaseModel):
if PYDANTIC_V1:
class Config(pydantic.BaseConfig): # type: ignore
extra: Any = pydantic.Extra.ignore # type: ignore
else:
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="ignore",
)
verbosity: int
version: Optional[str] = ... | Arguments |
python | getsentry__sentry | src/sentry/analytics/events/first_release_tag_sent.py | {
"start": 79,
"end": 237
} | class ____(analytics.Event):
user_id: int
organization_id: int
project_id: int
analytics.register(FirstReleaseTagSentEvent)
| FirstReleaseTagSentEvent |
python | doocs__leetcode | solution/1800-1899/1851.Minimum Interval to Include Each Query/Solution.py | {
"start": 0,
"end": 612
} | class ____:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
n, m = len(intervals), len(queries)
intervals.sort()
queries = sorted((x, i) for i, x in enumerate(queries))
ans = [-1] * m
pq = []
i = 0
for x, j in queries:
... | Solution |
python | Textualize__textual | docs/examples/guide/screens/modal01.py | {
"start": 493,
"end": 1022
} | class ____(Screen):
"""Screen with a dialog to quit."""
def compose(self) -> ComposeResult:
yield Grid(
Label("Are you sure you want to quit?", id="question"),
Button("Quit", variant="error", id="quit"),
Button("Cancel", variant="primary", id="cancel"),
i... | QuitScreen |
python | huggingface__transformers | tests/models/bridgetower/test_image_processing_bridgetower.py | {
"start": 3580,
"end": 7268
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = BridgeTowerImageProcessor if is_vision_available() else None
fast_image_processing_class = BridgeTowerImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_proc... | BridgeTowerImageProcessingTest |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/global_shuffle_op.py | {
"start": 2828,
"end": 4054
} | class ____(dataset_ops.UnaryUnchangedStructureDataset):
"""Shuffles all elements in the input dataset."""
def __init__(
self,
input_dataset: dataset_ops.DatasetV2,
seed: Optional[Union[int, tensor.Tensor]] = None,
reshuffle_each_iteration: bool = True,
name: Optional[str] = None):
... | _GlobalShuffleDataset |
python | ray-project__ray | rllib/core/models/torch/base.py | {
"start": 380,
"end": 3076
} | class ____(nn.Module, Model, abc.ABC):
"""Base class for RLlib's PyTorch models.
This class defines the interface for RLlib's PyTorch models.
Example usage for a single Flattening layer:
.. testcode::
from ray.rllib.core.models.configs import ModelConfig
from ray.rllib.core.models.to... | TorchModel |
python | davidhalter__jedi | jedi/api/refactoring/__init__.py | {
"start": 2733,
"end": 9579
} | class ____:
def __init__(self, inference_state, file_to_node_changes, renames=()):
self._inference_state = inference_state
self._renames = renames
self._file_to_node_changes = file_to_node_changes
def get_changed_files(self) -> Dict[Path, ChangedFile]:
def calculate_to_path(p):
... | Refactoring |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 78784,
"end": 84877
} | class ____(GeneratedAirbyteDestination):
class NoCompression:
@public
def __init__(self, compression_type: Optional[str] = None):
self.compression_type = check.opt_str_param(compression_type, "compression_type")
class Deflate:
@public
def __init__(self, codec: str, c... | R2Destination |
python | django__django | tests/generic_views/views.py | {
"start": 8209,
"end": 8332
} | class ____(generic.DetailView):
def get_queryset(self):
return Book.does_not_exist.all()
| ObjectDoesNotExistDetail |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/config/source.py | {
"start": 199,
"end": 2753
} | class ____:
"""Base class for implementing a config source."""
def __init__(self, root_path) -> None:
self.root_path = root_path
self.is_windows = sys.platform == "win32"
self.xdg_home = os.environ.get(
"XDG_CONFIG_HOME", os.path.expanduser("~/.config")
)
def us... | ConfigSource |
python | PrefectHQ__prefect | src/prefect/client/subscriptions.py | {
"start": 597,
"end": 4382
} | class ____(Generic[S]):
def __init__(
self,
model: type[S],
path: str,
keys: Iterable[str],
client_id: Optional[str] = None,
base_url: Optional[str] = None,
):
self.model = model
self.client_id = client_id
base_url = base_url.replace("http"... | Subscription |
python | laurentluce__python-algorithms | algorithms/a_star_path_finding.py | {
"start": 15,
"end": 662
} | class ____(object):
def __init__(self, x, y, reachable):
"""Initialize new cell.
@param reachable is cell reachable? not a wall?
@param x cell x coordinate
@param y cell y coordinate
@param g cost to move from the starting cell to this cell.
@param h estimation of th... | Cell |
python | numba__numba | numba/core/rewrites/ir_print.py | {
"start": 132,
"end": 2047
} | class ____(Rewrite):
"""
Rewrite calls to the print() global function to dedicated IR print() nodes.
"""
def match(self, func_ir, block, typemap, calltypes):
self.prints = prints = {}
self.block = block
# Find all assignments with a right-hand print() call
for inst in bl... | RewritePrintCalls |
python | doocs__leetcode | solution/0400-0499/0450.Delete Node in a BST/Solution.py | {
"start": 192,
"end": 833
} | class ____:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return None
if root.val > key:
root.left = self.deleteNode(root.left, key)
return root
if root.val < key:
root.right = self.deleteNode(... | Solution |
python | django-haystack__django-haystack | test_haystack/test_views.py | {
"start": 9192,
"end": 10887
} | class ____(TestCase):
fixtures = ["base_data"]
def setUp(self):
super().setUp()
# Stow.
self.old_unified_index = connections["default"]._index
self.ui = UnifiedIndex()
self.bmmsi = BasicMockModelSearchIndex()
self.bammsi = BasicAnotherMockModelSearchIndex()
... | BasicSearchViewTestCase |
python | doocs__leetcode | solution/0900-0999/0981.Time Based Key-Value Store/Solution.py | {
"start": 0,
"end": 567
} | class ____:
def __init__(self):
self.ktv = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.ktv[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if key not in self.ktv:
return ''
tv = self.ktv[key... | TimeMap |
python | PrefectHQ__prefect | src/prefect/server/database/query_components.py | {
"start": 19010,
"end": 28106
} | class ____(BaseQueryComponents):
# --- Postgres-specific SqlAlchemy bindings
def insert(self, obj: type[orm_models.Base]) -> postgresql.Insert:
return postgresql.insert(obj)
# --- Postgres-specific JSON handling
@property
def uses_json_strings(self) -> bool:
return False
def ... | AsyncPostgresQueryComponents |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 18258,
"end": 24423
} | class ____(core.Trace):
__slots__ = ("axis_name", "emap_info")
def __init__(self, axis_name, emap_info):
super().__init__()
self.emap_info = emap_info
self.axis_name = axis_name
def to_map_tracer(self, val):
if isinstance(val, MapTracer):
return val
else:
return MapTracer(self, v... | MapTrace |
python | django__django | tests/i18n/test_compilation.py | {
"start": 13995,
"end": 14371
} | class ____(MessageCompilationTests):
work_subdir = "exclude"
def test_locale_paths_pathlib(self):
with override_settings(LOCALE_PATHS=[Path(self.test_dir) / "canned_locale"]):
call_command("compilemessages", locale=["fr"], verbosity=0)
self.assertTrue(os.path.exists("canned_loca... | PathLibLocaleCompilationTests |
python | sympy__sympy | sympy/sets/fancysets.py | {
"start": 5876,
"end": 6869
} | class ____(Interval, metaclass=Singleton):
"""
Represents all real numbers
from negative infinity to positive infinity,
including all integer, rational and irrational numbers.
This set is also available as the singleton ``S.Reals``.
Examples
========
>>> from sympy import S, Rational,... | Reals |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_installation_external_issues.py | {
"start": 208,
"end": 4584
} | class ____(APITestCase):
def setUp(self) -> None:
self.superuser = self.create_user(email="a@example.com", is_superuser=True)
self.user = self.create_user(email="boop@example.com")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=se... | SentryAppInstallationExternalIssuesEndpointTest |
python | doocs__leetcode | solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution.py | {
"start": 0,
"end": 429
} | class ____:
def earliestAcq(self, logs: List[List[int]], n: int) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
for t, x, y in sorted(logs):
if find(x) == find(y):
continue
p... | Solution |
python | encode__httpx | httpx/_decoders.py | {
"start": 1145,
"end": 2022
} | class ____(ContentDecoder):
"""
Handle 'deflate' decoding.
See: https://stackoverflow.com/questions/1838699
"""
def __init__(self) -> None:
self.first_attempt = True
self.decompressor = zlib.decompressobj()
def decode(self, data: bytes) -> bytes:
was_first_attempt = se... | DeflateDecoder |
python | pydantic__pydantic | .github/actions/people/people.py | {
"start": 6455,
"end": 6566
} | class ____(BaseModel):
"""Container for pull request edges."""
edges: list[PullRequestEdge]
| PullRequests |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 13120,
"end": 13224
} | class ____(SuperTwo):
def __init__(self, a, b, *args):
super().__init__(a, b, *args)
| SubTwoTwo |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 1532,
"end": 1564
} | class ____(): # comment
pass
| C |
python | getsentry__sentry | src/sentry/integrations/services/integration/model.py | {
"start": 2613,
"end": 2758
} | class ____(RpcModel):
integration: RpcIntegration | None
organization_integration: RpcOrganizationIntegration | None
| RpcOrganizationContext |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/node.py | {
"start": 707,
"end": 2211
} | class ____(BaseNodePostprocessor):
"""Keyword-based Node processor."""
required_keywords: List[str] = Field(default_factory=list)
exclude_keywords: List[str] = Field(default_factory=list)
lang: str = Field(default="en")
@classmethod
def class_name(cls) -> str:
return "KeywordNodePostpr... | KeywordNodePostprocessor |
python | pydantic__pydantic | pydantic-core/tests/test_tzinfo.py | {
"start": 1358,
"end": 8497
} | class ____(unittest.TestCase):
"""Adapted from CPython `timezone` tests
Original tests are located here https://github.com/python/cpython/blob/a0bb4a39d1ca10e4a75f50a9fbe90cc9db28d29e/Lib/test/datetimetester.py#L256
"""
def setUp(self):
self.ACDT = TzInfo(timedelta(hours=9.5).total_seconds())
... | TestTzInfo |
python | openai__openai-python | src/openai/types/responses/custom_tool_param.py | {
"start": 291,
"end": 748
} | class ____(TypedDict, total=False):
name: Required[str]
"""The name of the custom tool, used to identify it in tool calls."""
type: Required[Literal["custom"]]
"""The type of the custom tool. Always `custom`."""
description: str
"""Optional description of the custom tool, used to provide more ... | CustomToolParam |
python | django__django | tests/order_with_respect_to/models.py | {
"start": 933,
"end": 1098
} | class ____(models.Model):
dimension = models.ForeignKey("Dimension", on_delete=models.CASCADE)
class Meta:
order_with_respect_to = "dimension"
| Component |
python | facebook__pyre-check | client/configuration/unwatched.py | {
"start": 1571,
"end": 2884
} | class ____:
change_indicator: str
files: UnwatchedFiles
@staticmethod
def from_json(json: Dict[str, object]) -> "UnwatchedDependency":
change_indicator = json.get("change_indicator", None)
if change_indicator is None:
raise exceptions.InvalidConfiguration(
"M... | UnwatchedDependency |
python | getsentry__sentry | src/sentry/replays/lib/new_query/fields.py | {
"start": 6321,
"end": 6414
} | class ____(ColumnField[int]):
"""Integer-type condition column field."""
| IntegerColumnField |
python | astropy__astropy | astropy/modeling/rotations.py | {
"start": 1972,
"end": 4323
} | class ____(Model):
"""
Perform a series of rotations about different axis in 3D space.
Positive angles represent a counter-clockwise rotation.
Parameters
----------
angles : array-like
Angles of rotation in deg in the order of axes_order.
axes_order : str
A sequence of 'x',... | RotationSequence3D |
python | ray-project__ray | python/ray/train/_internal/state/schema.py | {
"start": 910,
"end": 1869
} | class ____(BaseModel):
"""Metadata of a Ray Train worker."""
actor_id: str = Field(description="Actor ID of the worker.")
world_rank: int = Field(description="World rank of the worker.")
local_rank: int = Field(description="Local rank of the worker.")
node_rank: int = Field(description="Node rank o... | TrainWorkerInfo |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 21530,
"end": 21852
} | class ____(TemplateView):
template_name = "account/password_reset_done." + app_settings.TEMPLATE_EXTENSION
password_reset_done = PasswordResetDoneView.as_view()
@method_decorator(rate_limit(action="reset_password_from_key"), name="dispatch")
@method_decorator(login_not_required, name="dispatch")
| PasswordResetDoneView |
python | openai__openai-python | src/openai/resources/containers/files/content.py | {
"start": 5713,
"end": 5950
} | class ____:
def __init__(self, content: AsyncContent) -> None:
self._content = content
self.retrieve = _legacy_response.async_to_raw_response_wrapper(
content.retrieve,
)
| AsyncContentWithRawResponse |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 349337,
"end": 349709
} | class ____(FitDataError):
def __init__(self, ptp, fscale):
self.args = (
"Invalid values in `data`. Maximum likelihood estimation with "
"the uniform distribution and fixed scale requires that "
f"np.ptp(data) <= fscale, but np.ptp(data) = {ptp} and "
f"fscal... | FitUniformFixedScaleDataError |
python | huggingface__transformers | tests/models/swin2sr/test_modeling_swin2sr.py | {
"start": 1334,
"end": 5606
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=32,
patch_size=1,
num_channels=3,
num_channels_out=1,
embed_dim=16,
depths=[1, 2, 1],
num_heads=[2, 2, 4],
window_size=2,
mlp_ratio=2.0,
qkv_bias=... | Swin2SRModelTester |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/config.py | {
"start": 18204,
"end": 19086
} | class ____(IConfigReader):
"""A class that reads cluster config from a K8s RayCluster CR."""
def __init__(self, config_producer: AutoscalingConfigProducer):
self._config_producer = config_producer
self._cached_config = self._generate_configs_from_k8s()
def _generate_configs_from_k8s(self) ... | KubeRayConfigReader |
python | allegroai__clearml | clearml/automation/parameters.py | {
"start": 10604,
"end": 13024
} | class ____(Parameter):
"""
Discrete randomly sampled Hyper-Parameter object.
"""
def __init__(
self,
parameter_combinations: Sequence[Mapping[str, Union[float, int, str, Parameter]]] = (),
) -> ():
"""
Uniformly sample values form a list of discrete options (combinat... | ParameterSet |
python | kamyu104__LeetCode-Solutions | Python/count-paths-that-can-form-a-palindrome-in-a-tree.py | {
"start": 1020,
"end": 1734
} | class ____(object):
def countPalindromePaths(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def dfs(u, mask):
result = 0
if u:
mask ^= 1<<(ord(s[u])-ord('a'))
result += cnt[mask]+sum(c... | Solution2 |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/decrypt.py | {
"start": 208,
"end": 487
} | class ____(object):
# Standard files documentation fragment
DOCUMENTATION = r"""
options:
decrypt:
description:
- This option controls the auto-decryption of source files using vault.
type: bool
default: yes
version_added: '2.4'
"""
| ModuleDocFragment |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-arxiv/llama_index/tools/arxiv/base.py | {
"start": 163,
"end": 1199
} | class ____(BaseToolSpec):
"""arXiv tool spec."""
spec_functions = ["arxiv_query"]
def __init__(self, max_results: Optional[int] = 3):
self.max_results = max_results
def arxiv_query(self, query: str, sort_by: Optional[str] = "relevance"):
"""
A tool to query arxiv.org
A... | ArxivToolSpec |
python | lxml__lxml | test.py | {
"start": 3026,
"end": 11065
} | class ____:
"""Configurable properties of the test runner."""
# test location
basedir = '' # base directory for tests (defaults to
# basedir of argv[0] + 'src'), must be absolute
src_in_path = True # add 'src/' to sys.path
follow_symlinks = Tr... | Options |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 65297,
"end": 67781
} | class ____(_ConfigBase):
name: str
description: Optional[str]
generative_config: Optional[GenerativeConfig]
inverted_index_config: InvertedIndexConfig
multi_tenancy_config: MultiTenancyConfig
properties: List[PropertyConfig]
references: List[ReferencePropertyConfig]
replication_config: R... | _CollectionConfig |
python | tensorflow__tensorflow | tensorflow/lite/python/metrics/metrics_interface.py | {
"start": 748,
"end": 1542
} | class ____(metaclass=abc.ABCMeta):
"""Abstract class for TFLiteMetrics."""
@abc.abstractmethod
def increase_counter_debugger_creation(self):
raise NotImplementedError
@abc.abstractmethod
def increase_counter_interpreter_creation(self):
raise NotImplementedError
@abc.abstractmethod
def increase_... | TFLiteMetricsInterface |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/cyaml.py | {
"start": 1301,
"end": 1884
} | class ____(CParser, SafeConstructor, Resolver): # type: ignore
def __init__(self, stream, version=None, preserve_quotes=None):
# type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
CParser.__init__(self, stream)
self._parser = self._composer = self
SafeConstructor.... | CSafeLoader |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 155037,
"end": 157022
} | class ____(TestCase):
@parametrize(
"byteorder", [subtest("little", name="little"), subtest("big", name="big")]
)
@parametrize("dtype", [float, int, complex])
def test_basic(self, byteorder, dtype):
dt = np.dtype(dtype).newbyteorder(byteorder)
x = (np.random.random((4, 7)) * 5).a... | TestFromBuffer |
python | doocs__leetcode | solution/3100-3199/3171.Find Subarray With Bitwise OR Closest to K/Solution2.py | {
"start": 0,
"end": 255
} | class ____:
def minimumDifference(self, nums: List[int], k: int) -> int:
ans = inf
s = set()
for x in nums:
s = {x | y for y in s} | {x}
ans = min(ans, min(abs(y - k) for y in s))
return ans
| Solution |
python | plotly__plotly.py | plotly/tools.py | {
"start": 20475,
"end": 24915
} | class ____(object):
@staticmethod
def _deprecated(old_method, new_method=None):
if new_method is None:
# The method name stayed the same.
new_method = old_method
warnings.warn(
"plotly.tools.FigureFactory.{} is deprecated. "
"Use plotly.figure_fact... | FigureFactory |
python | getsentry__sentry | tests/sentry/api/serializers/test_apitoken.py | {
"start": 1606,
"end": 2532
} | class ____(TestApiTokenSerializer):
def setUp(self) -> None:
super().setUp()
attrs = self._serializer.get_attrs(item_list=[self._token], user=self._user)
attrs["application"] = None
self._attrs = attrs
def test_no_refresh_token_on_user_token(self) -> None:
serialized_obj... | TestRefreshTokens |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/loader_test.py | {
"start": 1086,
"end": 3920
} | class ____(test.TestCase):
def assertAstMatches(self, actual_node, expected_node_src):
expected_node = gast.parse(expected_node_src).body[0]
msg = 'AST did not match expected:\n{}\nActual:\n{}'.format(
pretty_printer.fmt(expected_node),
pretty_printer.fmt(actual_node))
self.assertTrue(as... | LoaderTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 11619,
"end": 11778
} | class ____(graphene.Interface):
message = graphene.NonNull(graphene.String)
class Meta:
name = "PipelineRunConflict"
| GraphenePipelineRunConflict |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 30050,
"end": 30588
} | class ____(GetItemSource):
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen.add_push_null(
lambda: codegen.load_import_from(utils.__name__, "tuple_iterator_getitem")
)
codegen(self.base)
codegen.append_output(codegen.create_load_const(self.index))
code... | TupleIteratorGetItemSource |
python | tornadoweb__tornado | maint/test/cython/cythonapp_test.py | {
"start": 125,
"end": 450
} | class ____(AsyncTestCase):
@gen_test
def test_native_coroutine(self):
x = yield cythonapp.native_coroutine()
self.assertEqual(x, "goodbye")
@gen_test
def test_decorated_coroutine(self):
x = yield cythonapp.decorated_coroutine()
self.assertEqual(x, "goodbye")
| CythonCoroutineTest |
python | Farama-Foundation__Gymnasium | gymnasium/core.py | {
"start": 537,
"end": 15508
} | class ____(Generic[ObsType, ActType]):
r"""The main Gymnasium class for implementing Reinforcement Learning Agents environments.
The class encapsulates an environment with arbitrary behind-the-scenes dynamics through the :meth:`step` and :meth:`reset` functions.
An environment can be partially or fully obs... | Env |
python | mlflow__mlflow | dev/clint/src/clint/rules/no_rst.py | {
"start": 36,
"end": 151
} | class ____(Rule):
def _message(self) -> str:
return "Do not use RST style. Use Google style instead."
| NoRst |
python | pytorch__pytorch | torch/_export/db/examples/unsupported_operator.py | {
"start": 89,
"end": 411
} | class ____(torch.nn.Module):
"""
torch.sym_min operator is not supported in export.
"""
def forward(self, x):
return x.sum() + torch.sym_min(x.size(0), 100)
example_args = (torch.randn(3, 2),)
tags = {"torch.operator"}
support_level = SupportLevel.NOT_SUPPORTED_YET
model = TorchSymMin()
| TorchSymMin |
python | gevent__gevent | src/greentest/3.9/test_httplib.py | {
"start": 19566,
"end": 47281
} | class ____(TestCase):
def test_dir_with_added_behavior_on_status(self):
# see issue40084
self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
def test_status_lines(self):
# Test HTTP status lines
body = "HTTP/1.1 200 Ok\r\n\r\nText"
s... | BasicTest |
python | scrapy__scrapy | tests/AsyncCrawlerRunner/multi_parallel.py | {
"start": 265,
"end": 669
} | class ____(Spider):
name = "no_request"
async def start(self):
return
yield
@deferred_f_from_coro_f
async def main(reactor):
configure_logging()
runner = AsyncCrawlerRunner()
runner.crawl(NoRequestsSpider)
runner.crawl(NoRequestsSpider)
await runner.join()
install_reacto... | NoRequestsSpider |
python | conda__conda | conda/models/records.py | {
"start": 4284,
"end": 5318
} | class ____(StringField):
def __init__(self):
super().__init__(required=False)
def __get__(self, instance, instance_type):
try:
return super().__get__(instance, instance_type)
except AttributeError:
try:
url = instance.url
except Attrib... | SubdirField |
python | openai__openai-python | tests/test_utils/test_typing.py | {
"start": 344,
"end": 432
} | class ____(BaseGenericMultipleTypeArgs[_T, _T2, _T3]): ...
| SubclassGenericMultipleTypeArgs |
python | scrapy__scrapy | tests/test_pipeline_files.py | {
"start": 11745,
"end": 11869
} | class ____(TestFilesPipelineFieldsMixin):
item_class = FilesPipelineTestDataClass
@attr.s
| TestFilesPipelineFieldsDataClass |
python | encode__django-rest-framework | tests/test_relations_pk.py | {
"start": 15826,
"end": 16782
} | class ____(TestCase):
def setUp(self):
self.target = ForeignKeyTarget.objects.create(name='target-1')
ForeignKeySource.objects.create(name='source-1', target=self.target)
ForeignKeySource.objects.create(name='source-2', target=self.target)
def test_relation_field_callable_source(self):... | PKRelationTests |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 2524,
"end": 2724
} | class ____:
"""Boundary details for parsing composite input."""
delimiters: str
required: bool
match: t.Optional[str] = None
ready: bool = True
@dataclasses.dataclass
| ParserBoundary |
python | bokeh__bokeh | src/bokeh/models/scales.py | {
"start": 2665,
"end": 2939
} | class ____(ContinuousScale):
''' Represent a linear scale transformation between continuous ranges.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| LinearScale |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/kernel_handler.py | {
"start": 2710,
"end": 3406
} | class ____(QThread):
"""Poll for changes in std buffers."""
sig_out = Signal(str)
def __init__(self, parent, std_buffer):
super().__init__(parent)
self._std_buffer = std_buffer
self._closing = False
def run(self):
txt = True
while txt:
try:
... | StdThread |
python | doocs__leetcode | solution/2000-2099/2027.Minimum Moves to Convert String/Solution.py | {
"start": 0,
"end": 241
} | class ____:
def minimumMoves(self, s: str) -> int:
ans = i = 0
while i < len(s):
if s[i] == "X":
ans += 1
i += 3
else:
i += 1
return ans
| Solution |
python | GoogleCloudPlatform__python-docs-samples | functions/slack/main_test.py | {
"start": 933,
"end": 1101
} | class ____:
def __init__(self, data="", headers={}):
self.data = data
self.headers = headers
def get_data(self):
return self.data
| Request |
python | pytorch__pytorch | torch/_inductor/comm_analysis.py | {
"start": 3444,
"end": 16793
} | class ____(IntEnum):
# The ordering and enum values here matches original in
# https://github.com/NVIDIA/nccl/blob/0b083e52096c387bad7a5c5c65b26a9dca54de8c/src/include/devcomm.h#L28
# For difference between these protocols, see https://github.com/NVIDIA/nccl/issues/281#issuecomment-571816990
LL = 0 # L... | NCCL_PROTO |
python | django__django | django/db/models/functions/text.py | {
"start": 9580,
"end": 9711
} | class ____(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform):
function = "SHA256"
lookup_name = "sha256"
| SHA256 |
python | pypa__pip | src/pip/_vendor/urllib3/response.py | {
"start": 3389,
"end": 4249
} | class ____(object):
"""
From RFC7231:
If one or more encodings have been applied to a representation, the
sender that applied the encodings MUST generate a Content-Encoding
header field that lists the content codings in the order in which
they were applied.
"""
def __ini... | MultiDecoder |
python | python__mypy | mypy/test/testtypes.py | {
"start": 54290,
"end": 56126
} | class ____(Suite):
def setUp(self) -> None:
self.fx = TypeFixture()
def test_optional(self) -> None:
t = UnionType.make_union([self.fx.a, self.fx.nonet])
self.assert_union_result(t, [self.fx.a, self.fx.nonet])
def test_two_instances(self) -> None:
t = UnionType.make_union([... | RemoveLastKnownValueSuite |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_model_checkpoint_additional_cases.py | {
"start": 378,
"end": 666
} | class ____(Dataset):
def __init__(self, n: int = 4):
self.x = torch.arange(n, dtype=torch.float32).view(-1, 1)
self.y = self.x.clone()
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
| TinyDataset |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.