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 | facebook__pyre-check | tools/upgrade/commands/tests/consolidate_nested_configurations_test.py | {
"start": 618,
"end": 6902
} | class ____(unittest.TestCase):
def test_gather_nested_configuration_mapping(self) -> None:
arguments = MagicMock()
configurations = []
expected_mapping = {}
mapping = ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).gather_nested_configurati... | ConsolidateNestedConfigurationsTest |
python | django__django | django/contrib/postgres/fields/array.py | {
"start": 11559,
"end": 12047
} | class ____(Transform):
def __init__(self, index, base_field, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = index
self.base_field = base_field
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
if not lhs.endswith("]"):
... | IndexTransform |
python | oauthlib__oauthlib | tests/openid/connect/core/grant_types/test_refresh_token.py | {
"start": 417,
"end": 677
} | class ____(RefreshTokenGrantTest):
"""Test that OpenID don't interfere with normal OAuth 2 flows."""
def setUp(self):
super().setUp()
self.auth = RefreshTokenGrant(request_validator=self.mock_validator)
| OpenIDRefreshTokenInterferenceTest |
python | pypa__warehouse | warehouse/accounts/interfaces.py | {
"start": 760,
"end": 6837
} | class ____(Interface):
def get_user(user_id):
"""
Return the user object that represents the given userid, or None if
there is no user for that ID.
"""
def get_user_by_username(username):
"""
Return the user object corresponding with the given username, or None
... | IUserService |
python | langchain-ai__langchain | libs/partners/prompty/tests/unit_tests/fake_chat_model.py | {
"start": 389,
"end": 1381
} | class ____(SimpleChatModel):
"""Fake Chat Model wrapper for testing purposes."""
def _call(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> str:
return json.dumps([mess... | FakeEchoPromptChatModel |
python | run-llama__llama_index | llama-index-integrations/graph_rag/llama-index-graph-rag-cognee/llama_index/graph_rag/cognee/base.py | {
"start": 343,
"end": 3100
} | class ____(Protocol):
"""
Abstract graph RAG protocol.
This protocol defines the interface for a graphRAG, which is responsible
for adding, storing, processing and retrieving information from knowledge graphs.
Attributes:
llm_api_key: str: Api key for desired llm.
graph_db_provider... | GraphRAG |
python | matplotlib__matplotlib | lib/matplotlib/patheffects.py | {
"start": 389,
"end": 2161
} | class ____:
"""
A base class for path effects.
Subclasses should override the ``draw_path`` method to add effect
functionality.
"""
def __init__(self, offset=(0., 0.)):
"""
Parameters
----------
offset : (float, float), default: (0, 0)
The (x, y) off... | AbstractPathEffect |
python | django__django | tests/staticfiles_tests/test_views.py | {
"start": 721,
"end": 954
} | class ____(TestServeStatic):
"""
Test serving static files disabled when DEBUG is False.
"""
def test_disabled_serving(self):
self.assertFileNotFound("test.txt")
@override_settings(DEBUG=True)
| TestServeDisabled |
python | apache__airflow | providers/pgvector/src/airflow/providers/pgvector/operators/pgvector.py | {
"start": 951,
"end": 1876
} | class ____(SQLExecuteQueryOperator):
"""
This operator is designed for ingesting data into a PostgreSQL database with pgvector support.
It inherits from the SQLExecuteQueryOperator and extends its functionality by registering
the pgvector data type with the database connection before executing queries.... | PgVectorIngestOperator |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/runner.py | {
"start": 351,
"end": 1126
} | class ____(VirtualEnv, PythonRun):
"""local file system python virtual environment via the virtualenv package."""
@staticmethod
def id() -> str:
return "virtualenv"
@property
def _package_tox_env_type(self) -> str:
return "virtualenv-pep-517"
@property
def _external_pkg_to... | VirtualEnvRunner |
python | doocs__leetcode | solution/3700-3799/3737.Count Subarrays With Majority Element I/Solution.py | {
"start": 0,
"end": 371
} | class ____:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
n = len(nums)
ans = 0
for i in range(n):
cnt = Counter()
for j in range(i, n):
k = j - i + 1
cnt[nums[j]] += 1
if cnt[target] > k // 2:
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-the-sum-of-the-power-of-all-subsequences.py | {
"start": 53,
"end": 431
} | class ____(object):
def sumOfPower(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(k+1)
dp[0] = 1
for x in nums:
for i in reversed(xrange(k+1)):
dp[i] = (dp[i]+(dp[i]+(d... | Solution |
python | ray-project__ray | python/ray/actor.py | {
"start": 5463,
"end": 6203
} | class ____(Generic[_Ret, _T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]):
def remote(
self,
__arg0: "Union[_T0, ObjectRef[_T0]]",
__arg1: "Union[_T1, ObjectRef[_T1]]",
__arg2: "Union[_T2, ObjectRef[_T2]]",
__arg3: "Union[_T3, ObjectRef[_T3]]",
__arg4: "Union[_T4, ObjectRef[_... | _RemoteMethod7 |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 95687,
"end": 97126
} | class ____:
def test_inprocess_supervisor_comms_roundtrip(self):
"""
Test that InProcessSupervisorComms correctly sends a message to the supervisor,
and that the supervisor's response is received via the message queue.
This verifies the end-to-end communication flow:
- send_... | TestInProcessTestSupervisor |
python | django-haystack__django-haystack | haystack/admin.py | {
"start": 584,
"end": 2293
} | class ____(ChangeList):
def __init__(self, **kwargs):
self.haystack_connection = kwargs.pop("haystack_connection", DEFAULT_ALIAS)
super_kwargs = kwargs
if django_version[0] >= 4:
super_kwargs["search_help_text"] = "Search..."
super().__init__(**super_kwargs)
def get_... | SearchChangeList |
python | bokeh__bokeh | tests/test_bokehjs.py | {
"start": 1129,
"end": 1989
} | class ____:
def test_bokehjs(self) -> None:
os.chdir('bokehjs')
proc = subprocess.Popen(["node", "make", "test"], stdout=subprocess.PIPE)
out, _ = proc.communicate()
msg = out.decode('utf-8', errors='ignore')
os.chdir('..')
print(msg)
if proc.returncode != 0:
... | TestBokehJS |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/splice_z/package.py | {
"start": 217,
"end": 917
} | class ____(Package):
"""Simple package with one optional dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/splice-z-1.0.tar.gz"
version("1.0.2")
version("1.0.1")
version("1.0.0")
variant("foo", default=False, description="nope")
variant("bar", default=Fal... | SpliceZ |
python | django__django | tests/db_functions/text/test_chr.py | {
"start": 209,
"end": 1861
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="John Smith", alias="smithj")
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
cls.rhonda = Author.objects.create(name="Rhonda")
def test_basic(self):
author... | ChrTests |
python | huggingface__transformers | tests/utils/import_structures/import_structure_register_with_duplicates.py | {
"start": 1290,
"end": 1446
} | class ____:
def __init__(self):
pass
@requires(
backends=(
"torch",
"torch"
)
)
# That's a statement
def c3():
pass
| C3 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 360159,
"end": 360806
} | 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("IssueTimelineItemEdge"), graphql_name="edges"
)
nodes = s... | IssueTimelineConnection |
python | astropy__astropy | astropy/convolution/kernels.py | {
"start": 5552,
"end": 7741
} | class ____(Kernel1D):
"""
1D Box filter kernel.
The Box filter or running mean is a smoothing filter. It is not isotropic
and can produce artifacts when applied repeatedly to the same data.
The generated kernel is normalized so that it integrates to 1.
By default, the Box kernel uses the ``li... | Box1DKernel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_natural_language.py | {
"start": 1683,
"end": 2120
} | class ____:
@patch("airflow.providers.google.cloud.operators.natural_language.CloudNaturalLanguageHook")
def test_minimal_green_path(self, hook_mock):
hook_mock.return_value.analyze_entities.return_value = ANALYZE_ENTITIES_RESPONSE
op = CloudNaturalLanguageAnalyzeEntitiesOperator(task_id="task-i... | TestCloudLanguageAnalyzeEntitiesOperator |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 10603,
"end": 11627
} | class ____(BaseExtensionApp):
description = "Update labextension(s)"
flags = update_flags
all = Bool(False, config=True, help="Whether to update all extensions")
def run_task(self):
self.deprecation_warning(
"Updating extensions with the jupyter labextension update command is now d... | UpdateLabExtensionApp |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 21499,
"end": 23783
} | class ____(StateMachineEvent):
key: Key
run_id: int
who_has: dict[Key, Collection[str]]
nbytes: dict[Key, int]
priority: tuple[int, ...]
run_spec: T_runspec | None
resource_restrictions: dict[str, float]
actor: bool
annotations: dict
span_id: str | None
__slots__ = tuple(__a... | ComputeTaskEvent |
python | ansible__ansible | lib/ansible/module_utils/facts/network/nvme.py | {
"start": 910,
"end": 1967
} | class ____(NetworkCollector):
name = 'nvme'
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
"""
Currently NVMe is only supported in some Linux distributions.
If NVMe is configured on the host then a file will have been created
duri... | NvmeInitiatorNetworkCollector |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/timers.py | {
"start": 2721,
"end": 4002
} | class ____:
"""
Tracks the most recent value of a metric. This is analogous to gauges in statsd.
"""
__slots__ = ["value", "min_value", "max_value", "count", "_timestamp"]
def __init__(self, value: float):
self.value = value
self.min_value = value
self.max_value = value
... | GaugeNode |
python | falconry__falcon | docs/ext/cibuildwheel.py | {
"start": 1871,
"end": 5461
} | class ____(sphinx.util.docutils.SphinxDirective):
"""Directive to tabulate build info from a YAML workflow."""
required_arguments = 1
has_content = True
@classmethod
def _emit_table(cls, data):
columns = len(data[0])
assert all(len(row) == columns for row in data), (
'A... | WheelsDirective |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_http_status_name.py | {
"start": 740,
"end": 1755
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_http_status_name"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _... | ColumnValuesToBeValidHttpStatusName |
python | cherrypy__cherrypy | cherrypy/lib/auth_digest.py | {
"start": 4781,
"end": 16275
} | class ____(object):
"""Digest Authorization implementation.
Parses a Digest Authorization header and performs
re-calculation of the digest.
"""
scheme = 'digest'
def errmsg(self, s):
"""Make an error message for HTTP Digest Authorization."""
return 'Digest Authorization header... | HttpDigestAuthorization |
python | pandas-dev__pandas | pandas/core/dtypes/dtypes.py | {
"start": 3586,
"end": 23998
} | class ____(PandasExtensionDtype, ExtensionDtype):
"""
Type for categorical data with the categories and orderedness.
It is a dtype representation for categorical data, which allows users to define
a fixed set of values and optionally impose an ordering. This is particularly
useful for handling cate... | CategoricalDtype |
python | django__django | tests/async/models.py | {
"start": 65,
"end": 174
} | class ____(models.Model):
simple = models.ForeignKey("SimpleModel", models.CASCADE, null=True)
| RelatedModel |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_ops.py | {
"start": 4069,
"end": 4423
} | class ____(TestCase):
def test_quantize(self):
x = torch.randn(3, 4, 5, dtype=torch.float32, device="openreg")
quantized_tensor = torch.quantize_per_tensor(x, 0.1, 10, torch.qint8)
self.assertEqual(quantized_tensor.device, torch.device("openreg:0"))
self.assertEqual(quantized_tensor.... | TestQuantization |
python | huggingface__transformers | src/transformers/models/vitpose_backbone/configuration_vitpose_backbone.py | {
"start": 887,
"end": 6651
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VitPoseBackbone`]. It is used to instantiate a
VitPose model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults wi... | VitPoseBackboneConfig |
python | rushter__MLAlgorithms | mla/neuralnet/parameters.py | {
"start": 95,
"end": 2892
} | class ____(object):
def __init__(
self,
init="glorot_uniform",
scale=0.5,
bias=1.0,
regularizers=None,
constraints=None,
):
"""A container for layer's parameters.
Parameters
----------
init : str, default 'glorot_uniform'.
... | Parameters |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 181252,
"end": 181549
} | class ____(_MatrixMixin, TestCSC):
@classmethod
def spcreator(cls, *args, **kwargs):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", WMSG, SparseEfficiencyWarning)
return csc_matrix(*args, **kwargs)
TestCSCMatrix.init_class()
| TestCSCMatrix |
python | keon__algorithms | tests/test_graph.py | {
"start": 9176,
"end": 9729
} | class ____(unittest.TestCase):
def test_digraph_strongly_connected(self):
g1 = check_digraph_strongly_connected.Graph(5)
g1.add_edge(0, 1)
g1.add_edge(1, 2)
g1.add_edge(2, 3)
g1.add_edge(3, 0)
g1.add_edge(2, 4)
g1.add_edge(4, 2)
self.assertTrue(g1.is_s... | TestDigraphStronglyConnected |
python | PyCQA__mccabe | mccabe.py | {
"start": 1291,
"end": 1583
} | class ____(object):
def __init__(self, name, look="circle"):
self.name = name
self.look = look
def to_dot(self):
print('node [shape=%s,label="%s"] %d;' % (
self.look, self.name, self.dot_id()))
def dot_id(self):
return id(self)
| PathNode |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/win32_types.py | {
"start": 2285,
"end": 2507
} | class ____(Structure):
"""
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687093(v=vs.85).aspx
"""
if TYPE_CHECKING:
Size: COORD
_fields_ = [("Size", COORD)]
| WINDOW_BUFFER_SIZE_RECORD |
python | GoogleCloudPlatform__python-docs-samples | endpoints/bookstore-grpc-transcoding/bookstore.py | {
"start": 595,
"end": 776
} | class ____:
"""The contents of a single shelf."""
def __init__(self, shelf):
self._shelf = shelf
self._last_book_id = 0
self._books = dict()
| ShelfInfo |
python | realpython__materials | python-oop/dogbreeds.py | {
"start": 282,
"end": 385
} | class ____(Dog):
def speak(self, sound="Arf"):
return super().speak(sound)
| JackRussellTerrier |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/database.py | {
"start": 3682,
"end": 5557
} | class ____(abc.ABCMeta):
def __call__(self, *args: Any, **kwargs: Any) -> "ExampleDatabase":
if self is ExampleDatabase:
note_deprecation(
"Creating a database using the abstract ExampleDatabase() class "
"is deprecated. Prefer using a concrete subclass, like "
... | _EDMeta |
python | PrefectHQ__prefect | src/prefect/server/schemas/graph.py | {
"start": 569,
"end": 614
} | class ____(PrefectBaseModel):
id: UUID
| Edge |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/utils.py | {
"start": 2552,
"end": 3246
} | class ____:
"""
Enum for Apache Arrow C type format strings.
The Arrow C data interface:
https://arrow.apache.org/docs/format/CDataInterface.html#data-type-description-format-strings
"""
NULL = "n"
BOOL = "b"
INT8 = "c"
UINT8 = "C"
INT16 = "s"
UINT16 = "S"
INT32 = "i"
... | ArrowCTypes |
python | huggingface__transformers | src/transformers/generation/watermarking.py | {
"start": 12292,
"end": 12814
} | class ____(ModelOutput):
"""
Base class for outputs of models predicting if the text is watermarked.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
posterior_probabilities (`torch.FloatTensor` of shape `(... | BayesianWatermarkDetectorModelOutput |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 85709,
"end": 86550
} | class ____(nn.Module):
def __init__(self, config: DFineConfig):
super().__init__()
self.top_prob_values = config.top_prob_values
self.max_num_bins = config.max_num_bins
self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
def forw... | DFineLQE |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 160426,
"end": 161254
} | class ____(torch.nn.Module):
def forward(self, L_model_parameters_weight_: "f32[3, 3]", L_model_parameters_bias_: "f32[3]", L_inputs_: "f32[64, 3]", L_targets_: "f32[64, 3]"):
l_model_parameters_weight_ = L_model_parameters_weight_
l_model_parameters_bias_ = L_model_parameters_bias_
l_inputs... | GraphModule |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 14719,
"end": 20677
} | class ____(unittest.TestCase):
@unittest.skipIf(_testcapi is None, 'need _testcapi')
def test_socket(self):
# use a subprocess to have only one thread
code = """if 1:
import signal
import socket
import struct
import _testcapi
signum = signal.SIGINT
... | WakeupSocketSignalTests |
python | sympy__sympy | sympy/physics/mechanics/tests/test_wrapping_geometry.py | {
"start": 669,
"end": 4343
} | class ____:
@staticmethod
def test_valid_constructor():
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
assert isinstance(sphere, WrappingSphere)
assert hasattr(sphere, 'radius')
assert sphere.radius == r
assert hasattr(sphe... | TestWrappingSphere |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/conditional_accumulator_test.py | {
"start": 1336,
"end": 17514
} | class ____(test.TestCase):
def testConstructorWithInvalidArg(self):
with ops.Graph().as_default():
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", reduction_type="Invalid")
@test_util.run_deprecated_v1
def testAccumulatorSizeE... | ConditionalAccumulatorTest |
python | django__django | tests/delete/models.py | {
"start": 420,
"end": 490
} | class ____(models.Model):
r = models.ForeignKey(R, models.CASCADE)
| S |
python | hynek__structlog | src/structlog/exceptions.py | {
"start": 320,
"end": 505
} | class ____(BaseException):
"""
If raised by an processor, the event gets silently dropped.
Derives from BaseException because it's technically not an error.
"""
| DropEvent |
python | doocs__leetcode | solution/0800-0899/0812.Largest Triangle Area/Solution.py | {
"start": 0,
"end": 403
} | class ____:
def largestTriangleArea(self, points: List[List[int]]) -> float:
ans = 0
for x1, y1 in points:
for x2, y2 in points:
for x3, y3 in points:
u1, v1 = x2 - x1, y2 - y1
u2, v2 = x3 - x1, y3 - y1
t = abs(u... | Solution |
python | ray-project__ray | python/ray/dashboard/modules/reporter/healthz_agent.py | {
"start": 311,
"end": 2069
} | class ____(dashboard_utils.DashboardAgentModule):
"""Health check in the agent.
This module adds health check related endpoint to the agent to check
local components' health.
"""
def __init__(self, dashboard_agent):
super().__init__(dashboard_agent)
node_id = (
NodeID.f... | HealthzAgent |
python | huggingface__transformers | src/transformers/integrations/executorch.py | {
"start": 26543,
"end": 34411
} | class ____(torch.nn.Module):
"""
A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
specifically for decoder-only LM to hybrid `StaticCache`. This module ensures that the
exported model is compatible with further lowering and execution in `ExecuTorch`.
"""
def ... | TorchExportableModuleWithHybridCache |
python | ipython__ipython | tests/test_pretty.py | {
"start": 14741,
"end": 15084
} | class ____(set): # Override repr of a basic type
def __repr__(self):
return "mine"
def test_custom_repr():
"""A custom repr should override a pretty printer for a parent type"""
oc = OrderedCounter("abracadabra")
assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
assert pretty.pret... | MySet |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/hooks/kubernetes.py | {
"start": 29517,
"end": 40688
} | class ____(KubernetesHook):
"""Hook to use Kubernetes SDK asynchronously."""
def __init__(self, config_dict: dict | None = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config_dict = config_dict
self._extras: dict | None = None
async def _load_config(self):
... | AsyncKubernetesHook |
python | PrefectHQ__prefect | src/prefect/logging/handlers.py | {
"start": 1597,
"end": 3297
} | class ____(BatchedQueueService[Dict[str, Any]]):
@property
def max_batch_size(self) -> int:
return max(
PREFECT_LOGGING_TO_API_BATCH_SIZE.value()
- PREFECT_LOGGING_TO_API_MAX_LOG_SIZE.value(),
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE.value(),
)
@property
d... | APILogWorker |
python | openai__openai-python | src/openai/types/responses/response_input_image.py | {
"start": 223,
"end": 778
} | class ____(BaseModel):
detail: Literal["low", "high", "auto"]
"""The detail level of the image to be sent to the model.
One of `high`, `low`, or `auto`. Defaults to `auto`.
"""
type: Literal["input_image"]
"""The type of the input item. Always `input_image`."""
file_id: Optional[str] = No... | ResponseInputImage |
python | skorch-dev__skorch | skorch/callbacks/training.py | {
"start": 23039,
"end": 23307
} | class ____(ParamMapper):
"""Inverse operation of :class:`.Freezer`."""
def __init__(self, *args, **kwargs):
kwargs['at'] = kwargs.get('at', 1)
kwargs['fn'] = kwargs.get('fn', unfreeze_parameter)
super().__init__(*args, **kwargs)
| Unfreezer |
python | kamyu104__LeetCode-Solutions | Python/evaluate-the-bracket-pairs-of-a-string.py | {
"start": 37,
"end": 671
} | class ____(object):
def evaluate(self, s, knowledge):
"""
:type s: str
:type knowledge: List[List[str]]
:rtype: str
"""
lookup = {k: v for k, v in knowledge}
result, curr = [], []
has_pair = False
for c in s:
if c == '(':
... | Solution |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_querysets.py | {
"start": 5859,
"end": 8146
} | class ____(TestVersionQuerySetWithManagerBase):
"""
Queries using Internal Manager should only include Internal Versions.
It will exclude EXTERNAL type Versions from the queries
and only include BRANCH, TAG, UNKNOWN type Versions.
"""
def test_all(self):
query = Version.internal.all()... | VersionQuerySetWithInternalManagerTest |
python | pydantic__pydantic | tests/mypy/modules/plugin_success_baseConfig.py | {
"start": 1388,
"end": 1576
} | class ____(NoMutationModel):
a: int = 1
model_config = dict(frozen=False, from_attributes=True)
MutationModel(x=1).x = 2
MutationModel.model_validate(model.__dict__)
| MutationModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/definitions_load_context.py | {
"start": 2277,
"end": 11312
} | class ____:
"""Holds data that's made available to Definitions-loading code when a DefinitionsLoader is
invoked.
User construction of this object is not supported.
"""
_instance: ClassVar[Optional["DefinitionsLoadContext"]] = None
def __init__(
self,
load_type: DefinitionsLoadT... | DefinitionsLoadContext |
python | django-debug-toolbar__django-debug-toolbar | tests/sync.py | {
"start": 115,
"end": 594
} | class ____(SyncToAsync):
"""
SyncToAsync version that cleans up old database connections when it exits.
"""
def thread_handler(self, loop, *args, **kwargs):
close_old_connections()
try:
return super().thread_handler(loop, *args, **kwargs)
finally:
close_o... | DatabaseSyncToAsync |
python | kamyu104__LeetCode-Solutions | Python/prime-subtraction-operation.py | {
"start": 632,
"end": 1055
} | class ____(object):
def primeSubOperation(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
for i in xrange(len(nums)):
j = bisect.bisect_left(PRIMES, nums[i]-nums[i-1] if i-1 >= 0 else nums[i])
if j-1 >= 0:
nums[i] -= PRIMES[j-1]... | Solution |
python | pytest-dev__pytest | testing/test_config.py | {
"start": 71855,
"end": 85582
} | class ____:
@pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
def test_override_ini_names(self, pytester: Pytester, name: str) -> None:
section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]"
pytester.path.joinpath(name).write_text(
textwrap.dedent(
... | TestOverrideIniArgs |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 12105,
"end": 12281
} | class ____:
"""
ODE problem
"""
stiff = False
cmplx = False
stop_t = 1
z0 = []
lband = None
uband = None
atol = 1e-6
rtol = 1e-5
| ODE |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/ref.py | {
"start": 4093,
"end": 5433
} | class ____(PathRefToDest, ExePathRef):
"""Link a exe path on the file system."""
def __init__(self, src, targets, dest, must=RefMust.NA, when=RefWhen.ANY) -> None:
ExePathRef.__init__(self, src, must, when)
PathRefToDest.__init__(self, src, dest, must, when)
if not self.FS_CASE_SENSITIV... | ExePathRefToDest |
python | coleifer__peewee | tests/regressions.py | {
"start": 62070,
"end": 62145
} | class ____(TestModel):
p = ForeignKeyField(P)
s = ForeignKeyField(S)
| PS |
python | getsentry__sentry | src/sentry/utils/auth.py | {
"start": 15633,
"end": 15689
} | class ____(Request):
user: User
| AuthenticatedHttpRequest |
python | google__pytype | third_party/cpython/umarshal.py | {
"start": 2289,
"end": 9818
} | class ____:
# A fairly literal translation of the marshal reader.
def __init__(self, data: bytes):
self.data: bytes = data
self.end: int = len(self.data)
self.pos: int = 0
self.refs: list[Any] = []
self.level: int = 0
def r_string(self, n: int) -> bytes:
ass... | Reader |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 4011,
"end": 8185
} | class ____(nn.Module):
def __init__(self, config, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the num... | BigBirdPegasusSelfAttention |
python | gevent__gevent | src/greentest/3.13/test_weakref.py | {
"start": 1515,
"end": 2142
} | class ____(unittest.TestCase):
def setUp(self):
self.cbcalled = 0
def callback(self, ref):
self.cbcalled += 1
@contextlib.contextmanager
def collect_in_thread(period=0.005):
"""
Ensure GC collections happen in a different thread, at a high frequency.
"""
please_stop = False
... | TestBase |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/orc_asset.py | {
"start": 1313,
"end": 1393
} | class ____(FileDataAsset, ORCAssetBase):
type: Literal["orc"] = "orc"
| ORCAsset |
python | pytorch__pytorch | torch/_inductor/autoheuristic/learnedheuristic_interface.py | {
"start": 790,
"end": 1680
} | class ____(LearnedHeuristic):
def get_feedback(self, context: AHContext, choice: Choice) -> float:
return 1.0
def get_decision(
self, context: AHContext, choices: list[Choice]
) -> Optional[Choice]:
choice2feedback = {}
for choice in choices:
predicted_feedback =... | LearnedHeuristicRegression |
python | tensorflow__tensorflow | tensorflow/python/framework/ops.py | {
"start": 67260,
"end": 71284
} | class ____(object):
"""A decorator for registering the statistics function for an op type.
This decorator can be defined for an op type so that it gives a
report on the resources used by an instance of an operator, in the
form of an OpStats object.
Well-known types of statistics include these so far:
- f... | RegisterStatistics |
python | pallets__jinja | src/jinja2/compiler.py | {
"start": 4440,
"end": 4664
} | class ____:
def __init__(self, node: nodes.Macro | nodes.CallBlock) -> None:
self.node = node
self.accesses_caller = False
self.accesses_kwargs = False
self.accesses_varargs = False
| MacroRef |
python | ethereum__web3.py | web3/providers/base.py | {
"start": 872,
"end": 3655
} | class ____:
# Set generic logger for the provider. Override in subclasses for more specificity.
logger: logging.Logger = logging.getLogger("web3.providers.base.BaseProvider")
# a tuple of (middleware, request_func)
_request_func_cache: tuple[tuple[Middleware, ...], Callable[..., RPCResponse]] = (
... | BaseProvider |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 167290,
"end": 167604
} | class ____:
def test_lmbda(self):
lam = special.lmbda(1,.1)
lamr = (
array([special.jn(0,.1), 2*special.jn(1,.1)/.1]),
array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])
)
assert_allclose(lam, lamr, atol=1.5e-8, rtol=0)
| TestLambda |
python | pypa__setuptools | setuptools/_distutils/command/install_headers.py | {
"start": 241,
"end": 1272
} | class ____(Command):
description = "install C/C++ header files"
user_options: ClassVar[list[tuple[str, str, str]]] = [
('install-dir=', 'd', "directory to install header files to"),
('force', 'f', "force installation (overwrite existing files)"),
]
boolean_options: ClassVar[list[str]] ... | install_headers |
python | getsentry__sentry | tests/sentry/auth/providers/fly/test_provider.py | {
"start": 3026,
"end": 3278
} | class ____(FlyOAuth2ProviderTest):
def setUp(self) -> None:
self.auth_provider = AuthProvider.objects.create(
provider=ChannelName.FLY_NON_PARTNER.value, organization_id=self.organization.id
)
| NonPartnerFlyOAuth2ProviderTest |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 11688,
"end": 11837
} | class ____(LTTextContainer):
def __init__(self, objs):
LTTextContainer.__init__(self)
self.extend(objs)
return
| LTTextGroup |
python | plotly__plotly.py | plotly/graph_objs/scatter/selected/_marker.py | {
"start": 233,
"end": 3584
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.selected"
_path_str = "scatter.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
The 'color' property is a color and may be s... | Marker |
python | django__django | tests/admin_views/models.py | {
"start": 11292,
"end": 11474
} | class ____(models.Model):
index = models.IntegerField(primary_key=True)
owner = models.ForeignKey(Collector, models.CASCADE)
name = models.CharField(max_length=100)
| Whatsit |
python | pytorch__pytorch | torch/utils/_device.py | {
"start": 1514,
"end": 3996
} | class ____(TorchFunctionMode):
def __init__(self, device) -> None:
# pyrefly: ignore [read-only]
self.device = torch.device(device)
def __enter__(self):
global CURRENT_DEVICE
self.old_device = CURRENT_DEVICE
CURRENT_DEVICE = self.device
# We need to put the devic... | DeviceContext |
python | streamlit__streamlit | lib/streamlit/elements/pdf.py | {
"start": 1533,
"end": 7163
} | class ____:
@gather_metrics("pdf")
def pdf(
self,
data: PdfData,
*,
height: HeightWithoutContent = 500,
key: str | None = None,
) -> DeltaGenerator:
"""Display a PDF viewer.
.. Important::
You must install |streamlit-pdf|_ to use this com... | PdfMixin |
python | kamyu104__LeetCode-Solutions | Python/pancake-sorting.py | {
"start": 1461,
"end": 3389
} | class ____(object):
def pancakeSort(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
def smallerMergeSort(idxs, start, end, counts):
if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.
return 0
... | Solution2 |
python | openai__openai-python | src/openai/lib/streaming/_assistants.py | {
"start": 16635,
"end": 17702
} | class ____(Generic[AssistantEventHandlerT]):
"""Wrapper over AssistantStreamEventHandler that is returned by `.stream()`
so that a context manager can be used.
```py
with client.threads.create_and_run_stream(...) as stream:
for event in stream:
...
```
"""
def __init__(... | AssistantStreamManager |
python | pytorch__pytorch | benchmarks/instruction_counts/execution/runner.py | {
"start": 707,
"end": 3122
} | class ____:
"""Allocator style helper class to assign individual tasks to a core range.
Pinning tasks to separate cores (or core ranges if `num_threads` > 1)
serves two purposes. First, it prevents the machine from being overloaded,
which can result in OOMs or Callgrind crashes. Second, it helps reduce... | CorePool |
python | pytorch__pytorch | torch/_guards.py | {
"start": 16614,
"end": 17456
} | class ____:
"""
The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
"""
dynamo_guards: set[Guard] = set()
def __init__(self, dynamo_guards: set[Guard]) -> None:
self.dynamo_guards = dynamo_guards
def diff(self, other: GuardsCheckpointState) -> Optional[set[Gu... | GuardsCheckpointState |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 36772,
"end": 40242
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a long-running DlpJob.
This method indicates that the client is no longer interested
in the DlpJob result. The job will be cancelled if possible.
.. seealso::
For more information on how to use this operator, take a look at the guide:
... | CloudDLPDeleteDLPJobOperator |
python | openai__openai-python | src/openai/types/audio/transcription_diarized_segment.py | {
"start": 205,
"end": 859
} | class ____(BaseModel):
id: str
"""Unique identifier for the segment."""
end: float
"""End timestamp of the segment in seconds."""
speaker: str
"""Speaker label for this segment.
When known speakers are provided, the label matches `known_speaker_names[]`.
Otherwise speakers are labeled... | TranscriptionDiarizedSegment |
python | huggingface__transformers | src/transformers/models/deberta_v2/modeling_deberta_v2.py | {
"start": 41224,
"end": 46165
} | class ____(DebertaV2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
num_labels = getattr(config, "num_labels", 2)
self.num_labels = num_labels
self.deberta = DebertaV2Model(config)
self.pooler = ContextPooler(config)
output_dim = self.pooler.o... | DebertaV2ForSequenceClassification |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 94288,
"end": 97696
} | class ____:
@staticmethod
@functools.cache
def patch() -> None:
# A better way to disable the following would be decorate the source
# functions with @torch._disable_dynamo. However, this causes issues
# with torch.deploy internally.
from .decorators import disable
t... | TorchPatcher |
python | huggingface__transformers | tests/models/instructblip/test_modeling_instructblip.py | {
"start": 17542,
"end": 25157
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (
(
InstructBlipModel,
InstructBlipForConditionalGeneration,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = {"image-text-to-text": InstructBlipFor... | InstructBlipForConditionalGenerationDecoderOnlyTest |
python | kubernetes-client__python | kubernetes/client/models/v1_role_binding.py | {
"start": 383,
"end": 7647
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1RoleBinding |
python | scrapy__scrapy | scrapy/core/http2/stream.py | {
"start": 1636,
"end": 2324
} | class ____(Enum):
# Received a StreamEnded event from the remote
ENDED = 1
# Received a StreamReset event -- ended abruptly
RESET = 2
# Transport connection was lost
CONNECTION_LOST = 3
# Expected response body size is more than allowed limit
MAXSIZE_EXCEEDED = 4
# Response defer... | StreamCloseReason |
python | numpy__numpy | numpy/lib/tests/test_shape_base.py | {
"start": 17571,
"end": 18504
} | class ____:
def test_non_iterable(self):
assert_raises(TypeError, column_stack, 1)
def test_1D_arrays(self):
# example from docstring
a = np.array((1, 2, 3))
b = np.array((2, 3, 4))
expected = np.array([[1, 2],
[2, 3],
... | TestColumnStack |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/merge.py | {
"start": 1201,
"end": 8201
} | class ____(Layer):
"""Generic merge layer for elementwise merge functions.
Used to implement `Sum`, `Average`, etc.
"""
def __init__(self, **kwargs):
"""Initializes a Merge layer.
Args:
**kwargs: standard layer keyword arguments.
"""
super(_Merge, self).__init__(**kwargs)
self.suppo... | _Merge |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 50802,
"end": 51100
} | class ____:
def test_default_none_parameter_imports(self):
stub = FunctionStub('test', inspect.signature(default_none_parameter), FunctionKind.MODULE)
expected = {'typing': {'Optional'}}
assert get_imports_for_signature(stub.signature) == expected
| TestGetImportsForSignature |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.