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
pypa__setuptools
setuptools/_vendor/backports/tarfile/__init__.py
{ "start": 11195, "end": 19391 }
class ____: """Class that serves as an adapter between TarFile and a stream-like object. The stream-like object only needs to have a read() or write() method that works with bytes, and the method is accessed blockwise. Use of gzip or bzip2 compression is possible. A stream-like o...
_Stream
python
django__django
django/forms/widgets.py
{ "start": 7982, "end": 8311 }
class ____(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class
MediaDefiningClass
python
django__django
tests/admin_changelist/models.py
{ "start": 227, "end": 301 }
class ____(models.Model): name = models.CharField(max_length=128)
Parent
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 54138, "end": 54346 }
class ____(IPredicate): def __call__(context, request): """ Return ``True`` if the view should be selected for the given arguments or ``False`` otherwise. """
IViewPredicate
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 448, "end": 764 }
class ____(BaseModel): a: int """ ) m = module.Model(a='123') assert m.model_dump() == {'a': 123} def test_postponed_annotations_auto_model_rebuild(create_module): module = create_module( # language=Python """ from __future__ import annotations from pydantic import BaseModel
Model
python
ray-project__ray
python/ray/train/v2/tests/util.py
{ "start": 2944, "end": 3907 }
class ____(ScalingPolicy): def __init__(self, scaling_config): self._recovery_decision_queue = [] self._monitor_decision_queue = [] super().__init__(scaling_config) def make_decision_for_non_running_worker_group(self) -> ScalingDecision: if self._recovery_decision_queue: ...
MockScalingPolicy
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_finetuning_callback.py
{ "start": 10524, "end": 10870 }
class ____(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv = nn.Conv2d(in_channels, out_channels, 3) self.act = nn.ReLU() self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.conv(x) x = self.act(x) ...
ConvBlock
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_math.py
{ "start": 9227, "end": 9365 }
class ____(object): def __init__(self, value): self.value = value def __index__(self): return self.value
MyIndexable
python
google__jax
tests/jaxpr_effects_test.py
{ "start": 28802, "end": 35775 }
class ____(jtu.JaxTestCase): def test_simple_jaxpr_input_effect(self): def f(x, y): input_effect(x, y, index=0) jaxpr = jax.make_jaxpr(f)(0, 1) self.assertIn(InputEffect(0), jaxpr.effects) def test_jaxpr_input_effect_is_tracked_by_index_properly(self): def f(x, y): input_effect(y, x, i...
JaxprInputEffectTest
python
kamyu104__LeetCode-Solutions
Python/pseudo-palindromic-paths-in-a-binary-tree.py
{ "start": 771, "end": 1204 }
class ____(object): def pseudoPalindromicPaths (self, root): """ :type root: TreeNode :rtype: int """ def dfs(node, count): if not root: return 0 count ^= 1 << (node.val-1) return int(node.left == node.right and count&(count...
Solution2
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 43610, "end": 53669 }
class ____(CompoundRequest): """ Adds a single event :param model_event: If set then the event is for a model. Otherwise for a task. Cannot be used with task log events. If used in batch then all the events should be marked the same :type model_event: bool :param allow_locked: Allow...
AddRequest
python
pytorch__pytorch
torch/distributed/_shard/metadata.py
{ "start": 198, "end": 2215 }
class ____: """ Represents a shard of the overall Tensor including its offsets, lengths and device placement. Args: shard_offsets(List[int]): Offsets in the original tensor indicating the start offsets for this shard. Should have the same rank as the original tensor. ...
ShardMetadata
python
bokeh__bokeh
src/bokeh/core/types.py
{ "start": 2471, "end": 2566 }
class ____(RectGeometry): x0: float x1: float y0: float y1: float
RectGeometryData
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 60956, "end": 61596 }
class ____(legend_position_inside): """ Location of legend Parameters ---------- theme_element : Literal["right", "left", "top", "bottom", "inside"] | \ tuple[float, float] | Literal["none"] Where to put the legend. Along the edge or inside the panels. If "insid...
legend_position
python
PyCQA__pylint
tests/functional/r/redundant_unittest_assert.py
{ "start": 1284, "end": 1434 }
class ____(unittest.TestCase): '''Don't fail if the bound method doesn't have arguments.''' def test(self): self.run()
RegressionWithArgs
python
getsentry__sentry
tests/sentry/dynamic_sampling/test_utils.py
{ "start": 1501, "end": 2069 }
class ____(TestCase): def test_no_org(self) -> None: assert not has_dynamic_sampling(None) def test_positive(self) -> None: org1 = self.create_organization("test-org") with self.feature("organizations:dynamic-sampling-custom"): assert has_custom_dynamic_sampling(org1) d...
HasCustomDynamicSamplingTestCase
python
ansible__ansible
lib/ansible/cli/galaxy.py
{ "start": 5421, "end": 5940 }
class ____: _api: t.Union[GalaxyAPI, None] api_servers: list[GalaxyAPI] @property def api(self): if self._api: return self._api for server in self.api_servers: try: if u'v1' in server.available_api_versions: self._api = server...
RoleDistributionServer
python
ray-project__ray
python/ray/_private/ray_experimental_perf.py
{ "start": 580, "end": 10945 }
class ____: def echo(self, x): return x def echo_multiple(self, *x): return x def check_optimized_build(): if not ray._raylet.OPTIMIZED: msg = ( "WARNING: Unoptimized build! " "To benchmark an optimized build, try:\n" "\tbazel run -c opt //:gen_...
DAGActor
python
pytorch__pytorch
test/dynamo/test_dicts.py
{ "start": 51202, "end": 51279 }
class ____(DictMethodsTests): thetype = SimpleDict
DictSubclassMethodsTests
python
modin-project__modin
modin/tests/core/storage_formats/pandas/test_internals.py
{ "start": 60820, "end": 85526 }
class ____: """Test ``ModinDtypes`` and ``DtypesDescriptor`` classes.""" schema = pandas.Series( { "a": np.dtype("int64"), "b": np.dtype(float), "c": np.dtype(bool), "d": np.dtype(bool), "e": np.dtype("object"), } ) def get_co...
TestModinDtypes
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/compute.py
{ "start": 1731, "end": 1872 }
class ____: """Class with GCE operations statuses.""" PENDING = "PENDING" RUNNING = "RUNNING" DONE = "DONE"
GceOperationStatus
python
catalyst-team__catalyst
catalyst/metrics/_ndcg.py
{ "start": 135, "end": 5012 }
class ____(TopKMetric): """ Calculates the Normalized discounted cumulative gain (NDCG) score given model outputs and targets The precision metric summarizes the fraction of relevant items Computes mean value of NDCG and it's approximate std value Args: topk: list of `topk` for ndcg@top...
NDCGMetric
python
Textualize__textual
src/textual/document/_document.py
{ "start": 569, "end": 1601 }
class ____: """Contains information about an edit that has occurred.""" end_location: Location """The new end Location after the edit is complete.""" replaced_text: str """The text that was replaced.""" @lru_cache(maxsize=1024) def _utf8_encode(text: str) -> bytes: """Encode the input text as...
EditResult
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external.py
{ "start": 16945, "end": 25268 }
class ____(RepresentedJob, LoadableBy[JobSubsetSelector, "BaseWorkspaceRequestContext"]): """RemoteJob is a object that represents a loaded job definition that is resident in another process or container. Host processes such as dagster-webserver use objects such as these to interact with user-defined artifa...
RemoteJob
python
joerick__pyinstrument
pyinstrument/renderers/speedscope.py
{ "start": 797, "end": 949 }
class ____(Enum): """Enum representing the only two types of speedscope frame events""" OPEN = "O" CLOSE = "C" @dataclass
SpeedscopeEventType
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/activation_functions.py
{ "start": 533, "end": 694 }
class ____(): def __call__(self, x): return 2 / (1 + np.exp(-2*x)) - 1 def gradient(self, x): return 1 - np.power(self.__call__(x), 2)
TanH
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/base.py
{ "start": 3658, "end": 3789 }
class ____(Enum): NO_ARG = 0 def __repr__(self): return f"_NoArg.{self.name}" NO_ARG: Final = _NoArg.NO_ARG
_NoArg
python
pytorch__pytorch
torch/distributed/checkpoint/_experimental/barriers.py
{ "start": 933, "end": 2949 }
class ____: """ Configuration for barrier construction. This class provides a flexible way to configure different barrier implementations with their specific constructor arguments. The barrier type will be looked up from a registry and instantiated with rank_info and barrier_args. Attributes: ...
BarrierConfig
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 100603, "end": 101086 }
class ____(Structure): _fields_ = [("device", c_nvmlDevice_t), ("gpuInstance", c_nvmlGpuInstance_t), ("id", c_uint), ("profileId", c_uint), ("placement", c_nvmlComputeInstancePlacement_t) ] NVML_MAX_GPU_UTILIZATIONS = 8 NVML_GPU_UTILIZA...
c_nvmlComputeInstanceInfo_t
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 388205, "end": 390871 }
class ____(Response): """ Response of tasks.started endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict :param started: Number of tasks started (0 or 1) :type started: int """ _service =...
StartedResponse
python
python-excel__xlrd
xlrd/sheet.py
{ "start": 103776, "end": 106806 }
class ____(BaseObject): """ Height and default formatting information that applies to a row in a sheet. Derived from ``ROW`` records. .. versionadded:: 0.6.1 """ if _USE_SLOTS: __slots__ = ( "height", "has_default_height", "outline_level", ...
Rowinfo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 510041, "end": 531979 }
class ____(sgqlc.types.Type): """A contributions collection aggregates contributions such as opened issues and commits created by a user. """ __schema__ = github_schema __field_names__ = ( "commit_contributions_by_repository", "contribution_calendar", "contribution_years", ...
ContributionsCollection
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 540018, "end": 540347 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("PullRequestReview", graphql_name="node")
PullRequestReviewEdge
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 638, "end": 898 }
class ____(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") history = HistoricalRecords() def get_absolute_url(self): return reverse("poll-detail", kwargs={"pk": self.pk})
Poll
python
plotly__plotly.py
plotly/graph_objs/scattermap/_textfont.py
{ "start": 233, "end": 5819 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattermap" _path_str = "scattermap.textfont" _valid_props = {"color", "family", "size", "style", "weight"} @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g....
Textfont
python
langchain-ai__langchain
libs/core/langchain_core/load/serializable.py
{ "start": 1065, "end": 2203 }
class ____(BaseSerialized): """Serialized not implemented.""" type: Literal["not_implemented"] """The type of the object. Must be `'not_implemented'`.""" repr: str | None """The representation of the object.""" def try_neq_default(value: Any, key: str, model: BaseModel) -> bool: """Try to det...
SerializedNotImplemented
python
ray-project__ray
python/ray/train/v2/_internal/exceptions.py
{ "start": 3935, "end": 5290 }
class ____(CollectiveTimeoutError): """Exception raised when the broadcast operation times out. There are two main timeout examples: 1. If not all workers call `ray.train.report`, the entire worker group will hang until the timeout before raising. This prevents indefinite worker group hangs...
BroadcastCollectiveTimeoutError
python
Textualize__textual
src/textual/css/errors.py
{ "start": 490, "end": 544 }
class ____(TokenError): pass
UnresolvedVariableError
python
getsentry__sentry
src/sentry/rules/conditions/event_attribute.py
{ "start": 2910, "end": 6937 }
class ____(EventCondition): """ Attributes are a mapping of <logical-key>.<property>. For example: - message - platform - exception.{type,value} - user.{id,ip_address,email,FIELD} - http.{method,url} - stacktrace.{code,module,filename,abs_path,package} - extra.{FIELD} """ ...
EventAttributeCondition
python
pandas-dev__pandas
pandas/tests/indexes/categorical/test_indexing.py
{ "start": 7337, "end": 11558 }
class ____: def test_get_indexer_base(self): # Determined by cat ordering. idx = CategoricalIndex(list("cab"), categories=list("cab")) expected = np.arange(len(idx), dtype=np.intp) actual = idx.get_indexer(idx) tm.assert_numpy_array_equal(expected, actual) with pyte...
TestGetIndexer
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_run.py
{ "start": 1870, "end": 2202 }
class ____(StrictBaseModel): """DAG Run serializer for clear endpoint body.""" dry_run: bool = True only_failed: bool = False run_on_latest_version: bool = Field( default=False, description="(Experimental) Run on the latest bundle version of the Dag after clearing the Dag Run.", ) ...
DAGRunClearBody
python
lxml__lxml
src/lxml/html/tests/test_html5parser.py
{ "start": 13707, "end": 14023 }
class ____: def __init__(self, tag='tag', tail=None): self.tag = tag self.tail = tail def xhtml_tag(tag): return '{%s}%s' % (XHTML_NAMESPACE, tag) XHTML_TEST_DOCUMENT = ''' <!DOCTYPE html> <html> <head><title>TITLE</title></head> <body></body> </html> '''
DummyElement
python
django__django
django/db/models/fields/files.py
{ "start": 13757, "end": 14864 }
class ____(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.attname) sup...
ImageFileDescriptor
python
encode__django-rest-framework
tests/test_relations_pk.py
{ "start": 744, "end": 901 }
class ____(serializers.ModelSerializer): class Meta: model = ForeignKeyTarget fields = ('id', 'name', 'sources')
ForeignKeyTargetSerializer
python
pytorch__pytorch
test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py
{ "start": 3209, "end": 3606 }
class ____(TestCase): def test_repr(self) -> None: desc = _NodeDesc("dummy_fqdn", 3, 5) self.assertEqual(repr(desc), "dummy_fqdn_3_5") def test_hash(self) -> None: desc1 = _NodeDesc("dummy_fqdn", 2, 4) desc2 = _NodeDesc("dummy_fqdn", 3, 5) descs = {desc1, desc2} ...
NodeDescTest
python
scikit-learn__scikit-learn
examples/neighbors/approximate_nearest_neighbors.py
{ "start": 1510, "end": 11351 }
class ____(TransformerMixin, BaseEstimator): """Wrapper for using nmslib as sklearn's KNeighborsTransformer""" def __init__(self, n_neighbors=5, metric="euclidean", method="sw-graph", n_jobs=-1): self.n_neighbors = n_neighbors self.method = method self.metric = metric self.n_job...
NMSlibTransformer
python
ray-project__ray
python/ray/autoscaler/v2/instance_manager/node_provider.py
{ "start": 2662, "end": 3722 }
class ____(CloudInstanceProviderError): # The node type that failed to launch. node_type: NodeType # Number of nodes that failed to launch. count: int # A unique id that identifies from which update request the error originates. request_id: str def __init__( self, node_type:...
LaunchNodeError
python
davidhalter__parso
parso/pgen2/grammar_parser.py
{ "start": 415, "end": 729 }
class ____: def __init__(self, next_: 'NFAState', nonterminal_or_string: Optional[str]): self.next: NFAState = next_ self.nonterminal_or_string: Optional[str] = nonterminal_or_string def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.nonterminal_or_string)
NFAArc
python
django__django
tests/forms_tests/tests/test_renderers.py
{ "start": 1103, "end": 1245 }
class ____(SharedTests, SimpleTestCase): renderer = DjangoTemplates @unittest.skipIf(jinja2 is None, "jinja2 required")
DjangoTemplatesTests
python
pytorch__pytorch
torch/_inductor/codegen/memory_planning.py
{ "start": 11223, "end": 14718 }
class ____: """ Represents a pool of allocations that will be generated by a single call to torch.empty. """ device: torch.device root: TemporalSplit can_expand: bool = True restrict_live_range: Optional[LiveRange] = None name: Optional[str] = None names_to_del: list[str] = data...
AllocationPool
python
ansible__ansible
lib/ansible/utils/collection_loader/_collection_finder.py
{ "start": 1783, "end": 4092 }
class ____: """Class that implements the ``importlib.resources.abc.Traversable`` interface for the following ``ansible_collections`` namespace packages:: * ``ansible_collections`` * ``ansible_collections.<namespace>`` These namespace packages operate differently from a normal Python namespace ...
_AnsibleNSTraversable
python
chroma-core__chroma
chromadb/api/configuration.py
{ "start": 677, "end": 937 }
class ____(Protocol): """Represents an abstract parameter validator.""" @abstractmethod def __call__(self, value: ParameterValue) -> bool: """Returns whether the given value is valid.""" raise NotImplementedError()
ParameterValidator
python
doocs__leetcode
solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution3.py
{ "start": 0, "end": 234 }
class ____: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: x = gcd(*numsDivide) y = min((v for v in nums if x % v == 0), default=0) return sum(v < y for v in nums) if y else -1
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/base_insight_streams.py
{ "start": 1130, "end": 19006 }
class ____(FBMarketingIncrementalStream): """doc: https://developers.facebook.com/docs/marketing-api/insights""" cursor_field = "date_start" ALL_ACTION_ATTRIBUTION_WINDOWS = [ "1d_click", "7d_click", "28d_click", "1d_view", "7d_view", "28d_view", ] ...
AdsInsights
python
pytorch__pytorch
torchgen/_autoheuristic/mixed_mm/test_mixed_mm.py
{ "start": 9425, "end": 16897 }
class ____(LearnedHeuristicDecision): def __init__(self) -> None: self.choices: list[Choice] = [] self.fill_choices() def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: return ( metadata.name == self.get_name() and metadata.shared_m...
MixedMMH100
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 21646, "end": 21726 }
class ____(CsvItemExporter, FromCrawlerMixin): pass
FromCrawlerCsvItemExporter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py
{ "start": 11335, "end": 11769 }
class ____(ProjectCategories, GeneratorMixin): """ https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-project-categories/#api-rest-api-3-projectcategory-post """ def generate(self): for index in range(10): payload = json.dumps({"name": f"Test category {index}", "d...
ProjectCategoriesGenerator
python
weaviate__weaviate-python-client
weaviate/collections/aggregations/near_text/async_.py
{ "start": 195, "end": 262 }
class ____(_NearTextExecutor[ConnectionAsync]): pass
_NearTextAsync
python
hynek__structlog
src/structlog/processors.py
{ "start": 1381, "end": 2894 }
class ____: """ Render ``event_dict`` as a list of ``Key=repr(Value)`` pairs. Args: sort_keys: Whether to sort keys when formatting. key_order: List of keys that should be rendered in this exact order. Missing keys will be rendered as ``None``, extra keys depending...
KeyValueRenderer
python
nedbat__coveragepy
tests/test_coverage.py
{ "start": 44724, "end": 45115 }
class ____(CoverageTest): """Tests for the module-level behavior of the `coverage` module.""" run_in_temp_dir = False def test_not_singleton(self) -> None: # You *can* create another coverage object. coverage.Coverage() coverage.Coverage() def test_old_name_and_new_name(self) ...
ModuleTest
python
huggingface__transformers
src/transformers/models/lightglue/modular_lightglue.py
{ "start": 12349, "end": 14443 }
class ____(LlamaAttention): def __init__(self, config: LightGlueConfig, layer_idx: int): super().__init__() del self.rotary_emb def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, attention_mask...
LightGlueAttention
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/hstore.py
{ "start": 8461, "end": 8578 }
class ____(sqlfunc.GenericFunction): type = HSTORE name = "slice" inherit_cache = True
_HStoreSliceFunction
python
getsentry__sentry
src/sentry/workflow_engine/types.py
{ "start": 3486, "end": 4053 }
class ____(TypedDict): """ A snapshot of data used to evaluate a workflow. Ensure that this size is kept smaller, since it's used in logging. """ associated_detector: DetectorSnapshot | None event_id: str | None # ID in NodeStore group: Group | None workflow_ids: list[int] | None t...
WorkflowEvaluationSnapshot
python
arrow-py__arrow
arrow/locales.py
{ "start": 137612, "end": 138896 }
class ____(Locale): names = ["kk", "kk-kz"] past = "{0} бұрын" future = "{0} кейін" timeframes = { "now": "қазір", "second": "бір секунд", "seconds": "{0} секунд", "minute": "бір минут", "minutes": "{0} минут", "hour": "бір сағат", "hours": "{0} с...
KazakhLocale
python
getsentry__sentry
src/sentry/rules/filters/issue_occurrences.py
{ "start": 404, "end": 2142 }
class ____(EventFilter): id = "sentry.rules.filters.issue_occurrences.IssueOccurrencesFilter" form_fields = {"value": {"type": "number", "placeholder": 10}} label = "The issue has happened at least {value} times" prompt = "The issue has happened at least {x} times (Note: this is approximate)" def p...
IssueOccurrencesFilter
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 16526, "end": 16876 }
class ____(RoleImpl): __slots__ = () def _literal_coercion(self, element, *, argname=None, **kw): if isinstance(element, str) and issubclass( elements.TextClause, self._role_class ): _no_text_coercion(element, argname) else: self._raise_for_expected(e...
_NoTextCoercion
python
sqlalchemy__sqlalchemy
test/orm/test_default_strategies.py
{ "start": 5799, "end": 19263 }
class ____(DefaultStrategyOptionsTestFixtures): def test_downgrade_baseline(self): """Mapper strategy defaults load as expected (compare to rest of DefaultStrategyOptionsTest downgrade tests).""" sess = self._downgrade_fixture() users = [] # test _downgrade_fixture mapper d...
DefaultStrategyOptionsTest
python
kamyu104__LeetCode-Solutions
Python/make-array-empty.py
{ "start": 418, "end": 1681 }
class ____(object): def countOperationsToEmptyArray(self, nums): """ :type nums: List[int] :rtype: int """ class BIT(object): # 0-indexed. def __init__(self, n): self.__bit = [0]*(n+1) # Extra one for dummy node. def add(self, i, val...
Solution2
python
coleifer__peewee
tests/regressions.py
{ "start": 43641, "end": 44114 }
class ____(ModelTestCase): requires = [User, Tweet] def test_save_clear_pk(self): u = User.create(username='u1') t1 = Tweet.create(content='t1', user=u) orig_id, t1.id = t1.id, None t1.content = 't2' t1.save() self.assertTrue(t1.id is not None) self.asser...
TestSaveClearingPK
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 284695, "end": 285243 }
class ____(sgqlc.types.Input): """Specifies the attributes for a new or updated rule.""" __schema__ = github_schema __field_names__ = ("id", "type", "parameters") id = sgqlc.types.Field(ID, graphql_name="id") """Optional ID of this rule when updating""" type = sgqlc.types.Field(sgqlc.types.non...
RepositoryRuleInput
python
xlwings__xlwings
xlwings/_xlmac.py
{ "start": 19198, "end": 24053 }
class ____(base_classes.Sheet): def __init__(self, workbook, name_or_index): self.workbook = workbook self.xl = workbook.xl.worksheets[name_or_index] @property def api(self): return self.xl @property def name(self): return self.xl.name.get() @name.setter de...
Sheet
python
openai__openai-python
src/openai/types/responses/response_input_file_content_param.py
{ "start": 257, "end": 771 }
class ____(TypedDict, total=False): type: Required[Literal["input_file"]] """The type of the input item. Always `input_file`.""" file_data: Optional[str] """The base64-encoded data of the file to be sent to the model.""" file_id: Optional[str] """The ID of the file to be sent to the model.""" ...
ResponseInputFileContentParam
python
uqfoundation__dill
dill/_objects.py
{ "start": 1766, "end": 1953 }
class ____: def _method(self): pass # @classmethod # def _clsmethod(cls): #XXX: test me # pass # @staticmethod # def _static(self): #XXX: test me # pass
_class
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 38347, "end": 38937 }
class ____(nn.Embedding): """ This module overrides nn.Embeddings' forward by multiplying with embeddings scale. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0): super().__init__(num_embeddings, embedding_dim, padding_idx) ...
SeamlessM4TScaledWordEmbedding
python
coleifer__peewee
tests/migrations.py
{ "start": 1626, "end": 33806 }
class ____(ModelTestCase): requires = [Person, Tag, User, Page, Session] # Each database behaves slightly differently. _exception_add_not_null = not IS_MYSQL _person_data = [ ('Charlie', 'Leifer', None), ('Huey', 'Kitty', datetime.date(2011, 5, 1)), ('Mickey', 'Dog', datetime.d...
TestSchemaMigration
python
django__django
tests/template_tests/syntax_tests/i18n/test_translate.py
{ "start": 12017, "end": 12194 }
class ____(SimpleTestCase): def test_repr(self): node = LocalizeNode(nodelist=[], use_l10n=True) self.assertEqual(repr(node), "<LocalizeNode>")
LocalizeNodeTests
python
astropy__astropy
astropy/table/tests/test_table.py
{ "start": 7716, "end": 10439 }
class ____: def test_1(self, table_types): t = table_types.Table() t.add_column(table_types.Column(name="a", dtype=int, length=100)) assert len(t["a"]) == 100 def test_2(self, table_types): t = table_types.Table() t.add_column(table_types.Column(name="a", dtype=int, shap...
TestEmptyData
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/pipes/clients/emr_serverless.py
{ "start": 1429, "end": 15927 }
class ____(PipesClient, TreatAsResourceParam): """A pipes client for running workloads on AWS EMR Serverless. Args: client (Optional[boto3.client]): The boto3 AWS EMR Serverless client used to interact with AWS EMR Serverless. context_injector (Optional[PipesContextInjector]): A context injecto...
PipesEMRServerlessClient
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/liblinear_svc_preprocessor.py
{ "start": 573, "end": 4173 }
class ____(AutoSklearnPreprocessingAlgorithm): # Liblinear is not deterministic as it uses a RNG inside def __init__( self, penalty, loss, dual, tol, C, multi_class, fit_intercept, intercept_scaling, class_weight=None, rando...
LibLinear_Preprocessor
python
apache__thrift
lib/py/src/transport/TSSLSocket.py
{ "start": 12535, "end": 16649 }
class ____(TSocket.TServerSocket, TSSLBase): """SSL implementation of TServerSocket This uses the ssl module's wrap_socket() method to provide SSL negotiated encryption. """ # New signature # def __init__(self, host='localhost', port=9090, unix_socket=None, **ssl_args): # Deprecated signat...
TSSLServerSocket
python
eventlet__eventlet
eventlet/zipkin/_thrift/zipkinCore/ttypes.py
{ "start": 3264, "end": 5852 }
class ____: """ Attributes: - timestamp - value - host """ thrift_spec = ( None, # 0 (1, TType.I64, 'timestamp', None, None, ), # 1 (2, TType.STRING, 'value', None, None, ), # 2 (3, TType.STRUCT, 'host', (Endpoint, Endpoint.thrift_spec), None, ), # 3 ) def __init__(self, timestamp...
Annotation
python
kubernetes-client__python
kubernetes/base/dynamic/exceptions.py
{ "start": 3591, "end": 3673 }
class ____(DynamicApiError): """ 500: StatusInternalServer """
InternalServerError
python
matplotlib__matplotlib
lib/matplotlib/tests/test_transforms.py
{ "start": 17873, "end": 26310 }
class ____: def test_invalidate(self): before = np.array([[1.0, 4.0, 0.0], [5.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) after = np.array([[1.0, 3.0, 0.0], [5.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # Tra...
TestAffineDeltaTransform
python
fastai__fastai
fastai/collab.py
{ "start": 4258, "end": 5290 }
class ____(TabularModel): "Subclass `TabularModel` to create a NN suitable for collaborative filtering." @delegates(TabularModel.__init__) def __init__(self, emb_szs, layers, **kwargs): super().__init__(emb_szs=emb_szs, n_cont=0, out_sz=1, layers=layers, **kwargs) # %% ../nbs/45_collab.ipynb 40 @de...
EmbeddingNN
python
kamyu104__LeetCode-Solutions
Python/deepest-leaves-sum.py
{ "start": 191, "end": 507 }
class ____(object): def deepestLeavesSum(self, root): """ :type root: TreeNode :rtype: int """ curr = [root] while curr: prev, curr = curr, [child for p in curr for child in [p.left, p.right] if child] return sum(node.val for node in prev)
Solution
python
PrefectHQ__prefect
src/prefect/exceptions.py
{ "start": 2059, "end": 2330 }
class ____(PrefectException): """ Raised when the result from a cancelled run is retrieved and an exception is not attached. This occurs when a string is attached to the state instead of an exception or if the state's data is null. """
CancelledRun
python
ray-project__ray
rllib/core/learner/learner_group.py
{ "start": 3070, "end": 33314 }
class ____(Checkpointable): """Coordinator of n (possibly remote) Learner workers. Each Learner worker has a copy of the RLModule, the loss function(s), and one or more optimizers. """ def __init__( self, *, config: "AlgorithmConfig", # TODO (sven): Rename into `rl_...
LearnerGroup
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/feature_store.py
{ "start": 5127, "end": 8903 }
class ____(GoogleCloudBaseOperator, OperationHelper): """ Create the Feature Online store. This method initiates VertexAI Feature Online Store creation request. Feature Online Store aims to serve and manage features data as a part of VertexAI MLOps. :param project_id: Required. The ID of the Googl...
CreateFeatureOnlineStoreOperator
python
getsentry__sentry
src/sentry/integrations/slack/actions/notification.py
{ "start": 2225, "end": 20596 }
class ____(IntegrationEventAction): id = "sentry.integrations.slack.notify_action.SlackNotifyServiceAction" prompt = "Send a Slack notification" provider = IntegrationProviderSlug.SLACK.value integration_key = "workspace" label = "Send a notification to the {workspace} Slack workspace to {channel} (...
SlackNotifyServiceAction
python
getsentry__sentry
tests/sentry/api/helpers/test_group_index.py
{ "start": 26034, "end": 41987 }
class ____(TestCase): def setUp(self) -> None: self.group = self.create_group() self.group_list = [self.group] self.project_lookup = {self.group.project_id: self.group.project} @patch("sentry.analytics.record") def test_assigned_to(self, mock_record: Mock) -> None: assigned_...
TestHandleAssignedTo
python
redis__redis-py
tests/mocks.py
{ "start": 30, "end": 1144 }
class ____: """ A class simulating an readable socket, optionally raising a special exception every other read. """ class TestError(BaseException): pass def __init__(self, data, interrupt_every=0): self.data = data self.counter = 0 self.pos = 0 self.inte...
MockSocket
python
ray-project__ray
python/ray/data/_internal/logical/operators/all_to_all_operator.py
{ "start": 7259, "end": 8027 }
class ____(AbstractAllToAll): """Logical operator for aggregate.""" def __init__( self, input_op: LogicalOperator, key: Optional[str], aggs: List[AggregateFn], num_partitions: Optional[int] = None, batch_format: Optional[str] = "default", ): super()._...
Aggregate
python
Pylons__pyramid
tests/test_view.py
{ "start": 29509, "end": 30596 }
class ____(unittest.TestCase): def _callFUT(self, context, request): from pyramid.view import default_exceptionresponse_view return default_exceptionresponse_view(context, request) def test_is_exception(self): context = Exception() result = self._callFUT(context, None) ...
Test_default_exceptionresponse_view
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 134917, "end": 140097 }
class ____(_TestMakeSplrepBase): @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6]) def test_fitpack_F(self, k): # test an implementation detail: banded/packed linalg vs full matrices from scipy.interpolate._fitpack_repro import F x, y, s = self._get_xykt() t = np.array([0]*(k+1...
TestMakeSplrep
python
conda__conda
conda/common/configuration.py
{ "start": 4653, "end": 4990 }
class ____(CondaMultiError, ConfigurationError): def __init__(self, errors, *args, **kwargs): super().__init__(errors, *args, **kwargs) def raise_errors(errors): if not errors: return True elif len(errors) == 1: raise errors[0] else: raise MultiValidationError(errors) ...
MultiValidationError
python
ray-project__ray
python/ray/llm/_internal/common/utils/cloud_filesystem/base.py
{ "start": 337, "end": 2618 }
class ____(ABC): """Abstract base class for cloud filesystem implementations. This class defines the interface that all cloud storage provider implementations must implement. Provider-specific classes (S3FileSystem, GCSFileSystem, etc.) will inherit from this base class and provide optimized implementa...
BaseCloudFileSystem
python
wandb__wandb
wandb/sdk/artifacts/_generated/delete_artifact.py
{ "start": 349, "end": 480 }
class ____(GQLResult): id: GQLId DeleteArtifact.model_rebuild() DeleteArtifactResult.model_rebuild()
DeleteArtifactResultArtifact
python
takluyver__flit
flit_core/flit_core/vendor/tomli/_parser.py
{ "start": 7369, "end": 21649 }
class ____(NamedTuple): data: NestedDict flags: Flags def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos: try: while src[pos] in chars: pos += 1 except IndexError: pass return pos def skip_until( src: str, pos: Pos, expect: str, *, err...
Output
python
Lightning-AI__lightning
tests/tests_pytorch/strategies/test_fsdp.py
{ "start": 4774, "end": 32739 }
class ____(TestBoringModel): def on_train_batch_start(self, batch, batch_idx): assert batch.dtype == torch.float32 def on_train_batch_end(self, _, batch, batch_idx): assert batch.dtype == torch.float32 self._assert_layer_fsdp_instance() def on_test_batch_end(self, _, batch, batch_i...
TestFSDPModelAutoWrapped
python
doocs__leetcode
solution/2100-2199/2129.Capitalize the Title/Solution.py
{ "start": 0, "end": 182 }
class ____: def capitalizeTitle(self, title: str) -> str: words = [w.lower() if len(w) < 3 else w.capitalize() for w in title.split()] return " ".join(words)
Solution