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/flava/configuration_flava.py | {
"start": 17720,
"end": 32812
} | class ____(PreTrainedConfig):
r"""
[`FlavaConfig`] is the configuration class to store the configuration of a [`FlavaModel`]. It is used to
instantiate FLAVA model according to the specified arguments, defining the text model, image model, image codebook
and multimodal model configs. Instantiating a con... | FlavaConfig |
python | walkccc__LeetCode | solutions/1030. Matrix Cells in Distance Order/1030.py | {
"start": 0,
"end": 567
} | class ____:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> list[list[int]]:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
ans = []
q = collections.deque([(rCenter, cCenter)])
seen = {(rCenter, cCenter)}
while q:
i, j = q.popleft()
ans.append([i, j])
... | Solution |
python | django__django | tests/prefetch_related/tests.py | {
"start": 45257,
"end": 53245
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title="Winnie the Pooh")
book2 = Book.objects.create(title="Do you like green eggs and spam?")
book3 = Book.objects.create(title="Three Men In A Boat")
reader1 = Reader.objects.create(name="me... | GenericRelationTests |
python | h5py__h5py | h5py/tests/test_h5f.py | {
"start": 3008,
"end": 3929
} | class ____(TestCase):
def test_vlen_strings(self):
# Create file with dataset containing vlen arrays of vlen strings
dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestVlenStrings.test_vlen_strings')
fn_h5 = os.path.join(dn_tmp, 'test.h5')
try:
with File(fn_h5, mode='w'... | TestVlenData |
python | pypa__setuptools | setuptools/command/editable_wheel.py | {
"start": 31465,
"end": 32746
} | class ____: # MetaPathFinder
@classmethod
def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None: # type: ignore
# Top-level packages and modules (we know these exist in the FS)
if fullname in MAPPING:
pkg_path = MAPPING[fullname]
return cls._fin... | _EditableFinder |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-potholes-that-can-be-fixed.py | {
"start": 53,
"end": 1450
} | class ____(object):
def maxPotholes(self, road, budget):
"""
:type road: str
:type budget: int
:rtype: int
"""
def inplace_counting_sort(nums, reverse=False): # Time: O(n)
if not nums:
return
count = [0]*(max(nums)+1)
... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 2630,
"end": 2833
} | class ____(StrEnum):
SLACK = "slack"
MSTEAMS = "msteams"
DISCORD = "discord"
PAGERDUTY = "pagerduty"
OPSGENIE = "opsgenie"
EMAIL = "email"
SENTRY_APP = "sentry_app"
| ActionType |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py | {
"start": 6600,
"end": 10100
} | class ____(GoogleCloudBaseOperator):
"""
Enables one or more disabled alerting policies identified by filter parameter.
Inoperative in case the policy is already enabled.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:Stack... | StackdriverEnableAlertPoliciesOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 291045,
"end": 291823
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
RevokeEnterpriseOrganizationsMigratorRole
"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "login", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId")
... | RevokeEnterpriseOrganizationsMigratorRoleInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/test_articles.py | {
"start": 865,
"end": 4837
} | class ____(TestCase):
def _config(self) -> ConfigBuilder:
return (
ConfigBuilder()
.with_basic_auth_credentials("user@example.com", "password")
.with_subdomain("d3v-airbyte")
.with_start_date(ab_datetime_now().subtract(timedelta(hours=1)))
)
def _... | TestArticlesStream |
python | getsentry__sentry | src/sentry/api/endpoints/organization_auth_token_details.py | {
"start": 834,
"end": 3065
} | class ____(ControlSiloOrganizationEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ENTERPRISE
authentication_classes = (SessionNoAuthTokenAuthentication,)
permission_classes ... | OrganizationAuthTokenDetailsEndpoint |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/records/posts_records_builder.py | {
"start": 196,
"end": 487
} | class ____(ZendeskSupportRecordBuilder):
@classmethod
def posts_record(cls) -> "PostsRecordBuilder":
record_template = cls.extract_record("posts", __file__, NestedPath(["posts", 0]))
return cls(record_template, FieldPath("id"), FieldPath("updated_at"))
| PostsRecordBuilder |
python | sympy__sympy | sympy/functions/elementary/trigonometric.py | {
"start": 18450,
"end": 30742
} | class ____(TrigonometricFunction):
"""
The cosine function.
Returns the cosine of x (measured in radians).
Explanation
===========
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import cos, pi
>>> from sympy.abc import x
>>> cos(x*... | cos |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/hosting.py | {
"start": 8825,
"end": 9564
} | class ____:
"""Mixin to remove fields from serializers."""
FIELDS_TO_REMOVE = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.FIELDS_TO_REMOVE:
if field in self.fields:
del self.fields[field]
if field in ... | RemoveFieldsMixin |
python | astropy__astropy | astropy/__init__.py | {
"start": 3589,
"end": 4094
} | class ____(base_constants_version):
"""
The version of physical constants to use.
"""
# Maintainers: update when new constants are added
_value = "codata2022"
_versions = dict(
codata2022="codata2022",
codata2018="codata2018",
codata2014="codata2014",
codata2010... | physical_constants |
python | getsentry__sentry | src/sentry/new_migrations/migrations.py | {
"start": 234,
"end": 1731
} | class ____(Migration):
"""
Migrations subclassing this will perform safety checks to help ensure that they
won't cause production issues during deploy.
"""
# This flag is used to decide whether to run this migration in a transaction or not. Generally
# we don't want to run in a transaction here... | CheckedMigration |
python | getsentry__sentry-python | sentry_sdk/integrations/anthropic.py | {
"start": 1279,
"end": 15640
} | class ____(Integration):
identifier = "anthropic"
origin = f"auto.ai.{identifier}"
def __init__(self, include_prompts=True):
# type: (AnthropicIntegration, bool) -> None
self.include_prompts = include_prompts
@staticmethod
def setup_once():
# type: () -> None
versio... | AnthropicIntegration |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink33.py | {
"start": 315,
"end": 950
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink33.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 2690,
"end": 3269
} | class ____(NodeEvent):
__slots__ = 'tag', 'implicit', 'flow_style', 'nr_items'
def __init__(
self,
anchor,
tag,
implicit,
start_mark=None,
end_mark=None,
flow_style=None,
comment=None,
nr_items=None,
):
# type: (Any, Any, Any, ... | CollectionStartEvent |
python | walkccc__LeetCode | solutions/945. Minimum Increment to Make Array Unique/945.py | {
"start": 0,
"end": 242
} | class ____:
def minIncrementForUnique(self, nums: list[int]) -> int:
ans = 0
minAvailable = 0
for num in sorted(nums):
ans += max(minAvailable - num, 0)
minAvailable = max(minAvailable, num) + 1
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/utils.py | {
"start": 2151,
"end": 2741
} | class ____(AirbyteTracedException):
"""Raises the error if authenticated user doesn't have access to verify the grantted scopes."""
help_url = "https://shopify.dev/docs/api/usage/access-scopes#authenticated-access-scopes"
def __init__(self, response, **kwargs) -> None:
self.message = f"Reason: Sco... | ShopifyAccessScopesError |
python | mwaskom__seaborn | tests/_marks/test_line.py | {
"start": 5188,
"end": 5716
} | class ____:
# Most behaviors shared with Path and covered by above tests
def test_xy_data(self):
x = [1, 5, 3, np.nan, 2]
y = [1, 4, 2, 5, 3]
g = [1, 2, 1, 1, 2]
p = Plot(x=x, y=y, group=g).add(Line()).plot()
line1, line2 = p._figure.axes[0].get_lines()
assert... | TestLine |
python | jazzband__prettytable | tests/test_html.py | {
"start": 869,
"end": 21839
} | class ____:
def test_html_output(self, helper_table: PrettyTable) -> None:
result = helper_table.get_html_string()
assert (
result.strip()
== """
<table>
<thead>
<tr>
<th></th>
<th>Field 1</th>
<th>Field 2</th>
<th>F... | TestHtmlOutput |
python | django-debug-toolbar__django-debug-toolbar | tests/base.py | {
"start": 3740,
"end": 3840
} | class ____(BaseMixin, TransactionTestCase):
databases = {"default", "replica"}
| BaseMultiDBTestCase |
python | django__django | tests/admin_registration/models.py | {
"start": 180,
"end": 215
} | class ____(Person):
pass
| Traveler |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 19020,
"end": 19088
} | class ____(Sam2VideoMemoryFuser):
pass
| Sam3TrackerVideoMemoryFuser |
python | pandas-dev__pandas | pandas/tests/api/test_api.py | {
"start": 11091,
"end": 11539
} | class ____(Base):
def test_util(self):
self.check(
pd.util,
["hash_array", "hash_pandas_object"],
ignored=[
"_decorators",
"_test_decorators",
"_exceptions",
"_validators",
"capitalize_first_l... | TestUtil |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 57100,
"end": 57387
} | class ____(FieldValues):
"""
Values for `TimeField` with a custom output format.
"""
valid_inputs = {}
invalid_inputs = {}
outputs = {
datetime.time(13, 00): '01:00PM'
}
field = serializers.TimeField(format='%I:%M%p')
| TestCustomOutputFormatTimeField |
python | anthropics__anthropic-sdk-python | src/anthropic/types/message_param.py | {
"start": 871,
"end": 1570
} | class ____(TypedDict, total=False):
content: Required[
Union[
str,
Iterable[
Union[
TextBlockParam,
ImageBlockParam,
DocumentBlockParam,
SearchResultBlockParam,
Thinkin... | MessageParam |
python | wandb__wandb | wandb/sdk/artifacts/_generated/enums.py | {
"start": 356,
"end": 442
} | class ____(str, Enum):
READY = "READY"
DELETED = "DELETED"
| ArtifactCollectionState |
python | pytorch__pytorch | torch/_strobelight/cli_function_profiler.py | {
"start": 696,
"end": 1389
} | class ____(Exception):
"""
Raised when an error happens during strobelight profiling
"""
def _pid_namespace_link(pid: Optional[int] = None) -> str:
"""Returns the link to the process's namespace, example: pid:[4026531836]"""
PID_NAMESPACE_PATH = "/proc/{}/ns/pid"
pid = pid or os.getpid()
r... | StrobelightCLIProfilerError |
python | sphinx-doc__sphinx | tests/roots/test-root/parsermod.py | {
"start": 65,
"end": 346
} | class ____(Parser):
supported = ('foo',)
def parse(self, input, document):
section = nodes.section(ids=['id1'])
section += nodes.title('Generated section', 'Generated section')
document += section
def get_transforms(self):
return []
| Parser |
python | pytorch__pytorch | torch/_inductor/fuzzer.py | {
"start": 1642,
"end": 1878
} | class ____(CustomGraphPass):
"""
A Dummy pass to be used by ConfigFuzzer
"""
def __call__(self, graph: torch.fx.graph.Graph) -> None:
return None
def uuid(self) -> Optional[Any]:
return None
| DummyPass |
python | astropy__astropy | astropy/units/tests/test_quantity_typing.py | {
"start": 234,
"end": 2573
} | class ____:
"""Test Quantity Typing Annotations."""
def test_quantity_typing(self):
"""Test type hint creation from Quantity."""
annot = u.Quantity[u.m]
assert get_origin(annot) is Annotated
assert get_args(annot) == (u.Quantity, u.m)
# test usage
def func(x: a... | TestQuantityTyping |
python | pytorch__pytorch | test/distributed/test_c10d_nccl.py | {
"start": 158699,
"end": 179443
} | class ____(test_c10d_common.AbstractCommTest, MultiProcessTestCase):
@property
def device(self):
return f"cuda:{self.rank}"
def setUp(self):
super().setUp()
# TORCH_NCCL_BLOCKING_WAIT overrides TORCH_NCCL_ASYNC_ERROR_HANDLING hence tests
# that use TORCH_NCCL_BLOCKING_WAIT w... | CommTest |
python | sanic-org__sanic | guide/webapp/display/layouts/models.py | {
"start": 72,
"end": 260
} | class ____(Struct, kw_only=False, omit_defaults=True):
label: str
path: str | None = None
href: str | None = None
items: list[MenuItem] = field(default_factory=list)
| MenuItem |
python | pytorch__pytorch | .github/scripts/test_delete_old_branches.py | {
"start": 274,
"end": 1759
} | class ____(unittest.TestCase):
def test_delete_tag(
self, mock_run_git: "MagicMock", mock_delete_tag: "MagicMock"
) -> None:
for tag in [
"ciflow/branch/12345",
"ciflow/commitsha/1234567890abcdef1234567890abcdef12345678",
"trunk/1234567890abcdef1234567890abcde... | TestDeleteTag |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_in_memory_base_store.py | {
"start": 537,
"end": 828
} | class ____(BaseStoreAsyncTests[str]):
@pytest.fixture
@override
def three_values(self) -> tuple[str, str, str]:
return "foo", "bar", "buzz"
@pytest.fixture
@override
async def kv_store(self) -> InMemoryStore:
return InMemoryStore()
| TestInMemoryStoreAsync |
python | huggingface__transformers | src/transformers/models/sam2/modular_sam2.py | {
"start": 17002,
"end": 17079
} | class ____(MaskFormerSinePositionEmbedding):
pass
| Sam2SinePositionEmbedding |
python | realpython__materials | gemini-cli/todolist/src/todolist/exporter.py | {
"start": 500,
"end": 1933
} | class ____:
def __init__(
self, output: SupportsWrite[str], options: FormatOptions = {}
) -> None:
self.output = output
self.options = options
def export(self, content: Any) -> None:
json.dump(content, self.output, **self.options)
def export_database_to_json() -> None:
... | JSONExporter |
python | google__pytype | pytype/abstract/function.py | {
"start": 34711,
"end": 35320
} | class ____(_ReturnType):
"""An abstract return type."""
def __init__(self, t: _base.BaseValue, ctx: "context.Context") -> None:
self._type = t
self._ctx = ctx
@property
def name(self) -> str:
return self._type.full_name
def instantiate_parameter(
self, node: cfg.CFGNode, param_name: str
... | AbstractReturnType |
python | walkccc__LeetCode | solutions/774. Minimize Max Distance to Gas Station/774.py | {
"start": 0,
"end": 641
} | class ____:
def minmaxGasDist(self, stations: list[int], k: int) -> float:
ERR = 1e-6
l = 0
r = stations[-1] - stations[0]
def possible(k: int, m: float) -> bool:
"""
Returns True if can use <= k gas stations to ensure that each adjacent
distance between gas stations <= m.
"""... | Solution |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 35581,
"end": 37514
} | class ____:
@pytest.mark.parametrize(
["rows", "hrule", "expected_result"],
[
(
[["value 1", "value2\nsecond line"], ["value 3", "value4"]],
HRuleStyle.ALL,
"""
+---------+-------------+
| Field 1 | Field 2 |
+---------+-------------+
|... | TestBreakLine |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 24483,
"end": 29736
} | class ____(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nanmean, np.nanvar, np.nanstd]
stdfuncs = [np.mean, np.var, np.std]
def test_dtype_error(self):
for f in self.nanfuncs:
for dtype in [np.bool, np.int_, np.object_]:
assert_raises(TypeError, f, _ndat, axis=1, dtype... | TestNanFunctions_MeanVarStd |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy.py | {
"start": 1376,
"end": 6509
} | class ____(distribute_lib.Strategy):
"""A distribution strategy for synchronous training on multiple workers.
This strategy implements synchronous distributed training across multiple
workers, each with potentially multiple GPUs. Similar to
`tf.distribute.MirroredStrategy`, it replicates all variables and comp... | MultiWorkerMirroredStrategy |
python | python-poetry__poetry | src/poetry/publishing/hash_manager.py | {
"start": 208,
"end": 309
} | class ____(NamedTuple):
md5: str | None
sha256: str | None
blake2_256: str | None
| Hexdigest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callable7.py | {
"start": 330,
"end": 422
} | class ____:
def method1(self, a: int):
return a
__call__ = method1
B()(0)
| B |
python | sphinx-doc__sphinx | sphinx/util/logging.py | {
"start": 3440,
"end": 6267
} | class ____(logging.LoggerAdapter[logging.Logger]):
"""LoggerAdapter allowing ``type`` and ``subtype`` keywords."""
KEYWORDS = ['type', 'subtype', 'location', 'nonl', 'color', 'once']
def log( # type: ignore[override]
self, level: int | str, msg: str, *args: Any, **kwargs: Any
) -> None:
... | SphinxLoggerAdapter |
python | huggingface__transformers | src/transformers/models/vit/modeling_vit.py | {
"start": 13946,
"end": 14479
} | class ____(nn.Module):
def __init__(self, config: ViTConfig):
super().__init__()
self.config = config
self.layer = nn.ModuleList([ViTLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, hidden_states: torch.Tensor) -> Bas... | ViTEncoder |
python | ansible__ansible | lib/ansible/executor/module_common.py | {
"start": 2686,
"end": 6257
} | class ____:
"""Represents a module/module_utils item awaiting import analysis."""
name_parts: tuple[str, ...]
is_ambiguous: bool = False
child_is_redirected: bool = False
is_optional: bool = False
@classmethod
def from_module(cls, module: types.ModuleType, append: str | None = None) -> t.Se... | _ModuleUtilsProcessEntry |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 883,
"end": 946
} | class ____(test_factory()):
fe_type = types.float32
| TestFloat |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 4027,
"end": 5573
} | class ____(TestCase):
def setUp(self):
self.elements = list(range(10))
random.shuffle(self.elements)
self.chunk: DataChunk[int] = DataChunk(self.elements)
def test_getitem(self):
for i in range(10):
self.assertEqual(self.elements[i], self.chunk[i])
def test_iter... | TestDataChunk |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 108676,
"end": 114816
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[2, 4]", L_y_: "f32[4]"):
l_x_ = L_x_
l_y_ = L_y_
x: "f32[2, 4]" = l_x_ + l_y_; l_x_ = None
hints_wrapper_body_1 = self.hints_wrapper_body_1
hints_wrapper = torch.ops.higher_order.hints_wrapper(hints_wrapper_body_1, ... | GraphModule |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 13334,
"end": 14186
} | class ____(ABC):
@staticmethod
def separate_fields(
data: dict[str, Any], excluded_keys: list[str] | None = None
) -> tuple[dict[str, Any], dict[str, Any]]:
"""
Separates data into standard and additional fields.
Returns tuple of (dynamic_form_fields, additional_fields)
... | TicketingActionDataBlobHelper |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 11590,
"end": 11894
} | class ____(InstallationError):
"""Metadata is invalid."""
def __init__(self, ireq: InstallRequirement, error: str) -> None:
self.ireq = ireq
self.error = error
def __str__(self) -> str:
return f"Requested {self.ireq} has invalid metadata: {self.error}"
| MetadataInvalid |
python | ray-project__ray | rllib/algorithms/mock.py | {
"start": 221,
"end": 2507
} | class ____(Algorithm):
"""Mock Algorithm for use in tests."""
@classmethod
@override(Algorithm)
def get_default_config(cls) -> AlgorithmConfig:
return (
AlgorithmConfig()
.framework("tf")
.update_from_dict(
{
"mock_error": ... | _MockTrainer |
python | pola-rs__polars | py-polars/src/polars/expr/whenthen.py | {
"start": 4305,
"end": 6500
} | class ____(Expr):
"""
Utility class for the `when-then-otherwise` expression.
Represents the state of the expression after an additional `then` is called.
"""
def __init__(self, chained_then: Any) -> None:
self._chained_then = chained_then
@classmethod
def _from_pyexpr(cls, pyexpr... | ChainedThen |
python | kamyu104__LeetCode-Solutions | Python/minimum-increments-for-target-multiples-in-an-array.py | {
"start": 105,
"end": 1399
} | class ____(object):
def minimumIncrements(self, nums, target):
"""
:type nums: List[int]
:type target: List[int]
:rtype: int
"""
INF = float("inf")
def gcd(a, b):
while b:
a, b = b, a%b
return a
def lcm(a, b):
... | Solution |
python | chroma-core__chroma | chromadb/proto/convert.py | {
"start": 1036,
"end": 26619
} | class ____(TypedDict):
record: ProjectionRecord
distance: Optional[float]
# TODO: Unit tests for this file, handling optional states etc
def to_proto_vector(vector: Vector, encoding: ScalarEncoding) -> chroma_pb.Vector:
if encoding == ScalarEncoding.FLOAT32:
as_bytes = np.array(vector, dtype=np.fl... | KNNProjectionRecord |
python | google__jax | jax/_src/lib/triton.py | {
"start": 839,
"end": 2202
} | class ____(Protocol):
def __call__(
self,
module: bytes,
arch_name: str,
num_warps: int,
num_ctas: int,
num_stages: int,
) -> CompilationResult:
...
_compilation_handlers: dict[str, CompilationHandler] = {}
_compilation_handlers_lock = threading.Lock()
def register_compi... | CompilationHandler |
python | fastai__fastai | fastai/data/transforms.py | {
"start": 3963,
"end": 8668
} | class ____(ItemTransform):
"Creates a proper transform that applies `attrgetter(nm)` (even on a tuple)"
_retain = False
def __init__(self, nm, default=None): store_attr()
def encodes(self, x): return getattr(x, self.nm, self.default)
# %% ../../nbs/05_data.transforms.ipynb 32
def RandomSplitter(valid_p... | AttrGetter |
python | pydata__xarray | xarray/tests/test_variable.py | {
"start": 2257,
"end": 38942
} | class ____(NamedArraySubclassobjects, ABC):
@pytest.fixture
def target(self, data):
data = 0.5 * np.arange(10).reshape(2, 5)
return Variable(["x", "y"], data)
def test_getitem_dict(self):
v = self.cls(["x"], np.random.randn(5))
actual = v[{"x": 0}]
expected = v[0]
... | VariableSubclassobjects |
python | crytic__slither | slither/slithir/operations/event_call.py | {
"start": 143,
"end": 622
} | class ____(Call):
def __init__(self, name: Union[str, Constant]) -> None:
super().__init__()
self._name = name
# todo add instance of the Event
@property
def name(self) -> Union[str, Constant]:
return self._name
@property
def read(self) -> List[Any]:
return ... | EventCall |
python | matplotlib__matplotlib | lib/matplotlib/widgets.py | {
"start": 2771,
"end": 5191
} | class ____(Widget):
"""
Widget connected to a single `~matplotlib.axes.Axes`.
To guarantee that the widget remains responsive and not garbage-collected,
a reference to the object should be maintained by the user.
This is necessary because the callback registry
maintains only weak-refs to the f... | AxesWidget |
python | celery__celery | t/unit/concurrency/test_eventlet.py | {
"start": 2476,
"end": 4721
} | class ____(EventletCase):
@pytest.fixture(autouse=True)
def setup_patches(self, patching):
self.GreenPool = patching('eventlet.greenpool.GreenPool')
self.greenthread = patching('eventlet.greenthread')
def test_pool(self):
x = TaskPool()
x.on_start()
x.on_stop()
... | test_TaskPool |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 2759,
"end": 3150
} | class ____(ArraySetup):
_data_cls = Longitude
@classmethod
def setup_class(cls):
super().setup_class()
cls.a = Longitude(cls.a, u.deg)
cls.b = Longitude(cls.b, u.deg)
cls.c = Longitude(cls.c, u.deg)
# Note: Longitude does not work on structured arrays, so
# l... | LongitudeSetup |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 35751,
"end": 35909
} | class ____(Type):
""" Integer base type, contains no size information. """
__slots__ = ()
cast_nocheck = lambda self, i: Integer(int(i))
| IntBaseType |
python | apache__airflow | providers/google/tests/unit/google/cloud/transfers/test_gcs_to_bigquery.py | {
"start": 69534,
"end": 85219
} | class ____:
def _set_execute_complete(self, session, ti, **next_kwargs):
ti.next_method = "execute_complete"
ti.next_kwargs = next_kwargs
session.flush()
@pytest.mark.db_test
@mock.patch(GCS_TO_BQ_PATH.format("BigQueryHook"))
def test_execute_without_external_table_async_should_... | TestAsyncGCSToBigQueryOperator |
python | huggingface__transformers | tests/models/levit/test_image_processing_levit.py | {
"start": 3020,
"end": 4775
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = LevitImageProcessor if is_vision_available() else None
fast_image_processing_class = LevitImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester... | LevitImageProcessingTest |
python | huggingface__transformers | src/transformers/models/videomae/modeling_videomae.py | {
"start": 12940,
"end": 13563
} | class ____(nn.Module):
def __init__(self, config: VideoMAEConfig):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> ... | VideoMAEOutput |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet_convblock.py | {
"start": 1285,
"end": 2310
} | class ____:
def __init__(self, D):
self.running_mean = tf.Variable(np.zeros(D, dtype=np.float32), trainable=False)
self.running_var = tf.Variable(np.ones(D, dtype=np.float32), trainable=False)
self.gamma = tf.Variable(np.ones(D, dtype=np.float32))
self.beta = tf.Variable(np.zeros(D, dt... | BatchNormLayer |
python | ipython__ipython | tests/test_pretty.py | {
"start": 5918,
"end": 14450
} | class ____(type):
def __new__(cls, name):
return type.__new__(cls, name, (object,), {"name": name})
def __repr__(self):
return "[CUSTOM REPR FOR CLASS %s]" % self.name
ClassWithMeta = MetaClass("ClassWithMeta")
def test_metaclass_repr():
output = pretty.pretty(ClassWithMeta)
assert ... | MetaClass |
python | wandb__wandb | wandb/vendor/pygments/lexers/parsers.py | {
"start": 19846,
"end": 20394
} | class ____(DelegatingLexer):
"""
`ANTLR`_ with Objective-C Target
.. versionadded:: 1.1
"""
name = 'ANTLR With ObjectiveC Target'
aliases = ['antlr-objc']
filenames = ['*.G', '*.g']
def __init__(self, **options):
super(AntlrObjectiveCLexer, self).__init__(ObjectiveCLexer,
... | AntlrObjectiveCLexer |
python | gevent__gevent | src/greentest/3.10/test_ssl.py | {
"start": 97823,
"end": 99860
} | class ____(unittest.TestCase):
def test_timeout_connect_ex(self):
# Issue #12065: on a timeout, connect_ex() should return the original
# errno (mimicking the behaviour of non-SSL sockets).
with socket_helper.transient_internet(REMOTE_HOST):
s = test_wrap_socket(socket.socket(so... | NetworkedTests |
python | spyder-ide__spyder | spyder/widgets/dock.py | {
"start": 5549,
"end": 7764
} | class ____(QWidget):
"""
Custom title bar for our dock widgets.
Inspired from
https://stackoverflow.com/a/40894225/438386
"""
def __init__(self, parent):
super().__init__(parent)
button_size = QSize(20, 20)
drag_button = DragButton(self, button_size)
left_spa... | DockTitleBar |
python | matplotlib__matplotlib | lib/matplotlib/widgets.py | {
"start": 68077,
"end": 71066
} | class ____(AxesWidget):
"""
A crosshair cursor that spans the Axes and moves with mouse cursor.
For the cursor to remain responsive you must keep a reference to it.
Parameters
----------
ax : `~matplotlib.axes.Axes`
The `~.axes.Axes` to attach the cursor to.
horizOn : bool, default... | Cursor |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 2214,
"end": 2800
} | class ____(nn.Module):
r"""Model with only Linear layers, alternating layers with biases,
wrapped in a Sequential. Used to test pruned Linear-Bias-Linear fusion."""
def __init__(self) -> None:
super().__init__()
self.seq = nn.Sequential(
nn.Linear(7, 5, bias=True),
n... | LinearBias |
python | huggingface__transformers | src/transformers/models/colqwen2/modeling_colqwen2.py | {
"start": 1598,
"end": 2812
} | class ____(PreTrainedModel):
config: ColQwen2Config
base_model_prefix = "model"
input_modalities = ("image", "text")
_no_split_modules = []
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
@torch.no_grad()
def _init_weights(self, module):
std = (
... | ColQwen2PreTrainedModel |
python | great-expectations__great_expectations | great_expectations/profile/base.py | {
"start": 3628,
"end": 4883
} | class ____(metaclass=abc.ABCMeta):
"""
Profiler creates suites from various sources of truth.
These sources of truth can be data or non-data sources such as DDLs.
When implementing a Profiler ensure that you:
- Implement a . _profile() method
- Optionally implement .validate() method that veri... | Profiler |
python | kamyu104__LeetCode-Solutions | Python/populating-next-right-pointers-in-each-node.py | {
"start": 761,
"end": 1122
} | class ____(object):
# @param root, a tree node
# @return nothing
def connect(self, root):
if root is None:
return
if root.left:
root.left.next = root.right
if root.right and root.next:
root.right.next = root.next.left
self.connect(root.left... | Solution2 |
python | gawel__pyquery | tests/test_pyquery.py | {
"start": 31243,
"end": 31485
} | class ____(TestCase):
def test_get(self):
d = pq(url='http://ru.wikipedia.org/wiki/Заглавная_страница',
method='get')
print(d)
self.assertEqual(d('#pt-login').text(), 'Войти')
| TestWebScrappingEncoding |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 18340,
"end": 21259
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = RobertaPreLayerNormAttention(config, is_causal=config.is_decoder, layer_idx=layer... | RobertaPreLayerNormLayer |
python | sphinx-doc__sphinx | tests/roots/test-ext-autosummary-recursive/package/module.py | {
"start": 33,
"end": 161
} | class ____:
def __init__(self):
pass
def bar(self):
pass
@property
def baz(self):
pass
| Foo |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/retrieval/evaluator.py | {
"start": 1834,
"end": 3717
} | class ____(BaseRetrievalEvaluator):
"""
Retriever evaluator.
This module will evaluate a retriever using a set of metrics.
Args:
metrics (List[BaseRetrievalMetric]): Sequence of metrics to evaluate
retriever: Retriever to evaluate.
node_postprocessors (Optional[List[BaseNodePos... | MultiModalRetrieverEvaluator |
python | getsentry__sentry | src/sentry/auth/providers/github/client.py | {
"start": 391,
"end": 2025
} | class ____:
def __init__(self, access_token: str) -> None:
self.http = http.build_session()
self.access_token = access_token
def __enter__(self) -> GitHubClient:
return self
def __exit__(
self, exc_type: type | None, exc_value: Exception | None, traceback: TracebackType | N... | GitHubClient |
python | django__django | tests/auth_tests/test_mixins.py | {
"start": 525,
"end": 618
} | class ____(UserPassesTestMixin):
def test_func(self):
return False
| AlwaysFalseMixin |
python | ray-project__ray | python/ray/util/client/runtime_context.py | {
"start": 173,
"end": 1886
} | class ____:
"""Emulates the properties of the ray._private.worker object for the client"""
def __init__(self, worker):
assert worker is not None
self.worker = worker
def build_runtime_context(self) -> "RuntimeContext":
"""Creates a RuntimeContext backed by the properites of this AP... | _ClientWorkerPropertyAPI |
python | sqlalchemy__sqlalchemy | test/sql/test_selectable.py | {
"start": 58630,
"end": 64270
} | class ____(fixtures.TestBase):
def test_join_uninit(self):
a = table("a", column("x"))
b = table("b", column("y"))
j = a.join(b, a.c.x == b.c.y)
q = column("q")
b.append_column(q)
j._refresh_for_new_column(q)
assert j.c.b_q is q
def test_join_init(self):... | RefreshForNewColTest |
python | openai__openai-python | src/openai/types/beta/threads/run.py | {
"start": 1640,
"end": 2218
} | class ____(BaseModel):
type: Literal["auto", "last_messages"]
"""The truncation strategy to use for the thread.
The default is `auto`. If set to `last_messages`, the thread will be truncated
to the n most recent messages in the thread. When set to `auto`, messages in the
middle of the thread will b... | TruncationStrategy |
python | pandas-dev__pandas | pandas/core/methods/describe.py | {
"start": 2422,
"end": 3010
} | class ____(ABC):
"""Abstract class for describing dataframe or series.
Parameters
----------
obj : Series or DataFrame
Object to be described.
"""
def __init__(self, obj: DataFrame | Series) -> None:
self.obj = obj
@abstractmethod
def describe(self, percentiles: Sequen... | NDFrameDescriberAbstract |
python | dask__distributed | distributed/dashboard/components/shared.py | {
"start": 3770,
"end": 4922
} | class ____(DashboardComponent):
"""Time plots of the current resource usage on the cluster
This is two plots, one for CPU and Memory and another for Network I/O
"""
def __init__(self, **kwargs):
state = profile.create()
data = profile.plot_data(state, profile_interval)
self.sta... | ProfilePlot |
python | simonw__datasette | datasette/facets.py | {
"start": 5217,
"end": 11294
} | class ____(Facet):
type = "column"
async def suggest(self):
row_count = await self.get_row_count()
columns = await self.get_columns(self.sql, self.params)
facet_size = self.get_facet_size()
suggested_facets = []
already_enabled = [c["config"]["simple"] for c in self.get_... | ColumnFacet |
python | django__django | django/db/backends/sqlite3/features.py | {
"start": 259,
"end": 6886
} | class ____(BaseDatabaseFeatures):
minimum_database_version = (3, 37)
test_db_allows_multiple_connections = False
supports_unspecified_pk = True
supports_timezones = False
supports_transactions = True
atomic_transactions = False
can_rollback_ddl = True
can_create_inline_fk = False
req... | DatabaseFeatures |
python | pytorch__pytorch | benchmarks/transformer/score_mod.py | {
"start": 5677,
"end": 5763
} | class ____:
eager_time: float
compiled_time: float
@dataclass(frozen=True)
| Times |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 3107,
"end": 3321
} | class ____(BaseWithSlots):
__slots__ = ("c",)
# Is in base __slots__
a: int
# Not in any base __slots__
d: int # [declare-non-slot]
e: str= "AnnAssign.value is not None"
| DerivedWithMoreSlots |
python | getsentry__sentry | tests/sentry/hybridcloud/tasks/test_deliver_webhooks.py | {
"start": 1044,
"end": 11012
} | class ____(TestCase):
@patch("sentry.hybridcloud.tasks.deliver_webhooks.drain_mailbox")
def test_schedule_no_records(self, mock_deliver: MagicMock) -> None:
schedule_webhook_delivery()
assert mock_deliver.delay.call_count == 0
@patch("sentry.hybridcloud.tasks.deliver_webhooks.drain_mailbox"... | ScheduleWebhooksTest |
python | mlflow__mlflow | mlflow/gateway/config.py | {
"start": 2248,
"end": 2465
} | class ____(ConfigModel):
ai21labs_api_key: str
@field_validator("ai21labs_api_key", mode="before")
def validate_ai21labs_api_key(cls, value):
return _resolve_api_key_from_input(value)
| AI21LabsConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/types.py | {
"start": 298,
"end": 1157
} | class ____(NamedTupleSerializer["DaemonHeartbeat"]):
def before_unpack(self, context, unpacked_dict):
# Previously daemon types were enums, now they are strings. If we find a packed enum,
# just extract the name, which is the string we want.
if isinstance(unpacked_dict.get("daemon_type"), Un... | DaemonHeartbeatSerializer |
python | pandas-dev__pandas | pandas/tests/reshape/concat/test_append.py | {
"start": 257,
"end": 12744
} | class ____:
def test_append(self, sort, float_frame):
mixed_frame = float_frame.copy()
mixed_frame["foo"] = "bar"
begin_index = float_frame.index[:5]
end_index = float_frame.index[5:]
begin_frame = float_frame.reindex(begin_index)
end_frame = float_frame.reindex(end... | TestAppend |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/tests/test_image_vision_llm.py | {
"start": 999,
"end": 2593
} | class ____:
"""
This double fakes the `Blip2Processor` tokenizer object so as to
avoid having to instantiate the actual tokenizer for these tests.
"""
def __call__(self, img, prompt, return_tensors) -> TokenizerFake:
"""
This is just a stub for the purposes of the test,
so w... | TokenizerFake |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.