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 | vyperlang__vyper | vyper/semantics/environment.py | {
"start": 272,
"end": 414
} | class ____(VyperType):
def __eq__(self, other):
return self is other
def __hash__(self):
return hash(id(self))
| _EnvType |
python | cython__cython | Cython/Debugger/Tests/test_libcython_in_gdb.py | {
"start": 10101,
"end": 10826
} | class ____(DebugTestCase):
def test_backtrace(self):
libcython.parameters.colorize_code.value = False
self.break_and_run('os.path.join("foo", "bar")')
def match_backtrace_output(result):
assert re.search(r'\#\d+ *0x.* in spam\(\) at .*codefile\.pyx:22',
... | TestBacktrace |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_getitem.py | {
"start": 6872,
"end": 11531
} | class ____:
def test_getitem_partial_str_slice_with_datetimeindex(self):
# GH#34860
arr = date_range("1/1/2008", "1/1/2009")
ser = arr.to_series()
result = ser["2008"]
rng = date_range(start="2008-01-01", end="2008-12-31")
expected = Series(rng, index=rng)
t... | TestSeriesGetitemSlices |
python | numpy__numpy | numpy/f2py/symbolic.py | {
"start": 2608,
"end": 2793
} | class ____(Enum):
"""
Used in Op.APPLY expression to specify the function part.
"""
POS = 1
NEG = 2
ADD = 3
SUB = 4
MUL = 5
DIV = 6
POW = 7
| ArithOp |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC202_google.py | {
"start": 854,
"end": 1233
} | class ____(metaclass=abc.abcmeta):
@abc.abstractmethod
def f(self):
"""Lorem ipsum
Returns:
dict: The values
"""
return
# DOC202 -- never explicitly returns anything, just short-circuits
def foo(s: str, condition: bool):
"""Fooey things.
Returns:
N... | A |
python | huggingface__transformers | src/transformers/models/convnextv2/configuration_convnextv2.py | {
"start": 912,
"end": 5564
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ConvNextV2Model`]. It is used to instantiate an
ConvNeXTV2 model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the default... | ConvNextV2Config |
python | getsentry__sentry | src/sentry/plugins/base/view.py | {
"start": 166,
"end": 1026
} | class ____:
"""
A mix-in which provides a render method which returns a special object to
enable embedding of content within base-views.
"""
def redirect(self, url: str) -> HttpResponseRedirect:
"""
Returns a redirect response type.
"""
return HttpResponseRedirect(ur... | PluggableViewMixin |
python | walkccc__LeetCode | solutions/1750. Minimum Length of String After Deleting Similar Ends/1750.py | {
"start": 0,
"end": 257
} | class ____:
def minimumLength(self, s: str) -> int:
i = 0
j = len(s) - 1
while i < j and s[i] == s[j]:
c = s[i]
while i <= j and s[i] == c:
i += 1
while i <= j and s[j] == c:
j -= 1
return j - i + 1
| Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 122443,
"end": 123919
} | class ____:
@mock.patch(DATAPROC_PATH.format("DataprocHook"))
def test_execute(self, mock_hook):
op = DataprocCreateWorkflowTemplateOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
region=GCP_REGION,
... | TestDataprocCreateWorkflowTemplateOperator |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 25148,
"end": 36275
} | class ____(Request):
"""
Create a new model not associated with a task
:param uri: URI for the model
:type uri: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined tags list
:type tags:... | CreateRequest |
python | pennersr__django-allauth | allauth/socialaccount/providers/soundcloud/provider.py | {
"start": 227,
"end": 450
} | class ____(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("permalink_url")
def get_avatar_url(self):
return self.account.extra_data.get("avatar_url")
| SoundCloudAccount |
python | doocs__leetcode | solution/0300-0399/0352.Data Stream as Disjoint Intervals/Solution.py | {
"start": 0,
"end": 1085
} | class ____:
def __init__(self):
self.mp = SortedDict()
def addNum(self, val: int) -> None:
n = len(self.mp)
ridx = self.mp.bisect_right(val)
lidx = n if ridx == 0 else ridx - 1
keys = self.mp.keys()
values = self.mp.values()
if (
lidx != n
... | SummaryRanges |
python | PrefectHQ__prefect | tests/cli/deployment/test_deployment_cli.py | {
"start": 42249,
"end": 44214
} | class ____:
def test_delete_single_deployment(self, flojo_deployment: DeploymentResponse):
invoke_and_assert(
[
"deployment",
"delete",
f"rence-griffith/{flojo_deployment.name}",
],
expected_code=0,
)
@pytest.fi... | TestDeploymentDelete |
python | Textualize__textual | src/textual/_animator.py | {
"start": 1017,
"end": 1416
} | class ____(Protocol):
"""Protocol for objects that can have their intrinsic values animated.
For example, the transition between two colors can be animated
because the class [`Color`][textual.color.Color.blend] satisfies this protocol.
"""
def blend(
self: ReturnType, destination: ReturnTy... | Animatable |
python | spyder-ide__spyder | spyder/plugins/workingdirectory/container.py | {
"start": 1290,
"end": 1454
} | class ____:
PathComboBox = 'path_combo'
# ---- Widgets
# ----------------------------------------------------------------------------
| WorkingDirectoryToolbarItems |
python | django__django | tests/swappable_models/models.py | {
"start": 207,
"end": 378
} | class ____(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
byline = models.CharField(max_length=100)
| AlternateArticle |
python | doocs__leetcode | solution/0400-0499/0427.Construct Quad Tree/Solution.py | {
"start": 329,
"end": 1213
} | class ____:
def construct(self, grid: List[List[int]]) -> 'Node':
def dfs(a, b, c, d):
zero = one = 0
for i in range(a, c + 1):
for j in range(b, d + 1):
if grid[i][j] == 0:
zero = 1
else:
... | Solution |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 77186,
"end": 79553
} | class ____(Fittable1DModel):
"""
One dimensional Box model.
Parameters
----------
amplitude : float
Amplitude A
x_0 : float
Position of the center of the box function
width : float
Width of the box
See Also
--------
Box2D, TrapezoidDisk2D
Notes
... | Box1D |
python | kamyu104__LeetCode-Solutions | Python/non-negative-integers-without-consecutive-ones.py | {
"start": 29,
"end": 614
} | class ____(object):
def findIntegers(self, num):
"""
:type num: int
:rtype: int
"""
dp = [0] * 32
dp[0], dp[1] = 1, 2
for i in xrange(2, len(dp)):
dp[i] = dp[i-1] + dp[i-2]
result, prev_bit = 0, 0
for i in reversed(xrange(31)):
... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/alertrule_workflow_serializer.py | {
"start": 189,
"end": 341
} | class ____(TypedDict):
ruleId: str | None
alertRuleId: str | None
workflowId: str
@register(AlertRuleWorkflow)
| ActionHandlerSerializerResponse |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/constitutional_ai/base.py | {
"start": 1024,
"end": 12455
} | class ____(Chain):
r'''Chain for applying constitutional principles.
!!! note
This class is deprecated. See below for a replacement implementation using
LangGraph. The benefits of this implementation are:
- Uses LLM tool calling features instead of parsing string responses;
- S... | ConstitutionalChain |
python | getsentry__sentry | src/sentry/search/events/builder/profile_functions.py | {
"start": 1079,
"end": 3004
} | class ____:
def resolve_column_name(self: ProfileFunctionsQueryBuilderProtocol, col: str) -> str:
# giving resolved a type here convinces mypy that the type is str
resolved: str = self.config.resolve_column(col)
return resolved
def get_field_type(self: ProfileFunctionsQueryBuilderProtoc... | ProfileFunctionsQueryBuilderMixin |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 12190,
"end": 12536
} | class ____(SpanProperty):
def __init__(self, spans: "Spans") -> None:
super().__init__(spans)
self.result: set[int] = set()
def finish(self) -> frozenset[int]:
return frozenset(self.result)
def stop_span(self, i: int, *, discarded: bool) -> None:
if discarded:
s... | _discarded |
python | astropy__astropy | astropy/io/ascii/tdat.py | {
"start": 26881,
"end": 31336
} | class ____(core.BaseReader):
"""TDAT format
See: https://heasarc.gsfc.nasa.gov/docs/software/dbdocs/tdat.html
Example::
<HEADER>
# # and // are comments
table_name = example_table
table_description = "Example table"
#
# Table Parameters
#
field[id] = intege... | Tdat |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed4.py | {
"start": 525,
"end": 780
} | class ____(TypedDict, extra_items=int | None):
name: str
year: int | None
details2: MovieDetails2 = {"name": "Kill Bill Vol. 1", "year": 2003}
# This should generate an error because "year" is not required.
movie2: Movie1 = details2
| MovieDetails2 |
python | paramiko__paramiko | tests/test_util.py | {
"start": 1549,
"end": 4939
} | class ____(unittest.TestCase):
def test_imports(self):
"""
Verify that all the classes can be imported from paramiko.
"""
for name in (
"Agent",
"AgentKey",
"AuthenticationException",
"AuthFailure",
"AuthHandler",
... | UtilTest |
python | django__django | django/contrib/contenttypes/migrations/0001_initial.py | {
"start": 85,
"end": 1434
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="ContentType",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=... | Migration |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/closure.py | {
"start": 1867,
"end": 6143
} | class ____:
pass
def closure():
obj = Object()
def source():
obj.x = _test_source()
def sink():
_test_sink(obj.x)
return source, sink
def closure_flow():
# TODO(T168869049): False Negative
source, sink = closure()
source()
sink()
def closure_no_flow():
so... | Object |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 117907,
"end": 118073
} | class ____:
def test_radians(self):
assert_almost_equal(ncu.radians(180.0), np.pi)
assert_almost_equal(ncu.radians(-90.0), -0.5 * np.pi)
| TestRadians |
python | sphinx-doc__sphinx | sphinx/domains/index.py | {
"start": 2041,
"end": 3108
} | class ____(SphinxDirective):
"""Directive to add entries to the index."""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {
'name': directives.unchanged,
}
def run(self) -> list[Node]:
... | IndexDirective |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/transformer.py | {
"start": 5517,
"end": 6655
} | class ____:
def __init__(self) -> None:
self.word2idx: dict[str, int] = {}
self.idx2word: list[str] = []
def add_word(self, word: str) -> int:
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return sel... | Dictionary |
python | redis__redis-py | redis/commands/bf/__init__.py | {
"start": 4600,
"end": 5724
} | class ____(CFCommands, AbstractBloom):
def __init__(self, client, **kwargs):
"""Create a new RedisBloom client."""
# Set the module commands' callbacks
_MODULE_CALLBACKS = {
CF_RESERVE: bool_ok,
# CF_ADD: spaceHolder,
# CF_ADDNX: spaceHolder,
#... | CFBloom |
python | apache__airflow | providers/apache/hive/tests/unit/apache/hive/operators/test_hive.py | {
"start": 1149,
"end": 2198
} | class ____(TestHiveEnvironment):
def test_hive_airflow_default_config_queue(self):
op = HiveOperator(
task_id="test_default_config_queue",
hql=self.hql,
mapred_queue_priority="HIGH",
mapred_job_name="airflow.test_default_config_queue",
dag=self.dag... | HiveOperatorConfigTest |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/shell-script-component/with-build-defs-pythonic.py | {
"start": 104,
"end": 978
} | class ____(dg.Component, dg.Resolvable):
"""Models a shell script as a Dagster asset."""
def __init__(self, script_path: str, asset_specs: Sequence[dg.ResolvedAssetSpec]):
self.script_path = script_path
self.asset_specs = asset_specs
# highlight-start
def build_defs(self, context: dg.C... | ShellCommand |
python | kamyu104__LeetCode-Solutions | Python/walking-robot-simulation-ii.py | {
"start": 29,
"end": 1226
} | class ____(object):
def __init__(self, width, height):
"""
:type width: int
:type height: int
"""
self.__w = width
self.__h = height
self.__curr = 0
def move(self, num):
"""
:type num: int
:rtype: None
"""
self.__c... | Robot |
python | allegroai__clearml | examples/reporting/hyper_parameters.py | {
"start": 2148,
"end": 3815
} | class ____(TaskParameters):
iterations = param(
type=int,
desc="Number of iterations to run",
range=(0, 100000),
)
target_accuracy = percent_param(
desc="The target accuracy of the model",
)
my_task_parameters = MyTaskParameters(iterations=1000, target_accuracy=0.95)
... | MyTaskParameters |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-jaguar/llama_index/vector_stores/jaguar/base.py | {
"start": 1036,
"end": 16562
} | class ____(BasePydanticVectorStore):
"""
Jaguar vector store.
See http://www.jaguardb.com
See http://github.com/fserv/jaguar-sdk
Examples:
`pip install llama-index-vector-stores-jaguar`
```python
from llama_index.vector_stores.jaguar import JaguarVectorStore
vector... | JaguarVectorStore |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_path_converters.py | {
"start": 2393,
"end": 4009
} | class ____:
def test_simple_module(self):
root = Path("/project")
file_path = root / "mypackage" / "module.py"
result = generic_path_converter(file_path, root)
assert result == "mypackage.module"
def test_nested_module(self):
root = Path("/project")
file_path = ... | TestGenericPathConverter |
python | jazzband__django-simple-history | simple_history/management/commands/populate_history.py | {
"start": 206,
"end": 6197
} | class ____(BaseCommand):
args = "<app.model app.model ...>"
help = (
"Populates the corresponding HistoricalRecords field with "
"the current state of all instances in a model"
)
COMMAND_HINT = "Please specify a model or use the --auto option"
MODEL_NOT_FOUND = "Unable to find model... | Command |
python | pydata__xarray | xarray/groupers.py | {
"start": 5244,
"end": 6186
} | class ____(Grouper):
"""
Abstract base class for Grouper objects that allow specializing resampling-type GroupBy instructions.
Currently only used for TimeResampler, but could be used for SpaceResampler in the future.
"""
def compute_chunks(self, variable: Variable, *, dim: Hashable) -> tuple[int,... | Resampler |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 43271,
"end": 43748
} | class ____(PreTrainedModel):
config: Emu3Config
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_no_split_modules = [
"Emu3DecoderLayer",
]
_skip_keys_device_placement = ["past_key_values", "causal_mask"]
_supports_flash_att... | Emu3PreTrainedModel |
python | encode__django-rest-framework | tests/test_requests_client.py | {
"start": 1223,
"end": 1552
} | class ____(APIView):
def get(self, request):
headers = {
key[5:].replace('_', '-'): value
for key, value in request.META.items()
if key.startswith('HTTP_')
}
return Response({
'method': request.method,
'headers': headers
})
... | HeadersView |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 29076,
"end": 32570
} | class ____(IterableDataset):
def __init__(self, size, error_event):
self.error_event = error_event
self.size = size
self.remaining = size
def __len__(self):
return self.size
def __iter__(self):
return self
def __next__(self):
worker_info = torch.utils.d... | TestProperExitIterableDataset |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 8359,
"end": 8516
} | class ____(models.Model):
uuid_primary_key = models.UUIDField(primary_key=True, default=uuid.uuid1)
field1 = models.CharField(max_length=30)
| UUIDPlainA |
python | fluentpython__example-code | 06-dp-1class-func/classic_strategy.py | {
"start": 2468,
"end": 2784
} | class ____(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
| BulkItemPromo |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/optics/pyoptic.py | {
"start": 17094,
"end": 17627
} | class ____(QtCore.QObject):
"""
Simple ray tracer.
Initialize with a list of rays and optics;
calling trace() will cause rays to be extended by propagating them through
each optic in sequence.
"""
def __init__(self, rays, optics):
QtCore.QObject.__init__(self)
self.opt... | Tracer |
python | huggingface__transformers | examples/modular-transformers/configuration_duplicated_method.py | {
"start": 733,
"end": 9723
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DuplicatedMethodModel`]. It is used to instantiate an DuplicatedMethod
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yi... | DuplicatedMethodConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 3787,
"end": 4574
} | class ____(DagsterError):
"""Indicates that you have attempted to construct a Pythonic config or resource class with an invalid value."""
def __init__(
self,
config_class: Optional[type],
field_name: Optional[str],
invalid_type: Any,
is_resource: bool = False,
**... | DagsterInvalidPythonicConfigDefinitionError |
python | pytest-dev__pytest | src/_pytest/_code/code.py | {
"start": 16230,
"end": 30168
} | class ____(Generic[E]):
"""Wraps sys.exc_info() objects and offers help for navigating the traceback."""
_assert_start_repr: ClassVar = "AssertionError('assert "
_excinfo: tuple[type[E], E, TracebackType] | None
_striptext: str
_traceback: Traceback | None
def __init__(
self,
... | ExceptionInfo |
python | bokeh__bokeh | src/bokeh/util/token.py | {
"start": 8197,
"end": 8391
} | class ____(json.JSONEncoder):
def default(self, o: Any) -> Any:
if isinstance(o, bytes):
return dict(bytes=_base64_encode(o))
return super().default(o)
| _BytesEncoder |
python | google__jax | jax/_src/pallas/pipelining/schedule_api.py | {
"start": 1372,
"end": 2066
} | class ____:
"""Constructs a synchronous pipeline stage."""
def __init__(self, func, max_in_flight: int):
self.func = func
self.max_in_flight = max_in_flight
def trace(
self, abstract_refs, state_avals, grid
) -> internal.PipelineStage:
jaxpr, effs = trace_fun(
self.func, abstract_ref... | SyncStage |
python | sympy__sympy | sympy/physics/quantum/operator.py | {
"start": 14728,
"end": 19657
} | class ____(Operator):
"""An operator for representing the differential operator, i.e. d/dx
It is initialized by passing two arguments. The first is an arbitrary
expression that involves a function, such as ``Derivative(f(x), x)``. The
second is the function (e.g. ``f(x)``) which we are to replace with ... | DifferentialOperator |
python | huggingface__transformers | src/transformers/models/segformer/modeling_segformer.py | {
"start": 11516,
"end": 13327
} | class ____(nn.Module):
"""This corresponds to the Block class in the original implementation."""
def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):
super().__init__()
self.layer_norm_1 = nn.LayerNorm(hidden_size)
self.attention ... | SegformerLayer |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1130196,
"end": 1130630
} | class ____(ScaleInvalidDataShowAsangle):
"""
ScaleInvalidDataShowAsValueangle schema wrapper.
Parameters
----------
value : float
The rotation angle of the text, in degrees.
"""
_schema = {"$ref": '#/definitions/ScaleInvalidDataShowAsValue<"angle">'}
def __init__(self, value: ... | ScaleInvalidDataShowAsValueangle |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_alloy_db.py | {
"start": 26486,
"end": 31254
} | class ____:
def setup_method(self):
self.operator = AlloyDBDeleteClusterOperator(
task_id=TEST_TASK_ID,
cluster_id=TEST_CLUSTER_ID,
etag=TEST_ETAG,
force=TEST_FORCE,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
gcp... | TestAlloyDBDeleteClusterOperator |
python | python__mypy | mypyc/test/test_emitfunc.py | {
"start": 34278,
"end": 36172
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.arg = RuntimeArg("arg", int_rprimitive)
self.reg = Register(int_rprimitive, "arg")
self.block = BasicBlock(0)
def test_simple(self) -> None:
self.block.ops.append(Return(self.reg))
fn = FuncIR(
Func... | TestGenerateFunction |
python | PrefectHQ__prefect | src/prefect/serializers.py | {
"start": 5445,
"end": 7831
} | class ____(Serializer[D]):
"""
Serializes data to JSON.
Input types must be compatible with the stdlib json library.
Wraps the `json` library to serialize to UTF-8 bytes instead of string types.
"""
type: str = Field(default="json", frozen=True)
jsonlib: str = "json"
object_encoder: ... | JSONSerializer |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 83667,
"end": 94948
} | class ____(BigBirdPegasusPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BigBirdPegasusDecoderLayer`]
Args:
config: BigBirdPegasusConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: BigBirdPeg... | BigBirdPegasusDecoder |
python | google__jax | jax/experimental/mosaic/gpu/constraints.py | {
"start": 1635,
"end": 1817
} | class ____(Constant):
"""Wraps a known TMEM layout."""
value: tcgen05.TMEMLayout
def __str__(self):
return f"C({self.value})"
@dataclasses.dataclass(frozen=True)
| TMEMLayout |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 16944,
"end": 18093
} | class ____(InlineProcessor):
""" Return a `<code>` element containing the escaped matching text. """
def __init__(self, pattern: str):
InlineProcessor.__init__(self, pattern)
self.ESCAPED_BSLASH = '{}{}{}'.format(util.STX, ord('\\'), util.ETX)
self.tag = 'code'
""" The tag of the... | BacktickInlineProcessor |
python | django__django | tests/model_forms/models.py | {
"start": 9619,
"end": 10079
} | class ____(models.CharField):
def __init__(self, *args, **kwargs):
kwargs["max_length"] = 20
super().__init__(*args, **kwargs)
def formfield(self, **kwargs):
# don't allow this field to be used in form (real use-case might be
# that you know the markup will always be X, but it i... | MarkupField |
python | pytest-dev__pytest | testing/test_assertion.py | {
"start": 13137,
"end": 14216
} | class ____:
def test_pytest_assertrepr_compare_called(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
values = []
def pytest_assertrepr_compare(op, left, right):
values.append((op, left, right))
@pytest.... | TestBinReprIntegration |
python | PyCQA__pylint | pylint/pyreverse/diagrams.py | {
"start": 2082,
"end": 10104
} | class ____(Figure, FilterMixIn):
"""Main class diagram handling."""
TYPE = "class"
def __init__(self, title: str, mode: str) -> None:
FilterMixIn.__init__(self, mode)
Figure.__init__(self)
self.title = title
# TODO: Specify 'Any' after refactor of `DiagramEntity`
se... | ClassDiagram |
python | kamyu104__LeetCode-Solutions | Python/verify-preorder-sequence-in-binary-search-tree.py | {
"start": 29,
"end": 465
} | class ____(object):
# @param {integer[]} preorder
# @return {boolean}
def verifyPreorder(self, preorder):
low, i = float("-inf"), -1
for p in preorder:
if p < low:
return False
while i >= 0 and p > preorder[i]:
low = preorder[i]
... | Solution |
python | huggingface__transformers | src/transformers/models/mpt/modeling_mpt.py | {
"start": 6166,
"end": 6934
} | class ____(nn.Module):
def __init__(self, config: MptConfig):
super().__init__()
hidden_size = config.hidden_size
self.up_proj = nn.Linear(hidden_size, 4 * hidden_size, bias=False)
self.act = nn.GELU(approximate="none")
self.down_proj = nn.Linear(4 * hidden_size, hidden_size... | MptMLP |
python | kamyu104__LeetCode-Solutions | Python/sum-of-weighted-modes-in-subarrays.py | {
"start": 905,
"end": 1521
} | class ____(object):
def modeWeight(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
cnt = collections.defaultdict(int)
max_heap = []
result = 0
for i in xrange(len(nums)):
cnt[nums[i]] += 1
heapq.he... | Solution2 |
python | scipy__scipy | scipy/optimize/_optimize.py | {
"start": 18446,
"end": 40469
} | class ____(RuntimeError):
pass
def _wrap_scalar_function_maxfun_validation(function, args, maxfun):
# wraps a minimizer function to count number of evaluations
# and to easily provide an args kwd.
ncalls = [0]
if function is None:
return ncalls, None
def function_wrapper(x, *wrapper_a... | _MaxFuncCallError |
python | huggingface__transformers | tests/models/flava/test_modeling_flava.py | {
"start": 35722,
"end": 42001
} | class ____(FlavaModelTester):
model_class = FlavaForPreTraining
def prepare_config_and_inputs_for_common(self):
_, pixel_values, bool_masked_pos = self.image_model_tester.prepare_config_and_inputs()
_, input_ids, token_type_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs(... | FlavaForPreTrainingTester |
python | facebook__pyre-check | scripts/build_pypi_sanity_test.py | {
"start": 386,
"end": 6165
} | class ____(Exception):
pass
def production_assert(value: bool, *args: Any) -> None:
if not value:
raise AssertionError(*args)
def validate_configuration(temporary_project_path: Path) -> None:
configuration_path = temporary_project_path / ".pyre_configuration"
try:
configuration = jso... | AssertionError |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-gaudi/llama_index/llms/gaudi/base.py | {
"start": 835,
"end": 18273
} | class ____(HuggingFaceLLM):
r"""
GaudiLLM LLM.
Examples:
`pip install llama-index-llms-gaudi`
```python
from llama_index.llms.gaudi import GaudiLLM
import argparse
import os, logging
def setup_parser(parser):
# Arguments management
p... | GaudiLLM |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 4425,
"end": 4574
} | class ____():
def __call__(self):
return 1
#? int()
CallClass()()
# -----------------
# variable assignments
# -----------------
| CallClass |
python | google__pytype | pytype/tests/test_match1.py | {
"start": 143,
"end": 4498
} | class ____(test_base.BaseTest):
"""Tests for matching types."""
def test_type_against_callable(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from typing import Callable
def f(x: Callable) -> str: ...
""",
)
ty = self.Infer(
... | MatchTest |
python | huggingface__transformers | src/transformers/models/blenderbot/modeling_blenderbot.py | {
"start": 3368,
"end": 4990
} | class ____(nn.Embedding):
"""
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
super().__init__(num_embeddings, embedding_dim, padding_idx)
... | BlenderbotScaledWordEmbedding |
python | getsentry__sentry | src/sentry/users/models/lostpasswordhash.py | {
"start": 718,
"end": 4157
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
user = FlexibleForeignKey(settings.AUTH_USER_MODEL, unique=True)
hash = models.CharField(max_length=32)
date_added = models.DateTimeField(default=timezone.now)
class Meta:
app_label = "sentry"
db_table = "sentry_los... | LostPasswordHash |
python | google__pytype | pytype/typegraph/typegraph_serializer.py | {
"start": 2358,
"end": 7352
} | class ____(json.JSONEncoder):
"""Implements the JSONEncoder behavior for typegraph objects."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._bindings: dict[int, cfg.Binding] = {}
def _encode_program(self, program: cfg.Program) -> dict[str, Any]:
# Surprisingly, program... | TypegraphEncoder |
python | vyperlang__vyper | vyper/ast/utils.py | {
"start": 152,
"end": 1881
} | class ____:
"""
Class to convert between character offsets in a text string, and pairs (line, column) of 1-based
line and 0-based column numbers.
Vendored from asttokens.
"""
def __init__(self, text: str) -> None:
# a list of character offsets of each line's first character
sel... | LineNumbers |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 143217,
"end": 143600
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(StarOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgqlc.types.n... | StarOrder |
python | kamyu104__LeetCode-Solutions | Python/extra-characters-in-a-string.py | {
"start": 113,
"end": 861
} | class ____(object):
def minExtraChar(self, s, dictionary):
"""
:type s: str
:type dictionary: List[str]
:rtype: int
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for word in dictionary:
reduce(dict.__getitem__, word, tri... | Solution |
python | huggingface__transformers | tests/models/phi4_multimodal/test_modeling_phi4_multimodal.py | {
"start": 1575,
"end": 6563
} | class ____:
def __init__(
self,
parent,
batch_size=2,
seq_length=12,
image_seq_length=275,
audio_seq_length=8,
is_training=True,
num_hidden_layers=2,
vocab_size=49,
hidden_size=32,
intermediate_size=64,
num_attention_hea... | Phi4MultimodalModelTester |
python | run-llama__llama_index | llama-index-core/llama_index/core/vector_stores/types.py | {
"start": 9485,
"end": 12804
} | class ____(BaseComponent, ABC):
"""Abstract vector store protocol."""
model_config = ConfigDict(arbitrary_types_allowed=True)
stores_text: bool
is_embedding_query: bool = True
@property
@abstractmethod
def client(self) -> Any:
"""Get client."""
def get_nodes(
self,
... | BasePydanticVectorStore |
python | readthedocs__readthedocs.org | readthedocs/gold/views.py | {
"start": 1976,
"end": 2279
} | class ____(PrivateViewMixin):
def get_gold_user(self):
return get_object_or_404(GoldUser, user=self.request.user)
def get_gold_projects(self):
return self.get_gold_user().projects.all()
def get_success_url(self):
return reverse_lazy("gold_projects")
| GoldProjectsMixin |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 117794,
"end": 118192
} | class ____(sgqlc.types.Enum):
"""The possible team member roles; either 'maintainer' or 'member'.
Enumeration Choices:
* `MAINTAINER`: A team maintainer has permission to add and remove
team members.
* `MEMBER`: A team member has no administrative permissions on the
team.
"""
__sc... | TeamMemberRole |
python | numba__numba | numba/experimental/structref.py | {
"start": 585,
"end": 9999
} | class ____:
"""Internal builder-code utils for structref definitions.
"""
def __init__(self, context, builder, struct_type):
"""
Parameters
----------
context :
a numba target context
builder :
a llvmlite IRBuilder
struct_type : numba.c... | _Utils |
python | boto__boto3 | boto3/dynamodb/conditions.py | {
"start": 6602,
"end": 6705
} | class ____(ConditionBase):
expression_operator = 'NOT'
expression_format = '({operator} {0})'
| Not |
python | xlwings__xlwings | xlwings/conversion/framework.py | {
"start": 2519,
"end": 2873
} | class ____:
@classmethod
def reader(cls, options):
return Pipeline()
@classmethod
def writer(cls, options):
return Pipeline()
@classmethod
def register(cls, *types):
for type in types:
accessors[type] = cls
@classmethod
def router(cls, value, rng, o... | Accessor |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/recurrent.py | {
"start": 46623,
"end": 52362
} | class ____(object):
"""Object that hold dropout related fields for RNN Cell.
This class is not a standalone RNN cell. It suppose to be used with a RNN cell
by multiple inheritance. Any cell that mix with class should have following
fields:
dropout: a float number within range [0, 1). The ratio that the inp... | DropoutRNNCellMixin |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/sanity/__init__.py | {
"start": 44165,
"end": 44907
} | class ____(SanityTest, metaclass=abc.ABCMeta):
"""Base class for sanity test plugins which are independent of the python version being used."""
@abc.abstractmethod
def test(self, args: SanityConfig, targets: SanityTargets) -> TestResult:
"""Run the sanity test and return the result."""
def loa... | SanityVersionNeutral |
python | psf__requests | src/requests/exceptions.py | {
"start": 3359,
"end": 3481
} | class ____(RequestException):
"""The server declared chunked encoding but sent an invalid chunk."""
| ChunkedEncodingError |
python | huggingface__transformers | src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py | {
"start": 14127,
"end": 14781
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
intermediate_size = int(config.hidden_size * config.intermediate_multiple_size)
self.dense_h_to_4h = nn.Linear(config.hidden_size, intermediate_size, bias=False)
# Project back to h.
self.dense_4h_to_h = nn... | GPTNeoXJapaneseMLP |
python | apache__airflow | providers/databricks/tests/unit/databricks/sensors/test_databricks.py | {
"start": 1354,
"end": 8489
} | class ____:
"""
Validate and test the functionality of the DatabricksSQLStatementsSensor. This Sensor borrows heavily
from the DatabricksSQLStatementOperator, meaning that much of the testing logic is also reused.
"""
def test_init_statement(self):
"""Test initialization for traditional use... | TestDatabricksSQLStatementsSensor |
python | pandas-dev__pandas | pandas/core/interchange/dataframe_protocol.py | {
"start": 1279,
"end": 1872
} | class ____(enum.IntEnum):
"""
Integer enum for null type representation.
Attributes
----------
NON_NULLABLE : int
Non-nullable column.
USE_NAN : int
Use explicit float NaN value.
USE_SENTINEL : int
Sentinel value besides NaN/NaT.
USE_BITMASK : int
The bit... | ColumnNullType |
python | doocs__leetcode | lcci/05.01.Insert Into Bits/Solution.py | {
"start": 0,
"end": 168
} | class ____:
def insertBits(self, N: int, M: int, i: int, j: int) -> int:
for k in range(i, j + 1):
N &= ~(1 << k)
return N | M << i
| Solution |
python | huggingface__transformers | tests/models/mvp/test_modeling_mvp.py | {
"start": 8147,
"end": 15694
} | class ____(unittest.TestCase):
vocab_size = 99
def _get_config_and_data(self):
input_ids = torch.tensor(
[
[71, 82, 18, 33, 46, 91, 2],
[68, 34, 26, 58, 30, 82, 2],
[5, 97, 17, 39, 94, 40, 2],
[76, 83, 94, 25, 70, 78, 2],
... | MvpHeadTests |
python | huggingface__transformers | src/transformers/models/shieldgemma2/modeling_shieldgemma2.py | {
"start": 1085,
"end": 1352
} | class ____(ImageClassifierOutputWithNoAttention):
"""ShieldGemma2 classifies imags as violative or not relative to a specific policy
Args:
"""
probabilities: Optional[torch.Tensor] = None
@auto_docstring
| ShieldGemma2ImageClassifierOutputWithNoAttention |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/memory.py | {
"start": 2261,
"end": 2371
} | class ____:
data: Union[bytes, str]
attributes: Mapping[str, Any]
retry_count: int = 0
| MemoryMessage |
python | ansible__ansible | test/integration/targets/delegate_to/connection_plugins/fakelocal.py | {
"start": 1006,
"end": 2426
} | class ____(ConnectionBase):
""" Local based connections """
transport = 'fakelocal'
has_pipelining = True
def __init__(self, *args, **kwargs):
super(Connection, self).__init__(*args, **kwargs)
self.cwd = None
def _connect(self):
""" verify """
if self.get_option(... | Connection |
python | wandb__wandb | wandb/sdk/lib/printer.py | {
"start": 7262,
"end": 7790
} | class ____(abc.ABC):
"""A handle to a block of text that's allowed to change."""
@abc.abstractmethod
def set_text(self, text: str) -> None:
r"""Change the text.
Args:
text: The text to put in the block, with lines separated
by \n characters. The text should not ... | DynamicText |
python | walkccc__LeetCode | solutions/1826. Faulty Sensor/1826.py | {
"start": 0,
"end": 644
} | class ____:
def badSensor(self, sensor1: list[int], sensor2: list[int]) -> int:
# A -> B, so B is defect
def canReplace(A, B):
i = 0 # A's index
j = 0 # B's index
droppedValue = -1
while i < len(A):
if A[i] == B[j]:
i += 1
j += 1
else:
d... | Solution |
python | spyder-ide__spyder | spyder/plugins/pylint/plugin.py | {
"start": 973,
"end": 1036
} | class ____:
AnalyzeCurrentFile = 'run analysis'
| PylintActions |
python | doocs__leetcode | lcci/16.25.LRU Cache/Solution.py | {
"start": 0,
"end": 148
} | class ____:
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = None
self.next = None
| Node |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.