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 | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 86071,
"end": 87735
} | class ____:
def test_avx_based_ufunc(self):
strides = np.array([-4, -3, -2, -1, 1, 2, 3, 4])
np.random.seed(42)
for func, prop in avx_ufuncs.items():
maxulperr = prop[0]
minval = prop[1]
maxval = prop[2]
# various array sizes to ensure masking ... | TestAVXUfuncs |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/entity_key.py | {
"start": 1091,
"end": 1293
} | class ____(graphene.ObjectType):
assetKey = graphene.NonNull(GrapheneAssetKey)
partitions = non_null_list(graphene.String)
class Meta:
name = "AssetLineageInfo"
| GrapheneAssetLineageInfo |
python | tornadoweb__tornado | tornado/netutil.py | {
"start": 16750,
"end": 18098
} | class ____(Resolver):
"""Resolver implementation using a `concurrent.futures.Executor`.
Use this instead of `ThreadedResolver` when you require additional
control over the executor being used.
The executor will be shut down when the resolver is closed unless
``close_resolver=False``; use this if y... | ExecutorResolver |
python | ray-project__ray | python/ray/llm/_internal/common/utils/download_utils.py | {
"start": 3721,
"end": 11657
} | class ____(CloudModelAccessor):
"""Unified downloader for models stored in cloud storage (S3 or GCS).
Args:
model_id: The model id to download.
mirror_config: The mirror config for the model.
"""
def get_model(
self,
tokenizer_only: bool,
exclude_safetensors: bo... | CloudModelDownloader |
python | scipy__scipy | scipy/linalg/tests/test_decomp.py | {
"start": 87209,
"end": 95585
} | class ____:
def test_qz_single(self):
rng = np.random.RandomState(12345)
n = 5
A = rng.random([n, n]).astype(float32)
B = rng.random([n, n]).astype(float32)
AA, BB, Q, Z = qz(A, B)
assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5)
assert_array_almost_equal... | TestQZ |
python | TheAlgorithms__Python | data_structures/binary_tree/distribute_coins.py | {
"start": 938,
"end": 3261
} | class ____(NamedTuple):
moves: int
excess: int
def distribute_coins(root: TreeNode | None) -> int:
"""
>>> distribute_coins(TreeNode(3, TreeNode(0), TreeNode(0)))
2
>>> distribute_coins(TreeNode(0, TreeNode(3), TreeNode(0)))
3
>>> distribute_coins(TreeNode(0, TreeNode(0), TreeNode(3)))... | CoinsDistribResult |
python | huggingface__transformers | src/transformers/models/eomt/modeling_eomt.py | {
"start": 34211,
"end": 36638
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim /... | EomtAttention |
python | neetcode-gh__leetcode | python/0377-combination-sum-iv.py | {
"start": 0,
"end": 656
} | class ____:
def combinationSum4(self, nums: List[int], target: int) -> int:
cache = {0: 1}
for total in range(1, target + 1):
cache[total] = 0
for n in nums:
cache[total] += cache.get(total - n, 0)
return cache[target]
def dfs(total):
... | Solution |
python | faif__python-patterns | patterns/structural/decorator.py | {
"start": 950,
"end": 1130
} | class ____:
"""Represents a base text tag"""
def __init__(self, text: str) -> None:
self._text = text
def render(self) -> str:
return self._text
| TextTag |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/grid_finder.py | {
"start": 4644,
"end": 10779
} | class ____:
"""
Internal helper for `~.grid_helper_curvelinear.GridHelperCurveLinear`, with
the same constructor parameters; should not be directly instantiated.
"""
def __init__(self,
transform,
extreme_finder=None,
grid_locator1=None,
... | GridFinder |
python | python__mypy | mypy/meet.py | {
"start": 30644,
"end": 53959
} | class ____(TypeVisitor[ProperType]):
def __init__(self, s: ProperType) -> None:
self.s = s
def visit_unbound_type(self, t: UnboundType) -> ProperType:
if isinstance(self.s, NoneType):
if state.strict_optional:
return UninhabitedType()
else:
... | TypeMeetVisitor |
python | plotly__plotly.py | plotly/graph_objs/waterfall/increasing/_marker.py | {
"start": 233,
"end": 3311
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall.increasing"
_path_str = "waterfall.increasing.marker"
_valid_props = {"color", "line"}
@property
def color(self):
"""
Sets the marker color of all increasing values.
The 'color' property is a color and may b... | Marker |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 16361,
"end": 17418
} | class ____(Instruction):
def __init__(self, parent, ptr, ordering, align, name='', typ=None):
if typ is None:
if isinstance(ptr, AllocaInstr):
typ = ptr.allocated_type
# For compatibility with typed pointers. Eventually this should
# probably be removed (w... | LoadAtomicInstr |
python | sqlalchemy__sqlalchemy | test/ext/declarative/test_reflection.py | {
"start": 12322,
"end": 15798
} | class ____(DeferredInhReflectBase):
@classmethod
def define_tables(cls, metadata):
Table(
"foo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(32)),
Column(... | DeferredSingleInhReflectionTest |
python | Pylons__pyramid | tests/test_csrf.py | {
"start": 7138,
"end": 7758
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def _callFUT(self, *args, **kwargs):
from pyramid.csrf import new_csrf_token
return new_csrf_token(*args, **kwargs)
def test_no_override_csrf_utility_registered(self):
request = testing.DummyRequ... | Test_new_csrf_token |
python | openai__gym | gym/envs/classic_control/mountain_car.py | {
"start": 286,
"end": 9826
} | class ____(gym.Env):
"""
### Description
The Mountain Car MDP is a deterministic MDP that consists of a car placed stochastically
at the bottom of a sinusoidal valley, with the only possible actions being the accelerations
that can be applied to the car in either direction. The goal of the MDP is t... | MountainCarEnv |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_default_format04.py | {
"start": 315,
"end": 1074
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("default_format04.xlsx")
def test_create_file(self):
"""Test the creation of a file with user defined default format"""
workbook = ... | TestCompareXLSXFiles |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_enhanced_section_headers.py | {
"start": 346,
"end": 6705
} | class ____:
"""Test enhanced detection of malformed section headers."""
# Using function-based validation approach
def test_missing_colon_detection(self):
"""Test detection of section headers missing colons."""
docstring = '''"""Function with missing colon in section header.
Args
... | TestEnhancedSectionHeaderDetection |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 39551,
"end": 39699
} | class ____(MutableCompositeColumnDefaultTest):
@classmethod
def _type_fixture(cls):
return DCPoint
| MutableDCCompositeColumnDefaultTest |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qinterpolate_test.py | {
"start": 1123,
"end": 2107
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, dtype, mode, scale, contig):
f_input = (torch.rand(1, M, N, K) - 0.5) * 256
scale = 0.1
zero_point = 42
self.q_input = torch.quantize_per_tensor(
f_input, scale=scale, zero_point=zero_point, dtype=dtype
... | QInterpolateBenchmark |
python | Textualize__textual | src/textual/_queue.py | {
"start": 179,
"end": 1211
} | class ____(Generic[QueueType]):
"""A cut-down version of asyncio.Queue
This has just enough functionality to run the message pumps.
"""
def __init__(self) -> None:
self.values: deque[QueueType] = deque()
self.ready_event = Event()
def put_nowait(self, value: QueueType) -> None:
... | Queue |
python | pypa__pipenv | pipenv/patched/pip/_internal/build_env.py | {
"start": 1206,
"end": 2736
} | class ____:
def __init__(self, path: str) -> None:
self.path = path
self.setup = False
scheme = get_scheme("", prefix=path)
self.bin_dir = scheme.scripts
self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
def get_runnable_pip() -> str:
"""Get a file to pass to a Pyt... | _Prefix |
python | walkccc__LeetCode | solutions/51. N-Queens/51.py | {
"start": 0,
"end": 602
} | class ____:
def solveNQueens(self, n: int) -> list[list[str]]:
ans = []
cols = [False] * n
diag1 = [False] * (2 * n - 1)
diag2 = [False] * (2 * n - 1)
def dfs(i: int, board: list[int]) -> None:
if i == n:
ans.append(board)
return
for j in range(n):
if cols[j] ... | Solution |
python | pytorch__pytorch | torch/_dynamo/aot_compile.py | {
"start": 986,
"end": 1571
} | class ____:
signature: inspect.Signature
guard_manager: Optional["GuardManagerWrapper"]
guards_state: bytes
backend_id: str
compiled_fn: SerializableCallable
original_code: types.CodeType
runtime_env: GraphRuntimeEnv
source_info: "SourceInfo"
device_type: str
backend_name: str
... | CompileArtifacts |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared_tests/test_checked.py | {
"start": 555,
"end": 3597
} | class ____: ...
def test_many():
@checked
def big(
name: str,
nick_names: list[str],
age: int,
cool: bool,
thing: Optional[Thing],
other_thing: Thing,
percent: float,
o_s: Optional[str],
o_n: Optional[int],
o_f: Optional[float],
... | Thing |
python | coleifer__peewee | tests/regressions.py | {
"start": 3936,
"end": 4007
} | class ____(TestModel):
c = ForeignKeyField(DiC)
d = TextField()
| DiD |
python | tensorflow__tensorflow | tensorflow/python/ops/variables.py | {
"start": 2483,
"end": 3496
} | class ____(enum.Enum):
"""Indicates when a distributed variable will be synced.
* `AUTO`: Indicates that the synchronization will be determined by the current
`DistributionStrategy` (eg. With `MirroredStrategy` this would be
`ON_WRITE`).
* `NONE`: Indicates that there will only be one copy of the variabl... | VariableSynchronization |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/chat_store/base.py | {
"start": 242,
"end": 2718
} | class ____(BaseComponent):
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "BaseChatStore"
@abstractmethod
def set_messages(self, key: str, messages: List[ChatMessage]) -> None:
"""Set messages for a key."""
...
@abstractmethod
def get_mess... | BaseChatStore |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 14192,
"end": 15029
} | class ____(BaseGroupingComponent[ExceptionGroupingComponent]):
id: str = "chained_exception"
frame_counts: Counter[str]
reverse_when_serializing: bool = False
def __init__(
self,
values: Sequence[ExceptionGroupingComponent] | None = None,
hint: str | None = None,
contrib... | ChainedExceptionGroupingComponent |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 112582,
"end": 112739
} | class ____(ServerAdapter):
def run(self, handler):
from waitress import serve
serve(handler, host=self.host, port=self.port)
| WaitressServer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 542330,
"end": 542993
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("PullRequestTimelineItemEdge"), graphql_name="edges"
)
nod... | PullRequestTimelineConnection |
python | facebookresearch__faiss | tests/test_fast_scan_ivf.py | {
"start": 6392,
"end": 7966
} | class ____(unittest.TestCase):
""" Verify implem 2 (search with original invlists with uint8 LUTs)
against IndexIVFPQ. Entails some loss in accuracy. """
def eval_quant_loss(self, by_residual, metric=faiss.METRIC_L2):
ds = datasets.SyntheticDataset(32, 2000, 5000, 1000)
index = faiss.inde... | TestIVFImplem2 |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 45348,
"end": 45634
} | class ____(ServeActorDetails, frozen=True):
"""Detailed info about a Ray Serve ProxyActor.
Attributes:
status: The current status of the proxy.
"""
status: ProxyStatus = Field(description="Current status of the proxy.")
@PublicAPI(stability="alpha")
| ProxyDetails |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 2724,
"end": 6230
} | class ____:
"""State of the composite argument parser."""
mode: ParserMode
remainder: str = ''
consumed: str = ''
boundaries: list[ParserBoundary] = dataclasses.field(default_factory=list)
namespaces: list[t.Any] = dataclasses.field(default_factory=list)
parts: list[str] = dataclasses.field... | ParserState |
python | pallets__itsdangerous | src/itsdangerous/exc.py | {
"start": 436,
"end": 882
} | class ____(BadData):
"""Raised if a signature does not match."""
def __init__(self, message: str, payload: t.Any | None = None):
super().__init__(message)
#: The payload that failed the signature test. In some
#: situations you might still want to inspect this, even if
#: you k... | BadSignature |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 87245,
"end": 87500
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING
AutoModelForTimeSeriesPrediction = auto_class_update(
AutoModelForTimeSeriesPrediction, head_doc="time-series prediction"
)
| AutoModelForTimeSeriesPrediction |
python | doocs__leetcode | solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/Solution.py | {
"start": 0,
"end": 541
} | class ____:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
ans = []
m = len(s)
mp = {"L": [0, -1], "R": [0, 1], "U": [-1, 0], "D": [1, 0]}
for i in range(m):
x, y = startPos
t = 0
for j in range(i, m):
... | Solution |
python | coleifer__peewee | tests/model_save.py | {
"start": 4175,
"end": 5101
} | class ____(ModelTestCase):
requires = [T5]
def test_save_no_data(self):
t5 = T5.create()
self.assertTrue(t5.id >= 1)
t5.val = 3
t5.save()
t5_db = T5.get(T5.id == t5.id)
self.assertEqual(t5_db.val, 3)
t5.val = None
t5.save()
t5_db = T5.... | TestSaveNoData |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 11754,
"end": 12643
} | class ____(OIDCOnlyMixin):
"""
Mixin for views that should only be accessible when OIDC and OIDC RP-Initiated Logout are enabled.
If either is not enabled:
* if DEBUG is True, raises an ImproperlyConfigured exception explaining why
* otherwise, returns a 404 response, logging the same warning
... | OIDCLogoutOnlyMixin |
python | keon__algorithms | algorithms/graph/minimum_spanning_tree.py | {
"start": 327,
"end": 4809
} | class ____:
"""
The disjoint set is represented with an list <n> of integers where
<n[i]> is the parent of the node at position <i>.
If <n[i]> = <i>, <i> it's a root, or a head, of a set
"""
def __init__(self, size):
"""
Args:
n (int): Number of vertices in the graph... | DisjointSet |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_glue.py | {
"start": 1823,
"end": 16324
} | class ____:
@pytest.mark.db_test
def test_render_template(self, create_task_instance_of_operator, session):
ti: TaskInstance = create_task_instance_of_operator(
GlueJobOperator,
dag_id=DAG_ID,
task_id=TASK_ID,
script_location="{{ dag.dag_id }}",
... | TestGlueJobOperator |
python | simonw__datasette | datasette/events.py | {
"start": 724,
"end": 888
} | class ____(Event):
"""
Event name: ``logout``
A user (represented by ``event.actor``) has logged out.
"""
name = "logout"
@dataclass
| LogoutEvent |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 27085,
"end": 30107
} | class ____(DataType):
"""
A fixed categorical encoding of a unique set of strings.
Parameters
----------
categories
The categories in the dataset; must be a unique set of strings, or an
existing Python string-valued enum.
Examples
--------
Explicitly define enumeration ... | Enum |
python | Textualize__textual | tests/option_list/test_option_list_option_subclass.py | {
"start": 251,
"end": 451
} | class ____(Option):
"""An example subclass of a option."""
def __init__(self, test: int) -> None:
super().__init__(str(test), str(test), False)
self.test = test
| OptionWithExtras |
python | OmkarPathak__pygorithm | tests/test_greedy_algorithm.py | {
"start": 383,
"end": 724
} | class ____(unittest.TestCase):
def test_activity_selection(self):
start_times = [1 , 3 , 0 , 5 , 8 , 5]
finish_times = [2 , 4 , 6 , 7 , 9 , 9]
self.assertEqual(activity_selection.activity_selection(start_times, finish_times), [0, 1, 3, 4])
if __name__ == '__main__':
unittest.main()
| TestActivitySelectionProblem |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 11919,
"end": 12605
} | class ____(nn.Module):
def __init__(self, config: MobileViTConfig, hidden_size: int, num_stages: int) -> None:
super().__init__()
self.layer = nn.ModuleList()
for _ in range(num_stages):
transformer_layer = MobileViTTransformerLayer(
config,
hidde... | MobileViTTransformer |
python | plotly__plotly.py | plotly/graph_objs/ohlc/_increasing.py | {
"start": 233,
"end": 2375
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "ohlc"
_path_str = "ohlc.increasing"
_valid_props = {"line"}
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.ohlc.i... | Increasing |
python | spyder-ide__spyder | spyder/plugins/explorer/confpage.py | {
"start": 571,
"end": 3849
} | class ____(PluginConfigPage):
def setup_page(self):
# Variables
newcb = self.create_checkbox
# Widgets
general_widget = QWidget()
# General options group
basic_group = QGroupBox(_("General options"))
check_show_hidden_files = newcb(_("Show hidden files"), '... | ExplorerConfigPage |
python | numba__llvmlite | llvmlite/binding/typeref.py | {
"start": 5519,
"end": 7805
} | class ____(_TypeIterator):
def _dispose(self):
self._capi.LLVMPY_DisposeElementIter(self)
def _next(self):
return ffi.lib.LLVMPY_ElementIterNext(self)
# FFI
ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef]
ffi.lib.LLVMPY_PrintType.restype = c_void_p
ffi.lib.LLVMPY_TypeIsPointer.argtyp... | _TypeListIterator |
python | getsentry__sentry | src/sentry/relay/types/rule_condition.py | {
"start": 776,
"end": 913
} | class ____(TypedDict):
"""Greater than or equal condition"""
op: Literal["gte"]
name: str
value: Value | None
| GteCondition |
python | django__django | tests/view_tests/tests/test_debug.py | {
"start": 21030,
"end": 50578
} | class ____(SimpleTestCase):
rf = RequestFactory()
def test_request_and_exception(self):
"A simple exception report can be generated"
try:
request = self.rf.get("/test_view/")
request.user = User()
raise ValueError("Can't find my keys")
except ValueErr... | ExceptionReporterTests |
python | scikit-learn__scikit-learn | sklearn/neural_network/_stochastic_optimizers.py | {
"start": 1971,
"end": 6085
} | class ____(BaseOptimizer):
"""Stochastic gradient descent optimizer with momentum
Parameters
----------
params : list, length = len(coefs_) + len(intercepts_)
The concatenated list containing coefs_ and intercepts_ in MLP model.
Used for initializing velocities and updating params
... | SGDOptimizer |
python | catalyst-team__catalyst | catalyst/contrib/layers/lama.py | {
"start": 153,
"end": 403
} | class ____(nn.Module):
"""@TODO: Docs. Contribution is welcome."""
def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
"""Forward call."""
x_out = x[:, -1:, :]
return x_out
| TemporalLastPooling |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib.py | {
"start": 26845,
"end": 40685
} | class ____(_IterableInput, composite_tensor.CompositeTensor):
"""Distributed dataset that supports prefetching to multiple devices."""
def __init__(
self,
input_workers,
strategy,
dataset=None,
num_replicas_in_sync=None,
input_context=None,
components=None,
element_s... | DistributedDataset |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/scroll_visible.py | {
"start": 359,
"end": 611
} | class ____(App):
def compose(self) -> ComposeResult:
with VerticalScroll():
yield MyCustomWidget()
def key_t(self) -> None:
self.query_one("#target").scroll_visible()
if __name__ == "__main__":
MyApp().run()
| MyApp |
python | huggingface__transformers | tests/models/prompt_depth_anything/test_image_processing_prompt_depth_anything.py | {
"start": 2811,
"end": 9180
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = PromptDepthAnythingImageProcessor if is_vision_available() else None
fast_image_processing_class = PromptDepthAnythingImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
... | PromptDepthAnythingImageProcessingTest |
python | getsentry__sentry | tests/snuba/rules/conditions/test_event_frequency.py | {
"start": 32548,
"end": 43492
} | class ____(StandardIntervalTestBase):
__test__ = Abstract(__module__, __qualname__)
rule_cls = EventUniqueUserFrequencyConditionWithConditions
def increment(self, event, count, environment=None, timestamp=None):
timestamp = timestamp if timestamp else before_now(minutes=1)
data = {"fingerp... | EventUniqueUserFrequencyConditionWithConditionsTestCase |
python | sqlalchemy__sqlalchemy | test/orm/test_syntax_extensions.py | {
"start": 1321,
"end": 1940
} | class ____(SyntaxExtension, ClauseElement):
_traverse_internals = []
def apply_to_select(self, select_stmt):
select_stmt.apply_syntax_extension_point(
lambda existing: [*existing, self],
"post_criteria",
)
def apply_to_update(self, update_stmt: Update) -> None:
... | PostCriteriaClause |
python | django__django | django/db/models/fields/related_lookups.py | {
"start": 5874,
"end": 5958
} | class ____(RelatedLookupMixin, GreaterThanOrEqual):
pass
| RelatedGreaterThanOrEqual |
python | getsentry__sentry | src/sentry/api/permissions.py | {
"start": 2609,
"end": 2984
} | class ____(BasePermission):
def has_permission(self, request: Request, view: object) -> bool:
enforce_staff_permission = has_staff_option(request.user)
if enforce_staff_permission:
return StaffPermission().has_permission(request, view)
return SuperuserPermission().has_permissio... | SuperuserOrStaffFeatureFlaggedPermission |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 55832,
"end": 58058
} | class ____(Interface):
"""
A cache buster modifies the URL generation machinery for
:meth:`~pyramid.request.Request.static_url`. See :ref:`cache_busting`.
.. versionadded:: 1.6
"""
def __call__(request, subpath, kw):
"""
Modifies a subpath and/or keyword arguments from which a ... | ICacheBuster |
python | pennersr__django-allauth | tests/apps/socialaccount/base.py | {
"start": 5207,
"end": 14943
} | class ____:
provider_id: str
def get_mocked_response(self):
pass
def get_expected_to_str(self):
raise NotImplementedError
def get_access_token(self) -> str:
return "testac"
def get_refresh_token(self) -> str:
return "testrf"
def get_login_response_json(self, ... | OAuth2TestsMixin |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 8403,
"end": 8799
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
if scipy.sparse.issparse(X):
return float(helper_functions.get_value("MissingValues").sum())
else:
return float(np.count_nonzero(helper_functions.get_value("MissingValues")))
@metafeatures.define("Perce... | NumberOfMissingValues |
python | facebook__pyre-check | client/language_server/tests/daemon_connection_test.py | {
"start": 841,
"end": 1248
} | class ____(AsyncContextManager[T]):
def __init__(self, value: T) -> None:
self.value: T = value
async def __aenter__(self) -> T:
return self.value
async def __aexit__(
self,
typ: Optional[Type[BaseException]],
value: Optional[BaseException],
traceback: Optio... | MockAsyncContextManager |
python | mlflow__mlflow | mlflow/projects/databricks.py | {
"start": 3469,
"end": 22005
} | class ____:
"""
Helper class for running an MLflow project as a Databricks Job.
Args:
databricks_profile: Optional Databricks CLI profile to use to fetch hostname &
authentication information when making Databricks API requests.
"""
def __init__(self, databricks_profile_uri):
... | DatabricksJobRunner |
python | getsentry__sentry | src/sentry/services/eventstore/reprocessing/redis.py | {
"start": 721,
"end": 7083
} | class ____(ReprocessingStore):
def __init__(self, **options: dict[str, Any]) -> None:
cluster = options.pop("cluster", "default")
assert isinstance(cluster, str), "cluster option must be a string"
self.redis = redis_clusters.get(cluster)
def event_count_for_hashes(
self, project... | RedisReprocessingStore |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/expandinput.py | {
"start": 1723,
"end": 2995
} | class ____(RuntimeError):
"""
Raise when ``get_map_lengths`` cannot populate all mapping metadata.
This is generally due to not all upstream tasks have finished when the
function is called.
"""
def __init__(self, missing: set[str]) -> None:
self.missing = missing
def __str__(self)... | NotFullyPopulated |
python | numba__numba | numba/tests/test_extending.py | {
"start": 47813,
"end": 53063
} | class ____(TestCase):
def setUp(self):
super().setUp()
many = base_dummy_type_factory("mydummy2")
self.DynTypeType, self.DynType, self.dyn_type_type = many
self.dyn_type = self.DynType()
def test_unboxer_basic(self):
# Implements an unboxer on DynType that calls an intri... | TestBoxingCallingJIT |
python | doocs__leetcode | lcof2/剑指 Offer II 108. 单词演变/Solution.py | {
"start": 0,
"end": 816
} | class ____:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
words = set(wordList)
q = deque([beginWord])
ans = 1
while q:
n = len(q)
for _ in range(n):
s = q.popleft()
s = list(s)
... | Solution |
python | fluentpython__example-code-2e | 24-class-metaprog/slots/slots_timing.py | {
"start": 612,
"end": 711
} | class ____(type):
def __prepare__(name, bases):
return dict(__slots__=('x', 'y'))
| Correct2 |
python | facebook__pyre-check | client/command_arguments.py | {
"start": 8046,
"end": 8791
} | class ____:
working_directory: Path
annotate_attributes: bool = False
annotate_from_existing_stubs: bool = False
debug_infer: bool = False
quote_annotations: bool = False
dequalify: bool = False
enable_memory_profiling: bool = False
enable_profiling: bool = False
log_identifier: Opti... | InferArguments |
python | walkccc__LeetCode | solutions/2381. Shifting Letters II/2381.py | {
"start": 0,
"end": 471
} | class ____:
def shiftingLetters(self, s: str, shifts: list[list[int]]) -> str:
ans = []
currShift = 0
line = [0] * (len(s) + 1)
for start, end, direction in shifts:
diff = 1 if direction else -1
line[start] += diff
line[end + 1] -= diff
for i, c in enumerate(s):
currShift... | Solution |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_typing.py | {
"start": 3660,
"end": 3713
} | class ____(A[str]): # [unsubscriptable-object]
...
| B |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 46958,
"end": 47417
} | class ____(TestCase):
@staticmethod
def application(env, start_response):
start_response('304 Not modified', [])
yield b""
yield b""
def test_err(self):
with self.makefile() as fd:
fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')
... | TestEmptyYield304 |
python | pytorch__pytorch | torch/testing/_internal/common_methods_invocations.py | {
"start": 407734,
"end": 407886
} | class ____(enum.Enum):
TensorList = enum.auto()
ScalarList = enum.auto()
Scalar = enum.auto()
Tensor = enum.auto()
| ForeachRightmostArgType |
python | pypa__warehouse | warehouse/admin/services.py | {
"start": 397,
"end": 1580
} | class ____:
def __init__(self, base):
# This class should not be used in production, it's trivial for it to
# be used to read arbitrary files from the disk. It is intended ONLY
# for local development with trusted users. To make this clear, we'll
# raise a warning.
warnings.w... | LocalSponsorLogoStorage |
python | coleifer__peewee | tests/regressions.py | {
"start": 52748,
"end": 54126
} | class ____(ModelTestCase):
requires = [User]
@skip_if(IS_MYSQL) # mysql can't do anything normally.
def test_weird_aliases(self):
User.create(username='huey')
def assertAlias(s, expected):
query = User.select(s).dicts()
row = query[0]
self.assertEqual(li... | TestWeirdAliases |
python | great-expectations__great_expectations | tests/metrics/test_metric.py | {
"start": 768,
"end": 929
} | class ____(ColumnMetric[ColumnValuesAboveResult]):
name = FULLY_QUALIFIED_METRIC_NAME
min_value: Comparable
strict_min: bool = False
| ColumnValuesAbove |
python | getsentry__sentry | src/sentry/ingest/transaction_clusterer/rules.py | {
"start": 726,
"end": 876
} | class ____(Protocol):
def read(self, project: Project) -> RuleSet: ...
def write(self, project: Project, rules: RuleSet) -> None: ...
| RuleStore |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 35061,
"end": 36523
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("no_NO")
Faker.seed(0)
def test_no_NO_ssn_checksum(self):
assert no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7], no_Provider.scale1) == 6
assert no_checksum([0, 1, 0, 2, 0, 3, 9, 8, 7, 6], no_Provider.scale2) == 7
d... | TestNoNO |
python | bottlepy__bottle | bottle.py | {
"start": 139131,
"end": 139428
} | class ____(ServerAdapter):
""" Untested. """
def run(self, handler):
depr(0, 13, "Diesel is not tested or supported and will be removed.")
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
| DieselServer |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_cli.py | {
"start": 18048,
"end": 18652
} | class ____:
def test_address(self, mock_sdk_client):
_job_cli_group_test_address(mock_sdk_client, "status", "fake_job_id")
def test_status(self, mock_sdk_client):
runner = CliRunner()
mock_client_instance = mock_sdk_client.return_value
with set_env_var("RAY_ADDRESS", "env_addr"... | TestStatus |
python | pydantic__pydantic | pydantic/functional_validators.py | {
"start": 18831,
"end": 19218
} | class ____(core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]):
"""`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`."""
def __call__( # noqa: D102
self,
value: Any,
outer_location: str | int | None = None,
/,
) -> _M... | ModelWrapValidatorHandler |
python | jazzband__django-model-utils | tests/models.py | {
"start": 3928,
"end": 4068
} | class ____(models.Model):
name = models.CharField(max_length=25)
name_changed = MonitorField(monitor="name", when=[])
| MonitorWhenEmpty |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/externaltest/package.py | {
"start": 217,
"end": 544
} | class ____(Package):
homepage = "http://somewhere.com"
url = "http://somewhere.com/test-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
depends_on("stuff")
depends_on("externaltool")
def install(self, spec, prefix):
touch(join_path(prefix, "an_installation_file"))
| Externaltest |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 7491,
"end": 11514
} | class ____(containers.VerticalGroup):
"""Demonstrates Logs."""
DEFAULT_CLASSES = "column"
LOGS_MD = """\
## Logs and Rich Logs
A Log widget to efficiently display a scrolling view of text, with optional highlighting.
And a RichLog widget to display Rich renderables.
"""
DEFAULT_CSS = """
Logs {
... | Logs |
python | pytorch__pytorch | tools/test/heuristics/test_interface.py | {
"start": 10909,
"end": 14726
} | class ____(TestTD):
def check(
self,
tests: list[str],
test_prioritizations: list[dict[TestRun, float]],
expected: dict[TestRun, float],
) -> None:
aggregated_heuristics = interface.AggregatedHeuristics(tests)
for i, test_prioritization in enumerate(test_prioritiz... | TestAggregatedHeuristics |
python | mlflow__mlflow | mlflow/store/tracking/dbmodels/models.py | {
"start": 22556,
"end": 25472
} | class ____(Base):
__tablename__ = "trace_info"
request_id = Column(String(50), nullable=False)
"""
Trace ID: `String` (limit 50 characters). *Primary Key* for ``trace_info`` table.
Named as "trace_id" in V3 format.
"""
experiment_id = Column(Integer, ForeignKey("experiments.experiment_id"),... | SqlTraceInfo |
python | doocs__leetcode | solution/0300-0399/0376.Wiggle Subsequence/Solution.py | {
"start": 0,
"end": 440
} | class ____:
def wiggleMaxLength(self, nums: List[int]) -> int:
n = len(nums)
ans = 1
f = [1] * n
g = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
f[i] = max(f[i], g[j] + 1)
elif nums[j] ... | Solution |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_project_release_details.py | {
"start": 1818,
"end": 7586
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user)
project = self.create_project(name="foo")
project2 = self.create_project(name="bar", organization=project.organization)
release = Release.objects.create(organization_id=project.organization_id, ve... | UpdateReleaseDetailsTest |
python | kamyu104__LeetCode-Solutions | Python/find-building-where-alice-and-bob-can-meet.py | {
"start": 2166,
"end": 3064
} | class ____(object):
def leftmostBuildingQueries(self, heights, queries):
"""
:type heights: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
result = [-1]*len(queries)
qs = [[] for _ in xrange(len(heights))]
for i, (a, b) in enumerate(que... | Solution2 |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 110159,
"end": 111604
} | class ____(IR):
"""Concatenate dataframes vertically."""
__slots__ = ("zlice",)
_non_child = ("schema", "zlice")
zlice: Zlice | None
"""Optional slice to apply to the result."""
def __init__(self, schema: Schema, zlice: Zlice | None, *children: IR):
self.schema = schema
self.zl... | Union |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-fish-in-a-grid.py | {
"start": 1146,
"end": 2131
} | class ____(object):
def findMaxFish(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def dfs(i, j):
result = grid[i][j]
grid[i][j] = 0
stk = [(i, j)]
while stk:... | Solution2 |
python | TheAlgorithms__Python | data_structures/suffix_tree/suffix_tree.py | {
"start": 354,
"end": 2005
} | class ____:
def __init__(self, text: str) -> None:
"""
Initializes the suffix tree with the given text.
Args:
text (str): The text for which the suffix tree is to be built.
"""
self.text: str = text
self.root: SuffixTreeNode = SuffixTreeNode()
sel... | SuffixTree |
python | getsentry__sentry | tests/sentry/api/endpoints/test_seer_models.py | {
"start": 239,
"end": 3911
} | class ____(APITestCase):
endpoint = "sentry-api-0-seer-models"
def setUp(self) -> None:
super().setUp()
self.url = "/api/0/seer/models/"
@patch("sentry.api.endpoints.seer_models.requests.get")
def test_get_models_successful(self, mock_get: MagicMock) -> None:
"""Test successful... | TestSeerModels |
python | RobertCraigie__pyright-python | src/pyright/_mureq.py | {
"start": 8309,
"end": 8942
} | class ____(HTTPException):
"""HTTPErrorStatus is raised by Response.raise_for_status() to indicate an
HTTP error code (a 40x or a 50x). Note that a well-formed response with an
error code does not result in an exception unless raise_for_status() is
called explicitly.
"""
def __init__(self, stat... | HTTPErrorStatus |
python | catalyst-team__catalyst | catalyst/core/callback.py | {
"start": 4802,
"end": 5014
} | class ____(Callback):
"""Scheduler callback interface, abstraction over scheduler step."""
def __init__(self):
"""Init."""
super().__init__(order=CallbackOrder.Scheduler)
| ISchedulerCallback |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 22318,
"end": 22743
} | class ____(Sky2PixProjection, Cylindrical):
r"""
Plate carrée projection - sky to pixel.
Corresponds to the ``CAR`` projection in FITS WCS.
.. math::
x &= \phi \\
y &= \theta
"""
@staticmethod
def evaluate(phi, theta):
# The intermediate variables are only used her... | Sky2Pix_PlateCarree |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 5059,
"end": 5235
} | class ____(TypedDict):
date: datetime
total_users: int
crash_free_users: float | None
total_sessions: int
crash_free_sessions: float | None
| CrashFreeBreakdown |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 120444,
"end": 123109
} | class ____(WrapHigherOrderVariable):
def install_subgraph_in_output_graph(
self, tx, fn_vt, fn_args_vt, kwargs, body_gmod, attr_name="wrap_body"
):
return tx.output.install_subgraph(
"hints_wrapper_body",
body_gmod,
)
@raise_hard_error_if_graph_break(
... | HintsWrapperHigherOrderVariable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.