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 | scikit-learn__scikit-learn | examples/miscellaneous/plot_metadata_routing.py | {
"start": 5499,
"end": 13510
} | class ____(MetaEstimatorMixin, ClassifierMixin, BaseEstimator):
def __init__(self, estimator):
self.estimator = estimator
def get_metadata_routing(self):
# This method defines the routing for this meta-estimator.
# In order to do so, a `MetadataRouter` instance is created, and the
... | MetaClassifier |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 3679,
"end": 8599
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
# Create a collision with the org slug we'll be requesting.
self.requested_org_slug = "testing"
self.existing_org_owner = self.create_user(
email="existing_org_owner@example.com",
is_superuser=Fal... | RelocationTaskTestCase |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 75370,
"end": 76374
} | class ____(SkipFunctionVariable):
def __init__(
self,
wrapped: VariableTracker,
context: "ContextWrappingVariable",
**kwargs: Any,
) -> None:
kwargs.pop("value", None)
kwargs.pop("reason", None)
super().__init__(wrapped.value, reason=wrapped.reason, **kwar... | WrappedSkipFunctionVariable |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py | {
"start": 2783,
"end": 4242
} | class ____(EcsBaseTestCase):
@pytest.mark.parametrize("aws_conn_id", [None, NOTSET, "aws_test_conn"])
@pytest.mark.parametrize("region_name", [None, NOTSET, "ca-central-1"])
def test_initialise_operator(self, aws_conn_id, region_name):
"""Test sensor initialize."""
op_kw = {"aws_conn_id": aw... | TestEcsBaseSensor |
python | pytorch__pytorch | torch/_dynamo/trace_rules.py | {
"start": 127316,
"end": 144877
} | class ____:
"""
Track a set of `id()`s of objects which are either allowed or not
allowed to go into the generated FX graph. Use to test for torch.*,
numpy.*, builtins.*, etc.
Support user modification to permit customization of what can be
added to the graph and what will cause a graph break.... | FunctionIdSet |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 4085,
"end": 4343
} | class ____(HasOptions, Generic[R]):
def __init__(self, function: Callable[[], R]) -> None:
pass
def remote(
self,
) -> "ObjectRef[R]":
...
def bind(
self,
) -> "DAGNode[R]":
...
| RemoteFunctionNoArgs |
python | getsentry__sentry | src/sentry/backup/sanitize.py | {
"start": 1102,
"end": 1203
} | class ____(Exception):
"""
A catch-all class for sanitization errors.
"""
| SanitizationError |
python | ray-project__ray | python/ray/cloudpickle/cloudpickle.py | {
"start": 19053,
"end": 39896
} | class ____:
"""Sentinel for empty closures."""
@classmethod
def __reduce__(cls):
return cls.__name__
def _make_function(code, globals, name, argdefs, closure):
# Setting __builtins__ in globals is needed for nogil CPython.
globals["__builtins__"] = __builtins__
return types.FunctionTy... | _empty_cell_value |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dependency.py | {
"start": 23871,
"end": 31936
} | class ____(_DependencyProcessor):
def __init__(self, prop):
_DependencyProcessor.__init__(self, prop)
for mapper in self.mapper.self_and_descendants:
mapper._dependency_processors.append(_DetectKeySwitch(prop))
def per_property_dependencies(
self,
uow,
parent... | _ManyToOneDP |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 774,
"end": 951
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.StandardModel
sqlalchemy_session = None
id = factory.Sequence(lambda n: n)
| NoSessionFactory |
python | PrefectHQ__prefect | src/prefect/server/exceptions.py | {
"start": 296,
"end": 407
} | class ____(PrefectException):
"""An error raised while orchestrating a state transition"""
| OrchestrationError |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/environments.py | {
"start": 12165,
"end": 17163
} | class ____(BuildCommand):
"""
Create a docker container and run a command inside the container.
Build command to execute in docker container
"""
bash_escape_re = re.compile(
r"([\s\!\"\#\$\&\'\(\)\*\:\;\<\>\?\@\[\\\]\^\`\{\|\}\~])" # noqa
)
def __init__(self, *args, escape_comman... | DockerBuildCommand |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/backends/sphinx.py | {
"start": 7200,
"end": 8832
} | class ____(BaseSphinx):
sphinx_builder = "singlehtml"
relative_output_dir = "htmlzip"
def _post_build(self):
"""Internal post build to create the ZIP file from the HTML output."""
target_file = os.path.join(
self.absolute_container_output_dir,
# TODO: shouldn't this ... | LocalMediaBuilder |
python | doocs__leetcode | solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution3.py | {
"start": 192,
"end": 842
} | class ____:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
while root:
if root.right is None:
ans.append(root.val)
root = root.left
else:
next = root.right
while next.left and next.... | Solution |
python | tox-dev__tox | src/tox/config/cli/ini.py | {
"start": 466,
"end": 3172
} | class ____:
TOX_CONFIG_FILE_ENV_VAR = "TOX_USER_CONFIG_FILE"
STATE: ClassVar[dict[bool | None, str]] = {None: "failed to parse", True: "active", False: "missing"}
def __init__(self) -> None:
config_file = os.environ.get(self.TOX_CONFIG_FILE_ENV_VAR, None)
self.is_env_var = config_file is no... | IniConfig |
python | pandas-dev__pandas | pandas/core/dtypes/base.py | {
"start": 890,
"end": 13654
} | class ____:
"""
A custom data type, to be paired with an ExtensionArray.
This enables support for third-party and custom dtypes within the
pandas ecosystem. By implementing this interface and pairing it with a custom
`ExtensionArray`, users can create rich data types that integrate cleanly
with... | ExtensionDtype |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-solr/llama_index/readers/solr/base.py | {
"start": 257,
"end": 3359
} | class ____(BasePydanticReader):
"""
Read documents from a Solr index.
These documents can then be used in a downstream Llama Index data structure.
"""
endpoint: str = Field(description="Full endpoint, including collection info.")
_client: Any = PrivateAttr()
def __init__(
self,
... | SolrReader |
python | wandb__wandb | tools/bench/_timing.py | {
"start": 137,
"end": 1364
} | class ____:
function_name: str
runtime_seconds: float
def timeit(
timings: List[FunctionTiming],
):
"""Timing decorator.
Args:
timings: list of FunctionTiming to append for each function call
"""
def timing_func(func):
def wrapper(*args, **kwargs):
t1 = time.ti... | FunctionTiming |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 16404,
"end": 18148
} | class ____(Structure):
_fields_ = (
("segname", p_str16),
("vmaddr", p_uint64),
("vmsize", p_uint64),
("fileoff", p_uint64),
("filesize", p_uint64),
("maxprot", vm_prot_t),
("initprot", vm_prot_t),
("nsects", p_uint32), # read the section structures ?... | segment_command_64 |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-vertexai-search/llama_index/retrievers/vertexai_search/base.py | {
"start": 900,
"end": 15227
} | class ____(BaseRetriever):
"""
`Vertex AI Search` retrieval.
For a detailed explanation of the Vertex AI Search concepts
and configuration parameters, refer to the product documentation.
https://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction
Args:
projec... | VertexAISearchRetriever |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_sampled_from.py | {
"start": 2472,
"end": 2640
} | class ____(enum.Flag):
a = enum.auto()
b = enum.auto()
c = enum.auto()
LargeFlag = enum.Flag("LargeFlag", {f"bit{i}": enum.auto() for i in range(64)})
| AFlag |
python | pytorch__pytorch | test/ao/sparsity/test_structured_sparsifier.py | {
"start": 1084,
"end": 1494
} | class ____(BaseStructuredSparsifier):
def update_mask(self, module, tensor_name, **kwargs):
"""Prunes 1/3 of the weight output channels, so resulting module has 33.3% pruning"""
num_rows = len(module.parametrizations[tensor_name][0].mask)
prune = random.sample(list(range(num_rows)), num_rows... | ImplementedPruner |
python | pandas-dev__pandas | asv_bench/benchmarks/inference.py | {
"start": 2677,
"end": 3691
} | class ____:
def setup(self):
self.ts_sec = Series(range(1521080307, 1521685107), dtype="int64")
self.ts_sec_uint = Series(range(1521080307, 1521685107), dtype="uint64")
self.ts_sec_float = self.ts_sec.astype("float64")
self.ts_nanosec = 1_000_000 * self.ts_sec
self.ts_nanose... | ToDatetimeFromIntsFloats |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 2335,
"end": 2387
} | class ____(ASTNode):
exc: ASTNode
@dataclass
| Raise |
python | huggingface__transformers | tests/models/dpt/test_image_processing_dpt.py | {
"start": 3537,
"end": 16254
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = DPTImageProcessor if is_vision_available() else None
fast_image_processing_class = DPTImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = D... | DPTImageProcessingTest |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 20445,
"end": 20841
} | class ____(PointEvent):
''' Announce the start of a pan event on a Bokeh plot.
Attributes:
sx (float) : x-coordinate of the event in *screen* space
sy (float) : y-coordinate of the event in *screen* space
x (float) : x-coordinate of the event in *data* space
y (float) : y-coordi... | PanStart |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 17010,
"end": 17141
} | class ____(models.Model):
history = HistoricalRecords(inherit=True)
class Meta:
abstract = True
| TrackedAbstractBaseA |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/multi_asset_sensor_definition.py | {
"start": 2223,
"end": 4998
} | class ____(
NamedTuple(
"_MultiAssetSensorAssetCursorComponent",
[
("latest_consumed_event_partition", Optional[str]),
("latest_consumed_event_id", Optional[int]),
("trailing_unconsumed_partitioned_event_ids", dict[str, int]),
],
)
):
"""A cursor c... | MultiAssetSensorAssetCursorComponent |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/confusion_matrix_test.py | {
"start": 8541,
"end": 18437
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testBothScalarShape(self):
label_values = 1.0
prediction_values = 0.0
static_labels, static_predictions = (
confusion_matrix.remove_squeezable_dimensions(
label_values, prediction_values))
labels_placeholder = array_op... | RemoveSqueezableDimensionsTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec51.py | {
"start": 304,
"end": 1149
} | class ____:
@overload
def method1(
self,
cb: Callable[Concatenate[Self, P], None],
*args: P.args,
**kwargs: P.kwargs,
) -> None: ...
@overload
def method1(
self, cb: tuple[Callable[..., None], str], *args: Any, **kwargs: Any
) -> None: ...
def method... | A |
python | pytorch__pytorch | test/dynamo/test_sets.py | {
"start": 2161,
"end": 8451
} | class ____(LoggingTestCase):
def test_set_with_function(self):
s = {
torch._C._set_grad_enabled,
"hello",
torch.amp._exit_autocast,
}
cnts = CompileCounter()
@torch.compile(backend=cnts, fullgraph=True)
def fn(x, s):
if torch.a... | TestSetGuards |
python | davidhalter__parso | parso/python/tokenize.py | {
"start": 8830,
"end": 25795
} | class ____:
def __init__(self, quote):
self.quote = quote
self.parentheses_count = 0
self.previous_lines = ''
self.last_string_start_pos = None
# In the syntax there can be multiple format_spec's nested:
# {x:{y:3}}
self.format_spec_count = 0
def open_par... | FStringNode |
python | pytorch__pytorch | test/distributed/test_store.py | {
"start": 37316,
"end": 38718
} | class ____(TestCase):
"""
This test shows how to use the legacy TCPStore (non-libuv) backend since libuv is now
the default backend.
"""
def tearDown(self):
super().tearDown()
os.environ.pop("USE_LIBUV", None)
os.environ.pop("MASTER_ADDR", None)
os.environ.pop("MASTE... | InitPgWithNonUvStore |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 258459,
"end": 259494
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
email: str,
password: str,
start_date: str,
logs_batch_size: Optional[int] = None,
):
"""Airbyte Source for My Hours.
Documentation can be found at https://docs.airbyte... | MyHoursSource |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_trace_item_attributes.py | {
"start": 36721,
"end": 67753
} | class ____(
OrganizationTraceItemAttributeValuesEndpointBaseTest, BaseSpansTestCase, SpanTestCase
):
feature_flags = {"organizations:visibility-explore-view": True}
item_type = SupportedTraceItemType.SPANS
def test_no_feature(self) -> None:
response = self.do_request(features={})
assert... | OrganizationTraceItemAttributeValuesEndpointSpansTest |
python | pytorch__pytorch | torch/_inductor/codegen/simd_kernel_features.py | {
"start": 15312,
"end": 17818
} | class ____:
"""Memory usage stats for a block dimension in the generated kernel (different from user dimensions)"""
# the number of load/store ops
count_per_thread_contiguous: int = 0
count_per_thread_broadcast: int = 0
count_per_thread_non_contiguous: int = 0 # excludes broadcast
# total byt... | StatsForDim |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 23562,
"end": 24159
} | class ____(TypedDict, closed=True, total=False): # type: ignore[call-arg]
# https://peps.python.org/pep-0728/
# Parameter {"param", "value", "empty"}
# Predicate {"test", "value"}
empty: Optional[bool]
param: Parameter | str
test: _TestPredicateType
value: Any
_Conditions: TypeAlias = lis... | _ConditionClosed |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 22234,
"end": 22439
} | class ____(AnyUrl):
"""A type that will accept any ws or wss URL.
* TLD not required
* Host not required
"""
_constraints = UrlConstraints(allowed_schemes=['ws', 'wss'])
| AnyWebsocketUrl |
python | python-markdown__markdown | markdown/extensions/footnotes.py | {
"start": 1050,
"end": 9175
} | class ____(Extension):
""" Footnote Extension. """
def __init__(self, **kwargs):
""" Setup configs. """
self.config = {
'PLACE_MARKER': [
'///Footnotes Go Here///', 'The text string that marks where the footnotes go'
],
'UNIQUE_IDS': [
... | FootnoteExtension |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_registries.py | {
"start": 365,
"end": 517
} | class ____(GQLResult):
org_entity: Optional[FetchRegistriesOrganizationOrgEntity] = Field(
alias="orgEntity"
)
| FetchRegistriesOrganization |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/exceptions.py | {
"start": 342,
"end": 483
} | class ____(SalesforceException):
"""
We use this exception for unknown input data types for Salesforce.
"""
| TypeSalesforceException |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 14949,
"end": 15099
} | class ____(models.Model):
manager = models.OneToOneField("Employee", null=True, on_delete=models.CASCADE)
history = HistoricalRecords()
| Employee |
python | arrow-py__arrow | arrow/locales.py | {
"start": 105378,
"end": 106933
} | class ____(Locale):
names = [
"sw",
"sw-ke",
"sw-tz",
]
past = "{0} iliyopita"
future = "muda wa {0}"
and_word = "na"
timeframes = {
"now": "sasa hivi",
"second": "sekunde",
"seconds": "sekunde {0}",
"minute": "dakika moja",
"minu... | SwahiliLocale |
python | pytorch__pytorch | test/ao/sparsity/test_data_scheduler.py | {
"start": 332,
"end": 836
} | class ____(BaseDataScheduler):
def __init__(self, sparsifier, sparsifier_hyperparam, last_epoch=-1, verbose=False):
super().__init__(sparsifier, sparsifier_hyperparam, last_epoch, verbose)
def get_schedule_param(self):
if self.last_epoch > 0:
return {
name: config["s... | ImplementedDataScheduler |
python | pytorch__pytorch | tools/code_coverage/package/util/setting.py | {
"start": 1323,
"end": 1405
} | class ____(Enum):
FBCODE = "fbcode"
OSS = "oss"
# compiler type
| TestPlatform |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-faker/source_faker/purchase_generator.py | {
"start": 379,
"end": 4591
} | class ____:
def __init__(self, stream_name: str, seed: int) -> None:
self.stream_name = stream_name
self.seed = seed
def prepare(self):
"""
Note: the instances of the mimesis generators need to be global.
Yes, they *should* be able to be instance variables on this class,... | PurchaseGenerator |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 8124,
"end": 8339
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'network']
valid_subsets = ['network']
fact_namespace = 'ansible_network'
collector_class = NetworkCollector
| TestNetworkCollector |
python | wandb__wandb | wandb/sdk/artifacts/_generated/add_aliases.py | {
"start": 250,
"end": 332
} | class ____(GQLResult):
success: bool
AddAliases.model_rebuild()
| AddAliasesResult |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/pool_test.py | {
"start": 2151,
"end": 3583
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, kernel, stride, N, C, H, W, device, op_func):
self.inputs = {"input": torch.rand(N, C, H, W, device=device)}
self.op_func = op_func(kernel, stride=stride)
def forward(self, input):
return self.op_func(input)
op_bench.generate_pt_... | Pool2dBenchmark |
python | getsentry__sentry | src/sentry/integrations/messaging/commands.py | {
"start": 1019,
"end": 1220
} | class ____(Exception):
def __init__(self, message: str, unmatched_input: CommandInput) -> None:
super().__init__(message)
self.unmatched_input = unmatched_input
| CommandNotMatchedError |
python | django__django | tests/backends/tests.py | {
"start": 38140,
"end": 39329
} | class ____(TestCase):
def test_can_reference_existent(self):
obj = Object.objects.create()
ref = ObjectReference.objects.create(obj=obj)
self.assertEqual(ref.obj, obj)
ref = ObjectReference.objects.get(obj=obj)
self.assertEqual(ref.obj, obj)
def test_can_reference_non_e... | DBConstraintTestCase |
python | getsentry__sentry | src/sentry/relay/config/__init__.py | {
"start": 13190,
"end": 13292
} | class ____(TypedDict):
method: Literal["replace"]
substitution: str
| TransactionNameRuleRedaction |
python | cython__cython | Tools/dataclass_test_data/test_dataclasses.py | {
"start": 101921,
"end": 106562
} | class ____(unittest.TestCase):
def test_set_name(self):
# See bpo-33141.
# Create a descriptor.
class D:
def __set_name__(self, owner, name):
self.name = name + 'x'
def __get__(self, instance, owner):
if instance is not None:
... | TestDescriptors |
python | fluentpython__example-code | 14-it-generator/sentence_gen2.py | {
"start": 122,
"end": 403
} | class ____:
def __init__(self, text):
self.text = text # <1>
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
for match in RE_WORD.finditer(self.text): # <2>
yield match.group() # <3>
| Sentence |
python | huggingface__transformers | tests/models/olmo/test_modeling_olmo.py | {
"start": 6826,
"end": 15708
} | class ____(unittest.TestCase):
@slow
def test_model_1b_logits(self):
input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
model = OlmoForCausalLM.from_pretrained("allenai/OLMo-1B-hf", device_map="auto")
out = model(torch.tensor(input_ids)).logits.float()
# Expected mean on dim... | OlmoIntegrationTest |
python | Textualize__textual | tests/test_widget_mounting.py | {
"start": 184,
"end": 4855
} | class ____(Widget):
"""Test a widget that tries to own itself."""
def __init__(self) -> None:
super().__init__(self)
async def test_mount_via_app() -> None:
"""Perform mount tests via the app."""
# Make a background set of widgets.
widgets = [Static(id=f"starter-{n}") for n in range(10)]... | SelfOwn |
python | facelessuser__soupsieve | tests/test_level4/test_nth_child.py | {
"start": 56,
"end": 1202
} | class ____(util.TestCase):
"""Test `nth` child selectors."""
MARKUP = """
<p id="0"></p>
<p id="1"></p>
<span id="2" class="test"></span>
<span id="3"></span>
<span id="4" class="test"></span>
<span id="5"></span>
<span id="6" class="test"></span>
<p id="7"></p>
<p id="8" cl... | TestNthChild |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py | {
"start": 1197,
"end": 2352
} | class ____(Benchmark):
r"""
McCormick objective function.
This class defines the McCormick [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{McCormick}}(x) = - x_{1} + 2 x_{2} + \left(x_{1}
- x_{2}\right)^{2} + \sin\l... | McCormick |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py | {
"start": 54649,
"end": 67833
} | class ____(test.TestCase):
def setUp(self):
self._seed = 23489
np.random.seed(self._seed)
def _createBidirectionalRNN(self, use_shape, use_sequence_length, scope=None):
num_units = 3
input_size = 5
batch_size = 2
max_length = 8
initializer = init_ops.random_uniform_initializer(
... | BidirectionalRNNTest |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 57332,
"end": 66343
} | class ____(PForTestCase):
def setUp(self):
self._enabled = control_flow_v2_toggles.control_flow_v2_enabled()
control_flow_v2_toggles.disable_control_flow_v2()
super(WhileV1Test, self).setUp()
def tearDown(self):
if self._enabled:
control_flow_v2_toggles.enable_control_flow_v2()
super(Whi... | WhileV1Test |
python | python-openxml__python-docx | tests/image/test_jpeg.py | {
"start": 3399,
"end": 7550
} | class ____:
def it_can_construct_from_a_jfif_stream(
self, stream_, _MarkerParser_, _JfifMarkers__init_, soi_, app0_, sof_, sos_
):
marker_lst = [soi_, app0_, sof_, sos_]
jfif_markers = _JfifMarkers.from_stream(stream_)
_MarkerParser_.from_stream.assert_called_once_with(stream_... | Describe_JfifMarkers |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 5226,
"end": 5308
} | class ____:
query_type: SnubaQuery.Type
dataset: Dataset
| _EntitySubscription |
python | python-openxml__python-docx | tests/test_enum.py | {
"start": 703,
"end": 2188
} | class ____:
"""Unit-test suite for `docx.enum.base.BaseXmlEnum`."""
def it_is_an_instance_of_EnumMeta_just_like_a_regular_Enum(self):
assert type(SomeXmlAttr) is enum.EnumMeta
def it_has_the_same_repr_as_a_regular_Enum(self):
assert repr(SomeXmlAttr) == "<enum 'SomeXmlAttr'>"
def it_h... | DescribeBaseXmlEnum |
python | scikit-learn__scikit-learn | sklearn/kernel_approximation.py | {
"start": 30408,
"end": 39735
} | class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
"""Approximate a kernel map using a subset of the training data.
Constructs an approximate feature map for an arbitrary kernel
using a subset of the data as basis.
Read more in the :ref:`User Guide <nystroem_kernel_approx>`.... | Nystroem |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 16490,
"end": 18665
} | class ____(TemplateNameMixin):
"""
Layout object for rendering an HTML button in a ``<button>`` tag.
Attributes
----------
template: str
The default template which this Layout Object will be rendered
with.
field_classes : str
The CSS classes to be applied to the button. ... | StrictButton |
python | conda__conda | tests/core/test_index.py | {
"start": 7788,
"end": 14524
} | class ____:
@pytest.fixture(params=[False, True])
def index(
self,
request: FixtureRequest,
test_recipes_channel: Path,
tmp_env: Path,
) -> Iterable[Index]:
with tmp_env("dependent=2.0") as prefix:
_index = Index(prefix=prefix, use_cache=True, use_system=T... | TestIndex |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/exceptions.py | {
"start": 1112,
"end": 2320
} | class ____(BuildBaseException):
GENERIC = "build:user:generic"
BUILD_COMMANDS_WITHOUT_OUTPUT = "build:user:output:no-html"
BUILD_OUTPUT_IS_NOT_A_DIRECTORY = "build:user:output:is-no-a-directory"
BUILD_OUTPUT_HAS_0_FILES = "build:user:output:has-0-files"
BUILD_OUTPUT_HAS_NO_PDF_FILES = "build:user:o... | BuildUserError |
python | keras-team__keras | keras/src/metrics/reduction_metrics_test.py | {
"start": 4290,
"end": 7418
} | class ____(testing.TestCase):
def test_config(self):
mse_obj = reduction_metrics.MeanMetricWrapper(
fn=mse, name="mse", dtype="float32"
)
self.assertEqual(mse_obj.name, "mse")
self.assertEqual(len(mse_obj.variables), 2)
self.assertEqual(mse_obj._dtype, "float32")
... | MetricWrapperTest |
python | FactoryBoy__factory_boy | tests/test_docs_internals.py | {
"start": 3654,
"end": 4270
} | class ____(unittest.TestCase):
def test_simple_usage(self):
user = UserFactory()
# Default user should be active, not super
self.assertTrue(user.is_active)
self.assertFalse(user.is_superuser)
self.assertFalse(user.is_staff)
# We should have one log
self.asse... | DocsInternalsTests |
python | scipy__scipy | scipy/sparse/linalg/_isolve/tests/test_iterative.py | {
"start": 1146,
"end": 1619
} | class ____:
def __init__(self, name, A, b=None, skip=None, nonconvergence=None):
self.name = name
self.A = A
if b is None:
self.b = arange(A.shape[0], dtype=float)
else:
self.b = b
if skip is None:
self.skip = []
else:
s... | Case |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 64865,
"end": 162263
} | class ____(Structure):
_fields_ = [("max", c_uint),
("high", c_uint),
("partial", c_uint),
("low", c_uint),
("none", c_uint)
]
## string/bytes conversion for ease of use
def convertStrBytes(func):
'''
In python 3, strings are ... | c_nvmlRowRemapperHistogramValues |
python | pydata__xarray | xarray/core/types.py | {
"start": 9720,
"end": 10328
} | class ____(Protocol[_T_co]):
def __len__(self, /) -> int: ...
@overload
def __getitem__(self, index: int, /) -> _T_co | NestedSequence[_T_co]: ...
@overload
def __getitem__(self, index: slice, /) -> NestedSequence[_T_co]: ...
def __iter__(self, /) -> Iterator[_T_co | NestedSequence[_T_co]]: ...
... | NestedSequence |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py | {
"start": 638,
"end": 802
} | class ____(BaseModel):
type: Literal["object"] = Field(default="object")
properties: Dict[str, ParamPropertyDefinition]
required: List[str]
| ToolParameters |
python | doocs__leetcode | solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/Solution.py | {
"start": 0,
"end": 977
} | class ____:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
if k >= m + n - 3:
return m + n - 2
q = deque([(0, 0, k)])
vis = {(0, 0, k)}
ans = 0
while q:
ans += 1
for _ in range(len(q)):
... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py | {
"start": 4060,
"end": 5497
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger for RedshiftCreateClusterSnapshotOperator.
The trigger will asynchronously poll the boto3 API and wait for the
Redshift cluster snapshot to be in the `available` state.
:param cluster_identifier: A unique identifier for the cluster.
:param waiter_... | RedshiftCreateClusterSnapshotTrigger |
python | optuna__optuna | optuna/pruners/_base.py | {
"start": 28,
"end": 910
} | class ____(abc.ABC):
"""Base class for pruners."""
@abc.abstractmethod
def prune(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial") -> bool:
"""Judge whether the trial should be pruned based on the reported values.
Note that this method is not supposed to be called by li... | BasePruner |
python | Textualize__textual | tests/tree/test_tree_messages.py | {
"start": 7064,
"end": 8875
} | class ____(App[None]):
"""Testing app related to https://github.com/Textualize/textual/issues/3869"""
def __init__(self, auto_expand: bool, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.messages: list[tuple[str, str]] = []
self._auto_expand = auto_expand
... | TreeViaCodeApp |
python | scipy__scipy | scipy/optimize/_differentiable_functions.py | {
"start": 1495,
"end": 3776
} | class ____:
"""
Wrapper class for hess calculation via finite differences
"""
def __init__(
self,
hess,
x0=None,
grad=None,
args=None,
finite_diff_options=None,
):
self.hess = hess
self.grad = grad
self.a... | _ScalarHessWrapper |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/automations.py | {
"start": 6927,
"end": 7959
} | class ____(Trigger, abc.ABC):
"""
Base class for triggers that may filter by the labels of resources.
"""
type: str
match: ResourceSpecification = Field(
default_factory=lambda: ResourceSpecification.model_validate({}),
description="Labels for resources which this trigger will matc... | ResourceTrigger |
python | EpistasisLab__tpot | tpot/graphsklearn.py | {
"start": 9106,
"end": 16272
} | class ____(_BaseComposition):
def __init__(
self,
graph,
cross_val_predict_cv=0, #signature function(estimator, X, y=none)
method='auto',
memory=None,
use_label_encoder=False,
**kwargs,
):... | GraphPipeline |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/dashboard.py | {
"start": 879,
"end": 1029
} | class ____(BaseModel):
"""DAG Run Types for responses."""
backfill: int
scheduled: int
manual: int
asset_triggered: int
| DAGRunTypes |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_multiple_forward.py | {
"start": 1384,
"end": 2587
} | class ____(FSDPTest):
def _dist_train(self, wrap_fsdp):
# keep everything deterministic for input data
torch.manual_seed(0)
model = Model(wrap_fsdp).to(device_type.type)
if wrap_fsdp:
model = FSDP(model, device_id=device_type.type)
else:
model = Distri... | TestMultiForward |
python | doocs__leetcode | solution/3300-3399/3314.Construct the Minimum Bitwise Array I/Solution.py | {
"start": 0,
"end": 369
} | class ____:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
... | Solution |
python | numpy__numpy | numpy/typing/tests/data/pass/ndarray_misc.py | {
"start": 365,
"end": 3205
} | class ____(npt.NDArray[np.intp]): ...
i4 = np.int32(1)
A: np.ndarray[Any, np.dtype[np.int32]] = np.array([[1]], dtype=np.int32)
B0 = np.empty((), dtype=np.int32).view(SubClass)
B1 = np.empty((1,), dtype=np.int32).view(SubClass)
B2 = np.empty((1, 1), dtype=np.int32).view(SubClass)
B_int0: IntSubClass = np.empty((), dt... | IntSubClass |
python | run-llama__llama_index | llama-index-core/tests/tools/tool_spec/test_load_and_search.py | {
"start": 499,
"end": 9764
} | class ____(BaseModel):
query: str
def _foo(query: str) -> List[Document]:
return [Document(text=f"Test document with query: {query}")]
def test_load_and_search_tool_spec_init() -> None:
function_tool = FunctionTool.from_defaults(
fn=_foo,
name="test_loader",
description="Test loa... | TestSchema |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/connectors/test_accelerator_connector.py | {
"start": 30470,
"end": 39508
} | class ____(Mock):
def __instancecheck__(self, instance):
return True
@RunIf(skip_windows=True)
def test_connector_with_tpu_accelerator_instance(tpu_available, monkeypatch):
monkeypatch.setattr(torch, "device", DeviceMock())
accelerator = XLAAccelerator()
trainer = Trainer(accelerator=accelera... | DeviceMock |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/key_binding/bindings/vi.py | {
"start": 1784,
"end": 75602
} | class ____:
"""
Return struct for functions wrapped in ``text_object``.
Both `start` and `end` are relative to the current cursor position.
"""
def __init__(
self, start: int, end: int = 0, type: TextObjectType = TextObjectType.EXCLUSIVE
):
self.start = start
self.end = ... | TextObject |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 42719,
"end": 45448
} | class ____(Request):
"""
Deletes a project
:param project: Project ID
:type project: str
:param force: If not true, fails if project has tasks. If true, and project has tasks, they will be unassigned
:type force: bool
:param delete_contents: If set to 'true' then the project tasks and model... | DeleteRequest |
python | pypa__pip | tests/unit/test_network_cache.py | {
"start": 387,
"end": 4396
} | class ____:
"""
The no_perms test are useless on Windows since SafeFileCache uses
pip._internal.utils.filesystem.check_path_owner which is based on
os.geteuid which is absent on Windows.
"""
def test_cache_roundtrip(self, cache_tmpdir: Path) -> None:
cache = SafeFileCache(os.fspath(cach... | TestSafeFileCache |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_type_test.py | {
"start": 27574,
"end": 29611
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.product(
name=["arg_0", "param"],
kind=[
function_type.Parameter.POSITIONAL_ONLY,
function_type.Parameter.POSITIONAL_OR_KEYWORD
],
optional=[True, False],
type_contraint=[None, trace_type.from_value(1)... | SerializationTest |
python | huggingface__transformers | src/transformers/models/ministral/modular_ministral.py | {
"start": 11959,
"end": 12044
} | class ____(Qwen2ForSequenceClassification):
pass
| MinistralForSequenceClassification |
python | scikit-learn__scikit-learn | sklearn/pipeline.py | {
"start": 59192,
"end": 82478
} | class ____(TransformerMixin, _BaseComposition):
"""Concatenates results of multiple transformer objects.
This estimator applies a list of transformer objects in parallel to the
input data, then concatenates the results. This is useful to combine
several feature extraction mechanisms into a single trans... | FeatureUnion |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/types.py | {
"start": 10513,
"end": 10828
} | class ____(TypedDict, Generic[ResponseT]):
"""State schema for the agent."""
messages: Required[Annotated[list[AnyMessage], add_messages]]
jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]
structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]
| AgentState |
python | PyCQA__pylint | tests/functional/m/member/member_checks.py | {
"start": 294,
"end": 589
} | class ____:
"""provide some attributes and method"""
cattr = 4
def __init__(self):
self.attr = 4
def method(self, val):
"""impressive method"""
return self.attr * val
def hophop(self):
"""hop method"""
print('hop hop hop', self)
| Provider |
python | pytorch__pytorch | test/export/test_export.py | {
"start": 609495,
"end": 611297
} | class ____(torch.nn.Module):
def forward(self, x: "f32[2, 4]", y: "f32[4]"):
add: "f32[2, 4]" = torch.ops.aten.add.Tensor(x, y); x = None
hints_wrapper_body_graph_0 = self.hints_wrapper_body_graph_0
hints_wrapper = torch.ops.higher_order.hints_wrapper(hints_wrapper_body_graph_0, (add, y), ... | GraphModule |
python | fsspec__filesystem_spec | fsspec/implementations/arrow.py | {
"start": 855,
"end": 6549
} | class ____(AbstractFileSystem):
"""FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
Parameters
----------
fs : pyarrow.fs.FileSystem
"""
root_marker = "/"
def __init__(self, fs, **kwargs):
global PYARROW_VERSION
PYARROW_VERSION = get_package_version_without_import("pya... | ArrowFSWrapper |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 56641,
"end": 57393
} | class ____(DelegatingLexer):
"""
Subclass of the `LassoLexer` which highlights unhandled data with the
`JavascriptLexer`.
.. versionadded:: 1.6
"""
name = 'JavaScript+Lasso'
aliases = ['js+lasso', 'javascript+lasso']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript... | LassoJavascriptLexer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 537792,
"end": 538135
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("PullRequestReviewComment", graphql_name="node")
| PullRequestReviewCommentEdge |
python | Textualize__textual | docs/examples/guide/layout/combining_layouts.py | {
"start": 157,
"end": 1050
} | class ____(App):
CSS_PATH = "combining_layouts.tcss"
def compose(self) -> ComposeResult:
yield Header()
with Container(id="app-grid"):
with VerticalScroll(id="left-pane"):
for number in range(15):
yield Static(f"Vertical layout, child {number}")
... | CombiningLayoutsExample |
python | django__django | tests/handlers/tests_custom_error_handlers.py | {
"start": 212,
"end": 1096
} | class ____:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# Response.content should be available in the middleware even with a
# TemplateResponse-based exception response.
assert resp... | MiddlewareAccessingContent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.