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 | google__python-fire | fire/test_components.py | {
"start": 4889,
"end": 5125
} | class ____:
def props(self, **kwargs):
return kwargs
def upper(self, **kwargs):
return ' '.join(sorted(kwargs.keys())).upper()
def run(self, positional, named=None, **kwargs):
return (positional, named, kwargs)
| Kwargs |
python | PrefectHQ__prefect | tests/server/services/test_foreman.py | {
"start": 6800,
"end": 19628
} | class ____:
async def test_status_update_when_worker_has_old_heartbeat(
self,
session: AsyncSession,
ready_work_pool,
client,
):
"""
Workers that haven't sent a heartbeat in greater than
INACTIVITY_HEARTBEAT_MULTIPLE * heartbeat_interval_seconds
se... | TestForeman |
python | redis__redis-py | redis/asyncio/connection.py | {
"start": 38936,
"end": 48457
} | class ____:
"""
Create a connection pool. ``If max_connections`` is set, then this
object raises :py:class:`~redis.ConnectionError` when the pool's
limit is reached.
By default, TCP connections are created unless ``connection_class``
is specified. Use :py:class:`~redis.UnixDomainSocketConnectio... | ConnectionPool |
python | skorch-dev__skorch | examples/word_language_model/train.py | {
"start": 1452,
"end": 3671
} | class ____(skorch.callbacks.Callback):
def on_epoch_end(self, net, **kwargs):
seed_sentence = "the meaning of"
indices = [corpus.dictionary.word2idx[n] for n in seed_sentence.split()]
indices = skorch.utils.to_tensor(
torch.LongTensor([indices]).t(), device=device)
senten... | ExamplePrinter |
python | RobertCraigie__pyright-python | src/pyright/errors.py | {
"start": 216,
"end": 258
} | class ____(PyrightError):
pass
| NodeError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/decl_api.py | {
"start": 3986,
"end": 4401
} | class ____(type):
def __setattr__(cls, key: str, value: Any) -> None:
if "__mapper__" in cls.__dict__:
_add_attribute(cls, key, value)
else:
type.__setattr__(cls, key, value)
def __delattr__(cls, key: str) -> None:
if "__mapper__" in cls.__dict__:
_de... | _DynamicAttributesType |
python | huggingface__transformers | src/transformers/models/mixtral/modular_mixtral.py | {
"start": 18502,
"end": 18587
} | class ____(MistralForSequenceClassification):
pass
| MixtralForSequenceClassification |
python | getsentry__sentry | tests/sentry_plugins/github/endpoints/test_push_event.py | {
"start": 821,
"end": 7733
} | class ____(APITestCase):
@mock_baxter_response()
def test_simple(self) -> None:
project = self.project # force creation
url = f"/plugins/github/organizations/{project.organization.id}/webhook/"
secret = "b3002c3e321d4b7880360d397db2ccfd"
OrganizationOption.objects.set_value(
... | PushEventWebhookTest |
python | ray-project__ray | python/ray/autoscaler/batching_node_provider.py | {
"start": 645,
"end": 1078
} | class ____:
"""Stores desired scale computed by the autoscaler.
Attributes:
desired_num_workers: Map of worker NodeType to desired number of workers of
that type.
workers_to_delete: List of ids of nodes that should be removed.
"""
desired_num_workers: Dict[NodeType, int] = ... | ScaleRequest |
python | django-haystack__django-haystack | test_haystack/mocks.py | {
"start": 401,
"end": 700
} | class ____(BaseRouter):
def for_read(self, **hints):
if hints.get("pass_through") is False:
return "pass"
return None
def for_write(self, **hints):
if hints.get("pass_through") is False:
return "pass"
return None
| MockPassthroughRouter |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 2075,
"end": 2939
} | class ____(GQLBase, SupportsBitwiseLogicalOps, ABC):
model_config = ConfigDict(
extra="forbid",
frozen=True,
)
def __repr__(self) -> str:
"""Returns the operator's repr string, with operand(s) as positional args.
Note that BaseModels implement `__iter__()`:
https:... | BaseOp |
python | sphinx-doc__sphinx | sphinx/domains/c/__init__.py | {
"start": 2882,
"end": 12008
} | class ____(ObjectDescription[ASTDeclaration]):
"""Description of a C language object."""
option_spec: ClassVar[OptionSpec] = {
'no-index-entry': directives.flag,
'no-contents-entry': directives.flag,
'no-typesetting': directives.flag,
'noindexentry': directives.flag,
'no... | CObject |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 14177,
"end": 14865
} | class ____(Node):
"""Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, ... | Expr |
python | run-llama__llama_index | llama-index-core/llama_index/core/utilities/token_counting.py | {
"start": 245,
"end": 3269
} | class ____:
"""
Token counter class.
Attributes:
model (Optional[str]): The model to use for token counting.
"""
def __init__(self, tokenizer: Optional[Callable[[str], list]] = None) -> None:
self.tokenizer = tokenizer or get_tokenizer()
def get_string_tokens(self, string: st... | TokenCounter |
python | pexpect__pexpect | tests/test_delay.py | {
"start": 72,
"end": 994
} | class ____(PexpectTestCase.PexpectTestCase):
"""
Tests for various delay attributes.
"""
def test_delaybeforesend(self):
"""
Test various values for delaybeforesend.
"""
p = pexpect.spawn("cat")
p.delaybeforesend = 1
p.sendline("line 1")
p.expect(... | TestCaseDelay |
python | pytorch__pytorch | torch/utils/_sympy/printers.py | {
"start": 5538,
"end": 14045
} | class ____(ExprPrinter):
def _print_ToFloat(self, expr: sympy.Expr) -> str:
if len(expr.args) != 1:
raise AssertionError("ToFloat expects exactly one argument")
# NB: We use sym_float here because the printer is used for cache
# serialization, and cache guards get evaluated with ... | PythonPrinter |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 11697,
"end": 12137
} | class ____(NamePathModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"AppendPath: {self.name}+{self.value}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories.append... | AppendPath |
python | plotly__plotly.py | plotly/graph_objs/treemap/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8549
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap.marker.colorbar"
_path_str = "treemap.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "m... | Tickformatstop |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 63771,
"end": 65078
} | class ____(Response):
"""
Response of queues.move_task_backward endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_backward"
_version = "2.13"
_sc... | MoveTaskBackwardResponse |
python | matplotlib__matplotlib | lib/matplotlib/axis.py | {
"start": 19553,
"end": 87723
} | class ____(martist.Artist):
"""
Base class for `.XAxis` and `.YAxis`.
Attributes
----------
isDefault_label : bool
axes : `~matplotlib.axes.Axes`
The `~.axes.Axes` to which the Axis belongs.
major : `~matplotlib.axis.Ticker`
Determines the major tick positions and their lab... | Axis |
python | pytest-dev__pytest | testing/test_runner.py | {
"start": 16022,
"end": 25662
} | class ____:
def test_collect_result(self, pytester: Pytester) -> None:
col = pytester.getmodulecol(
"""
def test_func1():
pass
class TestClass(object):
pass
"""
)
rep = runner.collect_one_node(col)
assert not... | TestSessionReports |
python | python__mypy | test-data/unit/plugins/depshook.py | {
"start": 101,
"end": 373
} | class ____(Plugin):
def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:
if file.fullname == "__main__":
return [(10, "err", -1)]
return []
def plugin(version: str) -> type[DepsPlugin]:
return DepsPlugin
| DepsPlugin |
python | sphinx-doc__sphinx | sphinx/io.py | {
"start": 4169,
"end": 4540
} | class ____(FileInput):
"""A basic FileInput for Sphinx."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs['error_handler'] = 'sphinx'
super().__init__(*args, **kwargs)
warnings.warn(
'sphinx.io.SphinxFileInput is deprecated',
RemovedInSphinx10Warni... | SphinxFileInput |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/issue_priority_equals.py | {
"start": 315,
"end": 677
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.ACTION_FILTER
subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
group = event_data.group
return group... | IssuePriorityCondition |
python | scrapy__scrapy | tests/test_downloadermiddleware_stats.py | {
"start": 224,
"end": 1372
} | class ____:
def setup_method(self):
self.crawler = get_crawler(Spider)
self.mw = DownloaderStats(self.crawler.stats)
self.crawler.stats.open_spider()
self.req = Request("http://scrapytest.org")
self.res = Response("scrapytest.org", status=400)
def assertStatsEqual(self... | TestDownloaderStats |
python | euske__pdfminer | pdfminer/lzw.py | {
"start": 111,
"end": 2936
} | class ____:
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from t... | LZWDecoder |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 132736,
"end": 136040
} | class ____(Response):
"""
Response of models.unarchive_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "models"
_action = "unarchive_many"
_version = "2.23"
_schema = {
"definitions": {},
... | UnarchiveManyResponse |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer_swin.py | {
"start": 12841,
"end": 13421
} | class ____(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:... | MaskFormerSwinDropPath |
python | huggingface__transformers | src/transformers/models/ovis2/modular_ovis2.py | {
"start": 2777,
"end": 2832
} | class ____(Aimv2Attention):
pass
| Ovis2VisionAttention |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 7986,
"end": 8105
} | class ____:
arg: Annotated[TensorArgument, 10]
parameter_name: Annotated[str, 20]
@dataclass
| InputToParameterSpec |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format25.py | {
"start": 345,
"end": 1928
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox04.py | {
"start": 315,
"end": 1419
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 75106,
"end": 75199
} | class ____(ConstantLikeVariable):
_error_prefix = "np.iinfo/np.finfo"
| NumpyTypeInfoVariable |
python | doocs__leetcode | solution/1900-1999/1906.Minimum Absolute Difference Queries/Solution.py | {
"start": 0,
"end": 810
} | class ____:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
m, n = len(nums), len(queries)
pre_sum = [[0] * 101 for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, 101):
t = 1 if nums[i - 1] == j else 0
... | Solution |
python | django__django | django/contrib/gis/gdal/geometries.py | {
"start": 24818,
"end": 24874
} | class ____(Polygon):
geos_support = False
| CurvePolygon |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/settings.py | {
"start": 4803,
"end": 5150
} | class ____(HyperparamSettings):
batch_size: int = 128
buffer_size: int = 50000
buffer_init_steps: int = 0
steps_per_update: float = 1
save_replay_buffer: bool = False
reward_signal_steps_per_update: float = 4
# INTRINSIC REWARD SIGNALS ##########################################################... | OffPolicyHyperparamSettings |
python | jazzband__django-oauth-toolkit | tests/test_authorization_code.py | {
"start": 2995,
"end": 20771
} | class ____(BaseTest):
def test_skip_authorization_completely(self):
"""
If application.skip_authorization = True, should skip the authorization page.
"""
self.oauth2_settings.PKCE_REQUIRED = False
self.client.login(username="test_user", password="123456")
self.applica... | TestAuthorizationCodeView |
python | huggingface__transformers | src/transformers/models/granite_speech/configuration_granite_speech.py | {
"start": 745,
"end": 4513
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GraniteSpeechCTCEncoder`]. It is used to instantiate
a Granite Speech audio encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the dfefaults... | GraniteSpeechEncoderConfig |
python | squidfunk__mkdocs-material | material/plugins/social/layout.py | {
"start": 2714,
"end": 2832
} | class ____(Config):
amount = Type((int, float), default = 1)
height = Type((int, float), default = 1)
# Font
| Line |
python | gevent__gevent | src/greentest/3.14/test_socketserver.py | {
"start": 1533,
"end": 9857
} | class ____(unittest.TestCase):
"""Test all socket servers."""
def setUp(self):
self.port_seed = 0
self.test_files = []
def tearDown(self):
reap_children()
for fn in self.test_files:
try:
os.remove(fn)
except OSError:
... | SocketServerTest |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 10828,
"end": 10982
} | class ____(Fittable1DModel):
p1 = Parameter()
p2 = Parameter()
@staticmethod
def evaluate(x, p1, p2):
return x + p1 + p2
| TModel_1_1 |
python | PrefectHQ__prefect | tests/test_task_engine.py | {
"start": 28429,
"end": 41088
} | class ____:
@pytest.mark.parametrize("always_fail", [True, False])
async def test_task_respects_retry_count(
self, always_fail, prefect_client, events_pipeline
):
mock = MagicMock()
exc = ValueError()
@task(retries=3)
async def flaky_function():
mock()
... | TestTaskRetries |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 221749,
"end": 222007
} | class ____(spack.error.UnsatisfiableSpecError):
"""Raised when some dependency of constrained specs are incompatible"""
def __init__(self, provided, required):
super().__init__(provided, required, "dependency")
| UnsatisfiableDependencySpecError |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 20829,
"end": 21109
} | class ____(graphene.ObjectType):
version = graphene.NonNull(graphene.String)
createTimestamp = graphene.NonNull(graphene.Float)
managementType = graphene.NonNull(GrapheneDefsStateManagementType)
class Meta:
name = "DefsKeyStateInfo"
| GrapheneDefsKeyStateInfo |
python | PyCQA__pylint | tests/functional/u/used/used_before_assignment_typing.py | {
"start": 2994,
"end": 3422
} | class ____:
"""Class to test self referential variable typing, no regression."""
def correct_inner_typing_method(self) -> bool:
def inner_method(self, other: MyOtherClass) -> bool:
return self == other
return inner_method(self, MyOtherClass())
def self_referential_optional_wit... | MyOtherClass |
python | chroma-core__chroma | chromadb/test/test_config.py | {
"start": 3353,
"end": 4652
} | class ____(Component):
def __init__(self, system: System):
super().__init__(system)
self.require(ComponentC)
@overrides
def start(self) -> None:
pass
@overrides
def stop(self) -> None:
pass
def test_runtime_dependencies() -> None:
settings = Settings()
sys... | ComponentZ |
python | celery__celery | t/unit/app/test_builtins.py | {
"start": 1382,
"end": 1675
} | class ____(BuiltinsCase):
def test_run(self):
@self.app.task(shared=False)
def smap_mul(x, y):
return x * y
res = self.app.tasks['celery.starmap'](
smap_mul, [(2, 2), (4, 4), (8, 8)],
)
assert res, [4, 16 == 64]
| test_starmap |
python | facebook__pyre-check | client/commands/server_event.py | {
"start": 3486,
"end": 6015
} | class ____:
wait_on_initialization: bool
def __init__(self, wait_on_initialization: bool) -> None:
self.wait_on_initialization = wait_on_initialization
def wait_on(self, event_stream: IO[str]) -> None:
"""
Read from the given input channel, expecting server events there.
If... | Waiter |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/resources.py | {
"start": 2170,
"end": 18346
} | class ____(DagsterModel):
"""This class exposes methods on top of the Airbyte APIs for Airbyte."""
rest_api_base_url: str = Field(
default=AIRBYTE_CLOUD_REST_API_BASE_URL,
description=(
"The base URL for the Airbyte REST API. "
"For Airbyte Cloud, leave this as the defau... | AirbyteClient |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_setitem.py | {
"start": 36419,
"end": 38247
} | class ____:
def test_setitem_slice_position(self):
# GH#31469
df = DataFrame(np.zeros((100, 1)))
df[-4:] = 1
arr = np.zeros((100, 1))
arr[-4:] = 1
expected = DataFrame(arr)
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("box", [Series, np.ar... | TestDataFrameSetItemSlicing |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 9977,
"end": 10033
} | class ____(_DataPermission):
pass
| DataPermissionOutput |
python | tensorflow__tensorflow | tensorflow/python/saved_model/registration/registration_saving_test.py | {
"start": 2345,
"end": 4962
} | class ____(autotrackable.AutoTrackable):
def __init__(self, parts=None):
self.parts = parts
@def_function.function(input_signature=[])
def value(self):
return array_ops_stack.stack(self.parts)
def get_tensor_slices(trackables):
tensor_names = []
shapes_and_slices = []
tensors = []
restored_tra... | Stack |
python | pytorch__pytorch | functorch/docs/source/tutorials/_src/plot_per_sample_gradients.py | {
"start": 459,
"end": 5065
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
... | SimpleCNN |
python | numpy__numpy | numpy/distutils/tests/test_ccompiler_opt.py | {
"start": 1145,
"end": 2414
} | class ____(CCompilerOpt):
fake_info = ""
def __init__(self, trap_files="", trap_flags="", *args, **kwargs):
self.fake_trap_files = trap_files
self.fake_trap_flags = trap_flags
CCompilerOpt.__init__(self, None, **kwargs)
def __repr__(self):
return textwrap.dedent("""\
... | FakeCCompilerOpt |
python | walkccc__LeetCode | solutions/205. Isomorphic Strings/205.py | {
"start": 0,
"end": 118
} | class ____:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)]
| Solution |
python | getsentry__sentry | src/sentry/notifications/platform/provider.py | {
"start": 510,
"end": 692
} | class ____[RenderableT](Protocol):
def send_notification(
self, target: IntegrationNotificationTarget, payload: RenderableT
) -> None: ...
| IntegrationNotificationClient |
python | automl__auto-sklearn | autosklearn/experimental/selector.py | {
"start": 13554,
"end": 15280
} | class ____(AbstractSelector):
def __init__(self, selector, default_strategies: typing.List[str]):
self.selector = selector
self.default_strategies = default_strategies
def fit(
self,
X: pd.DataFrame,
y: pd.DataFrame,
minima: typing.Dict[int, typing.Dict[str, floa... | FallbackWrapper |
python | kamyu104__LeetCode-Solutions | Python/minimum-average-difference.py | {
"start": 42,
"end": 540
} | class ____(object):
def minimumAverageDifference(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
mn, idx = float("inf"), -1
prefix = 0
for i, x in enumerate(nums):
prefix += x
a = prefix//(i+1)
... | Solution |
python | django-haystack__django-haystack | test_haystack/test_app_using_appconfig/migrations/0001_initial.py | {
"start": 43,
"end": 654
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="MicroBlogPost",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serializ... | Migration |
python | django__django | django/db/models/fields/__init__.py | {
"start": 3025,
"end": 42035
} | class ____(RegisterLookupMixin):
"""Base class for all field types"""
# Designates whether empty strings fundamentally are allowed at the
# database level.
empty_strings_allowed = True
empty_values = list(validators.EMPTY_VALUES)
# These track each time a Field instance is created. Used to ret... | Field |
python | mlflow__mlflow | tests/pyfunc/test_scoring_server.py | {
"start": 1488,
"end": 1846
} | class ____(NamedTuple):
model: Any
inference_data: Any
def build_and_save_sklearn_model(model_path):
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression().fit(X, y)
mlflow.sklearn.save_mod... | ModelWithData |
python | django__django | tests/staticfiles_tests/test_checks.py | {
"start": 4725,
"end": 5631
} | class ____(SimpleTestCase):
@override_settings(STORAGES={})
def test_error_empty_storages(self):
errors = check_storages(None)
self.assertEqual(errors, [E005])
@override_settings(
STORAGES={
DEFAULT_STORAGE_ALIAS: {
"BACKEND": "django.core.files.storage.F... | StoragesCheckTests |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 254474,
"end": 256074
} | class ____(ExternKernel):
"""
This needs to be a custom class to handle mutation properly
"""
def codegen(self, wrapper: PythonWrapperCodegen) -> None:
assert all(isinstance(t, IRNode) for t in self.inputs)
(x,) = (cast(IRNode, t).codegen_reference() for t in self.inputs)
if V.... | InplaceBernoulliFallback |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/matrix_multiply.py | {
"start": 7012,
"end": 9787
} | class ____(MatrixMultiplyOperator):
"""Operator for batch matrix multiplication (torch.bmm)."""
def __init__(self):
super().__init__("bmm")
self.weight = 5.0
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.bmm"
... | BmmOperator |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/blobstore/api/main.py | {
"start": 1902,
"end": 2310
} | class ____(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(
user=users.get_current_user().user_id(), blob_key=upload.key()
)
user_photo.put()
self.redirect("/view_photo/%s" % upload.key())
# [END... | PhotoUploadHandler |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 659,
"end": 787
} | class ____(Action):
"""Do nothing when an Automation is triggered"""
type: Literal["do-nothing"] = "do-nothing"
| DoNothing |
python | doocs__leetcode | solution/0200-0299/0231.Power of Two/Solution.py | {
"start": 0,
"end": 104
} | class ____:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
| Solution |
python | getsentry__sentry | src/sentry/models/grouphistory.py | {
"start": 1049,
"end": 5773
} | class ____:
# Note that we don't record the initial group creation unresolved here to save on creating a row
# for every group.
# Prefer to use ONGOING instead of UNRESOLVED. We will be deprecating UNRESOLVED in the future.
# Use REGRESSED/ESCALATING to specify other substatuses for UNRESOLVED groups.
... | GroupHistoryStatus |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial001.py | {
"start": 104,
"end": 684
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
model_config = {
"json_schema_extra": {
"examples": [
{
"name": "Foo",
"description": "A very nice Item",
... | Item |
python | pytorch__pytorch | test/test_cuda_sanitizer.py | {
"start": 482,
"end": 5076
} | class ____(TestCase):
def test_add(self):
add_func = torch.ops.aten.add.Tensor
a = torch.ones(5, 3, device="cuda")
b = torch.randn(5, 3, device="cuda")
argument_handler = csan.ArgumentHandler()
argument_handler.parse_inputs(add_func._schema, (a, b), {}, is_factory=False)
... | TestArgumentHandler |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py | {
"start": 1368,
"end": 13668
} | class ____(object):
"""Operator adding dropout to inputs and outputs of the given cell."""
def __init__(self,
cell,
input_keep_prob=1.0,
output_keep_prob=1.0,
state_keep_prob=1.0,
variational_recurrent=False,
input_size=None,... | DropoutWrapperBase |
python | falconry__falcon | tests/test_middleware.py | {
"start": 27908,
"end": 28657
} | class ____(TestMiddleware):
def test_base_path_is_removed_before_routing(self, asgi, util):
"""Test that RemoveBasePathMiddleware is executed before routing"""
app = util.create_app(asgi, middleware=RemoveBasePathMiddleware())
# We dont include /base_path as it will be removed in middleware... | TestRemoveBasePathMiddleware |
python | davidhalter__jedi | jedi/inference/filters.py | {
"start": 8671,
"end": 9072
} | class ____:
def __init__(self, *filters):
self._filters = filters
def get(self, name):
return [n for filter in self._filters for n in filter.get(name)]
def values(self):
return [n for filter in self._filters for n in filter.values()]
def __repr__(self):
return '%s(%s)'... | MergedFilter |
python | pytorch__pytorch | torch/ao/quantization/pt2e/_numeric_debugger.py | {
"start": 4195,
"end": 7044
} | class ____(torch.nn.Module):
"""
Base class for capturing output values for nodes in a GraphModule, it only captures
Tensor output currently, but we can extend it to work for other types of inputs later if needed
"""
# Mark as impure so that calls to it will not be removed during DCE.
_is_impur... | OutputLogger |
python | scipy__scipy | scipy/optimize/tests/test_linprog.py | {
"start": 95169,
"end": 103153
} | class ____:
method = "highs"
options = {}
@pytest.mark.fail_slow(10)
@pytest.mark.xfail(condition=(sys.maxsize < 2 ** 32 and
platform.system() == "Linux"),
run=False,
reason="gh-16347")
def test_mip1(self):
# solve non-rel... | TestLinprogHiGHSMIP |
python | python-excel__xlrd | xlrd/xldate.py | {
"start": 1497,
"end": 7934
} | class ____(XLDateError):
pass
def xldate_as_tuple(xldate, datemode):
"""
Convert an Excel number (presumed to represent a date, a datetime or a time) into
a tuple suitable for feeding to datetime or mx.DateTime constructors.
:param xldate: The Excel number
:param datemode: 0: 1900-based, 1: 1... | XLDateBadTuple |
python | walkccc__LeetCode | solutions/130. Surrounded Regions/130.py | {
"start": 0,
"end": 839
} | class ____:
def solve(self, board: list[list[str]]) -> None:
if not board:
return
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(board)
n = len(board[0])
q = collections.deque()
for i in range(m):
for j in range(n):
if i * j == 0 or i == m - 1 or j == n - 1:
... | Solution |
python | chroma-core__chroma | chromadb/utils/embedding_functions/baseten_embedding_function.py | {
"start": 294,
"end": 4299
} | class ____(OpenAIEmbeddingFunction):
def __init__(
self,
api_key: Optional[str],
api_base: str,
api_key_env_var: str = "CHROMA_BASETEN_API_KEY",
):
"""
Initialize the BasetenEmbeddingFunction.
Args:
api_key (str, optional): The API key for your... | BasetenEmbeddingFunction |
python | kamyu104__LeetCode-Solutions | Python/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py | {
"start": 50,
"end": 934
} | class ____(object):
def longestSubarray(self, nums, limit):
"""
:type nums: List[int]
:type limit: int
:rtype: int
"""
max_dq, min_dq = collections.deque(), collections.deque()
left = 0
for right, num in enumerate(nums):
while max_dq and nu... | Solution |
python | huggingface__transformers | src/transformers/models/llama4/modeling_llama4.py | {
"start": 20854,
"end": 24884
} | class ____(Llama4PreTrainedModel):
_no_split_modules = ["Llama4TextDecoderLayer"]
base_model_prefix = "model"
input_modalities = ("text",)
config: Llama4TextConfig
_can_record_outputs = {
"attentions": Llama4TextAttention,
"hidden_states": Llama4TextDecoderLayer,
"router_logi... | Llama4TextModel |
python | prompt-toolkit__python-prompt-toolkit | examples/prompts/auto-completion/colored-completions.py | {
"start": 440,
"end": 1938
} | class ____(Completer):
def get_completions(self, document, complete_event):
word = document.get_word_before_cursor()
for color in colors:
if color.startswith(word):
yield Completion(
color,
start_position=-len(word),
... | ColorCompleter |
python | getsentry__sentry | src/sentry/replays/endpoints/organization_replay_index.py | {
"start": 5243,
"end": 5859
} | class ____:
"""Defers all pagination decision making to the implementation."""
def __init__(self, data_fn: Callable[[int, int], QueryResponse]) -> None:
self.data_fn = data_fn
def get_result(self, limit: int, cursor=None):
assert limit > 0
offset = int(cursor.offset) if cursor is n... | ReplayPaginator |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 6462,
"end": 7101
} | class ____(AbstractTemplate):
key = operator.sub
def generic(self, args, kws):
if len(args) == 1:
# Guard against unary -
return
dt, td = args
if isinstance(dt, types.NPDatetime) and isinstance(td,
types.... | DatetimeMinusTimedelta |
python | pytorch__pytorch | test/distributed/test_store.py | {
"start": 2144,
"end": 8923
} | class ____:
def _create_store(self, i):
raise RuntimeError("not implemented")
def _test_set_get_check(self, fs):
fs.add("key", 1)
fs.add("key", 2)
fs.add("key", 3)
fs.set("key0", "value0")
fs.add("key3", 1)
fs.set("key1", "value1")
fs.add("key3", ... | StoreTestBase |
python | walkccc__LeetCode | solutions/2830. Maximize the Profit as the Salesman/2830.py | {
"start": 0,
"end": 575
} | class ____:
def maximizeTheProfit(self, n: int, offers: list[list[int]]) -> int:
# dp[i] := the maximum amount of gold of selling the first i houses
dp = [0] * (n + 1)
endToStartAndGolds = [[] for _ in range(n)]
for start, end, gold in offers:
endToStartAndGolds[end].append((start, gold))
... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ001.py | {
"start": 959,
"end": 1370
} | class ____:
charfield = DjangoModel.CharField(max_length=255, null=True)
textfield = SmthCharField(max_length=255, null=True)
slugfield = models.SlugField(max_length=255, null=True)
emailfield = models.EmailField(max_length=255, null=True)
filepathfield = models.FilePathField(max_length=255, null=Tr... | IncorrectModelWithoutSuperclass |
python | sqlalchemy__sqlalchemy | test/orm/test_transaction.py | {
"start": 33764,
"end": 39601
} | class ____(FixtureTest):
run_inserts = None
__sparse_driver_backend__ = True
@testing.fixture
def subtransaction_recipe(self):
return self.target_recipe()
@testing.requires.savepoints
def test_recipe_heavy_nesting(self, subtransaction_recipe):
users = self.tables.users
... | SubtransactionRecipeTest |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/data_factory.py | {
"start": 5080,
"end": 40673
} | class ____(BaseHook):
"""
A hook to interact with Azure Data Factory.
:param azure_data_factory_conn_id: The :ref:`Azure Data Factory connection id<howto/connection:adf>`.
"""
conn_type: str = "azure_data_factory"
conn_name_attr: str = "azure_data_factory_conn_id"
default_conn_name: str = ... | AzureDataFactoryHook |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 123450,
"end": 124591
} | class ____(Response):
"""
Response of tasks.add_or_update_model endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_model"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
... | AddOrUpdateModelResponse |
python | Pylons__pyramid | tests/test_config/test_actions.py | {
"start": 31092,
"end": 32447
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.config.actions import ActionInfo
return ActionInfo
def _makeOne(self, filename, lineno, function, linerepr):
return self._getTargetClass()(filename, lineno, function, linerepr)
def test_class_conforms(self):
... | TestActionInfo |
python | altair-viz__altair | altair/utils/deprecation.py | {
"start": 551,
"end": 4786
} | class ____(DeprecationWarning): ...
def _format_message(
version: LiteralString,
alternative: LiteralString | None,
message: LiteralString | None,
/,
) -> LiteralString:
output = f"\nDeprecated since `altair={version}`."
if alternative:
output = f"{output} Use {alternative} instead."
... | AltairDeprecationWarning |
python | google__jax | jax/_src/error_check.py | {
"start": 1695,
"end": 2561
} | class ____(threading.local):
def __init__(self):
self.ref: core.Ref | None = None
_error_storage = _ErrorStorage()
def _initialize_error_code_ref() -> None:
"""Initialize the error code ref in the current thread.
The shape and size of the error code array depend on the mesh in the context.
In single-d... | _ErrorStorage |
python | weaviate__weaviate-python-client | weaviate/collections/queries/hybrid/generate/async_.py | {
"start": 309,
"end": 456
} | class ____(
Generic[Properties, References],
_HybridGenerateExecutor[ConnectionAsync, Properties, References],
):
pass
| _HybridGenerateAsync |
python | pyca__cryptography | docs/development/custom-vectors/secp256k1/generate_secp256k1.py | {
"start": 493,
"end": 2371
} | class ____:
def __init__(self, hasher):
self.hasher = hasher
def __call__(self, data):
self.hasher.update(data)
return self
def digest(self):
return self.hasher.digest()[: 256 // 8]
def build_vectors(fips_vectors):
vectors = defaultdict(list)
for vector in fips_ve... | TruncatedHash |
python | python-visualization__folium | folium/plugins/terminator.py | {
"start": 119,
"end": 652
} | class ____(JSCSSMixin, MacroElement):
"""
Leaflet.Terminator is a simple plug-in to the Leaflet library to
overlay day and night regions on maps.
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
L.terminator().addTo({{this._parent.get_name()}});
{%... | Terminator |
python | falconry__falcon | falcon/response.py | {
"start": 2213,
"end": 53757
} | class ____:
"""Represents an HTTP response to a client request.
Note:
``Response`` is not meant to be instantiated directly by responders.
Keyword Arguments:
options (ResponseOptions): Set of global options passed from the App handler.
"""
__slots__ = (
'text',
'co... | Response |
python | dask__distributed | distributed/tests/test_worker_memory.py | {
"start": 2742,
"end": 2858
} | class ____(dict):
def __init__(self, **kwargs):
super().__init__()
self.kwargs = kwargs
| WorkerData |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 53504,
"end": 158595
} | class ____(Queryable):
"""
Tables should usually be initialized using the ``db.table(table_name)`` or
``db[table_name]`` methods.
The following optional parameters can be passed to ``db.table(table_name, ...)``:
:param db: Provided by ``db.table(table_name)``
:param name: Provided by ``db.tabl... | Table |
python | tensorflow__tensorflow | tensorflow/python/ops/template.py | {
"start": 11122,
"end": 20826
} | class ____(trackable.Trackable):
"""Wrap a function to aid in variable sharing.
Templates are functions that create variables the first time they are called
and reuse them thereafter. See `make_template` for full documentation.
Note: By default, the full variable scope is captured at the time of first
call.... | Template |
python | huggingface__transformers | src/transformers/models/tapas/tokenization_tapas.py | {
"start": 101020,
"end": 101524
} | class ____(enum.Enum):
HEADER_TO_CELL = 1 # Connects header to cell.
CELL_TO_HEADER = 2 # Connects cell to header.
QUERY_TO_HEADER = 3 # Connects query to headers.
QUERY_TO_CELL = 4 # Connects query to cells.
ROW_TO_CELL = 5 # Connects row to cells.
CELL_TO_ROW = 6 # Connects cells to row.... | Relation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.