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 | bokeh__bokeh | tests/unit/bokeh/core/property/test_override.py | {
"start": 1242,
"end": 1957
} | class ____:
def test_create_default(self) -> None:
o = bcpo.Override(default=10)
assert o.default_overridden
assert o.default == 10
#-----------------------------------------------------------------------------
# Dev API
#---------------------------------------------------------------------... | Test_Override |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecs/test_utils.py | {
"start": 395,
"end": 2041
} | class ____(EcsRunLauncher):
def __init__(
self,
inst_data: Optional[ConfigurableClassData] = None,
task_definition=None,
container_name="run",
secrets=None,
secrets_tag="dagster",
env_vars=None,
include_sidecars=False,
):
super().__init__(
... | CustomECSRunLauncher |
python | astropy__astropy | astropy/units/tests/test_quantity_ufuncs.py | {
"start": 51549,
"end": 51616
} | class ____:
data: u.Quantity
@dataclasses.dataclass
| DuckQuantity1 |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/duplicate_bases.py | {
"start": 177,
"end": 250
} | class ____(
A,
A,
):
...
# Duplicate base class is not last.
| F4 |
python | python__mypy | mypy/nodes.py | {
"start": 52873,
"end": 55190
} | class ____(Statement):
"""Assignment statement.
The same node class is used for single assignment, multiple assignment
(e.g. x, y = z) and chained assignment (e.g. x = y = z), assignments
that define new names, and assignments with explicit types ("# type: t"
or "x: t [= ...]").
An lvalue can ... | AssignmentStmt |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 13939,
"end": 16483
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim /... | BlipAttention |
python | doocs__leetcode | lcci/08.09.Bracket/Solution.py | {
"start": 0,
"end": 377
} | class ____:
def generateParenthesis(self, n: int) -> List[str]:
def dfs(l, r, t):
if l > n or r > n or l < r:
return
if l == n and r == n:
ans.append(t)
return
dfs(l + 1, r, t + '(')
dfs(l, r + 1, t + ')')
... | Solution |
python | django__django | tests/m2m_intermediary/models.py | {
"start": 663,
"end": 776
} | class ____(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
| Article |
python | dask__dask | dask/blockwise.py | {
"start": 630,
"end": 2650
} | class ____:
"""Blockwise-IO argument
This is the base class for indexable Blockwise-IO arguments.
When constructing a ``Blockwise`` Layer, one or more of the
collection tuples passed in with ``indices`` may contain a
``BlockwiseDep`` instance (in place of a "real" collection name).
This allows ... | BlockwiseDep |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg_catalog.py | {
"start": 1055,
"end": 1148
} | class ____(TypeDecorator[str]):
impl = Text(collation="C")
cache_ok = True
| PG_NODE_TREE |
python | PyCQA__pylint | tests/functional/c/class_members_py30.py | {
"start": 739,
"end": 879
} | class ____:
"""use object.__setattr__"""
def __init__(self):
self.__setattr__('toto', 'tutu')
from abc import ABCMeta
| NewClass |
python | davidhalter__jedi | test/completion/ordering.py | {
"start": 1646,
"end": 2080
} | class ____():
def __init__(self, a):
self.a = a
#? float()
a(1.0).a
#?
a().a
# -----------------
# imports
# -----------------
math = 3
import math
#? ['cosh']
math.cosh
#? []
math.real
math = 3
#? int()
math
#? []
math.cos
# do the same for star imports
cosh = 3
from math import *
# cosh doesn't work... | a |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 235082,
"end": 235634
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("first_day", "name", "total_weeks", "year")
first_day = sgqlc.types.Field(sgqlc.types.non_null(Date), graphql_name="firstDay")
name = sgqlc.types.Field(sgqlc.types.non_null(St... | ContributionCalendarMonth |
python | ray-project__ray | python/ray/serve/tests/test_list_outbound_deployments.py | {
"start": 2528,
"end": 7037
} | class ____:
"""Test suite for list_outbound_deployments() method."""
async def test_stored_handles_in_init(self, serve_instance):
"""Test listing handles that are passed to __init__ and stored as attributes."""
app_name = "test_stored_handles"
# Build and deploy the app
handle_... | TestListOutboundDeployments |
python | getsentry__sentry | src/sentry/identity/services/identity/service.py | {
"start": 545,
"end": 2768
} | class ____(RpcService):
key = "identity"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.identity.services.identity.impl import DatabaseBackedIdentityService
return DatabaseBackedIdentityService()
@rpc_method
@abstractmet... | IdentityService |
python | streamlit__streamlit | lib/streamlit/runtime/scriptrunner/script_runner.py | {
"start": 5926,
"end": 32127
} | class ____:
def __init__(
self,
session_id: str,
main_script_path: str,
session_state: SessionState,
uploaded_file_mgr: UploadedFileManager,
script_cache: ScriptCache,
initial_rerun_data: RerunData,
user_info: dict[str, str | bool | None],
frag... | ScriptRunner |
python | tensorflow__tensorflow | tensorflow/python/saved_model/nested_structure_coder.py | {
"start": 8719,
"end": 9164
} | class ____:
"""Codec for None."""
def can_encode(self, pyobj):
return pyobj is None
def do_encode(self, none_value, encode_fn):
del encode_fn, none_value
value = struct_pb2.StructuredValue()
value.none_value.CopyFrom(struct_pb2.NoneValue())
return value
def can_decode(self, value):
re... | _NoneCodec |
python | langchain-ai__langchain | libs/core/tests/unit_tests/messages/test_utils.py | {
"start": 20531,
"end": 52866
} | class ____(FakeChatModel):
@override
def get_num_tokens_from_messages(
self,
messages: list[BaseMessage],
tools: Sequence[dict[str, Any] | type | Callable | BaseTool] | None = None,
) -> int:
return dummy_token_counter(messages)
def test_convert_to_messages() -> None:
m... | FakeTokenCountingModel |
python | PrefectHQ__prefect | src/prefect/cache_policies.py | {
"start": 9900,
"end": 10357
} | class ____(CachePolicy):
"""
Policy that computes the cache key based on a hash of the flow parameters.
"""
def compute_key(
self,
task_ctx: TaskRunContext,
inputs: dict[str, Any],
flow_parameters: dict[str, Any],
**kwargs: Any,
) -> Optional[str]:
if... | FlowParameters |
python | sphinx-doc__sphinx | sphinx/domains/python/__init__.py | {
"start": 8816,
"end": 9097
} | class ____(PyMethod):
"""Description of a classmethod."""
option_spec: ClassVar[OptionSpec] = PyObject.option_spec.copy()
def run(self) -> list[Node]:
self.name = 'py:method'
self.options['classmethod'] = True
return super().run()
| PyClassMethod |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 35045,
"end": 40239
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (SpeechT5ForTextToSpeech,) if is_torch_available() else ()
all_generative_model_classes = ()
is_encoder_decoder = True
def setUp(self):
self.model_tester = SpeechT5ForTextToSpeechTester(self)
self.config_tester = Confi... | SpeechT5ForTextToSpeechTest |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 2294,
"end": 2535
} | class ____(TorchDynamoException):
restart_reason: Optional[str]
def __init__(self, *args: Any, restart_reason: Optional[str] = None) -> None:
self.restart_reason = restart_reason
super().__init__(*args)
| RestartAnalysis |
python | uqfoundation__dill | dill/tests/test_selected.py | {
"start": 872,
"end": 3069
} | class ____(object):
def _method(self):
pass
from dill import objects
from dill import load_types
load_types(pickleable=True,unpickleable=False)
_newclass = objects['ClassObjectType']
# some clean-up #FIXME: should happen internal to dill
objects['TemporaryFileType'].close()
objects['FileType'].close()
del object... | _d |
python | fastai__fastai | fastai/tabular/core.py | {
"start": 13480,
"end": 13750
} | class ____:
"Namespace containing the various filling strategies."
def median (c,fill): return c.median()
def constant(c,fill): return fill
def mode (c,fill): return c.dropna().value_counts().idxmax()
# %% ../../nbs/40_tabular.core.ipynb 81
| FillStrategy |
python | ray-project__ray | release/train_tests/xgboost_lightgbm/train_batch_inference_benchmark.py | {
"start": 1325,
"end": 1531
} | class ____(BasePredictor):
def __call__(self, data: pd.DataFrame) -> Dict[str, np.ndarray]:
dmatrix = xgb.DMatrix(data)
return {"predictions": self.model.predict(dmatrix)}
| XGBoostPredictor |
python | getsentry__sentry | src/sentry/interfaces/message.py | {
"start": 308,
"end": 1282
} | class ____(Interface):
"""
A message consisting of either a ``formatted`` arg, or an optional
``message`` with a list of ``params``.
- ``message`` and ``formatted`` are limited to 1000 characters.
>>> {
>>> "message": "My raw message with interpreted strings like %s",
>>> "formatte... | Message |
python | doocs__leetcode | solution/1800-1899/1889.Minimum Space Wasted From Packaging/Solution.py | {
"start": 0,
"end": 550
} | class ____:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
mod = 10**9 + 7
ans = inf
packages.sort()
for box in boxes:
box.sort()
if packages[-1] > box[-1]:
continue
s = i = 0
for b in box:... | Solution |
python | vyperlang__vyper | vyper/venom/memory_location.py | {
"start": 438,
"end": 3388
} | class ____:
# Initialize after class definition
EMPTY: ClassVar[MemoryLocation]
UNDEFINED: ClassVar[MemoryLocation]
@classmethod
def from_operands(
cls, offset: IROperand | int, size: IROperand | int, var_base_pointers: dict
) -> MemoryLocation:
if isinstance(size, IRLiteral):
... | MemoryLocation |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_inlinehilite.py | {
"start": 756,
"end": 3137
} | class ____(util.MdCase):
"""Test general cases for inline highlight."""
extension = [
'markdown.extensions.attr_list',
'pymdownx.highlight',
'pymdownx.inlinehilite',
]
extension_configs = {
'pymdownx.inlinehilite': {
'style_plain_text': True,
'css... | TestInlineHilite |
python | great-expectations__great_expectations | tests/data_context/test_workspace_aware_context.py | {
"start": 10019,
"end": 13268
} | class ____:
"""Test context behavior when GX_CLOUD_WORKSPACE_ID environment variable is set."""
@pytest.mark.unit
def test_get_context_uses_env_workspace_id(
self,
unset_gx_env_variables: None,
monkeypatch: pytest.MonkeyPatch,
mock_cloud_config_params: dict[str, Any],
... | TestContextWithWorkspaceIdEnvironmentVariable |
python | numpy__numpy | numpy/ma/tests/test_old_ma.py | {
"start": 29518,
"end": 33075
} | class ____:
def _create_data(self):
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
7.189, ... | TestArrayMethods |
python | kamyu104__LeetCode-Solutions | Python/print-binary-tree.py | {
"start": 41,
"end": 999
} | class ____(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def getWidth(root):
if not root:
return 0
return 2 * max(getWidth(root.left), getWidth(root.right)) + 1
def getHeight(root):
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 22161,
"end": 22689
} | class ____(StateMigration):
"""
Migrates global state to include use_global_cursor key. Previously legacy GlobalSubstreamCursor was used.
"""
def should_migrate(self, stream_state: Mapping[str, Any]) -> bool:
return stream_state and not stream_state.get("use_global_cursor")
def migrate(sel... | GoogleAdsGlobalStateMigration |
python | huggingface__transformers | src/transformers/pipelines/audio_classification.py | {
"start": 2039,
"end": 11074
} | class ____(Pipeline):
"""
Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
formats.
Example:
```python
>>> from tran... | AudioClassificationPipeline |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_forms.py | {
"start": 297,
"end": 1302
} | class ____(LiveWhooshRoundTripTestCase):
fixtures = ["base_data"]
def setUp(self):
self.old_spelling_setting = settings.HAYSTACK_CONNECTIONS["whoosh"].get(
"INCLUDE_SPELLING", False
)
settings.HAYSTACK_CONNECTIONS["whoosh"]["INCLUDE_SPELLING"] = True
super().setUp()... | SpellingSuggestionTestCase |
python | pypa__pipenv | pipenv/patched/pip/_vendor/typing_extensions.py | {
"start": 59103,
"end": 75938
} | class ____(type):
def __instancecheck__(cls, __instance: Any) -> bool:
return isinstance(__instance, cls._backported_typevarlike)
if _PEP_696_IMPLEMENTED:
from typing import TypeVar
else:
# Add default and infer_variance parameters from PEP 696 and 695
class TypeVar(metaclass=_TypeVarLikeMeta)... | _TypeVarLikeMeta |
python | weaviate__weaviate-python-client | weaviate/backup/backup.py | {
"start": 853,
"end": 1083
} | class ____(str, Enum):
"""The status of a backup."""
STARTED = "STARTED"
TRANSFERRING = "TRANSFERRING"
TRANSFERRED = "TRANSFERRED"
SUCCESS = "SUCCESS"
FAILED = "FAILED"
CANCELED = "CANCELED"
| BackupStatus |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 85065,
"end": 86778
} | class ____(PerceiverAbstractDecoder):
"""
Cross-attention based classification decoder. Light-weight wrapper of [`PerceiverBasicDecoder`] for logit output.
Will turn the output of the Perceiver encoder which is of shape (batch_size, num_latents, d_latents) to a tensor of
shape (batch_size, num_labels). ... | PerceiverClassificationDecoder |
python | doocs__leetcode | solution/2200-2299/2210.Count Hills and Valleys in an Array/Solution.py | {
"start": 0,
"end": 404
} | class ____:
def countHillValley(self, nums: List[int]) -> int:
ans = j = 0
for i in range(1, len(nums) - 1):
if nums[i] == nums[i + 1]:
continue
if nums[i] > nums[j] and nums[i] > nums[i + 1]:
ans += 1
if nums[i] < nums[j] and nums[... | Solution |
python | facebook__pyre-check | client/commands/servers.py | {
"start": 3878,
"end": 8761
} | class ____:
running: List[RunningServerStatus] = dataclasses.field(default_factory=list)
defunct: List[DefunctServerStatus] = dataclasses.field(default_factory=list)
def to_json(self) -> List[Dict[str, Any]]:
return [status.to_json() for status in self.running] + [
status.to_json() for ... | AllServerStatus |
python | PrefectHQ__prefect | tests/server/models/test_variables.py | {
"start": 3085,
"end": 3421
} | class ____:
async def test_read_variable(
self,
session,
variable,
):
model = await read_variable(session, variable.id) # type: ignore
assert model
assert model.id == variable.id
assert model.name == variable.name
assert model.tags == variable.tag... | TestReadVariable |
python | google__pytype | pytype/pyi/parser_test.py | {
"start": 63737,
"end": 64290
} | class ____(parser_test_base.ParserTestBase):
def test_canonical_version(self):
src = textwrap.dedent("""
from typing import Any
def foo(x: int = 0) -> Any: ...
def foo(x: str) -> Any: ...
""")
expected = textwrap.dedent("""
from typing import Any, overload
@overlo... | CanonicalPyiTest |
python | neetcode-gh__leetcode | python/0567-permutation-in-string.py | {
"start": 0,
"end": 1049
} | class ____:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
s1Count, s2Count = [0] * 26, [0] * 26
for i in range(len(s1)):
s1Count[ord(s1[i]) - ord("a")] += 1
s2Count[ord(s2[i]) - ord("a")] += 1
matches = 0
... | Solution |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 46788,
"end": 61687
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
losses.SparseCategoricalCrossentropy(name="scce")
)
def test_all_correct_unweighted(self):
y_true = np.array([[0], [1], [2]], dtype="int64")
y_pred = np.array(
[[1.0, ... | SparseCategoricalCrossentropyTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 7600,
"end": 14687
} | class ____(BaseComponent):
"""
Base node Object.
Generic abstract interface for retrievable nodes
"""
# hash is computed on local field, during the validation process
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
id_: str = Field(
default_factory=lamb... | BaseNode |
python | ansible__ansible | lib/ansible/module_utils/_internal/_datatag/_tags.py | {
"start": 197,
"end": 468
} | class ____(_datatag.AnsibleDatatagBase):
msg: str
help_text: t.Optional[str] = None
date: t.Optional[str] = None
version: t.Optional[str] = None
deprecator: t.Optional[_messages.PluginInfo] = None
formatted_traceback: t.Optional[str] = None
| Deprecated |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 17885,
"end": 17928
} | class ____:
exception = None
| DummyRequest |
python | tensorflow__tensorflow | tensorflow/python/training/supervisor_test.py | {
"start": 2387,
"end": 36181
} | class ____(test.TestCase):
def _test_dir(self, test_name):
test_dir = os.path.join(self.get_temp_dir(), test_name)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
return test_dir
def _wait_for_glob(self, pattern, timeout_secs, for_checkpoint=True):
"""Wait for a checkpoint file to appea... | SupervisorTest |
python | viewflow__viewflow | tests/workflow/test_flow_viewset__workflow.py | {
"start": 2072,
"end": 2226
} | class ____(Flow):
process_class = TestWorkflowViewestProcess
start = flow.StartHandle().Next(this.end)
end = flow.End()
| TestWorkflowViewestFlow |
python | django-compressor__django-compressor | compressor/tests/test_mtime_cache.py | {
"start": 147,
"end": 1382
} | class ____(TestCase):
# FIXME: add actual tests, improve the existing ones.
exclusion_patterns = [
"*CACHE*",
"*custom*",
"*066cd253eada.js",
"*d728fc7f9301.js",
"*8a0fed36c317.js",
"test.txt*",
]
def default_ignore(self):
return ["--ignore=%s" %... | TestMtimeCacheCommand |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/attributes.py | {
"start": 4155,
"end": 4548
} | class ____:
attribute: str = ""
def test_no_issue_sanitize():
x = A()
x.attribute = _test_source()
x.attribute = ""
_test_sink(x.attribute)
def sanitize_attribute(x: A) -> None:
x.attribute = ""
def test_no_issue_sanitize_via_call():
x = A()
x.attribute = _test_source()
sanitize_a... | A |
python | spack__spack | lib/spack/spack/vendor/macholib/MachO.py | {
"start": 5018,
"end": 16685
} | class ____(object):
"""
Provides reading/writing the Mach-O header of a specific existing file.
If allow_unknown_load_commands is True, allows unknown load commands.
Otherwise, raises ValueError if the file contains an unknown load command.
"""
# filename - the original filename of this ma... | MachOHeader |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_call_interpreting_event.py | {
"start": 221,
"end": 774
} | class ____(BaseModel):
item_id: str
"""The unique identifier of the code interpreter tool call item."""
output_index: int
"""
The index of the output item in the response for which the code interpreter is
interpreting code.
"""
sequence_number: int
"""The sequence number of this ev... | ResponseCodeInterpreterCallInterpretingEvent |
python | has2k1__plotnine | plotnine/scales/limits.py | {
"start": 3830,
"end": 3913
} | class ____(_lim):
"""
Shapee limits
"""
aesthetic = "shape"
| shapelim |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/utils.py | {
"start": 7083,
"end": 14018
} | class ____(RegressionCheck):
def compute(self, current, compared):
return current[self.field] - compared[self.field]
def parse_compare_fail(
string,
rex=re.compile(
r'^(?P<field>min|max|mean|median|stddev|iqr):' r'((?P<percentage>[0-9]+)%|(?P<difference>[0-9]*\.?[0-9]+([eE][-+]?[' r'0-9]+)... | DifferenceRegressionCheck |
python | facebook__pyre-check | tools/typeshed_patcher/typeshed.py | {
"start": 4744,
"end": 6285
} | class ____(Typeshed):
"""
A typeshed backed up by another `Typeshed` object and a set of patch results
that overwrite file contents in the base `Typeshed` object.
Patches are specified as a dictionary from paths to either a `str` or `None`.
When the value is a string, it serves as the new content f... | PatchedTypeshed |
python | pypa__pipenv | pipenv/cli/options.py | {
"start": 1960,
"end": 2330
} | class ____:
def __init__(self):
self.dev = False
self.pre = False
self.ignore_pipfile = False
self.code = False
self.requirementstxt = None
self.deploy = False
self.packages = []
self.editables = []
self.extra_pip_args = []
self.categor... | InstallState |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 9186,
"end": 9820
} | class ____(Sequence):
"""Composite of a LazyAttribute and a Sequence.
Attributes:
function (function): A function, expecting the current LazyStub and the
current sequence counter.
type (function): A function converting an integer into the expected kind
of counter for the... | LazyAttributeSequence |
python | django__django | tests/middleware/tests.py | {
"start": 30016,
"end": 35024
} | class ____(SimpleTestCase):
"""
Tests for the X-Frame-Options clickjacking prevention middleware.
"""
def test_same_origin(self):
"""
The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the
middleware use that value for the HTTP header.
"""
with override... | XFrameOptionsMiddlewareTest |
python | ansible__ansible | test/integration/targets/callback-dispatch/callback_plugins/missing_base_class.py | {
"start": 37,
"end": 169
} | class ____:
"""This callback should fail to load since it doesn't extend the required builtin base class."""
pass
| CallbackModule |
python | kamyu104__LeetCode-Solutions | Python/sort-vowels-in-a-string.py | {
"start": 45,
"end": 1193
} | class ____(object):
def sortVowels(self, s):
"""
:type s: str
:rtype: str
"""
def inplace_counting_sort(nums, reverse=False): # Time: O(n)
if not nums:
return
count = [0]*(max(nums)+1)
for num in nums:
count... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_ops.py | {
"start": 28012,
"end": 51812
} | class ____:
"""Helper class for with_space_to_batch.
Note that this class assumes that shapes of input and filter passed to
`__call__` are compatible with `input_shape`, `filter_shape`, and
`spatial_dims` passed to the constructor.
Arguments
input_shape: static shape of input. i.e. input.shape.
dila... | _WithSpaceToBatch |
python | tensorflow__tensorflow | tensorflow/python/ops/data_flow_ops.py | {
"start": 38378,
"end": 41156
} | class ____(QueueBase):
"""A queue implementation that dequeues elements in prioritized order.
See `tf.queue.QueueBase` for a description of the methods on
this class.
"""
def __init__(self,
capacity,
types,
shapes=None,
names=None,
s... | PriorityQueue |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 28870,
"end": 29594
} | class ____(NamedColumn[_T]):
__visit_name__ = "scalar_function_column"
_traverse_internals = [
("name", InternalTraversal.dp_anon_name),
("type", InternalTraversal.dp_type),
("fn", InternalTraversal.dp_clauseelement),
]
is_literal = False
table = None
def __init__(
... | ScalarFunctionColumn |
python | apache__airflow | providers/apache/livy/tests/unit/apache/livy/sensors/test_livy.py | {
"start": 1165,
"end": 2492
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
create_connection_without_db(
Connection(conn_id="livyu... | TestLivySensor |
python | spyder-ide__spyder | spyder/api/fonts.py | {
"start": 384,
"end": 1150
} | class ____:
"""
Font types used in Spyder plugins and the entire application.
Notes
-----
* This enum is meant to be used to get the QFont object corresponding to
each type.
* The names associated to the values in this enum depend on historical
reasons that go back to Spyder 2 and a... | SpyderFontType |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-telegram/llama_index/readers/telegram/base.py | {
"start": 274,
"end": 5897
} | class ____(BaseReader):
"""
Telegram posts/chat messages/comments reader.
Read posts/chat messages/comments from Telegram channels or chats.
Before working with Telegram’s API, you need to get your own API ID and hash:
1. Login to your Telegram account with the phone number of the developer a... | TelegramReader |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/linear_model.py | {
"start": 1705,
"end": 2815
} | class ____(Predictor, Estimator, Benchmark):
"""
Benchmarks for Ridge.
"""
param_names = ["representation", "solver"]
params = (
["dense", "sparse"],
["auto", "svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga"],
)
def setup_cache(self):
super().setup_cache()
... | RidgeBenchmark |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 36993,
"end": 41586
} | class ____(Structure):
_fields_ = (
("vmaddr", p_uint64),
("fileoff", p_uint64),
("entry_id", lc_str),
("reserved", p_uint32),
)
LC_REGISTRY = {
LC_SEGMENT: segment_command,
LC_IDFVMLIB: fvmlib_command,
LC_LOADFVMLIB: fvmlib_command,
LC_ID_DYLIB: dylib_command,
... | fileset_entry_command |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 339754,
"end": 350924
} | class ____:
class RaiseOnBool:
def __bool__(self):
raise ValueError
true_vals = [True, np._CopyMode.ALWAYS, np.True_]
if_needed_vals = [None, np._CopyMode.IF_NEEDED]
false_vals = [False, np._CopyMode.NEVER, np.False_]
def test_scalars(self):
# Test both numpy and pyth... | TestArrayCreationCopyArgument |
python | jina-ai__jina | tests/integration/docarray_v2/wrong_schema_executor.py | {
"start": 106,
"end": 230
} | class ____(Executor):
@requests
def foo(self, docs: TextDoc, **kwargs) -> DocList[TextDoc]:
pass
| WrongSchemaExec |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py | {
"start": 20694,
"end": 24679
} | class ____(TestXComEndpoint):
@pytest.mark.parametrize(
("dag_id", "task_id", "dag_run_id", "request_body", "expected_status", "expected_detail"),
[
# Test case: Valid input, should succeed with 201 CREATED
pytest.param(
TEST_DAG_ID,
TEST_TASK_... | TestCreateXComEntry |
python | h5py__h5py | h5py/tests/test_group.py | {
"start": 10838,
"end": 11257
} | class ____(BaseGroup):
"""
Base class for mapping tests
"""
def setUp(self):
self.f = File(self.mktemp(), 'w')
self.groups = ('a', 'b', 'c', 'd')
for x in self.groups:
self.f.create_group(x)
self.f['x'] = h5py.SoftLink('/mongoose')
self.groups = s... | BaseMapping |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_checkpoint.py | {
"start": 10415,
"end": 10931
} | class ____(nn.Module):
def __init__(self, checkpoint: bool = False, use_reentrant: bool = True):
super().__init__()
self.l1 = nn.Linear(100, 100)
self.relu = nn.ReLU()
self.checkpoint1 = ModelWithCheckpointSubmodule(checkpoint, use_reentrant)
self.checkpoint2 = ModelWithCheck... | TestModel |
python | scipy__scipy | scipy/linalg/tests/test_decomp_lu.py | {
"start": 8038,
"end": 11321
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(1682281250228846)
self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
# Those matrices are more robust to detect problems in permutation
# matrices th... | TestLUFactor |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/utils/utils.py | {
"start": 25036,
"end": 27712
} | class ____(InfoJsonEncodable):
"""Defines encoding DAG object to JSON."""
includes = [
"dag_id",
"description",
"fileloc",
"owner",
"owner_links",
"schedule_interval", # For Airflow 2 only -> AF3 has timetable_summary
"start_date",
"tags",
]
... | DagInfo |
python | getsentry__sentry | src/sentry/rules/conditions/event_frequency.py | {
"start": 21915,
"end": 31769
} | class ____(EventUniqueUserFrequencyCondition):
id = "sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyConditionWithConditions"
label = "The issue is seen by more than {value} users in {interval} with conditions"
def query_hook(
self,
event: GroupEvent,
start: datetime... | EventUniqueUserFrequencyConditionWithConditions |
python | getsentry__sentry | src/sentry/integrations/api/bases/external_actor.py | {
"start": 6641,
"end": 7264
} | class ____(ExternalActorSerializerBase):
_actor_key = "team_id"
team_id = serializers.IntegerField(required=True)
def validate_team_id(self, team_id: int) -> Team:
"""Ensure that this team exists and that they belong to the organization."""
try:
return Team.objects.get(id=team_... | ExternalTeamSerializer |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/base.py | {
"start": 2139,
"end": 47204
} | class ____(BaseReader, DispatcherSpanMixin):
"""
Confluence reader.
Reads a set of confluence pages given a space key and optionally a list of page ids
For more on OAuth login, checkout:
- https://atlassian-python-api.readthedocs.io/index.html
- https://developer.atlassian.com/cloud/co... | ConfluenceReader |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 145369,
"end": 148601
} | class ____(Layout):
def __init__(self, target: IRNode) -> None:
super().__init__(
target.get_device_or_error(),
target.get_dtype(),
target.get_size(),
None,
)
self.target = target
name = self.get_buffer().get_name()
V.graph.mark... | MutationLayoutSHOULDREMOVE |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 1319,
"end": 1367
} | class ____(ASTNode):
value: str
@dataclass
| Hex |
python | kamyu104__LeetCode-Solutions | Python/top-k-frequent-elements.py | {
"start": 50,
"end": 750
} | class ____(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = collections.Counter(nums)
buckets = [[] for _ in xrange(len(nums)+1)]
for i, count in counts.iteritems():
buckets[cou... | Solution |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 8643,
"end": 9773
} | class ____(Protocol[ContextT]):
"""Extra data used during validation."""
@property
def context(self) -> ContextT:
"""The current validation context."""
...
@property
def config(self) -> CoreConfig | None:
"""The CoreConfig that applies to this validation."""
...
... | ValidationInfo |
python | ray-project__ray | python/ray/util/client/server/logservicer.py | {
"start": 2724,
"end": 4278
} | class ____(ray_client_pb2_grpc.RayletLogStreamerServicer):
def __init__(self):
super().__init__()
self.num_clients = 0
self.client_lock = threading.Lock()
def Logstream(self, request_iterator, context):
initialized = False
with self.client_lock:
threshold = C... | LogstreamServicer |
python | tiangolo__fastapi | scripts/contributors.py | {
"start": 1778,
"end": 1843
} | class ____(BaseModel):
pullRequests: PullRequests
| PRsRepository |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-tree-from-leaf-values.py | {
"start": 29,
"end": 438
} | class ____(object):
def mctFromLeafValues(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
result = 0
stk = [float("inf")]
for x in arr:
while stk[-1] <= x:
result += stk.pop() * min(stk[-1], x)
stk.append(x)
... | Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/asset/__init__.py | {
"start": 15811,
"end": 16901
} | class ____(BaseAsset, AttrsInstance):
"""
Reference to an asset.
This class is not intended to be instantiated directly. Call ``Asset.ref``
instead to create one of the subclasses.
:meta private:
"""
_dependency_type: Literal["asset-name-ref", "asset-uri-ref"]
def as_expression(self)... | AssetRef |
python | doocs__leetcode | solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/Solution.py | {
"start": 0,
"end": 430
} | class ____:
def maxProfit(self, prices: List[int], fee: int) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= len(prices):
return 0
ans = dfs(i + 1, j)
if j:
ans = max(ans, prices[i] + dfs(i + 1, 0) - fee)
else:
... | Solution |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 19745,
"end": 21610
} | class ____(TestBaseAsyncSpiderMiddleware):
ITEM_TYPE = dict
MW_SIMPLE = ProcessSpiderOutputSimpleMiddleware
MW_ASYNCGEN = ProcessSpiderOutputAsyncGenMiddleware
MW_UNIVERSAL = ProcessSpiderOutputUniversalMiddleware
MW_EXC_SIMPLE = ProcessSpiderExceptionSimpleIterableMiddleware
MW_EXC_ASYNCGEN = P... | TestProcessSpiderException |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 32746,
"end": 33445
} | class ____(graphene.Mutation):
"""Sets the concurrency limit for a given concurrency key."""
Output = graphene.NonNull(graphene.Boolean)
class Meta:
name = "SetConcurrencyLimitMutation"
class Arguments:
concurrencyKey = graphene.Argument(graphene.NonNull(graphene.String))
limi... | GrapheneSetConcurrencyLimitMutation |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 50106,
"end": 50320
} | class ____(BatchPointwiseMathOpsPostGradFusion):
def __init__(self, **kwargs) -> None:
super().__init__(aten.div.Tensor, **kwargs)
@register_fusion("batch_aten_mul", pre_grad=False)
| BatchDivPostGradFusion |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/toys/input_managers.py | {
"start": 1143,
"end": 3499
} | class ____(PandasCsvIOManager):
def load_input(self, context) -> np.ndarray: # pyright: ignore[reportIncompatibleMethodOverride]
if context.upstream_output:
file_path = self._get_path(context.upstream_output)
df = np.genfromtxt(file_path, delimiter=",", dtype=None)
retur... | NumpyCsvIOManager |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/bash.py | {
"start": 1468,
"end": 11073
} | class ____(BaseOperator):
r"""
Execute a Bash script, command or set of commands.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BashOperator`
If BaseOperator.do_xcom_push is True, the last line written to stdout
will a... | BashOperator |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 2578,
"end": 2832
} | class ____(_MetadataRequester):
"""A Mixin to ``groups`` by default.
This Mixin makes the object to request ``groups`` by default as ``True``.
.. versionadded:: 1.3
"""
__metadata_request__split = {"groups": True}
| GroupsConsumerMixin |
python | walkccc__LeetCode | solutions/3121. Count the Number of Special Characters II/3121.py | {
"start": 0,
"end": 419
} | class ____:
def numberOfSpecialChars(self, word: str) -> int:
lower = collections.defaultdict(bool)
upper = collections.defaultdict(bool)
for c in word:
if c.islower():
lower[c] = not upper[c.upper()]
else:
upper[c] = True
return sum(lower[a] and upper[b]
f... | Solution |
python | python-openxml__python-docx | src/docx/oxml/xmlchemy.py | {
"start": 5103,
"end": 7410
} | class ____(BaseAttribute):
"""Defines an optional attribute on a custom element class.
An optional attribute returns a default value when not present for reading. When
assigned |None|, the attribute is removed, but still returns the default value when
one is specified.
"""
def __init__(
... | OptionalAttribute |
python | joblib__joblib | joblib/externals/loky/reusable_executor.py | {
"start": 3511,
"end": 10863
} | class ____(ProcessPoolExecutor):
def __init__(
self,
submit_resize_lock,
max_workers=None,
context=None,
timeout=None,
executor_id=0,
job_reducers=None,
result_reducers=None,
initializer=None,
initargs=(),
env=None,
):
... | _ReusablePoolExecutor |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/prediction_writer.py | {
"start": 1414,
"end": 6087
} | class ____(Callback):
"""Base class to implement how the predictions should be stored.
Args:
write_interval: When to write.
Example::
import torch
from lightning.pytorch.callbacks import BasePredictionWriter
class CustomWriter(BasePredictionWriter):
def __ini... | BasePredictionWriter |
python | numba__numba | numba/tests/test_array_attr.py | {
"start": 7991,
"end": 11257
} | class ____(MemoryLeakMixin, TestCase):
def check_complex(self, pyfunc):
cfunc = njit(pyfunc)
# test 1D
size = 10
arr = np.arange(size) + np.arange(size) * 10j
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
# test 2D
arr = arr.reshape(2, 5)
self.asser... | TestRealImagAttr |
python | spack__spack | lib/spack/spack/vendor/attr/_make.py | {
"start": 91629,
"end": 95758
} | class ____:
"""
Stores a factory callable.
If passed as the default value to `attrs.field`, the factory is used to
generate a new value.
:param callable factory: A callable that takes either none or exactly one
mandatory positional argument depending on *takes_self*.
:param bool takes_... | Factory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.