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 | great-expectations__great_expectations | great_expectations/datasource/fluent/data_connector/s3_data_connector.py | {
"start": 793,
"end": 959
} | class ____(pydantic.BaseModel):
s3_prefix: str = ""
s3_delimiter: str = "/"
s3_max_keys: int = 1000
s3_recursive_file_discovery: bool = False
| _S3Options |
python | lazyprogrammer__machine_learning_examples | rnn_class/batch_parity.py | {
"start": 512,
"end": 5864
} | class ____:
def __init__(self, M):
self.M = M # hidden layer size
def fit(self, X, Y, batch_sz=20, learning_rate=1.0, mu=0.99, reg=1.0, activation=T.tanh, epochs=100, show_fig=False):
D = X[0].shape[1] # X is of size N x T(n) x D
K = len(set(Y.flatten()))
N = len(Y)
M = ... | SimpleRNN |
python | Pylons__pyramid | tests/test_request.py | {
"start": 156,
"end": 12385
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _getTargetClass(self):
from pyramid.request import Request
return Request
def _makeOne(self, environ=None):
if environ is None:
... | TestRequest |
python | getsentry__sentry | src/sentry/replays/lib/event_linking.py | {
"start": 566,
"end": 675
} | class ____(TypedDict):
type: str
replay_id: str
timestamp: int
event_hash: str
| EventLinkPayload |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-autoembeddings/llama_index/embeddings/autoembeddings/base.py | {
"start": 349,
"end": 1817
} | class ____(BaseEmbedding):
"""
Autoembeddings from chonkie.
Args:
model_name (str): The name of the model to use.
"""
model_name: str
embedder: Optional[chonkie.BaseEmbeddings] = None
def __init__(self, model_name: str) -> None:
super().__init__(model_name=model_name)
... | ChonkieAutoEmbedding |
python | pydata__xarray | asv_bench/benchmarks/pandas.py | {
"start": 106,
"end": 735
} | class ____:
def setup(self, dtype, subset):
data = np.random.rand(100000).astype(dtype)
index = pd.MultiIndex.from_product(
[
list("abcdefhijk"),
list("abcdefhijk"),
pd.date_range(start="2000-01-01", periods=1000, freq="D"),
]
... | MultiIndexSeries |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/index_shuffle_test.py | {
"start": 6687,
"end": 8679
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(
self,
num_elements_per_file,
num_files,
num_epochs,
seed=None,
reshuffle_each_iteration=None,
symbolic_checkpoint=None,
):
file_infos = []
... | IndexShuffleCheckpointTest |
python | celery__celery | t/unit/worker/test_autoscale.py | {
"start": 221,
"end": 815
} | class ____(BasePool):
shrink_raises_exception = False
shrink_raises_ValueError = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._pool = Bunch(_processes=self.limit)
def grow(self, n=1):
self._pool._processes += n
def shrink(self, n=1):
... | MockPool |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_minnesota_zip.py | {
"start": 752,
"end": 1759
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_minnesota_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pan... | ColumnValuesToBeValidMinnesotaZip |
python | run-llama__llama_index | llama-index-core/llama_index/core/memory/types.py | {
"start": 2412,
"end": 5034
} | class ____(BaseMemory):
"""Base class for storing multi-tenant chat history."""
chat_store: SerializeAsAny[BaseChatStore] = Field(default_factory=SimpleChatStore)
chat_store_key: str = Field(default=DEFAULT_CHAT_STORE_KEY)
@field_serializer("chat_store")
def serialize_courses_in_order(self, chat_s... | BaseChatStoreMemory |
python | scipy__scipy | scipy/linalg/tests/test_decomp_update.py | {
"start": 2725,
"end": 3342
} | class ____:
def setup_method(self):
self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
self.atol = 10 * np.finfo(self.dtype).eps
def generate(self, type, mode='full'):
rng = np.random.default_rng(29382)
shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
... | BaseQRdeltas |
python | crytic__slither | slither/tools/upgradeability/checks/variables_order.py | {
"start": 300,
"end": 1849
} | class ____(AbstractCheck):
ARGUMENT = "missing-variables"
IMPACT = CheckClassification.MEDIUM
HELP = "Variable missing in the v2"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#missing-variables"
WIKI_TITLE = "Missing variables"
# region wiki_description
WIKI_DESCRIPT... | MissingVariable |
python | numpy__numpy | tools/swig/test/testFlat.py | {
"start": 2883,
"end": 3144
} | class ____(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
| ucharTestCase |
python | fastai__fastai | fastai/layers.py | {
"start": 12164,
"end": 12941
} | class ____(Module):
"Self attention layer for `n_channels`."
def __init__(self, n_channels):
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels)]
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return Conv... | SelfAttention |
python | python__mypy | mypy/typeanal.py | {
"start": 4576,
"end": 89288
} | class ____(SyntheticTypeVisitor[Type], TypeAnalyzerPluginInterface):
"""Semantic analyzer for types.
Converts unbound types into bound types. This is a no-op for already
bound types.
If an incomplete reference is encountered, this does a defer. The
caller never needs to defer.
"""
# Is th... | TypeAnalyser |
python | Netflix__metaflow | metaflow/plugins/cards/exception.py | {
"start": 4485,
"end": 5222
} | class ____(MetaflowException):
headline = "Component overwrite is not supported"
def __init__(self, component_id, card_id, card_type):
id_str = ""
if card_id is not None:
id_str = "id='%s'" % card_id
msg = (
"Card component overwrite is not supported. "
... | ComponentOverwriteNotSupportedException |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 2520,
"end": 5056
} | class ____(fixtures.TablesTest):
"""Test the dialect sends appropriate ORDER BY expressions when
labels are used.
This essentially exercises the "supports_simple_order_by_label"
setting.
"""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table... | OrderByLabelTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/events.py | {
"start": 26075,
"end": 27563
} | class ____(Exception):
"""Event indicating op failure.
Raise events of this type from within op compute functions or custom type checks in order to
indicate an unrecoverable failure in user code to the Dagster machinery and return
structured metadata about the failure.
Args:
description (O... | Failure |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 203720,
"end": 208657
} | class ____(TypedDict, total=False):
"""
:class:`altair.PointSelectionConfig` ``TypedDict`` wrapper.
Parameters
----------
type
Determines the default event processing and data query for the selection. Vega-Lite
currently supports two selection types:
* ``"point"`` -- to sel... | PointSelectionConfigKwds |
python | bokeh__bokeh | tests/unit/bokeh/document/test_events__document.py | {
"start": 10261,
"end": 12478
} | class ____:
def test_init(self) -> None:
doc = Document()
m = SomeModel()
e = bde.ColumnsStreamedEvent(doc, m, "data", dict(foo=1), 200, "setter", "invoker")
assert e.document == doc
assert e.model == m
assert e.attr == "data"
assert e.data == dict(foo=1)
... | TestColumnsStreamedEvent |
python | apache__airflow | providers/yandex/src/airflow/providers/yandex/operators/dataproc.py | {
"start": 19866,
"end": 23017
} | class ____(DataprocBaseOperator):
"""
Runs Spark job in Data Proc cluster.
:param main_jar_file_uri: URI of jar file with job. Can be placed in HDFS or S3.
:param main_class: Name of the main class of the job.
:param file_uris: URIs of files used in the job. Can be placed in HDFS or S3.
:param ... | DataprocCreateSparkJobOperator |
python | apache__airflow | airflow-core/src/airflow/models/expandinput.py | {
"start": 5064,
"end": 6543
} | class ____:
value: list
EXPAND_INPUT_TYPE: ClassVar[str] = "list-of-dicts"
def get_parse_time_mapped_ti_count(self) -> int:
if isinstance(self.value, Sized):
return len(self.value)
raise NotFullyPopulated({"expand_kwargs() argument"})
def get_total_map_length(self, run_id:... | SchedulerListOfDictsExpandInput |
python | realpython__materials | python-practice-problems/sudokusolve.py | {
"start": 1377,
"end": 3544
} | class ____(unittest.TestCase):
problems = [
"00400607900000060205609230007806103050900040602054089000741092010500"
"0000840600100",
"01640000020000900040000006207023010010000000300308704096000000500080"
"0007000006820",
"0490086050030070000000000300004008000608150200010090000... | SudokuSolverTestCase |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 36042,
"end": 36375
} | class ____(BaseModel):
dc: DC2
""")
Model = module_2.Model
Model(dc=dict(a=1, b='not_an_int'))
@pytest.mark.skipif(sys.version_info < (3, 12), reason='Requires PEP 695 syntax')
def test_class_locals_are_kept_during_schema_generation(create_module):
create_module(
"""
from pydantic import... | Model |
python | ray-project__ray | python/ray/tune/tests/test_commands.py | {
"start": 434,
"end": 6045
} | class ____:
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
self.captured = []
return self
def __exit__(self, *args):
self.captured.extend(self._stringio.getvalue().splitlines())
del self._stringio # free up some memory
... | Capturing |
python | walkccc__LeetCode | solutions/880. Decoded String at Index/880.py | {
"start": 0,
"end": 340
} | class ____:
def decodeAtIndex(self, s: str, k: int) -> str:
size = 0
for c in s:
if c.isdigit():
size *= int(c)
else:
size += 1
for c in reversed(s):
k %= size
if k == 0 and c.isalpha():
return c
if c.isdigit():
size //= int(c)
else:
... | Solution |
python | doocs__leetcode | solution/0000-0099/0089.Gray Code/Solution.py | {
"start": 0,
"end": 114
} | class ____:
def grayCode(self, n: int) -> List[int]:
return [i ^ (i >> 1) for i in range(1 << n)]
| Solution |
python | django__django | tests/defer/tests.py | {
"start": 16347,
"end": 17250
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.secondary = Secondary.objects.create(first="a", second="b")
cls.primary = PrimaryOneToOne.objects.create(
name="Bella", value="Baxter", related=cls.secondary
)
def test_defer_not_clear_cached_relations(self):... | DeferredRelationTests |
python | coleifer__peewee | tests/postgres.py | {
"start": 4282,
"end": 9536
} | class ____(ModelTestCase):
database = db_loader('postgres', db_class=PostgresqlExtDatabase,
register_hstore=True)
requires = [HStoreModel]
def setUp(self):
super(TestHStoreField, self).setUp()
self.t1 = HStoreModel.create(name='t1', data={'k1': 'v1', 'k2': 'v2'})
... | TestHStoreField |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 2883,
"end": 3345
} | class ____(Generic[_W]):
"""A warning meant to be formatted during runtime.
This is used to hold warnings that need to format their message at runtime,
as opposed to a direct message.
"""
category: type[_W]
template: str
def format(self, **kwargs: Any) -> _W:
"""Return an instance... | UnformattedWarning |
python | python-pillow__Pillow | src/PIL/BlpImagePlugin.py | {
"start": 12384,
"end": 14293
} | class ____(_BLPBaseDecoder):
def _load(self) -> None:
self._compression, self._encoding, alpha, self._alpha_encoding = self.args
palette = self._read_palette()
assert self.fd is not None
self.fd.seek(self._offsets[0])
if self._compression == 1:
# Uncompressed o... | BLP2Decoder |
python | gevent__gevent | src/gevent/tests/test__core_timer.py | {
"start": 1927,
"end": 2381
} | class ____(Test):
repeat = 1
def test_main(self):
# Again works for a new timer
x = self.timer
x.again(self.f, x)
self.assertTimerInKeepalive()
self.assertEqual(x.args, (x,))
# XXX: On libev, this takes 1 second. On libuv,
# it takes the expected time.
... | TestAgain |
python | huggingface__transformers | src/transformers/models/cwm/modular_cwm.py | {
"start": 8666,
"end": 9166
} | class ____(Qwen2Attention):
def __init__(self, config: CwmConfig, layer_idx: int):
super().__init__(config=config, layer_idx=layer_idx)
self.q_proj = torch.nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
self.k_proj = torch.nn.Linear(config.hidden_size, ... | CwmAttention |
python | huggingface__transformers | src/transformers/models/xcodec/modeling_xcodec.py | {
"start": 12190,
"end": 17123
} | class ____(PreTrainedAudioTokenizerBase):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = XcodecConfig
base_model_prefix = "xcodec"
main_input_name = "input_values"
input_modalities = "audio"... | XcodecPreTrainedModel |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 2870,
"end": 3291
} | class ____(Protocol):
@property
def f(self) -> int: ...
@property
def g(self) -> str: ...
# end
# no error
def f(
a,
):
pass
# end
# no error
if True:
class Class:
"""Docstring"""
def function(self):
...
# end
# no error
if True:
def function(self):
... | C |
python | plotly__plotly.py | plotly/graph_objs/box/selected/_marker.py | {
"start": 233,
"end": 3564
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "box.selected"
_path_str = "box.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
The 'color' property is a color and may be specified... | Marker |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/query.py | {
"start": 436,
"end": 2851
} | class ____:
"""
Represents an MQL query that can be run against Snuba.
Example:
# Defining a simple query.
query = MQLQuery("avg(d:transactions/duration@millisecond)", order=QueryOrder.ASC, limit=10)
# Defining more complex queries that depend on each other.
query_1 = MQLQuery("avg(d:trans... | MQLQuery |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_events_reader.py | {
"start": 26496,
"end": 31673
} | class ____(GraphExecutionTraceDigest):
"""Detailed data object describing an intra-graph tensor execution.
Attributes (in addition to GraphExecutionTraceDigest):
graph_ids: The debugger-generated IDs of the graphs that enclose the
executed op (tensor), ordered from the outermost to the innermost.
gra... | GraphExecutionTrace |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 34169,
"end": 34687
} | class ____(DelegatingLexer):
"""
A lexer that highlights CSS definitions in genshi text templates.
"""
name = 'CSS+Genshi Text'
aliases = ['css+genshitext', 'css+genshi']
alias_filenames = ['*.css']
mimetypes = ['text/css+genshi']
def __init__(self, **options):
super(CssGenshiL... | CssGenshiLexer |
python | celery__celery | t/unit/utils/test_threads.py | {
"start": 1092,
"end": 1492
} | class ____:
def test_stack(self):
x = _LocalStack()
assert x.pop() is None
x.__release_local__()
ident = x.__ident_func__
x.__ident_func__ = ident
with pytest.raises(RuntimeError):
x()[0]
x.push(['foo'])
assert x()[0] == 'foo'
x.... | test_LocalStack |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/N803.py | {
"start": 40,
"end": 180
} | class ____:
def method(self, _, a, A):
return _, a, A
def func(_, setUp):
return _, setUp
from typing import override
| Class |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 50180,
"end": 51032
} | class ____:
__slots__ = ("handler", "in_shardings", "in_layouts", "local_devices",
"input_indices")
def __init__(self, in_shardings, in_layouts, local_devices=None,
input_indices=None):
self.handler = partial(
shard_args, in_shardings, in_layouts,
[xc.ArrayCopySema... | InputsHandler |
python | huggingface__transformers | tests/models/dac/test_feature_extraction_dac.py | {
"start": 3340,
"end": 8903
} | class ____(SequenceFeatureExtractionTestMixin, unittest.TestCase):
feature_extraction_class = DacFeatureExtractor
def setUp(self):
self.feat_extract_tester = DacFeatureExtractionTester(self)
def test_call(self):
# Tests that all call wrap to encode_plus and batch_encode_plus
feat_e... | DacFeatureExtractionTest |
python | mlflow__mlflow | mlflow/webhooks/types.py | {
"start": 8599,
"end": 9245
} | class ____(TypedDict):
"""Payload sent when a tag is deleted from a prompt version.
Example payload:
.. code-block:: python
{
"name": "example_prompt",
"version": "1",
"key": "example_key",
}
"""
name: str
"""The name of the prompt."""
... | PromptVersionTagDeletedPayload |
python | huggingface__transformers | tests/models/dpr/test_tokenization_dpr.py | {
"start": 1637,
"end": 3794
} | class ____(test_tokenization_bert.BertTokenizationTest):
tokenizer_class = DPRReaderTokenizer
rust_tokenizer_class = DPRReaderTokenizerFast
test_rust_tokenizer = True
test_seq2seq = False
from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base"
@slow
def test_decode_best_spans(self):
... | DPRReaderTokenizationTest |
python | getsentry__sentry | src/sentry/api/serializers/models/organization.py | {
"start": 20283,
"end": 21770
} | class ____(_DetailedOrganizationSerializerResponseOptional):
experiments: Any
isDefault: bool
defaultRole: str # TODO: replace with enum/literal
availableRoles: list[Any] # TODO: deprecated, use orgRoleList
orgRoleList: list[OrganizationRoleSerializerResponse]
teamRoleList: list[TeamRoleSerial... | DetailedOrganizationSerializerResponse |
python | getsentry__sentry | src/sentry/integrations/github/types.py | {
"start": 178,
"end": 435
} | class ____(StrEnum):
OPEN = "open"
CLOSED = "closed"
@classmethod
def get_choices(cls):
"""Return choices formatted for dropdown selectors"""
return [(status.value, status.value.capitalize()) for status in cls]
| GitHubIssueStatus |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 39383,
"end": 39507
} | class ____(RegexAutomationRuleMixin, CreateView):
success_message = _("Automation rule created")
| RegexAutomationRuleCreate |
python | prabhupant__python-ds | data_structures/bst/insertion_iterative.py | {
"start": 0,
"end": 862
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
new_node = Node(val)
parent = None
curr = root
while curr:
parent = curr
if curr.val <= val:
curr = curr.right
else:
... | Node |
python | keras-team__keras | integration_tests/basic_full_flow.py | {
"start": 684,
"end": 1582
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basic_fit(self):
model = MyModel(hidden_dim=2, output_dim=1)
x = np.random.random((128, 4))
y = np.random.random((128, 4))
batch_size = 32
epochs = 3
model.compile(
optimi... | BasicFlowTest |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 2623,
"end": 5192
} | class ____(pallas_core.CompilerParams):
"""Mosaic GPU compiler parameters.
Attributes:
approx_math: If True, the compiler is allowed to use approximate
implementations of some math operations, e.g. ``exp``. Defaults to False.
dimension_semantics: A list of dimension semantics for each grid
dime... | CompilerParams |
python | anthropics__anthropic-sdk-python | src/anthropic/types/url_image_source_param.py | {
"start": 219,
"end": 329
} | class ____(TypedDict, total=False):
type: Required[Literal["url"]]
url: Required[str]
| URLImageSourceParam |
python | django__django | django/contrib/redirects/apps.py | {
"start": 91,
"end": 251
} | class ____(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "django.contrib.redirects"
verbose_name = _("Redirects")
| RedirectsConfig |
python | eventlet__eventlet | eventlet/coros.py | {
"start": 39,
"end": 2030
} | class ____:
"""This is sort of an inverse semaphore: a counter that starts at 0 and
waits only if nonzero. It's used to implement a "wait for all" scenario.
>>> from eventlet import coros, spawn_n
>>> count = coros.metaphore()
>>> count.wait()
>>> def decrementer(count, id):
... print("... | metaphore |
python | readthedocs__readthedocs.org | readthedocs/proxito/tests/storage.py | {
"start": 134,
"end": 699
} | class ____(BuildMediaFileSystemStorage):
"""
Storage to use in El Proxito tests to have more control.
Allow to specify when to return ``True`` or ``False`` depending if the file
does exist or not in the storage backend.
Mocking ``get_storage_class`` is not always an option, since there are other
... | BuildMediaStorageTest |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 46941,
"end": 47396
} | class ____(Stmt):
"""
An `exports` declaration.
Attributes
----------
annotation : Name | Attribute | Tuple
List of exports
"""
__slots__ = ("annotation",)
_only_empty_fields = ("value",)
def validate(self):
items = as_tuple(self.annotation)
for item in ite... | ExportsDecl |
python | getsentry__sentry | src/sentry/models/repository.py | {
"start": 931,
"end": 5866
} | class ____(Model):
__relocation_scope__ = RelocationScope.Global
organization_id = BoundedBigIntegerField(db_index=True)
name = models.CharField(max_length=200)
url = models.URLField(null=True)
provider = models.CharField(max_length=64, null=True)
# The external_id is the id of the repo in the ... | Repository |
python | scrapy__scrapy | tests/test_utils_request.py | {
"start": 8282,
"end": 11507
} | class ____:
def test_include_headers(self):
class RequestFingerprinter:
def fingerprint(self, request):
return fingerprint(request, include_headers=["X-ID"])
settings = {
"REQUEST_FINGERPRINTER_CLASS": RequestFingerprinter,
}
crawler = get_cra... | TestCustomRequestFingerprinter |
python | cython__cython | Cython/Compiler/Scanning.py | {
"start": 5041,
"end": 7675
} | class ____(SourceDescriptor):
"""
Represents a code source. A code source is a more generic abstraction
for a "filename" (as sometimes the code doesn't come from a file).
Instances of code sources are passed to Scanner.__init__ as the
optional name argument and will be passed back when asking for
... | FileSourceDescriptor |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 46383,
"end": 50981
} | class ____(Protocol[D]):
"""
A protocol for sparse vector functions. To implement a new sparse vector function,
you need to implement the following methods at minimum:
- __call__
For future compatibility, it is strongly recommended to also implement:
- __init__
- name
- build_from_confi... | SparseEmbeddingFunction |
python | redis__redis-py | redis/commands/search/field.py | {
"start": 3818,
"end": 4473
} | class ____(Field):
"""
TagField is a tag-indexing field with simpler compression and tokenization.
See http://redisearch.io/Tags/
"""
SEPARATOR = "SEPARATOR"
CASESENSITIVE = "CASESENSITIVE"
def __init__(
self,
name: str,
separator: str = ",",
case_sensitive:... | TagField |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/types.py | {
"start": 3214,
"end": 3448
} | class ____(TypedDict, total=False):
scheduler: Required[LRSchedulerTypeUnion]
name: Optional[str]
interval: str
frequency: int
reduce_on_plateau: bool
monitor: Optional[str]
strict: bool
| LRSchedulerConfigType |
python | astropy__astropy | astropy/nddata/nduncertainty.py | {
"start": 3015,
"end": 19003
} | class ____(metaclass=ABCMeta):
"""This is the metaclass for uncertainty classes used with `NDData`.
Parameters
----------
array : any type, optional
The array or value (the parameter name is due to historical reasons) of
the uncertainty. `numpy.ndarray`, `~astropy.units.Quantity` or
... | NDUncertainty |
python | modin-project__modin | modin/tests/pandas/extensions/test_base_extensions.py | {
"start": 5672,
"end": 11390
} | class ____:
def test_override_loc_for_one_backend(self, Backend1, data_class):
modin_object = data_class([1, 2, 3])
@register_base_accessor(name="loc", backend=Backend1)
@property
def my_loc(self):
return self.index[0]
assert isinstance(modin_object.set_backend(... | TestProperty |
python | joke2k__faker | faker/providers/internet/id_ID/__init__.py | {
"start": 46,
"end": 562
} | class ____(InternetProvider):
tlds = (
# From https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
"com",
"org",
"net",
"int",
"edu",
"gov",
"mil",
# From https://id.wikipedia.org/wiki/.id
"id",
"ac.id",
"biz... | Provider |
python | django__django | tests/admin_views/models.py | {
"start": 23535,
"end": 23845
} | class ____(models.Model):
"""
Issue #20522
Model where the validation of child foreign-key relationships depends
on validation of the parent
"""
some_required_info = models.PositiveIntegerField()
family_name = models.CharField(max_length=255, blank=False)
| ParentWithDependentChildren |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_container.py | {
"start": 4402,
"end": 5915
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpc.Dict()
def test_valid(self) -> None:
prop = bcpc.Dict(String, bcpc.List(Int))
assert prop.is_valid({})
assert prop.is_valid({"foo": [1,2,3]})
def test_invalid(self) -> None:
pr... | Test_Dict |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 422453,
"end": 423293
} | class ____(ExprNode):
# Initialize CyFunction.func_classobj
is_temp = True
type = py_object_type
subexprs = []
is_active = False
def analyse_expressions(self, env):
return self
def generate_result_code(self, code):
assert self.is_active
code.putln(
'%s =... | ClassCellInjectorNode |
python | conda__conda | conda/env/env.py | {
"start": 14324,
"end": 15361
} | class ____(EnvironmentYaml):
"""A class representing an ``environment.yaml`` file"""
@deprecated("25.9", "26.3")
def get_filename(filename):
"""Expand filename if local path or return the ``url``"""
url_scheme = filename.split("://", 1)[0]
if url_scheme in CONDA_SESSION_SCHEMES:
return filenam... | Environment |
python | pyca__cryptography | src/cryptography/utils.py | {
"start": 2189,
"end": 4128
} | class ____(types.ModuleType):
def __init__(self, module: types.ModuleType):
super().__init__(module.__name__)
self.__dict__["_module"] = module
def __getattr__(self, attr: str) -> object:
obj = getattr(self._module, attr)
if isinstance(obj, _DeprecatedValue):
warning... | _ModuleWithDeprecations |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 29818,
"end": 37207
} | class ____(CLIPPreTrainedModel):
config: CLIPConfig
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer", "CLIPVisionEmbeddings"]
def __init__(self, config: CLIPConfig):
super().__init__(config)
if not isinstance(config.text_config, CLIPTextConfig):
raise TypeError(
... | CLIPModel |
python | eth-brownie__brownie | brownie/test/strategies.py | {
"start": 1559,
"end": 7990
} | class ____(DeferredStrategy):
def __init__(self, fn: Callable, repr_target: str) -> None:
super().__init__(fn)
self._repr_target = repr_target
def __repr__(self):
return f"sampled_from({self._repr_target})"
def _exclude_filter(fn: Callable) -> Callable:
def wrapper(*args: Tuple, e... | _DeferredStrategyRepr |
python | aio-libs__aiohttp | aiohttp/multipart.py | {
"start": 5683,
"end": 6888
} | class ____:
"""Wrapper around the MultipartReader.
It takes care about
underlying connection and close it when it needs in.
"""
def __init__(
self,
resp: "ClientResponse",
stream: "MultipartReader",
) -> None:
self.resp = resp
self.stream = stream
d... | MultipartResponseWrapper |
python | django__django | tests/generic_views/views.py | {
"start": 5759,
"end": 5832
} | class ____(BookConfig, generic.TodayArchiveView):
pass
| BookTodayArchive |
python | facebook__pyre-check | client/commands/expression_level_coverage.py | {
"start": 1061,
"end": 1175
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
start: Pair
stop: Pair
@dataclass(frozen=True)
| Location |
python | astropy__astropy | astropy/io/fits/hdu/hdulist.py | {
"start": 8663,
"end": 60916
} | class ____(list, _Verify):
"""
HDU list class. This is the top-level FITS object. When a FITS
file is opened, a `HDUList` object is returned.
"""
def __init__(self, hdus=[], file=None):
"""
Construct a `HDUList` object.
Parameters
----------
hdus : BaseHDU... | HDUList |
python | neetcode-gh__leetcode | python/0724-find-pivot-index.py | {
"start": 0,
"end": 315
} | class ____:
def pivotIndex(self, nums: List[int]) -> int:
total = sum(nums) # O(n)
leftSum = 0
for i in range(len(nums)):
rightSum = total - nums[i] - leftSum
if leftSum == rightSum:
return i
leftSum += nums[i]
return -1
| Solution |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 60798,
"end": 61173
} | class ____(gdb.Command):
'Select and print the python stack frame that called this one (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-up",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self,... | PyUp |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 178129,
"end": 178949
} | class ____(TypedDict, total=False):
"""
:class:`altair.MultiPoint` ``TypedDict`` wrapper.
Parameters
----------
coordinates
type
Specifies the type of GeoJSON object.
bbox
Bounding box of the coordinate range of the object's Geometries, Features, or
Feature Collecti... | MultiPointKwds |
python | ray-project__ray | python/ray/data/datasource/file_meta_provider.py | {
"start": 5416,
"end": 18659
} | class ____(DefaultFileMetadataProvider):
"""Fast Metadata provider for
:class:`~ray.data.datasource.file_based_datasource.FileBasedDatasource`
implementations.
Offers improved performance vs.
:class:`DefaultFileMetadataProvider`
by skipping directory path expansion and file size collection.
... | FastFileMetadataProvider |
python | qdrant__qdrant-client | qdrant_client/http/api/indexes_api.py | {
"start": 3400,
"end": 4424
} | class ____(_IndexesApi):
async def create_field_index(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
create_field_index: m.CreateFieldIndex = None,
) -> m.InlineResponse2005:
"""
Create index for field in collection
... | AsyncIndexesApi |
python | django__django | tests/template_tests/filter_tests/test_yesno.py | {
"start": 117,
"end": 355
} | class ____(SimpleTestCase):
@setup({"t": '{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'})
def test_true(self):
output = self.engine.render_to_string("t", {"var": True})
self.assertEqual(output, "yup yes")
| YesNoTests |
python | conda__conda | conda/common/_logic.py | {
"start": 5143,
"end": 6059
} | class ____(_SatSolver):
def setup(self, m, limit=0, **kwargs):
from pycosat import itersolve
# NOTE: The iterative solving isn't actually used here, we just call
# itersolve to separate setup from the actual run.
return itersolve(self._clauses.as_list(), vars=m, prop_limit=lim... | _PycoSatSolver |
python | pytest-dev__pytest | src/_pytest/main.py | {
"start": 16101,
"end": 17846
} | class ____(nodes.Directory):
"""Collector of files in a file system directory.
.. versionadded:: 8.0
.. note::
Python directories with an `__init__.py` file are instead collected by
:class:`~pytest.Package` by default. Both are :class:`~pytest.Directory`
collectors.
"""
@... | Dir |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py | {
"start": 1090,
"end": 1223
} | class ____(Generic[T]):
added_keys: Set[T]
changed_keys: Set[T]
removed_keys: Set[T]
@whitelist_for_serdes
@record
| DictDiff |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 1475,
"end": 2248
} | class ____(fixtures.TestBase):
@testing.requires.predictable_gc
def test_cleanout_elements(self):
class Foo:
pass
f1, f2, f3 = Foo(), Foo(), Foo()
w = WeakSequence([f1, f2, f3])
eq_(len(w), 3)
eq_(len(w._storage), 3)
del f2
gc_collect()
... | WeakSequenceTest |
python | ansible__ansible | test/lib/ansible_test/_internal/processes.py | {
"start": 405,
"end": 2231
} | class ____:
"""A process in the process tree."""
pid: int
command: str
parent: Process | None = None
children: tuple[Process, ...] = dataclasses.field(default_factory=tuple)
@property
def args(self) -> list[str]:
"""The list of arguments that make up `command`."""
return sh... | Process |
python | doocs__leetcode | solution/1600-1699/1636.Sort Array by Increasing Frequency/Solution.py | {
"start": 0,
"end": 159
} | class ____:
def frequencySort(self, nums: List[int]) -> List[int]:
cnt = Counter(nums)
return sorted(nums, key=lambda x: (cnt[x], -x))
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image53.py | {
"start": 315,
"end": 862
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image53.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 2095,
"end": 2198
} | class ____(BaseModelOutput):
attention_mask: Optional[torch.Tensor] = None
| ParakeetEncoderModelOutput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 849136,
"end": 849526
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("ProjectV2Item", graphql_n... | ProjectV2ItemEdge |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/trainer_controller.py | {
"start": 1028,
"end": 11391
} | class ____:
def __init__(
self,
trainer_factory: TrainerFactory,
output_path: str,
run_id: str,
param_manager: EnvironmentParameterManager,
train: bool,
training_seed: int,
):
"""
:param output_path: Path to save the model.
:param s... | TrainerController |
python | falconry__falcon | falcon/errors.py | {
"start": 17894,
"end": 19998
} | class ____(HTTPNotFound):
"""404 Not Found.
The request did not match any routes configured for the application.
This subclass of :class:`~.HTTPNotFound` is raised by the framework to
provide a default 404 response when no route matches the request. This
behavior can be customized by registering a... | HTTPRouteNotFound |
python | pytorch__pytorch | test/distributed/elastic/test_control_plane.py | {
"start": 1449,
"end": 10266
} | class ____(TestCase):
def test_worker_server(self) -> None:
with local_worker_server() as pool:
resp = pool.request("GET", "/")
self.assertEqual(resp.status, 200)
self.assertEqual(
resp.data,
b"<h1>torch.distributed.WorkerServer</h1>\n"
... | WorkerServerTest |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 195152,
"end": 195885
} | class ____(_MatrixMixin,
BaseTestCOO,
sparse_test_class(getset=False,
slicing=False, slicing_assign=False,
fancy_indexing=False, fancy_assign=False)):
spcreator = coo_matrix
TestCOO.init_class()
Tes... | TestCOOMatrix |
python | redis__redis-py | tests/test_asyncio/conftest.py | {
"start": 8362,
"end": 9302
} | class ____:
def __init__(self, async_generator):
self.gen = async_generator
async def __aenter__(self):
try:
return await self.gen.__anext__()
except StopAsyncIteration as err:
raise RuntimeError("Pickles") from err
async def __aexit__(self, exc_type, exc_in... | AsyncContextManager |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 47858,
"end": 53311
} | class ____(AiryBase):
r"""
The Airy function $\operatorname{Bi}$ of the second kind.
Explanation
===========
The Airy function $\operatorname{Bi}(z)$ is defined to be the function
satisfying Airy's differential equation
.. math::
\frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = ... | airybi |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 5505,
"end": 6285
} | class ____(BuiltinFunction):
"""The base class for builtin predicates of the form f(obj, ...) -> bool.
Subclasses should implement run() for a specific signature.
(See UnaryPredicate and BinaryPredicate for examples.)
"""
def run(self, node, args, result):
raise NotImplementedError(self.__class__.__name... | ObjectPredicate |
python | eventlet__eventlet | eventlet/queue.py | {
"start": 18082,
"end": 18394
} | class ____(Queue):
'''A subclass of :class:`Queue` that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _put(self, item):
self.queue.append(item)
self._put_bookkeeping()
def _get(self):
return self.queue.pop()
| LifoQueue |
python | astropy__astropy | astropy/utils/iers/tests/test_leap_second.py | {
"start": 8332,
"end": 9027
} | class ____:
def setup_class(cls):
# Need auto_download so that IERS_B won't be loaded and cause tests to
# fail.
iers.conf.auto_download = True
def teardown_class(cls):
# This setting is to be consistent with astropy/conftest.py
iers.conf.auto_download = False
# In ... | TestRemoteURLs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.