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 | plotly__plotly.py | plotly/graph_objs/layout/newshape/_legendgrouptitle.py | {
"start": 235,
"end": 2999
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.newshape"
_path_str = "layout.newshape.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
th... | Legendgrouptitle |
python | huggingface__transformers | src/transformers/models/instructblipvideo/processing_instructblipvideo.py | {
"start": 1123,
"end": 7992
} | class ____(ProcessorMixin):
r"""
Constructs an InstructBLIPVideo processor which wraps a InstructBLIP image processor and a LLaMa/T5 tokenizer into a single
processor.
[`InstructBlipVideoProcessor`] offers all the functionalities of [`InstructBlipVideoVideoProcessor`] and [`AutoTokenizer`]. See the
... | InstructBlipVideoProcessor |
python | langchain-ai__langchain | libs/core/langchain_core/messages/ai.py | {
"start": 2757,
"end": 4437
} | class ____(TypedDict):
"""Usage metadata for a message, such as token counts.
This is a standard representation of token usage that is consistent across models.
Example:
```python
{
"input_tokens": 350,
"output_tokens": 240,
"total_tokens": 590,
... | UsageMetadata |
python | python-pillow__Pillow | src/PIL/WmfImagePlugin.py | {
"start": 1948,
"end": 5244
} | class ____(ImageFile.StubImageFile):
format = "WMF"
format_description = "Windows Metafile"
def _open(self) -> None:
# check placeable header
s = self.fp.read(44)
if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
# placeable windows metafile
# get units per inc... | WmfStubImageFile |
python | lxml__lxml | src/lxml/html/tests/test_html5parser.py | {
"start": 1175,
"end": 1739
} | class ____(unittest.TestCase):
def make_one(self, **kwargs):
from lxml.html.html5parser import XHTMLParser
return XHTMLParser(**kwargs)
@skipUnless(hasattr(html5lib, 'XHTMLParser'),
'xhtml5lib does not have XHTMLParser')
def test_integration(self):
# XXX: This test a... | Test_XHTMLParser |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 25057,
"end": 25181
} | class ____(Structure):
_fields_ = (("umbrella", lc_str),)
def describe(self):
return {}
| sub_framework_command |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/selector.py | {
"start": 8944,
"end": 9662
} | class ____:
location_name: str
repository_name: str
name: str
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
"name": self.name,
}
@staticmethod
def from_graphql_input... | InstigatorSelector |
python | paramiko__paramiko | tests/test_config.py | {
"start": 29690,
"end": 30951
} | class ____:
def test_matches_target_host_not_hostname(self):
result = load_config("match-orighost").lookup("target")
assert result["hostname"] == "bogus"
assert result["user"] == "tuon"
def test_matches_target_host_not_canonicalized_name(self, socket):
result = load_config("matc... | TestMatchOriginalHost |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 58556,
"end": 61189
} | class ____:
def test_cbrt(self):
cb = special.cbrt(27)
cbrl = 27**(1.0/3.0)
assert_allclose(cb, cbrl, atol=1.5e-7, rtol=0)
def test_cbrtmore(self):
cb1 = special.cbrt(27.9)
cbrl1 = 27.9**(1.0/3.0)
assert_allclose(cb1, cbrl1, atol=1.5e-8, rtol=0)
def test_cos... | TestTrigonometric |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py | {
"start": 115,
"end": 1869
} | class ____(ValidationRule):
def leave_Field(self, node, key, parent, path, ancestors):
field_def = self.context.get_field_def()
if not field_def:
return False
arg_asts = node.arguments or []
arg_ast_map = {arg.name.value: arg for arg in arg_asts}
for arg_name, ... | ProvidedNonNullArguments |
python | davidhalter__jedi | jedi/inference/value/iterable.py | {
"start": 889,
"end": 1538
} | class ____:
def py__next__(self, contextualized_node=None):
return self.py__iter__(contextualized_node)
def py__stop_iteration_returns(self):
return ValueSet([compiled.builtin_from_name(self.inference_state, 'None')])
# At the moment, safe values are simple values like "foo", 1 and not
... | IterableMixin |
python | mlflow__mlflow | mlflow/langchain/chat_agent_langgraph.py | {
"start": 2480,
"end": 11007
} | class ____(TypedDict):
"""
Helper class that enables building a LangGraph agent that produces ChatAgent-compatible
messages as state is updated. Other ChatAgent request fields (custom_inputs, context) and
response fields (custom_outputs) are also exposed within the state so they can be used and
upda... | ChatAgentState |
python | langchain-ai__langchain | libs/core/langchain_core/documents/base.py | {
"start": 992,
"end": 1897
} | class ____(Serializable):
"""Base class for content used in retrieval and data processing workflows.
Provides common fields for content that needs to be stored, indexed, or searched.
!!! note
For multimodal content in **chat messages** (images, audio sent to/from LLMs),
use `langchain.mess... | BaseMedia |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/evaluator.py | {
"start": 1340,
"end": 12353
} | class ____:
def __init__(self, target_cls=None):
self.target_cls = target_cls
def process(self, clause, *clauses):
if clauses:
clause = and_(clause, *clauses)
meth = getattr(self, f"visit_{clause.__visit_name__}", None)
if not meth:
raise UnevaluatableEr... | _EvaluatorCompiler |
python | coleifer__peewee | playhouse/postgres_ext.py | {
"start": 10984,
"end": 11042
} | class ____(Field):
field_type = 'INTERVAL'
| IntervalField |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 383642,
"end": 385766
} | class ____:
def test_alias(self):
# This test makes sure that "reciprocal" and "loguniform" are
# aliases of the same distribution and that both are log-uniform
rng = np.random.default_rng(98643218961)
rv = stats.loguniform(10 ** -3, 10 ** 0)
rvs = rv.rvs(size=10000, random_s... | TestLogUniform |
python | walkccc__LeetCode | solutions/767. Reorganize String/767-2.py | {
"start": 0,
"end": 576
} | class ____:
def reorganizeString(self, s: str) -> str:
n = len(s)
count = collections.Counter(s)
maxCount = max(count.values())
if maxCount > (n + 1) // 2:
return ''
if maxCount == (n + 1) // 2:
maxLetter = max(count, key=count.get)
ans = [maxLetter if i % 2 == 0 else '' for i ... | Solution |
python | getsentry__sentry | tests/sentry/feedback/endpoints/test_project_user_reports.py | {
"start": 518,
"end": 7986
} | class ____(APITestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1).isoformat()
self.environment = self.create_environment(project=self.project, name="production")
self.event = self.store_event(
data={
"eve... | ProjectUserReportListTest |
python | fastai__fastai | fastai/metrics.py | {
"start": 1430,
"end": 17345
} | class ____(Metric):
"Stores predictions and targets on CPU in accumulate to perform final calculations with `func`."
def __init__(self, func, dim_argmax=None, activation=ActivationType.No, thresh=None, to_np=False,
invert_arg=False, flatten=True, name=None, **kwargs):
store_attr('func,d... | AccumMetric |
python | ray-project__ray | release/llm_tests/serve/probes/query_utils.py | {
"start": 5398,
"end": 6631
} | class ____(BaseProbe):
def __init__(
self,
client: openai.AsyncClient,
default_configuration=None,
retryable_error_types: Sequence[Type[APIStatusError]] = None,
):
super().__init__(client, retryable_error_types)
self.default_configuration = default_configuration o... | TextGenerationProbeQuerier |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py | {
"start": 1395,
"end": 4806
} | class ____(BaseOperator):
"""
Deletes a report by its ID.
.. seealso::
Check official API docs:
`https://developers.google.com/doubleclick-advertisers/rest/v4/reports/delete`
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`... | GoogleCampaignManagerDeleteReportOperator |
python | pydantic__pydantic | pydantic/v1/mypy.py | {
"start": 2718,
"end": 8249
} | class ____(Plugin):
def __init__(self, options: Options) -> None:
self.plugin_config = PydanticPluginConfig(options)
self._plugin_data = self.plugin_config.to_data()
super().__init__(options)
def get_base_class_hook(self, fullname: str) -> 'Optional[Callable[[ClassDefContext], None]]':
... | PydanticPlugin |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 6900,
"end": 7866
} | class ____(object):
"""*
jina gRPC service for DataRequests.
This is used to send requests to Executors when a list of requests is not needed
"""
@staticmethod
def stream_doc(
request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
... | JinaSingleDocumentRequestRPC |
python | kamyu104__LeetCode-Solutions | Python/most-frequent-even-element.py | {
"start": 63,
"end": 340
} | class ____(object):
def mostFrequentEven(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = collections.Counter(x for x in nums if x%2 == 0)
return max(cnt.iterkeys(), key=lambda x: (cnt[x], -x)) if cnt else -1
| Solution |
python | django-mptt__django-mptt | tests/myapp/tests.py | {
"start": 3069,
"end": 4279
} | class ____(TreeTestCase):
def test_run_doctest(self):
import doctest
class DummyStream:
content = ""
encoding = "utf8"
def write(self, text):
self.content += text
def flush(self):
pass
dummy_stream = DummyStr... | DocTestTestCase |
python | falconry__falcon | tests/test_headers.py | {
"start": 568,
"end": 3364
} | class ____:
def __init__(self, last_modified=None):
if last_modified is not None:
self.last_modified = last_modified
else:
self.last_modified = _utcnow()
def _overwrite_headers(self, req, resp):
resp.content_type = 'x-falcon/peregrine'
resp.cache_control ... | HeaderHelpersResource |
python | PyCQA__pylint | tests/functional/b/bad_reversed_sequence.py | {
"start": 327,
"end": 497
} | class ____:
""" Implements __len__ and __getitem__ """
def __len__(self):
return 3
def __getitem__(self, index):
return index
| SecondGoodReversed |
python | sympy__sympy | sympy/core/numbers.py | {
"start": 102320,
"end": 106940
} | class ____(Number, metaclass=Singleton):
"""Negative infinite quantity.
NegativeInfinity is a singleton, and can be accessed
by ``S.NegativeInfinity``.
See Also
========
Infinity
"""
is_extended_real = True
is_complex = False
is_commutative = True
is_infinite = True
i... | NegativeInfinity |
python | openai__openai-python | tests/api_resources/vector_stores/test_files.py | {
"start": 588,
"end": 12655
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create(self, client: OpenAI) -> None:
file = client.vector_stores.files.create(
vector_store_id="vs_abc123",
file_id="file_id",
... | TestFiles |
python | plotly__plotly.py | plotly/graph_objs/table/hoverlabel/_font.py | {
"start": 233,
"end": 17133
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "table.hoverlabel"
_path_str = "table.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size"... | Font |
python | numpy__numpy | numpy/fft/tests/test_pocketfft.py | {
"start": 353,
"end": 462
} | class ____:
def test_fft_n(self):
assert_raises(ValueError, np.fft.fft, [1, 2, 3], 0)
| TestFFTShift |
python | openai__openai-python | src/openai/types/responses/response_function_shell_tool_call_output.py | {
"start": 815,
"end": 1071
} | class ____(BaseModel):
outcome: OutputOutcome
"""
Represents either an exit outcome (with an exit code) or a timeout outcome for a
shell call output chunk.
"""
stderr: str
stdout: str
created_by: Optional[str] = None
| Output |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/scenario_state.py | {
"start": 3424,
"end": 3608
} | class ____(NamedTuple):
specs: Sequence[dg.AssetSpec]
partitions_def: Optional[dg.PartitionsDefinition] = None
can_subset: bool = False
@dataclass(frozen=True)
| MultiAssetSpec |
python | gevent__gevent | src/greentest/3.13/test_ssl.py | {
"start": 92849,
"end": 106232
} | class ____(threading.Thread):
class ConnectionHandler(threading.Thread):
"""A mildly complicated class, because we want it to work both
with and without the SSL wrapper around the socket connection, so
that we can test the STARTTLS functionality."""
def __init__(self, server, conn... | ThreadedEchoServer |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/custom_job.py | {
"start": 91105,
"end": 95059
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a CustomTrainingJob, CustomPythonTrainingJob, or CustomContainerTrainingJob.
:param training_pipeline_id: Required. The name of the TrainingPipeline resource to be deleted.
:param custom_job_id: Required. The name of the CustomJob to delete.
:param p... | DeleteCustomTrainingJobOperator |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serialized_objects.py | {
"start": 18033,
"end": 23323
} | class ____(BaseTrigger):
def __init__(self, hi):
self.hi = hi
def serialize(self):
return "unit.serialization.test_serialized_objects.MyTrigger", {"hi": self.hi}
async def run(self):
yield
def test_roundtrip_exceptions():
"""
This is for AIP-44 when we need to send certai... | MyTrigger |
python | huggingface__transformers | src/transformers/models/lfm2_vl/modular_lfm2_vl.py | {
"start": 9030,
"end": 14162
} | class ____(LlavaForConditionalGeneration):
_checkpoint_conversion_mapping = {}
def get_image_features(
self,
pixel_values: torch.FloatTensor,
spatial_shapes: torch.Tensor,
pixel_attention_mask: torch.Tensor,
**kwargs,
):
return self.model.get_image_features(
... | Lfm2VlForConditionalGeneration |
python | ray-project__ray | python/ray/air/util/tensor_extensions/pandas.py | {
"start": 19103,
"end": 20751
} | class ____(_TensorOpsMixin, _TensorScalarCastMixin):
"""
Single element of a TensorArray, wrapping an underlying ndarray.
"""
def __init__(self, values: np.ndarray):
"""
Construct a TensorArrayElement from a NumPy ndarray.
Args:
values: ndarray that underlies this T... | TensorArrayElement |
python | pytorch__pytorch | test/dynamo/test_utils.py | {
"start": 388,
"end": 6712
} | class ____(TestCase):
def test_nan(self):
a = torch.Tensor([float("nan")])
b = torch.Tensor([float("nan")])
fp64_ref = torch.DoubleTensor([5.0])
res = utils.same(a, b, fp64_ref=fp64_ref, equal_nan=True)
self.assertTrue(res)
def test_larger_multiplier_for_smaller_tensor(s... | TestUtils |
python | tox-dev__tox | src/tox/tox_env/python/runner.py | {
"start": 764,
"end": 5753
} | class ____(Python, RunToxEnv, ABC):
def __init__(self, create_args: ToxEnvCreateArgs) -> None:
super().__init__(create_args)
def register_config(self) -> None:
super().register_config()
root = self.core["toxinidir"]
self.conf.add_config(
keys=["deps"],
of... | PythonRun |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/LegendItem.py | {
"start": 13287,
"end": 15390
} | class ____(GraphicsWidget):
"""Class responsible for drawing a single item in a LegendItem (sans label)
"""
sigClicked = QtCore.Signal(object)
def __init__(self, item):
GraphicsWidget.__init__(self)
self.item = item
self.setFixedWidth(20)
self.setFixedHeight(20)
de... | ItemSample |
python | bokeh__bokeh | tests/unit/bokeh/document/_util_document.py | {
"start": 1399,
"end": 1467
} | class ____(Model):
name = String(default="")
| ModelThatOverridesName |
python | dask__dask | dask/dataframe/dask_expr/_repartition.py | {
"start": 7518,
"end": 8628
} | class ____(Repartition):
"""Increase the partition count"""
_parameters = ["frame", "new_partitions"]
def _divisions(self):
return (None,) * (1 + sum(self._nsplits))
@functools.cached_property
def _nsplits(self):
df = self.frame
div, mod = divmod(self.new_partitions, df.np... | RepartitionToMore |
python | Textualize__textual | tests/option_list/test_option_removal.py | {
"start": 288,
"end": 4429
} | class ____(App[None]):
"""Test option list application."""
def compose(self) -> ComposeResult:
yield OptionList(
Option("0", id="0"),
Option("1", id="1"),
)
async def test_remove_first_option_via_index() -> None:
"""It should be possible to remove the first option ... | OptionListApp |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 60572,
"end": 71122
} | class ____(MultiProcessTestCase):
def setUp(self):
super().setUp()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
pass
def test_get_backend_name(self):
dpg = DummyProcessG... | PythonProcessGroupExtensionTest |
python | Textualize__textual | tests/animations/test_progress_bar_animation.py | {
"start": 282,
"end": 1611
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield ProgressBar()
async def test_progress_bar_animates_on_full() -> None:
"""An indeterminate progress bar is not fully highlighted when animating."""
app = ProgressBarApp()
app.animation_level = "full"
async with app.run_test()... | ProgressBarApp |
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/common.py | {
"start": 572,
"end": 1535
} | class ____:
def __init__(self, tokens_per_request: int):
self._tokens_per_request = tokens_per_request
# Switch off logging to minimize its impact
logging.getLogger("ray").setLevel(logging.WARNING)
logging.getLogger("ray.serve").setLevel(logging.WARNING)
def stream(self):
... | Endpoint |
python | pandas-dev__pandas | pandas/core/indexers/objects.py | {
"start": 14107,
"end": 17065
} | class ____(BaseIndexer):
"""
Creates window boundaries for fixed-length windows that include the current row.
Parameters
----------
index_array : np.ndarray, default None
Array-like structure representing the indices for the data points.
If None, the default indices are assumed. Thi... | FixedForwardWindowIndexer |
python | sympy__sympy | sympy/geometry/point.py | {
"start": 29721,
"end": 36661
} | class ____(Point):
"""A point in a 3-dimensional Euclidean space.
Parameters
==========
coords
A sequence of 3 coordinate values.
Attributes
==========
x
y
z
length
Raises
======
TypeError
When trying to add or subtract points with different dime... | Point3D |
python | euske__pdfminer | pdfminer/pdfparser.py | {
"start": 399,
"end": 463
} | class ____(PDFException):
pass
## PDFParser
##
| PDFSyntaxError |
python | pytorch__pytorch | benchmarks/transformer/sdp.py | {
"start": 415,
"end": 1462
} | class ____:
batch_size: int
num_heads: int
max_sequence_len: int
embed_dimension: int
dtype: torch.dtype
pad_percentage: Optional[float]
enable_math: bool
enable_flash: bool
enable_mem_efficient: bool
enable_cudnn: bool
def get_entries(self) -> list:
return [
... | ExperimentConfig |
python | huggingface__transformers | tests/models/clap/test_modeling_clap.py | {
"start": 16248,
"end": 18362
} | class ____:
def __init__(self, parent, text_kwargs=None, audio_kwargs=None, is_training=True):
if text_kwargs is None:
text_kwargs = {}
if audio_kwargs is None:
audio_kwargs = {}
self.parent = parent
self.text_model_tester = ClapTextModelTester(parent, **text... | ClapModelTester |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 16018,
"end": 17098
} | class ____(AnyUrl):
allowed_schemes = {'kafka'}
@staticmethod
def get_default_parts(parts: 'Parts') -> 'Parts':
return {
'domain': 'localhost',
'port': '9092',
}
def stricturl(
*,
strip_whitespace: bool = True,
min_length: int = 1,
max_length: int =... | KafkaDsn |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType42.py | {
"start": 638,
"end": 1395
} | class ____(Protocol[T, P]):
def __init__(self, *args: P.args, **kwds: P.kwargs): ...
def make_a(x: Callable[P, R]) -> Type[A[R, P]]: ...
@overload
def func2(x: Type[A[R, P]]) -> Type[A[R, P]]: ...
@overload
def func2(x: Callable[P, R]) -> Type[A[R, P]]: ...
def func2(x: Union[Type[A[R, P]], Callable[P, R]])... | A |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_mixed_py39.py | {
"start": 737,
"end": 873
} | class ____(typing.List[typing.Iterable[int]]):
pass
# Missing implementation for 'collections.abc' derived classes
| DerivedListIterable |
python | doocs__leetcode | solution/3700-3799/3738.Longest Non-Decreasing Subarray After Replacing at Most One Element/Solution.py | {
"start": 0,
"end": 717
} | class ____:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
left = [1] * n
right = [1] * n
for i in range(1, n):
if nums[i] >= nums[i - 1]:
left[i] = left[i - 1] + 1
for i in range(n - 2, -1, -1):
if nums[i] <= nums[i +... | Solution |
python | astropy__astropy | astropy/samp/errors.py | {
"start": 475,
"end": 555
} | class ____(Exception):
"""
SAMP Client exceptions.
"""
| SAMPClientError |
python | jschneier__django-storages | tests/test_s3.py | {
"start": 748,
"end": 869
} | class ____(s3.S3ManifestStaticStorage):
def read_manifest(self):
return None
| S3ManifestStaticStorageTestStorage |
python | langchain-ai__langchain | libs/core/langchain_core/chat_history.py | {
"start": 468,
"end": 7159
} | class ____(ABC):
"""Abstract base class for storing chat message history.
Implementations guidelines:
Implementations are expected to over-ride all or some of the following methods:
* add_messages: sync variant for bulk addition of messages
* aadd_messages: async variant for bulk addition of mess... | BaseChatMessageHistory |
python | ray-project__ray | python/ray/experimental/channel/shared_memory_channel.py | {
"start": 3059,
"end": 5180
} | class ____(ChannelOutputType):
def __init__(
self,
*,
buffer_size_bytes: Optional[int] = None,
num_shm_buffers: Optional[int] = None,
):
"""
Args:
buffer_size_bytes: The initial buffer size in bytes for messages
that can be passed betwe... | SharedMemoryType |
python | ray-project__ray | python/ray/dag/tests/test_py_obj_scanner.py | {
"start": 102,
"end": 2390
} | class ____:
pass
def test_simple_replace():
scanner = _PyObjScanner(source_type=Source)
my_objs = [Source(), [Source(), {"key": Source()}]]
found = scanner.find_nodes(my_objs)
assert len(found) == 3
replaced = scanner.replace_nodes({obj: 1 for obj in found})
assert replaced == [1, [1, {"... | Source |
python | numpy__numpy | numpy/lib/tests/test_packbits.py | {
"start": 13573,
"end": 17543
} | class ____:
x = np.array([
[1, 0, 1, 0, 0, 1, 0],
[0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 1],
[1, 1, 0, 0, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0],
], dtype=np.uint8)
padded1 = np.zeros(57, dtype=np.uint8)
pa... | TestCount |
python | arrow-py__arrow | arrow/locales.py | {
"start": 60670,
"end": 61241
} | class ____(ArabicLocale):
names = ["ar-tn", "ar-dz"]
month_names = [
"",
"جانفي",
"فيفري",
"مارس",
"أفريل",
"ماي",
"جوان",
"جويلية",
"أوت",
"سبتمبر",
"أكتوبر",
"نوفمبر",
"ديسمبر",
]
month_abbreviation... | AlgeriaTunisiaArabicLocale |
python | psf__requests | tests/test_utils.py | {
"start": 8688,
"end": 8910
} | class ____:
def test_valid(self):
assert address_in_network("192.168.1.1", "192.168.1.0/24")
def test_invalid(self):
assert not address_in_network("172.16.0.1", "192.168.1.0/24")
| TestAddressInNetwork |
python | getsentry__sentry | tests/apidocs/endpoints/events/test_group_tagkey_values.py | {
"start": 104,
"end": 598
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
key, value = "foo", "bar"
event = self.create_event("a", tags={key: value})
self.login_as(user=self.user)
self.url = f"/api/0/organizations/{self.organization.slug}/issues/{event.group_id}/tags/{key}/values/"
def test_get(s... | GroupTagKeyValuesDocs |
python | getsentry__sentry | src/sentry/search/eap/types.py | {
"start": 2112,
"end": 2309
} | class ____(str, Enum):
LOGS = "logs"
SPANS = "spans"
UPTIME_RESULTS = "uptime_results"
TRACEMETRICS = "tracemetrics"
PROFILE_FUNCTIONS = "profile_functions"
| SupportedTraceItemType |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modeling_instructblipvideo.py | {
"start": 5826,
"end": 7804
} | class ____(PreTrainedModel):
config: InstructBlipVideoConfig
base_model_prefix = "blip"
input_modalities = ("video", "text")
supports_gradient_checkpointing = True
_supports_attention_backend = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_co... | InstructBlipVideoPreTrainedModel |
python | getsentry__sentry | tests/sentry/preprod/api/endpoints/pull_request/test_organization_pullrequest_comments.py | {
"start": 424,
"end": 17690
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.factory = APIRequestFactory()
self.integration = self.create_integration(
organization=self.organization,
provider="github",
name="Test GitHub Integration",
external_id="12345",
... | OrganizationPrCommentsEndpointTest |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/dag_runs.py | {
"start": 991,
"end": 1457
} | class ____(BaseModel):
"""DAG Run serializer for responses."""
id: int
dag_id: str
run_id: str
logical_date: datetime | None
run_after: datetime
start_date: datetime | None
end_date: datetime | None
state: DagRunState
@computed_field
def duration(self) -> float | None:
... | DAGRunLightResponse |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/version.py | {
"start": 691,
"end": 2076
} | class ____(object):
def __init__(self, s):
self._string = s = s.strip()
self._parts = parts = self.parse(s)
assert isinstance(parts, tuple)
assert len(parts) > 0
def parse(self, s):
raise NotImplementedError('please implement in a subclass')
def _check_compatible(se... | Version |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_model_parallel_integration.py | {
"start": 2954,
"end": 3479
} | class ____(LightningModule):
def __init__(self, compile=False):
super().__init__()
self.model = FeedForward()
self._compile = compile
def training_step(self, batch):
output = self.model(batch)
return output.sum()
def train_dataloader(self):
dataset_size = 8
... | TemplateModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/endpoint_service.py | {
"start": 5193,
"end": 8078
} | class ____(GoogleCloudBaseOperator):
"""
Deletes an Endpoint.
: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 endpoint_id: Required. The Endpoint ID to delete.... | DeleteEndpointOperator |
python | django__django | django/core/management/commands/compilemessages.py | {
"start": 601,
"end": 7006
} | class ____(BaseCommand):
help = "Compiles .po files to .mo files for use with builtin gettext support."
requires_system_checks = []
program = "msgfmt"
program_options = ["--check-format"]
def add_arguments(self, parser):
parser.add_argument(
"--locale",
"-l",
... | Command |
python | getsentry__sentry | src/sentry/integrations/vercel/integration.py | {
"start": 15338,
"end": 18518
} | class ____(IntegrationProvider):
key = "vercel"
name = "Vercel"
can_add = False
can_disable = False
metadata = metadata
integration_cls = VercelIntegration
features = frozenset([IntegrationFeatures.DEPLOYMENT])
oauth_redirect_url = "/extensions/vercel/configure/"
# feature flag handl... | VercelIntegrationProvider |
python | sympy__sympy | sympy/physics/mechanics/linearize.py | {
"start": 342,
"end": 17242
} | class ____:
"""This object holds the general model form for a dynamic system. This
model is used for computing the linearized form of the system, while
properly dealing with constraints leading to dependent coordinates and
speeds. The notation and method is described in [1]_.
Attributes
======... | Linearizer |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 66100,
"end": 68295
} | class ____(ASTTrailingTypeSpec):
def __init__(
self, prefix: str, nestedName: ASTNestedName, placeholderType: str | None
) -> None:
self.prefix = prefix
self.nestedName = nestedName
self.placeholderType = placeholderType
def __eq__(self, other: object) -> bool:
if no... | ASTTrailingTypeSpecName |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 231536,
"end": 233371
} | class ____(fixtures.TestBase):
"""test pg-specific types for insertmanyvalues"""
__only_on__ = "postgresql"
__backend__ = True
@testing.combinations(
("BYTEA", BYTEA(), b"7\xe7\x9f"),
("BIT", BIT(3), BitString("011")),
argnames="type_,value",
id_="iaa",
)
@testi... | PGInsertManyValuesTest |
python | pypa__warehouse | tests/unit/oidc/models/test_google.py | {
"start": 8014,
"end": 9615
} | class ____:
@pytest.mark.parametrize("sub", ["fakesubject", None])
def test_reify_does_not_exist_yet(self, db_request, sub):
pending_publisher = PendingGooglePublisherFactory.create(sub=sub)
assert (
db_request.db.query(google.GooglePublisher)
.filter_by(
... | TestPendingGooglePublisher |
python | PyCQA__pylint | tests/checkers/unittest_typecheck.py | {
"start": 683,
"end": 1431
} | class ____(CheckerTestCase):
"""Tests for pylint.checkers.typecheck."""
CHECKER_CLASS = typecheck.TypeChecker
@needs_c_extension
def test_nomember_on_c_extension_info_msg(self) -> None:
node = astroid.extract_node(
"""
from coverage import tracer
tracer.CTracer #@
... | TestTypeChecker |
python | huggingface__transformers | src/transformers/models/markuplm/modeling_markuplm.py | {
"start": 9535,
"end": 10214
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forwa... | MarkupLMOutput |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 63433,
"end": 63979
} | class ____(torch.nn.Module):
def __init__(self, qengine):
super().__init__()
self.qconfig = torch.ao.quantization.get_default_qconfig(qengine)
self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float)
self.quant = QuantStub()
self.dequant = DeQuantStub()
def... | AnnotatedConvModel |
python | pytorch__pytorch | test/test_fx_passes.py | {
"start": 15627,
"end": 16221
} | class ____:
@staticmethod
def forward(x):
a = torch.neg(x)
a = a.relu()
left = a.sigmoid()
right = a.relu()
out = left + right
return out
@staticmethod
def pattern(a):
a = a.relu()
left = a.sigmoid()
right = a.relu()
out ... | DiamondShapePatternTestCase |
python | google__pytype | pytype/tests/test_protocols2.py | {
"start": 21570,
"end": 24730
} | class ____(test_base.BaseTest):
"""Tests for protocol implementation on a target using a Python 3 feature."""
def test_check_iterator(self):
self.Check("""
from typing import Iterator
def f(x: Iterator):
return None
class Foo:
def __next__(self):
return None
... | ProtocolsTestPython3Feature |
python | allegroai__clearml | examples/frameworks/jsonargparse/pytorch_lightning_cli_old.py | {
"start": 1972,
"end": 3930
} | class ____(LightningModule):
def __init__(self, model=None, lr=1.0, gamma=0.7, batch_size=32):
super().__init__()
self.save_hyperparameters(ignore="model")
self.model = model or Net()
try:
self.test_acc = Accuracy()
except TypeError:
self.test_acc = Ac... | ImageClassifier |
python | huggingface__transformers | src/transformers/models/gpt_oss/modular_gpt_oss.py | {
"start": 8088,
"end": 10911
} | class ____(Qwen2RotaryEmbedding):
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids... | GptOssRotaryEmbedding |
python | tornadoweb__tornado | tornado/test/locks_test.py | {
"start": 758,
"end": 6333
} | class ____(AsyncTestCase):
def setUp(self):
super().setUp()
self.history = [] # type: typing.List[typing.Union[int, str]]
def record_done(self, future, key):
"""Record the resolution of a Future returned by Condition.wait."""
def callback(_):
if not future.result()... | ConditionTest |
python | google__pytype | pytype/tests/test_basic1.py | {
"start": 57,
"end": 10826
} | class ____(test_base.BaseTest):
"""Basic tests."""
def test_constant(self):
self.Check("17")
def test_for_loop(self):
self.Check("""
out = ""
for i in range(5):
out = out + str(i)
print(out)
""")
def test_inplace_operators(self):
self.assertNoCrash(
self.Ch... | TestBasic |
python | jazzband__django-polymorphic | src/polymorphic/contrib/extra_views.py | {
"start": 585,
"end": 1946
} | class ____:
"""
Internal Mixin, that provides polymorphic integration with the ``extra_views`` package.
"""
formset_class = BasePolymorphicModelFormSet
#: Default 0 extra forms
factory_kwargs = {"extra": 0}
#: Define the children
# :type: list[PolymorphicFormSetChild]
formset_chil... | PolymorphicFormSetMixin |
python | django__django | tests/template_tests/syntax_tests/test_for.py | {
"start": 164,
"end": 13096
} | class ____(SimpleTestCase):
libraries = {"custom": "template_tests.templatetags.custom"}
@setup({"for-tag01": "{% for val in values %}{{ val }}{% endfor %}"})
def test_for_tag01(self):
output = self.engine.render_to_string("for-tag01", {"values": [1, 2, 3]})
self.assertEqual(output, "123")
... | ForTagTests |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/git_sparse_b/package.py | {
"start": 217,
"end": 550
} | class ____(Package):
"""Partal clone of the mock_git_repository fixture"""
# git='to-be-filled-in-by-test'
# ----------------------------
# -- mock_git_repository
version("main", branch="many_dirs")
homepage = "http://www.git-fetch-example.com"
submodules = False
git_sparse_paths = ["... | GitSparseB |
python | google__jax | tests/third_party/scipy/line_search_test.py | {
"start": 245,
"end": 4869
} | class ____(jtu.JaxTestCase):
# -- scalar functions; must have dphi(0.) < 0
def assert_wolfe(self, s, phi, derphi, c1=1e-4, c2=0.9, err_msg=""):
"""
Check that strong Wolfe conditions apply
"""
phi1 = phi(s)
phi0 = phi(0)
derphi0 = derphi(0)
derphi1 = derphi(s)
msg = "s = {}; phi(0) ... | TestLineSearch |
python | PyCQA__pylint | tests/functional/k/keyword_arg_before_vararg.py | {
"start": 301,
"end": 955
} | class ____:
"""class AAAA"""
def func_in_class(self, param1, param2=2, *args): # [keyword-arg-before-vararg]
"method in class AAAA"
pass
@staticmethod
def static_method_in_class(param1, param2=3, *args): # [keyword-arg-before-vararg]
"static method in class AAAA"
pass
... | AAAA |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 17440,
"end": 17538
} | class ____(OpcodeWithArg):
_FLAGS = HAS_ARGUMENT | HAS_JABS
__slots__ = ()
| JUMP_IF_NOT_EXC_MATCH |
python | FactoryBoy__factory_boy | tests/test_docs_internals.py | {
"start": 1214,
"end": 1836
} | class ____:
def __init__(
self,
username,
full_name,
is_active=True,
is_superuser=False,
is_staff=False,
creation_date=None,
deactivation_date=None,
):
self.username = username
self.full_name = full_name
self.is_active = is_... | User |
python | ray-project__ray | doc/source/serve/doc_code/key_concepts.py | {
"start": 737,
"end": 826
} | class ____:
def __call__(self) -> str:
return " world!"
@serve.deployment
| World |
python | pyinstaller__pyinstaller | tests/unit/test_hookutils.py | {
"start": 2642,
"end": 4319
} | class ____(object):
# Removing a suffix from a filename with no extension returns the filename.
def test_no_extension(self):
assert 'file' == hookutils.remove_file_extension('file')
# A filename with two extensions should have only the first removed.
def test_two_extensions(self):
asser... | TestRemoveExtension |
python | huggingface__transformers | src/transformers/models/ovis2/modular_ovis2.py | {
"start": 2037,
"end": 2777
} | class ____(SiglipVisionEmbeddings):
def __init__(self, config: Ovis2VisionConfig):
super().__init__(config)
self.rms_norm = Ovis2RMSNorm(config.hidden_size, config.rms_norm_eps)
def interpolate_pos_encoding(self):
raise NotImplementedError("Not needed for Ovis2")
def forward(self, ... | Ovis2VisionEmbeddings |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 893,
"end": 1174
} | class ____:
"""Contextual metadata attached to opcodes."""
# Function signature annotations in textual form
signature_annotations: dict[str, str] | None = None
# Code run out of line-number order, due to compiler optimisations.
is_out_of_order: bool = False
| OpcodeMetadata |
python | pytorch__pytorch | torch/_dynamo/profiler.py | {
"start": 791,
"end": 2098
} | class ____:
microseconds: float = 0.0
operators: int = 0
fusions: int = 0
graphs: int = 0
def __iadd__(self, other: Self) -> Self:
self.microseconds += other.microseconds
self.operators += other.operators
self.fusions += other.fusions
return self
def __add__(sel... | ProfileMetrics |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py | {
"start": 1522,
"end": 1675
} | class ____[T]:
class D[U](Generic[T, U]): ...
# In a single run, only the first is reported.
# Others will be reported/fixed in following iterations.
| C |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.