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 | pandas-dev__pandas | pandas/core/computation/ops.py | {
"start": 14183,
"end": 14487
} | class ____:
def __init__(self, name: str) -> None:
if name not in MATHOPS:
raise ValueError(f'"{name}" is not a supported function')
self.name = name
self.func = getattr(np, name)
def __call__(self, *args) -> MathCall:
return MathCall(self, args)
| FuncNode |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/reduce_join_op_test.py | {
"start": 3280,
"end": 13722
} | class ____(UnicodeTestCase):
def _testReduceJoin(self,
input_array,
truth,
truth_shape,
axis,
keep_dims=False,
separator=""):
"""Compares the output of reduce_join to an expected re... | ReduceJoinTest |
python | keras-team__keras | keras/src/metrics/confusion_metrics_test.py | {
"start": 24652,
"end": 28632
} | class ____(testing.TestCase):
def test_config(self):
s_obj = metrics.SensitivityAtSpecificity(
0.4,
num_thresholds=100,
class_id=12,
name="sensitivity_at_specificity_1",
)
self.assertEqual(s_obj.name, "sensitivity_at_specificity_1")
sel... | SensitivityAtSpecificityTest |
python | davidhalter__jedi | test/completion/inheritance.py | {
"start": 113,
"end": 450
} | class ____(Super):
#? 13 Sub.attribute
def attribute(self):
pass
#! 8 ['attribute = 3']
def attribute(self):
pass
#! 4 ['def func']
func = 3
#! 12 ['def func']
class func(): pass
#! 8 ['class Inner']
def Inner(self): pass
# -----------------
# Finding self
# -... | Sub |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_special_math_ops_test.py | {
"start": 9574,
"end": 11694
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_spence_boundary(self):
self.assertAllClose(np.pi**2 / 6., special_math_ops.spence(0.))
self.assertAllClose(0., special_math_ops.spence(1.))
self.assertTrue(np.isnan(self.evaluate(special_math_ops.spence(... | SpenceTest |
python | lxml__lxml | src/lxml/html/_setmixin.py | {
"start": 113,
"end": 1188
} | class ____(MutableSet):
"""
Mix-in for sets. You must define __iter__, add, remove
"""
def __len__(self):
length = 0
for item in self:
length += 1
return length
def __contains__(self, item):
for has_item in self:
if item == has_item:
... | SetMixin |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/widgets/status.py | {
"start": 786,
"end": 4745
} | class ____(StatusBarWidget):
"""Status bar widget for LSP status."""
ID = 'lsp_status'
INTERACT_ON_CLICK = True
BASE_TOOLTIP = _(
"Completions, linting, code\n"
"folding and symbols status."
)
STATUS = "LSP: {}"
def __init__(self, parent, provider):
self.tooltip =... | LSPStatusWidget |
python | tensorflow__tensorflow | tensorflow/python/distribute/step_fn.py | {
"start": 1831,
"end": 4086
} | class ____(StandardInputStep):
"""A step function that implements a training step for a feed forward network.
An instance of this class is intended to be used as a callable:
```python
...
step = step_fn.StandardSingleLossStep(
dataset, loss_fn, optimizer, distribution)
# Run a single training step ... | StandardSingleLossStep |
python | getsentry__sentry | src/sentry/search/events/builder/metrics.py | {
"start": 67828,
"end": 71368
} | class ____(MetricsQueryBuilder):
def __init__(
self,
*args: Any,
granularity: int,
time_range_window: int,
**kwargs: Any,
):
self._granularity = granularity
self._time_range_window = time_range_window
super().__init__(*args, **kwargs)
def reso... | AlertMetricsQueryBuilder |
python | doocs__leetcode | solution/2300-2399/2322.Minimum Score After Removals on a Tree/Solution.py | {
"start": 0,
"end": 991
} | class ____:
def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
def dfs(i: int, fa: int) -> int:
res = nums[i]
for j in g[i]:
if j != fa:
res ^= dfs(j, i)
return res
def dfs2(i: int, fa: int) -> int:
... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 288417,
"end": 302956
} | class ____(FieldChannelMixin, core.FieldDefWithoutScale):
r"""
Key schema wrapper.
Definition object for a data field, its type and transformation of an encoding channel.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and ... | Key |
python | pola-rs__polars | py-polars/src/polars/config.py | {
"start": 5291,
"end": 54092
} | class ____(contextlib.ContextDecorator):
"""
Configure polars; offers options for table formatting and more.
Notes
-----
Can also be used as a context manager OR a function decorator in order to
temporarily scope the lifetime of specific options. For example:
>>> with pl.Config() as cfg:
... | Config |
python | getsentry__sentry | tests/sentry/replays/endpoints/test_project_replay_video_details.py | {
"start": 387,
"end": 5191
} | class ____(APITestCase, ReplaysSnubaTestCase):
endpoint = "sentry-api-0-project-replay-video-details"
def setUp(self) -> None:
super().setUp()
self.replay_id = uuid.uuid4().hex
self.segment_id = 0
self.segment_data = b"hello, world!"
self.segment_data_size = len(self.seg... | ReplayVideoDetailsTestCase |
python | pyparsing__pyparsing | examples/tiny/tiny_ast.py | {
"start": 4013,
"end": 6270
} | class ____(TinyNode):
"""Dataclass node representing the `main` function body.
- Prebuilds and stores the list of child statement nodes under
`statements` at construction time.
- Execution pushes a new frame, executes each statement in order, and
returns the value propagated by a `return` (via ... | MainDeclNode |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/pagination.py | {
"start": 274,
"end": 1752
} | class ____(Generic[T]):
results: Sequence[T]
cursor: str
has_more: bool
"""
A wrapper for paginated connection results of type T.
Attributes:
results (Sequence[T]): The sequence of returned objects
cursor (Optional[str]): Pagination cursor for fetching next page
has_mor... | PaginatedResults |
python | mlflow__mlflow | dev/clint/src/clint/index.py | {
"start": 5198,
"end": 7765
} | class ____:
"""Index of all symbols (functions, classes) in the MLflow codebase."""
def __init__(
self,
import_mapping: dict[str, str],
func_mapping: dict[str, FunctionInfo],
) -> None:
self.import_mapping = import_mapping
self.func_mapping = func_mapping
def sa... | SymbolIndex |
python | pennersr__django-allauth | allauth/mfa/webauthn/forms.py | {
"start": 1919,
"end": 2334
} | class ____(_BaseAddWebAuthnForm):
if app_settings.PASSKEY_LOGIN_ENABLED:
passwordless = forms.BooleanField(
label=_("Passwordless"),
required=False,
help_text=_(
"Enabling passwordless operation allows you to sign in using just this key, but imposes additi... | AddWebAuthnForm |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 5158,
"end": 6888
} | class ____(nn.Module):
def __init__(self, config: MllamaVisionConfig):
super().__init__()
self.max_num_tiles = config.max_num_tiles
self.max_aspect_ratio_id = config.max_aspect_ratio_id
self.num_patches = (config.image_size // config.patch_size) ** 2 + 1
self.hidden_size = co... | MllamaPrecomputedPositionEmbedding |
python | openai__openai-python | src/openai/types/container_create_params.py | {
"start": 274,
"end": 591
} | class ____(TypedDict, total=False):
name: Required[str]
"""Name of the container to create."""
expires_after: ExpiresAfter
"""Container expiration time in seconds relative to the 'anchor' time."""
file_ids: SequenceNotStr[str]
"""IDs of files to copy to the container."""
| ContainerCreateParams |
python | jazzband__django-formtools | tests/wizard/wizardtests/tests.py | {
"start": 11679,
"end": 12681
} | class ____(WizardTests, TestCase):
wizard_url = '/wiz_cookie/'
wizard_step_1_data = {
'cookie_contact_wizard-current_step': 'form1',
}
wizard_step_data = (
{
'form1-name': 'Pony',
'form1-thirsty': '2',
'cookie_contact_wizard-current_step': 'form1',
... | CookieWizardTests |
python | ray-project__ray | doc/source/serve/doc_code/scheduled_batch_processing.py | {
"start": 439,
"end": 845
} | class ____:
async def __call__(self) -> str:
# Simulate batch processing work
await asyncio.sleep(0.5)
return "Hello, world!"
app = BatchProcessingDeployment.bind()
# __serve_example_end__
if __name__ == "__main__":
import requests # noqa
serve.run(app)
resp = requests.get("... | BatchProcessingDeployment |
python | Textualize__textual | src/textual/widgets/_text_area.py | {
"start": 2637,
"end": 2847
} | class ____(Exception):
"""Raised when the user tries to use a language which does not exist.
This means a language which is not builtin, or has not been registered.
"""
@dataclass
| LanguageDoesNotExist |
python | numpy__numpy | numpy/_core/tests/test_scalar_ctors.py | {
"start": 1317,
"end": 2336
} | class ____:
def test_superclass(self):
# try both positional and keyword arguments
s = np.str_(b'\\x61', encoding='unicode-escape')
assert s == 'a'
s = np.str_(b'\\x61', 'unicode-escape')
assert s == 'a'
# previously this would return '\\xx'
with pytest.raise... | TestExtraArgs |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/asset/decorators.py | {
"start": 8328,
"end": 9637
} | class ____(_DAGFactory):
"""Create an asset by decorating a materialization function."""
name: str | None = None
uri: str | ObjectStoragePath | None = None
group: str = Asset.asset_type
extra: dict[str, JsonValue] = attrs.field(factory=dict)
watchers: list[BaseTrigger] = attrs.field(factory=lis... | asset |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 8587,
"end": 8981
} | class ____(_Union):
user_input: Annotated[UserInputSpec, 10]
parameter: Annotated[InputToParameterSpec, 20]
buffer: Annotated[InputToBufferSpec, 30]
tensor_constant: Annotated[InputToTensorConstantSpec, 40]
custom_obj: Annotated[InputToCustomObjSpec, 50]
token: Annotated[InputTokenSpec, 70]
... | InputSpec |
python | Netflix__metaflow | test/core/tests/flow_options.py | {
"start": 67,
"end": 754
} | class ____(MetaflowTest):
"""
Test that the metaflow_extensions module is properly loaded
"""
PRIORITY = 0
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"rec... | FlowOptionsTest |
python | pypa__setuptools | setuptools/tests/test_core_metadata.py | {
"start": 13438,
"end": 20874
} | class ____:
STATIC_CONFIG = {
"setup.cfg": cleandoc(
"""
[metadata]
name = package
version = 0.0.1
author = Foo Bar
author_email = foo@bar.net
long_description = Long
description
de... | TestPEP643 |
python | getsentry__sentry | src/sentry/migrations/0905_fix_workflow_engine_cycle.py | {
"start": 230,
"end": 3474
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | django__django | tests/extra_regress/models.py | {
"start": 746,
"end": 862
} | class ____(models.Model):
created_by = models.ForeignKey(User, models.CASCADE)
text = models.TextField()
| Order |
python | anthropics__anthropic-sdk-python | tests/lib/tools/test_runners.py | {
"start": 8365,
"end": 30123
} | class ____:
@pytest.mark.respx(base_url=base_url)
def test_basic_call_sync(self, client: Anthropic, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None:
@beta_tool
def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
"""Lookup the weath... | TestSyncRunTools |
python | streamlit__streamlit | lib/tests/streamlit/file_util_test.py | {
"start": 884,
"end": 4968
} | class ____(unittest.TestCase):
def setUp(self):
self.patch1 = patch("streamlit.file_util.os.stat")
self.os_stat = self.patch1.start()
def tearDown(self):
self.patch1.stop()
@patch("streamlit.file_util.get_streamlit_file_path", mock_get_path)
@patch("streamlit.file_util.open", m... | FileUtilTest |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 12191,
"end": 12910
} | class ____(
APIv3Settings,
NestedViewSetMixin,
ProjectQuerySetMixin,
FlexFieldsMixin,
ListModelMixin,
GenericViewSet,
):
# The main query is done via the ``NestedViewSetMixin`` using the
# ``parents_query_lookups`` defined when registering the urls.
model = Project
lookup_field ... | TranslationRelationshipViewSet |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/dataframes.py | {
"start": 7215,
"end": 8054
} | class ____(Capture):
def __init__(self, callable, ctx=None, **kwargs) -> None:
if ctx is None:
self.ctx = {"operations": [], "variables": []}
else:
self.ctx = ctx
self.kwargs = kwargs
self.callable = callable
def __str__(self) -> str:
return "{cal... | CaptureCall |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 3302,
"end": 4679
} | class ____(RecordDispatcher):
"""A logger that attaches a tag to each record. This is an alternative
record dispatcher that does not use levels but tags to keep log
records apart. It is constructed with a descriptive name and at least
one tag. The tags are up for you to define::
logger = Tag... | TaggingLogger |
python | huggingface__transformers | src/transformers/models/timesfm/modeling_timesfm.py | {
"start": 1867,
"end": 2226
} | class ____(BaseModelOutput):
r"""
loc (`torch.Tensor` of shape `(batch_size, )`):
The mean of the time series inputs.
scale (`torch.Tensor` of shape `(batch_size,)`):
The scale of the time series inputs.
"""
loc: Optional[torch.Tensor] = None
scale: Optional[torch.Tensor] = None... | TimesFmOutput |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/optics/pyoptic.py | {
"start": 3787,
"end": 6105
} | class ____(pg.GraphicsObject, ParamObj):
sigStateChanged = QtCore.Signal()
def __init__(self, gitem, **params):
ParamObj.__init__(self)
pg.GraphicsObject.__init__(self) #, [0,0], [1,1])
self.gitem = gitem
self.surfaces = gitem.surfaces
gitem.setParentItem(... | Optic |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_geometry_to_be_near_shape.py | {
"start": 3462,
"end": 10997
} | class ____(ColumnMapExpectation):
"""Expect that column values as geometries are near (within a given distance) of a given reference shape in the units of the provided geometries.
expect_column_values_geometry_to_be_near_shape is a \
[Column Map Expectation](https://docs.greatexpectations.io/docs/guides/ex... | ExpectColumnValuesGeometryToBeNearShape |
python | qdrant__qdrant-client | tests/congruence_tests/test_query_batch.py | {
"start": 609,
"end": 7355
} | class ____:
__test__ = False
def __init__(self):
self.dense_vector_query_batch_text = []
self.dense_vector_query_batch_image = []
self.dense_vector_query_batch_code = []
self.sparse_vector_query_batch_text = []
self.sparse_vector_query_batch_image = []
self.spar... | TestQueryBatchSearcher |
python | getsentry__sentry | tests/sentry/db/test_transactions.py | {
"start": 5990,
"end": 6072
} | class ____:
def a(self) -> int:
return 2
@no_silo_test
| FakeRegionService |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 12517,
"end": 13259
} | class ____(FrameMatch):
field_path: list[str]
def matches_frame(
self,
frames: list[MatchFrame],
idx: int | None,
exception_data: dict[str, Any],
cache: ReturnValueCache,
) -> bool:
match_frame = None
rv = self._positive_frame_match(match_frame, excep... | ExceptionFieldMatch |
python | sanic-org__sanic | sanic/worker/manager.py | {
"start": 756,
"end": 18686
} | class ____:
"""Manage all of the processes.
This class is used to manage all of the processes. It is instantiated
by Sanic when in multiprocess mode (which is OOTB default) and is used
to start, stop, and restart the worker processes.
You can access it to interact with it **ONLY** when on the main... | WorkerManager |
python | dask__distributed | distributed/http/scheduler/prometheus/core.py | {
"start": 637,
"end": 7721
} | class ____(PrometheusCollector):
server: Scheduler
def __init__(self, server: Scheduler):
super().__init__(server)
self.subsystem = "scheduler"
def collect(self) -> Iterator[GaugeMetricFamily | CounterMetricFamily]:
self.server.monitor.update()
yield GaugeMetricFamily(
... | SchedulerMetricCollector |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-operations-to-make-arrays-similar.py | {
"start": 67,
"end": 400
} | class ____(object):
def makeSimilar(self, nums, target):
"""
:type nums: List[int]
:type target: List[int]
:rtype: int
"""
nums.sort(key=lambda x: (x%2, x))
target.sort(key=lambda x: (x%2, x))
return sum(abs(x-y)//2 for x, y in itertools.izip(nums, tar... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 15357,
"end": 15724
} | class ____(WrapperLine):
wrapper: PythonWrapperCodegen
node: ir.DynamicScalar
def codegen(self, code: IndentedBuffer) -> None:
self.wrapper._codegen_dynamic_scalar(self.node)
@staticmethod
def codegen_fx(converter: FxConverter) -> FxConversionFunc:
return converter._generate_dynami... | DynamicScalarLine |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 62233,
"end": 66815
} | class ____(Request):
"""
Returns metrics of the company queues. The metrics are averaged in the specified interval.
:param from_date: Starting time (in seconds from epoch) for collecting metrics
:type from_date: float
:param to_date: Ending time (in seconds from epoch) for collecting metrics
:t... | GetQueueMetricsRequest |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 16099,
"end": 16360
} | class ____:
DETECTOR_WORKFLOW_ID = OpenApiParameter(
name="detector_workflow_id",
location="path",
required=True,
type=int,
description="The ID of the DetectorWorkflow you'd like to query.",
)
| DetectorWorkflowParams |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 6903,
"end": 6989
} | class ____(JSONFieldMixin, fields.GenericIPAddressField):
pass
| GenericIPAddressField |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 34642,
"end": 37970
} | class ____(ElectraPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.electra = ElectraModel(config)
self.classifier = ElectraClassificationHead(config)
# Initialize weights and apply fi... | ElectraForSequenceClassification |
python | pytorch__pytorch | test/lazy/test_extract_compiled_graph.py | {
"start": 2079,
"end": 5401
} | class ____(nn.Module):
def forward(self, a, b):
a.sub_(b)
return b - 1, b + 1
@contextmanager
def force_fallback_ctx_mgr(fallback_op):
oldconfig = config.get_force_fallback()
config.set_force_fallback(fallback_op)
try:
yield None
finally:
config.set_force_fallback(o... | ModuleInplaceUpdate |
python | pytorch__pytorch | torch/_inductor/fx_passes/pre_grad.py | {
"start": 22581,
"end": 31061
} | class ____:
def __init__(self, node: torch.fx.Node) -> None:
assert node.op == "call_function"
assert node.target in [torch.bmm, torch.matmul]
self.node: torch.fx.Node = node
def get_input(self) -> torch.fx.Node:
if len(self.node.args) > 0:
return self.node.args[0] ... | NormalizedMatmulNode |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 159177,
"end": 161553
} | class ____:
@hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,
min_value=0, max_value=1),
t1=st.floats(allow_nan=False, allow_infinity=False,
min_value=0, max_value=1),
a=st.floats(al... | TestLerp |
python | bokeh__bokeh | src/bokeh/command/subcommands/json.py | {
"start": 2265,
"end": 3579
} | class ____(FileOutputSubcommand):
''' Subcommand to output applications as serialized JSON
'''
#: name for this subcommand
name = "json"
#: file extension for output generated by this :class:`~bokeh.command.subcommands.file_output.FileOutputSubcommand`
extension = "json"
help = "Create J... | JSON |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_geometry_centroids_to_be_within_shape.py | {
"start": 3395,
"end": 8331
} | class ____(ColumnMapExpectation):
"""Expect that column values as geometries each have a centroid that are within a given reference shape.
expect_column_values_geometry_centroids_to_be_within_shape is a \
[Column Map Expectation](https://docs.greatexpectations.io/docs/guides/expectations/creating_custom_ex... | ExpectColumnValuesGeometryCentroidsToBeWithinShape |
python | agronholm__apscheduler | src/apscheduler/triggers/combining.py | {
"start": 412,
"end": 1137
} | class ____(Trigger):
triggers: list[Trigger]
_next_fire_times: list[datetime | None] = attrs.field(
init=False, eq=False, converter=list_converter(as_aware_datetime), factory=list
)
def __getstate__(self) -> dict[str, Any]:
return {
"version": 1,
"triggers": [mar... | BaseCombiningTrigger |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_kubernetes_engine.py | {
"start": 49806,
"end": 51837
} | class ____:
def setup_method(self):
self.operator = GKESuspendJobOperator(
project_id=TEST_PROJECT_ID,
location=TEST_LOCATION,
cluster_name=GKE_CLUSTER_NAME,
task_id=TEST_TASK_ID,
name=K8S_JOB_NAME,
namespace=K8S_NAMESPACE,
)
... | TestGKESuspendJobOperator |
python | PyCQA__pylint | doc/data/messages/n/nonlocal-without-binding/good.py | {
"start": 0,
"end": 93
} | class ____:
colors = ["red", "green"]
def get_color(self):
nonlocal colors
| Fruit |
python | ansible__ansible | lib/ansible/module_utils/urls.py | {
"start": 12728,
"end": 13546
} | class ____(GzipFile):
"""A file-like object to decode a response encoded with the gzip
method, as described in RFC 1952.
Largely copied from ``xmlrpclib``/``xmlrpc.client``
"""
def __init__(self, fp):
if not HAS_GZIP:
raise MissingModuleError(self.missing_gzip_error(), import_tr... | GzipDecodedReader |
python | ray-project__ray | python/ray/tests/test_task_events_2.py | {
"start": 1009,
"end": 1072
} | class ____:
def ready(self):
pass
@ray.remote
| ActorOk |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 55986,
"end": 56084
} | class ____(lock_tests.SemaphoreTests):
semtype = staticmethod(threading.Semaphore)
| SemaphoreTests |
python | django__django | tests/admin_views/models.py | {
"start": 22625,
"end": 22834
} | class ____(models.Model):
"""
Model without any defined `Meta.ordering`.
Refs #16819.
"""
name = models.CharField(max_length=255)
bool = models.BooleanField(default=True)
| UnorderedObject |
python | django__django | django/db/models/query_utils.py | {
"start": 8518,
"end": 10672
} | class ____:
"""
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
"""
def __init__(self, field):
self.field = field
def __get__(self, instance, cls=None):
"""
Retrieve and caches the value from the dat... | DeferredAttribute |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 1408,
"end": 1636
} | class ____(factory.django.DjangoModelFactory):
class Meta:
model = models.StandardModel
django_get_or_create = ('pk',)
foo = factory.Sequence(lambda n: "foo%d" % n)
pk = None
| StandardFactoryWithPKField |
python | langchain-ai__langchain | libs/core/tests/unit_tests/indexing/test_in_memory_indexer.py | {
"start": 441,
"end": 653
} | class ____(DocumentIndexerTestSuite):
@pytest.fixture
@override
def index(self) -> Generator[DocumentIndex, None, None]:
yield InMemoryDocumentIndex() # noqa: PT022
| TestDocumentIndexerTestSuite |
python | numpy__numpy | benchmarks/benchmarks/bench_linalg.py | {
"start": 7061,
"end": 7876
} | class ____(Benchmark):
# Smaller for speed
# , (128, 128), (256, 256), (512, 512),
# (1024, 1024)
params = [[(16, 16), (32, 32),
(64, 64)], TYPES1]
param_names = ['shape', 'npdtypes']
def setup(self, shape, npdtypes):
self.xarg = np.random.uniform(-1, 1, np.dot(*shape)).r... | LinAlgTransposeVdot |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 20721,
"end": 21182
} | class ____(GroupType):
type_id = 2011
slug = "profile_function_regression"
description = "Function Regression"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.METRIC.value
enable_auto_resolve = False
released = True
default_priority = PriorityLevel.MEDIUM
notif... | ProfileFunctionRegressionType |
python | redis__redis-py | tests/test_credentials.py | {
"start": 19731,
"end": 22020
} | class ____:
@pytest.mark.parametrize(
"r_entra",
[
{
"cred_provider_class": EntraIdCredentialsProvider,
"single_connection_client": False,
},
{
"cred_provider_class": EntraIdCredentialsProvider,
"sing... | TestEntraIdCredentialsProvider |
python | tiangolo__fastapi | docs_src/security/tutorial004_an_py310.py | {
"start": 901,
"end": 963
} | class ____(BaseModel):
username: str | None = None
| TokenData |
python | ray-project__ray | python/ray/serve/_private/logging_utils.py | {
"start": 2623,
"end": 3412
} | class ____(logging.Filter):
"""Serve context filter.
The filter will add the route, request id, app name to the log record.
Note: the filter doesn't do any filtering, it only adds the serve request context
attributes.
"""
def filter(self, record):
if should_skip_context_filter(record)... | ServeContextFilter |
python | keras-team__keras | keras/src/backend/torch/optimizers/torch_nadam.py | {
"start": 188,
"end": 2421
} | class ____(torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Nadam):
def _parallel_update_step(
self,
grads,
variables,
learning_rate,
):
keras_variables = variables
variables = [v.value for v in variables]
dtype = variables[0].dtype
lr ... | Nadam |
python | graphql-python__graphene | graphene/validation/tests/test_depth_limit_validator.py | {
"start": 752,
"end": 978
} | class ____(ObjectType):
name = String(required=True)
email = String(required=True)
address = Field(AddressType, required=True)
pets = List(PetType, required=True)
class Meta:
name = "Human"
| HumanType |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/custom_nest_trace_type_test.py | {
"start": 2459,
"end": 6073
} | class ____(test.TestCase):
def testCustomNestTraceTypeEq(self):
trace_components1 = (default_types.Literal(1.0), default_types.Literal(2.0))
t1 = custom_nest_trace_type.CustomNestTraceType(
MaskedValuePair, (True,), trace_components1
)
trace_components2 = (default_types.Literal(1.0), default... | CustomNestTraceTypeTest |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/pool_slots_available_dep.py | {
"start": 1021,
"end": 2656
} | class ____(BaseTIDep):
"""Dep for pool slots availability."""
NAME = "Pool Slots Available"
IGNORABLE = True
@provide_session
def _get_dep_statuses(self, ti, session, dep_context=None):
"""
Determine if the pool task instance is in has available slots.
:param ti: the task ... | PoolSlotsAvailableDep |
python | pytorch__pytorch | torch/_subclasses/meta_utils.py | {
"start": 21594,
"end": 21975
} | class ____(TypedDict, total=False):
device: Union[torch.device, str]
# A callback where the device may not be provided (is optional).
# All of these satisfy this protocol:
# def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str] = "meta")
# def mk(arg: Callable[[], torch.Tensor], device: Opt... | _MetaTensorCallbackKwargs |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/run_config.py | {
"start": 4990,
"end": 5320
} | class ____(graphene.Union):
class Meta:
types = (
GrapheneRunConfigSchema,
GraphenePipelineNotFoundError,
GrapheneInvalidSubsetError,
GrapheneModeNotFoundError,
GraphenePythonError,
)
name = "RunConfigSchemaOrError"
| GrapheneRunConfigSchemaOrError |
python | pypa__pip | src/pip/_internal/models/wheel.py | {
"start": 447,
"end": 2920
} | class ____:
"""A wheel file"""
def __init__(self, filename: str) -> None:
self.filename = filename
try:
wheel_info = parse_wheel_filename(filename)
except _PackagingInvalidWheelFilename as e:
raise InvalidWheelFilename(e.args[0]) from None
self.name, _v... | Wheel |
python | scipy__scipy | scipy/stats/tests/test_qmc.py | {
"start": 45937,
"end": 55291
} | class ____:
def test_validations(self):
message = r"Dimension of `engine` must be consistent"
with pytest.raises(ValueError, match=message):
qmc.MultivariateNormalQMC([0], engine=qmc.Sobol(d=2))
message = r"Dimension of `engine` must be consistent"
with pytest.raises(V... | TestMultivariateNormalQMC |
python | agronholm__apscheduler | src/apscheduler/triggers/calendarinterval.py | {
"start": 365,
"end": 6885
} | class ____(Trigger):
"""
Runs the task on specified calendar-based intervals always at the same exact time of
day.
When calculating the next date, the ``years`` and ``months`` parameters are first
added to the previous date while keeping the day of the month constant. This is
repeated until the... | CalendarIntervalTrigger |
python | bokeh__bokeh | tests/unit/bokeh/embed/ext_package_no_main/__init__.py | {
"start": 48,
"end": 78
} | class ____(Model):
pass
| AModel |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 131413,
"end": 133836
} | class ____(test.TestCase):
def _npRelu(self, np_features):
return np.maximum(np_features, np.zeros(np_features.shape))
def testNpRelu(self):
self.assertAllClose(
np.array([[0.0, 0.7, 0.0, 0.3, 0.0], [0.1, 0.0, 0.5, 0.0, 0.9]]),
self._npRelu(
np.array(
[[-0.9, 0.... | ReluTest |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 29639,
"end": 29889
} | class ____(Reduction):
_parameters = ["frame", "skipna", "split_every"]
_defaults = {"split_every": False}
reduction_chunk = M.all
@property
def chunk_kwargs(self):
return dict(
skipna=self.skipna,
)
| All |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 2783,
"end": 2939
} | class ____(Base):
class_super = 3
def __init__(self):
self.var_super = ''
def method_super(self):
self.var2_super = list
| SuperClass |
python | davidhalter__jedi | test/static_analysis/class_simple.py | {
"start": 0,
"end": 78
} | class ____(object):
class Nested():
def foo():
pass
| Base |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/directive.py | {
"start": 3807,
"end": 6100
} | class ____(SphinxDirective):
"""A directive class for all autodoc directives. It works as a dispatcher of Documenters.
It invokes a Documenter upon running. After the processing, it parses and returns
the content generated by Documenter.
"""
option_spec = DummyOptionSpec()
has_content = True
... | AutodocDirective |
python | jmcnamara__XlsxWriter | xlsxwriter/test/app/test_app02.py | {
"start": 333,
"end": 2309
} | class ____(unittest.TestCase):
"""
Test assembling a complete App file.
"""
def test_assemble_xml_file(self):
"""Test writing an App file."""
self.maxDiff = None
fh = StringIO()
app = App()
app._set_filehandle(fh)
app._add_part_name("Sheet1")
a... | TestAssembleApp |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_variables.py | {
"start": 23890,
"end": 51144
} | class ____(TestVariableEndpoint):
@pytest.mark.enable_redact
@pytest.mark.parametrize(
("actions", "expected_results"),
[
pytest.param(
{
"actions": [
{
"action": "create",
... | TestBulkVariables |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_merge_range01.py | {
"start": 315,
"end": 894
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("merge_range01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | sympy__sympy | doc/ext/docscrape.py | {
"start": 1986,
"end": 13120
} | class ____(Mapping):
def __init__(self, docstring, config={}):
docstring = textwrap.dedent(docstring).split('\n')
self._doc = Reader(docstring)
self._parsed_data = {
'Signature': '',
'Summary': [''],
'Extended Summary': [],
'Parameters': [],
... | NumpyDocString |
python | google__flatbuffers | tests/MyGame/Example/NestedUnion/Vec3.py | {
"start": 3847,
"end": 5517
} | class ____(object):
# Vec3T
def __init__(
self,
x = 0.0,
y = 0.0,
z = 0.0,
test1 = 0.0,
test2 = 0,
test3 = None,
):
self.x = x # type: float
self.y = y # type: float
self.z = z # type: float
self.test1 = test1 # typ... | Vec3T |
python | bokeh__bokeh | examples/advanced/extensions/widget.py | {
"start": 299,
"end": 2918
} | class ____(InputWidget):
# The special class attribute ``__implementation__`` should contain a string
# of JavaScript or TypeScript code that implements the web browser
# side of the custom extension model or a string name of a file with the implementation.
__implementation__ = "ion_range_slider.ts"
... | IonRangeSlider |
python | facebook__pyre-check | client/commands/tests/daemon_query_test.py | {
"start": 273,
"end": 1325
} | class ____(testslide.TestCase):
def test_parse_response(self) -> None:
def assert_parsed(text: str, expected: Response) -> None:
self.assertEqual(Response.parse(text), expected)
def assert_not_parsed(text: str) -> None:
with self.assertRaises(InvalidQueryResponse):
... | ResponseTest |
python | pyca__cryptography | src/cryptography/x509/general_name.py | {
"start": 6901,
"end": 7836
} | class ____(GeneralName):
def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None:
if not isinstance(type_id, ObjectIdentifier):
raise TypeError("type_id must be an ObjectIdentifier")
if not isinstance(value, bytes):
raise TypeError("value must be a binary string")... | OtherName |
python | scipy__scipy | scipy/sparse/linalg/_svdp.py | {
"start": 512,
"end": 10352
} | class ____:
"""
Wrapper class for linear operator
The call signature of the __call__ method matches the callback of
the PROPACK routines.
"""
def __init__(self, A):
try:
self.A = aslinearoperator(A)
except TypeError:
self.A = aslinearoperator(np.asarray(A... | _AProd |
python | wandb__wandb | wandb/vendor/pygments/lexers/html.py | {
"start": 6000,
"end": 7389
} | class ____(RegexLexer):
"""
Generic lexer for XML (eXtensible Markup Language).
"""
flags = re.MULTILINE | re.DOTALL | re.UNICODE
name = 'XML'
aliases = ['xml']
filenames = ['*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd',
'*.wsdl', '*.wsf']
mimetypes = ['text/xml', 'appl... | XmlLexer |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 221,
"end": 348
} | class ____(UserWarning):
"""Base class for all warnings emitted by pytest."""
__module__ = "pytest"
@final
| PytestWarning |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/execution.py | {
"start": 4429,
"end": 11221
} | class ____:
"""
Represents a query that needs to be scheduled for execution.
Attributes:
type: The type of the query that needs to be run.
metrics_query: The query that needs to be run.
next: The next query that has a dependency with this, meaning that the executor will execute them... | ScheduledQuery |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_date.py | {
"start": 1912,
"end": 4437
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid dates."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
"2022-01... | ExpectColumnValuesToBeValidDate |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 15006,
"end": 15229
} | class ____(SendMessageToScheduler):
op = "release-worker-data"
__slots__ = ("key",)
key: Key
# Not to be confused with RescheduleEvent below or the distributed.Reschedule Exception
@dataclass
| ReleaseWorkerDataMsg |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 90383,
"end": 91956
} | class ____(MeanMetricWrapper):
"""Computes the cosine similarity between the labels and predictions.
`cosine similarity = (a . b) / ||a|| ||b||`
See: [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity).
This metric keeps the average cosine similarity between `predictions` and
`labels` over... | CosineSimilarity |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 44457,
"end": 46880
} | class ____(SineCosineTypeTransform):
"""
Class representing unevaluated inverse cosine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse cosine transforms, see the
:func:`inverse_cosine_transform` docstring.
"""
_name = 'Inverse ... | InverseCosineTransform |
python | huggingface__transformers | examples/modular-transformers/modeling_from_uppercase_model.py | {
"start": 1750,
"end": 5036
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Union[FromUppercaseModelVisionConfig, FromUppercaseModelTextConfig]):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads ... | FromUppercaseModelAttention |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.