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 | arrow-py__arrow | arrow/locales.py | {
"start": 68929,
"end": 72499
} | class ____(Locale):
names = ["cs", "cs-cz"]
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "Teď",
"second": {"past": "vteřina", "future": "vteřina"},
"seconds": {
"zero": "vteřina",
"past": "{0} sekundami",
"... | CzechLocale |
python | altair-viz__altair | tools/vega_expr.py | {
"start": 7014,
"end": 8242
} | class ____(_RSTRenderer):
def __init__(self) -> None:
super().__init__()
def link(self, token: Token, state: BlockState) -> str:
"""Store link url, for appending at the end of doc."""
attrs = token["attrs"]
url = expand_urls(attrs["url"])
text = self.render_children(toke... | RSTRenderer |
python | kubernetes-client__python | kubernetes/base/config/kube_config_test.py | {
"start": 15803,
"end": 63243
} | class ____(BaseTestCase):
TEST_KUBE_CONFIG = {
"current-context": "no_user",
"contexts": [
{
"name": "no_user",
"context": {
"cluster": "default"
}
},
{
"name": "simple_token",
... | TestKubeConfigLoader |
python | getsentry__sentry | src/sentry/taskworker/scheduler/schedules.py | {
"start": 3100,
"end": 7190
} | class ____(Schedule):
"""
Task schedules defined as crontab expressions.
crontab expressions naturally align to clock intervals. For example
an interval of `crontab(minute="*/2")` will spawn on the even numbered minutes.
If a crontab schedule loses its last_run state, it will assume that
one o... | CrontabSchedule |
python | google__jax | tests/fft_test.py | {
"start": 2895,
"end": 17147
} | class ____(jtu.JaxTestCase):
def testLaxFftAcceptsStringTypes(self):
rng = jtu.rand_default(self.rng())
x = rng((10,), np.complex64)
self.assertAllClose(np.fft.fft(x).astype(np.complex64),
lax.fft(x, "FFT", fft_lengths=(10,)))
self.assertAllClose(np.fft.fft(x).astype(np.comple... | FftTest |
python | astropy__astropy | astropy/io/votable/validator/result.py | {
"start": 411,
"end": 11779
} | class ____:
def __init__(self, url, root="results", timeout=10):
self.url = url
m = hashlib.md5(usedforsecurity=False)
m.update(url)
self._hash = m.hexdigest()
self._root = root
self._path = os.path.join(self._hash[0:2], self._hash[2:4], self._hash[4:])
if not... | Result |
python | plotly__plotly.py | _plotly_utils/png.py | {
"start": 10392,
"end": 10571
} | class ____(Error):
"""
Problem with input file format.
In other words, PNG file does not conform to
the specification in some way and is invalid.
"""
| FormatError |
python | prabhupant__python-ds | data_structures/binary_trees/array_to_binary_tree.py | {
"start": 198,
"end": 679
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def create_tree(arr):
curr_ptr = 0
child_ptr = 0
root = Node(arr[0])
curr_node = root
while i < (len(arr) - 1)/2:
curr_ptr = arr[i]
child_ptr = i + 1
left_... | Node |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 15305,
"end": 16039
} | class ____(sqltypes.TIMESTAMP):
"""MySQL TIMESTAMP type."""
__visit_name__ = "TIMESTAMP"
def __init__(self, timezone: bool = False, fsp: Optional[int] = None):
"""Construct a MySQL TIMESTAMP type.
:param timezone: not used by the MySQL dialect.
:param fsp: fractional seconds preci... | TIMESTAMP |
python | walkccc__LeetCode | solutions/2611. Mice and Cheese/2611.py | {
"start": 0,
"end": 233
} | class ____:
def miceAndCheese(
self,
reward1: list[int],
reward2: list[int],
k: int,
) -> int:
return (sum(reward2) +
sum(heapq.nlargest(k, (a - b for a, b in zip(reward1, reward2)))))
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec1.py | {
"start": 634,
"end": 1115
} | class ____(Protocol[P]):
def __call__(self, *args: P.args, **kwargs: P.kwargs): ...
# This should generate an error because P cannot be used with other
# type arguments.
def func3(x: SomeWrapper[P, int]):
pass
# This should generate an error because P cannot be used with other
# type arguments.
def func4(x:... | SomeWrapper |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project_forms.py | {
"start": 21910,
"end": 23392
} | class ____(TestCase):
def setUp(self):
# User with connection
# User without connection
self.user_github = get(User)
self.social_github = get(
SocialAccount, user=self.user_github, provider=GitHubProvider.id
)
self.user_email = get(User)
def test_form... | TestProjectPrevalidationForms |
python | kamyu104__LeetCode-Solutions | Python/target-sum.py | {
"start": 54,
"end": 634
} | class ____(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
def subsetSum(nums, S):
dp = collections.defaultdict(int)
dp[0] = 1
for n in nums:
for i in reversed(xr... | Solution |
python | sphinx-doc__sphinx | sphinx/domains/python/_object.py | {
"start": 4963,
"end": 5019
} | class ____(PyXrefMixin, TypedField):
pass
| PyTypedField |
python | huggingface__transformers | src/transformers/models/timesfm/modular_timesfm.py | {
"start": 3194,
"end": 3925
} | class ____(nn.Module):
"""TimesFM residual block."""
def __init__(self, input_dims, hidden_dims, output_dims):
super().__init__()
self.input_dims = input_dims
self.hidden_dims = hidden_dims
self.output_dims = output_dims
self.input_layer = nn.Linear(input_dims, hidden_d... | TimesFmResidualBlock |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_indexing.py | {
"start": 24413,
"end": 25293
} | class ____:
@pytest.mark.parametrize("tz", ["US/Pacific", None])
def test_putmask_dt64(self, tz):
# GH#37968
dti = date_range("2016-01-01", periods=9, tz=tz)
idx = IntervalIndex.from_breaks(dti)
mask = np.zeros(idx.shape, dtype=bool)
mask[0:3] = True
result = idx... | TestPutmask |
python | pypa__warehouse | warehouse/legacy/api/xmlrpc/cache/interfaces.py | {
"start": 118,
"end": 1031
} | class ____(Interface):
def create_service(context, request):
"""
Create the service, given the context and request for which it is being
created for.
"""
def fetch(func, args, kwargs, key, tag, expire):
"""
Gets cached function return value from the cache or call... | IXMLRPCCache |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/newType1.py | {
"start": 2066,
"end": 2240
} | class ____(AbstractBase):
def method1(self, /) -> int:
return 0
NewDerived = NewType("NewDerived", AbstractBase)
new_derived = NewDerived(DerivedBase())
| DerivedBase |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 3313,
"end": 4022
} | class ____(GreatExpectationsValidationError):
def __init__(self, message, validation_error=None, field_name=None) -> None:
if validation_error is not None:
if (
validation_error
and validation_error.messages
and isinstance(validation_error.messages... | InvalidBaseYamlConfigError |
python | dask__dask | dask/optimization.py | {
"start": 13961,
"end": 32408
} | class ____(Enum):
token = 0
def __repr__(self) -> str:
return "<default>"
_default = Default.token
def fuse(
dsk,
keys=None,
dependencies=None,
ave_width=_default,
max_width=_default,
max_height=_default,
max_depth_new_edges=_default,
rename_keys=_default,
):
"""... | Default |
python | doocs__leetcode | solution/1200-1299/1278.Palindrome Partitioning III/Solution.py | {
"start": 0,
"end": 730
} | class ____:
def palindromePartition(self, s: str, k: int) -> int:
n = len(s)
g = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = int(s[i] != s[j])
if i + 1 < j:
g[i][j] += g[i + 1][... | Solution |
python | google__jax | jax/_src/util.py | {
"start": 23455,
"end": 24014
} | class ____(Generic[T]):
elts_set: set[T]
elts_list: list[T]
def __init__(self):
self.elts_set = set()
self.elts_list = []
def add(self, elt: T) -> None:
if elt not in self.elts_set:
self.elts_set.add(elt)
self.elts_list.append(elt)
def update(self, elts: Seq[T]) -> None:
for e i... | OrderedSet |
python | davidhalter__jedi | jedi/api/classes.py | {
"start": 20916,
"end": 25147
} | class ____(BaseName):
"""
``Completion`` objects are returned from :meth:`.Script.complete`. They
provide additional information about a completion.
"""
def __init__(self, inference_state, name, stack, like_name_length,
is_fuzzy, cached_name=None):
super().__init__(inference... | Completion |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 14644,
"end": 15801
} | class ____(Node):
# stats a list of StatNode
child_attrs = ["stats"]
@staticmethod
def create_analysed(pos, env, **kw):
node = StatListNode(pos, **kw)
return node # No node-specific analysis needed
def analyse_declarations(self, env):
#print "StatListNode.analyse_decl... | StatListNode |
python | dagster-io__dagster | python_modules/libraries/dagster-msteams/dagster_msteams_tests/test_hooks.py | {
"start": 460,
"end": 5470
} | class ____(Exception):
pass
def my_message_fn(_):
return "Some custom text"
@op
def pass_op(_):
pass
@op
def fail_op(_):
raise SomeUserException()
@pytest.mark.parametrize(
"webhook_url",
[
LEGACY_WEBHOOK_URL,
WEBHOOK_URL,
],
)
def test_failure_hook_with_pythonic_reso... | SomeUserException |
python | tiangolo__fastapi | tests/test_additional_responses_router.py | {
"start": 114,
"end": 5229
} | class ____(BaseModel):
message: str
app = FastAPI()
router = APIRouter()
@router.get("/a", responses={501: {"description": "Error 1"}})
async def a():
return "a"
@router.get(
"/b",
responses={
502: {"description": "Error 2"},
"4XX": {"description": "Error with range, upper"},
}... | ResponseModel |
python | doocs__leetcode | solution/1200-1299/1250.Check If It Is a Good Array/Solution.py | {
"start": 0,
"end": 106
} | class ____:
def isGoodArray(self, nums: List[int]) -> bool:
return reduce(gcd, nums) == 1
| Solution |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py | {
"start": 22832,
"end": 23113
} | class ____(GenericForSequenceClassification, HunYuanDenseV1PreTrainedModel):
pass
__all__ = [
"HunYuanDenseV1ForCausalLM",
"HunYuanDenseV1Model",
"HunYuanDenseV1PreTrainedModel",
"HunYuanDenseV1ForSequenceClassification",
]
| HunYuanDenseV1ForSequenceClassification |
python | pytest-dev__pytest | testing/test_config.py | {
"start": 102462,
"end": 103860
} | class ____:
"""Tests for the deprecation of config.inicfg."""
def test_inicfg_deprecated(self, pytester: Pytester) -> None:
"""Test that accessing config.inicfg issues a deprecation warning."""
pytester.makeini(
"""
[pytest]
minversion = 3.0
"""
... | TestInicfgDeprecation |
python | pytorch__pytorch | test/distributed/test_functional_api.py | {
"start": 15215,
"end": 15655
} | class ____(MultiThreadedTestCase):
@property
def world_size(self):
return 2
def setUp(self):
super().setUp()
self._spawn_threads()
def test_all_reduce(self):
x = torch.rand([4], requires_grad=True)
y = torch.rand([4], requires_grad=True)
out = ft_c.all_r... | TestGradCollectives |
python | tensorflow__tensorflow | tensorflow/python/training/coordinator_test.py | {
"start": 1872,
"end": 10062
} | class ____(test.TestCase):
def testStopAPI(self):
coord = coordinator.Coordinator()
self.assertFalse(coord.should_stop())
self.assertFalse(coord.wait_for_stop(0.01))
coord.request_stop()
self.assertTrue(coord.should_stop())
self.assertTrue(coord.wait_for_stop(0.01))
def testStopAsync(self)... | CoordinatorTest |
python | ray-project__ray | rllib/connectors/agent/obs_preproc.py | {
"start": 429,
"end": 2520
} | class ____(AgentConnector):
"""A connector that wraps around existing RLlib observation preprocessors.
This includes:
- OneHotPreprocessor for Discrete and Multi-Discrete spaces.
- GenericPixelPreprocessor and AtariRamPreprocessor for Atari spaces.
- TupleFlatteningPreprocessor and DictFlatteningPr... | ObsPreprocessorConnector |
python | keras-team__keras | keras/src/metrics/confusion_metrics.py | {
"start": 9603,
"end": 15874
} | class ____(Metric):
"""Computes the precision of the predictions with respect to the labels.
The metric creates two local variables, `true_positives` and
`false_positives` that are used to compute the precision. This value is
ultimately returned as `precision`, an idempotent operation that simply
d... | Precision |
python | EpistasisLab__tpot | tpot/search_spaces/tuple_index.py | {
"start": 1504,
"end": 2414
} | class ____():
"""
TPOT uses tuples to create a unique id for some pipeline search spaces. However, tuples sometimes don't interact correctly with pandas indexes.
This class is a wrapper around a tuple that allows it to be used as a key in a dictionary, without it being an itereable.
An alternative coul... | TupleIndex |
python | cython__cython | Cython/Compiler/Tests/TestGrammar.py | {
"start": 2233,
"end": 5086
} | class ____(CythonTest):
def test_invalid_number_literals(self):
for literal in INVALID_UNDERSCORE_LITERALS:
for expression in ['%s', '1 + %s', '%s + 1', '2 * %s', '%s * 2']:
code = 'x = ' + expression % literal
try:
self.fragment('''\
... | TestGrammar |
python | python-openxml__python-docx | src/docx/text/parfmt.py | {
"start": 198,
"end": 10339
} | class ____(ElementProxy):
"""Provides access to paragraph formatting such as justification, indentation, line
spacing, space before and after, and widow/orphan control."""
@property
def alignment(self):
"""A member of the :ref:`WdParagraphAlignment` enumeration specifying the
justificat... | ParagraphFormat |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 15603,
"end": 17023
} | class ____(Widget):
"""A representation of ``st.date_input``."""
_value: DateValue | None | InitialValue
proto: DateInputProto = field(repr=False)
label: str
min: date
max: date
is_range: bool
help: str
form_id: str
def __init__(self, proto: DateInputProto, root: ElementTree) -... | DateInput |
python | huggingface__transformers | tests/models/llava_next/test_image_processing_llava_next.py | {
"start": 3704,
"end": 13212
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = LlavaNextImageProcessor if is_vision_available() else None
fast_image_processing_class = LlavaNextImageProcessorFast if is_torchvision_available() else None
# Copied from tests.models.clip.test_image_processing_clip.CLIPImage... | LlavaNextImageProcessingTest |
python | geekcomputers__Python | Python Programs/Program to reverse Linked List( Recursive solution).py | {
"start": 135,
"end": 1207
} | class ____:
def __init__(self, data):
self.data = data
self.next = None
def reverseLinkedListRec(head):
if head is None:
return None
if head.next is None:
return head
smallhead = reverseLinkedListRec(head.next)
head.next.next = head
head.next = None
return s... | Node |
python | pypa__pip | src/pip/_vendor/packaging/utils.py | {
"start": 614,
"end": 744
} | class ____(ValueError):
"""
An invalid wheel filename was found, users should refer to PEP 427.
"""
| InvalidWheelFilename |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 16866,
"end": 16992
} | class ____(OpcodeWithArg): # Arg: Jump offset to finally block
_FLAGS = HAS_JREL | HAS_ARGUMENT
__slots__ = ()
| CALL_FINALLY |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 5803,
"end": 6083
} | class ____:
def setup(self):
N = 1_000_000
d = 1e-5
arr = make_array(N, d, np.nan, np.float64)
self.sp_arr = SparseArray(arr)
def time_integer_indexing(self):
self.sp_arr[78]
def time_slice(self):
self.sp_arr[1:]
| GetItem |
python | tensorflow__tensorflow | tensorflow/python/framework/subscribe_test.py | {
"start": 1413,
"end": 13247
} | class ____(test_util.TensorFlowTestCase):
def _ExpectSubscribedIdentities(self, container):
"""Convenience function to test a container of subscribed identities."""
self.assertTrue(
all(subscribe._is_subscribed_identity(x) for x in container))
@test_util.run_deprecated_v1
def testSideEffect(self... | SubscribeTest |
python | pytorch__pytorch | test/distributed/test_c10d_gloo.py | {
"start": 6830,
"end": 7542
} | class ____(TestCase):
@requires_gloo()
@retry_on_connect_failures
def test_logging_init(self):
os.environ["WORLD_SIZE"] = "1"
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = str(common.find_free_port())
os.environ["RANK"] = "0"
previous_handlers =... | RendezvousEnvTest |
python | mlflow__mlflow | mlflow/entities/webhook.py | {
"start": 589,
"end": 1148
} | class ____(str, Enum):
ACTIVE = "ACTIVE"
DISABLED = "DISABLED"
def __str__(self) -> str:
return self.value
@classmethod
def from_proto(cls, proto: int) -> Self:
proto_name = ProtoWebhookStatus.Name(proto)
try:
return cls(proto_name)
except ValueError:
... | WebhookStatus |
python | sympy__sympy | sympy/printing/rust.py | {
"start": 7398,
"end": 8055
} | class ____(Expr):
"""
The type casting operator of the Rust language.
"""
def __init__(self, expr, type_) -> None:
super().__init__()
self.explicit = expr.is_integer and type_ is not integer
self._assumptions = expr._assumptions
if self.explicit:
setattr(self... | TypeCast |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-linkedin-ads/components.py | {
"start": 1466,
"end": 3020
} | class ____(HttpClient):
"""
A custom HTTP client that safely validates query parameters, ensuring that the symbols ():,% are preserved
during UTF-8 encoding.
"""
def _create_prepared_request(
self,
http_method: str,
url: str,
dedupe_query_params: bool = False,
... | SafeHttpClient |
python | kamyu104__LeetCode-Solutions | Python/find-largest-value-in-each-tree-row.py | {
"start": 664,
"end": 1042
} | class ____(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
curr = [root]
while any(curr):
result.append(max(node.val for node in curr))
curr = [child for node in curr for child in (node... | Solution2 |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 6078,
"end": 6367
} | class ____(Enum):
DYNAMIC_CONTROL_FLOW = auto()
ANTI_PATTERN = auto()
STANDARD_LIBRARY = auto()
CONSTRAINT_VIOLATION = auto()
DYNAMIC_DIM = auto()
INVALID_INPUT = auto()
INVALID_OUTPUT = auto()
UNSUPPORTED_ALIASED_MUTATED_DYNAMIC_INPUTS = auto()
| UserErrorType |
python | PrefectHQ__prefect | src/prefect/events/schemas/labelling.py | {
"start": 2131,
"end": 3103
} | class ____(RootModel[Dict[str, str]]):
def keys(self) -> Iterable[str]:
return self.root.keys()
def items(self) -> Iterable[Tuple[str, str]]:
return self.root.items()
def __getitem__(self, label: str) -> str:
return self.root[label]
def __setitem__(self, label: str, value: str... | Labelled |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 19217,
"end": 19357
} | class ____(IntFlag):
"""A class used as an enumerable flag for formatting an outline font."""
italic = 1
bold = 2
| OutlineFontFlag |
python | pandas-dev__pandas | pandas/tests/dtypes/test_missing.py | {
"start": 1496,
"end": 23386
} | class ____:
def test_0d_array(self):
assert isna(np.array(np.nan))
assert not isna(np.array(0.0))
assert not isna(np.array(0))
# test object dtype
assert isna(np.array(np.nan, dtype=object))
assert not isna(np.array(0.0, dtype=object))
assert not isna(np.array... | TestIsNA |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 94934,
"end": 97213
} | class ____(Request):
"""
Delete frames in a draft version.
:param version: Draft version ID
:type version: str
:param frames: Frame IDs to delete
:type frames: Sequence[str]
:param force: Ignore ongoing annotation tasks with this version as input
:type force: bool
"""
_service ... | DeleteFramesRequest |
python | psf__black | src/blib2to3/pytree.py | {
"start": 7046,
"end": 11332
} | class ____(Base):
"""Concrete implementation for interior nodes."""
fixers_applied: list[Any] | None
used_names: set[str] | None
def __init__(
self,
type: int,
children: list[NL],
context: Any | None = None,
prefix: str | None = None,
fixers_applied: lis... | Node |
python | django-haystack__django-haystack | haystack/management/commands/rebuild_index.py | {
"start": 149,
"end": 2177
} | class ____(BaseCommand):
help = "Completely rebuilds the search index by removing the old data and then updating." # noqa A003
def add_arguments(self, parser):
parser.add_argument(
"--noinput",
action="store_false",
dest="interactive",
default=True,
... | Command |
python | streamlit__streamlit | lib/streamlit/elements/plotly_chart.py | {
"start": 11882,
"end": 28104
} | class ____:
@overload
def plotly_chart(
self,
figure_or_data: FigureOrData,
use_container_width: bool | None = None,
*,
width: Width = "stretch",
height: Height = "content",
theme: Literal["streamlit"] | None = "streamlit",
key: Key | None = None,
... | PlotlyMixin |
python | getsentry__sentry | src/sentry/plugins/base/manager.py | {
"start": 389,
"end": 2893
} | class ____(InstanceManager):
def __iter__(self) -> Iterator[Plugin | Plugin2]:
return iter(self.all())
def __len__(self) -> int:
return sum(1 for i in self.all())
@overload
def all(self) -> Generator[Plugin]: ...
@overload
def all(self, *, version: Literal[2]) -> Generator[Plu... | PluginManager |
python | pydata__xarray | xarray/tests/test_plot.py | {
"start": 48002,
"end": 65735
} | class ____:
"""
Common tests for 2d plotting go here.
These tests assume that a staticmethod for `self.plotfunc` exists.
Should have the same name as the method.
"""
darray: DataArray
plotfunc: staticmethod
pass_in_axis: Callable
# Needs to be overridden in TestSurface for facet g... | Common2dMixin |
python | keras-team__keras | keras/src/layers/reshaping/reshape.py | {
"start": 257,
"end": 2650
} | class ____(Layer):
"""Layer that reshapes inputs into the given shape.
Args:
target_shape: Target shape. Tuple of integers, does not include the
samples dimension (batch size). One element of the `target_shape`
can be -1 in which case the missing value is inferred from the
... | Reshape |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 5384,
"end": 5969
} | class ____:
def kwonly_1(self, first, *, second, third):
"Normal positional with two positional only params."
def kwonly_2(self, *, first, second):
"Two positional only parameter."
def kwonly_3(self, *, first, second):
"Two positional only params."
def kwonly_4(self, *, first... | AbstractFoo |
python | pandas-dev__pandas | pandas/io/formats/info.py | {
"start": 10287,
"end": 12535
} | class ____(ABC):
"""
Base class for DataFrameInfo and SeriesInfo.
Parameters
----------
data : DataFrame or Series
Either dataframe or series.
memory_usage : bool or str, optional
If "deep", introspect the data deeply by interrogating object dtypes
for system-level memor... | _BaseInfo |
python | getsentry__sentry | src/sentry/dashboards/endpoints/organization_dashboards.py | {
"start": 2249,
"end": 4813
} | class ____(TypedDict):
prebuilt_id: PrebuiltDashboardId
title: str
# Prebuilt dashboards store minimal fields in the database. The actual dashboard and widget settings are
# coded in the frontend and we rely on matching prebuilt_id to populate the dashboard and widget display.
# Prebuilt dashboard database re... | PrebuiltDashboard |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_build_signature.py | {
"start": 2077,
"end": 2787
} | class ____:
__annotations__ = get_type_hints(use_annotations)
__signature__ = signature(use_signature)
def __init__(self, **kwargs):
# Check that we're being called with the expected arguments
assert set(kwargs) == {"testA", "testX", "testY"}
assert isinstance(kwargs["testA"], int)
... | ModelWithAlias |
python | lxml__lxml | src/lxml/tests/test_xmlschema.py | {
"start": 187,
"end": 14086
} | class ____(HelperTestCase):
def test_xmlschema(self):
tree_valid = self.parse('<a><b></b></a>')
tree_invalid = self.parse('<a><c></c></a>')
schema = self.parse('''
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType"... | ETreeXMLSchemaTestCase |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 4868,
"end": 5074
} | class ____(GQLResult):
typename__: Typename[Literal["PageInfo"]] = "PageInfo"
end_cursor: Optional[str] = Field(alias="endCursor")
has_next_page: bool = Field(alias="hasNextPage")
| PageInfoFragment |
python | ApeWorX__ape | tests/functional/test_provider.py | {
"start": 28015,
"end": 30759
} | class ____:
FAKE_PID = 12345678901234567890
@pytest.fixture(autouse=True)
def mock_process(self, mocker):
mock_process = mocker.MagicMock()
mock_process.pid = self.FAKE_PID
return mock_process
@pytest.fixture(autouse=True)
def popen_patch(self, mocker, mock_process):
... | TestSubprocessProvider |
python | django__django | tests/one_to_one/models.py | {
"start": 194,
"end": 378
} | class ____(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self):
return "%s the place" % self.name
| Place |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadImpl1.py | {
"start": 1254,
"end": 1810
} | class ____:
@overload
def method4(self, a: None) -> None: ...
@overload
def method4(self, a: list[T]) -> T: ...
def method4(self, a: list[T] | None) -> T | None: ...
@overload
def func5(a: list[T]) -> T: ...
@overload
def func5(a: None) -> None: ...
# This should generate an error because li... | ClassA |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataform.py | {
"start": 11364,
"end": 12213
} | class ____:
@mock.patch(HOOK_STR)
@mock.patch(WRITE_FILE_RESPONSE_STR)
def test_execute(self, _, hook_mock):
op = DataformWriteFileOperator(
task_id="write-file",
project_id=PROJECT_ID,
region=REGION,
repository_id=REPOSITORY_ID,
workspace_... | TestDataformWriteFileOperator |
python | joke2k__faker | tests/providers/test_emoji.py | {
"start": 43,
"end": 343
} | class ____(unittest.TestCase):
"""Test emoji provider methods"""
def setUp(self):
self.fake = Faker() # No locale specified, gets global for this provider
Faker.seed(0)
def test_emoji(self):
emoji = self.fake.emoji()
assert isinstance(emoji, str)
| TestGlobal |
python | jazzband__django-model-utils | tests/test_fields/test_field_tracker.py | {
"start": 15309,
"end": 16957
} | class ____(FieldTrackerMixin, TestCase):
tracked_class = TrackedNonFieldAttr
instance: TrackedNonFieldAttr
def setUp(self) -> None:
self.instance = self.tracked_class()
self.tracker = self.instance.tracker
def test_previous(self) -> None:
self.assertPrevious(rounded=None)
... | FieldTrackedModelAttributeTests |
python | python__mypy | mypy/semanal.py | {
"start": 352012,
"end": 352554
} | class ____(TrivialSyntheticTypeTranslator):
def visit_any(self, t: AnyType) -> Type:
if t.type_of_any == TypeOfAny.explicit:
return t.copy_modified(TypeOfAny.special_form)
return t
def visit_type_alias_type(self, t: TypeAliasType) -> Type:
return t.copy_modified(args=[a.acce... | MakeAnyNonExplicit |
python | realpython__materials | python-getter-setter/person.py | {
"start": 0,
"end": 359
} | class ____:
def __init__(self, name, birth_date):
self.name = name
self._birth_date = birth_date
def get_birth_date(self):
return self._birth_date
def set_birth_date(self, value, force=False):
if force:
self._birth_date = value
else:
raise At... | Person |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/type_dispatch_test.py | {
"start": 2131,
"end": 12267
} | class ____(test.TestCase):
def testVertical(self):
table = type_dispatch.TypeDispatchTable()
table.add_target(make_shape_function_type(None, None, None))
table.add_target(make_shape_function_type(None, None, 1))
table.add_target(make_shape_function_type(None, 1, 1))
table.add_target(make_shape_fu... | TypeDispatchTableTest |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 9745,
"end": 10863
} | class ____(BaseManager["IncidentTrigger"]):
CACHE_KEY = "incident:triggers:%s"
@classmethod
def _build_cache_key(cls, incident_id):
return cls.CACHE_KEY % incident_id
def get_for_incident(self, incident):
"""
Fetches the IncidentTriggers associated with an Incident. Attempts to... | IncidentTriggerManager |
python | doocs__leetcode | solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/Solution.py | {
"start": 0,
"end": 674
} | class ____:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
def check(matrix, mid, k, n):
count = 0
i, j = n - 1, 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
count += i + 1
j += 1
... | Solution |
python | bokeh__bokeh | src/bokeh/models/mappers.py | {
"start": 7103,
"end": 8419
} | class ____(ColorMapper):
''' Base class for continuous color mapper types.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
domain = List(Tuple(Instance("bokeh.models.renderers.GlyphRenderer"), Eith... | ContinuousColorMapper |
python | pytorch__pytorch | torch/utils/_ordered_set.py | {
"start": 322,
"end": 5658
} | class ____(MutableSet[T], Reversible[T]):
"""
Insertion ordered set, similar to OrderedDict.
"""
__slots__ = ("_dict",)
def __init__(self, iterable: Iterable[T] | None = None) -> None:
self._dict = dict.fromkeys(iterable, None) if iterable is not None else {}
@staticmethod
def _fr... | OrderedSet |
python | django__django | django/contrib/postgres/fields/ranges.py | {
"start": 5867,
"end": 6093
} | class ____(ContinuousRangeField):
base_field = models.DateTimeField
range_type = DateTimeTZRange
form_field = forms.DateTimeRangeField
def db_type(self, connection):
return "tstzrange"
| DateTimeRangeField |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/boolean_test.py | {
"start": 546,
"end": 1247
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device):
self.inputs = {
"input_one": torch.randint(0, 2, (M, N, K), device=device, dtype=torch.bool)
}
self.set_module_name("all")
def forward(self, input_one):
return torch.all(input_one)
# The gene... | AllBenchmark |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_create_user_job.py | {
"start": 17339,
"end": 18780
} | class ____:
"""Tests create user job service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"createUserJob": {
"labels": {"test_label": "test_label_value"},
},
},
show... | TestCreateUserJobServiceAccount |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_connector/google_cloud_storage_data_connector.py | {
"start": 962,
"end": 12395
} | class ____(FilePathDataConnector):
"""Extension of FilePathDataConnector used to connect to Google Cloud Storage (GCS).
Args:
datasource_name: The name of the Datasource associated with this DataConnector instance
data_asset_name: The name of the DataAsset using this DataConnector instance
... | GoogleCloudStorageDataConnector |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 6395,
"end": 7531
} | class ____(TestBaseItemExporter):
def _get_exporter(self, **kwargs):
return PickleItemExporter(self.output, **kwargs)
def _check_output(self):
self._assert_expected_item(pickle.loads(self.output.getvalue()))
def test_export_multiple_items(self):
i1 = self.item_class(name="hello", a... | TestPickleItemExporter |
python | doocs__leetcode | solution/1200-1299/1231.Divide Chocolate/Solution.py | {
"start": 0,
"end": 513
} | class ____:
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
def check(x: int) -> bool:
s = cnt = 0
for v in sweetness:
s += v
if s >= x:
s = 0
cnt += 1
return cnt > k
l, r =... | Solution |
python | pytorch__pytorch | torch/_dynamo/variables/dicts.py | {
"start": 40010,
"end": 40341
} | class ____(ConstDictVariable):
# Special class to avoid adding any guards on the nn module hook ids.
def install_dict_keys_match_guard(self) -> None:
pass
def install_dict_contains_guard(
self, tx: "InstructionTranslator", args: list[VariableTracker]
) -> None:
pass
| NNModuleHooksDictVariable |
python | tensorflow__tensorflow | tensorflow/python/ops/special_math_ops_test.py | {
"start": 44933,
"end": 46988
} | class ____(test.Benchmark):
cases = [
# Unary cases.
['ijk->i', 100],
['ijk->kji', 100],
# Regular matmul or batch matmul.
['ij,jk->ik', 500],
['ji,kj->ik', 500],
['bij,bjk->bik', 100],
['bji,bjk->bki', 100],
['ikl,kji->kl', 100],
['klj,lki->ij', 100],
... | EinsumBenchmark |
python | sympy__sympy | sympy/plotting/pygletplot/plot_camera.py | {
"start": 253,
"end": 3928
} | class ____:
min_dist = 0.05
max_dist = 500.0
min_ortho_dist = 100.0
max_ortho_dist = 10000.0
_default_dist = 6.0
_default_ortho_dist = 600.0
rot_presets = {
'xy': (0, 0, 0),
'xz': (-90, 0, 0),
'yz': (0, 90, 0),
'perspective': (-45, 0, -45)
}
def _... | PlotCamera |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 4403,
"end": 4534
} | class ____(enum.Enum):
@property
def name(self):
"""inherited"""
return super().name
| _NamePropertyInEnumMixin |
python | PyCQA__pylint | tests/functional/o/overloaded_operator.py | {
"start": 73,
"end": 435
} | class ____:
def __init__(self, array):
self.array = array
def __mul__(self, val):
return Myarray(val)
def astype(self):
return "ASTYPE", self
def randint(maximum):
if maximum is not None:
return Myarray([1, 2, 3]) * 2
return int(5)
print(randint(1).astype()) # we... | Myarray |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 58025,
"end": 78094
} | class ____:
def test_bad_input(self):
# Check that bad inputs raise errors
num_rows = 4
num_cols = 3
df = 5
M = np.full((num_rows, num_cols), 0.3)
U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
V = 0.7 * np.identity(num_cols) + np.full((... | TestMatrixT |
python | huggingface__transformers | tests/models/timm_wrapper/test_modeling_timm_wrapper.py | {
"start": 10124,
"end": 17280
} | class ____(unittest.TestCase):
# some popular ones
model_names_to_test = [
"vit_small_patch16_384.augreg_in21k_ft_in1k",
"resnet50.a1_in1k",
"tf_mobilenetv3_large_minimal_100.in1k",
"swin_tiny_patch4_window7_224.ms_in1k",
"ese_vovnet19b_dw.ra_in1k",
"hrnet_w18.ms_... | TimmWrapperModelIntegrationTest |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 127509,
"end": 127672
} | class ____(BaseModel, extra="forbid"):
type: "Snowball" = Field(..., description="")
language: "SnowballLanguage" = Field(..., description="")
| SnowballParams |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 11081,
"end": 11542
} | class ____:
test_ofb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SEED"),
["seed-ofb.txt"],
lambda key, **kwargs: SEED(binascii.unhexlify(key)),
lambda iv, **kwargs: OFB(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lambda backen... | TestSEEDModeOFB |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1121,
"end": 1200
} | class ____(ModelExtraA):
field2 = models.CharField(max_length=30)
| ModelExtraB |
python | Textualize__textual | tests/option_list/test_option_list_option_subclass.py | {
"start": 451,
"end": 1314
} | class ____(App[None]):
"""Test option list application."""
def compose(self) -> ComposeResult:
yield OptionList(*[OptionWithExtras(n) for n in range(100)])
async def test_option_list_with_subclassed_options() -> None:
"""It should be possible to build an option list with subclassed options."""
... | OptionListApp |
python | python-visualization__folium | folium/plugins/groupedlayercontrol.py | {
"start": 161,
"end": 3169
} | class ____(JSCSSMixin, MacroElement):
"""
Create a Layer Control with groups of overlays.
Parameters
----------
groups : dict
A dictionary where the keys are group names and the values are lists
of layer objects.
e.g. {
"Group 1": [layer1, layer2],
"G... | GroupedLayerControl |
python | keras-team__keras | keras/src/backend/torch/optimizers/torch_adamax.py | {
"start": 147,
"end": 1483
} | class ____(
torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adamax
):
def _parallel_update_step(
self,
grads,
variables,
learning_rate,
):
keras_variables = variables
variables = [v.value for v in variables]
dtype = variables[0].dtype
... | Adamax |
python | scipy__scipy | scipy/linalg/tests/test_decomp.py | {
"start": 84082,
"end": 87209
} | class ____:
def test_simple(self):
a = [[-149, -50, -154],
[537, 180, 546],
[-27, -9, -25]]
h1 = [[-149.0000, 42.2037, -156.3165],
[-537.6783, 152.5511, -554.9272],
[0, 0.0728, 2.4489]]
h, q = hessenberg(a, calc_q=1)
assert_array... | TestHessenberg |
python | doocs__leetcode | solution/0600-0699/0682.Baseball Game/Solution.py | {
"start": 0,
"end": 391
} | class ____:
def calPoints(self, operations: List[str]) -> int:
stk = []
for op in operations:
if op == "+":
stk.append(stk[-1] + stk[-2])
elif op == "D":
stk.append(stk[-1] << 1)
elif op == "C":
stk.pop()
... | Solution |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_indexing.py | {
"start": 54702,
"end": 61419
} | class ____:
@pytest.fixture
def orig(self):
cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"])
idx = Index(["h", "i", "j", "k", "l", "m", "n"])
values = [1, 1, 1, 1, 1, 1, 1]
orig = DataFrame({"cats": cats, "values": values}, index=idx)
return ... | TestLocILocDataFrameCategorical |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.