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 | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 70838,
"end": 72220
} | class ____:
"""
Helper for `.MaxNLocator`, `.MultipleLocator`, etc.
Take floating-point precision limitations into account when calculating
tick locations as integer multiples of a step.
"""
def __init__(self, step, offset):
"""
Parameters
----------
step : floa... | _Edge_integer |
python | walkccc__LeetCode | solutions/1154. Day of the Year/1154.py | {
"start": 0,
"end": 378
} | class ____:
def dayOfYear(self, date: str) -> int:
def isLeapYear(year: int) -> bool:
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
year = int(date[:4])
month = int(date[5:7])
day = int(date[8:])
days = [31, 29 if isLeapYear(
year) else 28, 31, 30, 31, 30, 31, 31, 30... | Solution |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 2560,
"end": 2703
} | class ____:
name: str
slug: Optional[str]
description: Optional[str]
p = AddProject(name='x', slug='y', description='z')
| AddProject |
python | pyca__cryptography | tests/hazmat/primitives/test_xofhash.py | {
"start": 1155,
"end": 2610
} | class ____:
def test_hash_reject_unicode(self, backend):
m = hashes.XOFHash(hashes.SHAKE128(sys.maxsize))
with pytest.raises(TypeError):
m.update("\u00fc") # type: ignore[arg-type]
def test_incorrect_hash_algorithm_type(self, backend):
with pytest.raises(TypeError):
... | TestXOFHash |
python | walkccc__LeetCode | solutions/1921. Eliminate Maximum Number of Monsters/1921.py | {
"start": 0,
"end": 255
} | class ____:
def eliminateMaximum(self, dist: list[int], speed: list[int]) -> int:
for i, arrivalTime in enumerate(
sorted([(d - 1) // s for d, s in zip(dist, speed)])):
if i > arrivalTime:
return i
return len(dist)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/number-of-laser-beams-in-a-bank.py | {
"start": 33,
"end": 371
} | class ____(object):
def numberOfBeams(self, bank):
"""
:type bank: List[str]
:rtype: int
"""
result = prev = 0
for x in bank:
cnt = x.count('1')
if not cnt:
continue
result += prev*cnt
prev = cnt
... | Solution |
python | geekcomputers__Python | Python Programs/Python Program to Reverse a linked list.py | {
"start": 107,
"end": 249
} | class ____:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
| Node |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 8170,
"end": 10787
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(30), nullable=False),
... | PickleTest |
python | doocs__leetcode | solution/2400-2499/2497.Maximum Star Sum of a Graph/Solution.py | {
"start": 0,
"end": 415
} | class ____:
def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:
g = defaultdict(list)
for a, b in edges:
if vals[b] > 0:
g[a].append(vals[b])
if vals[a] > 0:
g[b].append(vals[a])
for bs in g.values():
... | Solution |
python | mitsuhiko__rye | rye-devtools/src/rye_devtools/find_downloads.py | {
"start": 8855,
"end": 14000
} | class ____(Finder):
implementation = PythonImplementation.PYPY
RELEASE_URL = "https://raw.githubusercontent.com/pypy/pypy/main/pypy/tool/release/versions.json"
CHECKSUM_URL = (
"https://raw.githubusercontent.com/pypy/pypy.org/main/pages/checksums.rst"
)
CHECKSUM_RE = re.compile(
r"^... | PyPyFinder |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/resource.py | {
"start": 2097,
"end": 3475
} | class ____(ConfigurableResource):
"""Authenticates with PowerBI using a service principal."""
client_id: str = Field(..., description="The application client ID for the service principal.")
client_secret: str = Field(
..., description="A client secret created for the service principal."
)
t... | PowerBIServicePrincipal |
python | getsentry__sentry | tests/sentry/integrations/slack/threads/activity_notifications/test_external_issue_created_activity.py | {
"start": 1752,
"end": 3063
} | class ____(BaseTestCase):
def test_returns_fallback_when_provider_key_is_not_in_map(self) -> None:
self.activity.data = {}
create_issue_activity = _ExternalIssueCreatedActivity(self.activity)
ret = create_issue_activity.get_provider()
assert ret == create_issue_activity.DEFAULT_PROV... | TestGetProvider |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937_regressions.py | {
"start": 134,
"end": 8638
} | class ____:
def _create_generator(self):
return Generator(MT19937(121263137472525314065))
def test_vonmises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
mt19937 = self._create_generator()
for mu in np.linspace(-... | TestRegression |
python | huggingface__transformers | src/transformers/models/internvl/modeling_internvl.py | {
"start": 30245,
"end": 31831
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | InternVLCausalLMOutputWithPast |
python | python-markdown__markdown | tests/test_syntax/blocks/test_html_blocks.py | {
"start": 821,
"end": 42180
} | class ____(TestCase):
def test_raw_paragraph(self):
self.assertMarkdownRenders(
'<p>A raw paragraph.</p>',
'<p>A raw paragraph.</p>'
)
def test_raw_skip_inline_markdown(self):
self.assertMarkdownRenders(
'<p>A *raw* paragraph.</p>',
'<p>A... | TestHTMLBlocks |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/python.py | {
"start": 225,
"end": 573
} | class ____(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Python syntax."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize a PythonCodeTextSplitter."""
separators = self.get_separators_for_language(Language.PYTHON)
super().__init__(separators=separators, ... | PythonCodeTextSplitter |
python | pydantic__pydantic | .github/actions/people/people.py | {
"start": 6714,
"end": 6844
} | class ____(BaseModel):
"""Top-level container for pull requests response data."""
repository: PRsRepository
| PRsResponseData |
python | tensorflow__tensorflow | tensorflow/python/framework/test_util.py | {
"start": 149702,
"end": 152428
} | class ____:
"""A utility class to track increments to test counters."""
def __init__(self, name, label):
self.name = name
self.label = label
self.Reset()
def Reset(self) -> None:
self.last_value = _test_metrics_util.test_counter_value(
self.name, self.label)
def Get(self) -> int:
... | TestDelta |
python | crytic__slither | slither/core/declarations/structure_top_level.py | {
"start": 280,
"end": 510
} | class ____(Structure, TopLevel):
def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope") -> None:
super().__init__(compilation_unit)
self.file_scope: "FileScope" = scope
| StructureTopLevel |
python | giampaolo__psutil | tests/test_windows.py | {
"start": 1276,
"end": 2472
} | class ____(PsutilTestCase):
pass
def powershell(cmd):
"""Currently not used, but available just in case. Usage:
>>> powershell(
"Get-CIMInstance Win32_PageFileUsage | Select AllocatedBaseSize")
"""
if not shutil.which("powershell.exe"):
return pytest.skip("powershell.exe not avail... | WindowsTestCase |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modular_falcon_mamba.py | {
"start": 25842,
"end": 25909
} | class ____(MambaPreTrainedModel):
pass
| FalconMambaPreTrainedModel |
python | networkx__networkx | networkx/algorithms/tests/test_matching.py | {
"start": 14833,
"end": 15594
} | class ____:
"""Unit tests for the
:func:`~networkx.algorithms.matching.is_maximal_matching` function.
"""
def test_dict(self):
G = nx.path_graph(4)
assert nx.is_maximal_matching(G, {0: 1, 1: 0, 2: 3, 3: 2})
def test_valid(self):
G = nx.path_graph(4)
assert nx.is_ma... | TestIsMaximalMatching |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 58512,
"end": 62795
} | class ____(object):
"""
CUDA IPC handle. Serialization of the CUDA IPC handle object is implemented
here.
:param base: A reference to the original allocation to keep it alive
:type base: MemoryPointer
:param handle: The CUDA IPC handle, as a ctypes array of bytes.
:param size: Size of the o... | IpcHandle |
python | huggingface__transformers | src/transformers/models/afmoe/modular_afmoe.py | {
"start": 5601,
"end": 7000
} | class ____(nn.Module):
"""
Mixture of Experts (MoE) module for AFMoE.
This module implements a sparse MoE layer with both shared experts (always active) and
routed experts (activated based on token-choice routing).
"""
def __init__(self, config):
super().__init__()
self.config ... | AfmoeMoE |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 12071,
"end": 12221
} | class ____(ByteorderValues):
"""Check the byteorder in unicode (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
| TestByteorder_1_UCS2 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass9.py | {
"start": 528,
"end": 568
} | class ____:
pass
dataclass_only(A())
| A |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 35054,
"end": 35278
} | class ____(VOTableSpecWarning):
"""
The integer value is out of range for the size of the field.
"""
message_template = "Value '{}' is out of range for a {} integer field"
default_args = ("x", "n-bit")
| W51 |
python | pypa__twine | twine/auth.py | {
"start": 1529,
"end": 1833
} | class ____(t.TypedDict, total=False):
message: t.Optional[str]
errors: t.Optional[list[TrustedPublishingTokenRetrievalError]]
token: t.Optional[str]
success: t.Optional[bool]
# Depends on https://github.com/pypi/warehouse/issues/18235
expires: t.Optional[int]
| TrustedPublishingToken |
python | sanic-org__sanic | sanic/application/state.py | {
"start": 452,
"end": 689
} | class ____:
"""Information about a server instance."""
settings: dict[str, Any]
stage: ServerStage = field(default=ServerStage.STOPPED)
server: Optional[AsyncioServer] = field(default=None)
@dataclass
| ApplicationServerInfo |
python | sympy__sympy | sympy/physics/quantum/tests/test_innerproduct.py | {
"start": 936,
"end": 1032
} | class ____(Bra, FooState):
@classmethod
def dual_class(self):
return FooKet
| FooBra |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_bedrock.py | {
"start": 1498,
"end": 1798
} | class ____:
EXPECTED_WAITER_NAME: str | None = None
def test_setup(self):
# Ensure that all subclasses have an expected waiter name set.
if self.__class__.__name__ != "TestBaseBedrockTrigger":
assert isinstance(self.EXPECTED_WAITER_NAME, str)
| TestBaseBedrockTrigger |
python | TheAlgorithms__Python | sorts/external_sort.py | {
"start": 2867,
"end": 4238
} | class ____:
def __init__(self, block_size):
self.block_size = block_size
def sort(self, filename, sort_key=None):
num_blocks = self.get_number_blocks(filename, self.block_size)
splitter = FileSplitter(filename)
splitter.split(self.block_size, sort_key)
merger = FileMerg... | ExternalSort |
python | huggingface__transformers | tests/models/x_clip/test_modeling_x_clip.py | {
"start": 21912,
"end": 24901
} | class ____(unittest.TestCase):
@slow
def test_inference(self):
model_name = "microsoft/xclip-base-patch32"
model = XCLIPModel.from_pretrained(model_name).to(torch_device)
processor = XCLIPProcessor.from_pretrained(model_name)
video = prepare_video()
inputs = processor(
... | XCLIPModelIntegrationTest |
python | facelessuser__soupsieve | tests/test_level4/test_where.py | {
"start": 50,
"end": 755
} | class ____(util.TestCase):
"""Test where selectors."""
MARKUP = """
<div>
<p>Some text <span id="1"> in a paragraph</span>.
<a id="2" href="http://google.com">Link</a>
</p>
</div>
"""
def test_where(self):
"""Test multiple selectors with "where"."""
self.assert_sel... | TestWhere |
python | pypa__pipenv | pipenv/vendor/plette/models/sections.py | {
"start": 248,
"end": 316
} | class ____(DataModelMapping):
item_class = Script
| ScriptCollection |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 18133,
"end": 19487
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(self, config: DPTConfig):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = DPTViTAtten... | DPTViTLayer |
python | pandas-dev__pandas | asv_bench/benchmarks/algos/isin.py | {
"start": 2378,
"end": 3130
} | class ____:
params = [
[np.float64, np.int64, np.uint64, np.object_],
range(10, 21),
["inside", "outside"],
]
param_names = ["dtype", "exponent", "title"]
def setup(self, dtype, exponent, title):
M = 3 * 2 ** (exponent - 2)
# 0.77-the maximal share of occupied bu... | IsinAlmostFullWithRandomInt |
python | sympy__sympy | sympy/polys/numberfields/modules.py | {
"start": 42205,
"end": 53531
} | class ____(IntegerPowerable):
r"""
Represents an element of a :py:class:`~.Module`.
NOTE: Should not be constructed directly. Use the
:py:meth:`~.Module.__call__` method or the :py:func:`make_mod_elt()`
factory function instead.
"""
def __init__(self, module, col, denom=1):
"""
... | ModuleElement |
python | spack__spack | lib/spack/spack/builder.py | {
"start": 27350,
"end": 29287
} | class ____(BuilderWithDefaults):
"""The associated builder for the :class:`Package` base class. This class is typically only
used in ``package.py`` files when a package has multiple build systems. Packagers need to
implement the :meth:`install` phase to define how the package is installed.
This is the ... | GenericBuilder |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 17143,
"end": 17765
} | class ____(_RerankerProvider):
reranker: Union[Rerankers, _EnumLikeStr] = Field(
default=Rerankers.NVIDIA, frozen=True, exclude=True
)
model: Optional[str] = Field(default=None)
baseURL: Optional[AnyHttpUrl]
def _to_dict(self) -> Dict[str, Any]:
ret_dict = super()._to_dict()
... | _RerankerNvidiaConfig |
python | kamyu104__LeetCode-Solutions | Python/maximum-total-beauty-of-the-gardens.py | {
"start": 1197,
"end": 2333
} | class ____(object):
def maximumBeauty(self, flowers, newFlowers, target, full, partial):
"""
:type flowers: List[int]
:type newFlowers: int
:type target: int
:type full: int
:type partial: int
:rtype: int
"""
flowers.sort()
n = bisect.b... | Solution2 |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmc_scaled_concat.py | {
"start": 753,
"end": 9035
} | class ____:
def __init__(self, M, K):
self.M = M # number of hidden states
self.K = K # number of Gaussians
def fit(self, X, max_iter=25, eps=1e-1):
# train the HMM model using the Baum-Welch algorithm
# a specific instance of the expectation-maximization algorithm
... | HMM |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_composer.py | {
"start": 18252,
"end": 23678
} | class ____(GoogleCloudBaseOperator):
r"""
Update an environment.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param environment_id: Required. The ID of the Google... | CloudComposerUpdateEnvironmentOperator |
python | pytorch__pytorch | torch/ao/quantization/fx/custom_config.py | {
"start": 19979,
"end": 21815
} | class ____:
"""
Custom configuration for :func:`~torch.ao.quantization.quantize_fx.fuse_fx`.
Example usage::
fuse_custom_config = FuseCustomConfig().set_preserved_attributes(
["attr1", "attr2"]
)
"""
def __init__(self) -> None:
self.preserved_attributes: list[s... | FuseCustomConfig |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_imsi.py | {
"start": 1842,
"end": 4508
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid IMSI (International Mobile Subscriber Identity)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"... | ExpectColumnValuesToBeValidImsi |
python | huggingface__transformers | src/transformers/models/depth_pro/image_processing_depth_pro_fast.py | {
"start": 1434,
"end": 6697
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
size = {"height": 1536, "width": 1536}
do_resize = True
do_rescale = True
do_normalize = True
# DepthPro resizes image after rescaling and nor... | DepthProImageProcessorFast |
python | pandas-dev__pandas | pandas/_testing/__init__.py | {
"start": 9534,
"end": 16809
} | class ____(DataFrame):
_metadata = ["testattr"]
@property
def _constructor(self):
return lambda *args, **kwargs: SubclassedDataFrame(*args, **kwargs)
# error: Cannot override writeable attribute with read-only property
@property
def _constructor_sliced(self): # type: ignore[override]
... | SubclassedDataFrame |
python | readthedocs__readthedocs.org | readthedocs/integrations/migrations/0011_add_created_and_updated_fields.py | {
"start": 183,
"end": 1223
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("integrations", "0010_remove_old_jsonfields"),
]
operations = [
migrations.AlterModelOptions(
name="integration",
options={"get_latest_by": "modified"},
),
migrations.A... | Migration |
python | getsentry__sentry | src/sentry/flags/models.py | {
"start": 339,
"end": 793
} | class ____(Enum):
CREATED = 0
DELETED = 1
UPDATED = 2
@classmethod
def to_string(cls, integer):
if integer == 0:
return "created"
if integer == 1:
return "deleted"
if integer == 2:
return "updated"
raise ValueError
ACTION_MAP = {... | ActionEnum |
python | doocs__leetcode | solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/Solution.py | {
"start": 192,
"end": 865
} | class ____:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
def dfs(node: Optional[TreeNode], fa: Optional[TreeNode]):
if node is None:
return
if fa:
g[node.val].append(fa.val)
g[fa.val].append(node.val)
... | Solution |
python | google__flatbuffers | tests/MyGame/Example/Vec3.py | {
"start": 176,
"end": 1793
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 32
# Vec3
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Vec3
def X(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.numbe... | Vec3 |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/base.py | {
"start": 7984,
"end": 29197
} | class ____(BaseReader):
"""
ServiceNow Knowledge Base reader using PySNC with username/password or password grant flow.
This reader requires custom parsers for processing different file types. At minimum,
an HTML parser must be provided for processing article bodies. Additional parsers
can be provi... | SnowKBReader |
python | google__python-fire | fire/trace_test.py | {
"start": 4067,
"end": 5112
} | class ____(testutils.BaseTestCase):
def testFireTraceElementHasError(self):
el = trace.FireTraceElement()
self.assertFalse(el.HasError())
el = trace.FireTraceElement(error=ValueError('example error'))
self.assertTrue(el.HasError())
def testFireTraceElementAsStringNoMetadata(self):
el = trace.... | FireTraceElementTest |
python | optuna__optuna | optuna/storages/_rdb/models.py | {
"start": 10926,
"end": 11996
} | class ____(BaseModel):
__tablename__ = "trial_system_attributes"
__table_args__: Any = (UniqueConstraint("trial_id", "key"),)
trial_system_attribute_id = _Column(Integer, primary_key=True)
trial_id = _Column(Integer, ForeignKey("trials.trial_id"))
key = _Column(String(MAX_INDEXED_STRING_LENGTH))
... | TrialSystemAttributeModel |
python | pytorch__pytorch | test/distributed/tensor/test_redistribute.py | {
"start": 31524,
"end": 44495
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
return 8
def _extract_redistribute_trace_from_debug_mode(self, s: str) -> str:
import re
match = re.search(r"trace:\s*(.*)\)", s)
if match:
trace_str = match.group(1)
return trace_st... | DistributeWithDeviceOrderTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 41364,
"end": 41649
} | class ____(sgqlc.types.Enum):
"""The possible states of a milestone.
Enumeration Choices:
* `CLOSED`: A milestone that has been closed.
* `OPEN`: A milestone that is still open.
"""
__schema__ = github_schema
__choices__ = ("CLOSED", "OPEN")
| MilestoneState |
python | getsentry__sentry | src/sentry/integrations/api/serializers/models/external_issue.py | {
"start": 573,
"end": 1738
} | class ____(Serializer):
def get_attrs(
self,
item_list: Sequence[ExternalIssue],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
):
result = {}
for item in item_list:
# Get the integration (e.g. Jira, GitHub, etc) associated with that issue
... | ExternalIssueSerializer |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 261541,
"end": 268575
} | class ____(rv_continuous):
r"""A pearson type III continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `pearson3` is:
.. math::
f(x, \kappa) = \frac{|\beta|}{\Gamma(\alpha)}
(\beta (x - \zeta))^{\alpha - 1}
... | pearson3_gen |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/token.py | {
"start": 196,
"end": 697
} | class ____(LoginRequiredMixin, ListView):
"""
Show a page where the current logged-in user can see his tokens so they can revoke them
"""
context_object_name = "authorized_tokens"
template_name = "oauth2_provider/authorized-tokens.html"
model = get_access_token_model()
def get_queryset(sel... | AuthorizedTokensListView |
python | dagster-io__dagster | python_modules/automation/automation/parse_dataproc_configs.py | {
"start": 4681,
"end": 9022
} | class ____:
def __init__(self, schemas):
self.schemas = schemas
# Stashing these in a global so that we can write out after we're done constructing configs
self.all_enums = {}
def extract_config(self, base_field, suffix):
with IndentingBufferPrinter() as printer:
pr... | ConfigParser |
python | pytorch__pytorch | torch/utils/_debug_mode.py | {
"start": 14815,
"end": 15505
} | class ____(_DebugCall):
"""Designates entering an nn.Module's forward method"""
def __init__(self, module_name: str, call_depth: int, stack: bool = False) -> None:
super().__init__(call_depth, stack=stack)
self.module_name = module_name
def stringify_args(
self, attributes: list[st... | _NNModuleCall |
python | falconry__falcon | falcon/testing/helpers.py | {
"start": 3435,
"end": 10142
} | class ____:
"""Emits events on-demand to an ASGI app.
This class can be used to drive a standard ASGI app callable in order to
perform functional tests on the app in question.
Note:
In order to ensure the app is able to handle subtle variations
in the ASGI events that are allowed by th... | ASGIRequestEventEmitter |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_1.py | {
"start": 429,
"end": 469
} | class ____(E):
x: pyproj.Transformer
| F |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/flare/prompts.py | {
"start": 150,
"end": 1498
} | class ____(BaseOutputParser[tuple[str, bool]]):
"""Output parser that checks if the output is finished."""
finished_value: str = "FINISHED"
"""Value that indicates the output is finished."""
@override
def parse(self, text: str) -> tuple[str, bool]:
cleaned = text.strip()
finished =... | FinishedOutputParser |
python | mlflow__mlflow | mlflow/webhooks/types.py | {
"start": 7848,
"end": 8599
} | class ____(TypedDict):
"""Payload sent when a tag is set on a prompt version.
Example payload:
.. code-block:: python
{
"name": "example_prompt",
"version": "1",
"key": "example_key",
"value": "example_value",
}
"""
name: str
"... | PromptVersionTagSetPayload |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol3.py | {
"start": 4472,
"end": 4517
} | class ____(Proto13[T13], Protocol): ...
| Proto14 |
python | google__pytype | pytype/io_test.py | {
"start": 385,
"end": 6005
} | class ____(unittest.TestCase):
"""Test IO functions."""
def test_read_source_file_utf8(self):
with self._tmpfile("abc□def\n") as f:
self.assertEqual(io.read_source_file(f.name), "abc□def\n")
@contextlib.contextmanager
def _tmpfile(self, contents):
tempfile_options = {"mode": "w", "suffix": ".txt... | IOTest |
python | dagster-io__dagster | examples/experimental/assets_yaml_dsl/assets_yaml_dsl/domain_specific_dsl/stocks_dsl.py | {
"start": 1254,
"end": 3590
} | class ____(NamedTuple):
stock_infos: list[StockInfo]
index_strategy: IndexStrategy
forecast: Forecast
def build_stock_assets_object(stocks_dsl_document: dict[str, dict]) -> StockAssets:
return StockAssets(
stock_infos=[
StockInfo(ticker=stock_block["ticker"])
for stock_... | StockAssets |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 6145,
"end": 6850
} | class ____(DiagnosticPipError):
"""Raised when pyproject.toml has `build-system`, but no `build-system.requires`."""
reference = "missing-pyproject-build-system-requires"
def __init__(self, *, package: str) -> None:
super().__init__(
message=f"Can not process {escape(package)}",
... | MissingPyProjectBuildRequires |
python | apache__thrift | test/py/TestClient.py | {
"start": 13603,
"end": 13710
} | class ____(AbstractTest):
def get_protocol2(self, transport):
return None
| MultiplexedOptionalTest |
python | tensorflow__tensorflow | tensorflow/python/data/ops/options.py | {
"start": 12298,
"end": 18752
} | class ____(options_lib.OptionsBase):
"""Represents options for dataset optimizations.
You can set the optimization options of a dataset through the
`experimental_optimization` property of `tf.data.Options`; the property is
an instance of `tf.data.experimental.OptimizationOptions`.
```python
options = tf.d... | OptimizationOptions |
python | falconry__falcon | falcon/_typing.py | {
"start": 9078,
"end": 10762
} | class ____(Protocol[_AReqT, _ARespT]):
"""WSGI/ASGI middleware with response handler."""
async def process_response_async(
self,
req: _AReqT,
resp: _ARespT,
resource: object,
req_succeeded: bool,
) -> None: ...
# NOTE(jkmnt): This typing is far from perfect due to ... | UniversalMiddlewareWithProcessResponse |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 62321,
"end": 67612
} | class ____(WhisperPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.encoder = WhisperEncoder(config)
num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
if config.use_weighted_layer_sum:
self.layer_weights = nn.Par... | WhisperForAudioClassification |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/via_type_of.py | {
"start": 320,
"end": 1036
} | class ____:
def __init__(self, x: int, y: str, z: str) -> None:
self.x: int = x
self.y: str = y
self.z: Annotated[str, "test1"] = z
def test1_alarm1():
# always-via-type:int
c = Test1_C(**_test_source())
_test_sink(c.x)
def test1_alarm2():
# always-via-type:str
c = Te... | Test1_C |
python | ApeWorX__ape | src/ape_ethereum/transactions.py | {
"start": 6673,
"end": 7138
} | class ____(DynamicFeeTransaction):
"""
`EIP-4844 <https://eips.ethereum.org/EIPS/eip-4844>`__ transactions.
"""
max_fee_per_blob_gas: HexInt = Field(default=0, alias="maxFeePerBlobGas")
blob_versioned_hashes: list[HexBytes] = Field(default_factory=list, alias="blobVersionedHashes")
receiver: A... | SharedBlobTransaction |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/middle_adds_virtual/package.py | {
"start": 216,
"end": 429
} | class ____(Package):
url = "http://www.example.com/"
url = "http://www.example.com/2.0.tar.gz"
version("1.0", md5="abcdef1234567890abcdef1234567890")
depends_on("leaf-adds-virtual")
| MiddleAddsVirtual |
python | openai__openai-python | src/openai/types/audio/transcription.py | {
"start": 372,
"end": 630
} | class ____(BaseModel):
token: Optional[str] = None
"""The token in the transcription."""
bytes: Optional[List[float]] = None
"""The bytes of the token."""
logprob: Optional[float] = None
"""The log probability of the token."""
| Logprob |
python | doocs__leetcode | lcof/面试题20. 表示数值的字符串/Solution.py | {
"start": 0,
"end": 811
} | class ____:
def isNumber(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j and s[i] == " ":
i += 1
while i <= j and s[j] == " ":
j -= 1
if i > j:
return False
digit = dot = e = False
while i <= j:
if s[i] in "+-":
... | Solution |
python | jina-ai__jina | jina/orchestrate/pods/container.py | {
"start": 10737,
"end": 16460
} | class ____(BasePod):
"""
:class:`ContainerPod` starts a runtime of :class:`BaseRuntime` inside a container. It leverages :class:`multiprocessing.Process` to manage the logs and the lifecycle of docker container object in a robust way.
"""
def __init__(self, args: 'argparse.Namespace'):
super().... | ContainerPod |
python | kamyu104__LeetCode-Solutions | Python/number-of-student-replacements.py | {
"start": 42,
"end": 365
} | class ____(object):
def totalReplacements(self, ranks):
"""
:type ranks: List[int]
:rtype: int
"""
result = -1
mn = float("inf")
for x in ranks:
if x >= mn:
continue
mn = x
result += 1
return result
| Solution |
python | huggingface__transformers | tests/models/pix2struct/test_modeling_pix2struct.py | {
"start": 14809,
"end": 27474
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (Pix2StructForConditionalGeneration,) if is_torch_available() else ()
pipeline_model_mapping = (
{"image-to-text": Pix2StructForConditionalGeneration, "image-text-to-text": Pix2StructForCondi... | Pix2StructModelTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-monday/unit_tests/integrations/monday_responses/records/boards_record_builder.py | {
"start": 187,
"end": 464
} | class ____(MondayRecordBuilder):
@classmethod
def boards_record(cls) -> "BoardsRecordBuilder":
record_template = cls.extract_record("boards", __file__, NestedPath(["data", "boards", 0]))
return cls(record_template, FieldPath("id"), None)
| BoardsRecordBuilder |
python | python__mypy | test-data/unit/plugins/fnplugin.py | {
"start": 143,
"end": 548
} | class ____(Plugin):
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname == "__main__.f":
return my_hook
assert fullname is not None
return None
def my_hook(ctx: FunctionContext) -> Type:
return ctx.api.named_generic_type("buil... | MyPlugin |
python | huggingface__transformers | src/transformers/models/exaone4/modeling_exaone4.py | {
"start": 16135,
"end": 19829
} | class ____(Exaone4PreTrainedModel):
def __init__(self, config: Exaone4Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.l... | Exaone4Model |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 612,
"end": 12617
} | class ____(DefaultFieldsModel):
"""
A pre-production artifact provided by the user, presumably from their CI/CD pipeline or a manual build.
With this, we can analyze their artifact and provide them with insights to fix _before_
it's released to production.
Examples:
- iOS app builds
- Andro... | PreprodArtifact |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 6790,
"end": 7445
} | class ____(graphene.ObjectType):
"""The primary dimension of a multipartitioned asset is the time-partitioned dimension.
If both dimensions of the asset are static or time-partitioned, the primary dimension is
the first defined dimension.
"""
primaryDimStartKey = graphene.NonNull(graphene.String)
... | GrapheneMultiPartitionRangeStatuses |
python | doocs__leetcode | solution/1400-1499/1476.Subrectangle Queries/Solution.py | {
"start": 0,
"end": 719
} | class ____:
def __init__(self, rectangle: List[List[int]]):
self.g = rectangle
self.ops = []
def updateSubrectangle(
self, row1: int, col1: int, row2: int, col2: int, newValue: int
) -> None:
self.ops.append((row1, col1, row2, col2, newValue))
def getValue(self, row: in... | SubrectangleQueries |
python | allegroai__clearml | examples/hyperdatasets/dataview_pytorch_dataloader.py | {
"start": 237,
"end": 4386
} | class ____(torch.utils.data.IterableDataset):
"""PyTorch IterableDataset wrapper around a DataView."""
def __init__(self, query_kwargs: Dict[str, Any], projection: Iterable[str] = None):
super().__init__()
self._query_kwargs = dict(query_kwargs)
self._projection = list(projection) if pr... | HyperDatasetIterable |
python | PrefectHQ__prefect | tests/runtime/test_task_run.py | {
"start": 3818,
"end": 4359
} | class ____:
async def test_run_count_is_attribute(self):
assert "run_count" in dir(task_run)
async def test_run_count_is_zero_when_not_set(self):
assert task_run.run_count == 0
async def test_run_count_returns_run_count_when_present_dynamically(self):
assert task_run.run_count == 0... | TestRunCount |
python | coleifer__peewee | tests/manytomany.py | {
"start": 570,
"end": 827
} | class ____(TestModel):
user = ForeignKeyField(User, backref='_xx_rel')
note = ForeignKeyField(AltNote, backref='_xx_rel')
class Meta:
primary_key = CompositeKey('user', 'note')
AltThroughDeferred.set_model(AltThroughModel)
| AltThroughModel |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/relativity/relativity.py | {
"start": 14921,
"end": 24477
} | class ____:
def __init__(self, clocks, ref, duration, dt):
self.clocks = clocks
self.ref = ref
self.duration = duration
self.dt = dt
@staticmethod
def hypTStep(dt, v0, x0, tau0, g):
## Hyperbolic step.
## If an object has proper acceleration g and starts... | Simulation |
python | getsentry__sentry | src/sentry/data_export/endpoints/data_export_details.py | {
"start": 669,
"end": 2678
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.DATA_BROWSING
permission_classes = (OrganizationDataExportPermission,)
def get(
self, request: Request, organization: Organization, data_export_id: str
) -> Response | Stream... | DataExportDetailsEndpoint |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 2560,
"end": 5451
} | class ____(MemoryLeakMixin):
def setUp(self):
super(BaseUFuncTest, self).setUp()
self.inputs = [
(np.uint32(0), types.uint32),
(np.uint32(1), types.uint32),
(np.int32(-1), types.int32),
(np.int32(0), types.int32),
(np.int32(1), types.int32... | BaseUFuncTest |
python | ansible__ansible | lib/ansible/_internal/_ssh/_ssh_agent.py | {
"start": 15377,
"end": 15625
} | class ____(PublicKeyMsg):
type: KeyAlgo
p: mpint
q: mpint
g: mpint
y: mpint
comments: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
@dataclasses.dataclass(order=True, slots=True)
| DSAPublicKeyMsg |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 56369,
"end": 56468
} | class ____(_ConfigBase):
b: float
k1: float
BM25Config = _BM25Config
@dataclass
| _BM25Config |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/conv2d_transpose_test.py | {
"start": 1418,
"end": 13419
} | class ____(test.TestCase):
def testConv2DTransposeSingleStride(self):
with self.cached_session():
for dtype in (dtypes.float32, dtypes.int32):
strides = [1, 1, 1, 1]
# Input, output: [batch, height, width, depth]
x_shape = [2, 6, 4, 3]
y_shape = [2, 6, 4, 2]
# Filt... | Conv2DTransposeTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/index_store/keyval_index_store.py | {
"start": 419,
"end": 4144
} | class ____(BaseIndexStore):
"""
Key-Value Index store.
Args:
kvstore (BaseKVStore): key-value store
namespace (str): namespace for the index store
collection_suffix (str): suffix for the collection name
"""
def __init__(
self,
kvstore: BaseKVStore,
... | KVIndexStore |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_onboarding_continuation_email.py | {
"start": 488,
"end": 955
} | class ____(View):
def get(self, request: HttpRequest) -> HttpResponse:
platforms = request.GET.getlist("platforms", ["javascript", "python", "flutter"])
org = Organization(id=1, name="My Company")
user = User(name="Ben")
preview = MailPreviewAdapter(**get_request_builder_args(user, o... | DebugOrganizationOnboardingContinuationEmail |
python | joerick__pyinstrument | pyinstrument/frame_ops.py | {
"start": 391,
"end": 5015
} | class ____(ValueError):
pass
def build_frame_tree(
frame_records: Sequence[FrameRecordType], context: FrameContext
) -> Frame | None:
if len(frame_records) == 0:
return None
root_frame = Frame(identifier_or_frame_info=DUMMY_ROOT_FRAME_IDENTIFIER, context=context)
# put the root frame at ... | IdentifierDoesntMatchException |
python | doocs__leetcode | solution/1800-1899/1899.Merge Triplets to Form Target Triplet/Solution.py | {
"start": 0,
"end": 349
} | class ____:
def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
x, y, z = target
d = e = f = 0
for a, b, c in triplets:
if a <= x and b <= y and c <= z:
d = max(d, a)
e = max(e, b)
f = max(f, c)
re... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.