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 | mlflow__mlflow | mlflow/tracking/context/system_environment_context.py | {
"start": 274,
"end": 467
} | class ____(RunContextProvider):
def in_context(self):
return MLFLOW_RUN_CONTEXT.defined
def tags(self):
return json.loads(MLFLOW_RUN_CONTEXT.get())
| SystemEnvironmentContext |
python | kamyu104__LeetCode-Solutions | Python/minimum-flips-in-binary-tree-to-get-result.py | {
"start": 164,
"end": 1830
} | class ____(object):
def minimumFlips(self, root, result):
"""
:type root: Optional[TreeNode]
:type result: bool
:rtype: int
"""
INF = float("inf")
OP = {
2: lambda x, y: x or y,
3: lambda x, y: x and y,
4: lambda x, y: x^y ,... | Solution |
python | openai__openai-python | src/openai/resources/responses/responses.py | {
"start": 78774,
"end": 155426
} | class ____(AsyncAPIResource):
@cached_property
def input_items(self) -> AsyncInputItems:
return AsyncInputItems(self._client)
@cached_property
def input_tokens(self) -> AsyncInputTokens:
return AsyncInputTokens(self._client)
@cached_property
def with_raw_response(self) -> Async... | AsyncResponses |
python | numba__numba | numba/tests/test_closure.py | {
"start": 2710,
"end": 13629
} | class ____(TestCase):
"""
Tests for (partial) closure support in njit. The support is partial
because it only works for closures that can be successfully inlined
at compile time.
"""
def test_inner_function(self):
def outer(x):
def inner(x):
return x * x
... | TestInlinedClosure |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 23406,
"end": 24999
} | class ____(Instruction):
def __init__(self, parent, vector1, vector2, mask, name=''):
if not isinstance(vector1.type, types.VectorType):
raise TypeError("vector1 needs to be of VectorType.")
if vector2 != Undefined:
if vector2.type != vector1.type:
raise TypeE... | ShuffleVector |
python | pytorch__pytorch | torch/distributed/fsdp/api.py | {
"start": 12125,
"end": 13716
} | class ____(Enum):
"""
This enum indicates that which type of ``state_dict`` the FSDP module is
currently processing (returning or loading).
The default value is FULL_STATE_DICT to comply the PyTorch convention.
.. note::
FSDP currently supports three types of ``state_dict``:
1. ... | StateDictType |
python | sphinx-doc__sphinx | sphinx/domains/python/__init__.py | {
"start": 9381,
"end": 9834
} | class ____(PyMethod):
"""Description of a decoratormethod."""
def run(self) -> list[Node]:
self.name = 'py:method'
return super().run()
def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]:
ret = super().handle_signature(sig, signode)
signode.ins... | PyDecoratorMethod |
python | ray-project__ray | rllib/examples/envs/classes/debug_counter_env.py | {
"start": 102,
"end": 1007
} | class ____(gym.Env):
"""Simple Env that yields a ts counter as observation (0-based).
Actions have no effect.
The episode length is always 15.
Reward is always: current ts % 3.
"""
def __init__(self, config=None):
config = config or {}
self.action_space = gym.spaces.Discrete(2)... | DebugCounterEnv |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 15628,
"end": 16012
} | class ____(sgqlc.types.Enum):
"""The possible administrator roles in an enterprise account.
Enumeration Choices:
* `BILLING_MANAGER`: Represents a billing manager of the
enterprise account.
* `OWNER`: Represents an owner of the enterprise account.
"""
__schema__ = github_schema
__ch... | EnterpriseAdministratorRole |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_asb.py | {
"start": 11403,
"end": 14120
} | class ____:
def test_init(self):
"""
Test init by creating AzureServiceBusTopicCreateOperator with task id and topic name,
by asserting the value
"""
asb_create_topic = AzureServiceBusTopicCreateOperator(
task_id="asb_create_topic",
topic_name=TOPIC_NA... | TestABSTopicCreateOperator |
python | pallets__werkzeug | examples/cupoftee/network.py | {
"start": 180,
"end": 408
} | class ____:
last_sync = None
def sync(self):
try:
self._sync()
except (OSError, socket.timeout):
return False
self.last_sync = datetime.utcnow()
return True
| Syncable |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 15536,
"end": 16848
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.httpexceptions import _HTTPMove
return _HTTPMove(*arg, **kw)
def test_it_location_none_valueerrors(self):
# Constructing a HTTPMove instance with location=None should
# throw a ValueError from __init__ ... | Test_HTTPMove |
python | streamlit__streamlit | lib/tests/streamlit/elements/vega_charts_test.py | {
"start": 2876,
"end": 19606
} | class ____(DeltaGeneratorTestCase):
"""Test the `st.altair_chart` command."""
def test_altair_chart(self):
"""Test that it can be called with args."""
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
... | AltairChartTest |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 1148,
"end": 1330
} | class ____(serializers.ModelSerializer):
slug = serializers.ReadOnlyField()
class Meta:
model = SlugBasedModel
fields = ('text', 'slug')
# Views
| SlugSerializer |
python | python__mypy | mypyc/irbuild/prepare.py | {
"start": 26477,
"end": 26978
} | class ____(NamedTuple):
singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]
decorators_to_remove: dict[FuncDef, list[int]]
def find_singledispatch_register_impls(
modules: list[MypyFile], errors: Errors
) -> SingledispatchInfo:
visitor = SingledispatchVisitor(errors)
for module in modules:... | SingledispatchInfo |
python | tox-dev__tox | src/tox/config/main.py | {
"start": 586,
"end": 7201
} | class ____:
"""Main configuration object for tox."""
def __init__( # noqa: PLR0913 # <- no way around many args
self,
config_source: Source,
options: Parsed,
root: Path,
pos_args: Sequence[str] | None,
work_dir: Path,
extra_envs: Iterable[str],
) ->... | Config |
python | apache__thrift | contrib/zeromq/TZmqServer.py | {
"start": 1897,
"end": 2709
} | class ____(object):
def __init__(self):
self.servers = []
def serveOne(self, timeout=-1):
self._serveActive(self._setupPoll(), timeout)
def serveForever(self):
poll_info = self._setupPoll()
while True:
self._serveActive(poll_info, -1)
def _setupPoll(self):
... | TZmqMultiServer |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-chatgpt-plugin/llama_index/tools/chatgpt_plugin/base.py | {
"start": 249,
"end": 2598
} | class ____(BaseToolSpec):
"""
ChatGPT Plugin Tool.
This tool leverages the OpenAPI tool spec to automatically load ChatGPT
plugins from a manifest file.
You should also provide the Requests tool spec to allow the Agent to make calls to the OpenAPI endpoints
To use endpoints with authorization, ... | ChatGPTPluginToolSpec |
python | kamyu104__LeetCode-Solutions | Python/partition-array-according-to-given-pivot.py | {
"start": 44,
"end": 530
} | class ____(object):
def pivotArray(self, nums, pivot):
"""
:type nums: List[int]
:type pivot: int
:rtype: List[int]
"""
result = [pivot]*len(nums)
left, right = 0, len(nums)-sum(x > pivot for x in nums)
for x in nums:
if x < pivot:
... | Solution |
python | pandas-dev__pandas | pandas/tests/apply/conftest.py | {
"start": 1877,
"end": 2045
} | class ____:
__pandas_udf__ = MockExecutionEngine
@pytest.fixture(params=[None, MockEngineDecorator])
def engine(request):
return request.param
| MockEngineDecorator |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/airbyte_cloud/define_upstream_dependencies.py | {
"start": 421,
"end": 1014
} | class ____(DagsterAirbyteTranslator):
def get_asset_spec(self, props: AirbyteConnectionTableProps) -> dg.AssetSpec:
# We create the default asset spec using super()
default_spec = super().get_asset_spec(props)
# We set an upstream dependency for our assets
return default_spec.replace... | MyCustomAirbyteTranslator |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/main_widget.py | {
"start": 1068,
"end": 1199
} | class ____:
Files = 'files_section'
Header = 'header_section'
Common = 'common_section'
| ExplorerWidgetOptionsMenuSections |
python | astropy__astropy | astropy/modeling/rotations.py | {
"start": 5373,
"end": 6369
} | class ____:
"""
Base class which does the actual computation.
"""
_separable = False
def evaluate(self, alpha, delta, phi, theta, psi, axes_order):
shape = None
if isinstance(alpha, np.ndarray):
alpha = alpha.ravel()
delta = delta.ravel()
shape =... | _EulerRotation |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 46545,
"end": 46954
} | class ____(Elemwise):
_projection_passthrough = True
_parameters = ["frame", "values"]
operation = M.isin
@functools.cached_property
def _meta(self):
return make_meta(
meta_nonempty(self.frame._meta).isin(
meta_nonempty(self.frame._meta).iloc[[0]]
)
... | Isin |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer.py | {
"start": 56972,
"end": 58738
} | class ____(nn.Module):
def __init__(self, *args, feature_size: int = 256, mask_feature_size: int = 256, **kwargs):
r"""
Pixel Decoder Module proposed in [Per-Pixel Classification is Not All You Need for Semantic
Segmentation](https://huggingface.co/papers/2107.06278). It first runs the backb... | MaskFormerPixelDecoder |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 13515,
"end": 15321
} | class ____(VisitorWithPositionData):
suppression_regexes: Dict[SuppressionKind, str] = {
SuppressionKind.PYRE_FIXME: r".*# *pyre-fixme(\[(\d* *,? *)*\])?",
SuppressionKind.PYRE_IGNORE: r".*# *pyre-ignore(\[(\d* *,? *)*\])?",
SuppressionKind.TYPE_IGNORE: r".*# *type: ignore",
}
def _... | SuppressionCollector |
python | plotly__plotly.py | plotly/graph_objs/layout/_smith.py | {
"start": 235,
"end": 5129
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.smith"
_valid_props = {"bgcolor", "domain", "imaginaryaxis", "realaxis"}
@property
def bgcolor(self):
"""
Set the background color of the subplot
The 'bgcolor' property is a color and may ... | Smith |
python | huggingface__transformers | tests/models/owlv2/test_image_processing_owlv2.py | {
"start": 2895,
"end": 6800
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = Owlv2ImageProcessor if is_vision_available() else None
fast_image_processing_class = Owlv2ImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester... | Owlv2ImageProcessingTest |
python | huggingface__transformers | tests/models/time_series_transformer/test_modeling_time_series_transformer.py | {
"start": 7028,
"end": 19689
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(TimeSeriesTransformerModel, TimeSeriesTransformerForPrediction) if is_torch_available() else ()
)
pipeline_model_mapping = {"feature-extraction": TimeSeriesTransformerModel} if is_torch_available() else {}
... | TimeSeriesTransformerModelTest |
python | jschneier__django-storages | storages/utils.py | {
"start": 4679,
"end": 5536
} | class ____(FileProxyMixin):
"""
A wrapper for a file-like object, that makes read() always returns bytes.
"""
def __init__(self, file, encoding=None):
"""
:param file: The file-like object to wrap.
:param encoding: Specify the encoding to use when file.read() returns strings.
... | ReadBytesWrapper |
python | realpython__materials | django-diary/source_code_step_6/entries/views.py | {
"start": 446,
"end": 653
} | class ____(SuccessMessageMixin, CreateView):
model = Entry
fields = ["title", "content"]
success_url = reverse_lazy("entry-list")
success_message = "Your new entry was created!"
| EntryCreateView |
python | sqlalchemy__sqlalchemy | test/ext/test_baked.py | {
"start": 894,
"end": 3225
} | class ____(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
cls.mapper_registry.map_imperatively(User, cls.tables.users)
def _assert_cache_key(self, key, elements):
eq_(key, tuple(elem.__code__ for elem in elements))
def test_initial_key(self):
... | StateChangeTest |
python | GoogleCloudPlatform__python-docs-samples | functions/v2/typed/greeting/main.py | {
"start": 686,
"end": 997
} | class ____:
first_name: str
last_name: str
# Required to deserialize the request
@staticmethod
def from_dict(req: dict) -> "GreetingRequest":
return GreetingRequest(
first_name=req["first_name"],
last_name=req["last_name"],
)
@dataclass
| GreetingRequest |
python | openai__openai-python | src/openai/types/responses/response_output_text.py | {
"start": 2272,
"end": 2367
} | class ____(BaseModel):
token: str
bytes: List[int]
logprob: float
| LogprobTopLogprob |
python | apache__thrift | lib/py/test/thrift_transport.py | {
"start": 891,
"end": 1598
} | class ____(unittest.TestCase):
def test_TFileObjectTransport(self):
test_dir = os.path.dirname(os.path.abspath(__file__))
datatxt_path = os.path.join(test_dir, 'data.txt')
buffer = '{"soft":"thrift","version":0.13,"1":true}'
with open(datatxt_path, "w+") as f:
buf = TTra... | TestTFileObjectTransport |
python | skorch-dev__skorch | skorch/tests/callbacks/test_scoring.py | {
"start": 34879,
"end": 39419
} | class ____:
@pytest.fixture
def scoring_cls(self, request):
from skorch.callbacks import PassthroughScoring
return PassthroughScoring
@pytest.fixture
def train_loss(self, scoring_cls):
# use train batch size to stand in for batch-level scores
return scoring_cls(name='tra... | TestPassthrougScoring |
python | pytest-dev__pytest | testing/test_skipping.py | {
"start": 36509,
"end": 43534
} | class ____:
def test_skipif(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.skipif(True, reason="True123")
def test_func1():
pass
@pytest.mark.skipif(False, reason="True123")
def te... | TestBooleanCondition |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 117471,
"end": 118573
} | class ____(Pair):
"""Fallback ABC pair that handles non-numeric inputs.
To avoid recreating the mismatch messages of :meth:`unittest.TestCase.assertEqual`, this pair simply wraps it in
order to use it with the :class:`Pair` "framework" from :func:`are_equal`.
Define the :attr:`UnittestPair.CLS` in a s... | UnittestPair |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 19268,
"end": 20322
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreMemcachedHook")
def test_assert_valid_hook_call(self, mock_hook):
task = CloudMemorystoreMemcachedListInstancesOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
p... | TestCloudMemorystoreMemcachedListInstancesOperator |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/freshness_tests/test_internal_freshness.py | {
"start": 1525,
"end": 2134
} | class ____:
def test_apply_freshness_policy_explicit_none_fails(self) -> None:
"""Check that we cannot apply a null policy to assets."""
@asset
def asset_no_freshness():
pass
defs = dg.Definitions(assets=[asset_no_freshness])
with pytest.raises(ParameterCheckEr... | TestApplyFreshnessPolicy |
python | openai__gym | gym/error.py | {
"start": 1484,
"end": 1607
} | class ____(Error):
"""Raised when the user requests a rendering mode not supported by the environment."""
| UnsupportedMode |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 25829,
"end": 25919
} | class ____(PallasCallDynamicGridTest):
INTERPRET = True
| PallasCallDynamicGridInterpretTest |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14684,
"end": 14849
} | class ____(QueryExecutionError):
"""
Exception raised when a function in the query is provided an invalid
argument type.
"""
| QueryIllegalTypeOfArgument |
python | django__django | django/db/models/functions/datetime.py | {
"start": 13437,
"end": 13571
} | class ____(TruncBase):
kind = "second"
DateTimeField.register_lookup(TruncDate)
DateTimeField.register_lookup(TruncTime)
| TruncSecond |
python | spack__spack | lib/spack/spack/new_installer.py | {
"start": 17415,
"end": 25741
} | class ____:
"""Attach to an existing POSIX jobserver or create a FIFO-based one."""
def __init__(self, num_jobs: int) -> None:
#: Keep track of how many tokens Spack itself has acquired, which is used to release them.
self.tokens_acquired = 0
self.num_jobs = num_jobs
self.fifo_p... | JobServer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/report_check_status_record_builder.py | {
"start": 221,
"end": 1223
} | class ____(RecordBuilder):
@classmethod
def status_record(cls) -> "ReportCheckStatusRecordBuilder":
return cls(
find_template("report_status_response", __file__), id_path=None, status_path=FieldPath("status"), url_path=FieldPath("url")
)
def __init__(
self,
templ... | ReportCheckStatusRecordBuilder |
python | getsentry__sentry | src/sentry/sentry_apps/installations.py | {
"start": 1991,
"end": 4179
} | class ____:
sentry_app_installation: SentryAppInstallation
expires_at: datetime.date | None = None
def run(self, user: User | RpcUser, request: HttpRequest | None = None) -> ApiToken:
with transaction.atomic(router.db_for_write(ApiToken)):
self._check_token_limit()
api_token... | SentryAppInstallationTokenCreator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 689904,
"end": 690292
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("LinkedBranch", graphql_na... | LinkedBranchEdge |
python | walkccc__LeetCode | solutions/1304. Find N Unique Integers Sum up to Zero/1304.py | {
"start": 0,
"end": 94
} | class ____:
def sumZero(self, n: int) -> list[int]:
return list(range(1 - n, n, 2))
| Solution |
python | pydata__xarray | xarray/backends/scipy_.py | {
"start": 5736,
"end": 10788
} | class ____(WritableCFDataStore):
"""Store for reading and writing data via scipy.io.netcdf_file.
This store has the advantage of being able to be initialized with a
StringIO object, allow for serialization without writing to disk.
It only supports the NetCDF3 file-format.
"""
def __init__(
... | ScipyDataStore |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 17308,
"end": 20942
} | class ____(fixtures.TestBase):
@testing.combinations(
("Boo", Boolean()),
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Int", Integer()),
("Sma", SmallInteger()),
("Big", BigInteger()),
("Num", Numeric()),
("Flo", Float()),
... | PickleTypesTest |
python | python-excel__xlrd | xlrd/book.py | {
"start": 4216,
"end": 9265
} | class ____(BaseObject):
"""
Information relating to a named reference, formula, macro, etc.
.. note::
Name information is **not** extracted from files older than
Excel 5.0 (``Book.biff_version < 50``)
"""
_repr_these = ['stack']
book = None # parent
#: 0 = Visible; 1 = Hidden
... | Name |
python | tensorflow__tensorflow | tensorflow/python/data/ops/interleave_op.py | {
"start": 3715,
"end": 6409
} | class ____(dataset_ops.UnaryDataset):
"""A `Dataset` that maps a function over its input and interleaves the result.
"""
def __init__(self,
input_dataset,
map_func,
cycle_length,
block_length,
num_parallel_calls,
buffer_out... | _ParallelInterleaveDataset |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/types.py | {
"start": 9798,
"end": 10513
} | class ____:
"""Annotation used to mark state attributes as omitted from input or output schemas."""
input: bool = True
"""Whether to omit the attribute from the input schema."""
output: bool = True
"""Whether to omit the attribute from the output schema."""
OmitFromInput = OmitFromSchema(input=T... | OmitFromSchema |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 2793,
"end": 4209
} | class ____:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomia... | TestBinomial |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-graphdb-cypher/llama_index/readers/graphdb_cypher/base.py | {
"start": 190,
"end": 1766
} | class ____(BaseReader):
"""
Graph database Cypher reader.
Combines all Cypher query results into the Document type used by LlamaIndex.
Args:
uri (str): Graph Database URI
username (str): Username
password (str): Password
"""
def __init__(self, uri: str, username: str,... | GraphDBCypherReader |
python | facebook__pyre-check | tools/generate_taint_models/view_generator.py | {
"start": 481,
"end": 2163
} | class ____(NamedTuple):
urls_module: str
url_resolver_type: DynamicURLType
url_pattern_type: DynamicURLType
def get_all_views(django_urls: DjangoUrls) -> List[Callable[..., object]]:
LOG.info(f"Getting all URLs from `{django_urls.urls_module}`")
imported_urls_module = import_module(django_urls.url... | DjangoUrls |
python | huggingface__transformers | tests/models/janus/test_image_processing_janus.py | {
"start": 1133,
"end": 2980
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=384,
min_resolution=30,
max_resolution=200,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.48145466, 0.4578275, 0.40821073],
i... | JanusImageProcessingTester |
python | joke2k__faker | faker/providers/job/ru_RU/__init__.py | {
"start": 212,
"end": 12507
} | class ____(BaseProvider):
jobs = [
"Авиадиспетчер",
"Авиатехник",
"Авиационный техник",
"Автогонщик",
"Автослесарь",
"Автоэлектрик",
"Агроном",
"Агроном по защите растений",
"Агроном-почвовед",
"Адвокат",
"Администратор базы дан... | Provider |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_setitem.py | {
"start": 690,
"end": 29644
} | class ____:
def test_setitem_str_subclass(self):
# GH#37366
class mystring(str):
__slots__ = ()
data = ["2020-10-22 01:21:00+00:00"]
index = DatetimeIndex(data)
df = DataFrame({"a": [1]}, index=index)
df["b"] = 2
df[mystring("c")] = 3
expe... | TestDataFrameSetItem |
python | dagster-io__dagster | helm/dagster/schema/schema/utils/helm_template.py | {
"start": 623,
"end": 4577
} | class ____:
helm_dir_path: str
subchart_paths: list[str]
output: Optional[str] = None
model: Optional[Any] = None
release_name: str = "release-name"
api_client: ApiClient = ApiClient() # noqa: RUF009
namespace: str = "default"
def render(
self,
values: Optional[Union[Da... | HelmTemplate |
python | pytorch__pytorch | torch/_inductor/standalone_compile.py | {
"start": 972,
"end": 3686
} | class ____(ABC):
"""
CompiledArtifact class represents the inductor cache artifacts that
can be invoked in order to avoid repeated compilation.
CompiledArtifact can be obtained by calling standalone_compile(gm, example_inputs)
to create a fresh CompiledArtifact from a GraphModule and example inputs... | CompiledArtifact |
python | realpython__materials | python-class/week.py | {
"start": 24,
"end": 296
} | class ____(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
@classmethod
def favorite_day(cls):
return cls.FRIDAY
def __str__(self):
return f"Current day: {self.name}"
| WeekDay |
python | huggingface__transformers | src/transformers/models/dinat/modeling_dinat.py | {
"start": 27617,
"end": 31486
} | class ____(DinatPreTrainedModel, BackboneMixin):
def __init__(self, config):
super().__init__(config)
super()._init_backbone(config)
requires_backends(self, ["natten"])
self.embeddings = DinatEmbeddings(config)
self.encoder = DinatEncoder(config)
self.num_features =... | DinatBackbone |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context_creation_job.py | {
"start": 13721,
"end": 20602
} | class ____(ExecutionContextManager[PlanExecutionContext]):
def __init__(
self,
job: IJob,
execution_plan: ExecutionPlan,
run_config: Mapping[str, object],
dagster_run: DagsterRun,
instance: DagsterInstance,
retry_mode: RetryMode,
scoped_resources_build... | PlanExecutionContextManager |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 24853,
"end": 27471
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MiniMaxConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MiniMaxAttention(config, layer_idx)
self.input_layernorm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_n... | MiniMaxDecoderLayer |
python | pytorch__pytorch | test/inductor/test_provenance_tracing.py | {
"start": 18399,
"end": 20303
} | class ____(TestCase):
def get_node_with_target(self, gm, target):
"""
Return first node in gm with target
"""
return next(iter([node for node in gm.graph.nodes if node.target == target]))
@requires_gpu_and_triton # test only works for cuda pattern matcher
def test_pattern_m... | TestProvenanceTracingNodeMeta |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/base.py | {
"start": 67876,
"end": 70036
} | class ____(compiler.IdentifierPreparer):
reserved_words = {
"add",
"after",
"all",
"alter",
"analyze",
"and",
"as",
"asc",
"attach",
"autoincrement",
"before",
"begin",
"between",
"by",
"cascade",... | SQLiteIdentifierPreparer |
python | pytorch__pytorch | torch/nn/modules/linear.py | {
"start": 4876,
"end": 5206
} | class ____(Linear):
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
device=None,
dtype=None,
) -> None:
super().__init__(
in_features, out_features, bias=bias, device=device, dtype=dtype
)
| NonDynamicallyQuantizableLinear |
python | kubernetes-client__python | kubernetes/client/models/v2_metric_value_status.py | {
"start": 383,
"end": 5872
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V2MetricValueStatus |
python | getsentry__sentry | src/sentry/analytics/events/inapp_request.py | {
"start": 67,
"end": 278
} | class ____(analytics.Event, abc.ABC):
organization_id: int
user_id: int | None = None
target_user_id: int
providers: str
subtype: str | None = None
@analytics.eventclass()
| InAppRequestSentEvent |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/test_util.py | {
"start": 20486,
"end": 30550
} | class ____(parameterized.TestCase):
"""Base class for tests including numerical checks and boilerplate."""
# copied from jax.test_util
def setUp(self):
super().setUp()
self._rng = npr.RandomState(zlib.adler32(self._testMethodName.encode()))
# copied from jax.test_util
def rng(self):
return self.... | TestCase |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 12576,
"end": 15692
} | class ____(BaseDataset):
"""
Feature: Datasets can be created only if they don't exist in the file
"""
def test_create(self):
""" Create new dataset with no conflicts """
dset = self.f.require_dataset(make_name(), (10, 3), 'f')
self.assertIsInstance(dset, Dataset)
s... | TestCreateRequire |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 57746,
"end": 60556
} | class ____(Request):
"""
Remove old logs from task
:param task: Task ID
:type task: str
:param allow_locked: Allow deleting events even if the task is locked
:type allow_locked: bool
:param threshold_sec: The amount of seconds ago to retain the log records. The
older log records wil... | ClearTaskLogRequest |
python | great-expectations__great_expectations | tests/data_context/abstract_data_context/test_data_docs_config_crud.py | {
"start": 5213,
"end": 6915
} | class ____:
@pytest.mark.unit
def test_delete_data_docs_site(self, ephemeral_context_with_defaults: EphemeralDataContext):
# Check fixture configuration
existing_site_name = "local_site"
assert existing_site_name in ephemeral_context_with_defaults.get_site_names()
ephemeral_cont... | TestDeleteDataDocsSite |
python | apache__airflow | providers/standard/src/airflow/providers/standard/decorators/stub.py | {
"start": 1112,
"end": 3020
} | class ____(DecoratedOperator):
custom_operator_name: str = "@task.stub"
def __init__(
self,
*,
python_callable: Callable,
task_id: str,
**kwargs,
) -> None:
super().__init__(
python_callable=python_callable,
task_id=task_id,
... | _StubOperator |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 31223,
"end": 33374
} | class ____(Schema):
schema = fields.Dict(required=False, allow_none=True)
header = fields.Dict(required=False, allow_none=True)
# for StringValueType
template = fields.String(required=False, allow_none=True)
params = fields.Dict(required=False, allow_none=True)
code_block = fields.Dict(required... | RenderedAtomicValueSchema |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 41123,
"end": 41659
} | class ____(SetitemCastingEquivalents):
# https://github.com/pandas-dev/pandas/issues/39584#issuecomment-941212124
@pytest.fixture
def obj(self):
return Series([1, 2, 3], dtype="i4")
@pytest.fixture
def key(self):
return 0
@pytest.fixture
def expected(self, val):
if ... | TestSmallIntegerSetitemUpcast |
python | great-expectations__great_expectations | tests/integration/metrics/query/test_data_source_table.py | {
"start": 2207,
"end": 3685
} | class ____:
@multi_source_batch_setup(
multi_source_test_configs=ALL_COMPARISON_TO_BASE_SOURCES,
base_data=BASE_DATA_FRAME,
comparison_data=COMPARISON_DATA_FRAME,
)
def test_success_sql(self, multi_source_batch: MultiSourceBatch) -> None:
query = f"SELECT * FROM {multi_source... | TestQueryRowCount |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 826821,
"end": 838725
} | class ____(DatumChannelMixin, core.PositionDatumDefBase):
"""
ThetaDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if s... | ThetaDatum |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 4863,
"end": 6591
} | class ____(str, BaseEnum):
"""The available generative search modules in Weaviate.
These modules generate text from text-based inputs.
See the [docs](https://weaviate.io/developers/weaviate/modules/reader-generator-modules) for more details.
Attributes:
AWS: Weaviate module backed by AWS Bedro... | GenerativeSearches |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/input_manager.py | {
"start": 1579,
"end": 6659
} | class ____(ResourceDefinition, IInputManagerDefinition):
"""Definition of an input manager resource.
Input managers load op inputs.
An InputManagerDefinition is a :py:class:`ResourceDefinition` whose resource_fn returns an
:py:class:`InputManager`.
The easiest way to create an InputManagerDefinit... | InputManagerDefinition |
python | ApeWorX__ape | src/ape/plugins/__init__.py | {
"start": 470,
"end": 583
} | class ____(Exception):
pass
# Combine all the plugins together via subclassing (merges `hookspec`s)
| PluginError |
python | huggingface__transformers | src/transformers/generation/watermarking.py | {
"start": 12814,
"end": 15681
} | class ____(nn.Module):
"""Watermarked likelihood model for binary-valued g-values.
This takes in g-values and returns p(g_values|watermarked).
"""
def __init__(self, watermarking_depth: int):
"""Initializes the model parameters."""
super().__init__()
self.watermarking_depth = w... | BayesianDetectorWatermarkedLikelihood |
python | ray-project__ray | python/ray/air/tests/test_air_usage.py | {
"start": 2941,
"end": 6123
} | class ____(Callback):
pass
_TEST_CALLBACKS = [
wandb.WandbLoggerCallback,
mlflow.MLflowLoggerCallback,
comet.CometLoggerCallback,
_CustomLoggerCallback,
_CustomLoggerCallback,
_CustomCallback,
]
def test_tag_setup_wandb(mock_record):
from ray.air.integrations.wandb import _setup_wand... | _CustomCallback |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 38531,
"end": 38798
} | class ____:
def __str__(self) -> str:
return ".cast_symbool_to_symint_guardless()"
def get(self, b: bool) -> IntLikeType:
"""Get the int value from bool"""
return cast_symbool_to_symint_guardless(b)
@dataclass(frozen=True)
| ConvertIntKey |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/gql.py | {
"start": 1532,
"end": 3672
} | class ____:
def __init__(
self,
name: str,
python_file: Optional[str] = None,
package_name: Optional[str] = None,
image: Optional[str] = None,
module_name: Optional[str] = None,
working_directory: Optional[str] = None,
executable_path: Optional[str] = ... | CliInputCodeLocation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_prepare_formula.py | {
"start": 301,
"end": 10929
} | class ____(unittest.TestCase):
"""
Test the _prepare_formula Worksheet method for different formula types.
"""
def test_prepare_formula(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
self.worksheet.use_future_functions ... | TestPrepareFormula |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/operators/databricks_workflow.py | {
"start": 10285,
"end": 15019
} | class ____(TaskGroup):
"""
A task group that takes a list of tasks and creates a databricks workflow.
The DatabricksWorkflowTaskGroup takes a list of tasks and creates a databricks workflow
based on the metadata produced by those tasks. For a task to be eligible for this
TaskGroup, it must contain ... | DatabricksWorkflowTaskGroup |
python | scipy__scipy | scipy/special/tests/test_logsumexp.py | {
"start": 12888,
"end": 16075
} | class ____:
def test_softmax_fixtures(self, xp):
xp_assert_close(softmax(xp.asarray([1000., 0., 0., 0.])),
xp.asarray([1., 0., 0., 0.]), rtol=1e-13)
xp_assert_close(softmax(xp.asarray([1., 1.])),
xp.asarray([.5, .5]), rtol=1e-13)
xp_assert_clos... | TestSoftmax |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 296605,
"end": 300527
} | class ____:
@property
def netcdfc_version(self):
return Version(nc4.getlibversion().split()[0].split("-development")[0])
def _create_nczarr(self, filename):
if self.netcdfc_version < Version("4.8.1"):
pytest.skip("requires netcdf-c>=4.8.1")
if platform.system() == "Windo... | TestNCZarr |
python | pennersr__django-allauth | allauth/socialaccount/providers/okta/provider.py | {
"start": 310,
"end": 1356
} | class ____(OAuth2Provider):
id = "okta"
name = "Okta"
account_class = OktaAccount
oauth2_adapter_class = OktaOAuth2Adapter
def get_default_scope(self):
return ["openid", "profile", "email", "offline_access"]
def extract_uid(self, data):
uid_field = self.app.settings.get("uid_fi... | OktaProvider |
python | getsentry__sentry-python | tests/utils/test_transaction.py | {
"start": 103,
"end": 1367
} | class ____:
def myfunc(self):
pass
def myfunc():
pass
@partial
def my_partial():
pass
my_lambda = lambda: None
my_partial_lambda = partial(lambda: None)
def test_transaction_from_function():
x = transaction_from_function
assert x(MyClass) == "tests.utils.test_transaction.MyClass"
... | MyClass |
python | pytest-dev__pytest | doc/en/example/multipython.py | {
"start": 540,
"end": 1958
} | class ____:
def __init__(self, version, picklefile):
self.pythonpath = shutil.which(version)
if not self.pythonpath:
pytest.skip(f"{version!r} not found")
self.picklefile = picklefile
def dumps(self, obj):
dumpfile = self.picklefile.with_name("dump.py")
dumpf... | Python |
python | PyCQA__pylint | pylint/lint/pylinter.py | {
"start": 8408,
"end": 53204
} | class ____(
_ArgumentsManager,
_MessageStateHandler,
reporters.ReportsHandlerMixIn,
checkers.BaseChecker,
):
"""Lint Python modules using external checkers.
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker... | PyLinter |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-assemblyai/llama_index/readers/assemblyai/base.py | {
"start": 801,
"end": 3854
} | class ____(BaseReader):
"""
Reader for AssemblyAI audio transcripts.
It uses the AssemblyAI API to transcribe audio files
and loads the transcribed text into one or more Documents,
depending on the specified format.
To use, you should have the ``assemblyai`` python package installed, and the
... | AssemblyAIAudioTranscriptReader |
python | gevent__gevent | src/gevent/libev/watcher.py | {
"start": 6443,
"end": 6492
} | class ____(_base.ForkMixin, watcher):
pass
| fork |
python | EpistasisLab__tpot | tpot/builtin_modules/genetic_encoders.py | {
"start": 2947,
"end": 4239
} | class ____(TransformerMixin, BaseEstimator ):
"""This class contains the function definition for encoding the input features as a Heterozygote Advantage genetic model.
The encoding used is AA(0)->0, Aa(1)->1, aa(2)->0. """
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged.
... | HeterosisEncoder |
python | keon__algorithms | tests/test_compression.py | {
"start": 227,
"end": 1277
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.file_in_name = "huffman_coding_in.txt"
cls.file_out_bin_name = "huffman_coding_out.bin"
cls.file_out_name = "huffman_coding_out.txt"
def setUp(self):
import random
random.seed(1951)
with ope... | TestHuffmanCoding |
python | wandb__wandb | wandb/vendor/pygments/lexers/dsls.py | {
"start": 23482,
"end": 26223
} | class ____(RegexLexer):
"""
Lexer for `crmsh <http://crmsh.github.io/>`_ configuration files
for Pacemaker clusters.
.. versionadded:: 2.1
"""
name = 'Crmsh'
aliases = ['crmsh', 'pcmk']
filenames = ['*.crmsh', '*.pcmk']
mimetypes = []
elem = words((
'node', 'primitive',... | CrmshLexer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.