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 | plotly__plotly.py | plotly/graph_objs/pie/_textfont.py | {
"start": 233,
"end": 17087
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie"
_path_str = "pie.textfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
... | Textfont |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 46586,
"end": 47787
} | class ____(Response):
"""
Response of models.delete_metadata endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
"""
_service = "models"
_action = "delete_metadata"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
... | DeleteMetadataResponse |
python | uqfoundation__dill | dill/_objects.py | {
"start": 1953,
"end": 2028
} | class ____:
def __call__(self):
pass
_instance2 = _class2()
| _class2 |
python | aimacode__aima-python | agents4e.py | {
"start": 28515,
"end": 36976
} | class ____(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super().__init__(width, height)
self.init_world(agent_program)
... | WumpusEnvironment |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 2097,
"end": 2318
} | class ____:
x: int = attr.ib(converter=attr.converters.to_bool)
ConvCToBool(1)
ConvCToBool(True)
ConvCToBool("on")
ConvCToBool("yes")
ConvCToBool(0)
ConvCToBool(False)
ConvCToBool("n")
# Validators
@attr.s
| ConvCToBool |
python | sympy__sympy | sympy/vector/vector.py | {
"start": 744,
"end": 12351
} | class ____(BasisDependent):
"""
Super class for all Vector classes.
Ideally, neither this class nor any of its subclasses should be
instantiated by the user.
"""
is_scalar = False
is_Vector = True
_op_priority = 12.0
_expr_type: type[Vector]
_mul_func: type[Vector]
_add_fun... | Vector |
python | networkx__networkx | networkx/algorithms/tests/test_summarization.py | {
"start": 9006,
"end": 11804
} | class ____(AbstractSNAP):
relationship_attributes = ()
def test_summary_graph(self):
original_graph = self.build_original_graph()
summary_graph = self.build_summary_graph()
relationship_attributes = ("type",)
generated_summary_graph = nx.snap_aggregation(
original_g... | TestSNAPNoEdgeTypes |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/binary_implicit_string.py | {
"start": 5402,
"end": 5510
} | class ____:
f.write ("Pathway name" + "\t" "Database Identifier" + "\t" "Source database" + "\n")
| EC2REPATH |
python | openai__openai-python | src/openai/types/conversations/item_list_params.py | {
"start": 292,
"end": 1896
} | class ____(TypedDict, total=False):
after: str
"""An item ID to list items after, used in pagination."""
include: List[ResponseIncludable]
"""Specify additional output data to include in the model response.
Currently supported values are:
- `web_search_call.action.sources`: Include the source... | ItemListParams |
python | kamyu104__LeetCode-Solutions | Python/largest-component-size-by-common-factor.py | {
"start": 143,
"end": 700
} | class ____(object):
def __init__(self, n):
self.set = range(n)
self.size = [1]*n
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(... | UnionFind |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-chroma/unit_tests/test_indexer.py | {
"start": 323,
"end": 7130
} | class ____(unittest.TestCase):
def setUp(self):
self.mock_config = ChromaIndexingConfigModel(
**{
"collection_name": "dummy-collection",
"auth_method": {
"mode": "persistent_client",
"path": "/local/path",
},... | TestChromaIndexer |
python | zarr-developers__zarr-python | src/zarr/core/indexing.py | {
"start": 12999,
"end": 18046
} | class ____:
dim_len: int
dim_chunk_len: int
nitems: int
nchunks: int
start: int
stop: int
step: int
def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int) -> None:
# normalize
start, stop, step = dim_sel.indices(dim_len)
if step < 1:
ra... | SliceDimIndexer |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 94088,
"end": 94295
} | class ____(spack.error.SpackError):
"""Raised when a buildcache cannot be read for any reason"""
FetchIndexResult = collections.namedtuple("FetchIndexResult", "etag hash data fresh")
| BuildcacheIndexError |
python | getsentry__sentry | src/sentry/web/frontend/project_event.py | {
"start": 226,
"end": 934
} | class ____(ProjectView):
required_scope = "event:read"
def handle(
self, request: HttpRequest, organization, project, client_event_id
) -> HttpResponseRedirect:
"""
Given a client event id and project, redirects to the event page
"""
event = eventstore.backend.get_ev... | ProjectEventRedirect |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/descriptors.py | {
"start": 23141,
"end": 23523
} | class ____(DifferentiableAOTOutput):
idx: int
def expr(self) -> str:
return f"__aliased_arg_with_metadata_mutation{self.idx}"
# NB: this is marked differentiable as it /would/ be differentiable if we
# support double backwards, but we never generate this today because we
# don't support double backwa... | MetadataMutationAOTOutput |
python | facebook__pyre-check | client/commands/tests/libcst_util_test.py | {
"start": 769,
"end": 5984
} | class ____(testslide.TestCase):
def setUp(self) -> None:
self.maxDiff = None
def test_success_case(self) -> None:
"""
Tests success cases for:
1. TODO:import statement
2. function name
3. imported Types
4. global scoped variables
5. out of order v... | LibcstUtilTest |
python | pytorch__pytorch | test/export/test_torchbind.py | {
"start": 47841,
"end": 65659
} | class ____(TestCase):
def setUp(self):
init_torchbind_implementations()
@torch._library.register_fake_class("_TorchScriptTesting::_TensorQueue")
class FakeTensorQueue:
def __init__(self, queue):
self.queue = queue
@classmethod
def __obj_u... | TestCompileTorchbind |
python | viewflow__viewflow | viewflow/utils.py | {
"start": 3700,
"end": 4558
} | class ____:
"""
A property that can be overridden.
The viewprop class is a descriptor that works similarly to the built-in
`property` decorator but allows its value to be overridden on instances
of the class it is used in.
"""
def __init__(self, func: Any):
self.__doc__ = getattr(f... | viewprop |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_upath_io_manager.py | {
"start": 15540,
"end": 22210
} | class ____(dg.ConfigurableIOManager, dg.UPathIOManager):
base_dir: str = PydanticField(None, description="Base directory for storing files.") # type: ignore
_base_path: UPath = PrivateAttr()
def setup_for_execution(self, context: InitResourceContext) -> None:
self._base_path = UPath(self.base_dir... | AsyncJSONIOManager |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py | {
"start": 66703,
"end": 80818
} | class ____:
def test_const_covered_neighbors(self):
G1 = nx.DiGraph([(0, 1), (1, 2), (0, 3), (2, 3)])
G2 = nx.DiGraph([("a", "b"), ("b", "c"), ("a", "k"), ("c", "k")])
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1:... | TestDiGraphISOFeasibility |
python | django__django | tests/template_tests/utils.py | {
"start": 3951,
"end": 4021
} | class ____:
def __str__(self):
return "you & me"
| UnsafeClass |
python | matplotlib__matplotlib | lib/matplotlib/quiver.py | {
"start": 35729,
"end": 48555
} | class ____(mcollections.PolyCollection):
"""
Specialized PolyCollection for barbs.
The only API method is :meth:`set_UVC`, which can be used to
change the size, orientation, and color of the arrows. Locations
are changed using the :meth:`set_offsets` collection method.
Possibly this method wil... | Barbs |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/mujoco_rendering.py | {
"start": 10714,
"end": 24069
} | class ____(BaseRender):
"""Class for window rendering in all MuJoCo environments."""
def __init__(
self,
model: "mujoco.MjModel",
data: "mujoco.MjData",
width: int | None = None,
height: int | None = None,
max_geom: int = 1000,
visual_options: dict[int, b... | WindowViewer |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-code-hierarchy/llama_index/packs/code_hierarchy/code_hierarchy.py | {
"start": 1295,
"end": 5415
} | class ____(BaseModel):
"""
Options for capturing the signature of a node.
"""
start_signature_types: Optional[List[_SignatureCaptureType]] = Field(
None,
description=(
"A list of node types any of which indicate the beginning of the signature."
"If this is none o... | _SignatureCaptureOptions |
python | streamlit__streamlit | lib/tests/streamlit/elements/arrow_dataframe_test.py | {
"start": 1624,
"end": 20207
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall arrow protos."""
def test_default_params(self):
"""Test that it can be called with a dataframe."""
df = pd.DataFrame({"a": [1, 2, 3]})
st.dataframe(df)
el = self.get_delta_from_queue().new_element
proto = e... | ArrowDataFrameProtoTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataproc.py | {
"start": 3040,
"end": 4449
} | class ____(BaseOperatorLink):
"""
Helper class for constructing Dataproc resource link.
.. warning::
This link is pending to deprecate.
"""
name = "Dataproc resource"
key = "conf"
@staticmethod
def persist(
context: Context,
url: str,
resource: str,
... | DataprocLink |
python | sympy__sympy | sympy/physics/quantum/sho1d.py | {
"start": 16730,
"end": 18957
} | class ____(SHOState, Ket):
"""1D eigenket.
Inherits from SHOState and Ket.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket
This is usually its quantum numbers or its symbol.
Examples
========
Ket's know about their a... | SHOKet |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 20455,
"end": 22502
} | class ____(Div):
"""
Base class used for `TabHolder` and `Accordion`, groups containers.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
css_class : str, optional
CSS classes to be applied to the ``<div>``. By def... | ContainerHolder |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_early_stopping.py | {
"start": 20012,
"end": 20348
} | class ____(BoringModel):
def __init__(self):
super().__init__()
self.epoch_losses = [1.0, 0.5, float("nan")]
def on_validation_epoch_end(self):
loss = self.epoch_losses[self.current_epoch] if self.current_epoch < len(self.epoch_losses) else float("nan")
self.log("val_loss", loss... | ModelWithNaNLoss |
python | walkccc__LeetCode | solutions/2896. Apply Operations to Make Two Strings Equal/2896-2.py | {
"start": 0,
"end": 649
} | class ____:
def minOperations(self, s1: str, s2: str, x: int) -> int:
diffIndices = [i for i, (a, b) in enumerate(zip(s1, s2))
if a != b]
if not diffIndices:
return 0
# It's impossible to make two strings equal if there are odd number of
# differences.
if len(diffIndices) ... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 9599,
"end": 10830
} | class ____(TestCase):
# see #3793
def test_int(self):
for st, ut, s in [
(np.int8, np.uint8, 8),
(np.int16, np.uint16, 16),
(np.int32, np.uint32, 32),
(np.int64, np.uint64, 64),
]:
for i in range(1, s):
assert_equal(
... | TestHash |
python | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 4425,
"end": 4589
} | class ____(BaseLayout):
"""A simple text paragraph.
attributes :
* BaseLayout attributes
A paragraph must not contains a section !
"""
| Paragraph |
python | getsentry__sentry | src/sentry/explore/models.py | {
"start": 2386,
"end": 4970
} | class ____(DefaultFieldsModel):
"""
A saved Explore query
"""
__relocation_scope__ = RelocationScope.Organization
projects = models.ManyToManyField("sentry.Project", through=ExploreSavedQueryProject)
organization = FlexibleForeignKey("sentry.Organization")
created_by_id = HybridCloudForeig... | ExploreSavedQuery |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-click/tests/test_formatter.py | {
"start": 19289,
"end": 20865
} | class ____(unittest.TestCase):
"""Validate filtering of commands."""
maxDiff = None
@staticmethod
def _get_ctx():
@click.group()
def cli():
"""A sample command group."""
@cli.command()
def hello():
"""A sample command."""
@cli.command()... | CommandFilterTestCase |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/tracing_compilation.py | {
"start": 2091,
"end": 2274
} | class ____(enum.Enum):
"""Enumerate scopes under which functions might be traced."""
NO_SCOPE = 1
VARIABLE_CREATION = 2
NO_VARIABLE_CREATION = 3
@dataclasses.dataclass
| ScopeType |
python | ansible__ansible | test/units/module_utils/datatag/test_datatag.py | {
"start": 11659,
"end": 30535
} | class ____(AutoParamSupport):
later = t.cast(t.Self, Later(locals()))
tag_instances_with_reprs: t.Annotated[t.List[t.Tuple[AnsibleDatatagBase, str]], ParamDesc(["value", "expected_repr"])] = [
(Deprecated(msg="hi mom, I am deprecated", date='2023-01-02', version="42.42"),
"Deprecated(msg='hi m... | TestDatatagTarget |
python | google__pytype | pytype/tests/test_six_overlay1.py | {
"start": 81,
"end": 2005
} | class ____(test_base.BaseTest):
"""Tests for six and six_overlay."""
def test_six_moves_import(self):
self.Check("""
import six
def use_range():
for x in six.moves.range(1, 10):
x
""")
def test_add_metaclass(self):
"""Like the test in test_abc but without a fake six.pyi... | SixTests |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 38070,
"end": 39203
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
latest_repair_id: Optional[int] = Field(
default=None,
description=(
"The ID of the latest repair. This parameter is not required when repai... | RepairRunInput |
python | PyCQA__pycodestyle | pycodestyle.py | {
"start": 80804,
"end": 83883
} | class ____:
"""Collect the results of the checks."""
print_filename = False
def __init__(self, options):
self._benchmark_keys = options.benchmark_keys
self._ignore_code = options.ignore_code
# Results
self.elapsed = 0
self.total_errors = 0
self.counters = di... | BaseReport |
python | getsentry__sentry | src/sentry/plugins/bases/data_forwarding.py | {
"start": 343,
"end": 2314
} | class ____(Plugin):
def has_project_conf(self) -> bool:
return True
def get_rate_limit(self):
"""
Returns a tuple of (Number of Requests, Window in Seconds)
"""
return (50, 1)
def forward_event(self, event: Event, payload: MutableMapping[str, Any]) -> bool:
... | DataForwardingPlugin |
python | facebookresearch__faiss | contrib/torch/clustering.py | {
"start": 469,
"end": 1438
} | class ____:
"""Wrapper for a tensor that offers a function to assign the vectors
to centroids. All other implementations offer the same interface"""
def __init__(self, x):
self.x = x
def count(self):
return self.x.shape[0]
def dim(self):
return self.x.shape[1]
def get... | DatasetAssign |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 59763,
"end": 67038
} | class ____(ConstNode):
# unsigned "" or "U"
# longness "" or "L" or "LL"
# is_c_literal True/False/None creator considers this a C integer literal
unsigned = ""
longness = ""
is_c_literal = None # unknown
# hex_value and base_10_value are designed only to simplify
# writi... | IntNode |
python | kamyu104__LeetCode-Solutions | Python/max-sum-of-a-pair-with-equal-sum-of-digits.py | {
"start": 58,
"end": 650
} | class ____(object):
def maximumSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def sum_digits(x):
result = 0
while x:
result += x%10
x //= 10
return result
lookup = {}
result = -1
... | Solution |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 172422,
"end": 173115
} | class ____(WrapperStore):
"""
Store that explicitly does not support consolidated metadata.
Useful as a proxy for stores like Icechunk, see https://github.com/zarr-developers/zarr-python/pull/3119.
"""
supports_consolidated_metadata = False
def __init__(
self,
store,
*... | NoConsolidatedMetadataSupportStore |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 58985,
"end": 60423
} | class ____(unittest.TestCase):
@pytest.mark.skipif(
sys.version_info < (3, 0), reason="typeguard not supported for python 2"
)
def test_retry_type_annotations(self):
"""The decorator should maintain types of decorated functions."""
# Just in case this is run with unit-test, return ea... | TestRetryTyping |
python | tornadoweb__tornado | tornado/test/netutil_test.py | {
"start": 6177,
"end": 7038
} | class ____(unittest.TestCase):
def test_same_port_allocation(self):
sockets = bind_sockets(0, "localhost")
try:
port = sockets[0].getsockname()[1]
self.assertTrue(all(s.getsockname()[1] == port for s in sockets[1:]))
finally:
for sock in sockets:
... | TestPortAllocation |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/base.py | {
"start": 5025,
"end": 5689
} | class ____(
LoadableBy[AssetKey],
):
"""Internal representation of an asset record, as stored in a :py:class:`~dagster._core.storage.event_log.EventLogStorage`.
Users should not invoke this class directly.
"""
storage_id: int
asset_entry: AssetEntry
@classmethod
def _blocking_batch_lo... | AssetRecord |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_length/invalid_length_returned.py | {
"start": 1022,
"end": 1153
} | class ____:
""" __len__ returns nothing """
def __len__(self): # [invalid-length-returned]
print(3.0)
| NonRegression |
python | pallets__jinja | src/jinja2/environment.py | {
"start": 57767,
"end": 60847
} | class ____:
"""A template stream works pretty much like an ordinary python generator
but it can buffer multiple items to reduce the number of total iterations.
Per default the output is unbuffered which means that for every unbuffered
instruction in the template one string is yielded.
If buffering ... | TemplateStream |
python | pypa__hatch | tests/utils/test_platform.py | {
"start": 187,
"end": 1471
} | class ____:
def test_tag(self):
assert Platform().windows is True
def test_default_shell(self):
assert Platform().default_shell == os.environ.get("COMSPEC", "cmd")
def test_format_for_subprocess_list(self):
assert Platform().format_for_subprocess(["foo", "bar"], shell=False) == ["f... | TestWindows |
python | realpython__materials | fastapi-python-web-apis/main.py | {
"start": 1233,
"end": 4144
} | class ____(BaseModel):
message: str
deleted_item: str
remaining_items_count: int
@app.get("/", tags=["Random Playground"])
def home():
return {"message": "Welcome to the Randomizer API"}
@app.get("/random/{max_value}", tags=["Random Playground"])
def get_random_number(max_value: int):
return {"m... | ItemDeleteResponse |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 105956,
"end": 108003
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(
self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False, scale... | OneFormerSinePositionEmbedding |
python | aimacode__aima-python | games4e.py | {
"start": 15470,
"end": 15926
} | class ____(TicTacToe):
"""A TicTacToe-like game in which you can only make a move on the bottom
row, or in a square directly above an occupied square. Traditionally
played on a 7x6 board and requiring 4 in a row."""
def __init__(self, h=7, v=6, k=4):
TicTacToe.__init__(self, h, v, k)
def ... | ConnectFour |
python | ray-project__ray | python/ray/train/base_trainer.py | {
"start": 2353,
"end": 4480
} | class ____(RuntimeError):
"""An error indicating that training has failed."""
_RESTORE_MSG = (
"The Ray Train run failed. Please inspect the previous error messages for a "
"cause. After fixing the issue (assuming that the error is not caused by "
"your own application logic, but rather... | TrainingFailedError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1145333,
"end": 1146139
} | class ____(sgqlc.types.Type, Node):
"""An option for a discussion poll."""
__schema__ = github_schema
__field_names__ = ("option", "poll", "total_vote_count", "viewer_has_voted")
option = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="option")
"""The text for this option."""
pol... | DiscussionPollOption |
python | dask__dask | dask/array/_array_expr/_blockwise.py | {
"start": 10906,
"end": 11597
} | class ____(Blockwise):
_parameters = ["array", "axes"]
func = staticmethod(np.transpose)
align_arrays = False
adjust_chunks = None
concatenate = None
token = "transpose"
@property
def new_axes(self):
return {}
@property
def name(self):
return self._name
@pr... | Transpose |
python | python-pillow__Pillow | src/PIL/SgiImagePlugin.py | {
"start": 5378,
"end": 6389
} | class ____(ImageFile.PyDecoder):
_pulls_fd = True
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
assert self.fd is not None
assert self.im is not None
rawmode, stride, orientation = self.args
pagesize = self.state.xsize * self.state.ysize
... | SGI16Decoder |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/loop_control_flow_illegal_cases_test.py | {
"start": 1560,
"end": 2621
} | class ____(reference_test_base.TestCase,
parameterized.TestCase):
@parameterized.parameters(*itertools.product(
(
[1],
[1, 2],
[1, 2, 3],
),
(
tf_break_in_py_for,
tf_return_in_py_for,
),
))
def test_tf... | LoopControlFlowIllegalCasesTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1025,
"end": 1161
} | class ____(sgqlc.types.Scalar):
"""A (potentially binary) string encoded using base64."""
__schema__ = github_schema
| Base64String |
python | scipy__scipy | scipy/io/tests/test_idl.py | {
"start": 12584,
"end": 15000
} | class ____:
# Test that pointers in arrays are correctly read in
def test_1d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_1d.sav'), verbose=False)
assert_equal(s.array1d.shape, (123, ))
assert_(np.all(s.array1d == np.float32(4.)))
assert_(np.all(vect_id(s.array... | TestPointerArray |
python | Netflix__metaflow | test/core/tests/card_id_append.py | {
"start": 72,
"end": 3847
} | class ____(MetaflowTest):
"""
`current.card['myid']` should be accessible when cards have an `id` argument in decorator
- `current.card.append` should not work when there are no single default editable card.
- if a card has `ALLOW_USER_COMPONENTS=False` then it can still be edited via accessing it with ... | CardsWithIdTest |
python | django__django | django/contrib/auth/hashers.py | {
"start": 22409,
"end": 23750
} | class ____(BasePasswordHasher):
"""
The Salted MD5 password hashing algorithm (not recommended)
"""
algorithm = "md5"
def encode(self, password, salt):
self._check_encode_args(password, salt)
password = force_str(password)
salt = force_str(salt)
hash = hashlib.md5((... | MD5PasswordHasher |
python | keon__algorithms | tests/test_maths.py | {
"start": 6352,
"end": 6894
} | class ____(unittest.TestCase):
"""[summary]
Test for the file modular_Exponential.py
Arguments:
unittest {[type]} -- [description]
"""
def test_modular_exponential(self):
self.assertEqual(1, modular_exponential(5, 117, 19))
self.assertEqual(pow(1243, 65321, 10 ** 9 + 7),
... | TestModularExponential |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol6.py | {
"start": 373,
"end": 735
} | class ____(Protocol):
def __call__(self, path: str) -> str: ...
def func1_1(path: str = "") -> str: ...
def func1_2(path: str) -> str: ...
val1_1: Callback1 = func1_1
# This should generate an error.
val1_2: Callback1 = func1_2
val2_1: Callback2 = func1_1
val2_2: Callback2 = func1_2
# Callback with keywo... | Callback2 |
python | pypa__pip | src/pip/_vendor/rich/progress.py | {
"start": 23682,
"end": 24110
} | class ____(ProgressColumn):
"""Renders time elapsed."""
def render(self, task: "Task") -> Text:
"""Show time elapsed."""
elapsed = task.finished_time if task.finished else task.elapsed
if elapsed is None:
return Text("-:--:--", style="progress.elapsed")
delta = timed... | TimeElapsedColumn |
python | bokeh__bokeh | src/bokeh/plotting/contour.py | {
"start": 10495,
"end": 10915
} | class ____:
''' Coordinates for filled contour polygons between a lower and upper level.
The first list contains a list for each polygon. The second list contains
a separate NumPy array for each boundary of that polygon; the first array
is always the outer boundary, subsequent arrays are holes.
'''... | SingleFillCoords |
python | redis__redis-py | benchmarks/base.py | {
"start": 75,
"end": 1355
} | class ____:
ARGUMENTS = ()
def __init__(self):
self._client = None
def get_client(self, **kwargs):
# eventually make this more robust and take optional args from
# argparse
if self._client is None or kwargs:
defaults = {"db": 9}
defaults.update(kwarg... | Benchmark |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/shape_ops_test.py | {
"start": 17002,
"end": 30170
} | class ____(test.TestCase, parameterized.TestCase):
def testScalar(self):
for use_gpu in False, True:
with self.cached_session(use_gpu=use_gpu):
a = constant_op.constant(7, shape=[], dtype=dtypes.float32)
tiled = array_ops.tile(a, [])
result = self.evaluate(tiled)
self.assertEq... | TileTest |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 17606,
"end": 18488
} | class ____(Representation):
__slots__ = 'name', 'email'
def __init__(self, name: str, email: str):
self.name = name
self.email = email
def __eq__(self, other: Any) -> bool:
return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
@classmetho... | NameEmail |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 5677,
"end": 6002
} | class ____(generics.GenericAPIView):
serializer_class = ExampleSerializerModel
def get(self, *args, **kwargs):
from datetime import datetime
now = datetime.now()
serializer = self.get_serializer(data=now.date(), datetime=now)
return Response(serializer.data)
| ExampleGenericAPIViewModel |
python | jazzband__django-oauth-toolkit | oauth2_provider/apps.py | {
"start": 36,
"end": 244
} | class ____(AppConfig):
name = "oauth2_provider"
verbose_name = "Django OAuth Toolkit"
def ready(self):
# Import checks to ensure they run.
from . import checks # noqa: F401
| DOTConfig |
python | Textualize__textual | src/textual/app.py | {
"start": 7021,
"end": 7298
} | class ____(Exception):
"""Raised if suspending the application is not supported.
This exception is raised if [`App.suspend`][textual.app.App.suspend] is called while
the application is running in an environment where this isn't supported.
"""
| SuspendNotSupported |
python | getsentry__sentry | src/sentry/sentry_apps/metrics.py | {
"start": 248,
"end": 626
} | class ____(StrEnum):
"""Actions that Sentry Apps can do"""
# Webhook actions
PREPARE_WEBHOOK = "prepare_webhook"
SEND_WEBHOOK = "send_webhook"
# External Requests
EXTERNAL_REQUEST = "external_request"
# Authorizations
AUTHORIZATIONS = "authorizations"
# Managing Sentry Apps
M... | SentryAppInteractionType |
python | numba__numba | numba/core/types/functions.py | {
"start": 13782,
"end": 18908
} | class ____(Callable, Opaque):
"""
A function with an implicit first argument (denoted as *this* below).
"""
def __init__(self, template, this):
# Create a derived template with an attribute *this*
newcls = type(template.__name__ + '.' + str(this), (template,),
dict... | BoundFunction |
python | tiangolo__fastapi | docs_src/query_param_models/tutorial002_pv1_py310.py | {
"start": 120,
"end": 466
} | class ____(BaseModel):
class Config:
extra = "forbid"
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: list[str] = []
@app.get("/items/")
async def read_items(filter_query: FilterParams = Query()):
re... | FilterParams |
python | huggingface__transformers | src/transformers/models/dinov2/modeling_dinov2.py | {
"start": 7812,
"end": 10203
} | class ____(nn.Module):
def __init__(self, config: Dinov2Config):
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 number ... | Dinov2SelfAttention |
python | django__django | tests/validation/models.py | {
"start": 5539,
"end": 5677
} | class ____(Product):
class Meta:
required_db_features = {
"supports_table_check_constraints",
}
| ChildProduct |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 2382,
"end": 7725
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "age_gender_audience_report_hourly"
report_file = "age_gender_audience_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "age_gender_audience_report_hourly_incremental"
repor... | TestAgeGenderAudienceReportHourlyStream |
python | google__pytype | pytype/tests/test_dataclasses.py | {
"start": 115,
"end": 24893
} | class ____(test_base.BaseTest):
"""Tests for @dataclass."""
def test_basic(self):
ty = self.Infer("""
import dataclasses
@dataclasses.dataclass
class Foo:
x: bool
y: int
z: str
""")
self.assertTypesMatchPytd(
ty,
"""
import dataclasses
... | TestDataclass |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 931452,
"end": 931935
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of ReopenPullRequest"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "pull_request")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the... | ReopenPullRequestPayload |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/interfaces.py | {
"start": 15374,
"end": 15718
} | class ____(TypedDict):
"""Dictionary representing the reflected comment corresponding to
the :attr:`_schema.Table.comment` attribute.
The :class:`.ReflectedTableComment` structure is returned by the
:meth:`.Inspector.get_table_comment` method.
"""
text: Optional[str]
"""text of the commen... | ReflectedTableComment |
python | kamyu104__LeetCode-Solutions | Python/subsequence-of-size-k-with-the-largest-even-sum.py | {
"start": 80,
"end": 1769
} | class ____(object):
def largestEvenSum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
... | Solution |
python | huggingface__transformers | src/transformers/models/mobilenet_v1/modeling_mobilenet_v1.py | {
"start": 2158,
"end": 4421
} | class ____(nn.Module):
def __init__(
self,
config: MobileNetV1Config,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: Optional[int] = 1,
groups: Optional[int] = 1,
bias: bool = False,
use_normalization: Optional[bool] = True,
... | MobileNetV1ConvLayer |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/cwise_ops_test.py | {
"start": 32754,
"end": 37191
} | class ____(test.TestCase):
def _computeTensorAndLiteral(self, x, y, dtype, func):
with test_util.force_cpu():
inx = ops.convert_to_tensor(x, dtype=dtype)
z = func(inx, y) # Should use __add__, __sub__, etc.
return self.evaluate(z)
def _computeLiteralAndTensor(self, x, y, dtype, func):
w... | MathOpsOverloadTest |
python | spyder-ide__spyder | spyder/plugins/completion/plugin.py | {
"start": 1916,
"end": 51415
} | class ____(SpyderPluginV2):
"""
Spyder completion plugin.
This class provides a completion and linting plugin for the editor in
Spyder.
This plugin works by forwarding all the completion/linting requests to a
set of :class:`SpyderCompletionProvider` instances that are discovered
and regist... | CompletionPlugin |
python | huggingface__transformers | src/transformers/models/gemma/modeling_gemma.py | {
"start": 22195,
"end": 22300
} | class ____(GenericForSequenceClassification, GemmaPreTrainedModel):
pass
| GemmaForSequenceClassification |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 5923,
"end": 6760
} | class ____(AbstractInstanceValue):
# This is not really a compiled class, it's just an instance from a
# compiled class.
def __init__(self, inference_state, parent_context, class_value, arguments):
super().__init__(inference_state, parent_context, class_value)
self._arguments = arguments
... | CompiledInstance |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/visitors/query_expression.py | {
"start": 1831,
"end": 2767
} | class ____(QueryExpressionVisitor[QueryExpression]):
"""
Visitor that recursively injects a `ConditionGroup` into all `Timeseries`.
"""
def __init__(self, condition_group: ConditionGroup):
self._condition_group = condition_group
def _visit_formula(self, formula: Formula) -> QueryExpression... | TimeseriesConditionInjectionVisitor |
python | doocs__leetcode | solution/0600-0699/0635.Design Log Storage System/Solution.py | {
"start": 0,
"end": 681
} | class ____:
def __init__(self):
self.logs = []
self.d = {
"Year": 4,
"Month": 7,
"Day": 10,
"Hour": 13,
"Minute": 16,
"Second": 19,
}
def put(self, id: int, timestamp: str) -> None:
self.logs.append((id, tim... | LogSystem |
python | wandb__wandb | wandb/vendor/pygments/lexers/smalltalk.py | {
"start": 474,
"end": 5359
} | class ____(RegexLexer):
"""
For `Smalltalk <http://www.smalltalk.org/>`_ syntax.
Contributed by Stefan Matthias Aust.
Rewritten by Nils Winter.
.. versionadded:: 0.10
"""
name = 'Smalltalk'
filenames = ['*.st']
aliases = ['smalltalk', 'squeak', 'st']
mimetypes = ['text/x-smallta... | SmalltalkLexer |
python | django__django | tests/postgres_tests/models.py | {
"start": 3648,
"end": 3788
} | class ____(PostgreSQLModel):
line = models.ForeignKey("Line", models.CASCADE)
query = models.CharField(max_length=100)
| LineSavedSearch |
python | walkccc__LeetCode | solutions/624. Maximum Distance in Arrays/624-2.py | {
"start": 0,
"end": 539
} | class ____:
def maxDistance(self, arrays: list[list[int]]) -> int:
min1, index_min1 = min((A[0], i) for i, A in enumerate(arrays))
max1, index_max1 = max((A[-1], i) for i, A in enumerate(arrays))
if index_min1 != index_max1:
return max1 - min1
min2, index_min2 = min((A[0], i)
... | Solution |
python | google__pytype | pytype/tests/test_typed_dict.py | {
"start": 11080,
"end": 14286
} | class ____(test_base.BaseTest):
"""Tests for typing.TypedDict functional constructor."""
def test_constructor(self):
self.CheckWithErrors("""
from typing_extensions import TypedDict
A = TypedDict("A", {"x": int, "y": str})
B = TypedDict("B", "b") # wrong-arg-types
C = TypedDict("C") #... | TypedDictFunctionalTest |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 56306,
"end": 56650
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["ScrollResult"] = Field(default=None, descripti... | InlineResponse20015 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py | {
"start": 123593,
"end": 125452
} | class ____(test.TestCase):
def _CompareFwdConv2D(self, tensor_in_sizes, filter_in_sizes, conv_strides,
padding):
"""Verifies that DeepConv2D and Conv2D produce the same values.
Args:
tensor_in_sizes: Input tensor dimensions in
[batch, input_rows, input_cols, input_depth... | DeepConv2DTest |
python | python__mypy | mypy/nodes.py | {
"start": 25034,
"end": 26342
} | class ____(Node):
"""A single argument in a FuncItem."""
__slots__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
__match_args__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
def __init__(
self,
variable: Var,
type_annotation: mypy.... | Argument |
python | kamyu104__LeetCode-Solutions | Python/number-of-operations-to-make-network-connected.py | {
"start": 544,
"end": 981
} | class ____(object):
def makeConnected(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: int
"""
if len(connections) < n-1:
return -1
union_find = UnionFind(n)
for i, j in connections:
union_find.... | Solution |
python | huggingface__transformers | src/transformers/models/glm46v/modular_glm46v.py | {
"start": 5298,
"end": 5490
} | class ____(Glm4vProcessor):
def replace_frame_token_id(self, timestamp_sec):
return f"<|begin_of_image|>{self.image_token}<|end_of_image|>{timestamp_sec:.1f} seconds"
| Glm46VProcessor |
python | getsentry__sentry | src/sentry/seer/autofix/constants.py | {
"start": 1031,
"end": 1160
} | class ____(enum.Enum):
ISSUE_DETAILS = "issue_details"
ALERT = "alert"
POST_PROCESS = "post_process"
| SeerAutomationSource |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/unbatch_test.py | {
"start": 9969,
"end": 11246
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def build_dataset(self,
multiplier=15.0,
tensor_slice_len=2,
batch_size=2,
options=None):
components = (np.arange(tensor_slice_l... | UnbatchCheckpointTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.