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 | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/metadata.py | {
"start": 299,
"end": 3023
} | class ____(FieldInfo): # pyright: ignore[reportGeneralTypeIssues]
"""Wrapper class that stores additional resolution metadata within a pydantic FieldInfo object.
Examples:
```python
class MyModel(ComponentSchema):
resolvable_obj: Annotated[str, ResolvableFieldInfo(required_scope={"some_field"}... | ResolvableFieldInfo |
python | readthedocs__readthedocs.org | readthedocs/integrations/models.py | {
"start": 11859,
"end": 11979
} | class ____:
installation_id: int
repository_id: int
repository_full_name: str
| GitHubAppIntegrationProviderData |
python | catalyst-team__catalyst | catalyst/loggers/tensorboard.py | {
"start": 596,
"end": 5270
} | class ____(ILogger):
"""Tensorboard logger for parameters, metrics, images and other artifacts.
Args:
logdir: path to logdir for tensorboard.
use_logdir_postfix: boolean flag
to use extra ``tensorboard`` prefix in the logdir.
log_batch_metrics: boolean flag to log batch metr... | TensorboardLogger |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 4410,
"end": 4644
} | class ____(graphene.ObjectType):
name = graphene.String()
digest = graphene.String()
source_type = graphene.String()
source = graphene.String()
schema = graphene.String()
profile = graphene.String()
| MlflowDataset |
python | RaRe-Technologies__gensim | gensim/parsing/porter.py | {
"start": 897,
"end": 15535
} | class ____:
"""Class contains implementation of Porter stemming algorithm.
Attributes
--------
b : str
Buffer holding a word to be stemmed. The letters are in b[0], b[1] ... ending at b[`k`].
k : int
Readjusted downwards as the stemming progresses.
j : int
Word length.
... | PorterStemmer |
python | django__django | tests/forms_tests/tests/tests.py | {
"start": 487,
"end": 599
} | class ____(ModelForm):
class Meta:
model = ChoiceFieldModel
fields = "__all__"
| ChoiceFieldForm |
python | django__django | tests/migrations/test_migrations_conflict_long_name/0002_conflicting_second_migration_with_long_name.py | {
"start": 43,
"end": 321
} | class ____(migrations.Migration):
dependencies = [("migrations", "0001_initial")]
operations = [
migrations.CreateModel(
"SomethingElse",
[
("id", models.AutoField(primary_key=True)),
],
),
]
| Migration |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 193712,
"end": 198100
} | class ____(FileObjectClassTestCase):
"""Repeat the tests from FileObjectClassTestCase with bufsize==0.
In this case (and in this case only), it should be possible to
create a file object, read a line from it, create another file
object, read another line from it, without loss of data in the
first ... | UnbufferedFileObjectClassTestCase |
python | astropy__astropy | astropy/units/quantity.py | {
"start": 5456,
"end": 8019
} | class ____(QuantityInfoBase):
"""
Container for meta information like name, description, format. This is
required when the object is used as a mixin column within a table, but can
be used as a general way to store meta information.
"""
_represent_as_dict_attrs = ("value", "unit")
_construc... | QuantityInfo |
python | psf__black | tests/test_black.py | {
"start": 118053,
"end": 119288
} | class ____:
"""Test that certain symbols that are commonly used externally keep working.
We don't (yet) formally expose an API (see issue #779), but we should endeavor to
keep certain functions that external users commonly rely on working.
"""
def test_format_str(self) -> None:
# format_s... | TestDeFactoAPI |
python | PyCQA__pylint | tests/test_func.py | {
"start": 3465,
"end": 6356
} | class ____(LintTestUsingModule):
def _check_result(self, got: str) -> None:
if not self._has_output():
return
try:
expected = self._get_expected()
except OSError:
expected = ""
if got != expected:
with open(self.output or "", "w", encod... | LintTestUpdate |
python | sympy__sympy | sympy/core/relational.py | {
"start": 38879,
"end": 39171
} | class ____(_Greater):
__doc__ = GreaterThan.__doc__
__slots__ = ()
rel_op = '>'
@classmethod
def _eval_fuzzy_relation(cls, lhs, rhs):
return is_gt(lhs, rhs)
@property
def weak(self):
return Ge(*self.args)
Gt = StrictGreaterThan
| StrictGreaterThan |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 92192,
"end": 92266
} | class ____(Binop):
operation = operator.xor
_operator_repr = "^"
| XOr |
python | redis__redis-py | redis/commands/search/querystring.py | {
"start": 6590,
"end": 6784
} | class ____(DisjunctNode):
"""
This node is true if *all* of its children are false. This is equivalent to
```
disjunct(union(...))
```
"""
JOINSTR = "|"
| DistjunctUnion |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 380172,
"end": 380625
} | class ____(sgqlc.types.Input):
"""Ordering options for user status connections."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(UserStatusOrderField), graphql_name="field")
"""The field to order user statuses by."""
directio... | UserStatusOrder |
python | django__django | tests/postgres_tests/test_operations.py | {
"start": 9261,
"end": 9362
} | class ____:
def allow_migrate(self, db, app_label, **hints):
return False
| NoMigrationRouter |
python | joblib__joblib | joblib/externals/loky/backend/queues.py | {
"start": 6145,
"end": 7322
} | class ____(mp_SimpleQueue):
def __init__(self, reducers=None, ctx=None):
super().__init__(ctx=ctx)
# Add possiblity to use custom reducers
self._reducers = reducers
def close(self):
self._reader.close()
self._writer.close()
# Use custom queue set/get state to be ab... | SimpleQueue |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py | {
"start": 1386,
"end": 3731
} | class ____(recurrent.AbstractRNNCell):
"""Base class for cells wrappers V2 compatibility.
This class along with `rnn_cell_impl._RNNCellWrapperV1` allows to define
wrappers that are compatible with V1 and V2, and defines helper methods for
this purpose.
"""
def __init__(self, cell, *args, **kwargs):
su... | _RNNCellWrapperV2 |
python | sqlalchemy__sqlalchemy | test/sql/test_returning.py | {
"start": 21524,
"end": 22397
} | class ____(fixtures.TestBase):
__requires__ = ("insert_returning",)
__sparse_driver_backend__ = True
@testing.provide_metadata
def test_select_doesnt_pollute_result(self, connection):
class MyType(TypeDecorator):
impl = Integer
cache_ok = True
def process_re... | CompositeStatementTest |
python | walkccc__LeetCode | solutions/1228. Missing Number In Arithmetic Progression/1228.py | {
"start": 0,
"end": 298
} | class ____:
def missingNumber(self, arr: list[int]) -> int:
n = len(arr)
delta = (arr[-1] - arr[0]) // n
l = 0
r = n - 1
while l < r:
m = (l + r) // 2
if arr[m] == arr[0] + m * delta:
l = m + 1
else:
r = m
return arr[0] + l * delta
| Solution |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks.py | {
"start": 18980,
"end": 25284
} | class ____(session_run_hook.SessionRunHook):
"""Saves checkpoints every N steps or seconds."""
def __init__(self,
checkpoint_dir,
save_secs=None,
save_steps=None,
saver=None,
checkpoint_basename="model.ckpt",
scaffold=None,
... | CheckpointSaverHook |
python | pytorch__pytorch | test/quantization/core/experimental/test_floatx.py | {
"start": 13956,
"end": 15120
} | class ____(TestCase):
# TODO(#146647): make the testing generic for shell dtypes
def test_float4_e2m1fn_x2(self, device):
# can create a tensor of dtype float4
x1 = torch.empty(4096, 4096, device=device, dtype=torch.float4_e2m1fn_x2)
# can create a string (so printing will work)
... | TestFloat4Dtype |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/lda.py | {
"start": 574,
"end": 3282
} | class ____(AutoSklearnClassificationAlgorithm):
def __init__(self, shrinkage, tol, shrinkage_factor=0.5, random_state=None):
self.shrinkage = shrinkage
self.tol = tol
self.shrinkage_factor = shrinkage_factor
self.estimator = None
def fit(self, X, Y):
import sklearn.discr... | LDA |
python | kamyu104__LeetCode-Solutions | Python/longest-balanced-subarray-i.py | {
"start": 75,
"end": 3018
} | class ____(object):
def longestBalanced(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
class SegmentTree(object):
def __init__(self, N):
self.min = [0]*(1<<((N-1).bit_length()+1))
self.max = [0]*(1<<((N-1).bit_length()+1))
... | Solution |
python | FactoryBoy__factory_boy | examples/flask_alchemy/demoapp_factories.py | {
"start": 211,
"end": 370
} | class ____(BaseFactory):
class Meta:
model = demoapp.User
username = factory.fuzzy.FuzzyText()
email = factory.fuzzy.FuzzyText()
| UserFactory |
python | pytorch__pytorch | torch/_inductor/select_algorithm.py | {
"start": 7573,
"end": 8721
} | class ____:
body: IndentedBuffer
template_mask: Optional[str] = None
template_out_shape: Optional[Union[str, tuple[str]]] = None
compute: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer)
indexing_code: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer)
loads: In... | SubgraphInfo |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 12897,
"end": 13233
} | class ____(SpanProperty):
def __init__(self, spans: "Spans") -> None:
super().__init__(spans)
self.result = IntList.of_length(len(self.spans))
def start_span(self, i: int, label_index: int) -> None:
self.result[i] = len(self.span_stack)
def finish(self) -> IntList:
return s... | _depths |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 27827,
"end": 30694
} | class ____(YosoPreTrainedModel):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "yoso.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
self.yoso = YosoModel(config)
... | YosoForMaskedLM |
python | django-haystack__django-haystack | haystack/backends/whoosh_backend.py | {
"start": 2151,
"end": 2455
} | class ____(HtmlFormatter):
"""
This is a HtmlFormatter simpler than the whoosh.HtmlFormatter.
We use it to have consistent results across backends. Specifically,
Solr, Xapian and Elasticsearch are using this formatting.
"""
template = "<%(tag)s>%(t)s</%(tag)s>"
| WhooshHtmlFormatter |
python | PrefectHQ__prefect | tests/server/models/test_variables.py | {
"start": 6667,
"end": 8108
} | class ____:
async def test_update_name(
self,
session,
variable,
):
new_name = "another_name"
updated = await update_variable(
session,
variable.id,
VariableUpdate(name=new_name), # type: ignore
)
assert updated
... | TestUpdateVariable |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py | {
"start": 5810,
"end": 6936
} | class ____(Benchmark):
r"""
Mishra 1 objective function.
This class defines the Mishra 1 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Mishra01}}(x) = (1 + x_n)^{x_n}
where
.. math::
x_n = n - \sum_{i... | Mishra01 |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 29955,
"end": 30395
} | class ____(VOTableSpecWarning):
"""
Bit values do not support masking. This warning is raised upon
setting masked data in a bit column.
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
`1.2
<http://www.ivoa.net/documents/... | W39 |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 20685,
"end": 21187
} | class ____(_SimulatedWithAsyncMixin,
_base.ForkMixin,
watcher):
# We'll have to implement this one completely manually.
_watcher_skip_ffi = False
def _register_loop_callback(self):
self.loop._fork_watchers.add(self)
def _unregister_loop_callback(self):
try:
... | fork |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_union.py | {
"start": 3363,
"end": 3815
} | class ____(ModelA):
pass
@pytest.mark.parametrize('input_value', [ModelA(b'bite', 2.3456), SubclassA(b'bite', 2.3456)])
def test_model_a(model_serializer: SchemaSerializer, input_value):
assert model_serializer.to_python(input_value) == {'a': b'bite', 'b': '2.3'}
assert model_serializer.to_python(input_va... | SubclassA |
python | cython__cython | Cython/Build/Tests/TestStripLiterals.py | {
"start": 131,
"end": 5285
} | class ____(unittest.TestCase):
maxDiff = None
@staticmethod
def _rebuild_string(stripped, literals):
def lookup(match):
return literals[match.group()]
return re.sub("__Pyx_L[0-9]+_", lookup, stripped)
def test_strip_string_literals(self):
def strip_equals(s, expect... | TestStripLiterals |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 43993,
"end": 44207
} | class ____(TypedDict, total=False):
"""
:class:`altair.AxisResolveMap` ``TypedDict`` wrapper.
Parameters
----------
x
y
"""
x: ResolveMode_T
y: ResolveMode_T
| AxisResolveMapKwds |
python | davidhalter__jedi | test/completion/precedence.py | {
"start": 705,
"end": 1304
} | class ____():
foo = 2
#? int()
(X.foo ** 3)
# -----------------
# assignments
# -----------------
x = [1, 'a', 1.0]
i = 0
i += 1
i += 1
#? float()
x[i]
i = 1
i += 1
i -= 3
i += 1
#? int()
x[i]
# -----------------
# in
# -----------------
if 'X' in 'Y':
a = 3
else:
a = ''
# For now don't really check f... | X |
python | great-expectations__great_expectations | docs/docusaurus/docs/core/trigger_actions_based_on_results/_examples/create_a_custom_action.py | {
"start": 709,
"end": 2261
} | class ____(ValidationAction):
# </snippet>
# 2. Set the `type` attribute to a unique string that identifies the Action.
# <snippet name="docs/docusaurus/docs/core/trigger_actions_based_on_results/_examples/create_a_custom_action.py - set type">
type: Literal["my_custom_action"] = "my_custom_action"
... | MyCustomAction |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/sql_event_log.py | {
"start": 4542,
"end": 138788
} | class ____(EventLogStorage):
"""Base class for SQL backed event log storages.
Distinguishes between run-based connections and index connections in order to support run-level
sharding, while maintaining the ability to do cross-run queries
"""
@abstractmethod
def run_connection(self, run_id: Opt... | SqlEventLogStorage |
python | kamyu104__LeetCode-Solutions | Python/number-of-beautiful-partitions.py | {
"start": 38,
"end": 871
} | class ____(object):
def beautifulPartitions(self, s, k, minLength):
"""
:type s: str
:type k: int
:type minLength: int
:rtype: int
"""
MOD = 10**9+7
PRIMES = {'2', '3', '5', '7'}
dp = [0]*len(s) # dp[i] at j : number of j beautiful partitions ... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 774150,
"end": 774383
} | class ____(sgqlc.types.Type, GitSignature):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("key_id",)
key_id = sgqlc.types.Field(String, graphql_name="keyId")
| GpgSignature |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-bedrock/llama_index/llms/bedrock/utils.py | {
"start": 9379,
"end": 9711
} | class ____(Provider):
max_tokens_key = "max_tokens"
def __init__(self) -> None:
self.messages_to_prompt = messages_to_llama_prompt
self.completion_to_prompt = completion_to_llama_prompt
def get_text_from_response(self, response: dict) -> str:
return response["outputs"][0]["text"]
... | MistralProvider |
python | simplejson__simplejson | simplejson/tests/test_bigint_as_string.py | {
"start": 59,
"end": 2238
} | class ____(TestCase):
# Python 2.5, at least the one that ships on Mac OS X, calculates
# 2 ** 53 as 0! It manages to calculate 1 << 53 correctly.
values = [(200, 200),
((1 << 53) - 1, 9007199254740991),
((1 << 53), '9007199254740992'),
((1 << 53) + 1, '900719925474... | TestBigintAsString |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/normalization.py | {
"start": 8075,
"end": 10049
} | class ____(torch.nn.InstanceNorm3d):
r"""This is the quantized version of :class:`~torch.nn.InstanceNorm3d`.
Additional args:
* **scale** - quantization scale of the output, type: double.
* **zero_point** - quantization zero point of the output, type: long.
"""
def __init__(
s... | InstanceNorm3d |
python | Netflix__metaflow | metaflow/_vendor/click/types.py | {
"start": 12481,
"end": 12951
} | class ____(ParamType):
name = "boolean"
def convert(self, value, param, ctx):
if isinstance(value, bool):
return bool(value)
value = value.lower()
if value in ("true", "t", "1", "yes", "y"):
return True
elif value in ("false", "f", "0", "no", "n"):
... | BoolParamType |
python | PrefectHQ__prefect | src/prefect/server/exceptions.py | {
"start": 407,
"end": 596
} | class ____(PrefectException):
"""An error raised by the Prefect REST API when attempting to create or update a
deployment with missing required variables.
"""
| MissingVariableError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 292083,
"end": 292731
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("EnterpriseMemberEdge"), graphql_name="edges"
)
nodes = sg... | EnterpriseMemberConnection |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 88414,
"end": 91814
} | class ____(Response):
"""
Response of events.get_multi_task_plots endpoint.
:param plots: Plots mapping (keyed by task name)
:type plots: dict
:param returned: Number of results returned
:type returned: int
:param total: Total number of results available for this query. In case there
... | GetMultiTaskPlotsResponse |
python | cython__cython | tests/run/withstat_py.py | {
"start": 3619,
"end": 4700
} | class ____(object):
def get(self, *args):
return ContextManager(*args)
def manager_from_expression():
"""
>>> manager_from_expression()
enter
1
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
enter
2
exit <type 'NoneType'> <type 'NoneType'> <type 'NoneType'>
... | GetManager |
python | django__django | tests/prefetch_related/test_uuid.py | {
"start": 2090,
"end": 4965
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
house = House.objects.create(name="Redwood", address="Arcata")
room = Room.objects.create(name="Racoon", house=house)
fleas = [Flea.objects.create(current_room=room) for i in range(3)]
pet = Pet.objects.create(name="Spook... | UUIDPrefetchRelatedLookups |
python | readthedocs__readthedocs.org | readthedocs/organizations/migrations/0010_add_stripe_customer.py | {
"start": 182,
"end": 1292
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("djstripe", "0010_alter_customer_balance"),
("organizations", "0009_update_meta_options"),
]
operations = [
migrations.AddField(
model_name="historicalorganization",
name="stri... | Migration |
python | tensorflow__tensorflow | tensorflow/python/framework/type_spec_test.py | {
"start": 2042,
"end": 3119
} | class ____(type_spec.TypeSpec):
"""A TypeSpec for the TwoTensors value type."""
def __init__(self, x_shape, x_dtype, y_shape, y_dtype, color="red"):
self.x_shape = tensor_shape.as_shape(x_shape)
self.x_dtype = dtypes.as_dtype(x_dtype)
self.y_shape = tensor_shape.as_shape(y_shape)
self.y_dtype = dty... | TwoTensorsSpec |
python | keon__algorithms | tests/test_matrix.py | {
"start": 5046,
"end": 6361
} | class ____(unittest.TestCase):
"""[summary]
Test for the file matrix_inversion.py
Arguments:
unittest {[type]} -- [description]
"""
def test_inversion(self):
from fractions import Fraction
m1 = [[1, 1], [1, 2]]
self.assertEqual(matrix_inversion.invert_matrix(m1),
... | TestInversion |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 123469,
"end": 123866
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(PullRequestOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgqlc.... | PullRequestOrder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/test_streams.py | {
"start": 3055,
"end": 7170
} | class ____:
def generate_records(self, stream_name, count) -> Union[Mapping[str, List[Mapping[str, Any]]], Mapping[str, Any]]:
if not stream_name:
return {f"record_{1}": f"test_{1}"}
result = []
for i in range(0, count):
result.append({f"record_{i}": f"test_{i}"})
... | TestFullRefreshStreams |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 487211,
"end": 487528
} | 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("PackageFile", graphql_name="node")
| PackageFileEdge |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 15426,
"end": 15679
} | class ____(Interface):
def __call__(info):
"""Return an object that implements
:class:`pyramid.interfaces.IRenderer`. ``info`` is an
object that implements :class:`pyramid.interfaces.IRendererInfo`.
"""
| IRendererFactory |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/subset/default.py | {
"start": 574,
"end": 8310
} | class ____(
PartitionsSubset,
NamedTuple("_DefaultPartitionsSubset", [("subset", Set[str])]),
):
# Every time we change the serialization format, we should increment the version number.
# This will ensure that we can gracefully degrade when deserializing old data.
SERIALIZATION_VERSION = 1
def ... | DefaultPartitionsSubset |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/flare/base.py | {
"start": 2989,
"end": 10725
} | class ____(Chain):
"""Flare chain.
Chain that combines a retriever, a question generator,
and a response generator.
See [Active Retrieval Augmented Generation](https://arxiv.org/abs/2305.06983) paper.
"""
question_generator_chain: Runnable
"""Chain that generates questions from uncertain ... | FlareChain |
python | falconry__falcon | tests/test_error_handlers.py | {
"start": 509,
"end": 882
} | class ____(CustomBaseException):
@staticmethod
def handle(req, resp, ex, params):
raise falcon.HTTPError(
falcon.HTTP_792,
title='Internet crashed!',
description='Catastrophic weather event',
href='http://example.com/api/inconvenient-truth',
hr... | CustomException |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 18998,
"end": 20500
} | class ____(HelperFunction):
def _calculate(self, X, y, logger, feat_type):
numerical = {
key: True if value.lower() == "numerical" else False
for key, value in feat_type.items()
}
kurts = []
for i in range(X.shape[1]):
if numerical[X.columns[i] if ... | Kurtosisses |
python | huggingface__transformers | src/transformers/models/smollm3/modeling_smollm3.py | {
"start": 22916,
"end": 23305
} | class ____(GenericForQuestionAnswering, SmolLM3PreTrainedModel):
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
__all__ = [
"SmolLM3PreTrainedModel",
"SmolLM3Model",
"SmolLM3ForCausalLM",
"SmolLM3ForSequenceClassification",
"SmolLM3ForTokenClassifi... | SmolLM3ForQuestionAnswering |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/completion/word_completer.py | {
"start": 320,
"end": 3435
} | class ____(Completer):
"""
Simple autocompletion on a list of words.
:param words: List of words or callable that returns a list of words.
:param ignore_case: If True, case-insensitive completion.
:param meta_dict: Optional dict mapping words to their meta-text. (This
should map strings to ... | WordCompleter |
python | joke2k__faker | tests/test_factory.py | {
"start": 258,
"end": 12282
} | class ____(unittest.TestCase):
def setUp(self):
self.generator = Generator()
def test_documentor(self):
from faker.cli import print_doc
output = io.StringIO()
print_doc(output=output)
print_doc("address", output=output)
print_doc("faker.providers.person.it_IT", ... | FactoryTestCase |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 58421,
"end": 59170
} | class ____(PrefectFilterBaseModel):
"""Filter by `BlockSchema.capabilities`"""
all_: Optional[list[str]] = Field(
default=None,
examples=[["write-storage", "read-storage"]],
description=(
"A list of block capabilities. Block entities will be returned only if an"
... | BlockSchemaFilterCapabilities |
python | pola-rs__polars | py-polars/src/polars/io/cloud/credential_provider/_providers.py | {
"start": 18212,
"end": 19380
} | class ____(CredentialProvider):
"""User-provided GCP token in storage_options."""
def __init__(self, token: str) -> None:
self.token = token
def __call__(self) -> CredentialProviderFunctionReturn:
return {"bearer_token": self.token}, None
def _get_credentials_from_provider_expiry_aware(
... | UserProvidedGCPToken |
python | qdrant__qdrant-client | qdrant_client/http/api_client.py | {
"start": 9649,
"end": 9800
} | class ____:
async def __call__(self, request: Request, call_next: SendAsync) -> Response:
return await call_next(request)
| BaseAsyncMiddleware |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/sqlparser.py | {
"start": 7688,
"end": 21022
} | class ____(LoggingMixin):
"""
Interface for openlineage-sql.
:param dialect: dialect specific to the database
:param default_schema: schema applied to each table with no schema parsed
"""
def __init__(self, dialect: str | None = None, default_schema: str | None = None) -> None:
super()... | SQLParser |
python | huggingface__transformers | tests/models/depth_pro/test_modeling_depth_pro.py | {
"start": 12435,
"end": 14785
} | class ____(unittest.TestCase):
def test_inference_depth_estimation(self):
model_path = "apple/DepthPro-hf"
image_processor = DepthProImageProcessor.from_pretrained(model_path)
model = DepthProForDepthEstimation.from_pretrained(model_path).to(torch_device)
config = model.config
... | DepthProModelIntegrationTest |
python | qdrant__qdrant-client | qdrant_client/local/distances.py | {
"start": 1994,
"end": 10161
} | class ____:
def __init__(self, context_pairs: list[ContextPair]):
self.context_pairs = context_pairs
DenseQueryVector = Union[
DiscoveryQuery,
ContextQuery,
RecoQuery,
]
def distance_to_order(distance: models.Distance) -> DistanceOrder:
"""
Convert distance to order
Args:
... | ContextQuery |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property2.py | {
"start": 120,
"end": 610
} | class ____(abc.ABC):
@abc.abstractproperty
def x(self) -> int:
raise NotImplementedError
@x.setter
def x(self, value: int):
raise NotImplementedError
@abc.abstractproperty
def y(self) -> float:
raise NotImplementedError
a = Foo()
requires_int(a.x)
a.x = 3
# This sho... | Foo |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 689,
"end": 888
} | class ____(DistutilsError):
"""Unable to load an expected module, or to find an expected class
within some module (in particular, command modules and classes)."""
pass
| DistutilsModuleError |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 42141,
"end": 42385
} | class ____(Callback):
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
if not trainer.sanity_checking and batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledCallbackOnValidationBatchEnd |
python | django-extensions__django-extensions | django_extensions/management/commands/dumpscript.py | {
"start": 15519,
"end": 20922
} | class ____(Code):
"""Produces a complete python script that can recreate data for the given apps."""
def __init__(self, models, context=None, stdout=None, stderr=None, options=None):
super().__init__(stdout=stdout, stderr=stderr)
self.imports = {}
self.models = models
if contex... | Script |
python | pytorch__pytorch | test/dynamo/test_generator.py | {
"start": 467,
"end": 1374
} | class ____(torch._dynamo.test_case.TestCaseWithNestedGraphBreaks):
def setUp(self):
super().setUp()
self._old = torch._dynamo.config.enable_faithful_generator_behavior
torch._dynamo.config.enable_faithful_generator_behavior = True
self._unittest_old = torch._dynamo.config.enable_trac... | GeneratorTestsBase |
python | google__pytype | pytype/tests/test_cmp1.py | {
"start": 1491,
"end": 2797
} | class ____(test_base.BaseTest):
"""Test for "x not in y". Also test overloading of this operator."""
def test_concrete(self):
ty, errors = self.InferWithErrors("""
def f(x, y):
return x not in y # unsupported-operands[e]
f(1, [1])
f(1, [2])
f("x", "x")
f("y", "x")
f... | NotInTest |
python | kamyu104__LeetCode-Solutions | Python/verbal-arithmetic-puzzle.py | {
"start": 64,
"end": 1711
} | class ____(object):
def isSolvable(self, words, result):
"""
:type words: List[str]
:type result: str
:rtype: bool
"""
def backtracking(words, result, i, j, carry, lookup, used):
if j == len(result):
return carry == 0
if i != l... | Solution |
python | pytorch__pytorch | .ci/lumen_cli/cli/lib/core/vllm/vllm_test.py | {
"start": 1729,
"end": 9941
} | class ____(BaseRunner):
def __init__(self, args: Any):
self.work_directory = "vllm"
self.test_plan = ""
self.test_type = TestInpuType.UNKNOWN
self.shard_id = args.shard_id
self.num_shards = args.num_shards
if args.test_plan:
self.test_plan = args.test_pl... | VllmTestRunner |
python | ray-project__ray | python/ray/serve/tests/unit/test_cli.py | {
"start": 914,
"end": 1478
} | class ____:
def __init__(self):
self._deployed_config: Optional[Dict] = None
@property
def deployed_config(self) -> Optional[Dict]:
return self._deployed_config
def deploy_applications(self, config: Dict):
self._deployed_config = config
@pytest.fixture
def fake_serve_client()... | FakeServeSubmissionClient |
python | jina-ai__jina | tests/integration/hub_usage/hub-mwu/mwu_encoder.py | {
"start": 62,
"end": 292
} | class ____(Executor):
def __init__(self, greetings: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._greetings = greetings
@requests
def encode(self, **kwargs) -> Any:
pass
| MWUEncoder |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 7677,
"end": 8079
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter by `FlowRun.parent_task_run_id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of flow run parent_task_run_ids to include"
)
is_null_: Optional[bool] = Field(
default=None,
description="If true, on... | FlowRunFilterParentTaskRunId |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_config_migrations.py | {
"start": 5424,
"end": 8701
} | class ____:
OLD_TEST1_CONFIG_PATH = _config_path(f"{_EXCLUDE_DELETE_CONFIGS_PATH}/test_old_config.json")
NEW_TEST1_CONFIG_PATH = _config_path(f"{_EXCLUDE_DELETE_CONFIGS_PATH}/test_new_config.json")
OLD_TEST2_CONFIG_PATH = _config_path(f"{_INCLUDE_DELETE_CONFIGS_PATH}/test_old_config.json")
NEW_TEST2_CON... | TestMigrateIncludeDeletedToStatusFilters |
python | ipython__ipython | IPython/lib/backgroundjobs.py | {
"start": 15958,
"end": 16756
} | class ____(BackgroundJobBase):
"""Evaluate an expression as a background job (uses a separate thread)."""
def __init__(self, expression, glob=None, loc=None):
"""Create a new job from a string which can be fed to eval().
global/locals dicts can be provided, which will be passed to the eval
... | BackgroundJobExpr |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/12_Proximal_Policy_Optimization/simply_PPO.py | {
"start": 867,
"end": 6467
} | class ____(object):
def __init__(self):
self.sess = tf.Session()
self.tfs = tf.placeholder(tf.float32, [None, S_DIM], 'state')
# critic
with tf.variable_scope('critic'):
l1 = tf.layers.dense(self.tfs, 100, tf.nn.relu)
self.v = tf.layers.dense(l1, 1)
... | PPO |
python | PyCQA__pylint | tests/functional/c/class_attributes.py | {
"start": 122,
"end": 415
} | class ____:
"dummy class"
def __init__(self):
self.topic = 5
self._data = 45
def change_type(self, new_class):
"""Change type"""
self.__class__ = new_class
def do_nothing(self):
"I do nothing useful"
return self.topic + 56
| Clazz |
python | scikit-image__scikit-image | src/skimage/transform/_geometric.py | {
"start": 31459,
"end": 45011
} | class ____(_HMatrixTransform):
r"""Projective transformation.
Apply a projective transformation (homography) on coordinates.
For each homogeneous coordinate :math:`\mathbf{x} = [x, y, 1]^T`, its
target position is calculated by multiplying with the given matrix,
:math:`H`, to give :math:`H \mathbf... | ProjectiveTransform |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/blob/fake_blob_client.py | {
"start": 4863,
"end": 5135
} | class ____:
"""Mock of a Blob file downloader for testing."""
def __init__(self, contents):
self.contents = contents
def readall(self):
return self.contents
def readinto(self, fileobj):
fileobj.write(self.contents)
| FakeBlobDownloader |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/fakes/fake_adls2_resource.py | {
"start": 4423,
"end": 6142
} | class ____:
"""Stateful mock of an ADLS2 file client for testing."""
def __init__(self, name, fs_client):
self.name = name
self.contents = None
self._lease = None
self.fs_client = fs_client
@property
def lease(self):
return self._lease if self._lease is None els... | FakeADLS2FileClient |
python | ansible__ansible | lib/ansible/modules/user.py | {
"start": 64435,
"end": 64745
} | class ____(FreeBsdUser):
"""
This is a DragonFlyBSD User manipulation class - it inherits the
FreeBsdUser class behaviors, such as using the pw command to
manipulate the user database, followed by the chpass command
to change the password.
"""
platform = 'DragonFly'
| DragonFlyBsdUser |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 136726,
"end": 138179
} | class ____(ASTTemplateParam):
def __init__(self, data: ASTTemplateKeyParamPackIdDefault) -> None:
assert data
self.data = data
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemplateParamType):
return NotImplemented
return self.data == other.dat... | ASTTemplateParamType |
python | numba__numba | numba/tests/test_range.py | {
"start": 5324,
"end": 5643
} | class ____(TestCase):
def test_range_safe_cast_mixed(self):
"""Test that mixing `uint64` and `int64` works."""
a = my_arange(np.uint64(6), np.uint64(0), np.int64(-1))
self.assertPreciseEqual(a, np.arange(6, 0, -1, dtype=np.uint64))
if __name__ == '__main__':
unittest.main()
| TestRangeNumpy |
python | doocs__leetcode | solution/2600-2699/2663.Lexicographically Smallest Beautiful String/Solution.py | {
"start": 0,
"end": 769
} | class ____:
def smallestBeautifulString(self, s: str, k: int) -> str:
n = len(s)
cs = list(s)
for i in range(n - 1, -1, -1):
p = ord(cs[i]) - ord('a') + 1
for j in range(p, k):
c = chr(ord('a') + j)
if (i > 0 and cs[i - 1] == c) or (i >... | Solution |
python | numpy__numpy | numpy/_core/tests/test_scalarmath.py | {
"start": 5836,
"end": 8022
} | class ____:
@pytest.mark.xfail(check_support_sve(), reason="gh-22982")
def test_blocked(self):
# test alignments offsets for simd instructions
# alignments for vz + 2 * (vs - 1) + 1
for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
for out, inp1, inp2, msg in... | TestBaseMath |
python | plotly__plotly.py | plotly/graph_objs/contourcarpet/_stream.py | {
"start": 233,
"end": 3541
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contourcarpet"
_path_str = "contourcarpet.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` ... | Stream |
python | modin-project__modin | modin/error_message.py | {
"start": 928,
"end": 5397
} | class ____(object):
# Only print full ``default to pandas`` warning one time.
printed_default_to_pandas = False
printed_warnings: Set[int] = set() # Set of hashes of printed warnings
@classmethod
def not_implemented(cls, message: str = "") -> NoReturn:
if message == "":
message... | ErrorMessage |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_descriptors.py | {
"start": 7925,
"end": 8610
} | class ____:
def test___init__(self) -> None:
f = Alias("bar")
d = bcpd.AliasPropertyDescriptor("foo", f)
assert d.name == "foo"
assert d.aliased_name == "bar"
assert d.property == f
assert d.__doc__ == "This is a compatibility alias for the 'bar' property."
def t... | Test_AliasDescriptor |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 2920,
"end": 3534
} | class ____(nn.Module):
"""
Construct the CvT embeddings.
"""
def __init__(self, patch_size, num_channels, embed_dim, stride, padding, dropout_rate):
super().__init__()
self.convolution_embeddings = CvtConvEmbeddings(
patch_size=patch_size, num_channels=num_channels, embed_di... | CvtEmbeddings |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 4377,
"end": 4482
} | class ____(Web3Exception):
"""
Raised when a supplied value is invalid.
"""
| Web3ValidationError |
python | cython__cython | Cython/Compiler/FlowControl.py | {
"start": 9971,
"end": 10429
} | class ____:
"""Exception handling helper.
entry_point ControlBlock Exception handling entry point
finally_enter ControlBlock Normal finally clause entry point
finally_exit ControlBlock Normal finally clause exit point
"""
def __init__(self, entry_point, finally_enter=None, finally_exit=None... | ExceptionDescr |
python | ansible__ansible | test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/lookup/lookup_subdir/my_subdir_lookup.py | {
"start": 84,
"end": 212
} | class ____(LookupBase):
def run(self, terms, variables, **kwargs):
return ['subdir_lookup_from_user_dir']
| LookupModule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.