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 | tensorflow__tensorflow | tensorflow/python/data/experimental/benchmarks/snapshot_dataset_benchmark.py | {
"start": 1037,
"end": 6665
} | class ____(benchmark_base.DatasetBenchmarkBase):
"""Benchmarks for `tf.data.experimental.snapshot()`."""
def _makeSnapshotDirectory(self):
tmp_dir = test.get_temp_dir()
tmp_dir = os.path.join(tmp_dir, "snapshot")
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
os.mkdir(tmp_dir)
return ... | SnapshotDatasetBenchmark |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 28195,
"end": 29210
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a block document."""
name: Optional[BlockDocumentName] = Field(
default=None,
description=(
"The block document's name. Not required for anonymous block documents."
),
)
data: Dict[str, Any] ... | BlockDocumentCreate |
python | falconry__falcon | examples/recipes/msgspec_msgpack_handler.py | {
"start": 122,
"end": 529
} | class ____(media.BaseHandler):
def deserialize(
self,
stream: ReadableIO,
content_type: Optional[str],
content_length: Optional[int],
) -> object:
return msgpack.decode(stream.read())
def serialize(self, media: object, content_type: str) -> bytes:
return msgp... | MsgspecMessagePackHandler |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 24751,
"end": 26116
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.decoder_embed = nn.Linear(
config.hidden_size * len(config.intermediate_hidden_state_indices),
config.patch_size**2 * config.decoder_hidden_size,
bias=True,
)
self.decoder_p... | SegGptDecoder |
python | scipy__scipy | scipy/stats/_stats_py.py | {
"start": 342871,
"end": 418172
} | class ____:
r"""
Result of `scipy.stats.quantile_test`.
Attributes
----------
statistic: float
The statistic used to calculate the p-value; either ``T1``, the
number of observations less than or equal to the hypothesized quantile,
or ``T2``, the number of observations strict... | QuantileTestResult |
python | getsentry__sentry | src/sentry/testutils/helpers/task_runner.py | {
"start": 757,
"end": 3115
} | class ____:
def __init__(self) -> None:
self._active = False
self._orig_signal_send = TaskworkerTask._signal_send
self.queue: list[tuple[TaskworkerTask[Any, Any], tuple[Any, ...], dict[str, Any]]] = []
def _signal_send(
self,
task: TaskworkerTask[Any, Any],
args:... | _BurstState |
python | milvus-io__pymilvus | tests/test_bulk_writer_validators.py | {
"start": 2484,
"end": 4731
} | class ____:
def test_valid_list(self):
"""Test valid list of binary values"""
result = binary_vector_validator([1, 0, 1, 1, 0, 0, 1, 0], 8)
expected = np.packbits([1, 0, 1, 1, 0, 0, 1, 0], axis=-1).tolist()
assert result == expected
def test_invalid_list_length(self):
""... | TestBinaryVectorValidator |
python | ipython__ipython | IPython/external/qt_loaders.py | {
"start": 1171,
"end": 11863
} | class ____(importlib.abc.MetaPathFinder):
"""Import Hook that will guard against bad Qt imports
once IPython commits to a specific binding
"""
def __init__(self):
self.__forbidden = set()
def forbid(self, module_name):
sys.modules.pop(module_name, None)
self.__forbidden.add... | ImportDenier |
python | bokeh__bokeh | tests/unit/bokeh/core/test_enums.py | {
"start": 3127,
"end": 4547
} | class ____:
def test_basic(self) -> None:
e = bce.enumeration("foo", "bar", "baz")
assert isinstance(e, bce.Enumeration)
assert str(e) == "Enumeration(foo, bar, baz)"
assert [x for x in e] == ["foo", "bar", "baz"]
for x in ["foo", "bar", "baz"]:
assert x in e
... | Test_enumeration |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 14680,
"end": 19545
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: MoshiConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.c... | MoshiRotaryEmbedding |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 28314,
"end": 28856
} | class ____:
# Serializer.set_value() modifies the first parameter in-place.
s = serializers.Serializer()
def test_no_keys(self):
ret = {'a': 1}
self.s.set_value(ret, [], {'b': 2})
assert ret == {'a': 1, 'b': 2}
def test_one_key(self):
ret = {'a': 1}
self.s.set_... | TestSetValueMethod |
python | getsentry__sentry | src/sentry/sentry_metrics/consumers/indexer/slicing_router.py | {
"start": 685,
"end": 829
} | class ____(Exception):
"""
Exception raised when the configuration for the SlicingRouter is invalid.
"""
| SlicingConfigurationException |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/lsp.py | {
"start": 1347,
"end": 1423
} | class ____:
NONE = 0
FULL = 1
INCREMENTAL = 2
| TextDocumentSyncKind |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 164236,
"end": 170776
} | class ____:
# Preserving original test cases.
# Recomputed statistics and p-values with R t.test, e.g.
# options(digits=16)
# t.test(c(-1., 0., 1.), mu=2)
X1 = [-1., 0., 1.]
X2 = [0., 1., 2.]
T1_0 = 0.
P1_0 = 1.
T1_1 = -1.7320508075689
P1_1 = 0.2254033307585
T1_2 = -3.4641016... | TestStudentTest |
python | realpython__materials | django-pagination/terms/views.py | {
"start": 287,
"end": 1344
} | class ____(ListView):
paginate_by = 5
model = Keyword
def listing(request, page):
keywords = Keyword.objects.all().order_by("name")
paginator = Paginator(keywords, 2)
page_object = paginator.get_page(page)
page_object.adjusted_elided_pages = paginator.get_elided_page_range(page)
context = ... | KeywordListView |
python | OmkarPathak__pygorithm | tests/test_backtracking.py | {
"start": 2706,
"end": 4038
} | class ____(unittest.TestCase):
def test_kmp_search(self):
"""Test KMP string search"""
from pygorithm.strings import kmp_search
text = "ABABDABACDABABCABCABCABCABC"
pattern = "ABABCABCABCABC"
matches = kmp_search.kmp_search(text, pattern)
self.a... | TestNewStringAlgorithms |
python | realpython__materials | wordcount/tests/fixtures.py | {
"start": 295,
"end": 1021
} | class ____:
content: bytes
counts: tuple[int, ...]
@cached_property
def path(self) -> Path:
return Path("-")
def format_line(self, max_digits=None, selected=None):
if selected is None:
selected = 8 + 4 + 1
numbers = [
self.counts[i] for i in range(4)... | FakeFile |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/constants_ast.py | {
"start": 3579,
"end": 3754
} | class ____(Exception):
# a control flow exception which we raise in ConstantsVisitor when the
# number of constants in a module gets too large.
pass
| TooManyConstants |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_hitl.py | {
"start": 19872,
"end": 23213
} | class ____:
def test_init_with_options(self) -> None:
with pytest.raises(ValueError, match="Passing options to ApprovalOperator is not allowed."):
ApprovalOperator(
task_id="hitl_test",
subject="This is subject",
body="This is body",
... | TestApprovalOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1027407,
"end": 1028138
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
UpdateEnterpriseRepositoryProjectsSetting
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "enterprise", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A uniqu... | UpdateEnterpriseRepositoryProjectsSettingPayload |
python | django-guardian__django-guardian | guardian/testapp/tests/test_shortcuts.py | {
"start": 13615,
"end": 27431
} | class ____(TestCase):
"""
Tests get_users_with_perms function.
"""
def setUp(self):
self.obj1 = ContentType.objects.create(model="foo", app_label="guardian-tests")
self.obj2 = ContentType.objects.create(model="bar", app_label="guardian-tests")
self.user1 = User.objects.create(us... | GetUsersWithPermsTest |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 317,
"end": 1400
} | class ____(scale_discrete):
"""
Abstract class for manual scales
"""
values: InitVar[Sequence[Any] | dict[Any, Any]]
"""
Exact values the scale should map to.
"""
def __post_init__(self, values):
from collections.abc import Iterable, Sized
super().__post_init__()
... | _scale_manual |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 43390,
"end": 44116
} | class ____:
"""
Mix-in for all input elements (input, select, and textarea)
"""
@property
def name(self):
"""
Get/set the name of the element
"""
return self.get('name')
@name.setter
def name(self, value):
self.set('name', value)
@name.deleter
... | InputMixin |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 104889,
"end": 105632
} | class ____(TestCase):
def test_basic(self):
for size, expected in [
(0, []),
(1, [(True, True, '0')]),
(2, [(True, False, '0'), (False, True, '1')]),
(3, [(True, False, '0'), (False, False, '1'), (False, True, '2')]),
(
4,
... | MarkEndsTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass16.py | {
"start": 200,
"end": 270
} | class ____(C):
def __init__(self, x: int):
pass
@dataclass
| B |
python | wandb__wandb | wandb/automations/_generated/create_automation.py | {
"start": 220,
"end": 302
} | class ____(GQLResult):
result: Optional[CreateAutomationResult]
| CreateAutomation |
python | sphinx-doc__sphinx | sphinx/ext/todo.py | {
"start": 2801,
"end": 3218
} | class ____(SphinxDirective):
"""A list of all todo entries."""
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
# Simply insert an empty todolist node which will b... | TodoList |
python | django__django | tests/admin_views/admin.py | {
"start": 29157,
"end": 29323
} | class ____(admin.TabularInline):
model = Worker
def view_on_site(self, obj):
return "/worker_inline/%s/%s/" % (obj.surname, obj.name)
| WorkerInlineAdmin |
python | spack__spack | lib/spack/spack/environment/list.py | {
"start": 10492,
"end": 10604
} | class ____(SpecListError):
"""Error class for undefined references in Spack stacks."""
| UndefinedReferenceError |
python | davidhalter__parso | parso/python/errors.py | {
"start": 25415,
"end": 25683
} | class ____(SyntaxRule):
message = "import * only allowed at module level"
def is_issue(self, node):
return node.is_star_import() and self._normalizer.context.parent_context is not None
@ErrorFinder.register_rule(type='import_from')
| _ImportStarInFunction |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 16693,
"end": 23811
} | class ____:
"""
Decorator class for parametrizing a test function, yielding a set of new tests spawned
from the original generic test, each specialized for a specific set of test inputs. For
example, parametrizing a test across the set of ops will result in a test function per op.
The decision of h... | _TestParametrizer |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 200752,
"end": 206199
} | class ____(GeneratedAirbyteSource):
class HTTPSPublicWeb:
@public
def __init__(self, user_agent: Optional[bool] = None):
self.storage = "HTTPS"
self.user_agent = check.opt_bool_param(user_agent, "user_agent")
class GCSGoogleCloudStorage:
@public
def __ini... | FileSecureSource |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 223669,
"end": 225591
} | class ____(MemoryCopyNode):
"""
Assign a scalar to a slice. dst must be simple, scalar will be assigned
to a correct type and not just something assignable.
memslice1[...] = 0.0
memslice1[:] = 0.0
"""
def __init__(self, pos, dst):
super().__init__(pos, dst)
self.typ... | MemoryCopyScalar |
python | pytest-dev__pluggy | testing/test_hookcaller.py | {
"start": 724,
"end": 12289
} | class ____:
def __init__(self, hc: HookCaller) -> None:
self.hc = hc
def __call__(
self,
tryfirst: bool = False,
trylast: bool = False,
hookwrapper: bool = False,
wrapper: bool = False,
) -> Callable[[FuncT], FuncT]:
def wrap(func: FuncT) -> FuncT:
... | AddMeth |
python | walkccc__LeetCode | solutions/81. Search in Rotated Sorted Array II/81.py | {
"start": 0,
"end": 569
} | class ____:
def search(self, nums: list[int], target: int) -> bool:
l = 0
r = len(nums) - 1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return True
if nums[l] == nums[m] == nums[r]:
l += 1
r -= 1
elif nums[l] <= nums[m]: # nums[l..m] are sorted
... | Solution |
python | ray-project__ray | python/ray/train/v2/_internal/state/schema.py | {
"start": 1236,
"end": 2024
} | class ____(str, Enum):
"""Enumeration of the possible statuses for a Train run attempt."""
# ====== Active States ======
# The run attempt is waiting to be scheduled.
PENDING = "PENDING"
# The run attempt is currently in progress.
RUNNING = "RUNNING"
# ===== Terminal States =====
# The... | RunAttemptStatus |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_alloy_db.py | {
"start": 69577,
"end": 73357
} | class ____:
def setup_method(self):
self.operator = AlloyDBDeleteUserOperator(
task_id=TEST_TASK_ID,
user_id=TEST_USER_ID,
cluster_id=TEST_CLUSTER_ID,
project_id=TEST_GCP_PROJECT,
location=TEST_GCP_REGION,
gcp_conn_id=TEST_GCP_CONN_ID,
... | TestAlloyDBDeleteUserOperator |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 11,
"end": 144
} | class ____(
Aaaaaaaaaaaaaaaaa,
Bbbbbbbbbbbbbbbb,
DDDDDDDDDDDDDDDD,
EEEEEEEEEEEEEE,
metaclass=meta,
):
pass
| Test |
python | tensorflow__tensorflow | tensorflow/python/keras/combinations.py | {
"start": 2271,
"end": 2753
} | class ____(test_combinations.TestCombination):
"""Combination for Keras test mode.
It by default includes v1_session, v2_eager and v2_tf_function.
"""
def context_managers(self, kwargs):
run_eagerly = kwargs.pop('run_eagerly', None)
if run_eagerly is not None:
return [testing_utils.run_eagerly_... | KerasModeCombination |
python | wandb__wandb | tests/system_tests/test_functional/test_tensorboard/test_keras_tb_callback.py | {
"start": 233,
"end": 2047
} | class ____(keras.Model):
def build(self, _):
self.dense = keras.layers.Dense(10)
def call(self, x):
outputs = self.dense(x)
tf.summary.histogram("outputs", outputs)
return outputs
def test_tb_callback(wandb_backend_spy):
np.random.seed(42)
with wandb.init(sync_tensorb... | MyModel |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 17785,
"end": 22788
} | class ____(_expr_core.OperatorMixin):
_schema: t.ClassVar[_TypeMap[Literal["object"]]] = {"type": "object"}
def __init__(self, expr: IntoExpression) -> None:
self.expr = expr
def to_dict(self) -> dict[str, str]:
return {"expr": repr(self.expr)}
def _to_expr(self) -> str:
retur... | SelectionExpression |
python | wandb__wandb | wandb/sdk/launch/sweeps/scheduler.py | {
"start": 2361,
"end": 26868
} | class ____(ABC):
"""A controller/agent that populates a Launch RunQueue from a hyperparameter sweep."""
PLACEHOLDER_URI = "placeholder-uri-scheduler"
SWEEP_JOB_TYPE = "sweep-controller"
ENTRYPOINT = ["wandb", "scheduler", "WANDB_SWEEP_ID"]
def __init__(
self,
api: "Api",
*a... | Scheduler |
python | scipy__scipy | scipy/io/_harwell_boeing/tests/test_hb.py | {
"start": 1963,
"end": 2516
} | class ____:
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file, spmatrix=False)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):
... | TestHBReadWrite |
python | ansible__ansible | lib/ansible/module_utils/_internal/_json/_profiles/__init__.py | {
"start": 3234,
"end": 10629
} | class ____(t.Generic[_T_encoder, _T_decoder]):
serialize_map: t.ClassVar[dict[type, t.Callable]]
"""
Each concrete non-JSON type must be included in this mapping to support serialization.
Including a JSON type in the mapping allows for overriding or disabling of serialization of that type.
"""
... | _JSONSerializationProfile |
python | gevent__gevent | src/gevent/events.py | {
"start": 11286,
"end": 11832
} | class ____(IGeventWillPatchEvent):
"""
An event emitted *before* gevent begins patching a specific module.
Both *source* and *target* attributes are module objects.
"""
module_name = Attribute("The name of the module being patched. "
"This is the same as ``target.__name... | IGeventWillPatchModuleEvent |
python | PrefectHQ__prefect | tests/server/models/test_task_runs.py | {
"start": 27452,
"end": 29929
} | class ____:
@pytest.fixture
async def task_run_1(self, session, flow_run):
model = await models.task_runs.create_task_run(
session=session,
task_run=schemas.core.TaskRun(
flow_run_id=flow_run.id,
task_key="my-key-1",
dynamic_key="0"... | TestPreventOrphanedConcurrencySlots |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/legendgrouptitle/_font.py | {
"start": 233,
"end": 9962
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary.legendgrouptitle"
_path_str = "scatterternary.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | dagster-io__dagster | docs/sphinx/_ext/sphinx-mdx-builder/tests/test_mdx_builder.py | {
"start": 214,
"end": 12306
} | class ____:
"""Test class for the MDX builder functionality."""
@pytest.fixture
def temp_dir(self):
"""Create a temporary directory for test files."""
temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
@pytest.fixture
def test_docs_dir(self):
... | TestMdxBuilder |
python | getsentry__sentry | src/sentry/api/serializers/models/event.py | {
"start": 23552,
"end": 25241
} | class ____(EventSerializer):
"""
Event serializer for the minimum event data needed to send to an external service. This
should be used for Integrations that need to include event data.
"""
def serialize(self, obj, attrs, user, **kwargs):
from sentry.notifications.utils import get_notificat... | ExternalEventSerializer |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 2884,
"end": 4076
} | class ____(containers.VerticalGroup):
"""Demonstrates Checkboxes."""
DEFAULT_CLASSES = "column"
DEFAULT_CSS = """
Checkboxes {
height: auto;
Checkbox, RadioButton { width: 1fr; }
&>HorizontalGroup > * { width: 1fr; }
}
"""
CHECKBOXES_MD = """\
## Checkboxes, Radio ... | Checkboxes |
python | kamyu104__LeetCode-Solutions | Python/maximum-fruits-harvested-after-at-most-k-steps.py | {
"start": 29,
"end": 989
} | class ____(object):
def maxTotalFruits(self, fruits, startPos, k):
"""
:type fruits: List[List[int]]
:type startPos: int
:type k: int
:rtype: int
"""
max_pos = max(startPos, fruits[-1][0])
cnt = [0]*(1+max_pos)
for p, a in fruits:
c... | Solution |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/Binary-tree/left-view.py | {
"start": 1000,
"end": 1128
} | class ____:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
# Tree Class
| Node |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-deepinfra/llama_index/llms/deepinfra/types.py | {
"start": 210,
"end": 465
} | class ____(BaseModel):
id: str
"""The ID of the tool call."""
function: Function
"""The function that the model called."""
type: Literal["function"]
"""The type of the tool. Currently, only `function` is supported."""
| ToolCallMessage |
python | realpython__materials | inheritance-and-composition/choosing/productivity.py | {
"start": 625,
"end": 738
} | class ____:
def perform_duties(self, hours):
return f"screams and yells for {hours} hours."
| ManagerRole |
python | Pylons__pyramid | tests/test_security.py | {
"start": 12705,
"end": 13886
} | class ____(unittest.TestCase):
def setUp(self):
testing.setUp()
def tearDown(self):
testing.tearDown()
def test_no_authentication_policy(self):
from pyramid.security import Everyone
request = _makeRequest()
self.assertEqual(request.effective_principals, [Everyone])... | TestEffectivePrincipals |
python | huggingface__transformers | tests/models/idefics/test_processing_idefics.py | {
"start": 1017,
"end": 7252
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = IdeficsProcessor
input_keys = ["pixel_values", "input_ids", "attention_mask", "image_attention_mask"]
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_proce... | IdeficsProcessorTest |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 10743,
"end": 11436
} | class ____(Structure):
_fields_ = (("_version", p_uint32),)
@property
def major(self):
return self._version >> 16 & 0xFFFF
@major.setter
def major(self, v):
self._version = (self._version & 0xFFFF) | (v << 16)
@property
def minor(self):
return self._version >> 8 & ... | mach_version_helper |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/vector.py | {
"start": 2072,
"end": 2504
} | class ____(Enum):
"""Enum representing the vector type,
See :ref:`oracle_vector_datatype` for background.
.. versionadded:: 2.0.43
"""
SPARSE = "SPARSE"
"""
A Sparse vector is a vector which has zero value for
most of its dimensions.
"""
DENSE = "DENSE"
"""
A Dense ve... | VectorStorageType |
python | econchick__interrogate | src/interrogate/coverage.py | {
"start": 2218,
"end": 2938
} | class ____(BaseInterrogateResult):
"""Coverage results for all files.
:attr int ret_code: return code of program (``0`` for success, ``1``
for fail).
:attr list(InterrogateFileResult) file_results: list of file
results associated with this program run.
"""
ret_code: int = attr.ib(i... | InterrogateResults |
python | encode__django-rest-framework | tests/test_one_to_one_with_inheritance.py | {
"start": 772,
"end": 1255
} | class ____(TestCase):
def test_multitable_inherited_model_fields_as_expected(self):
"""
Assert that the parent pointer field is not included in the fields
serialized fields
"""
child = ChildModel(name1='parent name', name2='child name')
serializer = DerivedModelSeria... | InheritedModelSerializationTests |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8574
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.marker.colorbar"
_path_str = "scattersmith.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*]... | Tickformatstop |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_write_a_graphic_frame_locks.py | {
"start": 297,
"end": 844
} | class ____(unittest.TestCase):
"""
Test the Drawing _write_a_graphic_frame_locks() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_a_graphic_frame_locks(self):
"""Test the _write_a_grap... | TestWriteAgraphicFrameLocks |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 12862,
"end": 13231
} | class ____(SerializedAttributes.with_attributes(
'RNNAttributes',
checkpointable_objects=['states'],
copy_from=[LayerAttributes])):
"""RNN checkpointable objects + functions that are saved to the SavedModel.
List of all attributes:
All attributes from LayerAttributes (including CommonEndpoints)
... | RNNAttributes |
python | oauthlib__oauthlib | tests/oauth1/rfc5849/endpoints/test_base.py | {
"start": 10504,
"end": 14008
} | class ____(RequestValidator):
clients = ['foo']
nonces = [('foo', 'once', '1234567891', 'fez')]
owners = {'foo': ['abcdefghijklmnopqrstuvxyz', 'fez']}
assigned_realms = {('foo', 'abcdefghijklmnopqrstuvxyz'): 'photos'}
verifiers = {('foo', 'fez'): 'shibboleth'}
@property
... | ClientValidator |
python | jschneier__django-storages | storages/backends/dropbox.py | {
"start": 941,
"end": 2098
} | class ____(File):
def __init__(self, name, storage):
self.name = name
self._storage = storage
self._file = None
def _get_file(self):
if self._file is None:
self._file = SpooledTemporaryFile()
# As dropbox==9.3.0, the client returns a tuple
# (... | DropboxFile |
python | spack__spack | lib/spack/spack/llnl/util/lock.py | {
"start": 28626,
"end": 28873
} | class ____(LockError):
"""Raised when unable to downgrade from a write to a read lock."""
def __init__(self, path):
msg = "Cannot downgrade lock from write to read on file: %s" % path
super().__init__(msg)
| LockDowngradeError |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 22372,
"end": 23215
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_list_stored_info_types(self, mock_hook):
mock_hook.return_value.list_stored_info_types.return_value = mock.MagicMock()
operator = CloudDLPListStoredInfoTypesOperator(organization_id=ORGANIZATION_ID, tas... | TestCloudDLPListStoredInfoTypesOperator |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 75862,
"end": 79958
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Gemma3nTextConfig, device=None, layer_type=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_emb... | Gemma3nRotaryEmbedding |
python | django__django | tests/template_tests/syntax_tests/test_with.py | {
"start": 2465,
"end": 2641
} | class ____(SimpleTestCase):
def test_repr(self):
node = WithNode(nodelist=[], name="a", var="dict.key")
self.assertEqual(repr(node), "<WithNode>")
| WithNodeTests |
python | huggingface__transformers | src/transformers/models/mask2former/modeling_mask2former.py | {
"start": 99737,
"end": 102896
} | class ____(PreTrainedModel):
config: Mask2FormerConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
input_modalities = ("image",)
@torch.no_grad()
def _init_weights(self, module: nn.Module):
xavier_std = self.config.init_xavier_std
std = self.config.init_std
... | Mask2FormerPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/server/schemas/responses.py | {
"start": 19422,
"end": 19645
} | class ____(WorkQueueResponse, WorkQueueStatusDetail):
"""Combines a work queue and its status details into a single object"""
DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30
INACTIVITY_HEARTBEAT_MULTIPLE = 3
| WorkQueueWithStatus |
python | huggingface__transformers | tests/utils/test_core_model_loading.py | {
"start": 7313,
"end": 7494
} | class ____(nn.Module):
base_model_prefix = "model"
def __init__(self):
super().__init__()
self.model = DummyTopModel()
self.mlp = DummyMLP()
| DummyRoot |
python | apache__airflow | task-sdk/tests/task_sdk/bases/test_operator.py | {
"start": 40621,
"end": 40749
} | class ____(HelloWorldOperator):
def execute(self, context):
return super().execute(context)
| ExtendedHelloWorldOperator |
python | huggingface__transformers | examples/pytorch/old_test_xla_examples.py | {
"start": 1212,
"end": 2796
} | class ____(TestCasePlus):
def test_run_glue(self):
import xla_spawn
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
./examples/pytorch/text-classification/run_glue.py
--num_cores=8
./examples/pytorch/text-classification/run_glue.py
--... | TorchXLAExamplesTests |
python | ray-project__ray | python/ray/data/tests/test_download_expression.py | {
"start": 163,
"end": 1296
} | class ____:
"""Test DownloadExpr structural equality and basic properties."""
def test_download_expression_creation(self):
"""Test that download() creates a DownloadExpr with correct properties."""
expr = download("uri_column")
assert isinstance(expr, DownloadExpr)
assert expr.... | TestDownloadExpressionStructure |
python | plotly__plotly.py | plotly/graph_objs/pie/marker/_line.py | {
"start": 233,
"end": 4566
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie.marker"
_path_str = "pie.marker.line"
_valid_props = {"color", "colorsrc", "width", "widthsrc"}
@property
def color(self):
"""
Sets the color of the line enclosing each sector.
The 'color' property is a color and ... | Line |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_ecs.py | {
"start": 1024,
"end": 6332
} | class ____:
@pytest.fixture(autouse=True)
def _setup_test_cases(self, monkeypatch):
self.client = boto3.client("ecs", region_name="eu-west-3")
monkeypatch.setattr(EcsHook, "conn", self.client)
@pytest.fixture
def mock_describe_clusters(self):
"""Mock ``ECS.Client.describe_cluste... | TestCustomECSServiceWaiters |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 35530,
"end": 36327
} | class ____:
"""
Definition of a single field within a `Struct` DataType.
Parameters
----------
name
The name of the field within its parent `Struct`.
dtype
The `DataType` of the field's values.
"""
name: str
dtype: PolarsDataType
def __init__(self, name: str, d... | Field |
python | boto__boto3 | boto3/resources/collection.py | {
"start": 12266,
"end": 19113
} | class ____:
"""
A factory to create new
:py:class:`CollectionManager` and :py:class:`ResourceCollection`
subclasses from a :py:class:`~boto3.resources.model.Collection`
model. These subclasses include methods to perform batch operations.
"""
def load_from_definition(
self, resource_... | CollectionFactory |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 109779,
"end": 118860
} | class ____:
def _create_arrays(self):
return np.array([2]), np.array([3]), np.array([4]), (1,)
def test_one_arg_funcs(self):
argOne, _, _, tgtShape = self._create_arrays()
funcs = (random.exponential, random.standard_gamma,
random.chisquare, random.standard_t,
... | TestSingleEltArrayInput |
python | google__jax | jax/experimental/source_mapper/common.py | {
"start": 1017,
"end": 1126
} | class ____(Protocol):
def __call__(self, work_dir, fn, f_args, f_kwargs, **kwargs) -> Any:
...
| CompileFn |
python | ray-project__ray | python/ray/tune/search/sample.py | {
"start": 882,
"end": 2294
} | class ____:
"""Thin wrapper to ensure backwards compatibility between
new and old numpy randomness generators.
"""
_rng = None
def __init__(
self,
generator_or_seed: Optional[
Union["np_random_generator", np.random.RandomState, int]
] = None,
):
if g... | _BackwardsCompatibleNumpyRng |
python | rushter__MLAlgorithms | mla/ensemble/gbm.py | {
"start": 1632,
"end": 2008
} | class ____(Loss):
"""Logistic loss."""
def grad(self, actual, predicted):
return actual * expit(-actual * predicted)
def hess(self, actual, predicted):
expits = expit(predicted)
return expits * (1 - expits)
def transform(self, output):
# Apply logistic (sigmoid) functi... | LogisticLoss |
python | ansible__ansible | lib/ansible/_internal/_ssh/_ssh_agent.py | {
"start": 10680,
"end": 11018
} | class ____(PrivateKeyMsg):
type: KeyAlgo
p: mpint
q: mpint
g: mpint
y: mpint
x: mpint
comments: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
constraints: constraints = dataclasses.field(default=constraints(b''))
@dataclasses.dataclass(order=True, slots=... | DSAPrivateKeyMsg |
python | getsentry__sentry | src/sentry/incidents/subscription_processor.py | {
"start": 1988,
"end": 12620
} | class ____:
"""
Class for processing subscription updates for workflow engine. Accepts a subscription
and then can process one or more updates via `process_update`.
"""
def __init__(self, subscription: QuerySubscription) -> None:
self.subscription = subscription
self.detector: Detec... | SubscriptionProcessor |
python | google__jax | jax/_src/pallas/triton/lowering.py | {
"start": 21841,
"end": 97688
} | class ____:
arg_classes: Sequence[jax.typing.DTypeLike]
op: Callable[..., ir.Value]
def matches(self, avals: Sequence[jax_core.ShapedArray]) -> bool:
if len(avals) != len(self.arg_classes):
return False
return all(
jnp.issubdtype(aval.dtype, arg_class)
for aval, arg_class in zip(ava... | _Fallback |
python | altair-viz__altair | altair/utils/schemapi.py | {
"start": 37831,
"end": 38331
} | class ____(SchemaLike[Literal["object"]], Protocol):
"""
Represents the wrapped state of a conditional encoding or property.
Attributes
----------
condition
One or more (predicate, statement) pairs which each form a condition.
Notes
-----
- Can be extended with additional condi... | ConditionLike |
python | doocs__leetcode | solution/2100-2199/2166.Design Bitset/Solution.py | {
"start": 0,
"end": 1009
} | class ____:
def __init__(self, size: int):
self.a = ['0'] * size
self.b = ['1'] * size
self.cnt = 0
def fix(self, idx: int) -> None:
if self.a[idx] == '0':
self.a[idx] = '1'
self.cnt += 1
self.b[idx] = '0'
def unfix(self, idx: int) -> None:
... | Bitset |
python | django__django | django/template/loaders/base.py | {
"start": 61,
"end": 1636
} | class ____:
def __init__(self, engine):
self.engine = engine
def get_template(self, template_name, skip=None):
"""
Call self.get_template_sources() and return a Template object for
the first template matching template_name. If skip is provided, ignore
template origins in... | Loader |
python | huggingface__transformers | tests/pipelines/test_pipelines_automatic_speech_recognition.py | {
"start": 1754,
"end": 83306
} | class ____(unittest.TestCase):
model_mapping = dict(
(list(MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING.items()) if MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING else [])
+ (MODEL_FOR_CTC_MAPPING.items() if MODEL_FOR_CTC_MAPPING else [])
)
def get_test_pipeline(
self,
model,
tokenizer=No... | AutomaticSpeechRecognitionPipelineTests |
python | astropy__astropy | astropy/extern/configobj/configobj.py | {
"start": 11680,
"end": 11977
} | class ____(InterpolationEngine):
"""Behaves like ConfigParser."""
_cookie = '%'
_KEYCRE = re.compile(r"%\(([^)]*)\)s")
def _parse_match(self, match):
key = match.group(1)
value, section = self._fetch(key)
return key, value, section
| ConfigParserInterpolation |
python | ray-project__ray | python/ray/_private/ray_perf.py | {
"start": 346,
"end": 572
} | class ____:
def small_value(self):
return b"ok"
def small_value_arg(self, x):
return b"ok"
def small_value_batch(self, n):
ray.get([small_value.remote() for _ in range(n)])
@ray.remote
| Actor |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_parameters.py | {
"start": 493,
"end": 2427
} | class ____(ParameterTestMixin):
"""Tests for `astropy.cosmology.Parameter` H0 on a Cosmology.
H0 is a descriptor, which are tested by mixin, here with ``TestFLRW``.
These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the
args and kwargs for the cosmology class, respectively. See ``Test... | ParameterH0TestMixin |
python | scipy__scipy | scipy/optimize/tests/test_trustregion.py | {
"start": 273,
"end": 571
} | class ____:
""" This is for testing callbacks."""
def __init__(self):
self.count = 0
self.accum = None
def __call__(self, x):
self.count += 1
if self.accum is None:
self.accum = np.array(x)
else:
self.accum += x
| Accumulator |
python | urllib3__urllib3 | test/with_dummyserver/test_https.py | {
"start": 46921,
"end": 51798
} | class ____:
def test_can_validate_san(self, san_server: ServerConfig) -> None:
"""Ensure that urllib3 can validate SANs with IP addresses in them."""
with HTTPSConnectionPool(
san_server.host,
san_server.port,
cert_reqs="CERT_REQUIRED",
ca_certs=san_se... | TestHTTPS_Hostname |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 114499,
"end": 115200
} | class ____(nn.Module):
"""
Projection postprocessing for Perceiver. Can be used to project the channels of the decoder output to a lower
dimension.
Args:
in_channels (`int`):
Number of channels in the input.
out_channels (`int`):
Number of channels in the output.... | PerceiverProjectionPostprocessor |
python | PyCQA__pylint | tests/functional/r/redundant_unittest_assert.py | {
"start": 457,
"end": 1284
} | class ____(unittest.TestCase):
def test_something(self):
''' Simple test '''
some_var = 'It should be assertEqual'
# +1:[redundant-unittest-assert]
self.assertTrue('I meant assertEqual not assertTrue', some_var)
# +1:[redundant-unittest-assert]
self.assertFalse('I mea... | Tests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/pysqlite.py | {
"start": 16828,
"end": 17415
} | class ____(DATE):
def bind_processor( # type: ignore[override]
self, dialect: SQLiteDialect
) -> Optional[_BindProcessorType[Any]]:
if dialect.native_datetime:
return None
else:
return DATE.bind_processor(self, dialect)
def result_processor( # type: ignore[... | _SQLite_pysqliteDate |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_state_dict.py | {
"start": 4838,
"end": 50917
} | class ____(FSDPTest):
@property
def world_size(self):
return min(torch.accelerator.device_count(), 2)
def _broadcast_state_dict(self, state_dict):
return _broadcast_state_dict(self.rank, state_dict)
def _state_compare(self, model, model_new, assert_fn, state_generator="parameters"):
... | TestFSDPStateDict |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 536805,
"end": 537122
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("PullRequest", graphql_name="node")
| PullRequestEdge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.