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
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 9542, "end": 9615 }
class ____(HTTPClientError): status_code = 428
HTTPPreconditionRequired
python
davidhalter__jedi
test/refactor/extract_function.py
{ "start": 9256, "end": 9441 }
class ____: def f(): #? 11 text {'new_name': 'ab', 'until_line': 5, 'until_column': 22} return glob1 + 2 # ++++++++++++++++++++++++++++++++++++++++++++++++++ glob1 = 1
X
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/telnet/protocol.py
{ "start": 959, "end": 5584 }
class ____: """ Parser for the Telnet protocol. Usage:: def data_received(data): print(data) def size_received(rows, columns): print(rows, columns) p = TelnetProtocolParser(data_received, size_received) p.feed(binary_data) """ def __init__(...
TelnetProtocolParser
python
jazzband__django-pipeline
tests/tests/test_compressor.py
{ "start": 757, "end": 23206 }
class ____(TestCase): def setUp(self): self.maxDiff = None self.compressor = Compressor() default_collector.collect() def test_js_compressor_class(self): self.assertEqual(self.compressor.js_compressor, YuglifyCompressor) def test_css_compressor_class(self): self.ass...
CompressorTest
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 37057, "end": 42347 }
class ____(Request): """ Get the debug image events for the requested amount of iterations per each task's metric :param metrics: List metrics for which the envents will be retreived :type metrics: Sequence[TaskMetric] :param iters: Max number of latest iterations for which to return debug images ...
DebugImagesRequest
python
mlflow__mlflow
mlflow/genai/judges/utils/__init__.py
{ "start": 3341, "end": 4661 }
class ____(StrEnum): """ A categorical rating for an assessment. Example: .. code-block:: python from mlflow.genai.judges import CategoricalRating from mlflow.entities import Feedback # Create feedback with categorical rating feedback = Feedback( ...
CategoricalRating
python
spyder-ide__spyder
spyder/plugins/run/api.py
{ "start": 4493, "end": 4775 }
class ____(TypedDict): """Run context name schema.""" # CamelCase name of the context. name: str # String identifier for the run context. If non-existent or None, then a # snake_case version of the name is used. identifier: NotRequired[Optional[str]]
Context
python
coleifer__peewee
tests/sqlite.py
{ "start": 4510, "end": 4953 }
class ____(TableFunction): params = ['data'] columns = ['part'] name = 'str_split' def initialize(self, data=None): self._parts = data.split() self._idx = 0 def iterate(self, idx): if self._idx < len(self._parts): result = (self._parts[self._idx],) s...
Split
python
getsentry__sentry
src/sentry/integrations/slack/sdk_client.py
{ "start": 2822, "end": 4203 }
class ____(WebClient, metaclass=MetaClass): def __init__(self, integration_id: int): self.integration_id = integration_id integration: Integration | RpcIntegration | None if SiloMode.get_current_mode() == SiloMode.REGION: """ # In order to send requests, SlackClient ...
SlackSdkClient
python
pytest-dev__pytest
testing/test_doctest.py
{ "start": 562, "end": 28112 }
class ____: def test_collect_testtextfile(self, pytester: Pytester): w = pytester.maketxtfile(whatever="") checkfile = pytester.maketxtfile( test_something=""" alskdjalsdk >>> i = 5 >>> i-1 4 """ ) for x in (pyteste...
TestDoctests
python
xlwings__xlwings
tests/test_sheet.py
{ "start": 1791, "end": 8299 }
class ____(TestBase): def test_name(self): self.wb1.sheets[0].name = "NewName" self.assertEqual(self.wb1.sheets[0].name, "NewName") def test_names(self): self.wb1.sheets[0].range("A1").name = "test1" self.assertEqual(len(self.wb1.sheets[0].names), 0) self.wb1.sheets[0].n...
TestSheet
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_compiler.py
{ "start": 139790, "end": 149740 }
class ____(fixtures.TestBase, AssertsCompiledSQL): """Tests for full text searching""" __dialect__ = postgresql.dialect() def setup_test(self): self.table = Table( "t", MetaData(), Column("id", Integer, primary_key=True), Column("title", String), ...
FullTextSearchTest
python
jackfrued__Python-100-Days
Day31-35/code/example21.py
{ "start": 239, "end": 1606 }
class ____(): """银行账户""" def __init__(self, balance=0): self.balance = balance lock = threading.Lock() self.condition = threading.Condition(lock) def withdraw(self, money): """取钱""" with self.condition: while money > self.balance: self.co...
Account
python
great-expectations__great_expectations
great_expectations/expectations/row_conditions.py
{ "start": 1260, "end": 1568 }
class ____(ValueError): """Raised when the number of conditions exceeds the maximum allowed.""" def __init__(self, count: int, max_conditions: int): super().__init__( f"{max_conditions} conditions is the maximum, but {count} conditions are defined" )
TooManyConditionsError
python
networkx__networkx
networkx/tests/test_convert_numpy.py
{ "start": 175, "end": 19032 }
class ____: def setup_method(self): self.G1 = nx.barbell_graph(10, 3) self.G2 = nx.cycle_graph(10, create_using=nx.DiGraph) self.G3 = self.create_weighted(nx.Graph()) self.G4 = self.create_weighted(nx.DiGraph()) def create_weighted(self, G): g = nx.cycle_graph(4) ...
TestConvertNumpyArray
python
django-haystack__django-haystack
test_haystack/elasticsearch7_tests/test_backend.py
{ "start": 7602, "end": 24955 }
class ____(TestCase): def setUp(self): super().setUp() # Wipe it clean. self.raw_es = elasticsearch.Elasticsearch( settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] ) clear_elasticsearch_index() # Stow. self.old_ui = connections["elasticsearc...
Elasticsearch7SearchBackendTestCase
python
celery__celery
t/unit/tasks/test_stamping.py
{ "start": 1579, "end": 2492 }
class ____(StampingVisitor): def on_signature(self, actual_sig: Signature, **headers) -> dict: return {"on_signature": True} def on_group_start(self, actual_sig: Signature, **headers) -> dict: return {"on_group_start": True} def on_chain_start(self, actual_sig: Signature, **headers) -> dic...
BooleanStampingVisitor
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-dashscope/llama_index/readers/dashscope/domain/lease_domains.py
{ "start": 7952, "end": 10013 }
class ____(DictToObject): def __init__(self, file_id, lease_id, file_name, type, param) -> None: self.file_id = file_id self.lease_id = lease_id self.file_name = file_name self.type = type self.param = param @classmethod def from_dict(cls, data: dict): """ ...
DownloadFileLeaseResult
python
networkx__networkx
networkx/classes/tests/test_digraph_historical.py
{ "start": 123, "end": 3668 }
class ____(HistoricalTests): @classmethod def setup_class(cls): HistoricalTests.setup_class() cls.G = nx.DiGraph def test_in_degree(self): G = self.G() G.add_nodes_from("GJK") G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")]) ass...
TestDiGraphHistorical
python
huggingface__transformers
src/transformers/models/autoformer/modeling_autoformer.py
{ "start": 19188, "end": 29175 }
class ____(nn.Module): """ AutoCorrelation Mechanism with the following two phases: (1) period-based dependencies discovery (2) time delay aggregation This block replace the canonical self-attention mechanism. """ def __init__( self, embed_dim: int, num_heads: int, ...
AutoformerAttention
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/init_ops_test.py
{ "start": 29728, "end": 32225 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testInitializerIdentical(self): for dtype in [dtypes.float32, dtypes.float64]: init1 = init_ops.orthogonal_initializer(seed=1, dtype=dtype) init2 = init_ops.orthogonal_initializer(seed=1, dtype=dtype) self.assertTrue(identicaltest(se...
OrthogonalInitializerTest
python
pytorch__pytorch
test/dynamo/cpython/3_13/typinganndata/_typed_dict_helper.py
{ "start": 620, "end": 684 }
class ____(TypedDict): a: OptionalIntType T = TypeVar("T")
Foo
python
run-llama__llama_index
llama-index-core/tests/program/test_llm_program.py
{ "start": 1194, "end": 2829 }
class ____(BaseModel): __test__ = False hello: str def test_llm_program() -> None: """Test LLM program.""" output_parser = PydanticOutputParser(output_cls=TestModel) llm_program = LLMTextCompletionProgram.from_defaults( output_parser=output_parser, prompt_template_str="This is a te...
TestModel
python
kamyu104__LeetCode-Solutions
Python/shortest-path-visiting-all-nodes.py
{ "start": 62, "end": 784 }
class ____(object): def shortestPathLength(self, graph): """ :type graph: List[List[int]] :rtype: int """ dp = [[float("inf")]*(len(graph)) for _ in xrange(1 << len(graph))] q = collections.deque() for i in xrange(len(graph)): dp[1 <<...
Solution
python
django__django
tests/admin_filters/tests.py
{ "start": 9286, "end": 9411 }
class ____(EmployeeAdmin): list_filter = [DepartmentListFilterLookupWithDynamicValue]
DepartmentFilterDynamicValueBookAdmin
python
google__pytype
pytype/rewrite/frame_test.py
{ "start": 19232, "end": 22081 }
class ____(FrameTestBase): """Test making and calling functions.""" def _make_function(self, code, name): module_frame = self._make_frame(code, name='__main__') module_frame.run() return _get(module_frame, name, _FrameFunction) def _run_until_call(self, code): def cond(frame): return frame...
FunctionTest
python
viewflow__viewflow
viewflow/workflow/migrations/0012_alter_process_data_alter_task_data.py
{ "start": 92, "end": 565 }
class ____(migrations.Migration): dependencies = [ ("viewflow", "0011_alter_task_created_and_more"), ] operations = [ migrations.AlterField( model_name="process", name="data", field=models.JSONField(blank=True, default=dict), ), migrations...
Migration
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 359719, "end": 360159 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("about", "body", "name", "title") about = sgqlc.types.Field(String, graphql_name="about") body = sgqlc.types.Field(String, graphql_name="body") name = sgqlc.types.Field(sg...
IssueTemplate
python
gevent__gevent
src/gevent/_config.py
{ "start": 17817, "end": 17946 }
class ____(AresSettingMixin, Setting): name = 'ares_flags' default = None environment_key = 'GEVENTARES_FLAGS'
AresFlags
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_stackdriver.py
{ "start": 6385, "end": 8082 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook") def test_execute(self, mock_hook): operator = StackdriverListNotificationChannelsOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER) mock_hook.return_value.list_notification_channels.return_value = [ ...
TestStackdriverListNotificationChannelsOperator
python
squidfunk__mkdocs-material
material/plugins/tags/structure/listing/config.py
{ "start": 1492, "end": 4226 }
class ____(Config): """ A listing configuration. """ scope = Type(bool, default = False) """ Whether to only include pages in the current subsection. Enabling this setting will only include pages that are on the same level or on a lower level than the page the listing is on. This allow...
ListingConfig
python
getsentry__sentry
tests/sentry/api/serializers/test_event.py
{ "start": 17532, "end": 25532 }
class ____(TestCase): def test_event_breadcrumb_formatting(self) -> None: event = self.store_event( data={ "breadcrumbs": [ {"category": "generic", "message": "should not format this"}, { "category": "query", ...
SqlFormatEventSerializerTest
python
matplotlib__matplotlib
lib/matplotlib/category.py
{ "start": 4196, "end": 5128 }
class ____(ticker.Formatter): """String representation of the data at every tick.""" def __init__(self, units_mapping): """ Parameters ---------- units_mapping : dict Mapping of category names (str) to indices (int). """ self._units = units_mapping ...
StrCategoryFormatter
python
django-import-export__django-import-export
import_export/exceptions.py
{ "start": 319, "end": 1002 }
class ____(ImportExportError): def __init__(self, error, number=None, row=None): """A wrapper for errors thrown from the import process. :param error: The underlying error that occurred. :param number: The row number of the row containing the error (if obtainable). :param row: The r...
ImportError
python
kamyu104__LeetCode-Solutions
Python/fair-candy-swap.py
{ "start": 37, "end": 366 }
class ____(object): def fairCandySwap(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ diff = (sum(A)-sum(B))//2 setA = set(A) for b in set(B): if diff+b in setA: return [diff+b, b] return...
Solution
python
django__django
tests/model_fields/test_charfield.py
{ "start": 1760, "end": 3853 }
class ____(SimpleTestCase): class Choices(models.TextChoices): C = "c", "C" def test_charfield_raises_error_on_empty_string(self): f = models.CharField() msg = "This field cannot be blank." with self.assertRaisesMessage(ValidationError, msg): f.clean("", None) d...
ValidationTests
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 1935, "end": 2060 }
class ____: 'Used to test self-referential repr() calls' def __repr__(self): return repr(self.value)
ReprWrapper
python
plotly__plotly.py
plotly/express/_special_inputs.py
{ "start": 958, "end": 1300 }
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 be mapped onto integers starting at 0. An optional label can be provided. """ def __init__(self, label=None): ...
Range
python
sympy__sympy
sympy/codegen/fnodes.py
{ "start": 18265, "end": 18363 }
class ____(FFunction): """ Fortran sign intrinsic for integer arguments. """ nargs = 2
isign
python
ray-project__ray
python/ray/data/_internal/datasource/avro_datasource.py
{ "start": 381, "end": 1484 }
class ____(FileBasedDatasource): """A datasource that reads Avro files.""" _FILE_EXTENSIONS = ["avro"] def __init__( self, paths: Union[str, List[str]], **file_based_datasource_kwargs, ): super().__init__(paths, **file_based_datasource_kwargs) _check_import(sel...
AvroDatasource
python
apache__airflow
scripts/ci/prek/lint_json_schema.py
{ "start": 3396, "end": 6137 }
class ____(Exception): pass def load_file(file_path: str): """Loads a file using a serializer which guesses based on the file extension""" if file_path.lower().endswith(".json"): with open(file_path) as input_file: return json.load(input_file) elif file_path.lower().endswith((".yam...
_ValidatorError
python
django__django
tests/view_tests/tests/test_debug.py
{ "start": 1887, "end": 2382 }
class ____(SimpleTestCase): """Unittests for CallableSettingWrapper""" def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(...
CallableSettingWrapperTests
python
redis__redis-py
redis/commands/search/document.py
{ "start": 0, "end": 413 }
class ____: """ Represents a single document in a result set """ def __init__(self, id, payload=None, **fields): self.id = id self.payload = payload for k, v in fields.items(): setattr(self, k, v) def __repr__(self): return f"Document {self.__dict__}" ...
Document
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-openrouter/llama_index/llms/openrouter/base.py
{ "start": 490, "end": 2975 }
class ____(OpenAILike): """ OpenRouter LLM. To instantiate the `OpenRouter` class, you will need to provide an API key. You can set the API key either as an environment variable `OPENROUTER_API_KEY` or directly in the class constructor. If setting it in the class constructor, it would look like this: ...
OpenRouter
python
pytorch__pytorch
torch/_dynamo/utils.py
{ "start": 144825, "end": 161611 }
class ____: # inclusive left_end_lineno: int left_end_offset: int right_start_lineno: int # exclusive right_start_offset: int def _extract_anchors_from_expr(segment: str) -> Optional[_Anchors]: """ Given source code `segment` corresponding to a bytecode instruction, determine: ...
_Anchors
python
mlflow__mlflow
mlflow/entities/param.py
{ "start": 129, "end": 1133 }
class ____(_MlflowObject): """ Parameter object. """ def __init__(self, key, value): if "pyspark.ml" in sys.modules: import pyspark.ml.param if isinstance(key, pyspark.ml.param.Param): key = key.name value = str(value) self._key =...
Param
python
sanic-org__sanic
sanic/response/types.py
{ "start": 689, "end": 7427 }
class ____: """The base class for all HTTP Responses""" __slots__ = ( "asgi", "body", "content_type", "stream", "status", "headers", "_cookies", ) _dumps = json_dumps def __init__(self): self.asgi: bool = False self.body: Opt...
BaseHTTPResponse
python
pytorch__pytorch
test/functorch/test_vmap.py
{ "start": 145280, "end": 194136 }
class ____(TestCase): def vmap_outplace_test( self, func, args, kwargs, in_dims, check_shape_only=False, postprocess_fn=None, out_dim=0, ): for vmap_out, loop_out in compute_quantities_for_vmap_test( func, args, kwargs, in_dims,...
TestVmapOperatorsOpInfo
python
getsentry__sentry
src/sentry/replays/endpoints/project_replay_details.py
{ "start": 814, "end": 1185 }
class ____(ProjectPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin"], "POST": ["project:write", "project:admin"], "PUT": ["project:write", "project:admin"], "DELETE": ["project:read", "project:write", "project:admin"], } @region_silo_endpoint @...
ReplayDetailsPermission
python
catalyst-team__catalyst
catalyst/contrib/datasets/mnist.py
{ "start": 11270, "end": 12958 }
class ____(MNIST): """Partial MNIST dataset. Args: num_samples: number of examples per selected class/digit. default: 100 classes: list selected MNIST classes. default: (0, 1, 2) **kwargs: MNIST parameters Examples: >>> dataset = PartialMNIST(".", download=True) >>>...
PartialMNIST
python
ansible__ansible
test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py
{ "start": 747, "end": 1583 }
class ____(CallbackBase): CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'aggregate' CALLBACK_NAME = 'display_resolved_action' CALLBACK_NEEDS_ENABLED = True def __init__(self, *args, **kwargs): super(CallbackModule, self).__init__(*args, **kwargs) def v2_playbook_on_task_start(self, task, is_...
CallbackModule
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/knowledge_base/base.py
{ "start": 146, "end": 6053 }
class ____(BaseReader): """ Knowledge base reader. Crawls and reads articles from a knowledge base/help center with Playwright. Tested on Zendesk and Intercom CMS, may work on others. Can be run in headless mode but it may be blocked by Cloudflare. Run it headed to be safe. Times out occasional...
KnowledgeBaseWebReader
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 155434, "end": 161421 }
class ____(Request): """ Get raw data for a specific metric variants in the task :param task: Task ID :type task: str :param metric: Metric and variants for which to return data points :type metric: MetricVariants :param key: Array of x axis to return. Supported values: iter - iteration ...
ScalarMetricsIterRawRequest
python
kamyu104__LeetCode-Solutions
Python/design-phone-directory.py
{ "start": 145, "end": 1510 }
class ____(object): def __init__(self, maxNumbers): """ Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. :type maxNumbers: int """ self.__curr = 0 self.__numbers = range(maxNumbers) ...
PhoneDirectory
python
eth-brownie__brownie
brownie/_cli/console.py
{ "start": 14155, "end": 22959 }
class ____(AutoSuggest): """ AutoSuggest subclass to display contract input hints. If an object has an `_autosuggest` method, it is used to build the suggestion. Otherwise, names and default values are pulled from `__code__` and `__defaults__` respectively. """ def __init__(self, console, ...
ConsoleAutoSuggest
python
fsspec__filesystem_spec
fsspec/implementations/libarchive.py
{ "start": 2362, "end": 7098 }
class ____(AbstractArchiveFileSystem): """Compressed archives as a file-system (read-only) Supports the following formats: tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar Microsoft CAB, 7-Zip, WARC See the libarchive documentation for further restrictions. https://www.li...
LibArchiveFileSystem
python
realpython__materials
dwitter-part-1/source_code_final/dwitter/admin.py
{ "start": 115, "end": 179 }
class ____(admin.StackedInline): model = Profile
ProfileInline
python
getsentry__sentry
src/sentry/dynamic_sampling/models/projects_rebalancing.py
{ "start": 295, "end": 477 }
class ____(ModelInput): classes: list[RebalancedItem] sample_rate: float def validate(self) -> bool: return 0.0 <= self.sample_rate <= 1.0
ProjectsRebalancingInput
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 46419, "end": 47728 }
class ____(Tap, RegionSelectTool): ''' *toolbar icon*: |poly_select_icon| The polygon selection tool allows users to make selections on a Plot by indicating a polygonal region with mouse clicks. single clicks (or taps) add successive points to the definition of the polygon, and a press click (or ta...
PolySelectTool
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP042.py
{ "start": 24, "end": 50 }
class ____(str, Enum): ...
A
python
py-pdf__pypdf
tests/test_protocols.py
{ "start": 89, "end": 411 }
class ____(PdfObjectProtocol): pass def test_pdfobjectprotocol(): o = IPdfObjectProtocol() assert o.clone(None, False, None) is None assert o._reference_clone(None, None) is None assert o.get_object() is None assert o.hash_value() is None assert o.write_to_stream(None) is None
IPdfObjectProtocol
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/scheduler.py
{ "start": 7463, "end": 10951 }
class ____(Scheduler, ConfigurableClass): """Default scheduler implementation that submits runs from the long-lived ``dagster-daemon`` process. Periodically checks each running schedule for execution times that don't yet have runs and launches them. """ def __init__( self, max_catch...
DagsterDaemonScheduler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/session.py
{ "start": 50079, "end": 186465 }
class ____(_SessionClassMethods, EventTarget): """Manages persistence operations for ORM-mapped objects. The :class:`_orm.Session` is **not safe for use in concurrent threads.**. See :ref:`session_faq_threadsafe` for background. The Session's usage paradigm is described at :doc:`/orm/session`. "...
Session
python
ray-project__ray
doc/source/ray-core/doc_code/runtime_env_example.py
{ "start": 1019, "end": 1208 }
class ____: def g(self): pass ray.get(f_job.remote()) a = Actor_job.remote() ray.get(a.g.remote()) ray.shutdown() ray.init() @ray.remote def f(): pass @ray.remote
Actor_job
python
plotly__plotly.py
plotly/graph_objs/histogram/selected/_marker.py
{ "start": 233, "end": 3021 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram.selected" _path_str = "histogram.selected.marker" _valid_props = {"color", "opacity"} @property def color(self): """ Sets the marker color of selected points. The 'color' property is a color and may be speci...
Marker
python
walkccc__LeetCode
solutions/3500. Minimum Cost to Divide Array Into Subarrays/3500.py
{ "start": 0, "end": 588 }
class ____: def minimumCost(self, nums: list[int], cost: list[int], k: int) -> int: n = len(nums) prefixNums = list(itertools.accumulate(nums, initial=0)) prefixCost = list(itertools.accumulate(cost, initial=0)) # dp[i] := the minimum cost to divide nums[i..n - 1] into subarrays dp = [math.inf] * ...
Solution
python
getsentry__sentry
src/sentry/replays/models.py
{ "start": 783, "end": 1470 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Excluded range_start = models.DateTimeField() range_end = models.DateTimeField() environments = ArrayField(models.TextField(), default=list) organization_id = BoundedBigIntegerField(db_index=True) project_id = BoundedBigInte...
ReplayDeletionJobModel
python
walkccc__LeetCode
solutions/1186. Maximum Subarray Sum with One Deletion/1186-2.py
{ "start": 0, "end": 318 }
class ____: # Similar to 53. Maximum Subarray def maximumSum(self, arr: list[int]) -> int: ans = -math.inf zero = -math.inf # no deletion one = -math.inf # <= 1 deletion for a in arr: one = max(a, one + a, zero) zero = max(a, zero + a) ans = max(ans, one) return ans
Solution
python
Textualize__textual
src/textual/css/_style_properties.py
{ "start": 30366, "end": 31522 }
class ____: """Descriptor for getting and setting name properties.""" def __set_name__(self, owner: StylesBase, name: str) -> None: self.name = name def __get__(self, obj: StylesBase, objtype: type[StylesBase] | None) -> str: """Get the name property. Args: obj: The ``...
NameProperty
python
apache__airflow
providers/apache/kafka/tests/unit/apache/kafka/hooks/test_base.py
{ "start": 1395, "end": 3826 }
class ____: @mock.patch(f"{BASEHOOK_PATCH_PATH}.get_connection") def test_get_conn(self, mock_get_connection, hook): config = {"bootstrap.servers": MagicMock()} mock_get_connection.return_value.extra_dejson = config assert hook.get_conn == config @mock.patch(f"{BASEHOOK_PATCH_PATH}....
TestKafkaBaseHook
python
numba__numba
numba/core/compiler_machinery.py
{ "start": 2704, "end": 2828 }
class ____(CompilerPass): """ Base class for analysis passes (no modification made to state) """ pass
AnalysisPass
python
kamyu104__LeetCode-Solutions
Python/digit-count-in-range.py
{ "start": 32, "end": 617 }
class ____(object): def digitsCount(self, d, low, high): """ :type d: int :type low: int :type high: int :rtype: int """ def digitsCount(n, k): pivot, result = 1, 0 while n >= pivot: result += (n//(10*pivot))*pivot + \ ...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/workers/cloud_run.py
{ "start": 8937, "end": 20943 }
class ____(BaseJobConfiguration): """ Configuration class used by the Cloud Run Worker to create a Cloud Run Job. An instance of this class is passed to the Cloud Run worker's `run` method for each flow run. It contains all information necessary to execute the flow run as a Cloud Run Job. Attr...
CloudRunWorkerJobConfiguration
python
getsentry__sentry
tests/sentry/notifications/notification_action/metric_alert_registry/test_sentry_app_metric_alert_handler.py
{ "start": 1226, "end": 8679 }
class ____(MetricAlertHandlerBase): def setUp(self) -> None: super().setUp() self.sentry_app = self.create_sentry_app( name="foo", organization=self.organization, is_alertable=True, verify_install=False, ) self.action = self.create_acti...
TestSentryAppMetricAlertHandler
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 26293, "end": 26416 }
class ____(Exception): """ Exception to indicate that the FxGraphCache should be bypassed. """
BypassFxGraphCache
python
apache__airflow
airflow-ctl/src/airflowctl/api/client.py
{ "start": 2935, "end": 6374 }
class ____: """Credentials for the API.""" api_url: str | None api_token: str | None api_environment: str def __init__( self, api_url: str | None = None, api_token: str | None = None, client_kind: ClientKind | None = None, api_environment: str = "production"...
Credentials
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column.py
{ "start": 86872, "end": 88680 }
class ____( _DenseColumn, collections.namedtuple( '_NumericColumn', ['key', 'shape', 'default_value', 'dtype', 'normalizer_fn'])): """see `numeric_column`.""" @property def name(self): return self.key @property def _parse_example_spec(self): return { self.key: ...
_NumericColumn
python
gevent__gevent
src/gevent/tests/test__all__.py
{ "start": 2236, "end": 11547 }
class ____(object): modname = None stdlib_has_all = False stdlib_all = None stdlib_name = None stdlib_module = None @classmethod def setUpClass(cls): modname = cls.modname if modname.endswith(PLATFORM_SPECIFIC_SUFFIXES): raise unittest.SkipTest("Module %s is plat...
AbstractTestMixin
python
psf__black
tests/data/cases/preview_long_strings__regression.py
{ "start": 1993, "end": 2559 }
class ____: def disappearing_comment(): return ( ( # xx -x xxxxxxx xx xxx xxxxxxx. '{{xxx_xxxxxxxxxx_xxxxxxxx}} xxx xxxx' ' {} {{xxxx}} >&2' .format( "{xxxx} {xxxxxx}" if xxxxx.xx_xxxxxxxxxx ...
A
python
django__django
tests/custom_lookups/tests.py
{ "start": 6234, "end": 6903 }
class ____(models.lookups.Lookup): """ InMonth matches if the column's month is the same as value's month. """ lookup_name = "inmonth" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, conne...
InMonth
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_deprecation.py
{ "start": 632, "end": 812 }
class ____(MockClass1): """Inherit from deprecated class but does not call super().__init__.""" def __init__(self, a): self.a = a @deprecated("a message")
MockClass5
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 227315, "end": 227661 }
class ____(VegaLiteSchema): """ConditionalPredicateValueDefnumberArraynullExprRef schema wrapper.""" _schema = { "$ref": "#/definitions/ConditionalPredicate<(ValueDef<(number[]|null)>|ExprRef)>" } def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ConditionalPredicateValueDefnumberArraynullExprRef
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 1316, "end": 3385 }
class ____(enum.IntEnum): HasGil = 0 NoGil = 1 # For 'cdef func() nogil:' functions, as the GIL may be held while # calling this function (thus contained 'nogil' blocks may be valid). NoGilScope = 2 def relative_position(pos): return (pos[0].get_filenametable_entry(), pos[1]) def embed_posit...
NoGilState
python
scikit-learn__scikit-learn
sklearn/linear_model/_stochastic_gradient.py
{ "start": 75040, "end": 93800 }
class ____(OutlierMixin, BaseSGD): """Solves linear One-Class SVM using Stochastic Gradient Descent. This implementation is meant to be used with a kernel approximation technique (e.g. `sklearn.kernel_approximation.Nystroem`) to obtain results similar to `sklearn.svm.OneClassSVM` which uses a Gaussian ...
SGDOneClassSVM
python
simonw__sqlite-utils
sqlite_utils/db.py
{ "start": 4302, "end": 5839 }
class ____: pass DEFAULT = Default() COLUMN_TYPE_MAPPING = { float: "REAL", int: "INTEGER", bool: "INTEGER", str: "TEXT", dict: "TEXT", tuple: "TEXT", list: "TEXT", bytes.__class__: "BLOB", bytes: "BLOB", memoryview: "BLOB", datetime.datetime: "TEXT", datetime.date...
Default
python
ZoranPandovski__al-go-rithms
games/Python/paddleball.py
{ "start": 1831, "end": 3535 }
class ____: """This is the user controlled paddle class.""" def __init__(self, canvas, color): self.canvas = canvas #canvas = var with functions inside self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color) #creating paddle self.canvas.move(self.id, 200, 300) self.x = 0 ...
Paddle
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 2300, "end": 2734 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) month = indexes.CharField(indexed=False) pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel def prepare_text(self, obj): return "Indexed!\n%s" % ob...
WhooshMaintainTypeMockSearchIndex
python
kamyu104__LeetCode-Solutions
Python/maximum-product-after-k-increments.py
{ "start": 1308, "end": 1699 }
class ____(object): def maximumProduct(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ MOD = 10**9+7 min_heap = nums heapq.heapify(min_heap) while k: heapq.heappush(min_heap, heapq.heappop(min_heap)+1) ...
Solution3
python
ipython__ipython
tests/test_interactivshell.py
{ "start": 4870, "end": 7576 }
class ____(unittest.TestCase): def rl_hist_entries(self, rl, n): """Get last n readline history entries as a list""" return [ rl.get_history_item(rl.get_current_history_length() - x) for x in range(n - 1, -1, -1) ] @mock_input def test_inputtransformer_syntax...
InteractiveShellTestCase
python
fluentpython__example-code
01-data-model/vector2d.py
{ "start": 24, "end": 509 }
class ____: def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def __add__(self, other): x =...
Vector
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 19386, "end": 19726 }
class ____(GroupType): type_id = 2002 slug = "profile_image_decode_main_thread" description = "Image Decoding on Main Thread" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.MOBILE.value default_priority = PriorityLevel.LOW released = True @dataclass(frozen=True)
ProfileImageDecodeGroupType
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_date04.py
{ "start": 342, "end": 2116 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_date04.xlsx") self.ignore_elements = {"xl/charts/chart1.xml": ["<c:formatCode"]} def test_create_file(self): """Test the cre...
TestCompareXLSXFiles
python
openai__openai-python
src/openai/types/beta/threads/text_content_block_param.py
{ "start": 221, "end": 407 }
class ____(TypedDict, total=False): text: Required[str] """Text content to be sent to the model""" type: Required[Literal["text"]] """Always `text`."""
TextContentBlockParam
python
ansible__ansible
test/integration/targets/no_log/action_plugins/action_sets_no_log.py
{ "start": 84, "end": 319 }
class ____(ActionBase): def run(self, tmp=None, task_vars=None): return dict(changed=False, failed=False, msg="action result should be masked", _ansible_no_log="yeppers") # ensure that a truthy non-bool works here
ActionModule
python
mlflow__mlflow
tests/db/test_schema.py
{ "start": 998, "end": 4695 }
class ____(NamedTuple): table: str columns: str _CREATE_TABLE_REGEX = re.compile( r""" CREATE TABLE (?P<table>\S+?) \( (?P<columns>.+?) \) """.strip(), flags=re.DOTALL, ) def parse_create_tables(schema): return [ _CreateTable( table=m.group("table"), columns=set(m...
_CreateTable
python
huggingface__transformers
src/transformers/models/stablelm/modeling_stablelm.py
{ "start": 35218, "end": 35324 }
class ____(GenericForSequenceClassification, StableLmPreTrainedModel): ...
StableLmForSequenceClassification
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v1.py
{ "start": 1354, "end": 5618 }
class ____(object): """Abstract optimizer base class. Note: this is the parent class of all optimizers, not an actual optimizer that can be used for training models. All Keras optimizers support the following keyword arguments: clipnorm: float >= 0. Gradients will be clipped when their L2 nor...
Optimizer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 5688, "end": 5897 }
class ____(ArgumentError): """raised when a constraint refers to a string column name that is not present in the table being constrained. .. versionadded:: 2.0 """
ConstraintColumnNotFoundError
python
cython__cython
tests/run/ext_auto_richcmp.py
{ "start": 307, "end": 1443 }
class ____(X): """ >>> a = ClassEq(1) >>> b = ClassEq(2) >>> c = ClassEq(1) >>> a == a True >>> a != a False >>> a == b False >>> a != b True >>> a == c True >>> a != c False >>> b == c False >>> b != c True >>> c == a True ...
ClassEq
python
walkccc__LeetCode
solutions/846. Hand of Straights/846.py
{ "start": 0, "end": 351 }
class ____: def isNStraightHand(self, hand: list[int], groupSize: int) -> bool: count = collections.Counter(hand) for start in sorted(count): value = count[start] if value > 0: for i in range(start, start + groupSize): count[i] -= value if count[i] < 0: ret...
Solution