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 | tensorflow__tensorflow | tensorflow/python/saved_model/tests/variable_wrapper_test.py | {
"start": 1283,
"end": 2155
} | class ____(base.Trackable):
_should_act_as_resource_variable = True
def __init__(self, value):
self.value = variables.Variable(value)
@property
def _shared_name(self):
return self.value._shared_name
def _serialize_to_tensors(self):
return self.value._serialize_to_tensors()
def _restore_from_... | VariableWrapper |
python | wandb__wandb | wandb/vendor/pygments/lexers/rust.py | {
"start": 447,
"end": 7691
} | class ____(RegexLexer):
"""
Lexer for the Rust programming language (version 1.10).
.. versionadded:: 1.6
"""
name = 'Rust'
filenames = ['*.rs', '*.rs.in']
aliases = ['rust']
mimetypes = ['text/rust']
keyword_types = (
words(('u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', '... | RustLexer |
python | ray-project__ray | python/ray/serve/tests/test_config_files/logging_config_test.py | {
"start": 1530,
"end": 1750
} | class ____:
def __call__(self):
logger.debug("this_is_debug_info")
log_file = logger.handlers[1].target.baseFilename
return {"log_file": log_file}
model2 = ModelWithConfig.bind()
| ModelWithConfig |
python | pypa__setuptools | setuptools/tests/test_windows_wrappers.py | {
"start": 6658,
"end": 7868
} | class ____(WrapperTester):
"""
Testing the GUI Version
-----------------------
"""
script_name = 'bar-script.pyw'
wrapper_source = win_launcher_exe('gui')
wrapper_name = 'bar.exe'
script_tmpl = textwrap.dedent(
"""
#!%(python_exe)s
import sys
f = open(sy... | TestGUI |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py | {
"start": 39,
"end": 5733
} | class ____:
def test_K5(self):
"""Betweenness Centrality Subset: K5"""
G = nx.complete_graph(5)
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[1, 3], weight=None
)
b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
for n in sorted(G):
... | TestSubsetBetweennessCentrality |
python | qdrant__qdrant-client | qdrant_client/grpc/snapshots_service_pb2_grpc.py | {
"start": 6252,
"end": 10406
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def Create(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wai... | Snapshots |
python | astral-sh__uv | scripts/benchmark/src/benchmark/tools.py | {
"start": 4928,
"end": 10766
} | class ____(Suite):
def __init__(self, *, path: str | None = None) -> Command | None:
"""Initialize a uv benchmark."""
self.name = path or "uv"
self.path = path or os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
... | Uv |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/zyte_web/base.py | {
"start": 311,
"end": 5728
} | class ____(BasePydanticReader):
"""
Load text from URLs using `Zyte api`.
Args:
api_key: Zyte API key.
mode: Determines how the text is extracted for the page content.
It can take one of the following values: 'html', 'html-text', 'article'
n_conn: It is the maximum numbe... | ZyteWebReader |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 18261,
"end": 20210
} | class ____:
"""
Flat iterator object to iterate over Masked Arrays.
A `~astropy.utils.masked.MaskedIterator` iterator is returned by ``m.flat``
for any masked array ``m``. It allows iterating over the array as if it
were a 1-D array, either in a for-loop or by calling its `next` method.
Itera... | MaskedIterator |
python | kamyu104__LeetCode-Solutions | Python/the-number-of-ways-to-make-the-sum.py | {
"start": 4710,
"end": 5086
} | class ____(object):
def numberOfWays(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(n+1)
dp[0] = 1
for i in (1, 2, 6):
for j in xrange(i, n+1):
dp[j] += dp[j-i]
return reduce(lambda x, y: (x+dp[n-... | Solution4 |
python | getsentry__sentry | src/sentry/sentry_apps/components.py | {
"start": 744,
"end": 4146
} | class ____:
component: SentryAppComponent | RpcSentryAppComponent
install: SentryAppInstallation | RpcSentryAppInstallation
project_slug: str | None = None
values: list[Mapping[str, Any]] = dataclasses.field(default_factory=list)
def run(self) -> None:
if self.component.type == "issue-link"... | SentryAppComponentPreparer |
python | EpistasisLab__tpot | tpot/search_spaces/nodes/estimator_node_gradual.py | {
"start": 1864,
"end": 6628
} | class ____(SklearnIndividual):
"""
Note that ConfigurationSpace does not support None as a parameter. Instead, use the special string "<NONE>". TPOT will automatically replace instances of this string with the Python None.
Parameters
----------
method : type
The class of the estimator to b... | EstimatorNodeIndividual_gradual |
python | doocs__leetcode | solution/0000-0099/0020.Valid Parentheses/Solution.py | {
"start": 0,
"end": 284
} | class ____:
def isValid(self, s: str) -> bool:
stk = []
d = {'()', '[]', '{}'}
for c in s:
if c in '({[':
stk.append(c)
elif not stk or stk.pop() + c not in d:
return False
return not stk
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 22716,
"end": 24318
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testNonEmptyConstantTensor(self):
x = array_ops.zeros((2, 3, 4))
value = du.prefer_static_value(x)
self.assertIsInstance(value, np.ndarray)
self.assertAllEqual(np.zeros((2, 3, 4)), value)
@test_util.run_deprecated_v1
def testEmptyCons... | PreferStaticValueTest |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 18174,
"end": 22186
} | class ____(CoverageTest):
"""Tests that we work properly with `sys.gettrace()`."""
def test_round_trip_in_untraced_function(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/575
self.make_file("main.py", """import sample""")
self.make_file(
"sample.py",
... | GettraceTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py | {
"start": 272,
"end": 326
} | class ____(IntFlag): ...
@dataclass(
frozen=True
)
| E |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 53686,
"end": 54169
} | class ____:
xlHundredMillions = -8 # from enum XlDisplayUnit
xlHundredThousands = -5 # from enum XlDisplayUnit
xlHundreds = -2 # from enum XlDisplayUnit
xlMillionMillions = -10 # from enum XlDisplayUnit
xlMillions = -6 # from enum XlDisplayUnit
xlTenMillions = -7 # from enum XlDisplayUnit
... | DisplayUnit |
python | scikit-learn__scikit-learn | sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py | {
"start": 58912,
"end": 76018
} | class ____(RegressorMixin, BaseHistGradientBoosting):
"""Histogram-based Gradient Boosting Regression Tree.
This estimator is much faster than
:class:`GradientBoostingRegressor<sklearn.ensemble.GradientBoostingRegressor>`
for big datasets (n_samples >= 10 000).
This estimator has native support fo... | HistGradientBoostingRegressor |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 22487,
"end": 23353
} | class ____(PreTrainedModel):
config: MobileBertConfig
base_model_prefix = "mobilebert"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": M... | MobileBertPreTrainedModel |
python | django__django | django/db/transaction.py | {
"start": 176,
"end": 3959
} | class ____(ProgrammingError):
"""Transaction management is used improperly."""
pass
def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
"""
if using is None:
using = DEFAULT_DB_ALI... | TransactionManagementError |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_collections.py | {
"start": 84735,
"end": 99317
} | class ____(__TestCase):
def test_basics(self):
c = Counter('abcaba')
self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1}))
self.assertEqual(c, Counter(a=3, b=2, c=1))
self.assertIsInstance(c, dict)
self.assertIsInstance(c, Mapping)
self.assertTrue(issubclass(Counter... | TestCounter |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datafusion.py | {
"start": 5069,
"end": 7726
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a single Date Fusion instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataFusionDeleteInstanceOperator`
:param instance_name: The name of the instance to restart... | CloudDataFusionDeleteInstanceOperator |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 43916,
"end": 44280
} | class ____:
"""
Entry type for the FakeTensor dispatch cache. It supports two types of outputs
1) tensor
2) tuple of tensors
is_output_tuple flag helps in differentiating the return type
"""
output_infos: tuple[_DispatchCacheEntryOutputInfo]
is_output_tuple: bool = False
@dataclass(f... | _DispatchCacheValidEntry |
python | keras-team__keras | keras/src/layers/preprocessing/hashing_test.py | {
"start": 504,
"end": 20549
} | class ____(testing.TestCase):
def test_config(self):
layer = layers.Hashing(
num_bins=8,
output_mode="int",
)
self.run_class_serialization_test(layer)
def test_correctness(self):
layer = layers.Hashing(num_bins=3)
inp = [["A"], ["B"], ["C"], ["D"]... | HashingTest |
python | django__django | tests/many_to_one/models.py | {
"start": 3334,
"end": 3445
} | class ____(models.Model):
is_public = models.BooleanField(default=False)
objects = SchoolManager()
| School |
python | django__django | django/forms/models.py | {
"start": 40476,
"end": 50090
} | class ____(BaseModelFormSet):
"""A formset for child objects related to a parent."""
def __init__(
self,
data=None,
files=None,
instance=None,
save_as_new=False,
prefix=None,
queryset=None,
**kwargs,
):
if instance is None:
... | BaseInlineFormSet |
python | django__django | django/template/smartif.py | {
"start": 265,
"end": 3754
} | class ____:
"""
Base class for operators and literals, mainly for debugging and for
throwing syntax errors.
"""
id = None # node/token type name
value = None # used by literals
first = second = None # used by tree nodes
def nud(self, parser):
# Null denotation - called in pr... | TokenBase |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 32393,
"end": 33380
} | class ____(ExtensionType):
oid = ExtensionOID.TLS_FEATURE
def __init__(self, features: Iterable[TLSFeatureType]) -> None:
features = list(features)
if (
not all(isinstance(x, TLSFeatureType) for x in features)
or len(features) == 0
):
raise TypeError(... | TLSFeature |
python | django__django | tests/admin_scripts/tests.py | {
"start": 95909,
"end": 96520
} | class ____(SimpleTestCase):
def test_program_name_from_argv(self):
"""
Program name is computed from the execute_from_command_line()'s argv
argument, not sys.argv.
"""
args = ["help", "shell"]
with captured_stdout() as out, captured_stderr() as err:
with m... | ExecuteFromCommandLine |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/salesforce/tests.py | {
"start": 248,
"end": 2247
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = SalesforceProvider.id
def get_mocked_response(
self,
last_name="Penners",
first_name="Raymond",
name="Raymond Penners",
email="raymond.penners@gmail.com",
verified_email=True,
):
userinfo = USERINF... | SalesforceTests |
python | google__pytype | pytype/load_pytd.py | {
"start": 1927,
"end": 2033
} | class ____:
module_name: str
filename: str
ast: pytd.TypeDeclUnit
metadata: list[str]
| ResolvedModule |
python | sympy__sympy | sympy/physics/biomechanics/tests/test_musculotendon.py | {
"start": 3019,
"end": 9321
} | class ____:
@pytest.fixture(autouse=True)
def _musculotendon_rigid_tendon_fixture(self, musculotendon_concrete):
self.name = 'name'
self.N = ReferenceFrame('N')
self.q = dynamicsymbols('q')
self.origin = Point('pO')
self.insertion = Point('pI')
self.insertion.set... | TestMusculotendonRigidTendon |
python | huggingface__transformers | src/transformers/models/internvl/modular_internvl.py | {
"start": 24215,
"end": 26182
} | class ____(LlavaForConditionalGeneration):
def forward(**super_kwargs):
r"""
Example:
```python
>>> import torch
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> torch_device = "cuda"
>>> processor = AutoProcessor.from_pretrained("... | InternVLForConditionalGeneration |
python | astropy__astropy | astropy/coordinates/attributes.py | {
"start": 10190,
"end": 13491
} | class ____(Attribute):
"""
A frame attribute that is a quantity with specified units and shape
(optionally).
Can be `None`, which should be used for special cases in associated
frame transformations like "this quantity should be ignored" or similar.
Parameters
----------
default : numb... | QuantityAttribute |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 39184,
"end": 39259
} | class ____(Stmt):
__slots__ = ("target", "annotation", "value")
| AnnAssign |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 989741,
"end": 990186
} | class ____(sgqlc.types.Type):
"""Represents a count of the state of a status context."""
__schema__ = github_schema
__field_names__ = ("count", "state")
count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="count")
"""The number of statuses with this state."""
state = sgqlc.types.... | StatusContextStateCount |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 39850,
"end": 43117
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
Desmoothing](https://huggingface.co/papers... | EpsilonLogitsWarper |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 14345,
"end": 15063
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(sel... | ChineseCLIPTextSelfOutput |
python | plotly__plotly.py | _plotly_utils/png.py | {
"start": 10571,
"end": 10716
} | class ____(Error):
"""
Problem with the way the programming interface has been used,
or the data presented to it.
"""
| ProtocolError |
python | walkccc__LeetCode | solutions/25. Reverse Nodes in k-Group/25-2.py | {
"start": 0,
"end": 597
} | class ____:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k == 1:
return head
def getLength(head: ListNode) -> int:
length = 0
while head:
length += 1
head = head.next
return length
length = getLength(head)
dummy = ListNode(0, hea... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/workers/container_instance.py | {
"start": 18895,
"end": 19025
} | class ____(BaseWorkerResult):
"""Contains information about the final state of a completed process"""
| AzureContainerWorkerResult |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 44575,
"end": 44810
} | class ____(MemoryUsageFrame):
reduction_chunk = total_mem_usage
@staticmethod
def reduction_combine(x, is_dataframe):
return x
@staticmethod
def reduction_aggregate(x):
return x
| TotalMemoryUsageFrame |
python | redis__redis-py | redis/asyncio/multidb/failover.py | {
"start": 1833,
"end": 3635
} | class ____(FailoverStrategyExecutor):
"""
Executes given failover strategy.
"""
def __init__(
self,
strategy: AsyncFailoverStrategy,
failover_attempts: int = DEFAULT_FAILOVER_ATTEMPTS,
failover_delay: float = DEFAULT_FAILOVER_DELAY,
):
self._strategy = strate... | DefaultFailoverStrategyExecutor |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_int.py | {
"start": 1063,
"end": 2013
} | class ____(BaseTestZDType):
test_cls = Int16
scalar_type = np.int16
valid_dtype = (np.dtype(">i2"), np.dtype("<i2"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float64),
)
valid_json_v2 = (
{"name": ">i2", "object_codec_id": None},
... | TestInt16 |
python | pytorch__pytorch | test/lazy/test_debug_util.py | {
"start": 312,
"end": 1441
} | class ____(TestCase):
def _run_linear(self):
device = "lazy"
model = nn.Linear(5, 5).to(device)
output = model(torch.randn(1, 5).to(device)) # noqa: F841
torch._lazy.mark_step()
def test_get_python_frames(self):
# We only care about the first "Python Stacktrace" part of... | DebugUtilTest |
python | kamyu104__LeetCode-Solutions | Python/convex-polygon.py | {
"start": 29,
"end": 600
} | class ____(object):
def isConvex(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
def det(A):
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
n, prev, curr = len(points), 0, None
for i in xrange(len(points)):
A = [[points[(i+... | Solution |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_response_format.py | {
"start": 24429,
"end": 29008
} | class ____:
"""Test response_format with middleware that modifies the model."""
def test_middleware_model_swap_provider_to_tool_strategy(self) -> None:
"""Test that strategy resolution is deferred until after middleware modifies the model.
Verifies that when a raw schema is provided, `_support... | TestDynamicModelWithResponseFormat |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 4076,
"end": 5430
} | class ____(keras.layers.Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
... | Linear |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 6906,
"end": 9095
} | class ____:
def test_unauthenticated_raises_401(self):
pyramid_request = pretend.stub(user=None)
with pytest.raises(HTTPUnauthorized):
views.accounts_search(pyramid_request)
def test_no_query_string_raises_400(self):
pyramid_request = pretend.stub(user=pretend.stub(), params... | TestAccountsSearch |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/node.py | {
"start": 9102,
"end": 12628
} | class ____(BaseNodePostprocessor):
"""
Previous/Next Node post-processor.
Allows users to fetch additional nodes from the document store,
based on the prev/next relationships of the nodes.
NOTE: difference with PrevNextPostprocessor is that
this infers forward/backwards direction.
NOTE: t... | AutoPrevNextNodePostprocessor |
python | getsentry__sentry | tests/sentry/api/endpoints/test_debug_files.py | {
"start": 13699,
"end": 16436
} | class ____(DebugFilesTestCases):
def setUp(self) -> None:
super().setUp()
self.associate_url = reverse(
"sentry-api-0-associate-dsym-files",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
... | AssociateDebugFilesTest |
python | getsentry__sentry | src/sentry/uptime/endpoints/validators.py | {
"start": 13242,
"end": 16444
} | class ____(BaseDataSourceValidator[UptimeSubscription]):
@property
def data_source_type_handler(self) -> type[UptimeSubscriptionDataSourceHandler]:
return UptimeSubscriptionDataSourceHandler
url = URLField(required=True, max_length=255)
interval_seconds = serializers.ChoiceField(
requir... | UptimeMonitorDataSourceValidator |
python | openai__openai-python | src/openai/types/shared/function_definition.py | {
"start": 237,
"end": 1475
} | class ____(BaseModel):
name: str
"""The name of the function to be called.
Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length
of 64.
"""
description: Optional[str] = None
"""
A description of what the function does, used by the model to choose when and
... | FunctionDefinition |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 10238,
"end": 10920
} | class ____(BaseActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.DISCORD
@property
def required_fields(self) -> list[str]:
return [
ACTION_FIELD_MAPPINGS[ActionType.DISCORD][
ActionFieldMappingKeys.INTEGRATION_ID_KEY.value
... | DiscordActionTranslator |
python | astropy__astropy | astropy/io/fits/hdu/base.py | {
"start": 28436,
"end": 30911
} | class ____(_BaseHDU, _Verify):
"""
A Non-standard HDU class.
This class is used for a Primary HDU when the ``SIMPLE`` Card has
a value of `False`. A non-standard HDU comes from a file that
resembles a FITS file but departs from the standards in some
significant way. One example would be files... | _NonstandardHDU |
python | simonw__datasette | datasette/filters.py | {
"start": 6949,
"end": 7201
} | class ____:
key = None
display = None
no_argument = False
def where_clause(self, table, column, value, param_counter):
raise NotImplementedError
def human_clause(self, column, value):
raise NotImplementedError
| Filter |
python | hyperopt__hyperopt | hyperopt/ipy.py | {
"start": 735,
"end": 7548
} | class ____(Trials):
def __init__(self, client, job_error_reaction="raise", save_ipy_metadata=True):
self._client = client
self._clientlbv = client.load_balanced_view()
self.job_map = {}
self.job_error_reaction = job_error_reaction
self.save_ipy_metadata = save_ipy_metadata
... | IPythonTrials |
python | tensorflow__tensorflow | tensorflow/python/distribute/values_test.py | {
"start": 11386,
"end": 12495
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations
.mirrored_strategy_with_two_gpus_no_merge_call,
strat... | PerReplicaTest |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/questrade/tests.py | {
"start": 246,
"end": 550
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = QuestradeProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{"userId":400,"accounts":[]}""",
)
def get_expected_to_str(self):
return "Questrade"
| QuestradeTests |
python | ray-project__ray | python/ray/data/_internal/datasource/sql_datasink.py | {
"start": 281,
"end": 1251
} | class ____(Datasink[None]):
_MAX_ROWS_PER_WRITE = 128
def __init__(self, sql: str, connection_factory: Callable[[], Connection]):
self.sql = sql
self.connection_factory = connection_factory
def write(
self,
blocks: Iterable[Block],
ctx: TaskContext,
) -> None:
... | SQLDatasink |
python | django__django | django/forms/boundfield.py | {
"start": 12216,
"end": 13373
} | class ____:
"""
A container class used for iterating over widgets. This is useful for
widgets that have choices. For example, the following can be used in a
template:
{% for radio in myform.beatles %}
<label for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
<span class=... | BoundWidget |
python | django__django | django/test/utils.py | {
"start": 1806,
"end": 2970
} | class ____(list):
"""
A wrapper that provides direct key access to context items contained
in a list of context objects.
"""
def __getitem__(self, key):
if isinstance(key, str):
for subcontext in self:
if key in subcontext:
return subcontext[k... | ContextList |
python | huggingface__transformers | src/transformers/models/llava_next/modeling_llava_next.py | {
"start": 5984,
"end": 6978
} | class ____(BaseModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
C... | LlavaNextModelOutputWithPast |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/execution.py | {
"start": 430,
"end": 893
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
class Meta:
name = "ExecutionStepOutput"
def __init__(self, step_output_snap):
super().__init__()
self._step_output_snap = check.inst_param(
step_output_snap, "step_output_snap", ExecutionStepOutp... | GrapheneExecutionStepOutput |
python | getsentry__sentry | src/sentry/new_migrations/monkey/state.py | {
"start": 344,
"end": 4700
} | class ____(ProjectState):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pending_deletion_models: dict[tuple[str, str], type[Model]] = {}
self.pending_deletion_fields: dict[tuple[str, str, str], type[Field]] = {}
def get_pending_deletion_model(self, app_labe... | SentryProjectState |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess10.py | {
"start": 422,
"end": 713
} | class ____:
number_cls = IntDescriptorClass
reveal_type(X.number_cls, expected_text="int")
reveal_type(X().number_cls, expected_text="int")
X.number_cls = "hi"
X().number_cls = "hi"
# This should generate an error
X.number_cls = 1
# This should generate an error
X().number_cls = 1
| X |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/tryceratops/TRY004.py | {
"start": 363,
"end": 5455
} | class ____:
pass
def incorrect_with_issubclass(some_arg):
if issubclass(some_arg, MyClass):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_with_callable(some_arg):
if callable(some_arg):
pass
else:
raise Exception("...") # should be typeer... | MyClass |
python | pytorch__pytorch | torch/_inductor/debug.py | {
"start": 17352,
"end": 28363
} | class ____:
def __init__(self, handler: DebugContext) -> None:
self.fopen = handler.fopen
self.fopen_context = handler.fopen_context
self.filename = handler.filename
self.handler = handler
def fx_graph(
self,
gm: torch.fx.GraphModule,
inputs: list[torch.T... | DebugFormatter |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 16068,
"end": 18989
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.pos_conv_embed = HubertPositionalConvEmbedding(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout... | HubertEncoder |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 146232,
"end": 159727
} | class ____(
_RelationshipErrors, fixtures.MappedTest
):
@classmethod
def define_tables(cls, metadata):
Table(
"foos",
metadata,
Column("id", Integer, primary_key=True),
Column("fid", Integer),
)
Table(
"bars",
me... | InvalidRelationshipEscalationTest |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/dynamic_ragged_shape_test.py | {
"start": 4813,
"end": 116966
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def assertRowPartitionEq(self,
x: RowPartition,
y: RowPartition,
msg=None) -> None:
self.assertAllEqual(x.row_splits(), y.row_splits(), m... | DynamicRaggedShapeTest |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/pretty.py | {
"start": 7910,
"end": 13849
} | class ____(JupyterMixin):
"""A rich renderable that pretty prints an object.
Args:
_object (Any): An object to pretty print.
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
indent_size (int, optional): Number... | Pretty |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_managed_kafka.py | {
"start": 18691,
"end": 19754
} | class ____:
@mock.patch(MANAGED_KAFKA_PATH.format("ManagedKafkaHook"))
def test_execute(self, mock_hook):
op = ManagedKafkaDeleteConsumerGroupOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
location=GCP_LOCATION... | TestManagedKafkaDeleteConsumerGroupOperator |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 73323,
"end": 77198
} | class ____(SingleODESolver):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solv... | NthLinearConstantCoeffHomogeneous |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/models.py | {
"start": 149,
"end": 1029
} | class ____:
"""A recorded session of the `scaffold branch` command, useful for evaluating effectiveness."""
# isoformat
timestamp: str
# what code was used - semver for published package, commit hash for local development
dg_version: str
# the name of the branch created (even if AI not used)
... | Session |
python | dask__dask | dask/array/core.py | {
"start": 44342,
"end": 198746
} | class ____(DaskMethodsMixin):
"""Parallel Dask Array
A parallel nd-array comprised of many numpy arrays arranged in a grid.
This constructor is for advanced uses only. For normal use see the
:func:`dask.array.from_array` function.
Parameters
----------
dask : dict
Task dependency... | Array |
python | psf__black | src/black/rusty.py | {
"start": 251,
"end": 396
} | class ____(Generic[T]):
def __init__(self, value: T) -> None:
self._value = value
def ok(self) -> T:
return self._value
| Ok |
python | PrefectHQ__prefect | src/prefect/serializers.py | {
"start": 9512,
"end": 9789
} | class ____(CompressedSerializer[D]):
"""
A compressed serializer preconfigured to use the json serializer.
"""
type: str = Field(default="compressed/json", frozen=True)
serializer: Serializer[D] = Field(default_factory=JSONSerializer)
| CompressedJSONSerializer |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 115734,
"end": 115952
} | class ____(ServerAdapter):
""" Untested. """
def run(self, handler):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
| DieselServer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 55831,
"end": 56188
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("subject_id", "client_mutation_id")
subject_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subjectId")
client_mutation_id = sgqlc.types.Field(String, graphql_... | AddUpvoteInput |
python | chroma-core__chroma | sample_apps/generative_benchmarking/functions/types.py | {
"start": 76,
"end": 156
} | class ____:
doc_relevances: Dict[str, Dict[str, int]]
@dataclass
| QueryRelevance |
python | kamyu104__LeetCode-Solutions | Python/find-the-key-of-the-numbers.py | {
"start": 43,
"end": 443
} | class ____(object):
def generateKey(self, num1, num2, num3):
"""
:type num1: int
:type num2: int
:type num3: int
:rtype: int
"""
L = 4
result = 0
base = pow(10, L-1)
for _ in xrange(L):
result = result*10+min(num1//base%10, ... | Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_state_dict_stager.py | {
"start": 7171,
"end": 7242
} | class ____:
tensor: torch.Tensor
value: int = 100
| FrozenDataClass |
python | pytorch__pytorch | torch/autograd/profiler.py | {
"start": 2556,
"end": 29580
} | class ____:
"""Context manager that manages autograd profiler state and holds a summary of results.
.. note::
This is the backend, most people should use :mod:`torch.profiler` instead.
Under the hood it just records events of functions being executed in C++ and
exposes those events to Python. ... | profile |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_github_enterprise.py | {
"start": 979,
"end": 6855
} | class ____(TestCase):
factory = RequestFactory()
path = reverse("sentry-integration-github-enterprise-webhook")
external_host = "12.345.678.901"
external_identifier = "github_enterprise:1"
external_id = f"{external_host}:{external_identifier}"
def get_response(self, req: HttpRequest) -> HttpRes... | GithubEnterpriseRequestParserTest |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 77728,
"end": 90099
} | class ____(TestCase, BaseIncidentsTest):
def setUp(self) -> None:
super().setUp()
class _DynamicMetricAlertSettings(TypedDict):
name: str
query: str
aggregate: str
time_window: int
threshold_type: AlertRuleThresholdType
thresho... | DeleteAlertRuleTest |
python | astropy__astropy | astropy/table/info.py | {
"start": 3521,
"end": 7381
} | class ____(DataInfo):
def __call__(self, option="attributes", out=""):
return table_info(self._parent, option, out)
__call__.__doc__ = table_info.__doc__
@contextmanager
def serialize_method_as(tbl, serialize_method):
"""Context manager to temporarily override individual
column info.serialize... | TableInfo |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 212977,
"end": 217534
} | class ____:
@pytest.mark.parametrize(
"func,ftype",
[
make_xp_pytest_param(butter, "butter"),
make_xp_pytest_param(bessel, "bessel"),
make_xp_pytest_param(cheby1, "cheby1"),
make_xp_pytest_param(cheby2, "cheby2"),
make_xp_pytest_param(elli... | TestIIRFilter |
python | pandas-dev__pandas | pandas/core/interchange/dataframe.py | {
"start": 455,
"end": 3867
} | class ____(DataFrameXchg):
"""
A data frame class, with only the methods required by the interchange
protocol defined.
Instances of this (private) class are returned from
``pd.DataFrame.__dataframe__`` as objects with the methods and
attributes defined on this class.
"""
def __init__(se... | PandasDataFrameXchg |
python | astropy__astropy | astropy/units/errors.py | {
"start": 322,
"end": 418
} | class ____(Exception):
"""
The base class for unit-specific exceptions.
"""
| UnitsError |
python | walkccc__LeetCode | solutions/1987. Number of Unique Good Subsequences/1987.py | {
"start": 0,
"end": 557
} | class ____:
# Similar to 940. Distinct Subsequences II
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
MOD = 1_000_000_007
# endsIn[i] := the number of subsequence that end in ('0' + i)
endsIn = {'0': 0, '1': 0}
for c in binary:
endsIn[c] = sum(endsIn.values()) % MOD
# Don... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with2.py | {
"start": 188,
"end": 254
} | class ____(object):
def __enter__(self):
return 1
| Class2 |
python | django__django | django/contrib/auth/migrations/0010_alter_group_name_max_length.py | {
"start": 43,
"end": 378
} | class ____(migrations.Migration):
dependencies = [
("auth", "0009_alter_user_last_name_max_length"),
]
operations = [
migrations.AlterField(
model_name="group",
name="name",
field=models.CharField(max_length=150, unique=True, verbose_name="name"),
... | Migration |
python | crytic__slither | slither/vyper_parsing/ast/ast.py | {
"start": 612,
"end": 11525
} | class ____(Exception):
pass
def _extract_base_props(raw: Dict) -> Dict:
return {
"src": raw["src"],
"node_id": raw["node_id"],
}
def _extract_decl_props(raw: Dict) -> Dict:
return {
"doc_string": parse_doc_str(raw["doc_string"]) if raw["doc_string"] else None,
**_extr... | ParsingError |
python | plotly__plotly.py | plotly/graph_objs/parcats/line/colorbar/_tickfont.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcats.line.colorbar"
_path_str = "parcats.line.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",... | Tickfont |
python | Pylons__pyramid | tests/test_security.py | {
"start": 6733,
"end": 9492
} | class ____(unittest.TestCase):
def setUp(self):
testing.setUp()
def tearDown(self):
testing.tearDown()
def _callFUT(self, *arg, **kw):
from pyramid.security import view_execution_permitted
return view_execution_permitted(*arg, **kw)
def _registerSecuredView(self, view... | TestViewExecutionPermitted |
python | walkccc__LeetCode | solutions/2963. Count the Number of Good Partitions/2963.py | {
"start": 0,
"end": 709
} | class ____:
def numberOfGoodPartitions(self, nums: list[int]) -> int:
MOD = 1_000_000_007
ans = 1
# lastSeen[num] := the index of the last time `num` appeared
lastSeen = {}
for i, num in enumerate(nums):
lastSeen[num] = i
# Track the maximum right index of each running partition by ens... | Solution |
python | spyder-ide__spyder | spyder/plugins/run/tests/test_run.py | {
"start": 11736,
"end": 31105
} | class ____(type(ExampleRunExecutorWrapper)):
def __new__(cls, clsname, bases, attrs):
executor_name = attrs.pop('executor_name_meta')
def get_name():
return executor_name
return super(MetaExampleRunExecutor, cls).__new__(
cls, clsname, bases, {
**at... | MetaExampleRunExecutor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance2.py | {
"start": 345,
"end": 991
} | class ____(Document):
pass
def func1() -> Union[int, DbModel]:
return DbModel()
# This should not generate an error even though DbModel is
# derived from an unknown base class.
isinstance(func1(), int)
def func2(obj: object, typ: type):
return isinstance(obj, typ)
def func3(obj: float):
if isins... | DbModel |
python | huggingface__transformers | src/transformers/models/cwm/modeling_cwm.py | {
"start": 15465,
"end": 15547
} | class ____(BaseModelOutputWithPast):
pass
@auto_docstring
| CwmModelOutputWithPast |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.