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 | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_policy.py | {
"start": 2005,
"end": 2258
} | class ____(Enum):
EAGER = "EAGER"
LAZY = "LAZY"
@whitelist_for_serdes(
old_fields={"time_window_partition_scope_minutes": 1e-6},
serializer=AutoMaterializePolicySerializer,
)
@deprecated(breaking_version="1.10.0")
| AutoMaterializePolicyType |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 73379,
"end": 75038
} | class ____:
def test_not_name(self):
with pytest.raises(TypeError):
x509.DirectoryName(b"notaname") # type:ignore[arg-type]
with pytest.raises(TypeError):
x509.DirectoryName(1.3) # type:ignore[arg-type]
def test_repr(self):
name = x509.Name([x509.NameAttribute... | TestDirectoryName |
python | PrefectHQ__prefect | src/prefect/server/services/scheduler.py | {
"start": 12067,
"end": 14987
} | class ____(Scheduler):
"""
Schedules deployments that were updated very recently
This scheduler can run on a tight loop and ensure that runs from
newly-created or updated deployments are rapidly scheduled without having to
wait for the "main" scheduler to complete its loop.
Note that schedulin... | RecentDeploymentsScheduler |
python | tensorflow__tensorflow | tensorflow/lite/python/metrics/wrapper/metrics_wrapper_test.py | {
"start": 1024,
"end": 1784
} | class ____(test_util.TensorFlowTestCase):
def test_basic_retrieve_collected_errors_empty(self):
errors = metrics_wrapper.retrieve_collected_errors()
self.assertEmpty(errors)
def test_basic_retrieve_collected_errors_not_empty(self):
@tf.function(
input_signature=[tf.TensorSpec(shape=[None], dt... | MetricsWrapperTest |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_arrays_test.py | {
"start": 1229,
"end": 7914
} | class ____(test.TestCase):
def testDtype(self):
a = array_ops.zeros(shape=[1, 2], dtype=dtypes.int64)
self.assertIs(a.dtype.as_numpy_dtype, np.int64)
np_dt = a.dtype.as_numpy_dtype
self.assertAllEqual(0, np_dt(0))
def testAstype(self):
a = ops.convert_to_tensor(value=1.1, dtype=dtypes.float32)... | ArrayTest |
python | huggingface__transformers | src/transformers/models/bit/modeling_bit.py | {
"start": 3102,
"end": 4589
} | class ____(nn.Conv2d):
"""Conv2d with Weight Standardization. Used for ViT Hybrid model.
Paper: [Micro-Batch Training with Batch-Channel Normalization and Weight
Standardization](https://huggingface.co/papers/1903.10520v2)
"""
def __init__(
self,
in_channel,
out_channels,
... | WeightStandardizedConv2d |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypedDict2.py | {
"start": 323,
"end": 1120
} | class ____(TypedDict):
tag: Literal["other-job"]
message: str
Event = Event1 | Event2 | Event3
def process_event1(event: Event) -> None:
if event["tag"] == "new-job":
reveal_type(event, expected_text="Event1")
event["job_name"]
elif event["tag"] == 2:
reveal_type(event, expec... | Event3 |
python | protocolbuffers__protobuf | python/google/protobuf/internal/python_message.py | {
"start": 2107,
"end": 24938
} | class ____(type):
"""Metaclass for protocol message classes created at runtime from Descriptors.
We add implementations for all methods described in the Message class. We
also create properties to allow getting/setting all fields in the protocol
message. Finally, we create slots to prevent users from accide... | GeneratedProtocolMessageType |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/openai_functions/citation_fuzzy_match.py | {
"start": 2032,
"end": 5615
} | class ____(BaseModel):
"""A question and its answer as a list of facts.
Each fact should have a source.
Each sentence contains a body and a list of sources.
"""
question: str = Field(..., description="Question that was asked")
answer: list[FactWithEvidence] = Field(
...,
descri... | QuestionAnswer |
python | PrefectHQ__prefect | tests/server/models/test_artifacts.py | {
"start": 10448,
"end": 13053
} | class ____:
@pytest.fixture
async def artifact(self, session):
artifact_schema = schemas.core.Artifact(
key="voltaic", data=1, metadata_={"description": "opens many doors"}
)
artifact = await models.artifacts.create_artifact(
session=session, artifact=artifact_sch... | TestUpdateArtifacts |
python | numpy__numpy | benchmarks/benchmarks/bench_itemselection.py | {
"start": 60,
"end": 487
} | class ____(Benchmark):
params = [
[(1000, 1), (2, 1000, 1), (1000, 3)],
["raise", "wrap", "clip"],
TYPES1 + ["O", "i,O"]]
param_names = ["shape", "mode", "dtype"]
def setup(self, shape, mode, dtype):
self.arr = np.ones(shape, dtype)
self.indices = np.arange(1000)
... | Take |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/invalid_gitlab_patch_url/package.py | {
"start": 217,
"end": 668
} | class ____(Package):
"""Package that has GitLab patch URLs that fail auditing."""
homepage = "http://www.example.com"
url = "http://www.example.com/patch-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
patch(
"https://gitlab.com/QEF/q-e/-/commit/4ca3afd4c6f27afcf3f42415... | InvalidGitlabPatchUrl |
python | getsentry__sentry-python | sentry_sdk/integrations/opentelemetry/integration.py | {
"start": 961,
"end": 1791
} | class ____(Integration):
identifier = "opentelemetry"
@staticmethod
def setup_once():
# type: () -> None
logger.warning(
"[OTel] Initializing highly experimental OpenTelemetry support. "
"Use at your own risk."
)
_setup_sentry_tracing()
# _se... | OpenTelemetryIntegration |
python | scipy__scipy | scipy/optimize/_nonlin.py | {
"start": 11565,
"end": 13692
} | class ____:
"""
Common interface for Jacobians or Jacobian approximations.
The optional methods come useful when implementing trust region
etc., algorithms that often require evaluating transposes of the
Jacobian.
Methods
-------
solve
Returns J^-1 * v
update
Update... | Jacobian |
python | allegroai__clearml | clearml/binding/joblib_bind.py | {
"start": 506,
"end": 8636
} | class ____(object):
_patched_joblib = False
_patched_sk_joblib = False
_current_task = None
@staticmethod
def patch_joblib() -> None:
# try manually
PatchedJoblib._patch_joblib()
# register callback
PostImportHookPatching.add_on_import("joblib", PatchedJoblib._patch_... | PatchedJoblib |
python | great-expectations__great_expectations | tests/datasource/fluent/test_fabric.py | {
"start": 2720,
"end": 7231
} | class ____:
@pytest.mark.parametrize(
["asset_type", "asset_kwargs"],
[
param("powerbi_dax", {"dax_string": "my_dax_string"}, id="dax min_args"),
param(
"powerbi_measure",
{
"measure": "my_measure",
},
... | TestFabricPowerBI |
python | gevent__gevent | src/gevent/contextvars.py | {
"start": 7196,
"end": 9838
} | class ____(Mapping):
"""
Implementation of :class:`contextvars.Context`
"""
__slots__ = (
'_data',
'_prev_context',
)
def __init__(self):
"""
Creates an empty context.
"""
self._data = _ContextData()
self._prev_context = None
__init_... | Context |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_multi_connector.py | {
"start": 416,
"end": 6240
} | class ____:
"""Test suite for MultiConnectorBackend."""
@pytest.fixture
def basic_llm_config(self):
"""Fixture for basic LLM config with MultiConnector."""
return LLMConfig(
model_loading_config=dict(model_id="test-model"),
engine_kwargs=dict(
kv_tran... | TestMultiConnectorBackend |
python | mwaskom__seaborn | tests/_core/test_properties.py | {
"start": 586,
"end": 1402
} | class ____:
@pytest.fixture
def num_vector(self, long_df):
return long_df["s"]
@pytest.fixture
def num_order(self, num_vector):
return categorical_order(num_vector)
@pytest.fixture
def cat_vector(self, long_df):
return long_df["a"]
@pytest.fixture
def cat_orde... | DataFixtures |
python | huggingface__transformers | tests/models/clap/test_modeling_clap.py | {
"start": 18362,
"end": 20822
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (ClapModel,) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": ClapModel} if is_torch_available() else {}
test_resize_embeddings = False
test_attention_outputs = False
def setUp(... | ClapModelTest |
python | huggingface__transformers | src/transformers/models/clip/configuration_clip.py | {
"start": 5776,
"end": 10032
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a simi... | CLIPVisionConfig |
python | Lightning-AI__lightning | tests/tests_pytorch/utilities/test_model_summary.py | {
"start": 1179,
"end": 1519
} | class ____(LightningModule):
"""A module that has no layers."""
def __init__(self):
super().__init__()
self.parameter = torch.rand(3, 3, requires_grad=True)
self.example_input_array = torch.zeros(1, 2, 3, 4, 5)
def forward(self, *args, **kwargs):
return {"loss": self.parame... | EmptyModule |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_zip5.py | {
"start": 628,
"end": 1609
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_zip5"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, ... | ColumnValuesToBeValidZip5 |
python | readthedocs__readthedocs.org | dockerfiles/settings/celery.py | {
"start": 49,
"end": 738
} | class ____(DockerBaseSettings):
DONT_HIT_DB = False
# TODO: review this since it may not be needed with MinIO (S3). For now,
# this is still required, but the CORS issue may have disappeared in MinIO.
# Since we can't properly set CORS on storage container
# trying to fetch ``objects.inv`` from ce... | CeleryDevSettings |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 69966,
"end": 70971
} | class ____(FileField):
"""
A Image File storage field.
:param size: max size to store images, provided as (width, height, force)
if larger, it will be automatically resized (ex: size=(800, 600, True))
:param thumbnail_size: size to generate a thumbnail, provided as (width, height, force)
""... | ImageField |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 10333,
"end": 10423
} | class ____(BaseGroupingComponent[str]):
id: str = "violation"
| ViolationGroupingComponent |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 80168,
"end": 92784
} | class ____(_Style):
"""
`BoxStyle` is a container class which defines several
boxstyle classes, which are used for `FancyBboxPatch`.
A style object can be created as::
BoxStyle.Round(pad=0.2)
or::
BoxStyle("Round", pad=0.2)
or::
BoxStyle("Round, pad=0.2")
... | BoxStyle |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_week.py | {
"start": 448,
"end": 3907
} | class ____:
def test_repr(self):
assert repr(Week(weekday=0)) == "<Week: weekday=0>"
assert repr(Week(n=-1, weekday=0)) == "<-1 * Week: weekday=0>"
assert repr(Week(n=-2, weekday=0)) == "<-2 * Weeks: weekday=0>"
def test_corner(self):
with pytest.raises(ValueError, match="Day mu... | TestWeek |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 103290,
"end": 103714
} | class ____(SendrecvmsgBase):
# Mixin to implement doRecvmsg() using recvmsg_into().
def doRecvmsg(self, sock, bufsize, *args):
buf = bytearray(bufsize)
result = sock.recvmsg_into([buf], *args)
self.registerRecvmsgResult(result)
self.assertGreaterEqual(result[0], 0)
self.... | RecvmsgIntoMixin |
python | gevent__gevent | src/gevent/tests/test__threading_native_before_monkey.py | {
"start": 581,
"end": 2157
} | class ____(greentest.TestCase):
@classmethod
def tearDownClass(cls):
global native_thread
if native_thread is not None:
native_thread.stop(1)
native_thread = None
def test_main_thread(self):
current = threading.current_thread()
self.assertNotIsInstan... | Test |
python | huggingface__transformers | src/transformers/models/ernie/modular_ernie.py | {
"start": 33390,
"end": 35533
} | class ____(BertForTokenClassification):
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] =... | ErnieForTokenClassification |
python | boto__boto3 | tests/unit/ec2/test_createtags.py | {
"start": 651,
"end": 1968
} | class ____(unittest.TestCase):
def setUp(self):
self.client = mock.Mock()
self.resource = mock.Mock()
self.resource.meta.client = self.client
self.ref_tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6']
self.resource.Tag.side_effect = self.ref_tags
def test_create_ta... | TestCreateTags |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/spec.py | {
"start": 1826,
"end": 2880
} | class ____(BaseModel):
class Config(OneOfOptionConfig):
title = "Authenticate via Facebook Marketing (Oauth)"
discriminator = "auth_type"
auth_type: Literal["Client"] = Field("Client", const=True)
client_id: str = Field(
title="Client ID",
description="Client ID for the Face... | OAuthCredentials |
python | python-pillow__Pillow | src/PIL/FtexImagePlugin.py | {
"start": 2020,
"end": 3535
} | class ____(ImageFile.ImageFile):
format = "FTEX"
format_description = "Texture File Format (IW2:EOC)"
def _open(self) -> None:
if not _accept(self.fp.read(4)):
msg = "not an FTEX file"
raise SyntaxError(msg)
struct.unpack("<i", self.fp.read(4)) # version
sel... | FtexImageFile |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/dashboard.py | {
"start": 13295,
"end": 25395
} | class ____(CamelSnakeSerializer[Dashboard]):
# Is a string because output serializers also make it a string.
id = serializers.CharField(required=False)
title = serializers.CharField(required=False, allow_blank=True, max_length=255)
description = serializers.CharField(
required=False, max_length=... | DashboardWidgetSerializer |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 16149,
"end": 16820
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden stat... | VisualBertPooler |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/settings.py | {
"start": 5633,
"end": 7360
} | class ____:
gamma: float = 0.99
strength: float = 1.0
network_settings: NetworkSettings = attr.ib(factory=NetworkSettings)
@staticmethod
def structure(d: Mapping, t: type) -> Any:
"""
Helper method to structure a Dict of RewardSignalSettings class. Meant to be registered with
... | RewardSignalSettings |
python | kamyu104__LeetCode-Solutions | Python/balance-a-binary-search-tree.py | {
"start": 1659,
"end": 2472
} | class ____(object):
def balanceBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def inorderTraversalHelper(node, arr):
if not node:
return
inorderTraversalHelper(node.left, arr)
arr.append(node.val)
... | Solution2 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/code_pointer.py | {
"start": 6941,
"end": 8325
} | class ____(CodePointer, LegacyNamedTupleMixin):
python_file: str
fn_name: str
working_directory: Optional[str] = None
def load_target(self) -> object:
module = load_python_file(self.python_file, self.working_directory)
return _load_target_from_module(
module, self.fn_name, f... | FileCodePointer |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/commands/test_help.py | {
"start": 1254,
"end": 4342
} | class ____(SlackCommandsTest):
@responses.activate
def test_missing_command(self) -> None:
if SiloMode.get_current_mode() == SiloMode.CONTROL:
region_response = SlackHelpMessageBuilder(
command=None,
integration_id=self.integration.id,
).as_payload... | SlackCommandsHelpTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 7208,
"end": 7585
} | class ____(Value):
"""Float literal.
Floating point literals are treated as constant values and are generally
not included in data flow analyses and such, unlike Register and
Op subclasses.
"""
def __init__(self, value: float, line: int = -1) -> None:
self.value = value
self.ty... | Float |
python | django__django | tests/model_options/apps.py | {
"start": 441,
"end": 576
} | class ____(AppConfig):
name = "model_options"
default_auto_field = "django.db.models.NonexistentAutoField"
| ModelPKNonexistentConfig |
python | huggingface__transformers | tests/models/cvt/test_modeling_cvt.py | {
"start": 8891,
"end": 9815
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return AutoImageProcessor.from_pretrained("microsoft/cvt-13")
@slow
def test_inference_image_classification_head(self):
model = CvtForImageClassification.from_pretrained("microsoft/cvt-13").to(torch_devic... | CvtModelIntegrationTest |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 127750,
"end": 128511
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.less(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
return KerasTensor(output_s... | Less |
python | Netflix__metaflow | test/core/tests/current_singleton.py | {
"start": 67,
"end": 6967
} | class ____(MetaflowTest):
"""
Test that the current singleton returns the right values
"""
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recurs... | CurrentSingletonTest |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 26732,
"end": 29300
} | class ____(fixtures.TablesTest):
__requires__ = ("ctes", "insert_returning", "ctes_on_dml")
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"q",
metadata,
Column("x", Integer, default=2),
Column("y", Integer,... | CTEDefaultTest |
python | squidfunk__mkdocs-material | material/plugins/blog/structure/options.py | {
"start": 2110,
"end": 4366
} | class ____(BaseConfigOption[DateDict]):
# Initialize post dates
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Normalize the supported types for post dates to datetime
def pre_validation(self, config: Config, key_name: str):
# If the date points to a scalar v... | PostDate |
python | scikit-learn__scikit-learn | sklearn/ensemble/_forest.py | {
"start": 26115,
"end": 35801
} | class ____(ClassifierMixin, BaseForest, metaclass=ABCMeta):
"""
Base class for forest of trees-based classifiers.
Warning: This class should not be used directly. Use derived classes
instead.
"""
@abstractmethod
def __init__(
self,
estimator,
n_estimators=100,
... | ForestClassifier |
python | redis__redis-py | tests/test_sentinel.py | {
"start": 424,
"end": 1159
} | class ____:
def __init__(self, cluster, id):
self.cluster = cluster
self.id = id
def sentinel_masters(self):
self.cluster.connection_error_if_down(self)
self.cluster.timeout_if_down(self)
return {self.cluster.service_name: self.cluster.master}
def sentinel_slaves(se... | SentinelTestClient |
python | openai__openai-python | src/openai/types/fine_tuning/job_create_params.py | {
"start": 5699,
"end": 6178
} | class ____(TypedDict, total=False):
type: Required[Literal["supervised", "dpo", "reinforcement"]]
"""The type of method. Is either `supervised`, `dpo`, or `reinforcement`."""
dpo: DpoMethodParam
"""Configuration for the DPO fine-tuning method."""
reinforcement: ReinforcementMethodParam
"""Conf... | Method |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_base32.py | {
"start": 660,
"end": 1647
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_base32"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls... | ColumnValuesToBeValidBase32 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/gradient_correctness_test.py | {
"start": 1073,
"end": 5264
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters(set((True, context.executing_eagerly())))
def testMultipleOutputChainedGradients(self, use_tape):
with test_util.AbstractGradientTape(use_tape=use_tape) as tape:
x = constant_op.constant(1.0, dtype=dtypes.float32)
tape.wat... | GradientCorrectnessTest |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 74591,
"end": 75079
} | class ____(nn.Module, metaclass=abc.ABCMeta):
"""Perceiver abstract decoder."""
@abc.abstractmethod
def decoder_query(self, inputs, modality_sizes=None, inputs_without_pos=None, subsampled_points=None):
raise NotImplementedError
@property
@abc.abstractmethod
def num_query_channels(self... | PerceiverAbstractDecoder |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/rpc/rpc_ops.py | {
"start": 4513,
"end": 10185
} | class ____(object):
"""Client class for invoking RPCs to the server."""
@staticmethod
def create(rpc_layer, address, name="", timeout_in_ms=0):
"""Create TF RPC client to connect to the given address.
Args:
rpc_layer: Communication layer between client and server. Only "grpc" rpc
layer is ... | Client |
python | getsentry__sentry | tests/sentry/models/test_organization.py | {
"start": 19747,
"end": 22118
} | class ____(TestCase):
def add_org_notification_settings(self, org: Organization, user: User):
with assume_test_silo_mode(SiloMode.CONTROL):
args = {
"scope_type": "organization",
"scope_identifier": org.id,
"type": "deploy",
"user_i... | OrganizationDeletionTest |
python | huggingface__transformers | src/transformers/models/phi3/modeling_phi3.py | {
"start": 9509,
"end": 12827
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", conf... | Phi3Attention |
python | doocs__leetcode | solution/2500-2599/2584.Split the Array to Make Coprime Products/Solution.py | {
"start": 0,
"end": 792
} | class ____:
def findValidSplit(self, nums: List[int]) -> int:
first = {}
n = len(nums)
last = list(range(n))
for i, x in enumerate(nums):
j = 2
while j <= x // j:
if x % j == 0:
if j in first:
last[fi... | Solution |
python | google__pytype | pytype/pytd/booleq.py | {
"start": 1558,
"end": 1865
} | class ____(BooleanTerm):
"""Class for representing "TRUE"."""
def simplify(self, assignments):
return self
def __repr__(self):
return "TRUE"
def __str__(self):
return "TRUE"
def extract_pivots(self, assignments):
return {}
def extract_equalities(self):
return ()
| TrueValue |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/collective_ops_test.py | {
"start": 2388,
"end": 5329
} | class ____(object):
@staticmethod
def all_reduce(t, group_size, group_key, instance_key, *args, **kwargs):
group_size = array_ops.identity(group_size)
group_key = array_ops.identity(group_key)
instance_key = array_ops.identity(instance_key)
return _collective_ops.all_reduce_v2(t, group_size, group_... | CollectiveOpsV2 |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modeling_lfm2_moe.py | {
"start": 29217,
"end": 30091
} | class ____(PreTrainedModel):
config: Lfm2MoeConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Lfm2MoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True... | Lfm2MoePreTrainedModel |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial011.py | {
"start": 105,
"end": 1594
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
... | Hero |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 339,
"end": 575
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.StandardModel
sqlalchemy_session = models.session
id = factory.Sequence(lambda n: n)
foo = factory.Sequence(lambda n: 'foo%d' % n)
| StandardFactory |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1594892,
"end": 1595079
} | class ____(WindowEventType):
"""EventType schema wrapper."""
_schema = {"$ref": "#/definitions/EventType"}
def __init__(self, *args):
super().__init__(*args)
| EventType |
python | ray-project__ray | rllib/examples/learners/classes/intrinsic_curiosity_learners.py | {
"start": 910,
"end": 1067
} | class ____(DQNTorchLearner):
def build(self) -> None:
super().build()
add_intrinsic_curiosity_connectors(self)
| DQNTorchLearnerWithCuriosity |
python | walkccc__LeetCode | solutions/2411. Smallest Subarrays With Maximum Bitwise OR/2411.py | {
"start": 0,
"end": 414
} | class ____:
def smallestSubarrays(self, nums: list[int]) -> list[int]:
MAX_BIT = 30
ans = [1] * len(nums)
# closest[j] := the closest index i s.t. the j-th bit of nums[i] is 1
closest = [0] * MAX_BIT
for i in reversed(range(len(nums))):
for j in range(MAX_BIT):
if nums[i] >> j & 1:
... | Solution |
python | viewflow__viewflow | viewflow/urls/model.py | {
"start": 11401,
"end": 11588
} | class ____(
DetailViewMixin, ListBulkActionsMixin, AppMenuMixin, BaseModelViewset
):
"""
Readonly model viewset with List and object details view only
"""
| ReadonlyModelViewset |
python | keras-team__keras | keras/src/export/saved_model_test.py | {
"start": 495,
"end": 1770
} | class ____(models.Model):
def __init__(self, layer_list):
super().__init__()
self.layer_list = layer_list
def call(self, input):
output = input
for layer in self.layer_list:
output = layer(output)
return output
def get_model(type="sequential", input_shape=(... | CustomModel |
python | explosion__spaCy | spacy/pipeline/edit_tree_lemmatizer.py | {
"start": 1183,
"end": 14794
} | class ____(TrainablePipe):
"""
Lemmatizer that lemmatizes each word using a predicted edit tree.
"""
def __init__(
self,
vocab: Vocab,
model: Model,
name: str = "trainable_lemmatizer",
*,
backoff: Optional[str] = "orth",
min_tree_freq: int = 3,
... | EditTreeLemmatizer |
python | run-llama__llama_index | scripts/integration_health_check.py | {
"start": 964,
"end": 16693
} | class ____:
def __init__(
self,
package_name: str,
repo_path: str,
metric_weights: Dict = DEFAULT_METRIC_WEIGHTS,
new_project_score: float = DEFAULT_SCORE_NEW_PROJECT,
verbose: bool = False,
):
self.package_name = package_name
self.repo_path = repo... | IntegrationActivityAnalyzer |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-multi-tenancy-rag/llama_index/packs/multi_tenancy_rag/base.py | {
"start": 591,
"end": 2382
} | class ____(BaseLlamaPack):
def __init__(self) -> None:
llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)
self.llm = llm
Settings.llm = self.llm
self.index = VectorStoreIndex.from_documents(documents=[])
def get_modules(self) -> Dict[str, Any]:
"""Get modules."""
... | MultiTenancyRAGPack |
python | huggingface__transformers | src/transformers/models/pegasus_x/modeling_pegasus_x.py | {
"start": 60483,
"end": 66869
} | class ____(PegasusXPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_tied_weights_keys = {
"lm_head.weight": "model.shared.weight",
}
def __init__(self, config: PegasusXConfig):
super().__init__(config)
self.model = PegasusXModel(config)
self.lm_head = nn.L... | PegasusXForConditionalGeneration |
python | langchain-ai__langchain | libs/partners/qdrant/langchain_qdrant/qdrant.py | {
"start": 659,
"end": 810
} | class ____(str, Enum):
"""Modes for retrieving vectors from Qdrant."""
DENSE = "dense"
SPARSE = "sparse"
HYBRID = "hybrid"
| RetrievalMode |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 37421,
"end": 37599
} | class ____(axis_ticks_major, axis_ticks_minor):
"""
x & y major and minor axis tick lines
Parameters
----------
theme_element : element_line
"""
| axis_ticks |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B006_4.py | {
"start": 176,
"end": 246
} | class ____:
def __init__(self, a=[]):
print(a)
| FormFeedIndent |
python | ipython__ipython | tests/test_guarded_eval.py | {
"start": 7957,
"end": 8059
} | class ____(ProtocolTest):
def test_method(self) -> bool:
return True
| ProtocolTestImplementer |
python | getsentry__sentry | src/sentry/integrations/mixins/issues.py | {
"start": 2528,
"end": 15123
} | class ____(IntegrationInstallation, ABC):
def should_sync(self, attribute, sync_source: AssignmentSource | None = None) -> bool:
return False
def get_group_title(self, group, event, **kwargs):
return get_notification_group_title(group, event, **kwargs)
@abstractmethod
def get_issue_url... | IssueBasicIntegration |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/base.py | {
"start": 6419,
"end": 7043
} | class ____(Expr):
__slots__ = ("name",)
_non_child = ("dtype", "name")
name: str
def __init__(self, dtype: DataType, name: str) -> None:
self.dtype = dtype
self.name = name
self.is_pointwise = True
self.children = ()
def do_evaluate(
self, df: DataFrame, *, ... | Col |
python | pytorch__pytorch | torch/ao/quantization/fx/_equalize.py | {
"start": 8701,
"end": 40805
} | class ____(
# pyrefly: ignore [invalid-inheritance]
namedtuple("EqualizationQConfig", ["input_activation", "weight"])
):
"""
Describes how to quantize a layer or a part of the network specifically for
input-weight equalization by providing settings (observer classes) for
inputs, outputs, and wei... | EqualizationQConfig |
python | walkccc__LeetCode | solutions/583. Delete Operation for Two Strings/583.py | {
"start": 0,
"end": 550
} | class ____:
def minDistance(self, word1: str, word2: str) -> int:
k = self._lcs(word1, word2)
return (len(word1) - k) + (len(word2) - k)
def _lcs(self, a: str, b: str) -> int:
m = len(a)
n = len(b)
# dp[i][j] := the length of LCS(a[0..i), b[0..j))
dp = [[0] * (n + 1) for _ in range(m + 1)]
... | Solution |
python | PrefectHQ__prefect | src/prefect/cli/deploy/_models.py | {
"start": 3387,
"end": 3552
} | class ____(BaseModel):
model_config = ConfigDict(extra="ignore")
limit: Optional[int] = None
collision_strategy: Optional[str] = None
| ConcurrencyLimitSpec |
python | numba__numba | numba/core/typed_passes.py | {
"start": 22269,
"end": 31872
} | class ____(FunctionPass):
"""
This pass will inline a function wrapped by the numba.extending.overload
decorator directly into the site of its call depending on the value set in
the 'inline' kwarg to the decorator.
This is a typed pass. CFG simplification and DCE are performed on
completion.
... | InlineOverloads |
python | doocs__leetcode | solution/0800-0899/0881.Boats to Save People/Solution.py | {
"start": 0,
"end": 307
} | class ____:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
ans = 0
i, j = 0, len(people) - 1
while i <= j:
if people[i] + people[j] <= limit:
i += 1
j -= 1
ans += 1
return ans
| Solution |
python | Pylons__pyramid | tests/test_scripts/test_ptweens.py | {
"start": 39,
"end": 1834
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.scripts.ptweens import PTweensCommand
return PTweensCommand
def _makeOne(self):
cmd = self._getTargetClass()([])
cmd.bootstrap = dummy.DummyBootstrap()
cmd.setup_logging = dummy.dummy_setup_logging()... | TestPTweensCommand |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_standalone.py | {
"start": 11060,
"end": 14669
} | class ____:
def test_return_type(self, test_plot: figure) -> None:
class fake_template:
def __init__(self, tester: Any, user_template_variables: set[str] | None = None) -> None:
self.tester = tester
self.template_variables = {
"title",
... | Test_file_html |
python | plotly__plotly.py | plotly/graph_objs/layout/hoverlabel/_font.py | {
"start": 235,
"end": 9932
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.hoverlabel"
_path_str = "layout.hoverlabel.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Font |
python | fastapi__sqlmodel | docs_src/tutorial/select/tutorial001_py310.py | {
"start": 71,
"end": 1106
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLM... | Hero |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/sagemaker.py | {
"start": 3460,
"end": 4648
} | class ____(SageMakerBaseSensor):
"""
Poll the endpoint state until it reaches a terminal state; raise AirflowException with the failure reason.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:SageMakerEndpointSensor`
:param endp... | SageMakerEndpointSensor |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/notifications.py | {
"start": 4171,
"end": 5361
} | class ____(MSTeamsNotificationsMessageBuilder):
def __init__(
self,
notification: GroupActivityNotification | AlertRuleNotification,
context: Mapping[str, Any],
recipient: Actor,
):
super().__init__(notification, context, recipient)
assert notification.group is no... | MSTeamsIssueNotificationsMessageBuilder |
python | python__mypy | mypy/nodes.py | {
"start": 97287,
"end": 97953
} | class ____(Expression):
"""Named tuple expression namedtuple(...) or NamedTuple(...)."""
__slots__ = ("info", "is_typed")
__match_args__ = ("info",)
# The class representation of this named tuple (its tuple_type attribute contains
# the tuple item types)
info: TypeInfo
is_typed: bool # w... | NamedTupleExpr |
python | pallets__werkzeug | src/werkzeug/wsgi.py | {
"start": 14740,
"end": 20920
} | class ____(io.RawIOBase):
"""Wrap a stream so that it doesn't read more than a given limit. This is used to
limit ``wsgi.input`` to the ``Content-Length`` header value or
:attr:`.Request.max_content_length`.
When attempting to read after the limit has been reached, :meth:`on_exhausted` is
called. W... | LimitedStream |
python | getsentry__sentry | src/sentry/web/frontend/base.py | {
"start": 5651,
"end": 9693
} | class ____(Protocol):
active_organization: RpcUserOrganizationContext | None
def respond(
self, template: str, context: dict[str, Any] | None = None, status: int = 200
) -> HttpResponseBase: ...
def _find_implicit_slug(request: HttpRequest) -> str | None:
organization_slug = request.session.g... | _HasRespond |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks.py | {
"start": 5229,
"end": 5554
} | class ____(_HookTimer):
"""Timer that never triggers."""
def should_trigger_for_step(self, step):
_ = step
return False
def update_last_triggered_step(self, step):
_ = step
return (None, None)
def last_triggered_step(self):
return None
@tf_export(v1=["train.LoggingTensorHook"])
| NeverTriggerTimer |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py | {
"start": 9740,
"end": 12123
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook"))
def test_execute(self, mock_hook_class):
ENTITY_ID = "entity-id"
FEATURE_VIEW_DATA_KEY = {"key": "28098"}
sample_result = {
"key_values": {
"features": [
{"nam... | TestFetchFeatureValuesOperator |
python | chroma-core__chroma | chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py | {
"start": 2441,
"end": 2569
} | class ____(Protocol):
def stem(self, token: str) -> str: # pragma: no cover - protocol definition
...
| SnowballStemmer |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_sys.py | {
"start": 2340,
"end": 3631
} | class ____(__TestCase):
def test_original_displayhook(self):
dh = sys.__displayhook__
with support.captured_stdout() as out:
dh(42)
self.assertEqual(out.getvalue(), "42\n")
self.assertEqual(builtins._, 42)
del builtins._
with support.captured_stdout()... | DisplayHookTest |
python | huggingface__transformers | tests/models/whisper/test_modeling_whisper.py | {
"start": 13653,
"end": 53430
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (WhisperModel, WhisperForConditionalGeneration) if is_torch_available() else ()
pipeline_model_mapping = (
{
"audio-classification": WhisperForAudioClassification,
"au... | WhisperModelTest |
python | jazzband__django-simple-history | simple_history/tests/tests/test_templatetags.py | {
"start": 132,
"end": 391
} | class ____(TestCase):
def test_get_existing_attributes_return_it(self):
self.assertEqual(getattribute(Foo(), "bar"), "bar")
def test_get_missing_attributes_return_None(self):
self.assertIsNone(getattribute(Foo(), "baz"))
| TestGetAttributes |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 12941,
"end": 13033
} | class ____(AbstractBase):
pass
register(ConcreteUtil, bases=[AbstractBase])
| ConcreteUtil |
python | google__pytype | pytype/tests/test_errors2.py | {
"start": 14419,
"end": 15879
} | class ____(test_base.BaseTest):
"""Tests for errors."""
def test_nis_wrong_arg_types(self):
errors = self.CheckWithErrors("""
from typing import Iterable
def f(x: Iterable[str]): ...
f("abc") # wrong-arg-types[e]
""")
self.assertErrorSequences(
errors, {"e": ["str does not ma... | ErrorTestPy3 |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_container.py | {
"start": 13643,
"end": 14220
} | class ____:
def test_valid(self) -> None:
prop = bcpc.RestrictedDict(String, bcpc.List(Int), disallow=("disallowed_key_1", "disallowed_key_2"))
assert prop.is_valid({"non_disallowed_key_1": [1,2,3]})
assert prop.is_valid({"non_disallowed_key_2": [1,2,3]})
def test_invalid(self) -> None... | Test_RestrictedDict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.