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
gevent__gevent
src/gevent/testing/testrunner.py
{ "start": 8497, "end": 9284 }
class ____(object): def __init__(self, runner, travis_fold_msg): self._runner = runner self._travis_fold_msg = travis_fold_msg self._travis_fold_name = str(int(util.perf_counter())) # A zope-style acquisition proxy would be convenient here. run_tests = runner._run_tests ...
TravisFoldingRunner
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 22676, "end": 23141 }
class ____(DifferentiableAOTOutput): """An intermediate base of multiple outputs which alias each other. We only report ONE of the outputs that contributed to this base""" base_of: "AOTOutput" def expr(self) -> str: return f"__intermediate_base({self.base_of.expr()})" # TODO: it's a little ...
IntermediateBaseAOTOutput
python
pypa__pip
tests/unit/test_base_command.py
{ "start": 873, "end": 1613 }
class ____(Command): _name = "fake" def __init__( self, run_func: Callable[[], int] | None = None, error: bool = False ) -> None: if error: def run_func() -> int: raise SystemExit(1) self.run_func = run_func super().__init__(self._name, self._na...
FakeCommand
python
python-openxml__python-docx
tests/opc/test_pkgwriter.py
{ "start": 5041, "end": 7218 }
class ____: def it_can_compose_content_types_element(self, xml_for_fixture): cti, expected_xml = xml_for_fixture types_elm = cti._element assert types_elm.xml == expected_xml # fixtures --------------------------------------------- def _mock_part(self, request: FixtureRequest, name...
Describe_ContentTypesItem
python
sympy__sympy
sympy/geometry/ellipse.py
{ "start": 42460, "end": 50305 }
class ____(Ellipse): r"""A circle in space. Constructed simply from a center and a radius, from three non-collinear points, or the equation of a circle. Parameters ========== center : Point radius : number or SymPy expression points : sequence of three Points equation : equation o...
Circle
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/destination_pgvector/config.py
{ "start": 183, "end": 522 }
class ____(BaseModel): password: str = Field( ..., title="Password", airbyte_secret=True, description="Enter the password you want to use to access the database", examples=["AIRBYTE_PASSWORD"], order=7, ) class Config: title = "Credentials"
PasswordBasedAuthorizationModel
python
plotly__plotly.py
plotly/graph_objs/parcoords/unselected/_line.py
{ "start": 233, "end": 3648 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.unselected" _path_str = "parcoords.unselected.line" _valid_props = {"color", "opacity"} @property def color(self): """ Sets the base color of unselected lines. in connection with `unselected.line.opacity`. ...
Line
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 9490, "end": 9635 }
class ____(AnsibleTemplateError): """A syntax error was encountered while parsing a Jinja template or expression."""
AnsibleTemplateSyntaxError
python
huggingface__transformers
src/transformers/models/align/processing_align.py
{ "start": 718, "end": 975 }
class ____(ProcessingKwargs, total=False): # see processing_utils.ProcessingKwargs documentation for usage. _defaults = { "text_kwargs": { "padding": "max_length", "max_length": 64, }, }
AlignProcessorKwargs
python
apache__airflow
airflow-core/tests/unit/plugins/test_plugin.py
{ "start": 5790, "end": 6225 }
class ____(AirflowPlugin): name = "preload" def on_load(self, *args, **kwargs): self.name = "postload" # Example external view with invalid destination external_view_with_invalid_destination = { "name": "Invalid External View", "href": "https://example.com/invalid", "url_route": "invalid_...
AirflowTestOnLoadPlugin
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 465, "end": 670 }
class ____(models.Model): name = models.CharField(blank=True, max_length=255, null=True) text = models.TextField(blank=True, null=True) class Meta: app_label = "django_extensions"
Secret
python
kamyu104__LeetCode-Solutions
Python/largest-unique-number.py
{ "start": 50, "end": 278 }
class ____(object): def largestUniqueNumber(self, A): """ :type A: List[int] :rtype: int """ A.append(-1) return max(k for k,v in collections.Counter(A).items() if v == 1)
Solution
python
scipy__scipy
scipy/io/wavfile.py
{ "start": 2115, "end": 30691 }
class ____(IntEnum): """ WAVE form wFormatTag IDs Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the newest additions, in v10.0.14393 2016-07 """ UNKNOWN = 0x0000 PCM = 0x0001 ADPCM = 0x0002 IEEE_FLOAT = 0x0003 VSELP = 0x0004 IBM_CVSD = 0x0005 ALAW = 0...
WAVE_FORMAT
python
PyCQA__pylint
tests/checkers/unittest_base_checker.py
{ "start": 1728, "end": 5311 }
class ____(BaseChecker): name = "message-with-options-checker" msgs = { "W0003": ( "Just a message with pre-defined options %s()", "message-with-options", "Message with options dict to test consistent hashing.", {"old_names": [("W1003", "old-message-with-o...
MessageWithOptionsChecker
python
vyperlang__vyper
tests/venom_utils.py
{ "start": 1944, "end": 3304 }
class ____: passes: list[type] post_passes: list[type] pass_objects: list[IRPass] default_hevm: bool def __init__(self, passes: list[type], post: list[type] = None, default_hevm: bool = True): self.passes = passes if post is None: self.post_passes = [] else: ...
PrePostChecker
python
getsentry__sentry
tests/sentry/seer/explorer/test_tools.py
{ "start": 28058, "end": 28113 }
class ____(BaseModel): id: int slug: str
_Project
python
conda__conda
conda/gateways/repodata/jlap/interface.py
{ "start": 666, "end": 4006 }
class ____(RepoInterface): def __init__( self, url: str, repodata_fn: str | None, *, cache: RepodataCache, **kwargs, ) -> None: log.debug("Using %s", self.__class__.__name__) self._cache = cache self._url = url self._repodata_fn =...
JlapRepoInterface
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/constant_op_test.py
{ "start": 37585, "end": 39373 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testFullShape(self): with self.session(force_gpu=test_util.is_gpu_available()): p = array_ops.placeholder_with_default([[2, 2], [2, 2]], shape=[2, 2]) a = array_ops.identity(p) self.assertAllEqual([[2, 2], [2, 2]], self.evaluate(a)) ...
PlaceholderWithDefaultTest
python
agronholm__apscheduler
tests/test_schedulers.py
{ "start": 3139, "end": 47388 }
class ____: def test_repr(self) -> None: scheduler = AsyncScheduler(identity="my identity") assert repr(scheduler) == ( "AsyncScheduler(identity='my identity', role=<SchedulerRole.both: 3>, " "data_store=MemoryDataStore(), event_broker=LocalEventBroker())" ) asyn...
TestAsyncScheduler
python
pandas-dev__pandas
asv_bench/benchmarks/indexing.py
{ "start": 15690, "end": 15944 }
class ____: # GH#19299 def setup(self): N = 1000 cols = 500 self.df = DataFrame(index=range(N), columns=range(cols), dtype=object) def time_setitem_object_dtype(self): self.df.loc[0, 1] = 1.0
SetitemObjectDtype
python
django__django
tests/check_framework/test_commands.py
{ "start": 424, "end": 1025 }
class ____(SimpleTestCase): def test_migrate_and_makemigrations_autodetector_different(self): expected_error = Error( "The migrate and makemigrations commands must have the same " "autodetector.", hint=( "makemigrations.Command.autodetector is int, but " ...
CommandCheckTests
python
cython__cython
tests/run/pure_cdef_class_dataclass.py
{ "start": 1043, "end": 2430 }
class ____: """ >>> NoInitFields() NoInitFields(has_default=DummyObj(), has_factory='From a lambda', neither=None) >>> NoInitFields().has_default is NoInitFields().has_default True >>> NoInitFields(1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): TypeError: NoI...
NoInitFields
python
pydantic__pydantic
tests/mypy/outputs/mypy-default_ini/metaclass_args.py
{ "start": 740, "end": 1021 }
class ____(BaseModel): i: int = Field(2, alias='j') NoArguments(i=1) # MYPY: error: Unexpected keyword argument "i" for "NoArguments" [call-arg] NoArguments(j=None) # MYPY: error: Argument "j" to "NoArguments" has incompatible type "None"; expected "int" [arg-type]
NoArguments
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/renderer.py
{ "start": 11969, "end": 12130 }
class ____(Enum): "Enum: whether or not CPR is supported." SUPPORTED = "SUPPORTED" NOT_SUPPORTED = "NOT_SUPPORTED" UNKNOWN = "UNKNOWN"
CPR_Support
python
pytorch__pytorch
test/export/test_export.py
{ "start": 99618, "end": 609495 }
class ____(torch.nn.Module): def forward(self, x): x: "f32[3, 3]"; x, = fx_pytree.tree_flatten_spec(([x], {}), self._in_spec) _guards_fn = self._guards_fn(x); _guards_fn = None sum_1: "f32[]" = torch.ops.aten.sum.default(x) gt: "b8[]" = torch.ops.aten.gt.Scalar(sum_1, 3); ...
GraphModule
python
django__django
tests/postgres_tests/test_hstore.py
{ "start": 12734, "end": 15305 }
class ____(PostgreSQLSimpleTestCase): def test_valid(self): field = forms.HStoreField() value = field.clean('{"a": "b"}') self.assertEqual(value, {"a": "b"}) def test_invalid_json(self): field = forms.HStoreField() with self.assertRaises(exceptions.ValidationError) as cm...
TestFormField
python
gevent__gevent
src/gevent/_hub_primitives.py
{ "start": 1338, "end": 4577 }
class ____(SwitchOutGreenletWithLoop): # pylint:disable=undefined-variable def wait(self, watcher): """ Wait until the *watcher* (which must not be started) is ready. The current greenlet will be unscheduled during this time. """ waiter = Waiter(self) # pylint:disable=undef...
WaitOperationsGreenlet
python
huggingface__transformers
tests/models/aya_vision/test_processing_aya_vision.py
{ "start": 928, "end": 5517 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = AyaVisionProcessor model_id = "hf-internal-testing/namespace-CohereForAI-repo_name_aya-vision-8b" @classmethod def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token @classmethod def _se...
AyaVisionProcessorTest
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 28227, "end": 28606 }
class ____(VariableTracker): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def produce_trampoline_autograd_apply(fn_cls): def trampoline_autograd_apply(*args, **kwargs): return fn_cls.apply(*args, **kwargs) trampoline_autograd_apply._origin = produce_trampoline_autograd...
NewGlobalVariable
python
django__django
tests/auth_tests/test_views.py
{ "start": 40238, "end": 41054 }
class ____(AuthViewsTestCase): """Tests for settings.LOGIN_REDIRECT_URL.""" def assertLoginRedirectURLEqual(self, url): response = self.login() self.assertRedirects(response, url, fetch_redirect_response=False) def test_default(self): self.assertLoginRedirectURLEqual("/accounts/pro...
LoginRedirectUrlTest
python
pytorch__pytorch
torch/distributions/relaxed_categorical.py
{ "start": 3825, "end": 5752 }
class ____(TransformedDistribution): r""" Creates a RelaxedOneHotCategorical distribution parametrized by :attr:`temperature`, and either :attr:`probs` or :attr:`logits`. This is a relaxed version of the :class:`OneHotCategorical` distribution, so its samples are on simplex, and are reparametrizable...
RelaxedOneHotCategorical
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 39859, "end": 40995 }
class ____(FieldValues): """ Valid and invalid values for `DecimalField` with min and max limits. """ valid_inputs = { '10.0': Decimal('10.0'), '20.0': Decimal('20.0'), } invalid_inputs = { '9.9': ['Ensure this value is greater than or equal to 10.0.'], '20.1': ['...
TestMinMaxDecimalField
python
getsentry__sentry
tests/sentry/auth/test_access.py
{ "start": 3237, "end": 23861 }
class ____(AccessFactoryTestCase): def test_no_access(self) -> None: organization = self.create_organization() team = self.create_team(organization=organization) project = self.create_project(organization=organization, teams=[team]) user = self.create_user() request = self.m...
FromUserTest
python
huggingface__transformers
src/transformers/models/dinov3_convnext/modeling_dinov3_convnext.py
{ "start": 8204, "end": 10115 }
class ____(DINOv3ConvNextPreTrainedModel): def __init__(self, config: DINOv3ConvNextConfig): super().__init__(config) self.config = config self.stages = nn.ModuleList([DINOv3ConvNextStage(config, stage_idx) for stage_idx in range(config.num_stages)]) self.layer_norm = nn.LayerNorm(co...
DINOv3ConvNextModel
python
huggingface__transformers
src/transformers/models/janus/modeling_janus.py
{ "start": 31450, "end": 31859 }
class ____(nn.Module): def __init__(self, in_channels): super().__init__() self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1) def forward(self, hidden_states): hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest") h...
JanusVQVAEConvUpsample
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-opendal/llama_index/readers/opendal/s3/base.py
{ "start": 348, "end": 2363 }
class ____(BaseReader): """General reader for any S3 file or directory.""" def __init__( self, bucket: str, path: str = "/", endpoint: str = "", region: str = "", access_key_id: str = "", secret_access_key: str = "", file_extractor: Optional[Dict[...
OpendalS3Reader
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 12315, "end": 12785 }
class ____(BaseSimpleType): @classmethod def convert_from_xml(cls, str_value: str) -> Emu: float_part, units_part = str_value[:-2], str_value[-2:] quantity = float(float_part) multiplier = { "mm": 36000, "cm": 360000, "in": 914400, "pt": 12...
ST_UniversalMeasure
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/forms.py
{ "start": 1575, "end": 1688 }
class ____(ReprModelForm): class Meta: model = ManyNumerics fields = "__all__"
ManyNumericsForm
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 9306, "end": 9668 }
class ____(BaseModel): """ DAG Source serializer for responses. """ content: Annotated[str | None, Field(title="Content")] = None dag_id: Annotated[str, Field(title="Dag Id")] version_number: Annotated[int | None, Field(title="Version Number")] = None dag_display_name: Annotated[str, Field(...
DAGSourceResponse
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_abs_import_only.py
{ "start": 471, "end": 2599 }
class ____( sqlalchemy.testing.fixtures.TestBase, sqlalchemy.testing.AssertsCompiledSQL ): __dialect__ = "default" def test_fully_qualified_mapped_name(self, decl_base): """test #8853 *again*, as reported in #9335 this failed to be fixed""" class Foo(decl_base): __tablename__ =...
MappedColumnTest
python
pyca__cryptography
tests/hazmat/primitives/test_ec.py
{ "start": 25248, "end": 29186 }
class ____: def test_public_numbers_eq(self): pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()) assert pub == ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()) def test_public_numbers_ne(self): pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()) assert pub != ec....
TestECEquality
python
cython__cython
Cython/Compiler/Annotate.py
{ "start": 325, "end": 13208 }
class ____(CCodeWriter): # also used as marker for detection of complete code emission in tests COMPLETE_CODE_TITLE = "Complete cythonized code" def __init__(self, create_from=None, buffer=None, copy_formatting=True, show_entire_c_code=False, source_desc=None): CCodeWriter.__init__(self, create_fr...
AnnotationCCodeWriter
python
walkccc__LeetCode
solutions/1071. Greatest Common Divisor of Strings/1071.py
{ "start": 0, "end": 504 }
class ____: def gcdOfStrings(self, str1: str, str2: str) -> str: for sz in range(min(len(str1), len(str2)), 0, -1): if self._isDivisible(str1, str2, sz): return str1[:sz] return '' def _isDivisible(self, str1: str, str2: str, sz: int) -> bool: """Returns True if str1 and str2 are divisibl...
Solution
python
realpython__materials
python-import/namespace_package/third_party/serializers/xml.py
{ "start": 71, "end": 476 }
class ____: def __init__(self): self._element = None def start_object(self, object_name, object_id): self._element = et.Element(object_name, attrib={"id": object_id}) def add_property(self, name, value): prop = et.SubElement(self._element, name) prop.text = value def _...
XmlSerializer
python
openai__openai-python
src/openai/types/responses/response_output_text.py
{ "start": 804, "end": 1252 }
class ____(BaseModel): end_index: int """The index of the last character of the URL citation in the message.""" start_index: int """The index of the first character of the URL citation in the message.""" title: str """The title of the web resource.""" type: Literal["url_citation"] """...
AnnotationURLCitation
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 3932, "end": 5160 }
class ____(RuntimeError): pass def safety_limit(val): # Given an integer value from the process being debugged, limit it to some # safety threshold so that arbitrary breakage within said process doesn't # break the gdb process too much (e.g. sizes of iterations, sizes of lists) return min(val, 100...
NullPyObjectPtr
python
getsentry__sentry
src/sentry/db/models/fields/slug.py
{ "start": 418, "end": 1962 }
class ____(Lookup): lookup_name = "id_or_slug" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) # Use Django's built-in SQL compiler methods to properly quote table and column names...
IdOrSlugLookup
python
dagster-io__dagster
python_modules/dagster/dagster/components/testing/test_cases.py
{ "start": 5812, "end": 6908 }
class ____: """Pytest test class for testing customization of op spec. You can subclass this class and implement a test_op_customization function using the various fixtures in order to comprehensively test op spec customization options for your component. """ @pytest.fixture( params=[ ...
TestOpCustomization
python
davidhalter__jedi
jedi/inference/value/klass.py
{ "start": 4704, "end": 7892 }
class ____(ParserTreeFilter): def __init__(self, class_value, node_context=None, until_position=None, origin_scope=None, is_instance=False): super().__init__( class_value.as_context(), node_context, until_position=until_position, origin_scope=origin_scope...
ClassFilter
python
realpython__materials
python-print/custom_class.py
{ "start": 0, "end": 275 }
class ____: def __init__(self, name, age): self.name = name self.age = age def __str__(self): class_name = type(self).__name__ return f"{class_name}(name={self.name!r}, age={self.age!r})" jdoe = Person("John Doe", 42) print(jdoe)
Person
python
Textualize__textual
src/textual/widgets/_select.py
{ "start": 1203, "end": 5607 }
class ____(OptionList): """The 'pop-up' overlay for the Select control.""" BINDINGS = [("escape", "dismiss", "Dismiss menu")] @dataclass class Dismiss(Message): """Inform ancestor the overlay should be dismissed.""" lost_focus: bool = False """True if the overlay lost focus.""...
SelectOverlay
python
wandb__wandb
wandb/vendor/pygments/styles/monokai.py
{ "start": 506, "end": 5080 }
class ____(Style): """ This style mimics the Monokai color scheme. """ background_color = "#272822" highlight_color = "#49483e" styles = { # No corresponding class for the following: Text: "#f8f8f2", # class: '' Whitespace: "", ...
MonokaiStyle
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_reflection.py
{ "start": 2118, "end": 2555 }
class ____: @testing.fixture( params=[ "engine", "connection", ] ) def inspect_fixture(self, request, metadata, testing_engine): engine = request.param eng = testing_engine() conn = eng.connect() if engine == "connection": ...
ReflectionFixtures
python
bokeh__bokeh
tests/unit/bokeh/models/test_mappers.py
{ "start": 3239, "end": 3532 }
class ____: def test_basic(self) -> None: mapper = bmm.CategoricalPatternMapper() check_properties_existence(mapper, [ "factors", "patterns", "start", "end", "default_value"], )
Test_CategoricalPatternMapper
python
django__django
tests/queries/tests.py
{ "start": 150937, "end": 153289 }
class ____(TestCase): """ The queries reuse joins sensibly (for example, direct joins are always reused). """ def test_fk_reuse(self): qs = Annotation.objects.filter(tag__name="foo").filter(tag__name="bar") self.assertEqual(str(qs.query).count("JOIN"), 1) def test_fk_reuse_sele...
JoinReuseTest
python
django__django
tests/forms_tests/models.py
{ "start": 3235, "end": 3337 }
class ____(models.Model): file = models.FileField(storage=temp_storage, upload_to="tests")
FileModel
python
pypa__setuptools
setuptools/_distutils/compilers/C/cygwin.py
{ "start": 954, "end": 8532 }
class ____(unix.Compiler): """Handles the Cygwin port of the GNU C compiler to Windows.""" compiler_type = 'cygwin' obj_extension = ".o" static_lib_extension = ".a" shared_lib_extension = ".dll.a" dylib_lib_extension = ".dll" static_lib_format = "lib%s%s" shared_lib_format = "lib%s%s" ...
Compiler
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 36920, "end": 43764 }
class ____(ClvpPreTrainedModel): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`ClvpEncoderLayer`]. Args: config: ClvpConfig """ def __init__(self, config: ClvpConfig): super().__init__(config) self.config = co...
ClvpEncoder
python
pypa__pipenv
tests/integration/conftest.py
{ "start": 3469, "end": 5654 }
class ____: def __init__(self, path, index): self.path = path self.index = index if self.path.exists(): self.loads() else: self.document = tomlkit.document() self.document["source"] = self.document.get("source", tomlkit.aot()) self.document["re...
_Pipfile
python
gevent__gevent
src/greentest/3.10/test_signal.py
{ "start": 24078, "end": 28080 }
class ____(unittest.TestCase): def setUp(self): self.hndl_called = False self.hndl_count = 0 self.itimer = None self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm) def tearDown(self): signal.signal(signal.SIGALRM, self.old_alarm) if self.itimer is not N...
ItimerTest
python
chroma-core__chroma
chromadb/api/types.py
{ "start": 59896, "end": 59994 }
class ____: bool_inverted_index: Optional[BoolInvertedIndexType] = None @dataclass
BoolValueType
python
apache__airflow
providers/opsgenie/tests/unit/opsgenie/notifications/test_opsgenie.py
{ "start": 1084, "end": 5202 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="opsgenie_default", conn_type="opsgenie", host="https://api.opsgenie.com/", p...
TestOpsgenieNotifier
python
django__django
tests/select_related_regress/models.py
{ "start": 1976, "end": 2078 }
class ____(Client): value = models.IntegerField() # Some model inheritance exercises
SpecialClient
python
huggingface__transformers
src/transformers/models/udop/modeling_udop.py
{ "start": 38347, "end": 43111 }
class ____(nn.Module, ABC): """ Base class of relative biases. Args: num_heads (`int`): Number of attention heads in the model, it will create embeddings of size `num_heads`, which will be added to the scores of each token pair. relative_attention_num_buckets (`int`, *optional*,...
RelativePositionBiasBase
python
doocs__leetcode
solution/2100-2199/2161.Partition Array According to Given Pivot/Solution.py
{ "start": 0, "end": 318 }
class ____: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: a, b, c = [], [], [] for x in nums: if x < pivot: a.append(x) elif x == pivot: b.append(x) else: c.append(x) return a + b + c
Solution
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/add_test.py
{ "start": 542, "end": 1508 }
class ____(op_bench.TorchBenchmarkBase): def init(self, M, N, K, device): self.inputs = { "input_one": torch.rand( M, N, K, device=device, requires_grad=self.auto_set() ), "input_two": torch.rand( M, N, K, device=device, requires_grad=self....
AddBenchmark
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 128383, "end": 129777 }
class ____(TestCase): def test_empty(self): # empty iterable -> empty list self.assertEqual(list(mi.circular_shifts([])), []) def test_simple_circular_shifts(self): # test the a simple iterator case self.assertEqual( list(mi.circular_shifts(range(4))), [(...
CircularShiftsTests
python
tensorflow__tensorflow
tensorflow/python/ops/distributions/exponential.py
{ "start": 5023, "end": 5752 }
class ____(Exponential): """Exponential with softplus transform on `rate`.""" @deprecation.deprecated( "2019-01-01", "Use `tfd.Exponential(tf.nn.softplus(rate)).", warn_once=True) def __init__(self, rate, validate_args=False, allow_nan_stats=True, ...
ExponentialWithSoftplusRate
python
kamyu104__LeetCode-Solutions
Python/count-the-number-of-incremovable-subarrays-i.py
{ "start": 681, "end": 1159 }
class ____(object): def incremovableSubarrayCount(self, nums): """ :type nums: List[int] :rtype: int """ return sum((left == 0 or right == len(nums)-1 or nums[left-1] < nums[right+1]) and all(nums[i] < nums[i+1] for i in xrange(left-1)) and ...
Solution2
python
encode__django-rest-framework
tests/test_serializer.py
{ "start": 22186, "end": 23399 }
class ____: def setup_method(self): class ExampleSerializer(serializers.Serializer): char = serializers.CharField(default='abc') integer = serializers.IntegerField() self.Serializer = ExampleSerializer def test_default_should_included_on_create(self): serializer ...
TestDefaultInclusions
python
apache__airflow
airflow-core/src/airflow/timetables/base.py
{ "start": 2711, "end": 3502 }
class ____(NamedTuple): """ Restriction on when a DAG can be scheduled for a run. Specifically, the run must not be earlier than ``earliest``, nor later than ``latest``. If ``catchup`` is *False*, the run must also not be earlier than the current time, i.e. "missed" schedules are not backfilled. ...
TimeRestriction
python
PyCQA__isort
isort/exceptions.py
{ "start": 6498, "end": 7008 }
class ____(ISortError): """Raised when isort encounters an import that matches a section that is not defined""" def __init__(self, import_module: str, section: str): super().__init__( f"Found {import_module} import while parsing, but {section} was not included " "in the `section...
MissingSection
python
readthedocs__readthedocs.org
readthedocs/search/faceted_search.py
{ "start": 9213, "end": 14131 }
class ____(RTDFacetedSearch): facets = { "project": TermsFacet(field="project"), } doc_types = [PageDocument] index = PageDocument._index._name # boosting for these fields need to be close enough # to be re-boosted by the page rank. _outer_fields = ["title^1.5"] _section_fields ...
PageSearch
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 74830, "end": 75106 }
class ____(ConstantLikeVariable): _error_prefix = "torch.__version__" def __init__(self, **kwargs) -> None: kwargs.setdefault("value", torch.__version__) assert kwargs["value"] is torch.__version__ super().__init__(**kwargs)
TorchVersionVariable
python
tensorflow__tensorflow
tensorflow/python/util/lock_util_test.py
{ "start": 875, "end": 1838 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters(1, 2, 3, 5, 10) def testGroups(self, num_groups): lock = lock_util.GroupLock(num_groups) num_threads = 10 finished = set() def thread_fn(thread_id): time.sleep(random.random() * 0.1) group_id = thread_id % num...
GroupLockTest
python
google__pytype
pytype/tests/test_enums.py
{ "start": 108, "end": 40653 }
class ____(test_base.BaseTest): """Tests the overlay.""" def test_can_import_module_members(self): self.Check(""" import enum enum.Enum enum.IntEnum enum.IntFlag enum.Flag enum.unique enum.auto """) def test_create_basic_enum(self): self.Check(""" impo...
EnumOverlayTest
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 131770, "end": 147171 }
class ____(SeamlessM4TPreTrainedModel, GenerationMixin): output_modalities = ("audio",) _keys_to_ignore_on_load_missing = ["speech_encoder"] main_input_name = "input_ids" _tied_weights_keys = { "lm_head.weight": "shared.weight", "text_encoder.embed_tokens.weight": "shared.weight", ...
SeamlessM4TForTextToSpeech
python
numpy__numpy
tools/swig/test/testTensor.py
{ "start": 14065, "end": 14375 }
class ____(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" self.result = int(self.result) ######################################################################
longLongTestCase
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 26190, "end": 26711 }
class ____(ActionBaseModel): """Data used to create block document reference.""" id: UUID = Field(default_factory=uuid4) parent_block_document_id: UUID = Field( default=..., description="ID of block document the reference is nested within" ) reference_block_document_id: UUID = Field( ...
BlockDocumentReferenceCreate
python
spyder-ide__spyder
spyder/plugins/updatemanager/widgets/status.py
{ "start": 787, "end": 3452 }
class ____(StatusBarWidget): """Status bar widget for update manager.""" ID = 'update_manager_status' INTERACT_ON_CLICK = True sig_check_update = Signal() """Signal to request checking for updates.""" sig_start_update = Signal() """Signal to start the update process.""" sig_show_progr...
UpdateManagerStatus
python
pypa__warehouse
warehouse/sitemap/models.py
{ "start": 126, "end": 300 }
class ____: sitemap_bucket: Mapped[str] = mapped_column( server_default=FetchedValue(), server_onupdate=FetchedValue(), index=True, )
SitemapMixin
python
doocs__leetcode
solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/Solution.py
{ "start": 0, "end": 466 }
class ____: def numSubseq(self, nums: List[int], target: int) -> int: mod = 10**9 + 7 nums.sort() n = len(nums) f = [1] + [0] * n for i in range(1, n + 1): f[i] = f[i - 1] * 2 % mod ans = 0 for i, x in enumerate(nums): if x * 2 > target...
Solution
python
anthropics__anthropic-sdk-python
tests/test_legacy_response.py
{ "start": 3595, "end": 4240 }
class ____(pydantic.BaseModel): a: str @pytest.mark.parametrize("client", [False], indirect=True) # loose validation def test_response_parse_expect_model_union_non_json_content(client: Anthropic) -> None: response = LegacyAPIResponse( raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "...
OtherModel
python
plotly__plotly.py
plotly/express/_special_inputs.py
{ "start": 590, "end": 958 }
class ____(object): """ Objects of this class can be passed to Plotly Express functions that expect column identifiers or list-like objects to indicate that this attribute should take on a constant value. An optional label can be provided. """ def __init__(self, value, label=None): self...
Constant
python
jazzband__django-pipeline
pipeline/storage.py
{ "start": 1732, "end": 3030 }
class ____: gzip_patterns = ("*.css", "*.js") def _compress(self, original_file): content = BytesIO() gzip_file = gzip.GzipFile(mode="wb", fileobj=content) gzip_file.write(original_file.read()) gzip_file.close() content.seek(0) return File(content) def post_...
GZIPMixin
python
kamyu104__LeetCode-Solutions
Python/find-the-xor-of-numbers-which-appear-twice.py
{ "start": 42, "end": 333 }
class ____(object): def duplicateNumbersXOR(self, nums): """ :type nums: List[int] :rtype: int """ return reduce(lambda x, y: x^y, nums, 0)^reduce(lambda x, y: x^y, set(nums), 0) # Time: O(n) # Space: O(n) import collections # freq table
Solution
python
dateutil__dateutil
src/dateutil/zoneinfo/__init__.py
{ "start": 313, "end": 660 }
class ____(_tzfile): def __reduce__(self): return (gettz, (self._filename,)) def getzoneinfofile_stream(): try: return BytesIO(get_data(__name__, ZONEFILENAME)) except IOError as e: # TODO switch to FileNotFoundError? warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror...
tzfile
python
getsentry__sentry
src/sentry/users/web/accounts_form.py
{ "start": 3073, "end": 4678 }
class ____(forms.Form): username = forms.CharField(max_length=128, required=False, widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) tos_check = forms.BooleanField( label=_( f"I agree to the <a href={settings.TERMS_URL}>Terms of Service</a> and <a href={s...
RelocationForm
python
django__django
tests/proxy_model_inheritance/models.py
{ "start": 201, "end": 295 }
class ____(ConcreteModelSubclass): class Meta: proxy = True
ConcreteModelSubclassProxy
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 11618, "end": 11897 }
class ____(ToolBase): """Tool to call the figure manager destroy method.""" description = 'Quit all figures' default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all']) def trigger(self, sender, event, data=None): Gcf.destroy_all()
ToolQuitAll
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 318976, "end": 347890 }
class ____(ExprNode): # obj.attribute # # obj ExprNode # attribute string # needs_none_check boolean Used if obj is an extension type. # If set to True, it is known that the type is not None. # # Used internally: # # is_py...
AttributeNode
python
getsentry__sentry
src/sentry/incidents/metric_issue_detector.py
{ "start": 3251, "end": 4889 }
class ____(BaseDataConditionValidator): supported_conditions = frozenset( ( Condition.GREATER, Condition.LESS, Condition.GREATER_OR_EQUAL, Condition.LESS_OR_EQUAL, Condition.ANOMALY_DETECTION, ) ) supported_condition_results = froze...
MetricIssueComparisonConditionValidator
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 27011, "end": 27211 }
class ____(_CoerceLiterals, RoleImpl): __slots__ = () _coerce_consts = True def _text_coercion(self, element, argname=None): return elements.TextClause(element)
StatementOptionImpl
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/nodes.py
{ "start": 2785, "end": 3236 }
class ____(Node): __slots__ = ('flow_style',) def __init__( self, tag, value, start_mark=None, end_mark=None, flow_style=None, comment=None, anchor=None, ): # type: (Any, Any, Any, Any, Any, Any, Any) -> None Node.__init__(self...
CollectionNode
python
kamyu104__LeetCode-Solutions
Python/find-xor-sum-of-all-pairs-bitwise-and.py
{ "start": 47, "end": 283 }
class ____(object): def getXORSum(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ return reduce(operator.xor, arr1) & reduce(operator.xor, arr2)
Solution
python
scrapy__scrapy
scrapy/commands/view.py
{ "start": 203, "end": 892 }
class ____(fetch.Command): def short_desc(self) -> str: return "Open URL in browser, as seen by Scrapy" def long_desc(self) -> str: return ( "Fetch a URL using the Scrapy downloader and show its contents in a browser" ) def add_options(self, parser: argparse.ArgumentPar...
Command
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 21509, "end": 23859 }
class ____(CDeclaratorNode): # base CDeclaratorNode # dimension ExprNode child_attrs = ["base", "dimension"] def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False): if ((base_type.is_cpp_class and base_type.is_template_type()) or base_type.is_cfun...
CArrayDeclaratorNode
python
huggingface__transformers
tests/utils/test_cache_utils.py
{ "start": 1952, "end": 4958 }
class ____(unittest.TestCase): """Cache tests that don't require loading models""" def test_static_cache_mha_mqa_gqa(self): """ Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query attention (MQA) """ def _random_...
CacheTest
python
numba__numba
numba/cuda/cudadrv/dummyarray.py
{ "start": 3374, "end": 14209 }
class ____(object): """A dummy numpy array-like object. Consider it an array without the actual data, but offset from the base data pointer. Attributes ---------- dims: tuple of Dim describing each dimension of the array ndim: int number of dimension shape: tuple of int ...
Array
python
django__django
tests/postgres_tests/test_indexes.py
{ "start": 8020, "end": 8611 }
class ____(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = SpGistIndex def test_suffix(self): self.assertEqual(SpGistIndex.suffix, "spgist") def test_deconstruction(self): index = SpGistIndex(fields=["title"], name="test_title_spgist", fillfactor=80) path, args, kwargs = i...
SpGistIndexTests