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 | kamyu104__LeetCode-Solutions | Python/minimum-relative-loss-after-buying-chocolates.py | {
"start": 84,
"end": 985
} | class ____(object):
def minimumRelativeLosses(self, prices, queries):
"""
:type prices: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
def binary_search(left, right, check):
while left <= right:
mid = left + (right-left)//2
... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/crud.py | {
"start": 45948,
"end": 61090
} | class ____(elements.ColumnElement[Any]):
_is_multiparam_column = True
def __init__(self, original, index):
self.index = index
self.key = "%s_m%d" % (original.key, index + 1)
self.original = original
self.default = original.default
self.type = original.type
def compa... | _multiparam_column |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 7843,
"end": 8419
} | class ____(PosixConfig):
"""Configuration for a POSIX SSH host."""
user: t.Optional[str] = None
host: t.Optional[str] = None
port: t.Optional[int] = None
def get_defaults(self, context: HostContext) -> PosixSshCompletionConfig:
"""Return the default settings."""
return PosixSshComp... | PosixSshConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/articles_response_builder.py | {
"start": 384,
"end": 715
} | class ____(HttpResponseBuilder):
@classmethod
def response(cls, next_page_url: Optional[HttpRequest] = None) -> "ArticlesResponseBuilder":
return cls(
find_template("articles", __file__), FieldPath("articles"), NextPagePaginationStrategy(http_request_to_str(next_page_url))
)
| ArticlesResponseBuilder |
python | keras-team__keras | keras/src/ops/math_test.py | {
"start": 40354,
"end": 40847
} | class ____(testing.TestCase):
def test_in_top_k_call(self):
targets = np.array([2, 0, 1], dtype=np.int32)
predictions = np.array(
[[0.1, 0.2, 0.7], [1.0, 0.2, 0.3], [0.2, 0.6, 0.2]],
dtype=np.float32,
)
k = 2
in_top_k_op = kmath.InTopK(k=k)
out... | InTopKTest |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/batch_size_finder.py | {
"start": 1111,
"end": 8912
} | class ____(Callback):
"""Finds the largest batch size supported by a given model before encountering an out of memory (OOM) error.
All you need to do is add it as a callback inside Trainer and call ``trainer.{fit,validate,test,predict}``.
Internally, it calls the respective step function ``steps_per_trial`... | BatchSizeFinder |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 5706,
"end": 5778
} | class ____:
parents : list[Tracer]
recipe : JaxprEqnRecipe
| EffectHandle |
python | sqlalchemy__sqlalchemy | test/orm/test_events.py | {
"start": 111062,
"end": 115511
} | class ____(
RemoveORMEventsGlobally,
_fixtures.FixtureTest,
AssertsCompiledSQL,
testing.AssertsExecutionResults,
):
__dialect__ = "default"
@classmethod
def setup_mappers(cls):
User = cls.classes.User
users = cls.tables.users
cls.mapper_registry.map_imperatively(Use... | QueryEventsTest |
python | spyder-ide__spyder | spyder/plugins/help/widgets.py | {
"start": 4928,
"end": 6782
} | class ____(QWidget, SpyderWidgetMixin):
"""
WebView widget with find dialog
"""
sig_link_clicked = Signal(QUrl)
def __init__(self, parent):
if not PYSIDE2:
super().__init__(parent, class_parent=parent)
else:
QWidget.__init__(self, parent)
SpyderWi... | RichText |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-kyriba/source_kyriba/source.py | {
"start": 8696,
"end": 10435
} | class ____(IncrementalKyribaStream):
primary_key = "uuid"
def path(self, **kwargs) -> str:
return "cash-flows"
def stream_slices(
self, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None, **kwargs
) -> Iterable[Optional[Mapping[str, Any]]]:
end_date = self.e... | CashFlows |
python | urllib3__urllib3 | src/urllib3/exceptions.py | {
"start": 5526,
"end": 5648
} | class ____(ValueError, HTTPError):
"""Raised when there is something wrong with a given URL input."""
| LocationValueError |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/athena.py | {
"start": 1226,
"end": 3661
} | class ____(AwsBaseSensor[AthenaHook]):
"""
Poll the state of the Query until it reaches a terminal state; fails if the query fails.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:AthenaSensor`
:param query_execution_id: query_... | AthenaSensor |
python | django__django | tests/admin_views/tests.py | {
"start": 323861,
"end": 329878
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.s1 = Section.objects.create(name="Test section")
cls.a1 = Article.objects.create(
... | CSSTest |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/test_cards.py | {
"start": 358,
"end": 692
} | class ____(MetaflowCard):
type = "test_pathspec_card"
def render(self, task):
import random
import string
return "%s %s" % (
task.pathspec,
"".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(6)
),
)
... | TestPathSpecCard |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 13662,
"end": 15669
} | class ____(NonStrictDataModel):
"""
:param version: Version id of a version belonging to the dataset
:type version: str
:param dataset: Existing Dataset id
:type dataset: str
:param merge_with: Version ID to merge with
:type merge_with: str
"""
_schema = {
"properties": {
... | DataviewEntry |
python | fluentpython__example-code-2e | 06-obj-ref/twilight_bus.py | {
"start": 224,
"end": 632
} | class ____:
"""A bus model that makes passengers vanish"""
def __init__(self, passengers=None):
if passengers is None:
self.passengers = [] # <1>
else:
self.passengers = passengers #<2>
def pick(self, name):
self.passengers.append(name)
def drop(self,... | TwilightBus |
python | joke2k__faker | tests/providers/test_company.py | {
"start": 21564,
"end": 21874
} | class ____:
"""Test nl_BE company provider methods"""
def test_company_suffix(self, faker, num_samples):
for _ in range(num_samples):
suffix = faker.company_suffix()
assert isinstance(suffix, str)
assert suffix in NlBeCompanyProvider.company_suffixes
| TestNlBe |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_reshape_op_test.py | {
"start": 1165,
"end": 15279
} | class ____(test.TestCase):
def _SparseTensorPlaceholder(self):
return sparse_tensor.SparseTensor(
array_ops.placeholder(dtypes.int64),
array_ops.placeholder(dtypes.float64),
array_ops.placeholder(dtypes.int64))
def _SparseTensorValue_5x6(self):
ind = np.array([[0, 0], [1, 0], [1, 3... | SparseReshapeTest |
python | ansible__ansible | lib/ansible/_internal/_templating/_marker_behaviors.py | {
"start": 236,
"end": 525
} | class ____(metaclass=abc.ABCMeta):
"""Base class to support custom handling of `Marker` values encountered during concatenation or finalization."""
@abc.abstractmethod
def handle_marker(self, value: Marker) -> t.Any:
"""Handle the given `Marker` value."""
| MarkerBehavior |
python | modin-project__modin | modin/experimental/core/storage_formats/pandas/parsers.py | {
"start": 5701,
"end": 6294
} | class ____(PandasParser):
@staticmethod
@doc(_doc_parse_func, parameters=_doc_parse_parameters_common)
def parse(fname, **kwargs):
warnings.filterwarnings("ignore")
num_splits = 1
single_worker_read = kwargs.pop("single_worker_read", None)
df = pandas.read_xml(fname, **kwargs... | ExperimentalPandasXmlParser |
python | facebook__pyre-check | client/commands/pyre_language_server.py | {
"start": 2964,
"end": 4864
} | class ____(abc.ABC):
@abc.abstractmethod
async def write_telemetry(
self,
parameters: Dict[str, object],
activity_key: Optional[Dict[str, object]],
) -> None:
raise NotImplementedError()
@abc.abstractmethod
def get_language_server_features(self) -> features.LanguageS... | PyreLanguageServerApi |
python | Textualize__rich | tests/test_repr.py | {
"start": 1617,
"end": 2164
} | class ____:
def __init__(
self, name, eats, fly=True, another=StupidClass(2), extinct=NotStupid()
):
self.name = name
self.eats = eats
self.fly = fly
self.another = another
self.extinct = extinct
def test_rich_repr() -> None:
assert (repr(Foo("hello"))) == "... | Bird |
python | kamyu104__LeetCode-Solutions | Python/check-if-word-is-valid-after-substitutions.py | {
"start": 29,
"end": 448
} | class ____(object):
def isValid(self, S):
"""
:type S: str
:rtype: bool
"""
stack = []
for i in S:
if i == 'c':
if stack[-2:] == ['a', 'b']:
stack.pop()
stack.pop()
else:
... | Solution |
python | openai__openai-python | src/openai/types/audio/transcription.py | {
"start": 1373,
"end": 1685
} | class ____(BaseModel):
seconds: float
"""Duration of the input audio in seconds."""
type: Literal["duration"]
"""The type of the usage object. Always `duration` for this variant."""
Usage: TypeAlias = Annotated[Union[UsageTokens, UsageDuration], PropertyInfo(discriminator="type")]
| UsageDuration |
python | django__django | tests/invalid_models_tests/test_custom_fields.py | {
"start": 151,
"end": 666
} | class ____(SimpleTestCase):
def test_none_column(self):
class NoColumnField(models.AutoField):
def db_type(self, connection):
# None indicates not to create a column in the database.
return None
class Model(models.Model):
field = NoColumnField... | CustomFieldTest |
python | encode__starlette | starlette/websockets.py | {
"start": 576,
"end": 8004
} | class ____(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
assert scope["type"] == "websocket"
self._receive = receive
self._send = send
self.client_state = WebSocketState.CONNECTING
self.application_sta... | WebSocket |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 23755,
"end": 24420
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden stat... | RoCBertPooler |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-inversions.py | {
"start": 2319,
"end": 3138
} | class ____(object):
def numberOfPermutations(self, n, requirements):
"""
:type n: int
:type requirements: List[List[int]]
:rtype: int
"""
MOD = 10**9+7
lookup = [-1]*n
for i, c in requirements:
lookup[i] = c
dp = [0]*(lookup[-1]+1)
... | Solution3 |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_search_details.py | {
"start": 3560,
"end": 8995
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-search-details"
method = "put"
def setUp(self) -> None:
self.login_as(user=self.user)
@cached_property
def member(self):
user = self.create_user("test@test.com")
self.create_member(organization=self.organization... | PutOrganizationSearchTest |
python | kamyu104__LeetCode-Solutions | Python/subtree-inversion-sum.py | {
"start": 1928,
"end": 2939
} | class ____(object):
def subtreeInversionSum(self, edges, nums, k):
"""
:type edges: List[List[int]]
:type nums: List[int]
:type k: int
:rtype: int
"""
def dfs(u, p):
dp.append([0]*2)
total, pos, neg = nums[u], 0, 0
for v in ... | Solution2 |
python | getsentry__sentry | src/sentry/integrations/discord/message_builder/base/base.py | {
"start": 638,
"end": 2202
} | class ____:
"""
Base DiscordMessageBuilder class.
Should be extended to provide more abstracted message builders for
specific types of messages (e.g. DiscordIssuesMessageBuilder).
"""
def __init__(
self,
content: str = "",
embeds: list[DiscordMessageEmbed] | None = None... | DiscordMessageBuilder |
python | bokeh__bokeh | src/bokeh/core/property/struct.py | {
"start": 1503,
"end": 3768
} | class ____(ParameterizedProperty[T]):
""" Accept values that are structures.
"""
_fields: dict[str, Property[Any]]
_optional: set[str]
def __init__(self, **fields: Any) -> None:
default = fields.pop("default", None)
help = fields.pop("help", None)
if not fields:
... | Struct |
python | kamyu104__LeetCode-Solutions | Python/print-immutable-linked-list-in-reverse.py | {
"start": 49,
"end": 1001
} | class ____(object):
def printLinkedListInReverse(self, head):
"""
:type head: ImmutableListNode
:rtype: None
"""
def print_nodes(head, count):
nodes = []
while head and len(nodes) != count:
nodes.append(head)
head = head... | Solution |
python | redis__redis-py | redis/_parsers/base.py | {
"start": 2054,
"end": 4122
} | class ____(ABC):
EXCEPTION_CLASSES = {
"ERR": {
"max number of clients reached": ConnectionError,
"invalid password": AuthenticationError,
# some Redis server versions report invalid command syntax
# in lowercase
"wrong number of arguments "
... | BaseParser |
python | facebookresearch__faiss | contrib/big_batch_search.py | {
"start": 5556,
"end": 17640
} | class ____:
""" computation within one bucket """
def __init__(
self,
index,
method="knn_function",
pairwise_distances=faiss.pairwise_distances,
knn=faiss.knn):
self.index = index
if index.__class__ == faiss.IndexIVFFlat:
... | BlockComputer |
python | gevent__gevent | examples/udp_server.py | {
"start": 268,
"end": 618
} | class ____(DatagramServer):
def handle(self, data, address): # pylint:disable=method-hidden
print('%s: got %r' % (address[0], data))
self.socket.sendto(('Received %s bytes' % len(data)).encode('utf-8'), address)
if __name__ == '__main__':
print('Receiving datagrams on :9000')
EchoServer('... | EchoServer |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_stats_trace_metrics.py | {
"start": 204,
"end": 7321
} | class ____(OrganizationEventsEndpointTestBase):
dataset = "tracemetrics"
viewname = "sentry-api-0-organization-events-stats"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.start = self.day_ago = before_now(days=1).replace(
hour=10, minute=0, ... | OrganizationEventsStatsTraceMetricsEndpointTest |
python | ipython__ipython | IPython/extensions/deduperreload/deduperreload.py | {
"start": 4481,
"end": 5554
} | class ____:
"""
Recursive data structure to keep track of reloadable functions/methods. Each object corresponds to a specific scope level.
children: classes inside given scope, maps class name to autoreload tree for that class's scope
funcs_to_autoreload: list of function names that can be autoreloaded ... | AutoreloadTree |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_D.py | {
"start": 8492,
"end": 9752
} | class ____(Benchmark):
r"""
Deckkers-Aarts objective function.
This class defines the Deckkers-Aarts [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{DeckkersAarts}}(x) = 10^5x_1^2 + x_2^2 - (x_1^2 + x_2^2)^2
+ 10^{... | DeckkersAarts |
python | ray-project__ray | python/ray/tune/examples/pbt_dcgan_mnist/common.py | {
"start": 2566,
"end": 3291
} | class ____(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),... | Discriminator |
python | huggingface__transformers | src/transformers/models/dac/configuration_dac.py | {
"start": 826,
"end": 4581
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of an [`DacModel`]. It is used to instantiate a
Dac model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuratio... | DacConfig |
python | Textualize__textual | docs/examples/guide/widgets/checker01.py | {
"start": 174,
"end": 1107
} | class ____(Widget):
"""Render an 8x8 checkerboard."""
def render_line(self, y: int) -> Strip:
"""Render a line of the widget. y is relative to the top of the widget."""
row_index = y // 4 # A checkerboard square consists of 4 rows
if row_index >= 8: # Generate blank lines when we re... | CheckerBoard |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py | {
"start": 42620,
"end": 46939
} | class ____(CloudSQLBaseOperator):
"""
Import data into a Cloud SQL instance from Cloud Storage.
CSV IMPORT
``````````
This operator is NOT idempotent for a CSV import. If the same file is imported
multiple times, the imported data will be duplicated in the database.
Moreover, if there are ... | CloudSQLImportInstanceOperator |
python | bokeh__bokeh | src/bokeh/core/property/dataspec.py | {
"start": 8521,
"end": 8678
} | class ____(DataSpec):
def __init__(self, default, *, help: str | None = None) -> None:
super().__init__(Float, default=default, help=help)
| FloatSpec |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/bigquery.py | {
"start": 1803,
"end": 2022
} | class ____(BaseGoogleLink):
"""Helper class for constructing BigQuery Job Detail Link."""
name = "BigQuery Job Detail"
key = "bigquery_job_detail"
format_str = BIGQUERY_JOB_DETAIL_LINK
| BigQueryJobDetailLink |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py | {
"start": 317,
"end": 4538
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship... | Hero |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/dg_defs/composites/python/component.py | {
"start": 147,
"end": 487
} | class ____(Component, Model, Resolvable):
asset: ResolvedAssetSpec
def build_defs(self, context):
return Definitions(assets=[self.asset])
@component_instance
def first(_):
return PyComponent(asset=AssetSpec("first_py"))
@component_instance
def second(_):
return PyComponent(asset=AssetSpec("... | PyComponent |
python | RaRe-Technologies__gensim | gensim/corpora/textcorpus.py | {
"start": 2224,
"end": 15917
} | class ____(interfaces.CorpusABC):
"""Helper class to simplify the pipeline of getting BoW vectors from plain text.
Notes
-----
This is an abstract base class: override the :meth:`~gensim.corpora.textcorpus.TextCorpus.get_texts` and
:meth:`~gensim.corpora.textcorpus.TextCorpus.__len__` methods to ma... | TextCorpus |
python | mlflow__mlflow | mlflow/genai/optimize/types.py | {
"start": 537,
"end": 1353
} | class ____:
"""
Parameters for configuring a LLM Model.
Args:
model_name: Name of the model in the format `<provider>:/<model name>` or
`<provider>/<model name>`. For example, "openai:/gpt-4o", "anthropic:/claude-4",
or "openai/gpt-4o".
base_uri: Optional base URI fo... | LLMParams |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_impls.py | {
"start": 29154,
"end": 33648
} | class ____(
AutoMaterializeRule,
NamedTuple(
"_SkipOnNotAllParentsUpdatedRule", [("require_update_for_all_parent_partitions", bool)]
),
):
"""An auto-materialize rule that enforces that an asset can only be materialized if all parents
have been materialized since the asset's last materializa... | SkipOnNotAllParentsUpdatedRule |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_overridden_method.py | {
"start": 117,
"end": 426
} | class ____(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def prop(self):
pass
@abc.abstractmethod
async def async_method(self):
pass
@abc.abstractmethod
def method_a(self):
pass
@abc.abstractmethod
def method_b(self):
pass
| SuperClass |
python | keon__algorithms | tests/test_stack.py | {
"start": 295,
"end": 2621
} | class ____(unittest.TestCase):
def test_is_consecutive(self):
self.assertTrue(first_is_consecutive([3, 4, 5, 6, 7]))
self.assertFalse(first_is_consecutive([3, 4, 6, 7]))
self.assertFalse(first_is_consecutive([3, 2, 1]))
self.assertTrue(second_is_consecutive([3, 4, 5, 6, 7]))
... | TestSuite |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 119838,
"end": 120669
} | class ____(test_util.TensorFlowTestCase):
def testRegisteredNode(self):
graph = ops.Graph()
node = ops._NodeDef("a", "an_a")
flops = ops.get_stats_for_node_def(graph, node, "flops")
self.assertEqual(20, flops.value)
missing_stat = ops.get_stats_for_node_def(graph, node, "missing_stat")
self.a... | StatisticsTest |
python | google__jax | tests/pallas/export_pallas_test.py | {
"start": 3021,
"end": 3664
} | class ____(ExportTestWithTriton):
def setUp(self):
# TODO(b/432678342): remove once this is fixed.
if jtu.is_device_cuda() and not jtu.is_cuda_compute_capability_at_least("9.0"):
self.skipTest(
"LLVM seems to care about the compute capability if a GPU is present"
)
super().setUp()
... | ExportTestWithMosaicGpu |
python | plotly__plotly.py | plotly/graph_objs/scattergeo/marker/_colorbar.py | {
"start": 233,
"end": 61703
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergeo.marker"
_path_str = "scattergeo.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"m... | ColorBar |
python | huggingface__transformers | src/transformers/models/depth_pro/modeling_depth_pro.py | {
"start": 29067,
"end": 30441
} | class ____(nn.Module):
def __init__(self, config: DepthProConfig, use_deconv: bool = True):
super().__init__()
self.config = config
self.use_deconv = use_deconv
self.residual_layer1 = DepthProPreActResidualLayer(config)
self.residual_layer2 = DepthProPreActResidualLayer(conf... | DepthProFeatureFusionLayer |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-mdx-builder/tests/dummy_module.py | {
"start": 2020,
"end": 3039
} | class ____:
"""Base vehicle class.
This is a base class that demonstrates class documentation
with attributes and methods.
Attributes:
make: The vehicle manufacturer
model: The vehicle model
year: The manufacturing year
"""
def __init__(self, make: str, model: str, yea... | Vehicle |
python | huggingface__transformers | src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py | {
"start": 9328,
"end": 9931
} | class ____(nn.Module):
def __init__(self, config: ASTConfig):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch... | ASTOutput |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 21539,
"end": 24693
} | class ____(LogitsProcessor):
"""
[`LogitsProcessor`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].
Args:
top_p (`float`):
If set to < 1, only the smallest se... | TopPLogitsWarper |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 109012,
"end": 109923
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook):
op = DeleteModelOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
region=GCP_LOCATION,
... | TestVertexAIDeleteModelOperator |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 8067,
"end": 11057
} | class ____(_UnsupportedGroupCVMixin, BaseCrossValidator):
"""Leave-P-Out cross-validator.
Provides train/test indices to split data in train/test sets. This results
in testing on all distinct samples of size p, while the remaining n - p
samples form the training set in each iteration.
Note: ``Leav... | LeavePOut |
python | pypa__warehouse | tests/unit/admin/views/test_emails.py | {
"start": 8663,
"end": 9175
} | class ____:
def test_existing_email(self, db_session):
em = EmailMessageFactory.create()
request = pretend.stub(matchdict={"email_id": em.id}, db=db_session)
assert views.email_detail(request) == {"email": em}
def test_nonexistent_email(self, db_session):
EmailMessageFactory.c... | TestEmailDetail |
python | ansible__ansible | test/integration/targets/config/lookup_plugins/broken.py | {
"start": 1110,
"end": 1379
} | class ____(LookupBase):
def run(self, terms, variables=None, **kwargs):
"""Generate list."""
self.set_options(var_options=variables, direct=kwargs)
return [self.get_option("some_option"), *self.get_option_and_origin("some_option")]
| LookupModule |
python | walkccc__LeetCode | solutions/2306. Naming a Company/2306.py | {
"start": 0,
"end": 498
} | class ____:
def distinctNames(self, ideas: list[str]) -> int:
ans = 0
# suffixes[i] := the set of strings omitting the first letter, where the
# first letter is ('a' + i)
suffixes = [set() for _ in range(26)]
for idea in ideas:
suffixes[ord(idea[0]) - ord('a')].add(idea[1:])
for i, j i... | Solution |
python | numba__numba | numba/tests/npyufunc/test_errors.py | {
"start": 2018,
"end": 5497
} | class ____(TestCase, CheckWarningsMixin):
"""
Test floating-point exceptions inside ufuncs.
Note the warnings emitted by Numpy reflect IEEE-754 semantics.
"""
def check_truediv_real(self, dtype):
"""
Test 1 / 0 and 0 / 0.
"""
f = vectorize(nopython=True)(truediv)
... | TestFloatingPointExceptions |
python | kamyu104__LeetCode-Solutions | Python/subarray-sums-divisible-by-k.py | {
"start": 50,
"end": 444
} | class ____(object):
def subarraysDivByK(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
count = collections.defaultdict(int)
count[0] = 1
result, prefix = 0, 0
for a in A:
prefix = (prefix+a) % K
result ... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/table.py | {
"start": 286,
"end": 7088
} | class ____(xmlwriter.XMLwriter):
"""
A class for writing the Excel XLSX Table file.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self) -> ... | Table |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-yandexgpt/llama_index/embeddings/yandexgpt/util.py | {
"start": 132,
"end": 2397
} | class ____:
"""Class to handle authentication using folder ID and API key."""
def __init__(self, folder_id: str = None, api_key: str = None) -> None:
"""
Initialize the YAuth object with folder_id and api_key.
:param folder_id: The folder ID for authentication.
:param api_key: ... | YAuth |
python | huggingface__transformers | src/transformers/models/roberta/modeling_roberta.py | {
"start": 18070,
"end": 20849
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = RobertaAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
... | RobertaLayer |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_datafusion.py | {
"start": 3057,
"end": 23395
} | class ____:
@staticmethod
def mock_endpoint(get_conn_mock):
return get_conn_mock.return_value.projects.return_value.locations.return_value.instances.return_value
def test_name(self, hook):
expected = f"projects/{PROJECT_ID}/locations/{LOCATION}/instances/{INSTANCE_NAME}"
assert hook... | TestDataFusionHook |
python | walkccc__LeetCode | solutions/1959. Minimum Total Space Wasted With K Resizing Operations/1959.py | {
"start": 0,
"end": 642
} | class ____:
def minSpaceWastedKResizing(self, nums: list[int], k: int) -> int:
MAX = 200_000_000
@functools.lru_cache(None)
def dp(i: int, k: int) -> int:
"""
Returns the minimum space wasted for nums[i..n) if you can resize k times.
"""
if i == len(nums):
return 0
i... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/ecs.py | {
"start": 4475,
"end": 9306
} | class ____(BaseTrigger):
"""
Waits for an ECS task to be done, while eventually polling logs.
:param cluster: short name or full ARN of the cluster where the task is running.
:param task_arn: ARN of the task to watch.
:param waiter_delay: The amount of time in seconds to wait between attempts.
... | TaskDoneTrigger |
python | tensorflow__tensorflow | tensorflow/python/util/dispatch_test.py | {
"start": 5359,
"end": 16191
} | class ____(test_util.TensorFlowTestCase):
def testAddDispatchForTypes_With_CppOp(self):
original_handlers = gen_math_ops.atan2._tf_fallback_dispatchers[:]
# Override the behavior of gen_math_ops.atan2 and make it look like add.
@dispatch.dispatch_for_types(gen_math_ops.atan2, CustomTensor)
def custo... | DispatchTest |
python | huggingface__transformers | tests/quantization/bnb/test_mixed_int8.py | {
"start": 4044,
"end": 17608
} | class ____(BaseMixedInt8Test):
def setUp(self):
super().setUp()
# Models and tokenizer
self.model_fp16 = AutoModelForCausalLM.from_pretrained(self.model_name, dtype=torch.float16, device_map="auto")
self.model_8bit = AutoModelForCausalLM.from_pretrained(
self.model_name,... | MixedInt8Test |
python | django__django | tests/admin_scripts/tests.py | {
"start": 27219,
"end": 31880
} | class ____(AdminScriptTestCase):
"""
A series of tests for django-admin when the settings file is in a
directory. (see #9751).
"""
def setUp(self):
super().setUp()
self.write_settings("settings", is_dir=True)
def test_setup_environ(self):
"directory: startapp creates th... | DjangoAdminSettingsDirectory |
python | joke2k__faker | faker/providers/color/fa_IR/__init__.py | {
"start": 80,
"end": 5883
} | class ____(ColorProvider):
"""Implement color provider for ``fa_IR`` locale.
Sources:
- https://www.seyedrezabazyar.com/fa/name-and-code-of-colors/
- https://bit.ly/353BBiY
"""
all_colors = OrderedDict(
(
("نیلی محو", "#F0F8FF"),
("بژ تیره", "#FAEBD7"),
... | Provider |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 279334,
"end": 279804
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of RemoveStar"""
__schema__ = github_schema
__field_names__ = ("starrable_id", "client_mutation_id")
starrable_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="starrableId")
"""The Starrable ID to unstar."""
client_mutati... | RemoveStarInput |
python | wandb__wandb | wandb/vendor/pygments/token.py | {
"start": 236,
"end": 6167
} | class ____(tuple):
parent = None
def split(self):
buf = []
node = self
while node is not None:
buf.append(node)
node = node.parent
buf.reverse()
return buf
def __init__(self, *args):
# no need to call super.__init__
self.subty... | _TokenType |
python | pyqtgraph__pyqtgraph | pyqtgraph/dockarea/DockDrop.py | {
"start": 68,
"end": 2807
} | class ____:
"""Provides dock-dropping methods"""
def __init__(self, dndWidget):
self.dndWidget = dndWidget
self.allowedAreas = {'center', 'right', 'left', 'top', 'bottom'}
self.dndWidget.setAcceptDrops(True)
self.dropArea = None
self.overlay = DropAreaOverlay(dndWidget)
... | DockDrop |
python | getsentry__sentry | src/sentry/incidents/endpoints/organization_alert_rule_details.py | {
"start": 16393,
"end": 20825
} | class ____(OrganizationAlertRuleEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="Retrieve a Metric Alert Rule for an Organization",
... | OrganizationAlertRuleDetailsEndpoint |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_timestamp.py | {
"start": 8029,
"end": 14032
} | class ____:
@pytest.mark.parametrize("tz", [None, zoneinfo.ZoneInfo("US/Pacific")])
def test_disallow_setting_tz(self, tz):
# GH#3746
ts = Timestamp("2010")
msg = "Cannot directly set timezone"
with pytest.raises(AttributeError, match=msg):
ts.tz = tz
def test_de... | TestTimestamp |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 29354,
"end": 30167
} | class ____:
@pytest.mark.parametrize(
"digits,expected",
[
("22500105", "CHE225001055"),
("60362354", "CHE603623540"),
("36806684", "CHE368066842"),
],
ids=[
"checksum_remainder_11",
"checksum_remainder_10",
"che... | TestFrCH |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 1,
"end": 511
} | class ____(object):
def __init__(self, start_mark, end_mark):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in self.__dict__
if not key.endswith('_mark')]
attributes.sort()
arguments = ', '.join(['%s=%r... | Token |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_emr_notebook_execution.py | {
"start": 1794,
"end": 9319
} | class ____:
@mock.patch("botocore.waiter.get_service_module_name", return_value="emr")
@mock.patch.object(EmrHook, "conn")
@mock.patch.object(Waiter, "wait")
def test_start_notebook_execution_wait_for_completion(self, mock_waiter, mock_conn, _):
test_execution_id = "test-execution-id"
mo... | TestEmrStartNotebookExecutionOperator |
python | spyder-ide__spyder | spyder/plugins/run/api.py | {
"start": 19174,
"end": 20226
} | class ____(TypedDict):
"""Run execution configuration metadata."""
# File extension or identifier of the input context.
input_extension: str
# The context for the given input extension, e.g. file, selection, cell or
# others.
# The context can be compared against the values of `RunContext`. e.... | SupportedExecutionRunConfiguration |
python | pytorch__pytorch | torch/testing/_internal/autocast_test_lists.py | {
"start": 23926,
"end": 28405
} | class ____(TestCase):
def args_maybe_kwargs(self, op_with_args):
if len(op_with_args) == 2:
return op_with_args[0], op_with_args[1], {}
else:
return op_with_args[0], op_with_args[1], op_with_args[2]
def _run_autocast_outofplace(
self,
op,
args,
... | TestAutocast |
python | Pylons__pyramid | tests/test_url.py | {
"start": 45597,
"end": 46885
} | class ____(unittest.TestCase):
def _callFUT(self, path, request, **kw):
from pyramid.url import static_path
return static_path(path, request, **kw)
def _makeRequest(self):
class Request:
def static_path(self, path, **kw):
self.path = path
sel... | Test_static_path |
python | wandb__wandb | wandb/_pydantic/base.py | {
"start": 4793,
"end": 5116
} | class ____(GQLBase, ABC):
model_config = ConfigDict(
alias_generator=to_camel, # Assume JSON names are camelCase, by default
frozen=True, # Keep the actual response data immutable
)
# Base class for GraphQL input types, i.e. prepared variables or input objects
# for queries and mutations.
| GQLResult |
python | pytorch__pytorch | torch/distributed/tensor/examples/convnext_example.py | {
"start": 2515,
"end": 3529
} | class ____(nn.Module):
def __init__(self, dim_in=3, dim_out=2, down_scale=4, norm_first=False):
super().__init__()
self.norm_first = norm_first
if norm_first:
self.norm = LayerNorm(dim_in, eps=1e-6, data_format=torch.contiguous_format)
self.conv = nn.Conv2d(
... | DownSampling |
python | tensorflow__tensorflow | tensorflow/python/ops/gradients_util.py | {
"start": 36857,
"end": 42797
} | class ____:
"""A class listing aggregation methods used to combine gradients.
Computing partial derivatives can require aggregating gradient
contributions. This class lists the various methods that can
be used to combine gradients in the graph.
The following aggregation methods are part of the stable API fo... | AggregationMethod |
python | astropy__astropy | astropy/stats/spatial.py | {
"start": 408,
"end": 13929
} | class ____:
"""
Estimators for Ripley's K function for two-dimensional spatial data.
See [1]_, [2]_, [3]_, [4]_, [5]_ for detailed mathematical and
practical aspects of those estimators.
Parameters
----------
area : float
Area of study from which the points where observed.
x_max... | RipleysKEstimator |
python | huggingface__transformers | src/transformers/models/got_ocr2/modular_got_ocr2.py | {
"start": 10004,
"end": 10110
} | class ____(SamVisionEncoder, GotOcr2PreTrainedModel):
input_modalities = ("image",)
| GotOcr2VisionEncoder |
python | pytorch__pytorch | torch/nn/modules/rnn.py | {
"start": 71147,
"end": 74952
} | class ____(RNNCellBase):
r"""A gated recurrent unit (GRU) cell.
.. math::
\begin{array}{ll}
r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\
z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\
n = \tanh(W_{in} x + b_{in} + r \odot (W_{hn} h + b_{hn})) \\
h' = (1 - ... | GRUCell |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 34859,
"end": 35397
} | class ____(_DropBase["Index"]):
"""Represent a DROP INDEX statement."""
__visit_name__ = "drop_index"
def __init__(self, element: Index, if_exists: bool = False) -> None:
"""Create a :class:`.DropIndex` construct.
:param element: a :class:`_schema.Index` that's the subject
of the... | DropIndex |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 31444,
"end": 33828
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
base_parameters: Optional[Dict[str, Any]] = Field(
default=None,
description=(
"Base parameters to be used for each run of this job. If the ... | NotebookTask |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 331535,
"end": 335223
} | class ____(LoopNode, StatNode):
# Base class of 'for-in' statements.
#
# target ExprNode
# iterator IteratorNode | AIterAwaitExprNode(AsyncIteratorNode)
# body StatNode
# else_clause StatNode
# item NextNode | AwaitExprNode(AsyncNextNode)
# is_async... | _ForInStatNode |
python | ray-project__ray | rllib/utils/framework.py | {
"start": 8755,
"end": 9044
} | class ____:
def __init__(self, *a, **kw):
# Fake nn.functional module within torch.nn.
self.functional = None
self.Module = _FakeTorchClassStub
self.parallel = _ParallelStub()
# Fake class for e.g. torch.nn.Module to allow it to be inherited from.
| _NNStub |
python | realpython__materials | python-async-iterators/counter.py | {
"start": 44,
"end": 863
} | class ____:
def __init__(self, name="", end=5):
self.counter = 0
self.name = name
self.end = end
def __aiter__(self):
return self
async def __anext__(self):
if self.counter >= self.end:
raise StopAsyncIteration
self.counter += 1
await asy... | AsyncCounterIterator |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 74959,
"end": 75527
} | class ____(Mock):
"""
A mock intended to be used as a property, or other descriptor, on a class.
`PropertyMock` provides `__get__` and `__set__` methods so you can specify
a return value when it is fetched.
Fetching a `PropertyMock` instance from an object calls the mock, with
no args. Setting ... | PropertyMock |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_asn_country_code_in_set.py | {
"start": 2029,
"end": 4905
} | class ____(ColumnMapExpectation):
"""Expect the provided IP address ASN country code in set."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_hu": [
... | ExpectColumnValuesIpAsnCountryCodeInSet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.