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
walkccc__LeetCode
solutions/3483. Unique 3-Digit Even Numbers/3483.py
{ "start": 0, "end": 233 }
class ____: def totalNumbers(self, digits: list[int]) -> int: nums = set() for a, b, c in itertools.permutations(digits, 3): if a != 0 and c % 2 == 0: nums.add(a * 100 + b * 10 + c) return len(nums)
Solution
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/utilities.py
{ "start": 4973, "end": 6568 }
class ____(BaseModel): """ Utility class to call GCP `executions` API and interact with the returned objects. """ name: str namespace: str metadata: dict spec: dict status: dict log_uri: str def is_running(self) -> bool: """Returns True if Execution is not completed...
Execution
python
agronholm__apscheduler
src/apscheduler/_events.py
{ "start": 1346, "end": 1563 }
class ____(DataStoreEvent): """ Signals that a task was updated in a data store. :ivar task_id: ID of the task that was updated """ task_id: str @attrs.define(kw_only=True, frozen=True)
TaskUpdated
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1166979, "end": 1170359 }
class ____(sgqlc.types.Type, Node): """A user account on an Enterprise Server installation.""" __schema__ = github_schema __field_names__ = ( "created_at", "emails", "enterprise_server_installation", "is_site_admin", "login", "profile_name", "remote_c...
EnterpriseServerUserAccount
python
numba__numba
numba/cuda/tests/cudapy/test_serialize.py
{ "start": 264, "end": 2321 }
class ____(CUDATestCase): def check_call(self, callee): arr = np.array([100]) expected = callee[1, 1](arr) # serialize and rebuild foo1 = pickle.loads(pickle.dumps(callee)) del callee # call rebuild function got1 = foo1[1, 1](arr) np.testing.assert_e...
TestPickle
python
google__flatbuffers
tests/optional_scalars/OptionalByte.py
{ "start": 101, "end": 167 }
class ____(object): None_ = 0 One = 1 Two = 2
OptionalByte
python
encode__django-rest-framework
tests/test_validators.py
{ "start": 6174, "end": 6332 }
class ____(serializers.ModelSerializer): class Meta: model = NullUniquenessTogetherModel fields = '__all__'
NullUniquenessTogetherSerializer
python
kubernetes-client__python
kubernetes/client/models/v1_ephemeral_volume_source.py
{ "start": 383, "end": 3778 }
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...
V1EphemeralVolumeSource
python
google__jax
jax/experimental/jax2tf/examples/mnist_lib.py
{ "start": 3161, "end": 6576 }
class ____: """An MNIST model written using pure JAX. There is an option for the model to skip the classifier layer, for demonstrating reuse of the classifier-less model into a larger model. See README.md. """ name = "mnist_pure_jax" @staticmethod def predict(params: Sequence[tuple[Any, Any]], inputs...
PureJaxMNIST
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/data_version.py
{ "start": 12216, "end": 31984 }
class ____: """Used to resolve data version information. Avoids redundant database calls that would otherwise occur. Intended for use within the scope of a single "request" (e.g. GQL request, RunRequest resolution). """ _instance: "DagsterInstance" _instance_queryer: Optional["CachingInstanceQu...
CachingStaleStatusResolver
python
google__pytype
pytype_extensions/instrumentation_for_testing_test.py
{ "start": 1666, "end": 1860 }
class ____: def __init__(self): self.state = 3 def Mul100(self, i): return self.state * i * 102 def ProductionCodePassNoCtor(obj: NoCtor): return obj.Mul100(2)
FakeNoCtorSealedAs
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 696867, "end": 697369 }
class ____(sgqlc.types.Type, Node, Actor, UniformResourceLocatable): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("created_at", "database_id", "updated_at") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ...
Bot
python
getsentry__sentry
src/sentry/unmerge.py
{ "start": 619, "end": 2867 }
class ____(abc.ABC): """ A type defining how and by which criteria a subset of events can be moved out of a group into a new, different group. """ @staticmethod def parse_arguments(fingerprints: Any = None, replacement: Any = None) -> "UnmergeReplacement": if replacement is not None: ...
UnmergeReplacement
python
Lightning-AI__lightning
src/lightning/pytorch/tuner/lr_finder.py
{ "start": 14301, "end": 18133 }
class ____(Callback): """Special callback used by the learning rate finder. This callback logs the learning rate before each batch and logs the corresponding loss after each batch. Args: num_training: number of iterations done by the learning rate finder early_stop_threshold: threshold for ...
_LRCallback
python
huggingface__transformers
src/transformers/models/lfm2_vl/modular_lfm2_vl.py
{ "start": 3028, "end": 9030 }
class ____(LlavaModel): _checkpoint_conversion_mapping = {} def __init__(self, config: Lfm2VlConfig): super().__init__(config) def get_image_features( self, pixel_values: torch.FloatTensor, spatial_shapes: torch.Tensor, pixel_attention_mask: torch.Tensor, **...
Lfm2VlModel
python
django__django
tests/admin_filters/tests.py
{ "start": 2262, "end": 2409 }
class ____(DecadeListFilterWithTitleAndParameter): def lookups(self, request, model_admin): pass
DecadeListFilterWithNoneReturningLookups
python
pytorch__pytorch
test/fx/test_fx_param_shape_control_flow.py
{ "start": 751, "end": 990 }
class ____(MyModuleBase): def __init__(self, in_channels): super().__init__() self.param = torch.nn.Parameter(torch.randn(in_channels, 3)) def no_relu(self): return self.param.size()[0] < 10
MyModuleParamSize
python
pypa__build
src/build/env.py
{ "start": 4332, "end": 4618 }
class ____(typing.Protocol): # pragma: no cover python_executable: str scripts_dir: str def create(self, path: str) -> None: ... def install_requirements(self, requirements: Collection[str]) -> None: ... @property def display_name(self) -> str: ...
_EnvBackend
python
altair-viz__altair
altair/datasets/_reader.py
{ "start": 12629, "end": 18938 }
class ____(Reader[IntoDataFrameT, IntoFrameT]): def __repr__(self) -> str: return f"{super().__repr__()}\ncsv_cache\n {self.csv_cache!r}" @property def csv_cache(self) -> CsvCache: if not hasattr(self, "_csv_cache"): self._csv_cache = CsvCache() return self._csv_cache...
_NoParquetReader
python
tensorflow__tensorflow
tensorflow/core/function/trace_type/serialization.py
{ "start": 979, "end": 3717 }
class ____(metaclass=abc.ABCMeta): """TraceTypes implementing this additional interface are portable.""" @classmethod @abc.abstractmethod def experimental_type_proto(cls) -> Type[message.Message]: """Returns the unique type of proto associated with this class.""" raise NotImplementedError @classmeth...
Serializable
python
huggingface__transformers
src/transformers/models/deit/image_processing_deit.py
{ "start": 1438, "end": 15081 }
class ____(BaseImageProcessor): r""" Constructs a DeiT image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by `do_resize` in `preprocess`. size ...
DeiTImageProcessor
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 11045, "end": 11897 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = PkgMgrFactCollector collected_facts = { "ansible_distribution": "Fedora", "ansible_distribution_major_version": "28", ...
TestPkgMgrFactsAptFedora
python
dagster-io__dagster
python_modules/dagster/dagster_tests/utils_tests/test_dataloader.py
{ "start": 1025, "end": 3854 }
class ____(DataLoader[str, Thing]): def __init__(self): super().__init__(batch_load_fn=batch_load_fn) # pyright: ignore[reportArgumentType] def test_basic() -> None: async def two_round_trips(loader: ThingLoader, key: str): thing = await loader.load(key) repeat = await loader.load(thi...
ThingLoader
python
keras-team__keras
keras/src/losses/losses.py
{ "start": 13899, "end": 15516 }
class ____(LossFunctionWrapper): """Computes the hinge loss between `y_true` & `y_pred`. Formula: ```python loss = maximum(1 - y_true * y_pred, 0) ``` `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1. Args: red...
Hinge
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_detector_details.py
{ "start": 1670, "end": 3956 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-detector-details" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.environment = self.create_environment( organization_id=self.organization.id, name="production" ) with ...
OrganizationDetectorDetailsBaseTest
python
bokeh__bokeh
src/bokeh/models/ui/panels.py
{ "start": 1568, "end": 3188 }
class ____(Pane): """ A DOM-based UI element that allows for controlling its bounding box. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) position = Required(Instance(Coordinate), help=""" A comput...
Panel
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 104954, "end": 106204 }
class ____(Response): """ Response of events.next_debug_image_sample endpoint. """ _service = "events" _action = "next_debug_image_sample" _version = "2.13" _schema = { "$ref": "#/definitions/debug_image_sample_reposnse", "definitions": { "debug_image_sample_rep...
NextDebugImageSampleResponse
python
keras-team__keras
keras/src/distribution/distribution_lib_test.py
{ "start": 506, "end": 1867 }
class ____(testing.TestCase): def tearDown(self): super().tearDown() os.environ.clear() def test_initialize_with_explicit_param(self, mock_backend_initialize): job_addresses = "10.0.0.1:1234,10.0.0.2:2345" num_processes = 2 current_process_id = 0 distribution_li...
MultiProcessInitializeTest
python
jina-ai__jina
jina/jaml/__init__.py
{ "start": 1752, "end": 17578 }
class ____: """A Jina YAML parser supports loading and dumping and substituting variables. To use it: .. highlight:: python .. code-block:: python from jina.jaml import JAML JAML.load(...) JAML.dump(...) class DummyClass: pass JAML.register(Dum...
JAML
python
mahmoud__glom
glom/mutation.py
{ "start": 8551, "end": 12874 }
class ____: """ In addition to glom's core "deep-get" and ``Assign``'s "deep-set", the ``Delete`` specifier type performs a "deep-del", which can remove items from larger data structures by key, attribute, and index. >>> target = {'dict': {'x': [5, 6, 7]}} >>> glom(target, Delete('dict.x.1'...
Delete
python
scikit-learn__scikit-learn
sklearn/externals/array_api_extra/_lib/_utils/_helpers.py
{ "start": 15480, "end": 18965 }
class ____(Generic[T]): # numpydoc ignore=PR01 """ Helper of :func:`jax_autojit`. Wrap arbitrary inputs and outputs of the jitted function and convert them to/from PyTrees. """ obj: T _registered: ClassVar[bool] = False __slots__: tuple[str, ...] = ("obj",) def __init__(self, obj...
_AutoJITWrapper
python
fsspec__filesystem_spec
fsspec/implementations/cache_metadata.py
{ "start": 433, "end": 8502 }
class ____: """Cache metadata. All reading and writing of cache metadata is performed by this class, accessing the cached files and blocks is not. Metadata is stored in a single file per storage directory in JSON format. For backward compatibility, also reads metadata stored in pickle format w...
CacheMetadata
python
redis__redis-py
tests/test_ssl.py
{ "start": 292, "end": 15688 }
class ____: """Tests for SSL connections This relies on the --redis-ssl-url purely for rebuilding the client and connecting to the appropriate port. """ @pytest.fixture(autouse=True) def _set_ssl_certs(self, request): tls_cert_subdir = request.session.config.REDIS_INFO["tls_cert_subdir...
TestSSL
python
sqlalchemy__sqlalchemy
test/orm/test_cycles.py
{ "start": 16936, "end": 20026 }
class ____(fixtures.MappedTest): """Two mappers with a one-to-many relationship to each other, with a second one-to-many on one of the mappers""" run_define_tables = "each" @classmethod def define_tables(cls, metadata): Table( "t1", metadata, Column( ...
BiDirectionalOneToManyTest2
python
django__django
django/contrib/auth/migrations/0011_update_proxy_permissions.py
{ "start": 2540, "end": 2860 }
class ____(migrations.Migration): dependencies = [ ("auth", "0010_alter_group_name_max_length"), ("contenttypes", "0002_remove_content_type_name"), ] operations = [ migrations.RunPython( update_proxy_model_permissions, revert_proxy_model_permissions ), ]
Migration
python
celery__celery
t/smoke/tests/test_canvas.py
{ "start": 2902, "end": 6660 }
class ____: def test_sanity(self, celery_setup: CeleryTestSetup): upgraded_chord = signature( group( identity.si("header_task1"), identity.si("header_task2"), ) | identity.si("body_task"), queue=celery_setup.worker.worker_queue,...
test_chord
python
numba__numba
numba/cuda/stubs.py
{ "start": 1794, "end": 2097 }
class ____(Dim3): ''' The shape of a block of threads, as declared when instantiating the kernel. This value is the same for all threads in a given kernel launch, even if they belong to different blocks (i.e. each block is "full"). ''' _description_ = '<blockDim.{x,y,z}>'
blockDim
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/multimethod/package.py
{ "start": 229, "end": 4294 }
class ____(MultimethodBase): """This package is designed for use with Spack's multimethod test. It has a bunch of test cases for the @when decorator that the test uses. """ homepage = "http://www.example.com/" url = "http://www.example.com/example-1.0.tar.gz" version("5.0", md5="0123456789...
Multimethod
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_pdf.py
{ "start": 105409, "end": 106801 }
class ____(FigureCanvasBase): # docstring inherited fixed_dpi = 72 filetypes = {'pdf': 'Portable Document Format'} def get_default_filetype(self): return 'pdf' def print_pdf(self, filename, *, bbox_inches_restore=None, metadata=None): dpi = self.figure.dpi ...
FigureCanvasPdf
python
django__django
tests/template_tests/syntax_tests/test_builtins.py
{ "start": 68, "end": 628 }
class ____(SimpleTestCase): @setup({"builtins01": "{{ True }}"}) def test_builtins01(self): output = self.engine.render_to_string("builtins01") self.assertEqual(output, "True") @setup({"builtins02": "{{ False }}"}) def test_builtins02(self): output = self.engine.render_to_string...
BuiltinsTests
python
walkccc__LeetCode
solutions/3395. Subsequences with a Unique Middle Mode I/3395-3.py
{ "start": 937, "end": 2673 }
class ____: def subsequencesWithMiddleMode(self, nums: list[int]) -> int: MOD = 1_000_000_007 ans = 0 p = collections.Counter() # prefix counter s = collections.Counter(nums) # suffix counter def nC2(n: int) -> int: return n * (n - 1) // 2 pss = 0 spp = 0 pp = 0 ss = sum(...
Solution
python
tensorflow__tensorflow
tensorflow/python/util/tf_stack.py
{ "start": 5626, "end": 6115 }
class ____(_tf_stack.GraphDebugInfoBuilder): def AppendGraphDebugInfo(self, fn_name, fn_debug_info): debug_info_str = fn_debug_info.SerializeToString() super().AppendGraphDebugInfo(fn_name, debug_info_str) def Build(self): debug_info_str = super().Build() debug_info = graph_debug_info_pb2.GraphDeb...
GraphDebugInfoBuilder
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_factorize.py
{ "start": 149, "end": 4468 }
class ____: def test_factorize(self): idx1 = DatetimeIndex( ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"] ) exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"]) arr, idx = idx1.fact...
TestDatetimeIndexFactorize
python
getsentry__sentry
src/sentry/sentry_apps/api/parsers/sentry_app.py
{ "start": 2498, "end": 9529 }
class ____(Serializer): name = serializers.CharField(help_text="The name of the custom integration.") author = serializers.CharField( required=False, allow_null=True, help_text="The custom integration's author." ) scopes = ApiScopesField( allow_null=True, help_text="The custom integratio...
SentryAppParser
python
plotly__plotly.py
tests/test_optional/test_figure_factory/test_figure_factory.py
{ "start": 106024, "end": 116321 }
class ____(NumpyTestUtilsMixin, TestCaseNoTemplate): def test_data_must_be_dataframe(self): data = [] pattern = "You must input a pandas DataFrame." self.assertRaisesRegex( PlotlyError, pattern, ff.create_facet_grid, data, "a", "b" ) def test_x_and_y_for_scatter(se...
TestFacetGrid
python
huggingface__transformers
tests/models/siglip/test_modeling_siglip.py
{ "start": 1624, "end": 2989 }
class ____(ModelTesterMixin): def test_sdpa_can_dispatch_composite_models(self): for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) with tempfile.TemporaryDirectory() as tm...
SiglipModelTesterMixin
python
openai__openai-python
src/openai/types/responses/function_shell_tool_param.py
{ "start": 222, "end": 367 }
class ____(TypedDict, total=False): type: Required[Literal["shell"]] """The type of the shell tool. Always `shell`."""
FunctionShellToolParam
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 14927, "end": 17200 }
class ____(AggregateFnV2[SupportsRichComparisonType, SupportsRichComparisonType]): """Defines min aggregation. Example: .. testcode:: import ray from ray.data.aggregate import Min ds = ray.data.range(100) # Schema: {'id': int64} ds = ds.add...
Min
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/compression.py
{ "start": 571, "end": 729 }
class ____: name: str modified_at: datetime mode: int method: CompressionType data: BinaryIO size: int = 0 crc32: int = 0
MemberFile
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 33063, "end": 33348 }
class ____(TestSetSubclassWithSlots): thetype = FrozenSetSubclassWithSlots # Tests taken from test_sets.py ============================================= empty_set = set() #==============================================================================
TestFrozenSetSubclassWithSlots
python
PrefectHQ__prefect
src/integrations/prefect-aws/prefect_aws/settings.py
{ "start": 1367, "end": 1609 }
class ____(PrefectBaseSettings): model_config = build_settings_config(("integrations", "aws")) ecs: EcsSettings = Field( description="Settings for controlling ECS behavior.", default_factory=EcsSettings, )
AwsSettings
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/compiler.py
{ "start": 19579, "end": 20274 }
class ____(IntEnum): """represent preferences for the 'SQL linting' feature. this feature currently includes support for flagging cartesian products in SQL statements. """ NO_LINTING = 0 "Disable all linting." COLLECT_CARTESIAN_PRODUCTS = 1 """Collect data on FROMs and cartesian prod...
Linting
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 34030, "end": 35820 }
class ____( AssertsCompiledSQL, fixtures.DeclarativeMappedTest ): """test #6762""" __dialect__ = "default" run_create_tables = None @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Content(Base): __tablename__ = "content" id = Col...
ColPropWAliasJoinedToBaseTest
python
huggingface__transformers
tests/models/xlnet/test_tokenization_xlnet.py
{ "start": 967, "end": 2707 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "xlnet/xlnet-base-cased" tokenizer_class = XLNetTokenizer integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁false', '.', '▁', '生活的真谛是',...
XLNetTokenizationTest
python
pandas-dev__pandas
asv_bench/benchmarks/groupby.py
{ "start": 4845, "end": 5986 }
class ____: param_names = ["dtype"] params = ["float32", "float64", "datetime", "object"] def setup(self, dtype): N = 10**5 # with datetimes (GH7555) if dtype == "datetime": values = date_range("1/1/2011", periods=N, freq="s") elif dtype == "object": ...
Nth
python
PyCQA__pylint
tests/pyreverse/functional/class_diagrams/relationships/comprehensions.py
{ "start": 135, "end": 242 }
class ____: """A component class.""" def __init__(self, name: str): self.name = name
Component
python
huggingface__transformers
tests/utils/test_core_model_loading.py
{ "start": 1112, "end": 6302 }
class ____(unittest.TestCase): def setUp(self): self.weight_globs_digits = [ "model.layers.*.mlp.gate_up_proj.weight", "model.layers.*.self_attn.q_proj.weight", "embed_tokens.weight", ] self.alt_digits, self.map_digits, _ = build_glob_alternation(self.weig...
TestWeightGlobMatching
python
celery__celery
t/unit/tasks/test_stamping.py
{ "start": 15106, "end": 23880 }
class ____: def setup_method(self): @self.app.task(shared=False) def identity(x): return x self.identity = identity @self.app.task(shared=False) def fail(*args): args = ("Task expected to fail",) + args raise Exception(*args) sel...
CanvasCase
python
google__pytype
pytype/overlays/fiddle_overlay.py
{ "start": 8985, "end": 9789 }
class ____(abstract.Instance, mixin.HasSlots): """Base class for Config and Partial instances.""" def __init__(self, fiddle_type_name, cls, ctx, container=None): super().__init__(cls, ctx, container) self.fiddle_type_name = fiddle_type_name self.underlying = None mixin.HasSlots.init_mixin(self) ...
Buildable
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 14676, "end": 15242 }
class ____(BaseSafeMigrationTest, ColExistsMixin): app = "good_flow_delete_field_pending_with_fk_constraint_app" migrate_from = "0001" migrate_to = "0003" def test(self) -> None: self._run_migration(self.app, "0001_initial") assert self.col_exists("fk_table_id") self._run_migrat...
DeletionFieldGoodDeletePendingWithFKConstraint
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassKwOnly1.py
{ "start": 748, "end": 819 }
class ____(DC3): c: float DC4("", 0.2, b=3) DC4(a="", b=3, c=0.2)
DC4
python
falconry__falcon
tests/test_before_hooks.py
{ "start": 3181, "end": 4132 }
class ____: _some_fish = Fish() # Test non-callable should be skipped by decorator on_patch = {} # type: ignore @falcon.before(validate_param, 'limit') def on_get(self, req, resp, bunnies): self._capture(req, resp, bunnies) @falcon.before(validate_param, 'limit') def on_head(self...
WrappedClassResource
python
tornadoweb__tornado
tornado/websocket.py
{ "start": 3580, "end": 23028 }
class ____(tornado.web.RequestHandler): """Subclass this class to create a basic WebSocket handler. Override `on_message` to handle incoming messages, and use `write_message` to send messages to the client. You can also override `open` and `on_close` to handle opened and closed connections. Cu...
WebSocketHandler
python
pypa__warehouse
tests/unit/macaroons/test_caveats.py
{ "start": 7933, "end": 9739 }
class ____: def test_verify_no_identity(self): caveat = RequestUser(user_id="invalid") result = caveat.verify( pretend.stub(identity=None), pretend.stub(), pretend.stub() ) assert result == Failure("token with user restriction without a user") def test_verify_invali...
TestRequestUserCaveat
python
PyCQA__pylint
doc/data/messages/i/invalid-match-args-definition/bad.py
{ "start": 0, "end": 176 }
class ____: __match_args__ = ["title", "year"] # [invalid-match-args-definition] def __init__(self, title, year): self.title = title self.year = year
Book
python
getsentry__sentry
tests/sentry/tasks/test_clear_expired_resolutions.py
{ "start": 432, "end": 3021 }
class ____(TestCase): def test_task_persistent_name(self) -> None: assert clear_expired_resolutions.name == "sentry.tasks.clear_expired_resolutions" def test_simple(self) -> None: project = self.create_project() old_release = Release.objects.create(organization_id=project.organization_...
ClearExpiredResolutionsTest
python
html5lib__html5lib-python
html5lib/tests/tokenizer.py
{ "start": 6713, "end": 7698 }
class ____(pytest.Collector): def __init__(self, name, parent=None, config=None, session=None, testdata=None): super(TokenizerTestCollector, self).__init__(name, parent, config, session) if 'initialStates' not in testdata: testdata["initialStates"] = ["Data state"] if 'doubleEsca...
TokenizerTestCollector
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 40473, "end": 41699 }
class ____(util.MdCase): """Test custom Arithmatex preview format.""" extension = ['pymdownx.superfences'] extension_configs = { 'pymdownx.superfences': { 'custom_fences': [ { 'name': 'math', 'class': 'arithmatex', ...
TestSuperFencesCustomArithmatexPreview
python
modin-project__modin
asv_bench/benchmarks/io/csv.py
{ "start": 2275, "end": 2721 }
class ____(BaseReadCsv): data_type = "true_false_int" param_names = ["shape"] params = [get_benchmark_shapes("TimeReadCsvTrueFalseValues")] def time_true_false_values(self, test_filenames, shape): execute( IMPL.read_csv( test_filenames[self.shape_id], ...
TimeReadCsvTrueFalseValues
python
getsentry__sentry
tests/sentry/discover/test_dashboard_widget_split.py
{ "start": 914, "end": 24674 }
class ____(BaseMetricsLayerTestCase, TestCase, SnubaTestCase): @property def now(self) -> datetime: return before_now(minutes=10) def setUp(self) -> None: super().setUp() self.org = self.create_organization() with assume_test_silo_mode_of(User): self.user = User....
DashboardWidgetDatasetSplitTestCase
python
milvus-io__pymilvus
tests/test_grpc_handler_mutations.py
{ "start": 19312, "end": 21765 }
class ____: def test_get_info(self) -> None: handler = GrpcHandler(channel=None) # Test with schema provided schema = { "fields": [ {"name": "id", "type": DataType.INT64}, {"name": "vector", "type": DataType.FLOAT_VECTOR} ], ...
TestGrpcHandlerHelperMethods
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 675671, "end": 676059 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("IssueComment", graphql_na...
IssueCommentEdge
python
mlflow__mlflow
mlflow/gateway/providers/gemini.py
{ "start": 1020, "end": 20510 }
class ____(ProviderAdapter): @classmethod def chat_to_model(cls, payload, config): # Documentation: https://ai.google.dev/api/generate-content # Example payload for the chat API. # # { # "contents": [ # { # "role": "user", #...
GeminiAdapter
python
getsentry__sentry
tests/sentry/issues/test_utils.py
{ "start": 3601, "end": 4310 }
class ____: def build_statuschange_data(self, **overrides: Any) -> StatusChangeMessageData: kwargs: StatusChangeMessageData = { "id": uuid.uuid4().hex, "project_id": 1, "fingerprint": ["some-fingerprint"], "new_status": 1, "new_substatus": 1, ...
StatusChangeTestMixin
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 1643, "end": 1794 }
class ____(DagsterError): """Indicates that an invalid value was returned from a source asset observation function."""
DagsterInvalidObservationError
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 21574, "end": 22432 }
class ____(TestCase): def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [ np.int8, np.uint8, np.int16, np.int32, np.float32, np.float64, np.comp...
TestCumsum
python
sympy__sympy
sympy/physics/quantum/cartesian.py
{ "start": 6399, "end": 6750 }
class ____(Bra, PositionState3D): # type: ignore """ 3D cartesian position eigenbra """ @classmethod def dual_class(self): return PositionKet3D #------------------------------------------------------------------------- # Momentum eigenstates #------------------------------------------------------...
PositionBra3D
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassTransform3.py
{ "start": 1239, "end": 1311 }
class ____(Customer1): salary: float = model_field()
Customer1Subclass
python
ray-project__ray
python/ray/serve/tests/unit/test_user_callable_wrapper.py
{ "start": 647, "end": 15847 }
class ____: def __call__(self, suffix: Optional[str] = None, raise_exception: bool = False): if raise_exception: raise RuntimeError("uh-oh!") return "hi" + (suffix if suffix is not None else "") async def call_async( self, suffix: Optional[str] = None, raise_exception: bool...
BasicClass
python
PyCQA__pylint
pylint/pyreverse/diadefslib.py
{ "start": 794, "end": 7345 }
class ____: """Handle diagram generation options.""" def __init__(self, linker: Linker, handler: DiadefsHandler) -> None: """Common Diagram Handler initialization.""" self.config = handler.config self.args = handler.args self.module_names: bool = False self._set_default_...
DiaDefGenerator
python
wandb__wandb
wandb/vendor/pygments/lexers/html.py
{ "start": 15766, "end": 19269 }
class ____(ExtendedRegexLexer): """ For Pug markup. Pug is a variant of Scaml, see: http://scalate.fusesource.org/documentation/scaml-reference.html .. versionadded:: 1.4 """ name = 'Pug' aliases = ['pug', 'jade'] filenames = ['*.pug', '*.jade'] mimetypes = ['text/x-pug', 'text...
PugLexer
python
kamyu104__LeetCode-Solutions
Python/equal-sum-arrays-with-minimum-number-of-operations.py
{ "start": 54, "end": 843 }
class ____(object): def minOperations(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ if len(nums1)*6 < len(nums2) or len(nums1) > len(nums2)*6: return -1 diff = sum(nums2)-sum(nums1) if diff < 0: ...
Solution
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_servicehooks.py
{ "start": 752, "end": 1797 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.login_as(user=self.user) self.path = f"/api/0/projects/{self.project.organization.slug}/{self.project.slug}/hooks/" def test_simple(self) -> None: with self.featur...
CreateProjectServiceHookTest
python
PyCQA__pylint
tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py
{ "start": 536, "end": 681 }
class ____(type): def __getnewargs_ex__(cls): return ((1,), {"2": "2"}) @six.add_metaclass(GetNewArgsExMetaclass)
GetNewArgsExMetaclass
python
coleifer__peewee
tests/fields.py
{ "start": 41529, "end": 41603 }
class ____(TestModel): content = TextField() tags = ListField()
Todo
python
sympy__sympy
sympy/physics/quantum/circuitplot.py
{ "start": 10742, "end": 10984 }
class ____(OneQubitGate): """Mock-up of a z measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mz' gate_name_latex='M_z'
Mz
python
getsentry__sentry
src/sentry/notifications/notification_action/action_validation.py
{ "start": 5184, "end": 5369 }
class ____(TicketingActionValidatorHandler): provider = Action.Type.GITHUB_ENTERPRISE @action_validator_registry.register(Action.Type.PAGERDUTY)
GithubEnterpriseActionValidatorHandler
python
tensorflow__tensorflow
tensorflow/python/ops/script_ops.py
{ "start": 2900, "end": 6706 }
class ____: """A wrapper for a function owned by an EagerPyFunc.""" def __init__(self, func, Tout, is_grad_func): """Constructs an EagerFunc. Args: func: The function to wrap. Tout: A list of datatypes for the output; an empty list if the output is None. is_grad_func: Whether thi...
EagerFunc
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/rerank.py
{ "start": 221, "end": 840 }
class ____(BaseEvent): """ ReRankStartEvent. Args: query (QueryType): Query as a string or query bundle. nodes (List[NodeWithScore]): List of nodes with scores. top_n (int): Number of nodes to return after rerank. model_name (str): Name of the model used for reranking. ...
ReRankStartEvent
python
openai__openai-python
tests/api_resources/fine_tuning/checkpoints/test_permissions.py
{ "start": 531, "end": 7302 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: permission = client.fine_tuning.checkpoints.permissions.create( fine_tuned_model_checkpoint="ft:gpt-4o-mi...
TestPermissions
python
ansible__ansible
lib/ansible/module_utils/_internal/_json/_profiles/_tagless.py
{ "start": 396, "end": 2053 }
class ____(_profiles._JSONSerializationProfile["Encoder", "Decoder"]): @classmethod def post_init(cls) -> None: cls.serialize_map = { # DTFIX5: support serialization of every type that is supported in the Ansible variable type system set: cls.serialize_as_list, tuple:...
_Profile
python
gevent__gevent
src/gevent/libev/watcher.py
{ "start": 7790, "end": 8196 }
class ____(_base.StatMixin, watcher): _watcher_type = 'stat' @property def attr(self): if not self._watcher.attr.st_nlink: return return self._watcher.attr @property def prev(self): if not self._watcher.prev.st_nlink: return return self._watc...
stat
python
joke2k__faker
faker/providers/sbn/sbn.py
{ "start": 371, "end": 1520 }
class ____(SBN): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.check_digit = self._check_digit() def _check_digit(self) -> str: """Calculate the check digit for SBN-9. SBNs use the same check digit calculation as ISBN. See ...
SBN9
python
getsentry__sentry
src/sentry/issues/endpoints/organization_issues_count.py
{ "start": 1214, "end": 4246 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ISSUES enforce_rate_limit = True rate_limits = RateLimitConfig( limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=10, window=1), ...
OrganizationIssuesCountEndpoint
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-timeplus/destination_timeplus/destination.py
{ "start": 456, "end": 7515 }
class ____(Destination): def write( self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage] ) -> Iterable[AirbyteMessage]: """ Reads the input stream of messages, config, and catalog to write data to the destination. ...
DestinationTimeplus
python
google__flatbuffers
python/flatbuffers/number_types.py
{ "start": 2299, "end": 2447 }
class ____(object): bytewidth = 4 min_val = None max_val = None py_type = float name = "float32" packer_type = packer.float32
Float32Flags
python
allegroai__clearml
clearml/backend_api/services/v2_23/queues.py
{ "start": 86273, "end": 87172 }
class ____(Request): """ Peek the next task from a given queue :param queue: ID of the queue :type queue: str """ _service = "queues" _action = "peek_task" _version = "2.23" _schema = { "definitions": {}, "properties": {"queue": {"description": "ID of the queue", "t...
PeekTaskRequest
python
spack__spack
lib/spack/spack/solver/asp.py
{ "start": 53444, "end": 137987 }
class ____: """Class to set up and run a Spack concretization solve.""" gen: "ProblemInstanceBuilder" possible_versions: Dict[str, Dict[GitOrStandardVersion, List[Provenance]]] def __init__(self, tests: spack.concretize.TestsType = False): self.possible_graph = create_graph_analyzer() ...
SpackSolverSetup
python
getsentry__sentry
tests/sentry/workflow_engine/handlers/condition/test_level_handler.py
{ "start": 419, "end": 5648 }
class ____(ConditionTestCase): condition = Condition.LEVEL payload = { "id": LevelCondition.id, "match": MatchType.EQUAL, "level": "20", } def setup_group_event_and_job(self) -> None: self.group_event = self.event.for_group(self.group) self.event_data = WorkflowE...
TestLevelCondition
python
ZoranPandovski__al-go-rithms
others/Blockchain/blockchain.py
{ "start": 40, "end": 361 }
class ____: def __init__ (self, timestamp, data, previousHash = ' '): self.timestamp = timestamp self.data = data self.previousHash = previousHash self.hash = self.calculateHash() def calculateHash(self): return sha256((str(self.timestamp) + str(self.data) + str(self.previousHash)).encode()).hexdigest()
block