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 | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 538784,
"end": 540018
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("contributions", "repository")
contributions = sgqlc.types.Field(
sgqlc.types.non_null(CreatedPullRequestReviewContributionConnection),
graphql_name="contributions... | PullRequestReviewContributionsByRepository |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_randint.py | {
"start": 780,
"end": 3332
} | class ____(unittest.TestCase):
# test that that a space with a randint in it is
# (a) accepted for each algo (random, tpe)
# and
# (b) handled correctly in fmin, finding the solution in the constrained space
#
def setUp(self):
self.space = hp.randint("t", 2, 100)
self.trials = T... | TestSimpleFMin |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigtable.py | {
"start": 31207,
"end": 39085
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook")
def test_create_execute(self, mock_hook):
op = BigtableCreateTableOperator(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
initial_split_keys=INIT... | TestBigtableTableCreate |
python | pyparsing__pyparsing | tests/test_simple_unit.py | {
"start": 6300,
"end": 7036
} | class ____(PyparsingExpressionTestCase):
tests = [
PyparsingTest(
desc="Parsing real numbers - fail, parsed numbers are in pieces",
expr=(pp.Word(pp.nums) + "." + pp.Word(pp.nums))[...],
text="1.2 2.3 3.1416 98.6",
# fmt: off
expected_list=["1", ".... | TestCombine |
python | django__django | tests/utils_tests/test_os_utils.py | {
"start": 846,
"end": 1207
} | class ____(unittest.TestCase):
def test_to_path(self):
for path in ("/tmp/some_file.txt", Path("/tmp/some_file.txt")):
with self.subTest(path):
self.assertEqual(to_path(path), Path("/tmp/some_file.txt"))
def test_to_path_invalid_value(self):
with self.assertRaises(Ty... | ToPathTests |
python | doocs__leetcode | solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.py | {
"start": 0,
"end": 145
} | class ____:
def circularPermutation(self, n: int, start: int) -> List[int]:
return [i ^ (i >> 1) ^ start for i in range(1 << n)]
| Solution |
python | django__django | tests/basic/tests.py | {
"start": 1006,
"end": 8265
} | class ____(TestCase):
def test_object_is_not_written_to_database_until_save_was_called(self):
a = Article(
id=None,
headline="Parrot programs in Python",
pub_date=datetime(2005, 7, 28),
)
self.assertIsNone(a.id)
self.assertEqual(Article.objects.cou... | ModelInstanceCreationTests |
python | doocs__leetcode | solution/0700-0799/0790.Domino and Tromino Tiling/Solution.py | {
"start": 0,
"end": 357
} | class ____:
def numTilings(self, n: int) -> int:
f = [1, 0, 0, 0]
mod = 10**9 + 7
for i in range(1, n + 1):
g = [0] * 4
g[0] = (f[0] + f[1] + f[2] + f[3]) % mod
g[1] = (f[2] + f[3]) % mod
g[2] = (f[1] + f[3]) % mod
g[3] = f[0]
... | Solution |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 21911,
"end": 32454
} | class ____(TestCase):
def setUp(self):
self.username = 'john'
self.email = 'lennon@thebeatles.com'
self.password = 'password'
self.user = User.objects.create_user(
self.username,
self.email,
self.password
)
self.client.login(userna... | PermissionsCompositionTests |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 24330,
"end": 25223
} | class ____(ASTPostfixOp):
def __init__(self, expr: ASTExpression) -> None:
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTPostfixArray):
return NotImplemented
return self.expr == other.expr
def __hash__(self) -> int:
return... | ASTPostfixArray |
python | Netflix__metaflow | metaflow/packaging_sys/__init__.py | {
"start": 978,
"end": 19755
} | class ____:
"""
Base class for all Metaflow code packages (non user code).
A Metaflow code package, at a minimum, contains:
- a special INFO file (containing a bunch of metadata about the Metaflow environment)
- a special CONFIG file (containing user configurations for the flow)
Declare al... | MetaflowCodeContent |
python | huggingface__transformers | tests/models/mpt/test_modeling_mpt.py | {
"start": 12978,
"end": 13651
} | class ____(ConfigTester):
def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs):
super().__init__(parent, config_class, has_text_modality, common_properties, **kwargs)
def test_attn_config_as_dict(self):
config = self.config_class(**self.inputs_... | MptConfigTester |
python | pypa__hatch | tests/cli/fmt/test_fmt.py | {
"start": 1707,
"end": 7142
} | class ____:
def test_fix(self, hatch, helpers, temp_dir, config_file, env_run, mocker, platform, defaults_file_stable):
config_file.model.template.plugins["default"]["tests"] = False
config_file.save()
project_name = "My.App"
with temp_dir.as_cwd():
result = hatch("new"... | TestDefaults |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/bytes.py | {
"start": 620,
"end": 998
} | class ____(TypedDict):
"""
A configuration for a data type that takes a ``length_bytes`` parameter.
Attributes
----------
length_bytes : int
The length in bytes of the data associated with this configuration.
Examples
--------
```python
{
"length_bytes": 12
}
... | FixedLengthBytesConfig |
python | getsentry__sentry | src/sentry/sentry_apps/api/parsers/servicehook.py | {
"start": 112,
"end": 711
} | class ____(serializers.Serializer):
url = serializers.URLField(required=True)
events = serializers.ListField(child=serializers.CharField(max_length=255), required=False)
version = serializers.ChoiceField(choices=((0, "0"),), required=False, default=0)
isActive = serializers.BooleanField(required=False, ... | ServiceHookValidator |
python | redis__redis-py | redis/commands/search/reducers.py | {
"start": 476,
"end": 696
} | class ____(FieldOnlyReducer):
"""
Calculates the sum of all the values in the given fields within the group
"""
NAME = "SUM"
def __init__(self, field: str) -> None:
super().__init__(field)
| sum |
python | numpy__numpy | benchmarks/benchmarks/bench_shape_base.py | {
"start": 2536,
"end": 4310
} | class ____(Benchmark):
"""This benchmark concatenates an array of size ``(5n)^3``"""
# Having copy as a `mode` of the block3D
# allows us to directly compare the benchmark of block
# to that of a direct memory copy into new buffers with
# the ASV framework.
# block and copy will be plotted on th... | Block3D |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 1114,
"end": 41554
} | class ____(mcolorizer.ColorizingArtist):
r"""
Base class for Collections. Must be subclassed to be usable.
A Collection represents a sequence of `.Patch`\es that can be drawn
more efficiently together than individually. For example, when a single
path is being drawn repeatedly at different offsets,... | Collection |
python | pytorch__pytorch | test/inductor/test_benchmark_fusion.py | {
"start": 1035,
"end": 1503
} | class ____(InductorTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._stack = contextlib.ExitStack()
cls._stack.enter_context(
config.patch(
{
"benchmark_kernel": True,
"benchmark_fusion": True,
... | TestCase |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_search_tool_bm25_20251119_param.py | {
"start": 350,
"end": 1060
} | class ____(TypedDict, total=False):
name: Required[Literal["tool_search_tool_bm25"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["tool_search_tool_bm25_20251119", "tool_search_tool_bm25"]]
allowed_callers: List[Lit... | BetaToolSearchToolBm25_20251119Param |
python | Textualize__textual | src/textual/command.py | {
"start": 1706,
"end": 3061
} | class ____:
"""Holds the details of a single command search hit."""
score: float
"""The score of the command hit.
The value should be between 0 (no match) and 1 (complete match).
"""
match_display: VisualType
"""A string or Rich renderable representation of the hit."""
command: Ignor... | Hit |
python | pytorch__pytorch | torch/__init__.py | {
"start": 72089,
"end": 72311
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.bool
| BoolStorage |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_git_sync_webserver.py | {
"start": 914,
"end": 9477
} | class ____:
"""Test git sync webserver."""
def test_should_add_dags_volume_to_the_webserver_if_git_sync_and_persistence_is_enabled(self):
docs = render_chart(
values={
"airflowVersion": "1.10.14",
"dags": {"gitSync": {"enabled": True}, "persistence": {"enable... | TestGitSyncWebserver |
python | PrefectHQ__prefect | src/prefect/_vendor/croniter/croniter.py | {
"start": 4252,
"end": 4592
} | class ____(CroniterBadCronError):
"""Valid cron syntax, but likely to produce inaccurate results"""
# Extending CroniterBadCronError, which may be contridatory, but this allows
# catching both errors with a single exception. From a user perspective
# these will likely be handled the same way.
| CroniterUnsupportedSyntaxError |
python | huggingface__transformers | src/transformers/models/moonshine/modular_moonshine.py | {
"start": 12560,
"end": 17458
} | class ____(GlmAttention):
def __init__(
self,
config: MoonshineConfig,
layer_idx: int,
is_causal: bool,
num_attention_heads: int,
num_key_value_heads: int,
):
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_h... | MoonshineAttention |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/relativity/relativity.py | {
"start": 11211,
"end": 14921
} | class ____(object):
nClocks = 0
def __init__(self, x0=0.0, y0=0.0, m0=1.0, v0=0.0, t0=0.0, color=None, prog=None, size=0.5):
Clock.nClocks += 1
self.pen = pg.mkPen(color)
self.brush = pg.mkBrush(color)
self.y0 = y0
self.x0 = x0
self.v0 = v0
self.m0 = ... | Clock |
python | Farama-Foundation__Gymnasium | gymnasium/envs/registration.py | {
"start": 1735,
"end": 8873
} | class ____:
"""A specification for creating environments with :meth:`gymnasium.make`.
* **id**: The string used to create the environment with :meth:`gymnasium.make`
* **entry_point**: A string for the environment location, ``(import path):(environment name)`` or a function that creates the environment.
... | EnvSpec |
python | pydantic__pydantic | pydantic/v1/types.py | {
"start": 27114,
"end": 28411
} | class ____(SecretField):
min_length: OptionalInt = None
max_length: OptionalInt = None
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
update_not_none(
field_schema,
type='string',
writeOnly=True,
format='password',
... | SecretBytes |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 108901,
"end": 110801
} | class ____(ActivityTestCase):
def setUp(self):
with assume_test_silo_mode(SiloMode.CONTROL):
base_params = {
"user_id": self.user.id,
"scope_identifier": self.user.id,
"scope_type": "user",
"value": "always",
}
... | MSTeamsActivityNotificationTest |
python | PyCQA__pylint | doc/data/messages/t/too-many-ancestors/good.py | {
"start": 294,
"end": 404
} | class ____(Vertebrate):
has_beak = False
has_fur = True
lays_egg = False
venomous = False
| Mammal |
python | django__django | tests/view_tests/tests/test_debug.py | {
"start": 50578,
"end": 55539
} | class ____(SimpleTestCase):
rf = RequestFactory()
def test_request_and_exception(self):
"A simple exception report can be generated"
try:
request = self.rf.get("/test_view/")
request.user = User()
raise ValueError("Can't find my keys")
except ValueErr... | PlainTextReportTests |
python | pytorch__pytorch | torch/serialization.py | {
"start": 25625,
"end": 26161
} | class ____(_opener[IO[bytes]]):
def __exit__(self, *args):
self.file_like.flush()
def _open_file_like(name_or_buffer: FileLike, mode: str) -> _opener[IO[bytes]]:
if _is_path(name_or_buffer):
return _open_file(name_or_buffer, mode)
else:
if "w" in mode:
return _open_buff... | _open_buffer_writer |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 2080,
"end": 2224
} | class ____(Web3Exception):
"""
Raised by a provider to signal that too many requests have been made consecutively.
"""
| TooManyRequests |
python | pypa__pip | src/pip/_vendor/msgpack/exceptions.py | {
"start": 341,
"end": 424
} | class ____(ValueError, UnpackException):
"""Invalid msgpack format"""
| FormatError |
python | getsentry__sentry | src/sentry/relocation/models/relocation.py | {
"start": 8188,
"end": 11130
} | class ____(DefaultFieldsModelExisting):
"""
A `RelocationFile` is an association between a `Relocation` and a `File`.
This model should be created in an atomic transaction with the `Relocation` and `File` it points
to.
"""
__relocation_scope__ = RelocationScope.Excluded
# Several differen... | RelocationFile |
python | pyca__cryptography | tests/hazmat/primitives/test_hkdf_vectors.py | {
"start": 797,
"end": 986
} | class ____:
test_hkdfsha256 = generate_hkdf_test(
load_nist_vectors,
os.path.join("KDF"),
["rfc-5869-HKDF-SHA256.txt"],
hashes.SHA256(),
)
| TestHKDFSHA256 |
python | pytorch__pytorch | torch/distributed/argparse_util.py | {
"start": 297,
"end": 2221
} | class ____(Action):
"""
Get argument values from ``PET_{dest}`` before defaulting to the given ``default`` value.
For flags (e.g. ``--standalone``)
use ``check_env`` instead.
.. note:: when multiple option strings are specified, ``dest`` is
the longest option string (e.g. for ``"-f",... | env |
python | wandb__wandb | wandb/vendor/pygments/lexers/prolog.py | {
"start": 458,
"end": 3126
} | class ____(RegexLexer):
"""
Lexer for Prolog files.
"""
name = 'Prolog'
aliases = ['prolog']
filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl']
mimetypes = ['text/x-prolog']
flags = re.UNICODE | re.MULTILINE
tokens = {
'root': [
(r'^#.*', Comment.Single),
... | PrologLexer |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 212378,
"end": 216003
} | class ____:
def _check_range(self, x, cmin, cmax):
assert_(np.all(x >= cmin))
assert_(np.all(x <= cmax))
def _clip_type(self, type_group, array_max,
clip_min, clip_max, inplace=False,
expected_min=None, expected_max=None):
if expected_min is None:
... | TestClip |
python | getsentry__sentry | tools/mypy_helpers/plugin.py | {
"start": 6404,
"end": 8595
} | class ____(Plugin):
def get_function_signature_hook(
self, fullname: str
) -> Callable[[FunctionSigContext], FunctionLike] | None:
return _FUNCTION_SIGNATURE_HOOKS.get(fullname)
def get_method_signature_hook(
self, fullname: str
) -> Callable[[MethodSigContext], FunctionLike] | ... | SentryMypyPlugin |
python | crytic__slither | slither/core/declarations/custom_error_contract.py | {
"start": 237,
"end": 625
} | class ____(CustomError, ContractLevel):
def is_declared_by(self, contract: "Contract") -> bool:
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
@property
def canonical_name(self) -> str:
... | CustomErrorContract |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingCallable1.py | {
"start": 730,
"end": 1674
} | class ____:
def bar(self) -> None:
pass
def test2(o: ClassA) -> None:
if callable(o):
reveal_type(o, expected_text="<callable subtype of ClassA>")
# This should generate an error
o.foo()
o.bar()
r1 = o(1, 2, 3)
reveal_type(r1, expected_text="Unknown")
... | ClassA |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 51435,
"end": 54325
} | class ____(PForTestCase):
def test_loop_variant_scatter_update_no_shape(self):
if test_util.is_gpu_available():
self.skipTest(
"Flaky in some GPU configurations due to TensorScatterNdUpdate "
"nondeterminism.")
@def_function.function(input_signature=[
tensor_spec.TensorSpec... | TensorTest |
python | apache__airflow | dev/breeze/src/airflow_breeze/prepare_providers/provider_distributions.py | {
"start": 1324,
"end": 1428
} | class ____(Exception):
"""Tag already exist for the package."""
| PrepareReleasePackageTagExistException |
python | scipy__scipy | benchmarks/benchmarks/spatial.py | {
"start": 10038,
"end": 10497
} | class ____(Benchmark):
params = [10, 100, 1000, 5000, 10000]
param_names = ['num_points']
def setup(self, num_points):
self.points = generate_spherical_points(num_points)
def time_spherical_voronoi_calculation(self, num_points):
"""Perform spherical Voronoi calculation, but not the sor... | SphericalVor |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/javaw.py | {
"start": 7518,
"end": 8881
} | class ____(JTask):
color = 'BLUE'
run_str = '${JAVAC} -classpath ${CLASSPATH} -d ${OUTDIR} ${JAVACFLAGS} ${SRC}'
vars = ['CLASSPATH', 'JAVACFLAGS', 'JAVAC', 'OUTDIR']
def uid(self):
lst = [self.__class__.__name__, self.generator.outdir.abspath()]
for x in self.srcdir:
lst.ap... | javac |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 58875,
"end": 59589
} | class ____(ExtensionType):
oid = OCSPExtensionOID.NONCE
def __init__(self, nonce: bytes) -> None:
if not isinstance(nonce, bytes):
raise TypeError("nonce must be bytes")
self._nonce = nonce
def __eq__(self, other: object) -> bool:
if not isinstance(other, OCSPNonce):
... | OCSPNonce |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 4305,
"end": 4749
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter by `FlowRun.work_queue_name`."""
any_: Optional[List[str]] = Field(
default=None,
description="A list of work queue names to include",
examples=[["work_queue_1", "work_queue_2"]],
)
is_null_: Optional[bool] = Field(
... | FlowRunFilterWorkQueueName |
python | django__django | tests/forms_tests/tests/test_formsets.py | {
"start": 1750,
"end": 69584
} | class ____(SimpleTestCase):
def make_choiceformset(
self,
formset_data=None,
formset_class=ChoiceFormSet,
total_forms=None,
initial_forms=0,
max_num_forms=0,
min_num_forms=0,
**kwargs,
):
"""
Make a ChoiceFormset from the given form... | FormsFormsetTestCase |
python | pypa__pip | src/pip/_vendor/msgpack/exceptions.py | {
"start": 424,
"end": 564
} | class ____(ValueError, UnpackException):
"""Too nested"""
# Deprecated. Use ValueError instead
UnpackValueError = ValueError
| StackError |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isan.py | {
"start": 1842,
"end": 4624
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid ISAN (International Standard Audiovisual Number)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
... | ExpectColumnValuesToBeValidIsan |
python | eth-brownie__brownie | brownie/_gui/root.py | {
"start": 3312,
"end": 4799
} | class ____(ttk.Frame):
def __init__(self, root, project):
super().__init__(root)
self.root = root
# geometry
self.columnconfigure([0, 1], minsize=80)
self.columnconfigure(7, weight=1)
self.columnconfigure([8, 9], minsize=200)
self.columnconfigure(10, minsize=... | ToolbarFrame |
python | ray-project__ray | doc/source/ray-core/doc_code/direct_transport_gloo.py | {
"start": 1928,
"end": 2773
} | class ____:
@ray.method(tensor_transport="gloo")
def random_tensor_dict(self):
return {"tensor1": torch.randn(1000, 1000), "tensor2": torch.randn(1000, 1000)}
def sum(self, tensor_dict: dict):
return torch.sum(tensor_dict["tensor1"]) + torch.sum(tensor_dict["tensor2"])
sender, receiver = ... | MyActor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 314784,
"end": 315291
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UnfollowOrganization"""
__schema__ = github_schema
__field_names__ = ("organization_id", "client_mutation_id")
organization_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="organizationId")
"""ID of the organization to unfo... | UnfollowOrganizationInput |
python | tensorflow__tensorflow | tensorflow/python/ops/while_v2.py | {
"start": 38423,
"end": 61813
} | class ____(util.WhileBodyFuncGraph):
"""FuncGraph for the gradient function of the body of a While op.
Contains the logic for capturing the tensors from the body of the forward
While op which is as follows:
1. If the tensor is of resource type (these are not accumulated):
a. Ensure that the tensor is a lo... | _WhileBodyGradFuncGraph |
python | getsentry__sentry | tests/sentry/backup/test_exports.py | {
"start": 3750,
"end": 5390
} | class ____(BackupTransactionTestCase):
@staticmethod
def count(data: Any, model: type[models.base.BaseModel]) -> int:
return len(list(filter(lambda d: d["model"] == str(get_model_name(model)), data)))
@staticmethod
def exists(
data: Any, model: type[models.base.BaseModel], key: str, val... | ExportTestCase |
python | keras-team__keras | keras/src/optimizers/ftrl_test.py | {
"start": 168,
"end": 4402
} | class ____(testing.TestCase):
def test_config(self):
optimizer = Ftrl(
learning_rate=0.05,
learning_rate_power=-0.2,
initial_accumulator_value=0.4,
l1_regularization_strength=0.05,
l2_regularization_strength=0.15,
l2_shrinkage_regulariz... | FtrlTest |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 23421,
"end": 28478
} | class ____(PreTrainedModel):
config: T5Config
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_can_compile_fullgraph = True
_no_split_modules = ["T5Block"]
_keep_in_fp32_modules = ["wo"]
@property
def dummy_inputs(self):
input_ids = torch.tensor(DUMMY_I... | T5PreTrainedModel |
python | takluyver__flit | flit/install.py | {
"start": 2796,
"end": 2933
} | class ____(Exception):
def __str__(self):
return 'To install dependencies for extras, you cannot set deps=none.'
| DependencyError |
python | wandb__wandb | wandb/vendor/pygments/lexers/r.py | {
"start": 2331,
"end": 22534
} | class ____(RegexLexer):
"""
For S, S-plus, and R source code.
.. versionadded:: 0.10
"""
name = 'S'
aliases = ['splus', 's', 'r']
filenames = ['*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron']
mimetypes = ['text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r',
'tex... | SLexer |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/grpc_wrapper.py | {
"start": 5569,
"end": 8102
} | class ____(GrpcDebugWrapperSession):
"""A tfdbg Session wrapper that can be used with TensorBoard Debugger Plugin.
This wrapper is the same as `GrpcDebugWrapperSession`, except that it uses a
predefined `watch_fn` that
1) uses `DebugIdentity` debug ops with the `gated_grpc` attribute set to
`True` ... | TensorBoardDebugWrapperSession |
python | matplotlib__matplotlib | galleries/examples/widgets/menu.py | {
"start": 258,
"end": 400
} | class ____:
fontsize: float = 14
labelcolor: ColorType = 'black'
bgcolor: ColorType = 'yellow'
alpha: float = 1.0
| ItemProperties |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 2497,
"end": 13684
} | class ____:
_obj = None
def __new__(cls):
if NotConstant._obj is None:
NotConstant._obj = super().__new__(cls)
return NotConstant._obj
def __repr__(self):
return "<NOT CONSTANT>"
not_a_constant = NotConstant()
constant_value_not_set = object()
def _type_to_itself(tp)... | NotConstant |
python | plotly__plotly.py | plotly/graph_objs/treemap/_pathbar.py | {
"start": 233,
"end": 5690
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap"
_path_str = "treemap.pathbar"
_valid_props = {"edgeshape", "side", "textfont", "thickness", "visible"}
@property
def edgeshape(self):
"""
Determines which shape is used for edges between `barpath`
labels.
... | Pathbar |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 1588,
"end": 1691
} | class ____(TestModel):
host = ForeignKeyField(Host, backref='services')
name = TextField()
| Service |
python | google__jax | jax/_src/numpy/index_tricks.py | {
"start": 1744,
"end": 3113
} | class ____:
"""Return dense multi-dimensional "meshgrid".
LAX-backend implementation of :obj:`numpy.mgrid`. This is a convenience wrapper for
functionality provided by :func:`jax.numpy.meshgrid` with ``sparse=False``.
See Also:
jnp.ogrid: open/sparse version of jnp.mgrid
Examples:
Pass ``[start:sto... | _Mgrid |
python | ray-project__ray | python/ray/llm/_internal/batch/processor/vllm_engine_proc.py | {
"start": 1424,
"end": 1686
} | class ____(BaseModelExtended):
model_config = ConfigDict(extra="allow")
CPU: Optional[int] = Field(default=1, description="The number of CPUs per bundle.")
GPU: Optional[int] = Field(default=1, description="The number of GPUs per bundle.")
| BundleSchema |
python | huggingface__transformers | src/transformers/models/mlcd/modular_mlcd.py | {
"start": 12510,
"end": 14631
} | class ____(CLIPEncoder):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`MLCDEncoderLayer`].
Args:
config: MLCDVisionConfig
"""
def __init__(self, config: MLCDVisionConfig):
"""Overwrite dummy `MLCDConfig` to `MLCDVision... | MLCDEncoder |
python | huggingface__transformers | src/transformers/models/jetmoe/modular_jetmoe.py | {
"start": 7998,
"end": 11543
} | class ____(nn.Module):
"""
A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: JetMoeConfig):
super().__init__()
self.n... | JetMoeMoA |
python | pytorch__pytorch | torch/_numpy/_dtypes.py | {
"start": 1792,
"end": 1892
} | class ____(unsignedinteger):
name = "uint8"
typecode = "B"
torch_dtype = torch.uint8
| uint8 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 387963,
"end": 391371
} | class ____(sgqlc.types.Interface):
"""Represents a comment."""
__schema__ = github_schema
__field_names__ = (
"author",
"author_association",
"body",
"body_html",
"body_text",
"created_at",
"created_via_email",
"editor",
"id",
... | Comment |
python | django__django | tests/generic_views/views.py | {
"start": 5897,
"end": 6049
} | class ____(generic.edit.ModelFormMixin):
fields = "__all__"
def get_queryset(self):
return Author.objects.all()
| AuthorGetQuerySetFormView |
python | falconry__falcon | tests/asgi/test_hello_asgi.py | {
"start": 4758,
"end": 12178
} | class ____:
def test_env_headers_list_of_tuples(self):
env = testing.create_environ(headers=[('User-Agent', 'Falcon-Test')])
assert env['HTTP_USER_AGENT'] == 'Falcon-Test'
def test_root_route(self, client):
doc = {'message': 'Hello world!'}
resource = testing.SimpleTestResourceA... | TestHelloWorld |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_boolean_trap/FBT.py | {
"start": 3312,
"end": 3435
} | class ____(BaseSettings):
foo: bool = Field(True, exclude=True)
# https://github.com/astral-sh/ruff/issues/14202
| Settings |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 1481,
"end": 1642
} | class ____[T1 = str]:
# This should generate an error because T2 depends on T1, which
# is defined in an outer scope.
class ClassL[T2 = T1]: ...
| ClassK |
python | PrefectHQ__prefect | src/prefect/settings/models/runner.py | {
"start": 1146,
"end": 1991
} | class ____(PrefectBaseSettings):
"""
Settings for controlling runner behavior
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(("runner",))
process_limit: int = Field(
default=5,
description="Maximum number of processes a runner will execute in parallel.",
... | RunnerSettings |
python | spack__spack | lib/spack/spack/vendor/jinja2/ext.py | {
"start": 21539,
"end": 21881
} | class ____(Extension):
def __init__(self, environment: Environment) -> None:
super().__init__(environment)
warnings.warn(
"The 'with' extension is deprecated and will be removed in"
" Jinja 3.1. This is built in now.",
DeprecationWarning,
stacklevel=3,... | WithExtension |
python | doocs__leetcode | solution/1400-1499/1486.XOR Operation in an Array/Solution.py | {
"start": 0,
"end": 135
} | class ____:
def xorOperation(self, n: int, start: int) -> int:
return reduce(xor, ((start + 2 * i) for i in range(n)))
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py | {
"start": 46963,
"end": 47302
} | class ____(OutbrainAmplifyStream, ABC):
state_checkpoint_interval = None
@property
def cursor_field(self) -> str:
return []
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
return {}
# Source
| IncrementalOutbrainAmplifyStream |
python | doocs__leetcode | solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.py | {
"start": 0,
"end": 444
} | class ____:
def minOperations(self, boxes: str) -> List[int]:
n = len(boxes)
ans = [0] * n
cnt = 0
for i in range(1, n):
if boxes[i - 1] == '1':
cnt += 1
ans[i] = ans[i - 1] + cnt
cnt = s = 0
for i in range(n - 2, -1, -1):
... | Solution |
python | django__django | tests/admin_widgets/test_autocomplete_widget.py | {
"start": 769,
"end": 1020
} | class ____(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").remote_field, admin.site
),
required=False,
)
| NotRequiredBandForm |
python | scipy__scipy | scipy/optimize/tests/test_least_squares.py | {
"start": 29812,
"end": 30209
} | class ____(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin):
method = 'trf'
def test_lsmr_regularization(self):
p = BroydenTridiagonal()
for regularize in [True, False]:
res = least_squares(p.fun, p.x0, p.jac, method='trf',
tr_options={'regular... | TestTRF |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 13829,
"end": 15375
} | class ____(TestCase):
def test_duration_field(self):
class DurationFieldModel(models.Model):
"""
A model that defines DurationField.
"""
duration_field = models.DurationField()
class TestSerializer(serializers.ModelSerializer):
class Meta:... | TestDurationFieldMapping |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassSlots1.py | {
"start": 461,
"end": 651
} | class ____:
x: int
__slots__ = ("x",)
def __init__(self):
self.x = 3
# This should generate an error because "y" is not in slots.
self.y = 3
@dataclass
| C |
python | google__pytype | pytype/typegraph/typegraph_serializer.py | {
"start": 1305,
"end": 1410
} | class ____:
where: CFGNodeId
source_sets: list[list[BindingId]]
@dataclasses.dataclass
| SerializedOrigin |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 34097,
"end": 34308
} | class ____:
@staticmethod
def has_annos(a: int, b) -> int:
return 0
@classmethod
def a_class_method(cls):
pass
def an_instance_method(self):
pass
| UpdateSignatureHelper |
python | kamyu104__LeetCode-Solutions | Python/choose-edges-to-maximize-score-in-a-tree.py | {
"start": 54,
"end": 1120
} | class ____(object):
def maxScore(self, edges):
"""
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs():
result = [(0, 0) for _ in xrange(len(adj))]
stk = [(1, 0)]
while stk:
step, u = stk.pop()
if ste... | Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/PColorMeshItem.py | {
"start": 1931,
"end": 22464
} | class ____(GraphicsObject):
"""
**Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>`
"""
sigLevelsChanged = QtCore.Signal(object) # emits tuple with levels (low,high) when color levels are changed.
def __init__(self, *args, **kwargs):
"""
Create a pseudocolor plot with co... | PColorMeshItem |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/script_cache_test.py | {
"start": 937,
"end": 2859
} | class ____(unittest.TestCase):
def test_load_valid_script(self):
"""`get_bytecode` works as expected."""
cache = ScriptCache()
result = cache.get_bytecode(_get_script_path("good_script.py"))
assert result is not None
# Execing the code shouldn't raise an error
exec(re... | ScriptCacheTest |
python | RaRe-Technologies__gensim | gensim/test/test_utils.py | {
"start": 2463,
"end": 3719
} | class ____(unittest.TestCase):
def test_decode_entities(self):
# create a string that fails to decode with unichr on narrow python builds
body = u'It’s the Year of the Horse. YES VIN DIESEL 🙌 💯'
expected = u'It\x92s the Year of the Horse. YES VIN DIESEL \U0001f64c \U0001... | TestUtils |
python | kubernetes-client__python | kubernetes/client/models/v1_preconditions.py | {
"start": 383,
"end": 4314
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Preconditions |
python | pytorch__pytorch | torch/testing/_internal/distributed/distributed_test.py | {
"start": 10732,
"end": 15093
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin1 = nn.Linear(10, 10, bias=False)
self.lin2 = nn.Linear(10, 10, bias=False)
def forward(self, x):
# Second layer is used dependent on input x.
use_second_layer = torch.equal(x, torch.ones(20, 1... | ControlFlowToyModel |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 113354,
"end": 115571
} | class ____(MeanMetricWrapper):
"""Computes the crossentropy metric between the labels and predictions.
This is the crossentropy metric class to be used when there are multiple
label classes (2 or more). Here we assume that labels are given as a `one_hot`
representation. eg., When labels values are [2, 0, 1],
... | CategoricalCrossentropy |
python | python-attrs__attrs | tests/test_funcs.py | {
"start": 16344,
"end": 17524
} | class ____:
"""
Tests for `has`.
"""
def test_positive(self, C):
"""
Returns `True` on decorated classes.
"""
assert has(C)
def test_positive_empty(self):
"""
Returns `True` on decorated classes even if there are no attributes.
"""
@... | TestHas |
python | kamyu104__LeetCode-Solutions | Python/search-in-rotated-sorted-array-ii.py | {
"start": 39,
"end": 721
} | class ____(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
... | Solution |
python | ray-project__ray | doc/source/ray-core/doc_code/anti_pattern_return_ray_put.py | {
"start": 2974,
"end": 4576
} | class ____:
@ray.method(num_returns=1)
def task_with_static_multiple_returns_bad1(self):
return_value_1_ref = ray.put(1)
return_value_2_ref = ray.put(2)
return (return_value_1_ref, return_value_2_ref)
@ray.method(num_returns=2)
def task_with_static_multiple_returns_bad2(self):
... | Actor |
python | google__jax | jax/_src/lax/linalg.py | {
"start": 4253,
"end": 8247
} | class ____(enum.Enum):
"""Enum for eigendecomposition algorithm."""
CUSOLVER = "cusolver"
MAGMA = "magma"
LAPACK = "lapack"
def eig(
x: ArrayLike,
*,
compute_left_eigenvectors: bool = True,
compute_right_eigenvectors: bool = True,
implementation: EigImplementation | None = None,
use_ma... | EigImplementation |
python | huggingface__transformers | src/transformers/models/encodec/modeling_encodec.py | {
"start": 1127,
"end": 1655
} | class ____(ModelOutput):
r"""
audio_codes (`torch.LongTensor` of shape `(nb_frames, batch_size, nb_quantizers, frame_len)`, *optional*):
Discrete code embeddings computed using `model.encode`.
audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*):
Decoded a... | EncodecOutput |
python | plotly__plotly.py | plotly/graph_objs/_figure.py | {
"start": 173,
"end": 1111376
} | class ____(BaseFigure):
def __init__(
self, data=None, layout=None, frames=None, skip_invalid=False, **kwargs
):
"""
Create a new :class:Figure instance
Parameters
----------
data
The 'data' property is a tuple of trace instances
that may ... | Figure |
python | jamielennox__requests-mock | tests/test_mocker.py | {
"start": 11904,
"end": 22269
} | class ____(base.TestCase):
URL = 'http://test.com/path'
TEXT = 'resp'
def assertResponse(self, resp):
self.assertEqual(self.TEXT, resp.text)
@requests_mock.Mocker()
def test_mocker_request(self, m):
method = 'XXX'
mock_obj = m.request(method, self.URL, text=self.TEXT)
... | MockerHttpMethodsTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.