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
getsentry__sentry
tests/sentry/preprod/api/endpoints/test_project_preprod_artifact_update.py
{ "start": 342, "end": 17140 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.file = self.create_file(name="test_artifact.apk", type="application/octet-stream") self.preprod_artifact = PreprodArtifact.objects.create( project=self.project, file_id=self.file.id, state...
ProjectPreprodArtifactUpdateEndpointTest
python
walkccc__LeetCode
solutions/770. Basic Calculator IV/770.py
{ "start": 0, "end": 1848 }
class ____: def __init__(self, term: str = None, coef: int = None): if term and coef: self.terms = collections.Counter({term: coef}) else: self.terms = collections.Counter() def __add__(self, other): for term, coef in other.terms.items(): self.terms[term] += coef return self de...
Poly
python
sqlalchemy__sqlalchemy
test/orm/test_versioning.py
{ "start": 38671, "end": 52098 }
class ____(fixtures.MappedTest): run_define_tables = "each" __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): from sqlalchemy.sql import ColumnElement from sqlalchemy.ext.compiler import compiles import itertools counter = itertools.count(...
ServerVersioningTest
python
aio-libs__aiohttp
aiohttp/client_exceptions.py
{ "start": 3511, "end": 3591 }
class ____(ClientConnectionError, OSError): """OSError error."""
ClientOSError
python
coleifer__peewee
playhouse/migrate.py
{ "start": 3725, "end": 5156 }
class ____(object): """Encapsulate a single schema altering operation.""" def __init__(self, migrator, method, *args, **kwargs): self.migrator = migrator self.method = method self.args = args self.kwargs = kwargs def execute(self, node): self.migrator.database.execut...
Operation
python
doocs__leetcode
solution/3100-3199/3137.Minimum Number of Operations to Make Word K-Periodic/Solution.py
{ "start": 0, "end": 199 }
class ____: def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int: n = len(word) return n // k - max(Counter(word[i : i + k] for i in range(0, n, k)).values())
Solution
python
apache__airflow
task-sdk/src/airflow/sdk/io/stat.py
{ "start": 866, "end": 2494 }
class ____(dict): """ stat_result: Result from stat, fstat, or lstat. This object provides a subset of os.stat_result attributes, for results returned from ObjectStoragePath.stat() It provides st_dev, st_ino, st_mode, st_nlink, st_uid, st_gid, st_size and st_mtime if they are available from th...
stat_result
python
pallets__werkzeug
src/werkzeug/wrappers/request.py
{ "start": 931, "end": 24730 }
class ____(_SansIORequest): """Represents an incoming WSGI HTTP request, with headers and body taken from the WSGI environment. Has properties and methods for using the functionality defined by various HTTP specs. The data in requests object is read-only. Text data is assumed to use UTF-8 encoding,...
Request
python
getsentry__sentry
tests/sentry/issues/test_issue_search.py
{ "start": 21247, "end": 21921 }
class ____(TestCase): def test(self) -> None: assert convert_device_class_value(["high"], [self.project], self.user, None) == ["3"] assert convert_device_class_value(["medium"], [self.project], self.user, None) == ["2"] assert convert_device_class_value(["low"], [self.project], self.user, No...
DeviceClassValueTest
python
pytorch__pytorch
test/distributed/test_aten_comm_compute_reordering.py
{ "start": 56147, "end": 65361 }
class ____(TestComputeCommReorderingMultiProc): """ Tests for manual overlap scheduling and subgraph utilities. """ @unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch") def test_make_graph_view_and_get_subgraph_by_path(self): from torch._inductor.fx_passes.graph_vi...
TestManualOverlapBucketing
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/type_inference.py
{ "start": 6154, "end": 16435 }
class ____(gast.NodeVisitor): """Runs type inference on a single AST statement. This visitor annotates most nodes with type information. It also sets types for the symbols modified by this statement in its types_out property. Note: this inferrer is able to capture side effects of functions, however, these s...
StmtInferrer
python
pytorch__pytorch
test/quantization/core/experimental/test_quantizer.py
{ "start": 350, "end": 9213 }
class ____(unittest.TestCase): r""" Tests quantize_APoT result on random 1-dim tensor and hardcoded values for b, k by comparing to uniform quantization (non-uniform quantization reduces to uniform for k = 1) quantized tensor (https://pytorch.org/docs/stable/generated/torch.quantize_per_tens...
TestQuantizer
python
django__django
tests/model_fields/test_floatfield.py
{ "start": 101, "end": 1776 }
class ____(TestCase): def test_float_validates_object(self): instance = FloatModel(size=2.5) # Try setting float field to unsaved object instance.size = instance with transaction.atomic(): with self.assertRaises(TypeError): instance.save() # Set va...
TestFloatField
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/rng_test.py
{ "start": 7167, "end": 21022 }
class ____(test_util.DTensorBaseTest): def setUp(self): super(DTensorRNGTest, self).setUp() global_ids = test_util.create_device_ids_array((2, 4)) local_ids = _LOCAL_IDS mesh_dict = { device: Mesh( [_MESH_DIM_X, _MESH_DIM_Y], global_ids, local_ids, ...
DTensorRNGTest
python
jazzband__prettytable
tests/test_prettytable.py
{ "start": 23545, "end": 24716 }
class ____: def test_slice_all(self, city_data: PrettyTable) -> None: table = city_data[:] assert city_data.get_string() == table.get_string() def test_slice_first_two_rows(self, city_data: PrettyTable) -> None: table = city_data[0:2] string = table.get_string() assert l...
TestSlicing
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py
{ "start": 4539, "end": 5118 }
class ____(ZenloopStream): # API Doc: https://docs.zenloop.com/reference#get-list-of-surveys primary_key = None has_date_param = False extra_params = {"page": "1"} use_cache = True def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_...
Surveys
python
apache__airflow
providers/teradata/tests/unit/teradata/utils/test_bteq_util.py
{ "start": 1321, "end": 13211 }
class ____: def test_identify_os_linux(self): # Arrange ssh_client = MagicMock() stdout_mock = MagicMock() stdout_mock.read.return_value = b"Linux\n" ssh_client.exec_command.return_value = (MagicMock(), stdout_mock, MagicMock()) # Act os_info = identify_os(ss...
TestBteqUtils
python
pytorch__pytorch
test/distributed/algorithms/ddp_comm_hooks/test_ddp_hooks.py
{ "start": 1527, "end": 7749 }
class ____(MultiProcessTestCase): def setUp(self): super().setUp() self._spawn_processes() def tearDown(self): try: os.remove(self.file_name) except OSError: pass def _get_process_group_nccl(self): store = dist.FileStore(self.file_name, self....
DistributedDataParallelCommHookTest
python
wandb__wandb
wandb/vendor/pygments/lexers/robotframework.py
{ "start": 8766, "end": 8927 }
class ____(TestCaseSetting): _keyword_settings = ('teardown',) _other_settings = ('documentation', 'arguments', 'return', 'timeout', 'tags')
KeywordSetting
python
coleifer__peewee
tests/queries.py
{ "start": 296, "end": 5574 }
class ____(DatabaseTestCase): database = get_in_memory_db() def setUp(self): super(TestQueryExecution, self).setUp() User.bind(self.database) Tweet.bind(self.database) Register.bind(self.database) self.execute('CREATE TABLE "users" (id INTEGER NOT NULL PRIMARY KEY, ' ...
TestQueryExecution
python
aimacode__aima-python
agents.py
{ "start": 24162, "end": 24465 }
class ____(Environment): """Model for Continuous World""" def __init__(self, width=10, height=10): super().__init__() self.width = width self.height = height def add_obstacle(self, coordinates): self.things.append(PolygonObstacle(coordinates))
ContinuousWorld
python
encode__httpx
httpx/_config.py
{ "start": 2098, "end": 5406 }
class ____: """ Timeout configuration. **Usage**: Timeout(None) # No timeouts. Timeout(5.0) # 5s timeout on all operations. Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout ...
Timeout
python
doocs__leetcode
solution/0800-0899/0884.Uncommon Words from Two Sentences/Solution.py
{ "start": 0, "end": 193 }
class ____: def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: cnt = Counter(s1.split()) + Counter(s2.split()) return [s for s, v in cnt.items() if v == 1]
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/event_log/base.py
{ "start": 6806, "end": 6885 }
class ____: name: str limit: int from_default: bool @public
PoolLimit
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_ops_test.py
{ "start": 49184, "end": 52671 }
class ____(test_util.TensorFlowTestCase): # The same test can run with and without XLA compilation. # In non-XLA gpu case, it exercises gpu branch. # In XLA gpu cases, it exercises the default case. # This test is to test the non-XLA case so that we disable XLA. @test_util.disable_xla("xla has different exec...
ExecuteFnForDeviceTest
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ROI.py
{ "start": 83108, "end": 89654 }
class ____(ROI): r""" Container class for multiple connected LineSegmentROIs. This class allows the user to draw paths of multiple line segments. ============== ============================================================= **Arguments** positions (list of length-2 sequences) The list of p...
PolyLineROI
python
pytorch__pytorch
test/jit/test_union.py
{ "start": 537, "end": 33966 }
class ____(JitTestCase): """ This class tests the functionality of `Union`. Note: It's important to be able to refine the type of a `Union` to one of its internal types. Currently, there are differences in the way Python expects `isinstance` checks and the way TorchScript expects `isinstance` c...
TestUnion
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_crossing05.py
{ "start": 315, "end": 1396 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_crossing05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self....
TestCompareXLSXFiles
python
coleifer__peewee
tests/shortcuts.py
{ "start": 862, "end": 911 }
class ____(TestModel): label = TextField()
Label
python
django__django
tests/admin_views/models.py
{ "start": 12244, "end": 12410 }
class ____(models.Model): title = models.CharField(max_length=100) published = models.BooleanField(default=False) slug = models.SlugField()
PrePopulatedPost
python
PyCQA__pyflakes
pyflakes/messages.py
{ "start": 56, "end": 424 }
class ____: message = '' message_args = () def __init__(self, filename, loc): self.filename = filename self.lineno = loc.lineno self.col = loc.col_offset def __str__(self): return '{}:{}:{}: {}'.format(self.filename, self.lineno, self.col+1, ...
Message
python
HypothesisWorks__hypothesis
hypothesis-python/tests/pytest/test_mark.py
{ "start": 1010, "end": 1433 }
class ____(TestCase): @given(integers()) def test_foo(self, x): pass def test_bar(self): pass """ def test_can_select_mark_on_unittest(testdir): script = testdir.makepyfile(UNITTEST_TESTSUITE) result = testdir.runpytest( script, "--verbose", "--strict-markers", "-m", "hypo...
TestStuff
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/strings_ops/unicode_script_op_test.py
{ "start": 1068, "end": 2016 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testValidScripts(self): inputs = [ ord("a"), 0x0411, # CYRILLIC CAPITAL LETTER BE 0x82b8, # CJK UNIFIED IDEOGRAPH-82B8 ord(",") ] with self.cached_session(): input_vector = constant_op.constant(inputs, d...
UnicodeScriptOpTest
python
huggingface__transformers
tests/models/zamba/test_modeling_zamba.py
{ "start": 10111, "end": 18819 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( ZambaModel, ZambaForCausalLM, ZambaForSequenceClassification, ) if is_torch_available() else () ) pipeline_model_mapping = ...
ZambaModelTest
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/GroupBox.py
{ "start": 102, "end": 3185 }
class ____(QtWidgets.QGroupBox): """Subclass of QGroupBox that implements collapse handle. """ sigCollapseChanged = QtCore.Signal(object) def __init__(self, *args): QtWidgets.QGroupBox.__init__(self, *args) self._collapsed = False # We modify the size policy when th...
GroupBox
python
xlwings__xlwings
xlwings/constants.py
{ "start": 111003, "end": 111148 }
class ____: xlAllAtOnce = 2 # from enum XlRoutingSlipDelivery xlOneAfterAnother = 1 # from enum XlRoutingSlipDelivery
RoutingSlipDelivery
python
allegroai__clearml
clearml/binding/frameworks/tensorflow_bind.py
{ "start": 59013, "end": 77384 }
class ____(object): _current_task = None __original_fn_scalar = None __original_fn_hist = None __original_fn_image = None __original_fn_write_summary = None __trains_event_writer = {} __tf_tb_writer_id_to_logdir = {} __patched = False defaults_dict = dict( report_freq=1, ...
PatchTensorFlowEager
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 41649, "end": 42002 }
class ____(sgqlc.types.Enum): """The possible values for the notification restriction setting. Enumeration Choices: * `DISABLED`: The setting is disabled for the owner. * `ENABLED`: The setting is enabled for the owner. """ __schema__ = github_schema __choices__ = ("DISABLED", "ENABLED") ...
NotificationRestrictionSettingValue
python
getsentry__sentry
src/sentry/quotas/base.py
{ "start": 10153, "end": 27055 }
class ____(Service): """ Quotas handle tracking a project's usage and respond whether or not a project has been configured to throttle incoming data if they go beyond the specified quota. Quotas can specify a window to be tracked in, such as per minute or per hour. Additionally, quotas allow to...
Quota
python
getsentry__sentry
src/sentry/integrations/jira_server/handlers/jira_server_handler.py
{ "start": 409, "end": 568 }
class ____(TicketingActionHandler): group = ActionHandler.Group.TICKET_CREATION provider_slug = IntegrationProviderSlug.JIRA_SERVER
JiraServerActionHandler
python
ray-project__ray
python/ray/llm/_internal/serve/observability/usage_telemetry/usage.py
{ "start": 9464, "end": 12664 }
class ____: """Hardware usage class to report telemetry.""" def __init__(self, get_hardware_fn: Callable = get_hardware_usages_to_report): self._get_hardware_fn = get_hardware_fn def infer_gpu_from_hardware(self) -> str: """Infer the GPU type from the hardware when the accelerator type on ...
HardwareUsage
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1303371, "end": 1312880 }
class ____(TextDef): """ FieldOrDatumDefWithConditionStringDatumDefText schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if se...
FieldOrDatumDefWithConditionStringDatumDefText
python
run-llama__llama_index
llama-index-core/llama_index/core/llama_pack/base.py
{ "start": 87, "end": 293 }
class ____: @abstractmethod def get_modules(self) -> Dict[str, Any]: """Get modules.""" @abstractmethod def run(self, *args: Any, **kwargs: Any) -> Any: """Run."""
BaseLlamaPack
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_managed_kafka.py
{ "start": 2271, "end": 2615 }
class ____: def test_class_attributes(self): assert ApacheKafkaClusterLink.key == EXPECTED_MANAGED_KAFKA_CLUSTER_LINK_KEY assert ApacheKafkaClusterLink.name == EXPECTED_MANAGED_KAFKA_CLUSTER_LINK_NAME assert ApacheKafkaClusterLink.format_str == EXPECTED_MANAGED_KAFKA_CLUSTER_LINK_FORMAT_STR ...
TestApacheKafkaClusterLink
python
pytorch__pytorch
torch/_higher_order_ops/while_loop.py
{ "start": 23837, "end": 27804 }
class ____(HigherOrderOperator): """ while_loop_stack_output is a variant of while_loop that returns a stack of outputs. Its semantic can be illurated using python code as: def while_loop_stack_output(cond_fn, body_fn, carried_inputs, additional_inputs): outs = [] while cond_fn(*carried_...
WhileLoopStackOutputOp
python
getsentry__sentry
tests/sentry/api/endpoints/test_rule_snooze.py
{ "start": 14190, "end": 17978 }
class ____(BaseRuleSnoozeTest): endpoint = "sentry-api-0-rule-snooze" method = "delete" def test_delete_issue_alert_rule_mute_myself(self) -> None: """Test that a user can unsnooze a rule they've snoozed for just themselves""" self.snooze_rule(user_id=self.user.id, owner_id=self.user.id, ru...
DeleteRuleSnoozeTest
python
sphinx-doc__sphinx
sphinx/search/__init__.py
{ "start": 6662, "end": 8929 }
class ____(nodes.NodeVisitor): """A special visitor that collects words for the `IndexBuilder`.""" def __init__(self, document: nodes.document, lang: SearchLanguage) -> None: super().__init__(document) self.found_words: list[str] = [] self.found_titles: list[tuple[str, str | None]] = []...
WordCollector
python
langchain-ai__langchain
libs/core/langchain_core/language_models/fake_chat_models.py
{ "start": 618, "end": 1630 }
class ____(BaseChatModel): """Fake chat model for testing purposes.""" responses: list[BaseMessage] """List of responses to **cycle** through in order.""" sleep: float | None = None """Sleep time in seconds between responses.""" i: int = 0 """Internally incremented after every model invocat...
FakeMessagesListChatModel
python
pytorch__pytorch
scripts/release_notes/classifier.py
{ "start": 1052, "end": 1159 }
class ____: title: List[str] files: List[str] author: List[str] @dataclass
CommitClassifierInputs
python
scipy__scipy
scipy/integrate/tests/test_cubature.py
{ "start": 10671, "end": 14814 }
class ____: """ Tests related to the interface of `cubature`. """ @pytest.mark.parametrize("rule_str", [ "gauss-kronrod", "genz-malik", "gk21", "gk15", ]) def test_pass_str(self, rule_str, xp): n = xp.arange(5, dtype=xp.float64) a = xp.asarray([0,...
TestCubature
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 16561, "end": 17012 }
class ____(enum.Enum): SIZE = 0 STRIDE = 1 STORAGE_OFFSET = 2 def method_name(self) -> str: if self is TensorProperty.SIZE: return "size" elif self is TensorProperty.STRIDE: return "stride" elif self is TensorProperty.STORAGE_OFFSET: return "s...
TensorProperty
python
pypa__pip
src/pip/_vendor/rich/errors.py
{ "start": 212, "end": 271 }
class ____(StyleError): """No such style."""
MissingStyle
python
pypa__pip
src/pip/_vendor/urllib3/response.py
{ "start": 710, "end": 1570 }
class ____(object): def __init__(self): self._first_try = True self._data = b"" self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first...
DeflateDecoder
python
django__django
tests/admin_views/admin.py
{ "start": 27119, "end": 27278 }
class ____(forms.ModelForm): first = forms.CharField(widget=forms.HiddenInput) second = forms.CharField(widget=forms.HiddenInput)
FormWithoutVisibleField
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 14292, "end": 14840 }
class ____: __slots__ = ("tensor", "lock", "event", "thread") def __init__(self, t): self.tensor = t # Add one non-picklable field, to ensure it's ignored/skipped. self.lock = Lock() self.event = torch.cuda.Event(enable_timing=True) self.thread = threading.Thread() ...
TensorWrapper
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 28655, "end": 30651 }
class ____(CythonTransform, SkipDeclarations): """ Basic interpretation/validity checking that should only be done on pxd trees. A lot of this checking currently happens in the parser; but what is listed below happens here. - "def" functions are let through only if they fill the getbuffer/...
PxdPostParse
python
allegroai__clearml
clearml/backend_api/services/v2_23/dataviews.py
{ "start": 82210, "end": 98713 }
class ____(Request): """ Get all the company's dataviews and all public dataviews :param id: List of IDs to filter by :type id: Sequence[str] :param name: Get only dataviews whose name matches this pattern (python regular expression syntax) :type name: str :param user: List of user ...
GetAllRequest
python
scrapy__scrapy
scrapy/exporters.py
{ "start": 11338, "end": 11945 }
class ____(BaseItemExporter): """Exports items in a Python-specific binary format (see :mod:`marshal`). :param file: The file-like object to use for exporting the data. Its ``write`` method should accept :class:`bytes` (a disk file opened in binary mode, a :class:`~io.Byte...
MarshalItemExporter
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 1019, "end": 1137 }
class ____: key: AssetKey freshness_state: FreshnessState @whitelist_for_serdes @record
FreshnessStateEvaluation
python
apache__airflow
airflow-core/src/airflow/models/backfill.py
{ "start": 5371, "end": 18686 }
class ____(Base): """Mapping table between backfill run and dag run.""" __tablename__ = "backfill_dag_run" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) backfill_id: Mapped[int] = mapped_column(Integer, nullable=False) dag_run_id: Mapped[int | None] = mapped_column(...
BackfillDagRun
python
Netflix__metaflow
metaflow/plugins/azure/includefile_support.py
{ "start": 4298, "end": 4726 }
class ____(object): def __init__(self, url, path, exists, size): self._path = path self._url = url self._exists = exists self._size = size @property def path(self): return self._path @property def url(self): return self._url @property def ex...
AzureObject
python
pandas-dev__pandas
pandas/io/formats/xml.py
{ "start": 12100, "end": 15835 }
class ____(_BaseXMLFormatter): """ Class for formatting data in xml using Python standard library modules: `xml.etree.ElementTree` and `xml.dom.minidom`. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._convert_empty_str_key() def _build...
LxmlXMLFormatter
python
astropy__astropy
astropy/utils/console.py
{ "start": 31820, "end": 32287 }
class ____: def __init__(self): import sys # noqa: F401 import tty # noqa: F401 def __call__(self): import sys import termios import tty fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()...
_GetchUnix
python
huggingface__transformers
tests/models/swin/test_modeling_swin.py
{ "start": 8148, "end": 17322 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( SwinModel, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, ) if is_torch_available() else () ) pipeline_model_ma...
SwinModelTest
python
kamyu104__LeetCode-Solutions
Python/guess-number-higher-or-lower-ii.py
{ "start": 455, "end": 848 }
class ____(object): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ dp = [[0]*(n+1) for _ in xrange(n+1)] # dp[i][j]: min pay in [i+1, j+1) for i in reversed(xrange(n)): for j in xrange(i+2, n+1): dp[i][j] = min((k+1) + max(d...
Solution2
python
walkccc__LeetCode
solutions/31. Next Permutation/31.py
{ "start": 0, "end": 695 }
class ____: def nextPermutation(self, nums: list[int]) -> None: n = len(nums) # From back to front, find the first number < nums[i + 1]. i = n - 2 while i >= 0: if nums[i] < nums[i + 1]: break i -= 1 # From back to front, find the first number > nums[i], swap it with nums[i]....
Solution
python
pytorch__pytorch
test/test_tensorexpr.py
{ "start": 1089, "end": 58839 }
class ____(BaseTestClass): def test_easy(self): def easy(x, y): aaa = torch.add(x, y) return aaa traced = torch.jit.trace(easy, (torch.rand(1024), torch.rand(1024))) a = torch.rand(1024) b = torch.rand(1024) x = warmup_and_run_forward(traced, a, b) ...
TestTensorExprFuser
python
nedbat__coveragepy
coverage/cmdline.py
{ "start": 10323, "end": 12325 }
class ____(optparse.OptionParser): """Base OptionParser for coverage.py. Problems don't exit the program. Defaults are initialized for all options. """ def __init__(self, *args: Any, **kwargs: Any) -> None: kwargs["add_help_option"] = False super().__init__(*args, **kwargs) ...
CoverageOptionParser
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 14671, "end": 15211 }
class ____( SuperMixin, OfflineTestCaseMixin, TestCase ): templates_dir = "test_block_super_multiple_cached" expected_hash = "055f88f4751f" additional_test_settings = { "TEMPLATE_LOADERS": ( ( "django.template.loaders.cached.Loader", ( ...
OfflineCompressBlockSuperMultipleCachedLoaderTestCase
python
doocs__leetcode
solution/0500-0599/0553.Optimal Division/Solution.py
{ "start": 0, "end": 266 }
class ____: def optimalDivision(self, nums: List[int]) -> str: n = len(nums) if n == 1: return str(nums[0]) if n == 2: return f'{nums[0]}/{nums[1]}' return f'{nums[0]}/({"/".join(map(str, nums[1:]))})'
Solution
python
neetcode-gh__leetcode
python/0665-non-decreasing-array.py
{ "start": 0, "end": 497 }
class ____: def checkPossibility(self, nums): if len(nums) <= 2: return True changed = False for i, num in enumerate(nums): if i == len(nums) - 1 or num <= nums[i + 1]: continue if changed: return False if i == 0...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride1.py
{ "start": 13213, "end": 13296 }
class ____(Base7[int]): def method1(self, x: U) -> U: return x
Derived7_2
python
django__django
tests/proxy_models/models.py
{ "start": 1581, "end": 1782 }
class ____(Person, ManagerMixin): """ A class with the default manager from Person, plus a secondary manager. """ class Meta: proxy = True ordering = ["name"]
OtherPerson
python
django__django
tests/admin_views/admin.py
{ "start": 13656, "end": 13864 }
class ____(admin.ModelAdmin): inlines = [ WidgetInline, DooHickeyInline, GrommetInline, WhatsitInline, FancyDoodadInline, CategoryInline, ]
CollectorAdmin
python
mkdocs__mkdocs
mkdocs/tests/localization_tests.py
{ "start": 221, "end": 2645 }
class ____(unittest.TestCase): def setUp(self): self.env = mock.Mock() def test_jinja_extension_installed(self): install_translations(self.env, parse_locale('en'), []) self.env.add_extension.assert_called_once_with('jinja2.ext.i18n') def test_valid_language(self): locale = ...
LocalizationTests
python
astropy__astropy
astropy/io/fits/column.py
{ "start": 10639, "end": 13192 }
class ____(_BaseColumnFormat): """Similar to _ColumnFormat but specifically for columns in ASCII tables. The formats of ASCII table columns and binary table columns are inherently incompatible in FITS. They don't support the same ranges and types of values, and even reuse format codes in subtly differ...
_AsciiColumnFormat
python
getsentry__sentry
src/sentry/integrations/slack/utils/users.py
{ "start": 875, "end": 3344 }
class ____: email: str team_id: str slack_id: str def format_slack_info_by_email(users: list[dict[str, Any]]) -> dict[str, SlackUserData]: return { member["profile"]["email"]: SlackUserData( email=member["profile"]["email"], team_id=member["team_id"], slack_id=member["id"] ...
SlackUserData
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 77445, "end": 85201 }
class ____(PatchTSMixerPreTrainedModel): def __init__(self, config: PatchTSMixerConfig): super().__init__(config) self.model = PatchTSMixerModel(config) self.loss = config.loss self.distribution_output = config.distribution_output self.use_return_dict = config.use_return_d...
PatchTSMixerForRegression
python
django__django
django/db/backends/sqlite3/operations.py
{ "start": 616, "end": 16315 }
class ____(BaseDatabaseOperations): cast_char_field_without_max_length = "text" cast_data_types = { "DateField": "TEXT", "DateTimeField": "TEXT", } explain_prefix = "EXPLAIN QUERY PLAN" # List of datatypes to that cannot be extracted with JSON_EXTRACT() on # SQLite. Use JSON_TYPE...
DatabaseOperations
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 3196, "end": 25018 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker() Faker.seed(0) def assertBetween(self, date, start_date, end_date): assert date <= end_date assert date >= start_date def test_date(self): date_format = "%Y-%m-%d" date_string = self.fake.dat...
TestDateTime
python
ray-project__ray
python/ray/data/_internal/datasource/uc_datasource.py
{ "start": 212, "end": 7082 }
class ____: """ Load a Unity Catalog table or files into a Ray Dataset, handling cloud credentials automatically. Currently only supports Databricks-managed Unity Catalog Supported formats: delta, parquet. Supports AWS, Azure, and GCP with automatic credential handoff. """ def __init__( ...
UnityCatalogConnector
python
FactoryBoy__factory_boy
tests/test_using.py
{ "start": 87441, "end": 88071 }
class ____(unittest.TestCase): def test_example(self): sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from .cyclic import foo f = foo.FooFactory.build(bar__foo=None) self.assertEqual(42, f.x) self.assertEqual(13, f.bar.y) self.assertIsNone(f.bar.foo) ...
CircularTestCase
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 32570, "end": 35206 }
class ____(SynchronizedDataset): def __getitem__(self, idx): self.sync_once() return torch.tensor(self.value) # Should be used as worker_init_fn with TestWorkerInfoDataset. # See _test_get_worker_info below for usage. def _test_worker_info_init_fn(worker_id): worker_info = torch.utils.data.get...
TestWorkerInfoDataset
python
google__pytype
pytype/pytd/pytd_visitors.py
{ "start": 3727, "end": 6423 }
class ____(base_visitor.Visitor): """Renames a TypeDeclUnit.""" def __init__(self, old_module_name, new_module_name): """Constructor. Args: old_module_name: The old name of the module as a string, e.g. "foo.bar.module1" new_module_name: The new name of the module as a string, e.g. ...
RenameModuleVisitor
python
gevent__gevent
src/gevent/testing/testrunner.py
{ "start": 9284, "end": 36740 }
class ____(object): package_dir = None package = None def __init__( self, tests=None, ignore_files=None, ignored=(), coverage=False, package=None, config=None, allow_combine=True, ): self.config = co...
Discovery
python
ray-project__ray
python/ray/train/tensorflow/tensorflow_trainer.py
{ "start": 352, "end": 7436 }
class ____(DataParallelTrainer): """A Trainer for data parallel Tensorflow training. This Trainer runs the function ``train_loop_per_worker`` on multiple Ray Actors. These actors already have the necessary TensorFlow process group already configured for distributed TensorFlow training. The ``train...
TensorflowTrainer
python
plotly__plotly.py
tests/test_core/test_utils/test_utils.py
{ "start": 126, "end": 587 }
class ____(TestCase): def test_nan_to_null(self): array = [1, float("NaN"), float("Inf"), float("-Inf"), "platypus"] result = _json.dumps(array, cls=PlotlyJSONEncoder) expected_result = '[1, null, null, null, "platypus"]' self.assertEqual(result, expected_result) def test_invali...
TestJSONEncoder
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 36794, "end": 37769 }
class ____(ExprNode): __slots__ = ("func", "args", "keywords") @property def is_extcall(self): return isinstance(self._parent, ExtCall) @property def is_staticcall(self): return isinstance(self._parent, StaticCall) @property def is_plain_call(self): return not (sel...
Call
python
getsentry__sentry
tests/sentry/seer/endpoints/test_organization_seer_setup_check.py
{ "start": 686, "end": 5120 }
class ____(OrganizationSeerSetupCheckTestBase): def test_successful_setup_default_state(self) -> None: """ Test the default state with no acknowledgements and quotas available. """ response = self.get_response(self.organization.slug) assert response.status_code == 200 ...
OrganizationSeerSetupCheckSuccessTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataform.py
{ "start": 14534, "end": 15293 }
class ____: @mock.patch(HOOK_STR) @mock.patch(INSTALL_NPM_PACKAGES_RESPONSE_STR) def test_execute(self, _, hook_mock): op = DataformInstallNpmPackagesOperator( task_id="remove-directory", project_id=PROJECT_ID, region=REGION, repository_id=REPOSITORY_I...
TestDataformInstallNpmPackagesOperator
python
mlflow__mlflow
mlflow/gateway/providers/openai.py
{ "start": 1350, "end": 8811 }
class ____(ProviderAdapter): @classmethod def chat_to_model(cls, payload, config): return cls._add_model_to_payload_if_necessary(payload, config) @classmethod def completion_to_model(cls, payload, config): return cls._add_model_to_payload_if_necessary(payload, config) @classmethod ...
OpenAIAdapter
python
scipy__scipy
scipy/stats/tests/test_multicomp.py
{ "start": 181, "end": 17826 }
class ____: # For the following tests, p-values were computed using Matlab, e.g. # sample = [18. 15. 18. 16. 17. 15. 14. 14. 14. 15. 15.... # 14. 15. 14. 22. 18. 21. 21. 10. 10. 11. 9.... # 25. 26. 17.5 16. 15.5 14.5 22. 22. 24. 22.5 29.... #...
TestDunnett
python
jazzband__django-oauth-toolkit
oauth2_provider/migrations/0004_auto_20200902_2022.py
{ "start": 176, "end": 2700 }
class ____(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('oauth2_provider', '0003_auto_20201211_1314'), ] operations = [ migrations.AddField( model_name='application', name='algorithm', field=...
Migration
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_modelresource/test_resource_setup.py
{ "start": 262, "end": 2192 }
class ____(TestCase): def setUp(self): self.resource = BookResource() self.book = Book.objects.create(name="Some book") self.dataset = tablib.Dataset(headers=["id", "name", "author_email", "price"]) row = [self.book.pk, "Some book", "test@example.com", "10.25"] self.dataset.a...
TestResourceSetup
python
huggingface__transformers
tests/models/grounding_dino/test_modeling_grounding_dino.py
{ "start": 25536, "end": 36850 }
class ____(unittest.TestCase): @cached_property def default_processor(self): return AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-tiny") if is_vision_available() else None def test_inference_object_detection_head(self): model = GroundingDinoForObjectDetection.from_pretrained("...
GroundingDinoModelIntegrationTests
python
getsentry__sentry
tests/sentry/rules/history/backends/test_postgres.py
{ "start": 1640, "end": 10182 }
class ____(BasePostgresRuleHistoryBackendTest): def run_test(self, rule, start, end, expected, cursor=None, per_page=25): result = self.backend.fetch_rule_groups_paginated(rule, start, end, cursor, per_page) assert result.results == expected, (result.results, expected) return result def...
FetchRuleGroupsPaginatedTest
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 104898, "end": 117709 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) autoscale: Optional[AutoScale] = Field( None, description=( "If autoscale, parameters needed in order to automatically scale clusters" ...
ClusterInfo
python
wandb__wandb
wandb/vendor/pygments/lexers/markup.py
{ "start": 16904, "end": 20452 }
class ____(RegexLexer): """ For `Markdown <https://help.github.com/categories/writing-on-github/>`_ markup. .. versionadded:: 2.2 """ name = 'markdown' aliases = ['md'] filenames = ['*.md'] mimetypes = ["text/x-markdown"] flags = re.MULTILINE def _handle_codeblock(self, match):...
MarkdownLexer
python
Unity-Technologies__ml-agents
ml-agents/setup.py
{ "start": 357, "end": 3683 }
class ____(install): """ Custom command to verify that the git tag is the expected one for the release. Originally based on https://circleci.com/blog/continuously-deploying-python-packages-to-pypi-with-circleci/ This differs slightly because our tags and versions are different. """ description ...
VerifyVersionCommand
python
tornadoweb__tornado
tornado/httputil.py
{ "start": 23518, "end": 24460 }
class ____: """Implement this interface to handle requests from `.HTTPServer`. .. versionadded:: 4.0 """ def start_request( self, server_conn: object, request_conn: "HTTPConnection" ) -> "HTTPMessageDelegate": """This method is called by the server when a new request has started. ...
HTTPServerConnectionDelegate