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 | ray-project__ray | python/ray/llm/_internal/serve/config_generator/utils/prompt.py | {
"start": 44,
"end": 251
} | class ____(Prompt):
@classmethod
def ask(cls, prompt: str, **kwargs):
# Automatically apply bold style to the BoldPrompt
return Prompt.ask(f"[bold]{prompt}[/bold]", **kwargs)
| BoldPrompt |
python | hyperopt__hyperopt | hyperopt/rdists.py | {
"start": 901,
"end": 2283
} | class ____(scipy_lognorm_gen):
def __init__(self, mu, sigma):
self.mu_ = mu
self.s_ = sigma
scipy_lognorm_gen.__init__(self)
# I still don't understand what scipy stats objects are doing
# re: this stuff
del self.__dict__["_parse_args"]
del self.__dict__["_pa... | lognorm_gen |
python | scrapy__scrapy | tests/CrawlerRunner/explicit_default_reactor.py | {
"start": 157,
"end": 544
} | class ____(Spider):
name = "no_request"
custom_settings = {
"TWISTED_REACTOR": None,
}
async def start(self):
return
yield
def main(reactor):
configure_logging(
{"LOG_FORMAT": "%(levelname)s: %(message)s", "LOG_LEVEL": "DEBUG"}
)
runner = CrawlerRunner()
... | NoRequestsSpider |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 6088,
"end": 6353
} | class ____(Event):
name: str = "create_webhook"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
events = arguments.get("events") or []
return {"events": [str(event) for event in events]}
| CreateWebhookEvent |
python | great-expectations__great_expectations | great_expectations/experimental/metric_repository/metrics.py | {
"start": 7012,
"end": 7259
} | class ____(MetricRepositoryBaseModel):
"""Collection of Metric objects produced during the same execution run."""
data_asset_id: Union[uuid.UUID, None] = Field(description="Data asset id", default=None)
metrics: Sequence[Metric]
| MetricRun |
python | doocs__leetcode | solution/0400-0499/0448.Find All Numbers Disappeared in an Array/Solution.py | {
"start": 0,
"end": 172
} | class ____:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
s = set(nums)
return [x for x in range(1, len(nums) + 1) if x not in s]
| Solution |
python | spack__spack | var/spack/test_repos/spack_repo/builder_test/packages/builder_and_mixins/package.py | {
"start": 814,
"end": 929
} | class ____(BuilderMixin, generic.GenericBuilder):
def install(self, pkg, spec, prefix):
pass
| GenericBuilder |
python | numba__numba | numba/core/serialize.py | {
"start": 5406,
"end": 6284
} | class ____:
"""Wrap a callable object to be pickled by path to workaround limitation
in pickling due to non-pickleable objects in function non-locals.
Note:
- Do not use this as a decorator.
- Wrapped object must be a global that exist in its parent module and it
can be imported by `from the_... | PickleCallableByPath |
python | django__django | tests/admin_filters/tests.py | {
"start": 851,
"end": 1495
} | class ____(SimpleListFilter):
def lookups(self, request, model_admin):
return (
("the 80s", "the 1980's"),
("the 90s", "the 1990's"),
("the 00s", "the 2000's"),
("other", "other decades"),
)
def queryset(self, request, queryset):
decade = ... | DecadeListFilter |
python | ray-project__ray | rllib/offline/estimators/tests/test_ope.py | {
"start": 6409,
"end": 11234
} | class ____(unittest.TestCase):
"""Compilation and learning tests for the Fitted-Q Evaluation model"""
@classmethod
def setUpClass(cls) -> None:
ray.init()
env = CliffWalkingWallEnv()
cls.policy = CliffWalkingWallPolicy(
observation_space=env.observation_space,
... | TestFQE |
python | apache__airflow | providers/slack/tests/unit/slack/hooks/test_slack.py | {
"start": 22745,
"end": 24208
} | class ____:
@pytest.fixture
def mock_get_conn(self):
with mock.patch(
"airflow.providers.slack.hooks.slack.get_async_connection", new_callable=mock.AsyncMock
) as m:
m.return_value = Connection(
conn_id=SLACK_API_DEFAULT_CONN_ID,
conn_type=... | TestSlackHookAsync |
python | joke2k__faker | faker/providers/person/sw/__init__.py | {
"start": 44,
"end": 8089
} | class ____(PersonProvider):
"""
A Faker provider for generating fake Swahili.
"""
formats = (
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"... | Provider |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-boarddocs/llama_index/readers/boarddocs/base.py | {
"start": 261,
"end": 4337
} | class ____(BaseReader):
"""
BoardDocs doc reader.
Read public agendas included on a BoardDocs site.
Args:
site (str): The BoardDocs site you'd like to index, e.g. "ca/redwood"
committee_id (str): The committee on the site you want to index
"""
def __init__(
self,
... | BoardDocsReader |
python | great-expectations__great_expectations | tests/datasource/fluent/data_asset/test_data_asset.py | {
"start": 15956,
"end": 16641
} | class ____:
def test_get_returns_id(
self,
unset_gx_env_variables: None,
data_context: AbstractDataContext,
) -> None:
# arrange
resource_name = random_name()
ds = data_context.data_sources.add_pandas(
name=resource_name,
)
asset = ds.a... | TestGetBatchDefinition |
python | pyinstaller__pyinstaller | PyInstaller/building/datastruct.py | {
"start": 5226,
"end": 7648
} | class ____:
invcnum = 0
def __init__(self):
from PyInstaller.config import CONF
# Get a (per class) unique number to avoid conflicts between toc objects
self.invcnum = self.__class__.invcnum
self.__class__.invcnum += 1
self.tocfilename = os.path.join(CONF['workpath'], '... | Target |
python | ansible__ansible | test/sanity/code-smell/required-and-default-attributes.py | {
"start": 75,
"end": 768
} | class ____(ast.NodeVisitor):
def __init__(self, path: str) -> None:
self.path = path
def visit_Call(self, node: ast.Call) -> None:
if isinstance(node.func, ast.Name) and node.func.id.endswith("FieldAttribute"):
if len([kw for kw in node.keywords if kw.arg in ("default", "required")]... | CallVisitor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/spec.py | {
"start": 3606,
"end": 7064
} | class ____(BaseModel):
"""Config for custom insights"""
class Config:
use_enum_values = True
name: str = Field(
title="Name",
description="The name value of insight",
)
level: str = Field(
title="Level",
description="Chosen level for API",
default="... | InsightConfig |
python | Textualize__textual | tests/test_markdownviewer.py | {
"start": 1431,
"end": 3272
} | class ____(App[None]):
def __init__(self, markdown_string: str) -> None:
self.markdown_string = markdown_string
super().__init__()
def compose(self) -> ComposeResult:
yield MarkdownViewer(self.markdown_string, open_links=False)
async def on_mount(self) -> None:
self.query_o... | MarkdownStringViewerApp |
python | doocs__leetcode | solution/1700-1799/1727.Largest Submatrix With Rearrangements/Solution.py | {
"start": 0,
"end": 431
} | class ____:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
for i in range(1, len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]:
matrix[i][j] = matrix[i - 1][j] + 1
ans = 0
for row in matrix:
row.sort(reverse... | Solution |
python | huggingface__transformers | src/transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py | {
"start": 2883,
"end": 3668
} | class ____(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.... | Ernie4_5_MoeMLP |
python | donnemartin__interactive-coding-challenges | linked_lists/remove_duplicates/test_remove_duplicates.py | {
"start": 18,
"end": 1185
} | class ____(unittest.TestCase):
def test_remove_dupes(self, linked_list):
print('Test: Empty list')
linked_list.remove_dupes()
self.assertEqual(linked_list.get_all_data(), [])
print('Test: One element list')
linked_list.insert_to_front(2)
linked_list.remove_dupes()
... | TestRemoveDupes |
python | pyca__cryptography | src/cryptography/utils.py | {
"start": 1994,
"end": 2189
} | class ____:
def __init__(self, value: object, message: str, warning_class):
self.value = value
self.message = message
self.warning_class = warning_class
| _DeprecatedValue |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/log_stream.py | {
"start": 6438,
"end": 25425
} | class ____(BaseTracer, _StreamingCallbackHandler):
"""Tracer that streams run logs to a stream."""
def __init__(
self,
*,
auto_close: bool = True,
include_names: Sequence[str] | None = None,
include_types: Sequence[str] | None = None,
include_tags: Sequence[str] ... | LogStreamCallbackHandler |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 1571,
"end": 1772
} | class ____(BaseConfig):
"""
Gemm configuration used for most backends (CPU, CUDA)
"""
group_m: int = 8
ConvConfig = BaseConfig
# FlexAttention Configs
@dataclasses.dataclass
| GemmConfig |
python | wandb__wandb | wandb/vendor/pygments/lexers/felix.py | {
"start": 454,
"end": 9408
} | class ____(RegexLexer):
"""
For `Felix <http://www.felix-lang.org>`_ source code.
.. versionadded:: 1.2
"""
name = 'Felix'
aliases = ['felix', 'flx']
filenames = ['*.flx', '*.flxh']
mimetypes = ['text/x-felix']
preproc = (
'elif', 'else', 'endif', 'if', 'ifdef', 'ifndef',
... | FelixLexer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 292692,
"end": 294800
} | class ____(sgqlc.types.Input):
"""Specifies the parameters for a `RepositoryRule` object. Only one
of the fields should be specified.
"""
__schema__ = github_schema
__field_names__ = (
"update",
"required_deployments",
"pull_request",
"required_status_checks",
... | RuleParametersInput |
python | huggingface__transformers | utils/test_module/custom_feature_extraction.py | {
"start": 52,
"end": 117
} | class ____(Wav2Vec2FeatureExtractor):
pass
| CustomFeatureExtractor |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/typehints.py | {
"start": 1342,
"end": 1436
} | class ____:
def __new__(cls, i):
# type: (int) -> NewComment
pass
| NewComment |
python | huggingface__transformers | src/transformers/models/apertus/modeling_apertus.py | {
"start": 18484,
"end": 21934
} | class ____(ApertusPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Apert... | ApertusForCausalLM |
python | kamyu104__LeetCode-Solutions | Python/find-the-maximum-number-of-marked-indices.py | {
"start": 453,
"end": 783
} | class ____(object):
def maxNumOfMarkedIndices(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
left = 0
for right in xrange(len(nums)):
if nums[right] >= 2*nums[left]:
left += 1
return min(left, len(nums)//... | Solution2 |
python | huggingface__transformers | src/transformers/models/wavlm/modular_wavlm.py | {
"start": 23017,
"end": 23251
} | class ____(Wav2Vec2ForXVector):
pass
__all__ = [
"WavLMForAudioFrameClassification",
"WavLMForCTC",
"WavLMForSequenceClassification",
"WavLMForXVector",
"WavLMModel",
"WavLMPreTrainedModel",
]
| WavLMForXVector |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_twodim_base.py | {
"start": 1682,
"end": 3794
} | class ____(TestCase):
def test_basic(self):
assert_equal(
eye(4), array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
)
assert_equal(
eye(4, dtype="f"),
array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], "f"),
)
a... | TestEye |
python | pytorch__pytorch | torch/ao/quantization/fx/utils.py | {
"start": 2197,
"end": 38784
} | class ____:
node_name_to_qconfig: dict[str, QConfigAny]
node_name_to_scope: dict[str, tuple[str, type]]
prepare_custom_config: PrepareCustomConfig
equalization_node_name_to_qconfig: dict[str, Any]
qconfig_mapping: QConfigMapping
is_qat: bool
observed_node_names: set[str]
is_observed_stan... | ObservedGraphModuleAttrs |
python | pallets__quart | src/quart/cli.py | {
"start": 6843,
"end": 9487
} | class ____:
def __init__(
self,
app_import_path: str | None = None,
create_app: Callable[..., Quart] | None = None,
set_debug_flag: bool = True,
) -> None:
self.app_import_path = app_import_path
self.create_app = create_app
self.data: dict[Any, Any] = {}
... | ScriptInfo |
python | xlwings__xlwings | tests/test_sheet.py | {
"start": 81,
"end": 1791
} | class ____(TestBase):
def test_active(self):
self.assertEqual(self.wb2.sheets.active.name, self.wb2.sheets[0].name)
def test_index(self):
self.assertEqual(self.wb1.sheets[0].name, self.wb1.sheets(1).name)
def test_len(self):
self.assertEqual(len(self.wb1.sheets), 3)
def del_sh... | TestSheets |
python | pypa__setuptools | setuptools/tests/test_config_discovery.py | {
"start": 15237,
"end": 22580
} | class ____:
def _simulate_package_with_data_files(self, tmp_path, src_root):
files = [
f"{src_root}/proj/__init__.py",
f"{src_root}/proj/file1.txt",
f"{src_root}/proj/nested/file2.txt",
]
_populate_project_dir(tmp_path, files, {})
manifest = """
... | TestWithPackageData |
python | davidhalter__parso | parso/python/tree.py | {
"start": 22997,
"end": 23756
} | class ____(Flow):
type = 'with_stmt'
__slots__ = ()
def get_defined_names(self, include_setitem=False):
"""
Returns the a list of `Name` that the with statement defines. The
defined names are set after `as`.
"""
names = []
for with_item in self.children[1:-2:... | WithStmt |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py | {
"start": 4034,
"end": 4083
} | class ____(TypedDict):
d1: NotRequired[int]
| TD2 |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_bool.py | {
"start": 157,
"end": 1064
} | class ____(BaseTestZDType):
test_cls = Bool
valid_dtype = (np.dtype(np.bool_),)
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.float64),
np.dtype(np.uint16),
)
valid_json_v2 = ({"name": "|b1", "object_codec_id": None},)
valid_json_v3 = ("bool",)
invalid_json_v2 = (... | TestBool |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/converter_test.py | {
"start": 1998,
"end": 4618
} | class ____(converter_testing.TestCase):
def test_get_definition_directive_basic(self):
directive_key = object
def f():
a = 1
return a
_, node, ctx = self.transform(f, (), include_ast=True)
symbol_a = node.body[1].value
defs, = anno.getanno(symbol_a, anno.Static.ORIG_DEFINITIONS)
... | ConverterBaseTest |
python | scrapy__scrapy | tests/test_downloader_handlers.py | {
"start": 4227,
"end": 4928
} | class ____:
def setup_method(self):
crawler = get_crawler()
self.s3reqh = build_from_crawler(
S3DownloadHandler,
crawler,
httpdownloadhandler=HttpDownloadHandlerMock,
# anon=True, # implicit
)
self.download_request = self.s3reqh.downloa... | TestS3Anon |
python | davidhalter__jedi | test/completion/usages.py | {
"start": 3631,
"end": 3965
} | class ____(object):
#< 4 (0,4), (23,18), (25,13)
base_class = 1
#< 4 (0,4),
class_var = 1
#< 8 (0,8),
def base_method(self):
#< 13 (0,13), (20,13)
self.base_var = 1
#< 13 (0,13),
self.instance_var = 1
#< 8 (0,8),
def just_a_method(self): pass
#< 20 (0,... | Super |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 5773,
"end": 5974
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI Endpoint link."""
name = "Endpoint"
key = "endpoint_conf"
format_str = VERTEX_AI_ENDPOINT_LINK
| VertexAIEndpointLink |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py | {
"start": 2780,
"end": 3973
} | class ____(nn.Module):
"""
ResidualConvUnit, pre-activate residual unit.
Args:
config (`[PromptDepthAnythingConfig]`):
Model configuration class defining the model architecture.
"""
def __init__(self, config):
super().__init__()
self.activation1 = nn.ReLU()
... | PromptDepthAnythingPreActResidualLayer |
python | ray-project__ray | python/ray/util/queue.py | {
"start": 196,
"end": 262
} | class ____(queue.Empty):
pass
@PublicAPI(stability="beta")
| Empty |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_accounts_stream.py | {
"start": 514,
"end": 9287
} | class ____(BaseTest):
stream_name = "accounts"
def read_stream(
self,
stream_name: str,
sync_mode: SyncMode,
config: Dict[str, Any],
stream_data_file: Optional[str] = None,
state: Optional[Dict[str, Any]] = None,
expecting_exception: bool = False,
) -... | TestAccountsStream |
python | hynek__structlog | tests/processors/test_renderers.py | {
"start": 8660,
"end": 10666
} | class ____:
def test_renders_json(self, event_dict):
"""
Renders a predictable JSON string.
"""
rv = JSONRenderer(sort_keys=True)(None, None, event_dict)
assert (
r'{"a": "<A(\\o/)>", "b": [3, 4], "x": 7, '
r'"y": "test", "z": '
r"[1, 2]}"... | TestJSONRenderer |
python | pyca__cryptography | tests/hazmat/primitives/test_kbkdf_vectors.py | {
"start": 292,
"end": 487
} | class ____:
test_kbkdfctr = generate_kbkdf_counter_mode_test(
load_nist_kbkdf_vectors,
os.path.join("KDF"),
["nist-800-108-KBKDF-CTR.txt"],
)
| TestCounterKDFCounterMode |
python | walkccc__LeetCode | solutions/2596. Check Knight Tour Configuration/2596.py | {
"start": 0,
"end": 821
} | class ____:
def checkValidGrid(self, grid: list[list[int]]) -> bool:
if grid[0][0] != 0:
return False
DIRS = ((1, 2), (2, 1), (2, -1), (1, -2),
(-1, -2), (-2, -1), (-2, 1), (-1, 2))
n = len(grid)
i = 0
j = 0
def nextGrid(i: int, j: int, target: int) -> tuple[int, int]:
... | Solution |
python | python-excel__xlrd | xlrd/sheet.py | {
"start": 1604,
"end": 95597
} | class ____(BaseObject):
"""
Contains the data for one worksheet.
In the cell access functions, ``rowx`` is a row index, counting from
zero, and ``colx`` is a column index, counting from zero.
Negative values for row/column indexes and slice positions are supported in
the expected fashion.
... | Sheet |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_settings.py | {
"start": 8997,
"end": 11362
} | class ____(TestCase):
"""Real nasty edge case here.
in #2160, if ``example`` is after ``given`` but before ``settings``,
it will be completely ignored.
If we set phases to only ``explicit``, the test case will never be called!
We have to run an assertion outside of the test case itself.
"""
... | TestGivenExampleSettingsExplicitCalled |
python | walkccc__LeetCode | solutions/2847. Smallest Number With Given Digit Product/2847.py | {
"start": 0,
"end": 284
} | class ____:
def smallestNumber(self, n: int) -> str:
if n <= 9:
return str(n)
ans = []
for divisor in range(9, 1, -1):
while n % divisor == 0:
ans.append(str(divisor))
n //= divisor
return '-1' if n > 1 else ''.join(reversed(ans))
| Solution |
python | google__pytype | pytype/overlays/named_tuple.py | {
"start": 20276,
"end": 28195
} | class ____(abstract.InterpreterClass):
"""Named tuple classes."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Store the original properties, to output to pyi files.
self.props = None
self.generated_members = None
def instantiate(self, node, container=None):
# For... | NamedTupleClass |
python | doocs__leetcode | solution/1200-1299/1220.Count Vowels Permutation/Solution.py | {
"start": 0,
"end": 400
} | class ____:
def countVowelPermutation(self, n: int) -> int:
f = [1] * 5
mod = 10**9 + 7
for _ in range(n - 1):
g = [0] * 5
g[0] = (f[1] + f[2] + f[4]) % mod
g[1] = (f[0] + f[2]) % mod
g[2] = (f[1] + f[3]) % mod
g[3] = f[2]
... | Solution |
python | walkccc__LeetCode | solutions/1857. Largest Color Value in a Directed Graph/1857.py | {
"start": 0,
"end": 853
} | class ____:
def largestPathValue(self, colors: str, edges: list[list[int]]) -> int:
n = len(colors)
ans = 0
processed = 0
graph = [[] for _ in range(n)]
inDegrees = [0] * n
q = collections.deque()
count = [[0] * 26 for _ in range(n)]
# Build the graph.
for u, v in edges:
gra... | Solution |
python | doocs__leetcode | solution/3100-3199/3149.Find the Minimum Cost Array Permutation/Solution.py | {
"start": 0,
"end": 889
} | class ____:
def findPermutation(self, nums: List[int]) -> List[int]:
@cache
def dfs(mask: int, pre: int) -> int:
if mask == (1 << n) - 1:
return abs(pre - nums[0])
res = inf
for cur in range(1, n):
if mask >> cur & 1 ^ 1:
... | Solution |
python | ansible__ansible | lib/ansible/module_utils/_internal/_datatag/__init__.py | {
"start": 23385,
"end": 29945
} | class ____(AnsibleSerializable):
__slots__ = _NO_INSTANCE_STORAGE
_native_type: t.ClassVar[type]
_item_source: t.ClassVar[t.Optional[t.Callable]] = None
_tagged_type_map: t.ClassVar[t.Dict[type, t.Type['AnsibleTaggedObject']]] = {}
_tagged_collection_types: t.ClassVar[t.Set[t.Type[c.Collection]]] ... | AnsibleTaggedObject |
python | pdm-project__pdm | src/pdm/models/caches.py | {
"start": 6535,
"end": 10138
} | class ____:
"""Caches wheels so we do not need to rebuild them.
Wheels are only cached when the URL contains egg-info or is a VCS repository
with an *immutable* revision. There might be more than one wheels built for
one sdist, the one with most preferred tag will be returned.
"""
def __init__... | WheelCache |
python | python-openxml__python-docx | src/docx/image/gif.py | {
"start": 97,
"end": 1118
} | class ____(BaseImageHeader):
"""Image header parser for GIF images.
Note that the GIF format does not support resolution (DPI) information. Both
horizontal and vertical DPI default to 72.
"""
@classmethod
def from_stream(cls, stream):
"""Return |Gif| instance having header properties p... | Gif |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py | {
"start": 1018,
"end": 1203
} | class ____:
bar = "should've used attrs"
def __post_init__(self, bar: str = "ahhh", baz: str = "hmm") -> None: ...
# https://github.com/astral-sh/ruff/issues/18950
@dataclass
| Foo |
python | doocs__leetcode | solution/1000-1099/1021.Remove Outermost Parentheses/Solution.py | {
"start": 0,
"end": 367
} | class ____:
def removeOuterParentheses(self, s: str) -> str:
ans = []
cnt = 0
for c in s:
if c == '(':
cnt += 1
if cnt > 1:
ans.append(c)
else:
cnt -= 1
if cnt > 0:
... | Solution |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 42571,
"end": 44722
} | class ____(fixtures.MappedTest):
"""test a scenario where joined table inheritance might be
confused as an eagerly loaded joined table."""
@classmethod
def define_tables(cls, metadata):
Table(
"a_table",
metadata,
Column("id", Integer, primary_key=True),
... | EagerTargetingTest |
python | Textualize__rich | rich/text.py | {
"start": 2976,
"end": 47534
} | class ____(JupyterMixin):
"""Text with color / style.
Args:
text (str, optional): Default unstyled text. Defaults to "".
style (Union[str, Style], optional): Base style for text. Defaults to "".
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None... | Text |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 5581,
"end": 5818
} | class ____:
# GH 13166
def setup(self):
N = 100_000
a = np.arange(N, dtype=np.float64)
self.ind = Index(a * 4.8000000418824129e-08)
def time_get_loc(self):
self.ind.get_loc(0)
| Float64IndexMethod |
python | encode__django-rest-framework | tests/test_views.py | {
"start": 2841,
"end": 3889
} | class ____(TestCase):
def setUp(self):
self.DEFAULT_HANDLER = api_settings.EXCEPTION_HANDLER
def exception_handler(exc, request):
return Response('Error!', status=status.HTTP_400_BAD_REQUEST)
api_settings.EXCEPTION_HANDLER = exception_handler
def tearDown(self):
ap... | TestCustomExceptionHandler |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 60303,
"end": 60784
} | class ____(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`YamlLexer`.
Commonly used in Saltstack salt states.
.. versionadded:: 2.0
"""
name = 'YAML+Jinja'
aliases = ['yaml+jinja', 'salt', 'sls']
filenames = ['*.sls']
mimetypes = ['t... | YamlJinjaLexer |
python | tornadoweb__tornado | tornado/web.py | {
"start": 100933,
"end": 101467
} | class ____(RequestHandler):
"""Generates an error response with ``status_code`` for all requests."""
def initialize(self, status_code: int) -> None:
self.set_status(status_code)
def prepare(self) -> None:
raise HTTPError(self._status_code)
def check_xsrf_cookie(self) -> None:
... | ErrorHandler |
python | huggingface__transformers | tests/models/clap/test_modeling_clap.py | {
"start": 10017,
"end": 14060
} | class ____:
def __init__(
self,
parent,
batch_size=12,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
... | ClapTextModelTester |
python | realpython__materials | build-a-django-content-aggregator/source_code_final/podcasts/models.py | {
"start": 31,
"end": 417
} | class ____(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
pub_date = models.DateTimeField()
link = models.URLField()
image = models.URLField()
podcast_name = models.CharField(max_length=100)
guid = models.CharField(max_length=50)
def __str__(sel... | Episode |
python | apache__airflow | providers/apache/pinot/tests/unit/apache/pinot/hooks/test_pinot.py | {
"start": 7164,
"end": 7452
} | class ____:
def test_exception_when_overriding_cmd_path(self):
with pytest.raises(RuntimeError):
PinotAdminHook(cmd_path="some_path.sh")
def test_exception_when_keeping_cmd_path(self):
PinotAdminHook(cmd_path="pinot-admin.sh")
| TestPinotAdminHookCreation |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/multimethod_base/package.py | {
"start": 188,
"end": 628
} | class ____(Package):
"""This is a base class for the Multimethod test case.
It tests whether mutlimethod properly invokes methods in a base
class when subclass multi-methods do not match.
"""
homepage = "http://www.example.com/"
url = "http://www.example.com/example-1.0.tar.gz"
def base_... | MultimethodBase |
python | streamlit__streamlit | lib/tests/streamlit/elements/media_test.py | {
"start": 1185,
"end": 1254
} | class ____(Enum):
AUDIO = "audio"
VIDEO = "video"
| MockMediaKind |
python | getsentry__sentry | src/sentry/db/models/base.py | {
"start": 1426,
"end": 13224
} | class ____(models.Model):
class Meta:
abstract = True
__relocation_scope__: RelocationScope | set[RelocationScope]
__relocation_dependencies__: set[str]
# Some models have a globally unique identifier, like a UUID. This should be a set of one or
# more fields, none of which are foreign key... | BaseModel |
python | pytorch__pytorch | test/package/package_a/fake_interface.py | {
"start": 520,
"end": 800
} | class ____(torch.nn.Module):
"""A *different* module that implements ModuleInterface."""
def one(self, inp1: Tensor, inp2: Tensor) -> Tensor:
return inp1 * inp2 + 1
def forward(self, input: Tensor) -> Tensor:
return self.one(input, input + 1)
| NewModule |
python | lepture__authlib | authlib/common/errors.py | {
"start": 50,
"end": 743
} | class ____(Exception):
"""Base Exception for all errors in Authlib."""
#: short-string error code
error = None
#: long-string to describe this error
description = ""
#: web page that describes this error
uri = None
def __init__(self, error=None, description=None, uri=None):
if ... | AuthlibBaseError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 184490,
"end": 185918
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"pull_request_id",
"base_ref_name",
"title",
"body",
"state",
"maintainer_can_modify",
"assignee_ids",
"milestone_id"... | UpdatePullRequestInput |
python | tensorflow__tensorflow | tensorflow/python/ops/data_flow_ops.py | {
"start": 25337,
"end": 29058
} | class ____(QueueBase):
"""A queue implementation that dequeues elements in a random order.
See `tf.queue.QueueBase` for a description of the methods on
this class.
"""
def __init__(self,
capacity,
min_after_dequeue,
dtypes,
shapes=None,
... | RandomShuffleQueue |
python | pytorch__pytorch | torch/ao/nn/intrinsic/quantized/modules/conv_add.py | {
"start": 241,
"end": 2325
} | class ____(nnq.Conv2d):
r"""
A ConvAdd2d module is a fused module of Conv2d and Add
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
Attributes:
Same as torch.ao.nn.quantized.Conv2d
"""
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAdd2d # type: ignore[assignment]
... | ConvAdd2d |
python | getsentry__sentry | src/sentry/discover/migrations/0002_link_migrated_explore_query_in_discover.py | {
"start": 222,
"end": 1760
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/gdrive_to_local.py | {
"start": 1109,
"end": 3700
} | class ____(BaseOperator):
"""
Writes a Google Drive file into local Storage.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleDriveToLocalOperator`
:param output_file: Path to downloaded file
:param folder_id: The f... | GoogleDriveToLocalOperator |
python | pypa__virtualenv | src/virtualenv/util/error.py | {
"start": 52,
"end": 323
} | class ____(RuntimeError):
"""Failed a process call."""
def __init__(self, code, out, err, cmd) -> None:
super().__init__(code, out, err, cmd)
self.code = code
self.out = out
self.err = err
self.cmd = cmd
| ProcessCallFailedError |
python | PrefectHQ__prefect | src/integrations/prefect-docker/tests/test_containers.py | {
"start": 1012,
"end": 1495
} | class ____:
async def test_logs_kwargs(self, mock_docker_host: MagicMock):
logs_kwargs = dict(container_id="42")
with disable_run_logger():
logs = await get_docker_container_logs.fn(
docker_host=mock_docker_host, **logs_kwargs
)
assert logs == "here ar... | TestGetDockerContainerLogs |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 3455,
"end": 3639
} | class ____(BaseModel):
x: int = Field(..., alias='y')
class Config: # type: ignore[pydantic-alias]
alias_generator = lambda x: x + '_' # noqa E731
| AliasGeneratorModel2 |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_L.py | {
"start": 8572,
"end": 9864
} | class ____(Benchmark):
r"""
Levy13 objective function.
This class defines the Levy13 [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Levy13}}(x) = \left(x_{1} -1\right)^{2} \left[\sin^{2}
\left(3 \pi x_{2}\right) ... | Levy13 |
python | celery__celery | t/unit/contrib/test_abortable.py | {
"start": 75,
"end": 1394
} | class ____:
def setup_method(self):
@self.app.task(base=AbortableTask, shared=False)
def abortable():
return True
self.abortable = abortable
def test_async_result_is_abortable(self):
result = self.abortable.apply_async()
tid = result.id
assert isinst... | test_AbortableTask |
python | numpy__numpy | numpy/polynomial/tests/test_laguerre.py | {
"start": 12532,
"end": 15042
} | class ____:
def test_lagfit(self):
def f(x):
return x * (x - 1) * (x - 2)
# Test exceptions
assert_raises(ValueError, lag.lagfit, [1], [1], -1)
assert_raises(TypeError, lag.lagfit, [[1]], [1], 0)
assert_raises(TypeError, lag.lagfit, [], [1], 0)
assert_ra... | TestFitting |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/convolutional.py | {
"start": 19421,
"end": 29027
} | class ____(keras_layers.Conv3D, base.Layer):
"""3D convolution layer (e.g. spatial convolution over volumes).
This layer creates a convolution kernel that is convolved
(actually cross-correlated) with the layer input to produce a tensor of
outputs. If `use_bias` is True (and a `bias_initializer` is provided),
... | Conv3D |
python | keras-team__keras | keras/src/trainers/data_adapters/torch_data_loader_adapter_test.py | {
"start": 329,
"end": 7436
} | class ____(testing.TestCase):
def test_basic_dataloader(self):
x = torch.normal(2, 3, size=(34, 4))
y = torch.normal(1, 3, size=(34, 2))
ds = torch.utils.data.TensorDataset(x, y)
dataloader = torch.utils.data.DataLoader(ds, batch_size=16)
adapter = TorchDataLoaderAdapter(data... | TestTorchDataLoaderAdapter |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py | {
"start": 29063,
"end": 29778
} | class ____(SiglipMultiheadAttentionPoolingHead):
def __init__(self, config: Phi4MultimodalVisionConfig):
super().__init__(config)
self.mlp = Phi4MultimodalVisionMLP(config)
def forward(self, hidden_state, attention_mask):
batch_size = hidden_state.shape[0]
probe = self.probe.rep... | Phi4MultimodalVisionMultiheadAttentionPoolingHead |
python | getsentry__sentry | src/sentry/monitors/endpoints/project_monitor_environment_details.py | {
"start": 798,
"end": 2496
} | class ____(
ProjectMonitorEnvironmentEndpoint, MonitorEnvironmentDetailsMixin
):
publish_status = {
"DELETE": ApiPublishStatus.EXPERIMENTAL,
"PUT": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.CRONS
@extend_schema(
operation_id="Update a Monitor Environment for a Projec... | ProjectMonitorEnvironmentDetailsEndpoint |
python | Textualize__textual | tests/css/test_parse.py | {
"start": 35584,
"end": 36290
} | class ____:
@pytest.mark.parametrize(
"valid_align", ["left", "start", "center", "right", "end", "justify"]
)
def test_text_align(self, valid_align):
css = f"#foo {{ text-align: {valid_align} }}"
stylesheet = Stylesheet()
stylesheet.add_source(css)
assert stylesheet.r... | TestParseTextAlign |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 12944,
"end": 14192
} | class ____(BaseGroupingComponent[ExceptionGroupingComponentChildren]):
id: str = "exception"
frame_counts: Counter[str]
def __init__(
self,
values: Sequence[ExceptionGroupingComponentChildren] | None = None,
hint: str | None = None,
contributes: bool | None = None,
f... | ExceptionGroupingComponent |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 7163,
"end": 7298
} | class ____(WorkQueueAction):
"""Resumes a Work Queue"""
type: Literal["resume-work-queue"] = "resume-work-queue"
| ResumeWorkQueue |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 3876,
"end": 4107
} | class ____(graphene.ObjectType):
root_uri = graphene.String()
files = graphene.List(graphene.NonNull(MlflowFileInfo))
next_page_token = graphene.String()
apiError = graphene.Field(ApiError)
| MlflowListArtifactsResponse |
python | hynek__structlog | tests/test_dev.py | {
"start": 21374,
"end": 22507
} | class ____:
def test_wrong_name(self):
"""
Do nothing if name is not exception.
"""
assert {} == dev.set_exc_info(None, "foo", {})
@pytest.mark.parametrize("ei", [False, None, ()])
def test_already_set(self, ei):
"""
Do nothing if exc_info is already set.
... | TestSetExcInfo |
python | python__mypy | mypyc/transform/copy_propagation.py | {
"start": 3062,
"end": 3435
} | class ____(IRTransform):
def __init__(self, builder: LowLevelIRBuilder, map: dict[Value, Value]) -> None:
super().__init__(builder)
self.op_map.update(map)
self.removed = set(map)
def visit_assign(self, op: Assign) -> Value | None:
if op.dest in self.removed:
return ... | CopyPropagationTransform |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 10042,
"end": 10553
} | class ____(AnsibleTemplateError):
"""
Raised when the result of a template operation was the Omit singleton. This exception purposely does
not derive from AnsibleError to avoid elision of the traceback, since uncaught errors of this type always
indicate a bug.
"""
_default_message = "A template... | AnsibleValueOmittedError |
python | readthedocs__readthedocs.org | readthedocs/proxito/tests/test_full.py | {
"start": 32011,
"end": 57871
} | class ____(BaseDocServing):
# Test that robots.txt and sitemap.xml work
def tearDown(self):
super().tearDown()
# Cleanup cache to avoid throttling on tests
cache.clear()
@mock.patch.object(BuildMediaFileSystemStorageTest, "exists")
def test_default_robots_txt(self, storage_exis... | TestAdditionalDocViews |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 904,
"end": 1026
} | class ____(ParentE, total=False):
# This should generate an error because "x" is Required in the parent.
x: int
| ChildE |
python | ray-project__ray | rllib/algorithms/dqn/dqn.py | {
"start": 24984,
"end": 37031
} | class ____(Algorithm):
@classmethod
@override(Algorithm)
def get_default_config(cls) -> DQNConfig:
return DQNConfig()
@classmethod
@override(Algorithm)
def get_default_policy_class(
cls, config: AlgorithmConfig
) -> Optional[Type[Policy]]:
if config["framework"] == "... | DQN |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.