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 | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_text.py | {
"start": 29400,
"end": 30312
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None ... | Data2VecTextClassificationHead |
python | django__django | tests/template_tests/syntax_tests/test_extends.py | {
"start": 16844,
"end": 17141
} | class ____(SimpleTestCase):
def test_extends_node_repr(self):
extends_node = ExtendsNode(
nodelist=NodeList([]),
parent_name=Node(),
template_dirs=[],
)
self.assertEqual(repr(extends_node), "<ExtendsNode: extends None>")
| ExtendsNodeTests |
python | pandas-dev__pandas | pandas/tests/tools/test_to_datetime.py | {
"start": 126461,
"end": 142256
} | class ____:
@pytest.mark.parametrize(
"listlike,do_caching",
[
([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], False),
([1, 1, 1, 1, 4, 5, 6, 7, 8, 9], True),
],
)
def test_should_cache(self, listlike, do_caching):
assert (
tools.should_cache(listlike, ch... | TestShouldCache |
python | FactoryBoy__factory_boy | tests/djapp/models.py | {
"start": 2654,
"end": 2781
} | class ____(models.Model):
custom_objects = CustomManager()
class Meta:
abstract = True
| AbstractWithCustomManager |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/signal/dct_ops_test.py | {
"start": 5307,
"end": 9316
} | class ____(parameterized.TestCase, test.TestCase):
def _compare(self, signals, n, norm, dct_type, atol, rtol):
"""Compares (I)DCT to SciPy (if available) and a NumPy implementation."""
np_dct = NP_DCT[dct_type](signals, n=n, norm=norm)
tf_dct = dct_ops.dct(signals, n=n, type=dct_type, norm=norm)
self... | DCTOpsTest |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 23622,
"end": 24358
} | class ____(nn.Module):
def __init__(self, config: EfficientLoFTRConfig):
super().__init__()
self.layers = nn.ModuleList(
[
EfficientLoFTRLocalFeatureTransformerLayer(config, layer_idx=i)
for i in range(config.num_attention_layers)
]
)
... | EfficientLoFTRLocalFeatureTransformer |
python | apache__airflow | providers/apache/spark/src/airflow/providers/apache/spark/hooks/spark_jdbc.py | {
"start": 991,
"end": 11867
} | class ____(SparkSubmitHook):
"""
Extends the SparkSubmitHook for performing data transfers to/from JDBC-based databases with Apache Spark.
:param spark_app_name: Name of the job (default airflow-spark-jdbc)
:param spark_conn_id: The :ref:`spark connection id <howto/connection:spark-submit>`
as ... | SparkJDBCHook |
python | scrapy__scrapy | tests/test_signals.py | {
"start": 983,
"end": 1780
} | class ____:
@classmethod
def setup_class(cls):
cls.mockserver = MockServer()
cls.mockserver.__enter__()
@classmethod
def teardown_class(cls):
cls.mockserver.__exit__(None, None, None)
def setup_method(self):
self.items = []
async def _on_item_scraped(self, item... | TestMockServer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 5089,
"end": 5237
} | class ____(sqltypes.JSON.JSONIndexType):
def get_dbapi_type(self, dbapi):
raise NotImplementedError("should not be here")
| _PGJSONIndexType |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 719944,
"end": 727479
} | class ____(
ColorDef, MarkPropDefGradientstringnull
):
"""
FieldOrDatumDefWithConditionDatumDefGradientstringnull schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be... | FieldOrDatumDefWithConditionDatumDefGradientstringnull |
python | readthedocs__readthedocs.org | readthedocs/search/migrations/0004_make_total_results_not_null.py | {
"start": 149,
"end": 528
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("search", "0003_migrate_total_results_null_values"),
]
operations = [
migrations.AlterField(
model_name="searchquery",
name="total_results",
field=models.IntegerField(defau... | Migration |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 12165,
"end": 14050
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.quant_mode = config.quant_mode
self.act_bit = 8
self.weight_bit = 8
self.bias_bit = 32
self.ln_input_bit = 22
self.ln_output_bit = 32
self.dense = QuantLinear(
conf... | IBertSelfOutput |
python | neetcode-gh__leetcode | python/0211-design-add-and-search-words-data-structure.py | {
"start": 0,
"end": 111
} | class ____:
def __init__(self):
self.children = {} # a : TrieNode
self.word = False
| TrieNode |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 45395,
"end": 49054
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
drop_path = config.fusion_droppath
# pre layer norm
self.layer_norm_vision = nn.LayerNorm(config.d_model, config.layer_norm_eps)
self.layer_norm_text = nn.LayerNorm(config.d_model, config.layer_norm_eps)
... | GroundingDinoFusionLayer |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 45610,
"end": 53217
} | class ____:
async def test_suspended_flow_runs_do_not_block_execution(
self, prefect_client, deployment, session
):
flow_run_id = None
@flow()
async def suspending_flow():
nonlocal flow_run_id
context = get_run_context()
assert context.flow_ru... | TestSuspendFlowRun |
python | astropy__astropy | astropy/stats/sigma_clipping.py | {
"start": 901,
"end": 33766
} | class ____:
"""
Class to perform sigma clipping.
The data will be iterated over, each time rejecting values that are
less or more than a specified number of standard deviations from a
center value.
Clipped (rejected) pixels are those where::
data < center - (sigma_lower * std)
... | SigmaClip |
python | PyCQA__pylint | pylint/testutils/_primer/primer.py | {
"start": 669,
"end": 4685
} | class ____:
"""Main class to handle priming of packages."""
def __init__(self, primer_directory: Path, json_path: Path) -> None:
# Preparing arguments
self.primer_directory = primer_directory
self._argument_parser = argparse.ArgumentParser(prog="Pylint Primer")
self._subparsers ... | Primer |
python | walkccc__LeetCode | solutions/2032. Two Out of Three/2032.py | {
"start": 0,
"end": 291
} | class ____:
def twoOutOfThree(
self,
nums1: list[int],
nums2: list[int],
nums3: list[int],
) -> list[int]:
count = collections.Counter()
for nums in nums1, nums2, nums3:
count.update(set(nums))
return [i for i, c in count.items() if c >= 2]
| Solution |
python | pandas-dev__pandas | pandas/core/indexers/objects.py | {
"start": 530,
"end": 3509
} | class ____:
"""
Base class for window bounds calculations.
Parameters
----------
index_array : np.ndarray, default None
Array-like structure representing the indices for the data points.
If None, the default indices are assumed. This can be useful for
handling non-uniform in... | BaseIndexer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hide02.py | {
"start": 315,
"end": 887
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hide02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filena... | TestCompareXLSXFiles |
python | celery__celery | t/unit/tasks/test_stamping.py | {
"start": 779,
"end": 1579
} | class ____(StampingVisitor):
def clean_stamps(self, actual_sig: Signature) -> None:
if "stamped_headers" in actual_sig.options and actual_sig.options["stamped_headers"]:
for stamp in actual_sig.options["stamped_headers"]:
if stamp in actual_sig.options:
actual... | CleanupVisitor |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 453,
"end": 530
} | class ____(ABC):
@abstractmethod
def method(self):
foo()
| Base_2 |
python | wandb__wandb | wandb/vendor/pygments/lexers/parsers.py | {
"start": 1277,
"end": 5102
} | class ____(RegexLexer):
"""
A pure `Ragel <http://www.complang.org/ragel/>`_ lexer. Use this for
fragments of Ragel. For ``.rl`` files, use RagelEmbeddedLexer instead
(or one of the language-specific subclasses).
.. versionadded:: 1.1
"""
name = 'Ragel'
aliases = ['ragel']
filena... | RagelLexer |
python | jina-ai__jina | jina/resources/base-gateway/gateway.py | {
"start": 62,
"end": 110
} | class ____(BaseGateway):
pass
| PlaceHolderGateway |
python | scipy__scipy | scipy/sparse/linalg/_isolve/tests/test_lsmr.py | {
"start": 4159,
"end": 6362
} | class ____:
def setup_method(self):
self.n = 10
self.A = lowerBidiagonalMatrix(20, self.n)
self.xtrue = transpose(arange(self.n, 0, -1))
self.Afun = aslinearoperator(self.A)
self.b = self.Afun.matvec(self.xtrue)
self.x0 = ones(self.n)
self.x00 = self.x0.copy()... | TestLSMRReturns |
python | huggingface__transformers | src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py | {
"start": 3633,
"end": 3810
} | class ____(BambaMixer):
def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
super().__init__(BambaConfig(config), layer_idx)
| GraniteMoeHybridMambaLayer |
python | Textualize__textual | docs/examples/guide/widgets/hello02.py | {
"start": 223,
"end": 403
} | class ____(App):
CSS_PATH = "hello02.tcss"
def compose(self) -> ComposeResult:
yield Hello()
if __name__ == "__main__":
app = CustomApp()
app.run()
| CustomApp |
python | getsentry__sentry | tests/apidocs/endpoints/teams/test_by_slug.py | {
"start": 136,
"end": 932
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
team = self.create_team(organization=self.organization)
self.url = reverse(
"sentry-api-0-team-details",
kwargs={
"organization_id_or_slug": self.organization.slug,
"team_id_or_slug": team.... | TeamsBySlugDocs |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/testdata/gen_tf_readvariableop_model.py | {
"start": 1255,
"end": 2272
} | class ____(module.Module):
"""Simple model with two variables."""
def __init__(self):
self.var1 = variables.Variable(
np.array([[[13.]]], dtype=np.float32), name="var1")
self.var2 = variables.Variable(
np.array([[[37.]]], dtype=np.float32), name="var2")
@def_function.function
def __cal... | MyModel |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 437,
"end": 809
} | class ____:
collection: Collection
knn: Segment
metadata: Segment
record: Segment
@property
def version(self) -> RequestVersionContext:
return RequestVersionContext(
collection_version=self.collection.version,
log_position=self.collection.log_position,
)
... | Scan |
python | getsentry__sentry | src/sentry/integrations/api/serializers/rest_framework/doc_integration.py | {
"start": 1128,
"end": 4076
} | class ____(Serializer):
name = serializers.CharField(max_length=255)
author = serializers.CharField(max_length=255)
description = serializers.CharField()
url = URLField()
popularity = serializers.IntegerField(min_value=0, max_value=32767, allow_null=True)
is_draft = serializers.BooleanField(defa... | DocIntegrationSerializer |
python | great-expectations__great_expectations | docs/sphinx_api_docs_source/public_api_report.py | {
"start": 28813,
"end": 35972
} | class ____:
"""Generate a report from entity definitions (class, method and function)."""
def __init__(self, definitions: Set[Definition], repo_root: pathlib.Path) -> None:
"""Create a PublicAPIReport object.
Args:
definitions: Entity definitions to include in the report. Generally... | PublicAPIReport |
python | weaviate__weaviate-python-client | weaviate/collections/queries/fetch_objects_by_ids/generate/sync.py | {
"start": 332,
"end": 495
} | class ____(
Generic[Properties, References],
_FetchObjectsByIDsGenerateExecutor[ConnectionSync, Properties, References],
):
pass
| _FetchObjectsByIDsGenerate |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 99530,
"end": 100987
} | class ____(system_info):
section = 'numerix'
def calc_info(self):
which = None, None
if os.getenv("NUMERIX"):
which = os.getenv("NUMERIX"), "environment var"
# If all the above fail, default to numpy.
if which[0] is None:
which = "numpy", "defaulted"
... | numerix_info |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 122715,
"end": 125128
} | class ____:
def test_reproducibility(self):
rng = np.random.RandomState(514)
x = unitary_group.rvs(3, random_state=rng)
x2 = unitary_group.rvs(3, random_state=514)
expected = np.array(
[[0.308771+0.360312j, 0.044021+0.622082j, 0.160327+0.600173j],
[0.732757+... | TestUnitaryGroup |
python | pola-rs__polars | py-polars/src/polars/_dependencies.py | {
"start": 675,
"end": 11448
} | class ____(ModuleType):
"""
Module that can act both as a lazy-loader and as a proxy.
Notes
-----
We do NOT register this module with `sys.modules` so as not to cause
confusion in the global environment. This way we have a valid proxy
module for our own use, but it lives *exclusively* withi... | _LazyModule |
python | PrefectHQ__prefect | tests/_experimental/plugins/test_plugins.py | {
"start": 20407,
"end": 20922
} | class ____:
"""Tests for SetupSummary data structure."""
def test_setup_summary_creation(self):
"""Test creating a SetupSummary."""
summary = SetupSummary(
plugin="test-plugin",
env_preview={"KEY": "value"},
note="Test note",
error=None,
)... | TestSetupSummary |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 16239,
"end": 16388
} | class ____(
BaseGroupingComponent[HostnameGroupingComponent | SaltGroupingComponent]
):
id: str = "expect_staple"
| ExpectStapleGroupingComponent |
python | ansible__ansible | lib/ansible/plugins/inventory/constructed.py | {
"start": 4143,
"end": 7353
} | class ____(BaseInventoryPlugin, Constructable):
""" constructs groups and vars using Jinja2 template expressions """
NAME = 'constructed'
# implicit trust behavior is already added by the YAML parser invoked by the loader
def verify_file(self, path):
valid = False
if super(InventoryM... | InventoryModule |
python | dask__distributed | distributed/diagnostics/tests/test_worker_plugin.py | {
"start": 15817,
"end": 16869
} | class ____(WorkerPlugin):
def teardown(self, worker):
raise RuntimeError("test error")
@gen_cluster(client=True, nthreads=[("", 1)])
async def test_unregister_worker_plugin_with_broken_teardown_raises(c, s, a):
await c.register_plugin(BrokenTeardownPlugin(), name="TestPlugin1")
with pytest.raises(... | BrokenTeardownPlugin |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 328557,
"end": 329722
} | class ____(torch.fx.Interpreter):
def run_node(self, n: torch.fx.Node) -> Result:
"""
Run an FX node, propagating unbacked Symbol bindings to the new fake tensor
"""
from torch._guards import detect_fake_mode
result = super().run_node(n)
fake_mode = detect_fake_mode(... | PropagateUnbackedSymInts |
python | scrapy__scrapy | tests/spiders.py | {
"start": 15309,
"end": 16107
} | class ____(MetaSpider):
full_response_length = 2**18
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super().from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.bytes_received, signals.bytes_received)
return spider
async def start(self):... | BytesReceivedCallbackSpider |
python | sympy__sympy | sympy/physics/biomechanics/musculotendon.py | {
"start": 42867,
"end": 58289
} | class ____(MusculotendonBase):
r"""Musculotendon model using the curves of De Groote et al., 2016 [1]_.
Examples
========
This class models the musculotendon actuator parametrized by the
characteristic curves described in De Groote et al., 2016 [1]_. Like all
musculotendon models in SymPy's bi... | MusculotendonDeGroote2016 |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 35962,
"end": 36633
} | class ____(ServeActorDetails, frozen=True):
"""Detailed info about a single deployment replica."""
replica_id: str = Field(description="Unique ID for the replica.")
state: ReplicaState = Field(description="Current state of the replica.")
pid: Optional[int] = Field(description="PID of the replica actor ... | ReplicaDetails |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/entities/snippets.py | {
"start": 6218,
"end": 6760
} | class ____(ndb.Model):
name = ndb.StringProperty()
def _pre_put_hook(self):
_notify("Gee wiz I have a new friend!")
@classmethod
def _post_delete_hook(cls, key, future):
_notify("I have found occasion to rethink our friendship.")
def demonstrate_model_put_and_delete_hooks():
f = ... | Friend |
python | wandb__wandb | wandb/sdk/launch/runner/vertex_runner.py | {
"start": 674,
"end": 2214
} | class ____(AbstractRun):
def __init__(self, job: Any) -> None:
self._job = job
@property
def id(self) -> str:
# numeric ID of the custom training job
return self._job.name # type: ignore
async def get_logs(self) -> Optional[str]:
# TODO: implement
return None
... | VertexSubmittedRun |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 21600,
"end": 24653
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.pos_conv_embed = HubertPositionalConvEmbedding(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout... | HubertEncoderStableLayerNorm |
python | huggingface__transformers | src/transformers/models/falcon/modeling_falcon.py | {
"start": 31521,
"end": 32608
} | class ____(PreTrainedModel):
config: FalconConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_no_split_modules = ["FalconDecoderLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_can_compile_fullgraph = True
@torch.no_grad()
def _init_weights(se... | FalconPreTrainedModel |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/builtin_way.py | {
"start": 153,
"end": 520
} | class ____(Creator, Describe, ABC):
"""A creator that does operations itself without delegation, if we can create it we can also describe it."""
def __init__(self, options, interpreter) -> None:
Creator.__init__(self, options, interpreter)
Describe.__init__(self, self.dest, interpreter)
__all... | VirtualenvBuiltin |
python | ray-project__ray | python/ray/_common/tests/test_signature.py | {
"start": 3799,
"end": 6485
} | class ____:
"""Tests for the extract_signature utility function."""
def test_function_without_ignore_first(self):
"""Test extracting signature from function without ignoring first parameter."""
def test_func(a, b=10, c=None):
return a + b
params = extract_signature(test_fu... | TestExtractSignature |
python | huggingface__transformers | tests/models/dpr/test_tokenization_dpr.py | {
"start": 1321,
"end": 1637
} | class ____(test_tokenization_bert.BertTokenizationTest):
tokenizer_class = DPRQuestionEncoderTokenizer
rust_tokenizer_class = DPRQuestionEncoderTokenizerFast
test_rust_tokenizer = True
from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base"
@require_tokenizers
| DPRQuestionEncoderTokenizationTest |
python | pypa__pip | tests/unit/test_wheel.py | {
"start": 5757,
"end": 6055
} | class ____:
def test_unpack_wheel_no_flatten(self, tmpdir: Path) -> None:
filepath = os.path.join(DATA_DIR, "packages", "meta-1.0-py2.py3-none-any.whl")
unpack_file(filepath, os.fspath(tmpdir))
assert os.path.isdir(os.path.join(tmpdir, "meta-1.0.dist-info"))
| TestWheelFile |
python | doocs__leetcode | solution/0600-0699/0648.Replace Words/Solution.py | {
"start": 683,
"end": 1041
} | class ____:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
trie = Trie()
for i, w in enumerate(dictionary):
trie.insert(w, i)
ans = []
for w in sentence.split():
idx = trie.search(w)
ans.append(dictionary[idx] if idx != -1 els... | Solution |
python | apache__airflow | providers/microsoft/psrp/src/airflow/providers/microsoft/psrp/operators/psrp.py | {
"start": 1381,
"end": 7358
} | class ____(BaseOperator):
"""
PowerShell Remoting Protocol operator.
Use one of the 'command', 'cmdlet', or 'powershell' arguments.
The 'securestring' template filter can be used to tag a value for
serialization into a `System.Security.SecureString` (applicable only
for DAGs which have `render... | PsrpOperator |
python | graphql-python__graphene | graphene/tests/issues/test_425.py | {
"start": 276,
"end": 341
} | class ____(ObjectTypeOptions):
other_attr = None
| SpecialOptions |
python | google__jax | docs/autodidax2_part1.py | {
"start": 17331,
"end": 19695
} | class ____(Interpreter):
def __init__(self):
self.equations = [] # A mutable list of all the ops we've seen so far
self.name_counter = 0 # Counter for generating unique names
def fresh_var(self):
self.name_counter += 1
return "v_" + str(self.name_counter)
def interpret_op(self, op, args... | StagingInterpreter |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-multiple-arrays.py | {
"start": 1059,
"end": 1363
} | class ____(object):
def intersection(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
result = set(nums[0])
for i in xrange(1, len(nums)):
result = set(x for x in nums[i] if x in result)
return sorted(result)
| Solution3 |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 8591,
"end": 8728
} | class ____(AutomationAction):
"""Resumes a Work Queue"""
type: Literal["resume-automation"] = "resume-automation"
| ResumeAutomation |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 73785,
"end": 75860
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dropout = config.hidden_dropout_prob
self.layers = nn.ModuleList([ReformerLayer(config, i) for i in range(config.num_hidden_layers)])
# Reformer is using Rev Nets, thus last layer outputs are concatenated and... | ReformerEncoder |
python | pandas-dev__pandas | pandas/io/pytables.py | {
"start": 108929,
"end": 110416
} | class ____(GenericFixed):
pandas_kind = "series"
attributes = ["name"]
name: Hashable
@property
def shape(self) -> tuple[int] | None:
try:
return (len(self.group.values),)
except (TypeError, AttributeError):
return None
def read(
self,
w... | SeriesFixed |
python | django__django | tests/serializers/test_natural.py | {
"start": 289,
"end": 9431
} | class ____(TestCase):
pass
def natural_key_serializer_test(self, format):
# Create all the objects defined in the test data
with connection.constraint_checks_disabled():
objects = [
NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"),
FKDataNaturalKey.object... | NaturalKeySerializerTests |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/sharding/sharding_policies.py | {
"start": 2625,
"end": 14993
} | class ____(sharding_util.ShardingCallback):
"""Policy that splits tensors into shards with a max shard size.
Shards may exceed the max shard size if they contain 1. a single scalar/string
tensor that could not be sliced and exceeds the max shard size or 2. the
checkpoint object graph, whose size cannot be calc... | MaxShardSizePolicy |
python | davidhalter__jedi | test/test_api/test_classes.py | {
"start": 19108,
"end": 20142
} | class ____:
"""my class"""
@staticmethod
def hello():
func_var = 1
return func_var
'''
@pytest.mark.parametrize(
'code, pos, start, end', [
('def a_func():\n return "bar"\n', (1, 4), (1, 0), (2, 16)),
('var1 = 12', (1, 0), (1, 0), (1, 9)),
('var1 + 1', (1, 0)... | AClass |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/repository/event.py | {
"start": 460,
"end": 782
} | class ____(BaseEvent):
"""Event dispatched when GitHub repository processing completes."""
repository_name: str
branch_or_commit: str
total_documents: int = 0
@classmethod
def class_name(cls) -> str:
return "GitHubRepositoryProcessingCompletedEvent"
| GitHubRepositoryProcessingCompletedEvent |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_config.py | {
"start": 11515,
"end": 18011
} | class ____(TestConfigEndpoint):
@pytest.mark.parametrize(
("section", "option", "headers", "expected_status_code", "expected_response"),
[
(
SECTION_CORE,
OPTION_KEY_PARALLELISM,
HEADERS_JSON,
200,
GET_CONFIG... | TestGetConfigValue |
python | numba__numba | numba/cpython/hashing.py | {
"start": 14161,
"end": 27042
} | class ____(Union):
_fields_ = [
# ensure 24 bytes
('uc', c_ubyte * 24),
# two Py_hash_t for FNV
('fnv', FNV),
# two uint64 for SipHash24
('siphash', SIPHASH),
# a different (!) Py_hash_t for small string optimization
('djbx33a', DJBX33A),
('exp... | _Py_HashSecret_t |
python | PyCQA__pylint | doc/data/messages/s/signature-differs/good.py | {
"start": 84,
"end": 220
} | class ____(Animal):
def run(self, distance=0):
super(Animal, self).run(distance)
print("Fetched that stick, wuff !")
| Dog |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink22.py | {
"start": 315,
"end": 953
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink22.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | kamyu104__LeetCode-Solutions | Python/minimum-deletions-for-at-most-k-distinct-characters.py | {
"start": 75,
"end": 603
} | class ____(object):
def minDeletion(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
cnt = [0]*26
for x in s:
cnt[ord(x)-ord('a')] += 1
cnt2 = [0]*(max(cnt)+1)
for x in cnt:
cnt2[x] += 1
result = 0
... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 3651,
"end": 3810
} | class ____(StrEnum):
DEFAULT = "default"
CRITICAL = "critical"
WARNING = "warning"
ERROR = "error"
INFO = "info"
@dataclass
| PagerdutySeverity |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 626,
"end": 1371
} | class ____(TestCase):
"""Tests for ``take()``"""
def test_simple_take(self):
"""Test basic usage"""
t = mi.take(5, range(10))
self.assertEqual(t, [0, 1, 2, 3, 4])
def test_null_take(self):
"""Check the null case"""
t = mi.take(0, range(10))
self.assertEqual(... | TakeTests |
python | pypa__pip | src/pip/_vendor/rich/highlighter.py | {
"start": 4755,
"end": 9586
} | class ____(RegexHighlighter):
"""Highlights the ISO8601 date time strings.
Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html
"""
base_style = "iso8601."
highlights = [
#
# Dates
#
# Calendar month (e.g. 2008... | ISO8601Highlighter |
python | ipython__ipython | IPython/core/formatters.py | {
"start": 28483,
"end": 29038
} | class ____(BaseFormatter):
"""A LaTeX formatter.
To define the callables that compute the LaTeX representation of your
objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
or :meth:`for_type_by_name` methods to register functions that handle
this.
The return value of this ... | LatexFormatter |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/completion_widget.py | {
"start": 141,
"end": 8151
} | class ____(QtWidgets.QListWidget):
""" A widget for GUI tab completion.
"""
#--------------------------------------------------------------------------
# 'QObject' interface
#--------------------------------------------------------------------------
def __init__(self, console_widget, height=0)... | CompletionWidget |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 27611,
"end": 27782
} | class ____(Integer):
"""
Handles the short datatype. Signed 16-bit integer.
"""
format = "i2"
val_range = (-32768, 32767)
bit_size = "16-bit"
| Short |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 112806,
"end": 117847
} | class ____(_ColumnEntity):
"""Column/expression based entity."""
supports_single_entity = False
__slots__ = (
"expr",
"mapper",
"column",
"_label_name",
"entity_zero_or_selectable",
"entity_zero",
"_extra_entities",
)
def __init__(
s... | _ORMColumnEntity |
python | encode__httpx | httpx/_auth.py | {
"start": 5501,
"end": 11744
} | class ____(Auth):
_ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = {
"MD5": hashlib.md5,
"MD5-SESS": hashlib.md5,
"SHA": hashlib.sha1,
"SHA-SESS": hashlib.sha1,
"SHA-256": hashlib.sha256,
"SHA-256-SESS": hashlib.sha256,
"SHA-512": hash... | DigestAuth |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 9801,
"end": 10319
} | class ____(TestModelMixin, TestBase):
def testSetDateCreated(self):
date_created = timezone.now() - timedelta(days=20)
with reversion.create_revision():
reversion.set_date_created(date_created)
obj = TestModel.objects.create()
self.assertSingleRevision((obj,), date_c... | SetDateCreatedTest |
python | doocs__leetcode | solution/3200-3299/3217.Delete Nodes From Linked List Present in Array/Solution.py | {
"start": 151,
"end": 512
} | class ____:
def modifiedList(
self, nums: List[int], head: Optional[ListNode]
) -> Optional[ListNode]:
s = set(nums)
pre = dummy = ListNode(next=head)
while pre.next:
if pre.next.val in s:
pre.next = pre.next.next
else:
pre ... | Solution |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/variable_test.py | {
"start": 2134,
"end": 2196
} | class ____(object):
def __init__(self):
self.v = None
| Var |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/search.py | {
"start": 766,
"end": 6951
} | class ____:
"""
A search 'query', associated with a search field (like a SearchToolbar).
Every searchable `BufferControl` points to a `search_buffer_control`
(another `BufferControls`) which represents the search field. The
`SearchState` attached to that search field is used for storing the current... | SearchState |
python | catalyst-team__catalyst | catalyst/core/callback.py | {
"start": 4054,
"end": 4254
} | class ____(Callback):
"""Metric callback interface, abstraction over metric step."""
def __init__(self):
"""Init."""
super().__init__(order=CallbackOrder.Metric)
| IMetricCallback |
python | prabhupant__python-ds | data_structures/graphs/level_of_nodes.py | {
"start": 319,
"end": 1190
} | class ____:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def print_levels(self, s):
levels = [None] * self.vertices
levels[s] = 0
qu... | Graph |
python | readthedocs__readthedocs.org | readthedocs/projects/tests/test_domain_views.py | {
"start": 9096,
"end": 9319
} | class ____(TestDomainViews):
def setUp(self):
super().setUp()
self.org = get(
Organization, owners=[self.user], projects=[self.project, self.subproject]
)
| TestDomainViewsWithOrganizations |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_india_zip.py | {
"start": 729,
"end": 1724
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_india_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(... | ColumnValuesToBeValidIndiaZip |
python | agronholm__apscheduler | src/apscheduler/_events.py | {
"start": 4669,
"end": 4803
} | class ____(Event):
"""Base class for events originating from a scheduler."""
@attrs.define(kw_only=True, frozen=True)
| SchedulerEvent |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/common_transformers/anf_test.py | {
"start": 2988,
"end": 12300
} | class ____(AnfTestBase):
def test_basic(self):
def test_function():
a = 0
return a
node, _ = parser.parse_entity(test_function, future_features=())
node = anf.transform(node, self._simple_context())
result, _, _ = loader.load_ast(node)
self.assertEqual(test_function(), result.test_fu... | AnfTransformerTest |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_pair_map_metrics/column_pair_values_greater.py | {
"start": 393,
"end": 2074
} | class ____(ColumnPairMapMetricProvider):
condition_metric_name = "column_pair_values.a_greater_than_b"
condition_domain_keys = (
"batch_id",
"table",
"column_A",
"column_B",
"row_condition",
"condition_parser",
"ignore_row_if",
)
condition_value_ke... | ColumnPairValuesAGreaterThanB |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/image_ops/decode_bmp_op_test.py | {
"start": 952,
"end": 3291
} | class ____(test.TestCase):
def testex1(self):
img_bytes = [[[0, 0, 255], [0, 255, 0]], [[255, 0, 0], [255, 255, 255]]]
# Encoded BMP bytes from Wikipedia
# BMP header bytes: https://en.wikipedia.org/wiki/List_of_file_signatures
encoded_bytes = [
0x42, 0x4d,
0x46, 0, 0, 0,
0, 0... | DecodeBmpOpTest |
python | ansible__ansible | lib/ansible/module_utils/_internal/_datatag/__init__.py | {
"start": 16062,
"end": 16380
} | class ____:
"""Marker mixin for types that should raise an error when encountered."""
__slots__ = _NO_INSTANCE_STORAGE
def trip(self) -> t.NoReturn:
"""Derived types should implement a failure behavior."""
raise NotImplementedError()
@dataclasses.dataclass(**_tag_dataclass_kwargs)
| Tripwire |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_compile.py | {
"start": 1591,
"end": 1971
} | class ____(torch.nn.Module):
def __init__(self):
super().__init__()
self.encoder = torch.nn.Sequential(
torch.nn.Linear(28 * 28, 1024, device=device_type),
torch.nn.Linear(1024, 1024, device=device_type),
torch.nn.Linear(1024, 4096, device=device_type),
)... | Mod |
python | qdrant__qdrant-client | tools/async_client_generator/remote_generator.py | {
"start": 1134,
"end": 5330
} | class ____(BaseGenerator):
def __init__(
self,
keep_sync: Optional[list[str]] = None,
class_replace_map: Optional[dict] = None,
import_replace_map: Optional[dict] = None,
exclude_methods: Optional[list[str]] = None,
rename_methods: Optional[dict[str, str]] = None,
... | RemoteGenerator |
python | weaviate__weaviate-python-client | weaviate/cluster/models.py | {
"start": 241,
"end": 514
} | class ____(str, Enum):
"""Enum for replication operation states."""
REGISTERED = "REGISTERED"
HYDRATING = "HYDRATING"
FINALIZING = "FINALIZING"
DEHYDRATING = "DEHYDRATING"
READY = "READY"
CANCELLED = "CANCELLED"
@dataclass
| ReplicateOperationState |
python | huggingface__transformers | tests/utils/test_tokenization_utils.py | {
"start": 1237,
"end": 3229
} | class ____(unittest.TestCase):
def test_cached_files_are_used_when_internet_is_down(self):
# A mock response for an HTTP head request to emulate server down
response_mock = mock.Mock()
response_mock.status_code = 500
response_mock.headers = {}
response_mock.raise_for_status.s... | TokenizerUtilTester |
python | mlflow__mlflow | mlflow/genai/judges/tools/search_trace_regex.py | {
"start": 1029,
"end": 5969
} | class ____(JudgeTool):
"""
Tool for searching through entire traces using regex patterns.
Performs case-insensitive regex search across all trace fields including
spans, metadata, tags, requests, responses, and other fields. Returns
matched text with surrounding context to help understand where mat... | SearchTraceRegexTool |
python | tornadoweb__tornado | tornado/options.py | {
"start": 4266,
"end": 4362
} | class ____(Exception):
"""Exception raised by errors in the options module."""
pass
| Error |
python | pypa__pipenv | pipenv/vendor/pexpect/pxssh.py | {
"start": 1845,
"end": 24487
} | class ____ (spawn):
'''This class extends pexpect.spawn to specialize setting up SSH
connections. This adds methods for login, logout, and expecting the shell
prompt. It does various tricky things to handle many situations in the SSH
login process. For example, if the session is your first login, then p... | pxssh |
python | django__django | tests/template_tests/syntax_tests/test_numpy.py | {
"start": 229,
"end": 1174
} | class ____(SimpleTestCase):
@setup({"numpy-array-index01": "{{ var.1 }}"})
def test_numpy_array_index01(self):
"""
Numpy's array-index syntax allows a template to access a certain
item of a subscriptable object.
"""
output = self.engine.render_to_string(
"nump... | NumpyTests |
python | scipy__scipy | scipy/constants/_codata.py | {
"start": 198639,
"end": 202549
} | class ____(DeprecationWarning):
"""Accessing a constant no longer in current CODATA data set"""
pass
def _check_obsolete(key: str) -> None:
if key in _obsolete_constants and key not in _aliases:
warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
C... | ConstantWarning |
python | walkccc__LeetCode | solutions/1356. Sort Integers by The Number of 1 Bits/1356.py | {
"start": 0,
"end": 126
} | class ____:
def sortByBits(self, arr: list[int]) -> list[int]:
return sorted(arr, key=lambda x: (x.bit_count(), x))
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.