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 | huggingface__transformers | src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py | {
"start": 12561,
"end": 13492
} | class ____(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
return hidden_state * self.lambda1
def drop_path(input: to... | Dinov2WithRegistersLayerScale |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_wrapper_gpu.py | {
"start": 16865,
"end": 36612
} | class ____(CppWrapperCpu):
"""
Generates cpp wrapper for running on GPU and calls CUDA kernels
"""
def __init__(self) -> None:
self.device = get_gpu_type()
self.device_codegen = get_device_op_overrides(self.device)
super().__init__()
self.grid_id = count()
self._... | CppWrapperGpu |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_xml_parseable.py | {
"start": 1035,
"end": 1823
} | class ____(ColumnMapMetricProvider):
condition_metric_name = "column_values.xml_parseable"
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
def is_xml(val):
try:
etree.fromstring(val)
return True
exce... | ColumnValuesXmlParseable |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-koda-retriever/llama_index/packs/koda_retriever/matrix.py | {
"start": 73,
"end": 3904
} | class ____(BaseModel):
"""
This class is not necessary to understand to use a KodaRetriever - as it will be automatically instantiated if a dictionary is provided.
Pydantic class to enforce the required fields for a KodaRetriever
Its best to just instantiate this using a dictionary, don't both trying t... | AlphaMatrix |
python | pytorch__pytorch | torch/cuda/memory.py | {
"start": 1238,
"end": 1451
} | class ____(TypedDict):
"""Memory segment information."""
address: int
total_size: int
stream: int
segment_type: str
allocated_size: int
active_size: int
blocks: list[_Block]
| _Segment |
python | pytorch__pytorch | test/jit/test_data_parallel.py | {
"start": 444,
"end": 5633
} | class ____(JitTestCase):
class Mpy(torch.nn.Module):
def __init__(self) -> None:
super(TestDataParallel.Mpy, self).__init__()
self.m = nn.Sequential(
nn.Linear(2, 2), nn.BatchNorm1d(2), nn.ReLU(), nn.Linear(2, 2)
)
@torch.jit.ignore
def fo... | TestDataParallel |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 70147,
"end": 72786
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def assertCheckpointState(self, model_checkpoint_path,
all_model_checkpoint_paths, save_dir):
checkpoint_state = c... | RecoverLastCheckpointsTest |
python | walkccc__LeetCode | solutions/1958. Check if Move is Legal/1958.py | {
"start": 0,
"end": 703
} | class ____:
def checkMove(
self,
board: list[list[str]],
rMove: int,
cMove: int,
color: str,
) -> bool:
DIRS = ((-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1))
for dx, dy in DIRS:
cellsCount = 2
i = rMove + dx
j = cMove + dy
... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/decl_api.py | {
"start": 7523,
"end": 9850
} | class ____:
def __init__(
self,
fn: Callable[..., Any],
cascading: bool = False,
quiet: bool = False,
):
# suppport
# @declared_attr
# @classmethod
# def foo(cls) -> Mapped[thing]:
# ...
# which seems to help typing tools interpr... | _declared_attr_common |
python | walkccc__LeetCode | solutions/1998. GCD Sort of an Array/1998.py | {
"start": 0,
"end": 536
} | class ____:
def __init__(self, n: int):
self.id = list(range(n))
self.rank = [0] * n
def unionByRank(self, u: int, v: int) -> None:
i = self.find(u)
j = self.find(v)
if i == j:
return False
if self.rank[i] < self.rank[j]:
self.id[i] = j
elif self.rank[i] > self.rank[j]:
... | UnionFind |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 9635,
"end": 9895
} | class ____(AnsibleTemplateError):
"""A broken conditional with non-boolean result was used."""
_default_help_text = 'Broken conditionals can be temporarily allowed with the `ALLOW_BROKEN_CONDITIONALS` configuration option.'
| AnsibleBrokenConditionalError |
python | pandas-dev__pandas | pandas/tests/io/formats/test_ipython_compat.py | {
"start": 112,
"end": 3162
} | class ____:
def test_publishes(self, ip):
ipython = ip.instance(config=ip.config)
df = DataFrame({"A": [1, 2]})
objects = [df["A"], df] # dataframe / series
expected_keys = [
{"text/plain", "application/vnd.dataresource+json"},
{"text/plain", "text/html", "ap... | TestTableSchemaRepr |
python | django__django | tests/check_framework/test_4_0_compatibility.py | {
"start": 209,
"end": 1007
} | class ____(SimpleTestCase):
@override_settings(CSRF_TRUSTED_ORIGINS=["example.com"])
def test_invalid_url(self):
self.assertEqual(
check_csrf_trusted_origins(None),
[
Error(
"As of Django 4.0, the values in the CSRF_TRUSTED_ORIGINS "
... | CheckCSRFTrustedOrigins |
python | PyCQA__pylint | tests/functional/u/unsubscriptable_value.py | {
"start": 1800,
"end": 2158
} | class ____(metaclass=MetaSubscriptable):
pass
SubscriptableClass[0]
SubscriptableClass()[0] # [unsubscriptable-object]
# functions are not subscriptable
def test(*args, **kwargs):
return args, kwargs
test()[0]
test[0] # [unsubscriptable-object]
# deque
from collections import deque
deq = deque(maxlen=10)
... | SubscriptableClass |
python | ray-project__ray | doc/source/ray-core/doc_code/cgraph_nccl.py | {
"start": 1052,
"end": 1171
} | class ____:
def send(self, shape):
return torch.zeros(shape, device="cuda")
@ray.remote(num_gpus=1)
| GPUSender |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_ecs.py | {
"start": 4046,
"end": 5815
} | class ____(EcsBaseTestCase):
"""Test Base ECS Operator."""
@pytest.mark.parametrize("aws_conn_id", [None, NOTSET, "aws_test_conn"])
@pytest.mark.parametrize("region_name", [None, NOTSET, "ca-central-1"])
def test_initialise_operator(self, aws_conn_id, region_name):
"""Test initialize operator."... | TestEcsBaseOperator |
python | django__django | tests/postgres_tests/fields.py | {
"start": 1769,
"end": 1897
} | class ____(models.IntegerField):
def get_placeholder(self, value, compiler, connection):
return "(%s + 1)"
| OffByOneField |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 53129,
"end": 55021
} | class ____:
"""Ensure that only scheduled flow runs are marked late"""
@pytest.mark.parametrize(
"intended_transition",
[
(StateType.RUNNING, StateType.SCHEDULED),
(StateType.PENDING, StateType.SCHEDULED),
(StateType.COMPLETED, StateType.SCHEDULED),
... | TestEnsureOnlyScheduledFlowMarkedLate |
python | getsentry__sentry | src/sentry/hybridcloud/outbox/base.py | {
"start": 2937,
"end": 5797
} | class ____(BaseManager[_RM]):
"""
Provides bulk update and delete methods that respect outbox creation.
"""
def bulk_create(self, objs: Iterable[_RM], *args: Any, **kwds: Any) -> list[_RM]:
from sentry.hybridcloud.models.outbox import outbox_context
tuple_of_objs: tuple[_RM, ...] = tup... | RegionOutboxProducingManager |
python | fluentpython__example-code-2e | 23-descriptor/bulkfood/bulkfood_v3.py | {
"start": 1279,
"end": 1612
} | class ____:
weight = Quantity('weight') # <1>
price = Quantity('price') # <2>
def __init__(self, description, weight, price): # <3>
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# end::LINEI... | LineItem |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 7440,
"end": 7883
} | class ____(_Permission[RolesAction]):
role: str
scope: Optional[str] = None
def _to_weaviate(self) -> List[WeaviatePermission]:
roles: PermissionRoles = {"role": self.role}
if self.scope is not None:
roles["scope"] = self.scope
return [
{
"act... | _RolesPermission |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 19540,
"end": 19642
} | class ____(PermissionInstanceView):
permission_classes = (BasicPermWithDetail,)
| DeniedViewWithDetail |
python | doocs__leetcode | solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/Solution.py | {
"start": 343,
"end": 810
} | class ____:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
def dfs(i: int, j: int) -> Optional[TreeNode]:
if i > j:
return None
mid = (i + j) >> 1
l, r = dfs(i, mid - 1), dfs(mid + 1, j)
return TreeNode(nums[mid], l,... | Solution |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/test_backend_name.py | {
"start": 778,
"end": 1223
} | class ____(enum.Enum):
"""DTensor backend the test is being run on."""
UNSPECIFIED = 'unspecified'
CPU = 'cpu'
GPU = 'gpu'
GPU_2DEVS_BACKEND = '2gpus'
TPU = 'tpu'
TPU_STREAM_EXECUTOR = 'tpu_se'
TPU_V3_DONUT_BACKEND = 'tpu_v3_2x2'
TPU_V4_DONUT_BACKEND = 'tpu_v4_2x2'
DTENSOR_TEST_UTIL_BACKEND = DTenso... | DTensorTestUtilBackend |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 1122,
"end": 1226
} | class ____(GQLResult):
edges: List[ArtifactCollectionFragmentTagsEdges]
| ArtifactCollectionFragmentTags |
python | dagster-io__dagster | examples/assets_pandas_type_metadata/assets_pandas_type_metadata/lib.py | {
"start": 1561,
"end": 6046
} | class ____(pa.DataFrameModel):
"""Anomalous price events, defined by a day on which a stock's closing price strayed above or
below its Bollinger bands.
"""
date: Series[pd.Timestamp] = pa.Field(description="Date of price event")
name: Series[str] = pa.Field(description="Ticker symbol of stock")
... | AnomalousEvents |
python | ansible__ansible | lib/ansible/_internal/_datatag/_wrappers.py | {
"start": 149,
"end": 1137
} | class ____(ObjectProxy):
"""
Janky proxy around IOBase to allow streams to carry tags and support basic interrogation by the tagging API.
Most tagging operations will have undefined behavior for this type.
"""
_self__ansible_tags_mapping: _datatag._AnsibleTagsMapping
def __init__(self, stream:... | TaggedStreamWrapper |
python | paramiko__paramiko | paramiko/ssh_exception.py | {
"start": 4001,
"end": 4475
} | class ____(SSHException):
"""
A disagreement arose regarding an algorithm required for key exchange.
.. versionadded:: 2.9
"""
# TODO 4.0: consider making this annotate w/ 1..N 'missing' algorithms,
# either just the first one that would halt kex, or even updating the
# Transport logic so ... | IncompatiblePeer |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 6301,
"end": 8264
} | class ____(TestCase):
def test_extra_actions(self):
view = ActionViewSet()
actual = [action.__name__ for action in view.get_extra_actions()]
expected = [
'custom_detail_action',
'custom_list_action',
'detail_action',
'list_action',
... | GetExtraActionsTests |
python | getsentry__responses | responses/tests/test_responses.py | {
"start": 77314,
"end": 80034
} | class ____:
"""Validate that teardown raises if not all requests were executed.
Similar to ``TestUnitTestPatchSetup``.
"""
def setup_method(self):
self.r_mock = responses.RequestsMock()
self.r_mock.start()
self.r_mock.get("https://example.com", status=505)
self.r_mock.... | TestUnitTestPatchSetupRaises |
python | geekcomputers__Python | Assembler/assembler.py | {
"start": 557,
"end": 39047
} | class ____:
def __init__(self, token, t):
self.token = token
self.t = t
# def initRegister():
# global register
# for i in range(9):
# register.append(0)
def loadFile(fileName):
"""
loadFile: This function loads the file and reads its lines.
"""
global lines
f... | Token |
python | ray-project__ray | python/ray/air/_internal/filelock.py | {
"start": 132,
"end": 1430
} | class ____:
"""FileLock wrapper that uses temporary file locks.
The temporary directory that these locks are saved to can be configured via
the `RAY_TMPDIR` environment variable.
Args:
path: The file path that this temporary file lock is used for.
This will be used to generate the ... | TempFileLock |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mixedversions/package.py | {
"start": 217,
"end": 510
} | class ____(Package):
url = "http://www.fake-mixedversions.org/downloads/mixedversions-1.0.tar.gz"
version("2.0.1", md5="0000000000000000000000000000000c")
version("2.0", md5="0000000000000000000000000000000b")
version("1.0.1", md5="0000000000000000000000000000000a")
| Mixedversions |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance1.py | {
"start": 476,
"end": 937
} | class ____[T](Sequence[T]):
def __len__(self) -> int: ...
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, index: slice) -> Sequence[T]: ...
def __getitem__(self, index: int | slice) -> T | Sequence[T]: ...
vco2_1: ShouldBeCovariant2[float] = ShouldBeCovari... | ShouldBeCovariant2 |
python | getsentry__sentry | src/sentry/dynamic_sampling/models/common.py | {
"start": 231,
"end": 774
} | class ____:
id: ProjectId | TransactionName
count: float
new_sample_rate: float = 0.0
def sum_classes_counts(classes: list[RebalancedItem]) -> float:
ret_val = 0.0
for elm in classes:
ret_val += elm.count
return ret_val
def guarded_run(model: Model[Any, Any], model_input: ModelInpu... | RebalancedItem |
python | scipy__scipy | benchmarks/benchmarks/special.py | {
"start": 336,
"end": 470
} | class ____(Benchmark):
def time_ai_zeros(self):
ai_zeros(100000)
def time_bi_zeros(self):
bi_zeros(100000)
| Airy |
python | pydata__xarray | xarray/tests/test_sparse.py | {
"start": 8149,
"end": 17913
} | class ____:
@pytest.fixture(autouse=True)
def setUp(self):
self.data = sparse.random((4, 6), random_state=0, density=0.5)
self.var = xr.Variable(("x", "y"), self.data)
def test_nbytes(self):
assert self.var.nbytes == self.data.nbytes
def test_unary_op(self):
assert_spar... | TestSparseVariable |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 5953,
"end": 6068
} | class ____(BaseModel):
index: int
finish_reason: str | None = None
delta: ChatChoiceDelta
| ChatChunkChoice |
python | ApeWorX__ape | tests/functional/test_accounts.py | {
"start": 2153,
"end": 41707
} | class ____(EIP712Message):
_name_: "string" = "Foo" # type: ignore # noqa: F821
bar: "address" # type: ignore # noqa: F821
baz: Baz
def test_sign_message(signer, message):
signature = signer.sign_message(message)
assert signer.check_signature(message, signature)
def test_sign_transaction(sig... | Foo |
python | python-markdown__markdown | markdown/preprocessors.py | {
"start": 2266,
"end": 2737
} | class ____(Preprocessor):
""" Normalize whitespace for consistent parsing. """
def run(self, lines: list[str]) -> list[str]:
source = '\n'.join(lines)
source = source.replace(util.STX, "").replace(util.ETX, "")
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n"
s... | NormalizeWhitespace |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/identity_bijector_test.py | {
"start": 941,
"end": 1867
} | class ____(test.TestCase):
"""Tests correctness of the Y = g(X) = X transformation."""
def testBijector(self):
bijector = identity_bijector.Identity(validate_args=True)
self.assertEqual("identity", bijector.name)
x = [[[0.], [1.]]]
self.assertAllEqual(x, self.evaluate(bijector.forward(x)))
self... | IdentityBijectorTest |
python | bokeh__bokeh | src/bokeh/models/filters.py | {
"start": 5144,
"end": 5633
} | class ____(Filter):
''' A ``BooleanFilter`` filters data by returning the subset of data corresponding to indices
where the values of the booleans array is True.
'''
booleans = Nullable(Seq(Bool), help="""
A list of booleans indicating which rows of data to select.
""")
def __init__(self, ... | BooleanFilter |
python | davidhalter__jedi | test/completion/decorators.py | {
"start": 3032,
"end": 3278
} | class ____():
def __init__(self, func):
self.func = func
@DecoratorWithoutCall
def f():
return 1
# cannot be resolved - should be ignored
@DecoratorWithoutCall(None)
def g():
return 1
#?
f()
#? int()
g()
| DecoratorWithoutCall |
python | GoogleCloudPlatform__python-docs-samples | dataflow/flex-templates/pipeline_with_dependencies/src/my_package/my_transforms.py | {
"start": 925,
"end": 1241
} | class ____(beam.PTransform):
"""Extracts words from text and finds the longest one."""
def expand(self, pcoll):
return (
pcoll
| "Extract words" >> beam.ParDo(WordExtractingDoFn())
| "Find longest" >> beam.combiners.Top.Largest(n=1, key=len)
)
| FindLongestWord |
python | TheAlgorithms__Python | graphs/markov_chain.py | {
"start": 96,
"end": 2085
} | class ____:
"""
Undirected Unweighted Graph for running Markov Chain Algorithm
"""
def __init__(self):
self.connections = {}
def add_node(self, node: str) -> None:
self.connections[node] = {}
def add_transition_probability(
self, node1: str, node2: str, probability: fl... | MarkovChainGraphUndirectedUnweighted |
python | pandas-dev__pandas | asv_bench/benchmarks/ctors.py | {
"start": 2477,
"end": 2730
} | class ____:
def setup(self):
N = 10**4
self.iterables = [Index([f"i-{i}" for i in range(N)], dtype=object), range(20)]
def time_multiindex_from_iterables(self):
MultiIndex.from_product(self.iterables)
| MultiIndexConstructor |
python | keras-team__keras | keras/src/optimizers/loss_scale_optimizer_test.py | {
"start": 261,
"end": 11182
} | class ____(testing.TestCase):
def _skip_test_for_stateless(self, stateless):
if not stateless and backend.backend() == "jax":
self.skipTest(
"LossScaleOptimizer must use stateless_apply with JAX."
)
if stateless and backend.backend() == "tensorflow":
... | LossScaleOptimizerTest |
python | networkx__networkx | networkx/classes/coreviews.py | {
"start": 12489,
"end": 13251
} | class ____(FilterAdjacency): # multiedgedict
"""A read-only Mapping of Mappings with filtering criteria
for nodes and edges.
It is a view into a dict-of-dict-of-dict-of-dict data structure,
and it selects nodes and edges that satisfy specific criteria
defined by ``NODE_OK`` and ``EDGE_OK``, respec... | FilterMultiAdjacency |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py | {
"start": 2161,
"end": 3036
} | class ____(cfg.GraphVisitor):
"""CFG visitor that determines reaching definitions at statement level."""
def __init__(self, graph, external_defs):
super(Analyzer, self).__init__(graph)
# This allows communicating that nodes have extra reaching definitions,
# e.g. those that a function closes over.
... | Analyzer |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 413,
"end": 598
} | class ____(Generic[S]):
var: S
# This case gets a diagnostic but not a fix because we can't look up the bounds
# or constraints on the TypeVar imported from another module
| Constrained |
python | kamyu104__LeetCode-Solutions | Python/range-addition-ii.py | {
"start": 53,
"end": 336
} | class ____(object):
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
for op in ops:
m = min(m, op[0])
n = min(n, op[1])
return m*n
| Solution |
python | realpython__materials | contact-book-python-textual/source_code/rpcontacts/tui.py | {
"start": 3906,
"end": 4906
} | class ____(Screen):
def compose(self):
yield Grid(
Label("Add Contact", id="title"),
Label("Name:", classes="label"),
Input(placeholder="Contact Name", classes="input", id="name"),
Label("Phone:", classes="label"),
Input(placeholder="Contact Phone"... | InputDialog |
python | rq__rq | tests/test_spawn_worker.py | {
"start": 422,
"end": 2257
} | class ____(RQTestCase):
def test_work_and_quit(self):
"""SpawnWorker processes work, then quits."""
queue = Queue('foo', connection=self.connection)
worker = SpawnWorker([queue])
self.assertEqual(worker.work(burst=True), False, 'Did not expect any work on the queue.')
job = ... | TestWorker |
python | gevent__gevent | src/greentest/3.10/test_httplib.py | {
"start": 48349,
"end": 51821
} | class ____(TestCase):
"""
Test peek(), read1(), readline()
"""
lines = (
'HTTP/1.1 200 OK\r\n'
'\r\n'
'hello world!\n'
'and now \n'
'for something completely different\n'
'foo'
)
lines_expected = lines[lines.find('hello'):].encode("ascii")
... | ExtendedReadTest |
python | kamyu104__LeetCode-Solutions | Python/count-operations-to-obtain-zero.py | {
"start": 62,
"end": 356
} | class ____(object):
def countOperations(self, num1, num2):
"""
:type num1: int
:type num2: int
:rtype: int
"""
result = 0
while num2:
result += num1//num2
num1, num2 = num2, num1%num2
return result
| Solution |
python | getsentry__sentry | src/sentry/monitors/constants.py | {
"start": 606,
"end": 1275
} | class ____(Enum):
ACCEPT = 0
"""
Check-in should be fully accepted and shall be passed through
the entire Monitor Check-In processing logic.
"""
DROP = 1
"""
Check-in should not be processed. All logic should be skipped
and the consumer should halt work on this check-in immediately.... | PermitCheckInStatus |
python | pytorch__pytorch | test/dynamo/test_fx_graph_runnable.py | {
"start": 2158,
"end": 2387
} | class ____(logging.Filter):
def filter(self, record):
return (
"artifact" in record.metadata
and record.metadata["artifact"]["name"] == "fx_graph_runnable"
)
| FxGraphRunnableArtifactFilter |
python | doocs__leetcode | solution/2000-2099/2090.K Radius Subarray Averages/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def getAverages(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
ans = [-1] * n
s = 0
for i, x in enumerate(nums):
s += x
if i >= k * 2:
ans[i - k] = s // (k * 2 + 1)
s -= nums[i - k * 2]
return ans... | Solution |
python | django-debug-toolbar__django-debug-toolbar | tests/test_integration.py | {
"start": 1749,
"end": 1918
} | class ____(Panel):
def title(self):
return "BuggyPanel"
@property
def content(self):
raise Exception
@override_settings(DEBUG=True)
| BuggyPanel |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-databricks/llama_index/llms/databricks/base.py | {
"start": 104,
"end": 1736
} | class ____(OpenAILike):
"""
Databricks LLM.
Examples:
`pip install llama-index-llms-databricks`
```python
from llama_index.llms.databricks import Databricks
# Set up the Databricks class with the required model, API key and serving endpoint
llm = Databricks(model="... | Databricks |
python | tensorflow__tensorflow | tensorflow/python/data/ops/options.py | {
"start": 6891,
"end": 10707
} | class ____(options_lib.OptionsBase):
"""Represents options for autotuning dataset performance.
```python
options = tf.data.Options()
options.autotune.enabled = False
dataset = dataset.with_options(options)
```
"""
enabled = options_lib.create_option(
name="enabled",
ty=bool,
docstrin... | AutotuneOptions |
python | ray-project__ray | python/ray/_common/test_utils.py | {
"start": 5541,
"end": 7712
} | class ____(Enum):
DRIVER = "driver"
ACTOR = "actor"
TASK = "task"
def _get_library_usages() -> Set[str]:
return set(
ray_usage_lib.get_library_usages_to_report(
ray.experimental.internal_kv.internal_kv_get_gcs_client()
)
)
def _get_extra_usage_tags() -> Dict[str, str]... | TelemetryCallsite |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 720,
"end": 810
} | class ____(ParentA, ParentB):
def __init__(self):
ParentB.__init__(self)
| ChildC1 |
python | optuna__optuna | optuna/storages/_rdb/models.py | {
"start": 1368,
"end": 2470
} | class ____(BaseModel):
__tablename__ = "studies"
study_id = _Column(Integer, primary_key=True)
study_name = _Column(
String(MAX_INDEXED_STRING_LENGTH), index=True, unique=True, nullable=False
)
@classmethod
def find_or_raise_by_id(
cls, study_id: int, session: orm.Session, for_u... | StudyModel |
python | networkx__networkx | networkx/readwrite/gml.py | {
"start": 9127,
"end": 31193
} | class ____(NamedTuple):
category: Pattern
value: Any
line: int
position: int
LIST_START_VALUE = "_networkx_list_start"
def parse_gml_lines(lines, label, destringizer):
"""Parse GML `lines` into a graph."""
def tokenize():
patterns = [
r"[A-Za-z][0-9A-Za-z_]*\b", # keys
... | Token |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/twitter/tests.py | {
"start": 296,
"end": 4150
} | class ____(OAuthTestsMixin, TestCase):
provider_id = TwitterProvider.id
def get_mocked_response(self):
# TODO: Replace with actual/complete Twitter response
return [
MockedResponse(
HTTPStatus.OK,
r"""
{"follow_request_sent": false,
"profile_use_back... | TwitterTests |
python | huggingface__transformers | src/transformers/utils/dummy_pt_objects.py | {
"start": 13435,
"end": 13702
} | class ____(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
def torch_distributed_zero_first(*args, **kwargs):
requires_backends(torch_distributed_zero_first, ["torch"])
| Trainer |
python | readthedocs__readthedocs.org | readthedocs/proxito/exceptions.py | {
"start": 323,
"end": 1519
} | class ____(Http404):
"""
Base class for contextualized HTTP 404 handling.
Subclasses may define their own template name,
HTTP status and object that was not found.
The contextualized exception is handled by proxito's 404 handler
"""
template_name = "errors/proxito/404/base.html"
not_f... | ContextualizedHttp404 |
python | django-guardian__django-guardian | guardian/mixins.py | {
"start": 10984,
"end": 15286
} | class ____:
"""A view mixin that filter a queryset by user and permission.
This mixin filter object retrieved by a queryset that the
logged-in user has the specified permission for.
Example:
```python
from django.views.generic import ListView
from guardian.mixins import Permiss... | PermissionListMixin |
python | huggingface__transformers | src/transformers/models/grounding_dino/modular_grounding_dino.py | {
"start": 2491,
"end": 5616
} | class ____(DetrImageProcessorFast):
def post_process_object_detection(
self,
outputs: "GroundingDinoObjectDetectionOutput",
threshold: float = 0.1,
target_sizes: Optional[Union[TensorType, list[tuple]]] = None,
):
"""
Converts the raw output of [`GroundingDinoForO... | GroundingDinoImageProcessorFast |
python | encode__httpx | tests/client/test_auth.py | {
"start": 311,
"end": 829
} | class ____:
"""
A mock app to test auth credentials.
"""
def __init__(self, auth_header: str = "", status_code: int = 200) -> None:
self.auth_header = auth_header
self.status_code = status_code
def __call__(self, request: httpx.Request) -> httpx.Response:
headers = {"www-au... | App |
python | pytest-dev__pytest | src/_pytest/python.py | {
"start": 42158,
"end": 44650
} | class ____:
"""A planned parameterized invocation of a test function.
Calculated during collection for a given test function's Metafunc.
Once collection is over, each callspec is turned into a single Item
and stored in item.callspec.
"""
# arg name -> arg value which will be passed to a fixtur... | CallSpec2 |
python | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 795,
"end": 1214
} | class ____(Benchmark):
def setup(self):
self.d = np.linspace(0, 100, 200000).reshape((-1, 2))
def time_full_coverage(self):
np.histogramdd(self.d, (200, 200), ((0, 100), (0, 100)))
def time_small_coverage(self):
np.histogramdd(self.d, (200, 200), ((50, 51), (50, 51)))
def time... | Histogram2D |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 40369,
"end": 47608
} | class ____(unittest.TestCase):
"""
Stress signal delivery, especially when a signal arrives in
the middle of recomputing the signal state or executing
previously tripped signal handlers.
"""
def setsig(self, signum, handler):
old_handler = signal.signal(signum, handler)
self.add... | StressTest |
python | django__django | tests/admin_views/admin.py | {
"start": 21120,
"end": 21245
} | class ____(admin.ModelAdmin):
ordering = ("order",)
list_display = ("stuff", "some_order")
| AdminOrderedModelMethodAdmin |
python | openai__gym | gym/wrappers/resize_observation.py | {
"start": 172,
"end": 2399
} | class ____(gym.ObservationWrapper):
"""Resize the image observation.
This wrapper works on environments with image observations (or more generally observations of shape AxBxC) and resizes
the observation to the shape given by the 2-tuple :attr:`shape`. The argument :attr:`shape` may also be an integer.
... | ResizeObservation |
python | pennersr__django-allauth | allauth/socialaccount/providers/evernote/views.py | {
"start": 201,
"end": 1112
} | class ____(OAuthAdapter):
provider_id = "evernote"
settings = app_settings.PROVIDERS.get(provider_id, {})
request_token_url = "https://%s/oauth" % (
settings.get("EVERNOTE_HOSTNAME", "sandbox.evernote.com")
)
access_token_url = "https://%s/oauth" % (
settings.get("EVERNOTE_HOSTNAME",... | EvernoteOAuthAdapter |
python | vyperlang__vyper | vyper/codegen/context.py | {
"start": 646,
"end": 976
} | class ____:
name: str
offset: int
typ: VyperType
size: int
_id: int
# special metadata for calloca. hint for venom to tie calloca to call site.
_callsite: Optional[str] = None
def __post_init__(self):
assert self.typ.memory_bytes_required == self.size
# Function variable
@da... | Alloca |
python | conda__conda | conda/gateways/repodata/__init__.py | {
"start": 15517,
"end": 22802
} | class ____:
"""
Handle caching for a single repodata.json + repodata.info.json
(<hex-string>*.json inside `dir`)
Avoid race conditions while loading, saving repodata.json and cache state.
Also support bytes as in repodata_shards.msgpack.zst
"""
def __init__(self, base, repodata_fn):
... | RepodataCache |
python | aio-libs__aiohttp | tests/test_payload.py | {
"start": 1689,
"end": 4989
} | class ____(payload.Payload):
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
assert False
async def write(self, writer: AbstractStreamWriter) -> None:
pass
def test_register_type(registry: payload.PayloadRegistry) -> None:
class TestProvider:
pass
pa... | Payload |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/deep_learning/activation_functions.py | {
"start": 1076,
"end": 1344
} | class ____():
def __init__(self, alpha=0.1):
self.alpha = alpha
def __call__(self, x):
return np.where(x >= 0.0, x, self.alpha * (np.exp(x) - 1))
def gradient(self, x):
return np.where(x >= 0.0, 1, self.__call__(x) + self.alpha)
| ELU |
python | kamyu104__LeetCode-Solutions | Python/string-matching-in-an-array.py | {
"start": 2937,
"end": 4354
} | class ____(object):
def stringMatching(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j != -1 and pattern[j+1]... | Solution2 |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/relativity/relativity.py | {
"start": 7931,
"end": 9220
} | class ____(pTypes.GroupParameter):
def __init__(self, **kwds):
defs = dict(name="Clock", autoIncrementName=True, renamable=True, removable=True, children=[
dict(name='Initial Position', type='float', value=0.0, step=0.1),
#dict(name='V0', type='float', value=0.0, step=0.1),
... | ClockParam |
python | getsentry__sentry | src/sentry/logging/__init__.py | {
"start": 0,
"end": 65
} | class ____:
HUMAN = "human"
MACHINE = "machine"
| LoggingFormat |
python | spack__spack | lib/spack/spack/util/elf.py | {
"start": 17660,
"end": 22567
} | class ____:
def __init__(self, old_value: bytes, new_value: bytes, offset: int):
self.old_value = old_value
self.new_value = new_value
self.offset = offset
@property
def inplace(self) -> bool:
return len(self.new_value) <= len(self.old_value)
def apply(self, f: BinaryIO... | UpdateCStringAction |
python | tensorflow__tensorflow | tensorflow/python/compiler/mlir/mlir_test.py | {
"start": 4233,
"end": 5648
} | class ____(test.TestCase):
@test_util.run_v2_only
def testImport(self):
@def_function.function
def sqr(i):
return i * i
concrete_function = sqr.get_concrete_function(
tensor_spec.TensorSpec(None, dtypes.float32))
mlir_module = mlir.convert_function(concrete_function, show_debug_info... | MLIRConcreteFunctionImportTest |
python | django__django | tests/auth_tests/models/custom_user.py | {
"start": 3783,
"end": 4680
} | class ____(AbstractBaseUser):
pk = models.CompositePrimaryKey("email", "date_of_birth")
email = models.EmailField(verbose_name="email address", max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_of_birth = models.DateField()
... | CustomUserCompositePrimaryKey |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 12946,
"end": 15015
} | class ____(URLPatternsTestCase, APITestCase):
nested = [
path('namespaced/<int:pk>/', dummy_pk_view, name='nested'),
]
included = [
path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
path('nested/', include((nested, 'nested-namespace'), namespace='nested-namespace'))
... | TestNamespaceVersioningHyperlinkedRelatedFieldScheme |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_allocated_device_status.py | {
"start": 383,
"end": 10542
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta2AllocatedDeviceStatus |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datastore.py | {
"start": 6415,
"end": 6957
} | class ____:
@mock.patch(HOOK_PATH)
def test_execute(self, mock_hook):
op = CloudDatastoreRollbackOperator(
task_id="test_task",
gcp_conn_id=CONN_ID,
project_id=PROJECT_ID,
transaction=TRANSACTION,
)
op.execute({})
mock_hook.assert_... | TestCloudDatastoreRollback |
python | pytorch__pytorch | torch/testing/_internal/common_distributed.py | {
"start": 40117,
"end": 46102
} | class ____(MultiProcessTestCase):
def setUp(self):
super().setUp()
os.environ["WORLD_SIZE"] = str(self.world_size)
self._spawn_processes()
def tearDown(self):
try:
torch.distributed.destroy_process_group()
except AssertionError:
pass
try:
... | DistributedTestBase |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_utils.py | {
"start": 2991,
"end": 4056
} | class ____(TestCase):
mock_client = MagicMock()
mock_client.get_paginator.return_value.paginate.return_value = [
{
"Functions": [
{"FunctionName": "lambdaA", "Runtime": "nodejs12.x"},
{"FunctionName": "lambdaB", "Runtime": "nodejs10.x"},
]
... | GetSupportedFunctionsTest |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 52379,
"end": 53616
} | class ____(AsyncHTTPTestCase):
def get_app(self):
# The old request_callback interface does not implement the
# delegate interface, and writes its response via request.write
# instead of request.connection.write_headers.
def handle_request(request):
self.http1 = request.v... | LegacyInterfaceTest |
python | django__django | tests/model_forms/models.py | {
"start": 4237,
"end": 4325
} | class ____(models.Model):
f = CustomFileField(upload_to="unused", blank=True)
| CustomFF |
python | milvus-io__pymilvus | pymilvus/grpc_gen/milvus_pb2_grpc.py | {
"start": 196494,
"end": 197385
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def RegisterLink(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
... | ProxyService |
python | tornadoweb__tornado | tornado/auth.py | {
"start": 22040,
"end": 27029
} | class ____:
"""Abstract implementation of OAuth 2.0.
See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
implementations.
Class attributes:
* ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.
* ``_OAUTH_ACCESS_TOKEN_URL``: The service's access token url.
"""
d... | OAuth2Mixin |
python | django__django | tests/admin_scripts/management/commands/suppress_base_options_command.py | {
"start": 49,
"end": 650
} | class ____(BaseCommand):
help = "Test suppress base options command."
requires_system_checks = []
suppressed_base_arguments = {
"-v",
"--traceback",
"--settings",
"--pythonpath",
"--no-color",
"--force-color",
"--version",
"file",
}
de... | Command |
python | davidhalter__jedi | test/completion/goto.py | {
"start": 3297,
"end": 3490
} | class ____():
def class_func(func):
return func
#! 14 ['def class_func']
@ClassDec.class_func
def x():
pass
#! 2 ['class ClassDec']
@ClassDec.class_func
def z():
pass
| ClassDec |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 21532,
"end": 21960
} | class ____(DataBlob):
"""
TicketDataBlob is a specific type that represents the data blob for a ticket creation action.
"""
# Dynamic form fields from customer configuration
dynamic_form_fields: list[dict[str, Any]] = field(default_factory=list)
# Store any additional fields that aren't part of... | TicketDataBlob |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 80404,
"end": 81460
} | class ____:
"""Test de_CH address provider methods"""
def test_canton_name(self, faker, num_samples):
for _ in range(num_samples):
canton_name = faker.canton_name()
assert isinstance(canton_name, str)
assert any(canton_name == cantons[1] for cantons in DeChAddressPro... | TestDeCh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.