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 | ray-project__ray | doc/source/tune/doc_code/key_concepts.py | {
"start": 555,
"end": 4752
} | class ____(tune.Trainable):
def setup(self, config):
# config (dict): A dict of hyperparameters
self.x = 0
self.a = config["a"]
self.b = config["b"]
def step(self): # This is called iteratively.
score = objective(self.x, self.a, self.b)
self.x += 1
retur... | Trainable |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 170830,
"end": 174904
} | class ____:
# elision is only triggered on relatively large arrays
def test_extension_incref_elide(self):
# test extension (e.g. cython) calling PyNumber_* slots without
# increasing the reference counts
#
# def incref_elide(a):
# d = input.copy() # refcount 1
... | TestTemporaryElide |
python | huggingface__transformers | tests/models/aria/test_modeling_aria.py | {
"start": 7885,
"end": 26272
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("rhymes-ai/Aria")
cleanup(torch_device, gc_collect=True)
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@require_torch_large_accelerator
@require_bitsandbytes
def test... | AriaForConditionalGenerationIntegrationTest |
python | mkdocs__mkdocs | mkdocs/tests/utils/utils_tests.py | {
"start": 16374,
"end": 19142
} | class ____(unittest.TestCase):
def setUp(self):
utils.get_themes.cache_clear()
def test_get_themes(self):
themes = utils.get_theme_names()
self.assertIn('mkdocs', themes)
self.assertIn('readthedocs', themes)
@mock.patch('mkdocs.utils.entry_points', autospec=True)
def te... | ThemeUtilsTests |
python | google__pytype | pytype/pytd/optimize.py | {
"start": 21153,
"end": 21852
} | class ____(visitors.Visitor):
"""Converts mutable parameters to unions. This is lossy.
For example, this will change
def f(x: list[int]):
x = list[Union[int, float]]
to
def f(x: Union[list[int], list[Union[int, float]])
.
(Use optimize.CombineContainers to then change x to list[Union[int, float... | AbsorbMutableParameters |
python | bokeh__bokeh | src/bokeh/models/dom.py | {
"start": 2526,
"end": 2909
} | class ____(DOMNode):
""" Base class for DOM elements. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
style = Either(Instance(Styles), Dict(String, String), default={})
children = List(Either(Strin... | DOMElement |
python | imageio__imageio | imageio/plugins/ffmpeg.py | {
"start": 26979,
"end": 30141
} | class ____(threading.Thread):
"""Thread to keep reading the frame data from stdout. This is
useful when streaming from a webcam. Otherwise, if the user code
does not grab frames fast enough, the buffer will fill up, leading
to lag, and ffmpeg can also stall (experienced on Linux). The
get_frame() me... | FrameCatcher |
python | matplotlib__matplotlib | galleries/examples/event_handling/cursor_demo.py | {
"start": 946,
"end": 3102
} | class ____:
"""
A cross hair cursor.
"""
def __init__(self, ax):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.... | Cursor |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/file/json.py | {
"start": 426,
"end": 3613
} | class ____(NodeParser):
"""
JSON node parser.
Splits a document into Nodes using custom JSON splitting logic.
Args:
include_metadata (bool): whether to include metadata in nodes
include_prev_next_rel (bool): whether to include prev/next relationships
"""
@classmethod
def ... | JSONNodeParser |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/test_whoosh_backend.py | {
"start": 3806,
"end": 28390
} | class ____(WhooshTestCase):
fixtures = ["bulk_data.json"]
def setUp(self):
super().setUp()
self.old_ui = connections["whoosh"].get_unified_index()
self.ui = UnifiedIndex()
self.wmmi = WhooshMockSearchIndex()
self.wmmidni = WhooshMockSearchIndexWithSkipDocument()
... | WhooshSearchBackendTestCase |
python | ray-project__ray | python/ray/data/datasource/datasource.py | {
"start": 12685,
"end": 15168
} | class ____(Callable[[], Iterable[Block]]):
"""A function used to read blocks from the :class:`~ray.data.Dataset`.
Read tasks are generated by :meth:`~ray.data.Datasource.get_read_tasks`,
and return a list of ``ray.data.Block`` when called. Initial metadata about the read
operation can be retrieved via ... | ReadTask |
python | celery__celery | celery/utils/imports.py | {
"start": 716,
"end": 5048
} | class ____(Exception):
"""Raised when importing a package, but it's not a package."""
def qualname(obj):
"""Return object name."""
if not hasattr(obj, '__name__') and hasattr(obj, '__class__'):
obj = obj.__class__
q = getattr(obj, '__qualname__', None)
if '.' not in q:
q = '.'.join... | NotAPackage |
python | huggingface__transformers | src/transformers/models/edgetam/modeling_edgetam.py | {
"start": 3459,
"end": 6114
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, height, width, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
fpn_hidden_states (`tuple(torch.FloatTensor)`):
Tuple of `torch.FloatTensor` (one for each featur... | EdgeTamVisionEncoderOutput |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 40111,
"end": 45530
} | class ____(Blockwise):
_parameters = ["frame", "other", "drop", "new_divisions", "append"]
_defaults = {"append": False, "new_divisions": None, "drop": True}
_keyword_only = ["drop", "new_divisions", "append"]
_is_length_preserving = True
_preserves_partitioning_information = True
@staticmethod... | SetIndexBlockwise |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/ccroot.py | {
"start": 18582,
"end": 19729
} | class ____(Task.Task):
def runnable_status(self):
return Task.SKIP_ME
@extension('.o', '.obj')
def add_those_o_files(self, node):
tsk = self.create_task('fake_o', [], node)
try:
self.compiled_tasks.append(tsk)
except AttributeError:
self.compiled_tasks = [tsk]
@feature('fake_... | fake_o |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 412152,
"end": 412534
} | class ____:
def test_sf(self):
# During development of gh-18822, we found that the override of
# kappa3.sf could experience overflow where the version in main did
# not. Check that this does not happen in final implementation.
sf0 = 1 - stats.kappa3.cdf(0.5, 1e5)
sf1 = stats.... | TestKappa3 |
python | django__django | tests/invalid_models_tests/test_relative_fields.py | {
"start": 56193,
"end": 61487
} | class ____(SimpleTestCase):
def test_clash_between_accessors(self):
class Model(models.Model):
first_m2m = models.ManyToManyField("self", symmetrical=False)
second_m2m = models.ManyToManyField("self", symmetrical=False)
self.assertEqual(
Model.check(),
... | SelfReferentialM2MClashTests |
python | huggingface__transformers | tests/models/glm/test_modeling_glm.py | {
"start": 1255,
"end": 1394
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = GlmModelTester
@slow
@require_torch_large_accelerator
| GlmModelTest |
python | getsentry__sentry | src/sentry/rules/history/endpoints/project_rule_group_history.py | {
"start": 2066,
"end": 3276
} | class ____(RuleEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
@extend_schema(
operation_id="Retrieve a Group Firing History for an Issue Alert",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.PROJECT_ID_OR_SLUG,
Issu... | ProjectRuleGroupHistoryIndexEndpoint |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 45242,
"end": 45722
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("repository_id", "name", "client_mutation_id")
repository_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="repositoryId"
)
name = sgqlc.types.Field... | AcceptTopicSuggestionInput |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py | {
"start": 3372,
"end": 3521
} | class ____(graphene.ObjectType):
results = non_null_list(GraphenePipelineTag)
class Meta:
name = "PartitionTags"
| GraphenePartitionTags |
python | celery__celery | t/unit/utils/test_local.py | {
"start": 6873,
"end": 8215
} | class ____:
def test_only_evaluated_once(self):
class X:
attr = 123
evals = 0
def __init__(self):
self.__class__.evals += 1
p = PromiseProxy(X)
assert p.attr == 123
assert p.attr == 123
assert X.evals == 1
def test_... | test_PromiseProxy |
python | networkx__networkx | networkx/classes/coreviews.py | {
"start": 1531,
"end": 2124
} | class ____(AtlasView):
"""An AdjacencyView is a Read-only Map of Maps of Maps.
It is a View into a dict-of-dict-of-dict data structure.
The inner level of dict is read-write. But the
outer levels are read-only.
See Also
========
AtlasView: View into dict-of-dict
MultiAdjacencyView: Vie... | AdjacencyView |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 12436,
"end": 12591
} | class ____(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a single grammar production rule."""
# other directive-level nodes
| production |
python | google__jax | jax/experimental/mosaic/gpu/layout_inference.py | {
"start": 2433,
"end": 2615
} | class ____(enum.IntEnum):
"""The type of a variable.
Variables are operands, results, or arguments of MLIR operations.
"""
OPERAND = 0
RESULT = 1
ARGUMENT = 2
| VariableType |
python | celery__celery | t/unit/worker/test_heartbeat.py | {
"start": 798,
"end": 2384
} | class ____:
def test_start_stop(self):
timer = MockTimer()
eventer = MockDispatcher()
h = Heart(timer, eventer, interval=1)
h.start()
assert h.tref
h.stop()
assert h.tref is None
h.stop()
def test_send_sends_signal(self):
h = Heart(MockTi... | test_Heart |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_complex.py | {
"start": 190,
"end": 463
} | class ____(BaseTestZDType):
def scalar_equals(self, scalar1: object, scalar2: object) -> bool:
if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload]
return True
return super().scalar_equals(scalar1, scalar2)
| _BaseTestFloat |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_legend07.py | {
"start": 315,
"end": 1255
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_legend07.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 28478,
"end": 36231
} | class ____(T5PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
self.is_decoder = config.is_decoder
self.block = nn.ModuleList(
[T5Block(config, has_relative_attention_bias=bool(i ==... | T5Stack |
python | PrefectHQ__prefect | tests/server/utilities/test_text_search_parser.py | {
"start": 11699,
"end": 14813
} | class ____:
"""Test edge cases and documented limitations"""
def test_literal_dash_at_start_not_supported(self):
# Searching for literal `-` at start is not supported
# This should be treated as exclusion, not literal dash
result = parse_text_search_query("-")
assert result == T... | TestEdgeCasesAndLimitations |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/sequential.py | {
"start": 403,
"end": 4506
} | class ____(Chain):
"""Chain where the outputs of one chain feed directly into next."""
chains: list[Chain]
input_variables: list[str]
output_variables: list[str]
return_all: bool = False
model_config = ConfigDict(
arbitrary_types_allowed=True,
extra="forbid",
)
@proper... | SequentialChain |
python | getsentry__sentry | src/sentry/sentry_apps/services/app/model.py | {
"start": 5130,
"end": 5739
} | class ____(RpcModel):
id: str = ""
label: str = ""
action_type: str = ""
enabled: bool = True
@property
def actionType(self) -> str:
return self.action_type
def is_enabled(self) -> bool:
return self.enabled
@classmethod
def from_event(cls, data_interface: SentryApp... | RpcSentryAppEventData |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 44960,
"end": 53133
} | class ____(MBartPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
_tied_weights_keys = {"lm_head.weight": "model.shared.weight"}
def __init__(self, config: MBartConfig):
super().__init__(config)
self.model = MBartModel... | MBartForConditionalGeneration |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 26509,
"end": 26640
} | class ____(BasenameTestCase, TestCase):
def setUp(self):
self.router = DefaultRouter()
| TestDuplicateBasenameDefaultRouter |
python | mlflow__mlflow | mlflow/server/auth/entities.py | {
"start": 4753,
"end": 5952
} | class ____:
def __init__(
self,
experiment_id,
scorer_name,
user_id,
permission,
):
self._experiment_id = experiment_id
self._scorer_name = scorer_name
self._user_id = user_id
self._permission = permission
@property
def experiment_... | ScorerPermission |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 135160,
"end": 138032
} | class ____(DefaultGenerator, ABC):
"""A plain default value on a column.
This could correspond to a constant, a callable function,
or a SQL clause.
:class:`.ColumnDefault` is generated automatically
whenever the ``default``, ``onupdate`` arguments of
:class:`_schema.Column` are used. A :class... | ColumnDefault |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/benchmarks/pdsh.py | {
"start": 1035,
"end": 31158
} | class ____:
"""PDS-H query definitions."""
name: str = "pdsh"
@staticmethod
def q0(run_config: RunConfig) -> pl.LazyFrame:
"""Query 0."""
return pl.LazyFrame()
@staticmethod
def q1(run_config: RunConfig) -> pl.LazyFrame:
"""Query 1."""
lineitem = get_data(run_c... | PDSHQueries |
python | getsentry__sentry | src/sentry/uptime/endpoints/serializers.py | {
"start": 1729,
"end": 2025
} | class ____(UptimeSubscriptionSerializerResponse):
id: str
projectSlug: str
environment: str | None
name: str
status: str
uptimeStatus: int
mode: int
owner: ActorSerializerResponse
recoveryThreshold: int
downtimeThreshold: int
| UptimeDetectorSerializerResponse |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 1796,
"end": 46884
} | class ____(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
run_inserts = "once"
run_deletes = None
def test_basic(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
... | EagerTest |
python | automl__auto-sklearn | autosklearn/ensembles/ensemble_selection.py | {
"start": 621,
"end": 14007
} | class ____(AbstractEnsemble):
def __init__(
self,
task_type: int,
metrics: Sequence[Scorer] | Scorer,
backend: Backend,
ensemble_size: int = 50,
bagging: bool = False,
mode: str = "fast",
random_state: int | np.random.RandomState | None = None,
) -... | EnsembleSelection |
python | getsentry__sentry | tests/sentry/integrations/slack/test_notify_action.py | {
"start": 1206,
"end": 15443
} | class ____(RuleTestCase):
rule_cls = SlackNotifyServiceAction
def mock_list(self, list_type, channels, result_name="channels"):
return mock_slack_response(f"{list_type}_list", body={"ok": True, result_name: channels})
def mock_conversations_info(self, channel):
return mock_slack_response(
... | SlackNotifyActionTest |
python | realpython__materials | python-class/mro.py | {
"start": 0,
"end": 61
} | class ____:
def method(self):
print("A.method()")
| A |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image_anchor03.py | {
"start": 315,
"end": 1246
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image_anchor03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Wo... | TestCompareXLSXFiles |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1174562,
"end": 1174762
} | class ____(SelectionInit):
"""PrimitiveValue schema wrapper."""
_schema = {"$ref": "#/definitions/PrimitiveValue"}
def __init__(self, *args):
super().__init__(*args)
| PrimitiveValue |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 33615,
"end": 34358
} | class ____(IntegralTransform):
""" Base class for Fourier transforms."""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %s must implement b(self) but does not" %... | FourierTypeTransform |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataprep.py | {
"start": 8309,
"end": 9443
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataprep.GoogleDataprepHook")
def test_execute(self, hook_mock):
op = DataprepDeleteFlowOperator(
task_id=TASK_ID,
dataprep_conn_id=DATAPREP_CONN_ID,
flow_id=FLOW_ID,
)
op.execute(contex... | TestDataprepDeleteFlowOperator |
python | django__django | tests/logging_tests/views.py | {
"start": 525,
"end": 1028
} | class ____(Exception):
pass
def uncaught_exception(request):
raise UncaughtException("Uncaught exception")
def internal_server_error(request):
status = request.GET.get("status", 500)
return HttpResponseServerError("Server Error", status=int(status))
def permission_denied(request):
raise Permis... | UncaughtException |
python | huggingface__transformers | utils/modular_model_converter.py | {
"start": 4435,
"end": 8600
} | class ____(m.MatcherDecoratableTransformer):
"""A transformer that replaces `old_name` with `new_name` in comments, string and any references.
It should take into account name like `MyNewModel`, or `my_new_model`. Without using the AUTO_MAPPING.
Supported renaming patterns:
- llama -> my_new_model ... | ReplaceNameTransformer |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 2196,
"end": 5014
} | class ____(TestCase):
def setUp(self):
self.instance = UniquenessModel.objects.create(username='existing')
def test_repr(self):
serializer = UniquenessSerializer()
expected = dedent("""
UniquenessSerializer():
id = IntegerField(label='ID', read_only=True)
... | TestUniquenessValidation |
python | realpython__materials | python-property/circle_v3.py | {
"start": 0,
"end": 380
} | class ____:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = float(value)
@property
def diameter(self):
return self.radius * 2
@diameter.setter
d... | Circle |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 101885,
"end": 103479
} | class ____(SingleContinuousDistribution):
_argnames = ('b', 'eta')
set = Interval(0, oo)
@staticmethod
def check(b, eta):
_value_check(b > 0, "b must be positive")
_value_check(eta > 0, "eta must be positive")
def pdf(self, x):
b, eta = self.b, self.eta
return b*ex... | ShiftedGompertzDistribution |
python | getsentry__sentry | tests/sentry/receivers/test_sentry_apps.py | {
"start": 1112,
"end": 8176
} | class ____(APITestCase):
def setUp(self) -> None:
self.issue = self.create_group(project=self.project)
self.sentry_app = self.create_sentry_app(
events=["issue.resolved", "issue.ignored", "issue.unresolved"]
)
self.install = self.create_sentry_app_installation(
... | TestIssueWorkflowNotifications |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 25091,
"end": 25160
} | class ____(HtmlMixin, etree.PIBase):
pass
| HtmlProcessingInstruction |
python | getsentry__sentry | src/sentry/users/models/email.py | {
"start": 485,
"end": 2442
} | class ____(Model):
"""
Email represents a unique email. Email settings (unsubscribe state) should be associated here.
UserEmail represents whether a given user account has access to that email.
"""
__relocation_scope__ = RelocationScope.User
__relocation_dependencies__ = {"sentry.User"}
__r... | Email |
python | tiangolo__fastapi | docs_src/cookie_param_models/tutorial001_an.py | {
"start": 152,
"end": 391
} | class ____(BaseModel):
session_id: str
fatebook_tracker: Union[str, None] = None
googall_tracker: Union[str, None] = None
@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
return cookies
| Cookies |
python | pytorch__pytorch | test/package/package_a/test_nn_module.py | {
"start": 55,
"end": 1234
} | class ____(torch.nn.Module):
def __init__(self, nz=6, ngf=9, nc=3):
super().__init__()
self.main = torch.nn.Sequential(
# input is Z, going into a convolution
torch.nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False),
torch.nn.BatchNorm2d(ngf * 8),
to... | TestNnModule |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 31698,
"end": 42075
} | class ____(_repr.Representation):
"""
Info:
To use this type, you need to install the optional
[`email-validator`](https://github.com/JoshData/python-email-validator) package:
```bash
pip install email-validator
```
Validate a name and email address combination, as ... | NameEmail |
python | openai__openai-python | src/openai/types/chat/chat_completion_allowed_tools_param.py | {
"start": 265,
"end": 1010
} | class ____(TypedDict, total=False):
mode: Required[Literal["auto", "required"]]
"""Constrains the tools available to the model to a pre-defined set.
`auto` allows the model to pick from among the allowed tools and generate a
message.
`required` requires the model to call one or more of the allowed... | ChatCompletionAllowedToolsParam |
python | jazzband__django-oauth-toolkit | tests/migrations/0005_basetestapplication_allowed_origins_and_more.py | {
"start": 158,
"end": 878
} | class ____(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.OAUTH2_PROVIDER_ID_TOKEN_MODEL),
("tests", "0004_basetestapplication_hash_client_secret_and_more"),
]
operations = [
migrations.AddField(
model_name="basetestapplication",
... | Migration |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 19522,
"end": 21323
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`CLIPEncoderLayer`].
Args:
config: CLIPConfig
"""
def __init__(self, config: CLIPConfig):
super().__init__()
self.config = config
self... | CLIPEncoder |
python | keras-team__keras | keras/src/utils/torch_utils_test.py | {
"start": 370,
"end": 1363
} | class ____(models.Model):
def __init__(
self, use_batch_norm=False, num_torch_layers=1, *args, **kwargs
):
super().__init__(*args, **kwargs)
self.use_batch_norm = use_batch_norm
self.num_torch_layers = num_torch_layers
self.torch_wrappers = []
for _ in range(num_t... | Classifier |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-rag-evaluator/llama_index/packs/rag_evaluator/base.py | {
"start": 913,
"end": 16825
} | class ____(BaseLlamaPack):
"""
A pack for performing evaluation with your own RAG pipeline.
Args:
query_engine: The RAG pipeline to evaluate.
rag_dataset: The BaseLlamaDataset to evaluate on.
judge_llm: The LLM to use as the evaluator.
"""
def __init__(
self,
... | RagEvaluatorPack |
python | ansible__ansible | test/lib/ansible_test/_internal/diff.py | {
"start": 391,
"end": 1004
} | class ____:
"""Parsed diff for a single file."""
def __init__(self, old_path: str, new_path: str) -> None:
self.old = DiffSide(old_path, new=False)
self.new = DiffSide(new_path, new=True)
self.headers: list[str] = []
self.binary = False
def append_header(self, line: str) ->... | FileDiff |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 41858,
"end": 42719
} | class ____(Response):
"""
Response of projects.create endpoint.
:param id: Project id
:type id: str
"""
_service = "projects"
_action = "create"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"id": {"description": "Project id", "type": ["string", "n... | CreateResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py | {
"start": 3764,
"end": 3894
} | class ____(TypedDict):
x: NotRequired[Never]
y: ReadOnly[int]
def update_a(a: TD18, b: TD19) -> None:
a.update(b)
| TD19 |
python | falconry__falcon | falcon/media/handlers.py | {
"start": 917,
"end": 1652
} | class ____(BinaryBaseHandlerWS):
"""Placeholder handler that always raises an error.
This handler is used by the framework for media types that require an
external dependency that can not be found.
"""
def __init__(self, handler: str, library: str) -> None:
self._msg = ('The {} requires th... | MissingDependencyHandler |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 12901,
"end": 13152
} | class ____(DagsterUserCodeExecutionError):
"""Indicates an error in the op type system at runtime. E.g. a op receives an
unexpected input, or produces an output that does not match the type of the output definition.
"""
| DagsterTypeCheckError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol4.py | {
"start": 506,
"end": 648
} | class ____:
x: int
# This should generate an error because x is not a ClassVar in B
# but is a ClassVar in the protocol.
b: ProtoB = B()
| B |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_types.py | {
"start": 7265,
"end": 8875
} | class ____(_LiteralRoundTripFixture, fixtures.TablesTest):
"""Add ARRAY test suite, #8138.
This only works on PostgreSQL right now.
"""
__requires__ = ("array_type",)
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"array_table",
m... | ArrayTest |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 135952,
"end": 136292
} | class ____(Response):
"""
Response of events.multi_task_scalar_metrics_iter_histogram endpoint.
"""
_service = "events"
_action = "multi_task_scalar_metrics_iter_histogram"
_version = "2.20"
_schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
| MultiTaskScalarMetricsIterHistogramResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 125859,
"end": 130981
} | class ____(DeliveryZoneList):
"""
query DeliveryZoneList {
deliveryProfiles(
first: 1
) {
pageInfo {
hasNextPage
endCursor
}
nodes {
profileLocationGroups(
locationGroupId: "<locationGroupId>"
) {
loc... | DeliveryProfile |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1646,
"end": 1795
} | class ____(ShowFieldTypeAndContent, PolymorphicModel):
field1 = models.CharField(max_length=30)
m2m = models.ManyToManyField("self")
| ModelShow3 |
python | keras-team__keras | keras/src/utils/progbar.py | {
"start": 188,
"end": 10354
} | class ____:
"""Displays a progress bar.
Args:
target: Total number of steps expected, None if unknown.
width: Progress bar width on screen.
verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)
stateful_metrics: Iterable of string names of metrics that should *not*
... | Progbar |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/prev_dagrun_dep.py | {
"start": 1689,
"end": 8878
} | class ____(BaseTIDep):
"""
Is the past dagrun in a state that allows this task instance to run.
For example, did this task instance's task in the previous dagrun complete
if we are depending on past?
"""
NAME = "Previous Dagrun State"
IGNORABLE = True
IS_TASK_DEP = True
@staticmet... | PrevDagrunDep |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/utils.py | {
"start": 12075,
"end": 14368
} | class ____:
"""
This is the placeholder for the tmp stream state for each incremental stream,
It's empty, once the sync has started and is being updated while sync operation takes place,
It holds the `temporary stream state values` before they are updated to have the opportunity to reuse this state.
... | EagerlyCachedStreamState |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 70305,
"end": 70851
} | class ____(HTTPResponse):
default_status = 500
def __init__(self, status=None, body=None, exception=None, traceback=None,
**options):
self.exception = exception
self.traceback = traceback
super(HTTPError, self).__init__(body, status, **options)
#####################... | HTTPError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1008339,
"end": 1008832
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnfollowOrganization"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "organization")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing ... | UnfollowOrganizationPayload |
python | python-visualization__folium | folium/raster_layers.py | {
"start": 431,
"end": 5597
} | class ____(Layer):
"""
Create a tile layer to append on a Map.
Parameters
----------
tiles: str or :class:`xyzservices.TileProvider`, default 'OpenStreetMap'
Map tileset to use. Folium has built-in all tilesets
available in the ``xyzservices`` package. For example, you can pass
... | TileLayer |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 1643,
"end": 4432
} | class ____(
APITransactionTestCase,
SnubaTestCase,
SpanTestCase,
OurLogTestCase,
TraceMetricsTestCase,
ProfileFunctionsTestCase,
):
viewname = "sentry-api-0-organization-events"
referrer = "api.organization-events"
def setUp(self) -> None:
super().setUp()
self.nine_m... | OrganizationEventsEndpointTestBase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py | {
"start": 3700,
"end": 4529
} | class ____(object):
__slots__ = (
# name of descriptor record, also a module global name; a string
'name',
# length of argument, in bytes; an int; UP_TO_NEWLINE and
# TAKEN_FROM_ARGUMENT{1,4,8} are negative values for variable-length
# cases
'n',
# a functio... | ArgumentDescriptor |
python | joblib__joblib | joblib/externals/loky/backend/resource_tracker.py | {
"start": 3251,
"end": 15403
} | class ____(_ResourceTracker):
"""Resource tracker with refcounting scheme.
This class is an extension of the multiprocessing ResourceTracker class
which implements a reference counting scheme to avoid unlinking shared
resources still in use in other processes.
This feature is notably used by `jobl... | ResourceTracker |
python | getsentry__sentry | src/sentry/roles/manager.py | {
"start": 2061,
"end": 3882
} | class ____(Generic[R]):
"""Represent the set of all roles at one level (org or team)."""
def __init__(self, roles: Iterable[R], default_id: str | None = None) -> None:
self._priority_seq = tuple(sorted(roles, key=lambda r: r.priority))
self._id_map = {r.id: r for r in self._priority_seq}
... | RoleLevel |
python | python-openxml__python-docx | src/docx/shared.py | {
"start": 12517,
"end": 13506
} | class ____:
"""Accepts `str` fragments and joins them together, in order, on `.pop().
Handy when text in a stream is broken up arbitrarily and you want to join it back
together within certain bounds. The optional `separator` argument determines how
the text fragments are punctuated, defaulting to the e... | TextAccumulator |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modular_glm4v_moe.py | {
"start": 21860,
"end": 22369
} | class ____(Glm4MoePreTrainedModel):
config: Glm4vMoeConfig
base_model_prefix = "model"
input_modalities = ("text", "image", "video")
_no_split_modules = ["Glm4vMoeTextDecoderLayer", "Glm4vMoeVisionBlock"]
_skip_keys_device_placement = "past_key_values"
_can_record_outputs = {
"hidden_st... | Glm4vMoePreTrainedModel |
python | kamyu104__LeetCode-Solutions | Python/find-the-winner-of-the-circular-game.py | {
"start": 50,
"end": 315
} | class ____(object):
def findTheWinner(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
return reduce(lambda idx, n:(idx+k)%(n+1), xrange(1, n), 0)+1
# Time: O(n)
# Space: O(n)
# top-down solution
| Solution |
python | sqlalchemy__sqlalchemy | test/engine/test_reconnect.py | {
"start": 42750,
"end": 44174
} | class ____(fixtures.TestBase):
__backend__ = True
def test_pre_ping_db_is_restarted(self):
engine = engines.reconnecting_engine(options={"pool_pre_ping": True})
conn = engine.connect()
eq_(conn.execute(select(1)).scalar(), 1)
stale_connection = conn.connection.dbapi_connection
... | PrePingRealTest |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 111267,
"end": 114340
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(50), nullable=False),
... | NoPolyIdentInMiddleTest |
python | python-poetry__poetry | src/poetry/console/commands/run.py | {
"start": 360,
"end": 3364
} | class ____(EnvCommand):
name = "run"
description = "Runs a command in the appropriate environment."
arguments: ClassVar[list[Argument]] = [
argument("args", "The command and arguments/options to run.", multiple=True)
]
def handle(self) -> int:
args = self.argument("args")
s... | RunCommand |
python | pytorch__pytorch | torch/profiler/_memory_profiler.py | {
"start": 11315,
"end": 11780
} | class ____:
def __init__(self, result: _ProfilerResult) -> None:
self._root_nodes = result.experimental_event_tree()
self._sorted_nodes = tuple(sorted(self.dfs(), key=lambda x: x.start_time_ns))
def dfs(self, *args, **kwargs) -> Iterator[_ProfilerEvent]:
yield from _utils.traverse_dfs(s... | OpTree |
python | google__pytype | pytype/tests/test_fiddle_overlay.py | {
"start": 649,
"end": 805
} | class ____:
cwam: cwam.ClassWithAnnotatedMethod
fiddle.Config(
Dataclass,
cwam=fiddle.Config(cwam.ClassWithAnnotatedMethod.method),
)
"""
| Dataclass |
python | getsentry__sentry | src/sentry/metrics/precise_dogstatsd.py | {
"start": 171,
"end": 4519
} | class ____(MetricsBackend):
def __init__(self, prefix: str | None = None, **kwargs: Any) -> None:
self.tags = kwargs.pop("tags", None)
instance_kwargs: dict[str, Any] = {
"disable_telemetry": True,
"disable_buffering": False,
# When enabled, a background thread w... | PreciseDogStatsdMetricsBackend |
python | gevent__gevent | src/greentest/3.13/test_socket.py | {
"start": 200061,
"end": 206890
} | class ____(ThreadedTCPSocketTest):
def __init__(self, methodName='runTest'):
self.event = threading.Event()
ThreadedTCPSocketTest.__init__(self, methodName=methodName)
def assert_sock_timeout(self, sock, timeout):
self.assertEqual(self.serv.gettimeout(), timeout)
blocking = (t... | NonBlockingTCPTests |
python | kamyu104__LeetCode-Solutions | Python/delete-node-in-a-bst.py | {
"start": 29,
"end": 937
} | class ____(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return root
if root.val > key:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec3.py | {
"start": 1723,
"end": 2614
} | class ____:
def __call__(self, *args, **kwargs) -> None: ...
def func7(f1: Callable[P, R], f2: Callable[P, R]) -> Callable[P, R]: ...
def func8(cb1: Callback1, cb2: Callback2, cb3: Callback3):
v1 = func7(cb1, cb2)
reveal_type(v1, expected_text="(x: int, /) -> None")
v2 = func7(cb1, cb3)
reveal_... | Callback3 |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 43342,
"end": 43562
} | class ____(BaseModel, extra="forbid"):
type: "GeoIndexType" = Field(..., description="")
on_disk: Optional[bool] = Field(default=None, description="If true, store the index on disk. Default: false.")
| GeoIndexParams |
python | scipy__scipy | tools/ninjatracing.py | {
"start": 1004,
"end": 2313
} | class ____:
"""Represents a single line read for a .ninja_log file. Start and end times
are milliseconds."""
def __init__(self, start, end):
self.start = int(start)
self.end = int(end)
self.targets = []
def read_targets(log, show_all):
"""Reads all targets from .ninja_log file ... | Target |
python | google__pytype | pytype/abstract/_instances.py | {
"start": 13118,
"end": 17819
} | class ____( # pytype: disable=signature-mismatch
_instance_base.Instance, mixin.HasSlots, mixin.PythonConstant
):
"""Representation of Python 'list' objects."""
def __init__(self, content, ctx: "context.Context") -> None:
super().__init__(ctx.convert.list_type, ctx)
self._instance_cache = {}
combi... | List |
python | arrow-py__arrow | arrow/locales.py | {
"start": 31272,
"end": 33373
} | class ____(SlavicBaseLocale):
names = ["pl", "pl-pl"]
past = "{0} temu"
future = "za {0}"
# The nouns should be in genitive case (Polish: "dopełniacz")
# in order to correctly form `past` & `future` expressions.
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {... | PolishLocale |
python | sympy__sympy | sympy/polys/orderings.py | {
"start": 1107,
"end": 1316
} | class ____(MonomialOrder):
"""Graded lexicographic order of monomials. """
alias = 'grlex'
is_global = True
def __call__(self, monomial):
return (sum(monomial), monomial)
| GradedLexOrder |
python | tiangolo__fastapi | docs_src/sql_databases/tutorial002_an_py310.py | {
"start": 485,
"end": 2567
} | class ____(HeroBase):
name: str | None = None
age: int | None = None
secret_name: str | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, connect_args=connect_args)
def create_db_and_t... | HeroUpdate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.