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 | pyinstaller__pyinstaller | bootloader/waflib/Tools/qt5.py | {
"start": 6706,
"end": 7624
} | class ____(Task.Task):
color = 'BLUE'
run_str = '${QT_RCC} -name ${tsk.rcname()} ${SRC[0].abspath()} ${RCC_ST} -o ${TGT}'
ext_out = ['.h']
def rcname(self):
return os.path.splitext(self.inputs[0].name)[0]
def scan(self):
if not has_xml:
Logs.error('No xml.sax support wa... | rcc |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 8008,
"end": 8207
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DISABLED", "ENABLED")
| EnterpriseMembersCanMakePurchasesSettingValue |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 41057,
"end": 46514
} | class ____(Model):
"""
Perform an affine transformation in 2 dimensions.
Parameters
----------
matrix : array
A 2x2 matrix specifying the linear transformation to apply to the
inputs
translation : array
A 2D vector (given as either a 2x1 or 1x2 array) specifying a
... | AffineTransformation2D |
python | getsentry__sentry | src/sentry/relay/config/ai_model_costs.py | {
"start": 570,
"end": 1295
} | class ____(TypedDict):
version: Required[int]
models: Required[dict[ModelId, AIModelCostV2]]
def ai_model_costs_config() -> AIModelCosts | None:
"""
Get AI model costs configuration.
AI model costs are set in cache by a cron job,
if there are no costs, it should be investigated why.
Retur... | AIModelCosts |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 8027,
"end": 44094
} | class ____(_RingRotater):
"""
Allgather the kv and return only the required kv.
Only one communication will be done.
"""
def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None:
self._pg = pg
self._seq_dim = seq_dim
self._aggregated_buffer: torch.Tensor | None = None... | _AllGatherRotater |
python | huggingface__transformers | src/transformers/models/eomt/image_processing_eomt_fast.py | {
"start": 2219,
"end": 20751
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"shortest_edge": 640, "longest_edge": 640}
default_to_square = False
do_resize = True
do_rescale = True
do_normalize = True
do_split_... | EomtImageProcessorFast |
python | django-import-export__django-import-export | tests/core/tests/test_base_formats.py | {
"start": 5625,
"end": 7468
} | class ____(TestCase):
def setUp(self):
self.format = base_formats.CSV()
self.dataset = tablib.Dataset(headers=["id", "username"])
self.dataset.append(("1", "x"))
def test_import_dos(self):
filename = os.path.join(
os.path.dirname(__file__), os.path.pardir, "exports",... | CSVTest |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/toys/user_computed_data_versions/external_system.py | {
"start": 625,
"end": 674
} | class ____(TypedDict):
key: str
| SourceAssetInfo |
python | py-pdf__pypdf | pypdf/_text_extraction/_layout_mode/_font.py | {
"start": 345,
"end": 7067
} | class ____:
"""
A font object formatted for use during "layout" mode text extraction
Attributes:
subtype (str): font subtype
space_width (int | float): width of a space character
encoding (str | Dict[int, str]): font encoding
char_map (dict): character map
font_dicti... | Font |
python | redis__redis-py | redis/maint_notifications.py | {
"start": 10736,
"end": 13539
} | class ____(MaintenanceNotification):
"""
Notification for when a Redis cluster node has completed a failover.
This notification is received when a node has finished the failover process
during cluster maintenance operations or after handling node failures.
Args:
id (int): Unique identifier... | NodeFailedOverNotification |
python | ray-project__ray | python/ray/util/metrics.py | {
"start": 1395,
"end": 5820
} | class ____:
"""The parent class of custom metrics.
Ray's custom metrics APIs are rooted from this class and share
the same public methods.
"""
def __init__(
self,
name: str,
description: str = "",
tag_keys: Optional[Tuple[str, ...]] = None,
):
# Metrics ... | Metric |
python | django__django | tests/serializers/models/data.py | {
"start": 1659,
"end": 1758
} | class ____(models.Model):
data = models.PositiveBigIntegerField(null=True)
| PositiveBigIntegerData |
python | kamyu104__LeetCode-Solutions | Python/unique-paths.py | {
"start": 33,
"end": 481
} | class ____(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def nCr(n, r): # Time: O(n), Space: O(1)
if n-r < r:
r = n-r
c = 1
for k in xrange(1, r+1):
c *= n-k+1
... | Solution |
python | encode__django-rest-framework | tests/test_throttling.py | {
"start": 953,
"end": 1172
} | class ____(BaseThrottle):
def allow_request(self, request, view):
if not hasattr(self.__class__, 'called'):
self.__class__.called = True
return True
return False
| NonTimeThrottle |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 64945,
"end": 65823
} | class ____(DefinedFunction):
r"""
Returns the Kronecker symbol `(a / n)`.
Examples
========
>>> from sympy.functions.combinatorial.numbers import kronecker_symbol
>>> kronecker_symbol(45, 77)
-1
>>> kronecker_symbol(13, -120)
1
See Also
========
jacobi_symbol, legendr... | kronecker_symbol |
python | etianen__django-reversion | tests/test_app/tests/test_middleware.py | {
"start": 328,
"end": 892
} | class ____(TestModelMixin, TestBase):
def testCreateRevision(self):
response = self.client.post("/test-app/save-obj/")
obj = TestModel.objects.get(pk=response.content)
self.assertSingleRevision((obj,))
def testCreateRevisionError(self):
with self.assertRaises(Exception):
... | RevisionMiddlewareTest |
python | python__mypy | mypy/util.py | {
"start": 4250,
"end": 10023
} | class ____(Exception):
"""Exception raised when a file cannot be decoded due to an unknown encoding type.
Essentially a wrapper for the LookupError raised by `bytearray.decode`
"""
def decode_python_encoding(source: bytes) -> str:
"""Read the Python file with while obeying PEP-263 encoding detection.... | DecodeError |
python | wandb__wandb | wandb/sdk/internal/context.py | {
"start": 893,
"end": 2518
} | class ____:
_active_items: Dict[str, Context]
def __init__(self) -> None:
self._active_items = {}
def add_from_record(self, record: Record) -> Optional[Context]:
context_id = context_id_from_record(record)
if not context_id:
return None
context_obj = self.add(co... | ContextKeeper |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_between.py | {
"start": 559,
"end": 780
} | class ____(ValueError):
def __init__(self, column_type: str):
message = f"ColumnValuesBetween metrics cannot be computed on column of type {column_type}."
super().__init__(message)
| InvalidColumnTypeError |
python | dagster-io__dagster | .buildkite/dagster-buildkite/dagster_buildkite/steps/tox.py | {
"start": 484,
"end": 3683
} | class ____:
"""Represents a tox environment factor for configuration.
Args:
factor: The tox factor name (e.g., "pytest", "integration")
splits: Number of parallel splits to generate for this factor (default: 1)
"""
factor: str
splits: int = 1
_COMMAND_TYPE_TO_EMOJI_MAP = {
"p... | ToxFactor |
python | django-extensions__django-extensions | tests/test_templatetags.py | {
"start": 631,
"end": 1166
} | class ____(TestCase):
"""Test class for DebuggerTags."""
def setUp(self):
self.engine = engines["django"]
def test_pdb_filter(self):
"""Test for pdb filter."""
import pdb
pdb.set_trace = MagicMock(return_value=None)
template = self.engine.from_string(
"... | DebuggerTagsTests |
python | numpy__numpy | numpy/_core/tests/test_array_coercion.py | {
"start": 4583,
"end": 6418
} | class ____:
@pytest.mark.parametrize("obj",
[object(), 1.2, 10**43, None, "string"],
ids=["object", "1.2", "10**43", "None", "string"])
def test_basic_stringlength(self, obj):
length = len(str(obj))
expected = np.dtype(f"S{length}")
assert np.array(obj, dtype="S"... | TestStringDiscovery |
python | google__jax | jax/_src/custom_transpose.py | {
"start": 1535,
"end": 2247
} | class ____(lu.Store):
"""Stores an unchanging value. Checks empty reads and unequal overwrites."""
def store(self, val):
if self._val is not lu._EMPTY_STORE_VALUE and val != self._val:
raise lu.StoreException(
f"Store assignment mismatch, from {self._val} to {val}")
self._val = val
@util.cu... | StoreEqual |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_snippets.py | {
"start": 20698,
"end": 21629
} | class ____(util.MdCase):
"""Test snippet file case."""
extension = [
'pymdownx.snippets',
]
extension_configs = {
'pymdownx.snippets': {
'base_path': [os.path.join(BASE, '_snippets')]
}
}
def test_top_level(self):
"""Test top level."""
self... | TestSnippetsGracefulMissing |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py | {
"start": 17771,
"end": 20707
} | class ____:
@staticmethod
def make_mock_awaitable(mock_obj, result=None):
f = Future()
f.set_result(result)
mock_obj.return_value = f
@pytest.fixture
def async_hook(self):
return GKEKubernetesAsyncHook(
cluster_url=CLUSTER_URL,
ssl_ca_cert=SSL_CA... | TestGKEKubernetesAsyncHook |
python | kamyu104__LeetCode-Solutions | Python/count-valid-paths-in-a-tree.py | {
"start": 3657,
"end": 4489
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.size = [1]*n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
... | UnionFind |
python | pytorch__pytorch | test/dynamo/test_generator.py | {
"start": 24948,
"end": 25970
} | class ____(GeneratorTestsBase):
def test_send(self):
def double():
x = yield
yield x * 2
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = double()
next(gen)
return gen.send(t)
t = torch.randn(2)
y =... | TestGeneratorSend |
python | modin-project__modin | versioneer.py | {
"start": 14658,
"end": 19336
} | class ____:
"""Container for Versioneer configuration parameters."""
VCS: str
style: str
tag_prefix: str
versionfile_source: str
versionfile_build: Optional[str]
parentdir_prefix: Optional[str]
verbose: Optional[bool]
def get_root() -> str:
"""Get the project root directory.
... | VersioneerConfig |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 6931,
"end": 7587
} | class ____(BaseModel):
action: ShellCallAction
"""The shell commands and limits that describe how to run the tool call."""
call_id: str
"""The unique ID of the function shell tool call generated by the model."""
type: Literal["shell_call"]
"""The type of the item. Always `function_shell_call`.... | ShellCall |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 58938,
"end": 60640
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
host: str,
port: int,
database: str,
username: str,
password: Optional[str] = None,
jdbc_url_params: Optional[str] = None,
ssl: Optional[bool] = None,
):
... | ClickhouseSource |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_variables.py | {
"start": 1220,
"end": 3144
} | class ____:
@pytest.mark.parametrize(
("deserialize_json", "value", "expected_value"),
[
pytest.param(
False,
"my_value",
"my_value",
id="simple-value",
),
pytest.param(
True,
... | TestVariables |
python | pytorch__pytorch | torch/_inductor/sizevars.py | {
"start": 46184,
"end": 47285
} | class ____(V.WrapperHandler): # type: ignore[name-defined]
"""
A wrapper around .virtualize.ops that uses var range information to
simplify ModularIndexing/FloorDiv.
"""
def __init__(self, inner, var_ranges: VarRanges) -> None:
super().__init__(inner)
self.name = "SimplifyIndexing"... | SimplifyIndexing |
python | justquick__django-activity-stream | actstream/drf/serializers.py | {
"start": 3099,
"end": 3390
} | class ____(DEFAULT_SERIALIZER):
"""
Serializer for actstream.Follow models in the activity feeds
"""
user = get_grf()
follow_object = get_grf()
class Meta:
model = Follow
fields = 'id flag user follow_object started actor_only'.split()
| FollowSerializer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/mem_io_manager.py | {
"start": 228,
"end": 1135
} | class ____(IOManager):
"""I/O manager that stores and retrieves values in memory. After execution is complete, the values will
be garbage-collected. Note that this means that each run will not have access to values from previous runs.
"""
def __init__(self):
self.values: dict[tuple[object, ...]... | InMemoryIOManager |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 5024,
"end": 5364
} | class ____(CtrlNode):
"""Filters data by taking the mode (histogram-based) of a sliding window"""
nodeName = 'ModeFilter'
uiTemplate = [
('window', 'intSpin', {'value': 500, 'min': 1, 'max': 1000000}),
]
def processData(self, data):
return functions.modeFilter(data, self.ctrls['... | Mode |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 36520,
"end": 37608
} | class ____(BaseAPIIntegrationTest):
def test_diff(self):
container = self.client.create_container(TEST_IMG, ['touch', '/test'])
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exitcode = self.client.wait(id)['StatusCode']
assert exitcode == 0... | DiffTest |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 11936,
"end": 12946
} | class ____(URLPatternsTestCase, APITestCase):
included = [
path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
]
urlpatterns = [
path('v1/', include((included, 'v1'), namespace='v1')),
path('v2/', include((included, 'v2'), namespace='v2'))
]
def setUp(self):
... | TestHyperlinkedRelatedField |
python | PrefectHQ__prefect | tests/test_settings.py | {
"start": 59000,
"end": 60674
} | class ____:
def test_temporary_settings(self):
assert PREFECT_TEST_MODE.value() is True
with temporary_settings(updates={PREFECT_TEST_MODE: False}) as new_settings:
assert PREFECT_TEST_MODE.value_from(new_settings) is False, (
"Yields the new settings"
)
... | TestTemporarySettings |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/string_lower_op_test.py | {
"start": 838,
"end": 1908
} | class ____(test.TestCase):
"""Test cases for tf.strings.lower."""
def test_string_lower(self):
strings = ["Pigs on The Wing", "aNimals"]
with self.cached_session():
output = string_ops.string_lower(strings)
output = self.evaluate(output)
self.assertAllEqual(output, [b"pigs on the wing", ... | StringLowerOpTest |
python | pytorch__pytorch | test/dynamo/test_backward_higher_order_ops.py | {
"start": 1957,
"end": 2670
} | class ____(torch.nn.Module):
def forward(self, grad_1: "f32[2]"):
trace_wrapped: "f32[2]" = torch__dynamo__trace_wrapped_higher_order_op_self_invoke(grad_1); grad_1 = None
return trace_wrapped
""",
)
def test_invoke_make_bw(self):
x = torch.tensor([0.5, 0.5], requires_grad=True... | _multiply_invoke |
python | networkx__networkx | networkx/classes/tests/test_multigraph.py | {
"start": 205,
"end": 5848
} | class ____(BaseAttrGraphTester):
def test_has_edge(self):
G = self.K3
assert G.has_edge(0, 1)
assert not G.has_edge(0, -1)
assert G.has_edge(0, 1, 0)
assert not G.has_edge(0, 1, 1)
def test_get_edge_data(self):
G = self.K3
assert G.get_edge_data(0, 1) == ... | BaseMultiGraphTester |
python | doocs__leetcode | solution/0600-0699/0658.Find K Closest Elements/Solution2.py | {
"start": 0,
"end": 281
} | class ____:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr)
while r - l > k:
if x - arr[l] <= arr[r - 1] - x:
r -= 1
else:
l += 1
return arr[l:r]
| Solution |
python | google__pytype | pytype/rewrite/abstract/base.py | {
"start": 608,
"end": 2404
} | class ____(types.BaseValue, abc.ABC):
"""Base class for abstract values."""
# For convenience, we want the 'name' attribute to be available on all values.
# Setting it as a class attribute gives subclasses the most flexibility in how
# to define it.
name = ''
def __init__(self, ctx: ContextType):
self... | BaseValue |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-wordlift/llama_index/readers/wordlift/base.py | {
"start": 596,
"end": 819
} | class ____(WordLiftLoaderError):
"""Exception raised for errors in data transformation."""
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message)
| DataTransformError |
python | encode__starlette | tests/middleware/test_base.py | {
"start": 911,
"end": 1597
} | class ____(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
response = await call_next(request)
response.headers["Custom-Header"] = "Example"
return response
def homepage(request: Request) -> Pla... | CustomMiddleware |
python | Lightning-AI__lightning | src/lightning/fabric/_graveyard/tpu.py | {
"start": 2823,
"end": 3243
} | class ____(XLAPrecision):
"""Legacy class.
Use :class:`~lightning.fabric.plugins.precision.xla.XLAPrecision` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation(
"The `XLABf16Precision` class is deprecated. Use `lightning.fabric.plugins.precis... | XLABf16Precision |
python | mlflow__mlflow | mlflow/pyfunc/__init__.py | {
"start": 26848,
"end": 46676
} | class ____:
"""
MLflow 'python function' model.
Wrapper around model implementation and metadata. This class is not meant to be constructed
directly. Instead, instances of this class are constructed and returned from
:py:func:`load_model() <mlflow.pyfunc.load_model>`.
``model_impl`` can be any... | PyFuncModel |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/device_op_overrides.py | {
"start": 191,
"end": 14719
} | class ____(DeviceOpOverrides):
"""
CUDA-specific codegen functions, see DeviceOpOverrides for details
"""
def import_get_raw_stream_as(self, name: str) -> str:
return f"from torch._C import _cuda_getCurrentRawStream as {name}"
def set_device(self, device_idx: int) -> str:
return f"... | CUDADeviceOpOverrides |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 1110,
"end": 1208
} | class ____(Exception):
"""Raised if the node could not perform a requested action."""
| Impossible |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 18170,
"end": 22861
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: WhisperConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = WhisperAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_head... | WhisperDecoderLayer |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 4413,
"end": 5831
} | class ____:
def test_1d(self):
a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
desired = 3. / (1./1 + 1./2 + 1./3)
check_equal_hmean(a, desired, rtol=1e-14)
a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
desired = 34.1417152147
check_equal_hmean(a, desired)... | TestHarMean |
python | getsentry__sentry | src/sentry/notifications/platform/types.py | {
"start": 3041,
"end": 5126
} | class ____:
subject: str
"""
The subject or title of the notification. It's expected that the receiver understand the
expected content of the notification based on this alone, and it will be the first thing
they see. This string should not contain any formatting, and will be displayed as is.
"""... | NotificationRenderedTemplate |
python | getsentry__sentry | tests/sentry/utils/test_committers.py | {
"start": 4502,
"end": 5818
} | class ____(CommitTestCase):
def setUp(self) -> None:
super().setUp()
commit_1 = self.create_commit()
commit_2 = self.create_commit()
commit_3 = self.create_commit()
file_change_1 = self.create_commitfilechange(
filename="hello/app.py", type="A", commit=commit_1
... | GetCommitFileChangesTestCase |
python | bokeh__bokeh | src/bokeh/models/selectors.py | {
"start": 2165,
"end": 2547
} | class ____(Selector):
""" Represents a CSS class selector query. """
# explicit __init__ to support Init signatures
def __init__(self, query: Init[str] = Intrinsic, **kwargs: Any) -> None:
super().__init__(query=query, **kwargs)
query = Required(String, help="""
CSS class name without ``.`... | ByClass |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-click/sphinx_click/ext.py | {
"start": 13360,
"end": 19285
} | class ____(rst.Directive):
has_content = False
required_arguments = 1
option_spec = {
"prog": directives.unchanged_required,
"nested": nested,
"commands": directives.unchanged,
"show-nested": directives.flag,
}
def _load_module(self, module_path: str) -> ty.Union[cli... | ClickDirective |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/inheritance/simple_inheritance.py | {
"start": 0,
"end": 39
} | class ____:
"""parent class"""
| Parent |
python | huggingface__transformers | tests/models/metaclip_2/test_modeling_metaclip_2.py | {
"start": 1787,
"end": 5837
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
... | MetaClip2VisionModelTester |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 3103,
"end": 4548
} | class ____(DynamicCache):
def __init__(self):
super().__init__()
self.linear_cache: list[torch.Tensor] = []
def set_linear_cache(self, layer_idx, linear_cache):
# There may be skipped layers, fill them with empty lists
for _ in range(len(self.linear_cache), layer_idx + 1):
... | MiniMaxCache |
python | huggingface__transformers | src/transformers/models/mpnet/modeling_mpnet.py | {
"start": 19859,
"end": 20751
} | class ____(nn.Module):
"""MPNet Head for masked and permuted language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.de... | MPNetLMHead |
python | pypa__pipenv | pipenv/vendor/pipdeptree/_models/package.py | {
"start": 737,
"end": 2491
} | class ____(ABC):
"""Abstract class for wrappers around objects that pip returns."""
UNKNOWN_LICENSE_STR = "(Unknown license)"
def __init__(self, project_name: str) -> None:
self.project_name = project_name
self.key = canonicalize_name(project_name)
def licenses(self) -> str:
t... | Package |
python | fastapi__sqlmodel | docs_src/tutorial/select/tutorial002_py310.py | {
"start": 79,
"end": 1217
} | class ____(SQLModel, table=True): # (2)!
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) # (3)!
def create_db_and_ta... | Hero |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/jax_to_torch.py | {
"start": 1461,
"end": 3703
} | class ____(ArrayConversion):
"""Wraps a Jax-based environment so that it can be interacted with PyTorch Tensors.
Actions must be provided as PyTorch Tensors and observations will be returned as PyTorch Tensors.
A vector version of the wrapper exists, :class:`gymnasium.wrappers.vector.JaxToTorch`.
Note... | JaxToTorch |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/compiler.py | {
"start": 511,
"end": 10447
} | class ____(spack.package_base.PackageBase):
"""A Package mixin for all common logic for packages that implement compilers"""
# TODO: how do these play nicely with other tags
tags: Sequence[str] = ["compiler"]
#: Optional suffix regexes for searching for this type of compiler.
#: Suffixes are used ... | CompilerPackage |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 7217,
"end": 7860
} | class ____:
"""
Helper mixin that implements "scopes handling" behaviour
"""
required_scopes = None
def get_scopes(self, *args, **kwargs):
"""
Return the scopes needed to access the resource
:param args: Support scopes injections from the outside (not yet implemented)
... | ScopedResourceMixin |
python | readthedocs__readthedocs.org | readthedocs/builds/querysets.py | {
"start": 791,
"end": 5041
} | class ____(NoReprQuerySet, models.QuerySet):
"""Versions take into account their own privacy_level setting."""
use_for_related_fields = True
def __init__(self, *args, internal_only=False, external_only=False, **kwargs):
"""
Overridden to pass extra arguments from the manager.
Usag... | VersionQuerySetBase |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 1942,
"end": 3026
} | class ____(Exception):
pass
def read_headers(fd):
response_line = fd.readline()
if not response_line:
raise ConnectionClosed
response_line = response_line.decode('latin-1')
headers = {}
while True:
line = fd.readline().strip()
if not line:
break
line... | ConnectionClosed |
python | mitmproxy__pdoc | test/testdata/demopackage/subpackage/child_g.py | {
"start": 26,
"end": 180
} | class ____:
"""This class is defined in subpackage's child_g, but reexposed in the `demopackage.subpackage` namespace."""
def g(self):
pass
| G |
python | apache__airflow | airflow-core/tests/unit/serialization/serializers/test_serializers.py | {
"start": 2173,
"end": 2280
} | class ____(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=2)
| NoNameTZ |
python | walkccc__LeetCode | solutions/156. Binary Tree Upside Down/156.py | {
"start": 0,
"end": 372
} | class ____:
def upsideDownBinaryTree(self, root: TreeNode | None) -> TreeNode | None:
if not root or not root.left:
return root
newRoot = self.upsideDownBinaryTree(root.left)
root.left.left = root.right # 2's left = 3 (root's right)
root.left.right = root # 2's right = 1 (root)
root.left ... | Solution |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 184386,
"end": 189107
} | class ____(RunnableSerializable[list[Input], list[Output]]):
"""RunnableEachBase class.
`Runnable` that calls another `Runnable` for each element of the input sequence.
Use only if creating a new `RunnableEach` subclass with different `__init__`
args.
See documentation for `RunnableEach` for more... | RunnableEachBase |
python | django__django | tests/forms_tests/field_tests/test_base.py | {
"start": 1243,
"end": 1454
} | class ____(SimpleTestCase):
def test_disabled_field_has_changed_always_false(self):
disabled_field = Field(disabled=True)
self.assertFalse(disabled_field.has_changed("x", "y"))
| DisabledFieldTests |
python | python-poetry__poetry | src/poetry/config/config_source.py | {
"start": 334,
"end": 610
} | class ____(ABC):
@abstractmethod
def get_property(self, key: str) -> Any: ...
@abstractmethod
def add_property(self, key: str, value: Any) -> None: ...
@abstractmethod
def remove_property(self, key: str) -> None: ...
@dataclasses.dataclass
| ConfigSource |
python | ipython__ipython | IPython/core/display.py | {
"start": 13414,
"end": 13524
} | class ____(TextDisplayObject):
def _repr_pretty_(self, pp, cycle):
return pp.text(self.data)
| Pretty |
python | pypa__packaging | tests/test_tags.py | {
"start": 2879,
"end": 4166
} | class ____:
def test_lowercasing(self) -> None:
tag = tags.Tag("PY3", "None", "ANY")
assert tag.interpreter == "py3"
assert tag.abi == "none"
assert tag.platform == "any"
def test_equality(self) -> None:
args = "py3", "none", "any"
assert tags.Tag(*args) == tags.... | TestTag |
python | django__django | django/contrib/postgres/fields/ranges.py | {
"start": 6093,
"end": 6291
} | class ____(RangeField):
base_field = models.DateField
range_type = DateRange
form_field = forms.DateRangeField
def db_type(self, connection):
return "daterange"
| DateRangeField |
python | readthedocs__readthedocs.org | readthedocs/oauth/models.py | {
"start": 761,
"end": 2208
} | class ____(models.Manager):
def get_or_create_installation(
self, *, installation_id, target_id, target_type, extra_data=None
):
"""
Get or create a GitHub app installation.
Only the installation_id is unique, the target_id and target_type could change,
but this should n... | GitHubAppInstallationManager |
python | ray-project__ray | python/ray/tune/trainable/trainable_fn_utils.py | {
"start": 414,
"end": 2163
} | class ____(TrainCheckpoint):
# NOTE: This is just a pass-through wrapper around `ray.train.Checkpoint`
# in order to detect whether the import module was correct `ray.tune.Checkpoint`.
pass
@PublicAPI(stability="stable")
@_warn_session_misuse()
def report(metrics: Dict, *, checkpoint: Optional[Checkpoint]... | Checkpoint |
python | django-extensions__django-extensions | tests/testapp/jobs/daily/test_daily_job.py | {
"start": 120,
"end": 224
} | class ____(DailyJob):
help = "My sample daily job."
def execute(self):
DAILY_JOB_MOCK()
| Job |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py | {
"start": 100002,
"end": 125314
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_v1_only("b/124229375")
def testBasicRNNCell(self):
with self.cached_session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
x = array_ops.zeros([1, 2])
m = a... | RNNCellTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_views.py | {
"start": 4078,
"end": 6440
} | class ____(TestCase):
def setUp(self):
self.user = new(User, username="test")
self.user.set_password("test")
self.user.save()
self.project = get(Project, slug="my-mainproject")
self.subproject = get(Project, slug="my-subproject")
self.project.add_subproject(self.subp... | SubprojectViewTests |
python | apache__airflow | providers/datadog/src/airflow/providers/datadog/hooks/datadog.py | {
"start": 1060,
"end": 7279
} | class ____(BaseHook, LoggingMixin):
"""
Uses datadog API to send metrics of practically anything measurable.
It's possible to track # of db records inserted/deleted, records read
from file and many other useful metrics.
Depends on the datadog API, which has to be deployed on the same server where
... | DatadogHook |
python | google__jax | jax/_src/pallas/mosaic/lowering.py | {
"start": 5520,
"end": 6784
} | class ____:
dim_expr_to_placeholder: dict[shape_poly._DimExpr, int] = {}
placeholder_to_dim_expr: dict[int, shape_poly._DimExpr] = {}
def to_placeholder(self, dim_expr: Any) -> ir.Value:
if jax_core.is_constant_dim(dim_expr):
# avoid ints, these are not dynamic
return dim_expr
if dim_expr not... | LoweringDynamicShapeEnv |
python | django__django | tests/test_runner/tests.py | {
"start": 10445,
"end": 14012
} | class ____(unittest.TestCase):
def test_simple_dependencies(self):
raw = [
("s1", ("s1_db", ["alpha"])),
("s2", ("s2_db", ["bravo"])),
("s3", ("s3_db", ["charlie"])),
]
dependencies = {
"alpha": ["charlie"],
"bravo": ["charlie"],
... | DependencyOrderingTests |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 16297,
"end": 18337
} | class ____(TestCase, RowDeprecationTestMixin):
def setUp(self):
self.value = Decimal("11.111")
self.widget = widgets.DecimalWidget()
def test_clean(self):
self.assertEqual(self.widget.clean("11.111"), self.value)
self.assertEqual(self.widget.clean(11.111), self.value)
@over... | DecimalWidgetTest |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/hoverlabel/_font.py | {
"start": 233,
"end": 17168
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.hoverlabel"
_path_str = "scattersmith.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
... | Font |
python | pandas-dev__pandas | pandas/io/excel/_odswriter.py | {
"start": 595,
"end": 11519
} | class ____(ExcelWriter):
_engine = "odf"
_supported_extensions = (".ods",)
def __init__( # pyright: ignore[reportInconsistentConstructor]
self,
path: FilePath | WriteExcelBuffer | ExcelWriter,
engine: str | None = None,
date_format: str | None = None,
datetime_forma... | ODSWriter |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/base.py | {
"start": 1090,
"end": 15804
} | class ____(
RunnableSerializable[dict, PromptValue], ABC, Generic[FormatOutputType]
):
"""Base class for all prompt templates, returning a prompt."""
input_variables: list[str]
"""A list of the names of the variables whose values are required as inputs to the
prompt.
"""
optional_variables:... | BasePromptTemplate |
python | huggingface__transformers | src/transformers/models/idefics/modeling_idefics.py | {
"start": 2114,
"end": 3782
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,... | IdeficsBaseModelOutputWithPast |
python | tensorflow__tensorflow | tensorflow/python/framework/python_api_dispatcher_test.py | {
"start": 10421,
"end": 13612
} | class ____(test_util.TensorFlowTestCase):
def check_signatures(self, checker, canon_expected_pairs):
for (canon_args, expected) in canon_expected_pairs:
with self.subTest(f'{canon_args} -> {expected}'):
self.assertEqual(checker.CheckCanonicalizedArgs(canon_args), expected)
def testSimpleSignatur... | PythonSignatureCheckerTest |
python | django__django | tests/aggregation_regress/tests.py | {
"start": 71422,
"end": 71882
} | class ____(TestCase):
def test_ticket_24748(self):
t1 = SelfRefFK.objects.create(name="t1")
SelfRefFK.objects.create(name="t2", parent=t1)
SelfRefFK.objects.create(name="t3", parent=t1)
self.assertQuerySetEqual(
SelfRefFK.objects.annotate(num_children=Count("children")).o... | SelfReferentialFKTests |
python | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 8819,
"end": 9164
} | class ____(TypedDict, total=False):
diff: Required[str]
"""Unified diff content to apply when creating the file."""
path: Required[str]
"""Path of the file to create relative to the workspace root."""
type: Required[Literal["create_file"]]
"""The operation type. Always `create_file`."""
| ApplyPatchCallOperationCreateFile |
python | doocs__leetcode | solution/3500-3599/3516.Find Closest Person/Solution.py | {
"start": 0,
"end": 172
} | class ____:
def findClosest(self, x: int, y: int, z: int) -> int:
a = abs(x - z)
b = abs(y - z)
return 0 if a == b else (1 if a < b else 2)
| Solution |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 78134,
"end": 79815
} | class ____(Operation):
def __init__(self, k=0, *, name=None):
super().__init__(name=name)
self.k = k
def call(self, x):
return backend.numpy.diagflat(x, k=self.k)
def compute_output_spec(self, x):
x_shape = x.shape
if len(x_shape) == 0:
flat_size = 1
... | Diagflat |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_abc_methods.py | {
"start": 120,
"end": 282
} | class ____:
"""Abstract Base Class """
__metaclass__ = abc.ABCMeta
@property
@abc.abstractmethod
def prop(self):
""" Abstract """
| Parent |
python | doocs__leetcode | solution/3200-3299/3292.Minimum Number of Valid Strings to Form Target II/Solution.py | {
"start": 0,
"end": 486
} | class ____:
__slots__ = ["mod", "h", "p"]
def __init__(self, s: List[str], base: int, mod: int):
self.mod = mod
self.h = [0] * (len(s) + 1)
self.p = [1] * (len(s) + 1)
for i in range(1, len(s) + 1):
self.h[i] = (self.h[i - 1] * base + ord(s[i - 1])) % mod
... | Hashing |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 9624,
"end": 9993
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=101, name="SERVICEHOOK_EDIT", api_name="servicehook.edit")
def render(self, audit_log_entry: AuditLogEntry) -> str:
full_url = audit_log_entry.data.get("url")
return f'edited the service hook for "{truncate... | ServiceHookEditAuditLogEvent |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_slug.py | {
"start": 1807,
"end": 4371
} | class ____(ColumnMapExpectation):
"""Expect value to be valid slug."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_slug": [
"valid_pages",
... | ExpectColumnValuesToBeSlug |
python | django__django | tests/file_storage/tests.py | {
"start": 42868,
"end": 43670
} | class ____(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir)
self.thread = threading.Thread(target=self.save_file, args=["conflict"])
def save_file(self, nam... | FileSaveRaceConditionTest |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 71185,
"end": 145119
} | class ____(mixins.ConfigMethodMixin):
"""Mixin for top-level chart objects such as Chart, LayeredChart, etc."""
_class_is_valid_at_instantiation: bool = False
data: Any
def to_dict( # noqa: C901
self,
validate: bool = True,
*,
format: Literal["vega-lite", "vega"] = "ve... | TopLevelMixin |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 12587,
"end": 14176
} | class ____(greentest.TestCase):
def test_weakref(self):
# Event objects should allow weakrefs
e = Event()
r = weakref.ref(e)
self.assertIs(e, r())
del e
del r
def test_wait_while_notifying(self):
# If someone calls wait() on an Event that is
# re... | TestEventBasics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.