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 | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_alertrule_workflow.py | {
"start": 145,
"end": 1383
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-alert-rule-workflow-index"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.workflow_1 = self.create_workflow(organization=self.organization)
self.workflow_2 = self.create_workflow(organiz... | OrganizationAlertRuleWorkflowAPITestCase |
python | tensorflow__tensorflow | tensorflow/python/saved_model/proto_splitter_save_test.py | {
"start": 1169,
"end": 2520
} | class ____(test.TestCase, parameterized.TestCase):
def test_save_experimental_image_format(self):
root = module.Module()
root.c = constant_op.constant(np.random.random_sample([150, 150]))
root.get_c = def_function.function(lambda: root.c)
save_dir = os.path.join(self.get_temp_dir(), "chunked_model")
... | ProtoSplitterSaveTest |
python | getsentry__sentry | tests/sentry/integrations/gitlab/test_repository.py | {
"start": 682,
"end": 13631
} | class ____(IntegrationRepositoryTestCase):
provider_name = "integrations:gitlab"
def setUp(self) -> None:
super().setUp()
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration = self.create_provider_integration(
provider="gitlab",
name="Examp... | GitLabRepositoryProviderTest |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/triggers/message_bus.py | {
"start": 5774,
"end": 8485
} | class ____(BaseAzureServiceBusTrigger):
"""
Trigger for Azure Service Bus Topic Subscription message processing.
This trigger monitors topic subscriptions for incoming messages. It can handle
multiple topics with a single subscription name, processing messages as they
arrive and yielding them as tr... | AzureServiceBusSubscriptionTrigger |
python | fluentpython__example-code | attic/dicts/test_transformdict.py | {
"start": 646,
"end": 7288
} | class ____(TransformDictTestBase):
def test_init(self):
with self.assertRaises(TypeError):
TransformDict()
with self.assertRaises(TypeError):
# Too many positional args
TransformDict(str.lower, {}, {})
with self.assertRaises(TypeError):
# Not ... | TestTransformDict |
python | django__django | tests/admin_views/models.py | {
"start": 29159,
"end": 29578
} | class ____(models.Model):
born_country = models.ForeignKey(Country, models.CASCADE)
living_country = models.ForeignKey(
Country, models.CASCADE, related_name="living_country_set"
)
favorite_country_to_vacation = models.ForeignKey(
Country,
models.CASCADE,
related_name="fa... | Traveler |
python | getsentry__sentry | src/sentry/replays/testutils.py | {
"start": 290,
"end": 20307
} | class ____(Enum):
DomContentLoaded = 0
Load = 1
FullSnapshot = 2
IncrementalSnapshot = 3
Meta = 4
Custom = 5
Plugin = 6
SegmentList = list[dict[str, Any]]
RRWebNode = dict[str, Any]
def sec(timestamp: datetime.datetime) -> int:
# sentry data inside rrweb is recorded in seconds
re... | EventType |
python | doocs__leetcode | solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/Solution.py | {
"start": 0,
"end": 156
} | class ____:
def average(self, salary: List[int]) -> float:
s = sum(salary) - min(salary) - max(salary)
return s / (len(salary) - 2)
| Solution |
python | PyCQA__pylint | tests/functional/u/useless/useless_object_inheritance.py | {
"start": 366,
"end": 427
} | class ____(B, object): # [useless-object-inheritance]
pass
| C |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 383088,
"end": 384982
} | class ____(Response):
"""
Response of tasks.set_requirements endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "set_requirements"
_version = "2.20"
... | SetRequirementsResponse |
python | PrefectHQ__prefect | src/prefect/client/schemas/sorting.py | {
"start": 828,
"end": 1042
} | class ____(AutoEnum):
"""Defines automation sorting options."""
CREATED_DESC = AutoEnum.auto()
UPDATED_DESC = AutoEnum.auto()
NAME_ASC = AutoEnum.auto()
NAME_DESC = AutoEnum.auto()
| AutomationSort |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 133448,
"end": 135985
} | class ____(Response):
"""
Response of projects.get_unique_metric_variants endpoint.
:param metrics: A list of metric variants reported for tasks in this project
:type metrics: Sequence[MetricVariantResult]
"""
_service = "projects"
_action = "get_unique_metric_variants"
_version = "2.2... | GetUniqueMetricVariantsResponse |
python | modin-project__modin | modin/tests/pandas/extensions/conftest.py | {
"start": 1352,
"end": 1423
} | class ____(NativeIO):
query_compiler_cls = Test1QueryCompiler
| Test1IO |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/decision_tree.py | {
"start": 1492,
"end": 7944
} | class ____(object):
"""Super class of RegressionTree and ClassificationTree.
Parameters:
-----------
min_samples_split: int
The minimum number of samples needed to make a split when building a tree.
min_impurity: float
The minimum impurity required to split the tree further.
max... | DecisionTree |
python | google__pytype | pytype/abstract/_classes.py | {
"start": 26809,
"end": 36180
} | class ____( # pytype: disable=signature-mismatch
_base.BaseValue, class_mixin.Class, mixin.NestedAnnotation
):
"""A class that contains additional parameters.
E.g. a container.
Attributes:
base_cls: The base type.
formal_type_parameters: An iterable of BaseValue, one for each type
parameter.
... | ParameterizedClass |
python | pydata__xarray | xarray/groupers.py | {
"start": 26178,
"end": 28357
} | class ____:
seasons: tuple[str, ...]
# tuple[integer months] corresponding to each season
inds: tuple[tuple[int, ...], ...]
# integer code for each season, this is not simply range(len(seasons))
# when the seasons have overlaps
codes: Sequence[int]
def find_independent_seasons(seasons: Sequenc... | SeasonsGroup |
python | networkx__networkx | networkx/algorithms/bipartite/tests/test_covering.py | {
"start": 66,
"end": 1221
} | class ____:
"""Tests for :func:`networkx.algorithms.bipartite.min_edge_cover`"""
def test_empty_graph(self):
G = nx.Graph()
assert bipartite.min_edge_cover(G) == set()
def test_graph_single_edge(self):
G = nx.Graph()
G.add_edge(0, 1)
assert bipartite.min_edge_cover(... | TestMinEdgeCover |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 2693,
"end": 2954
} | class ____(MetaflowException):
headline = "Object not in the current namespace"
def __init__(self, namespace):
msg = "Object not in namespace '%s'" % namespace
super(MetaflowNamespaceMismatch, self).__init__(msg)
| MetaflowNamespaceMismatch |
python | getsentry__sentry | tests/sentry/rules/conditions/test_first_seen_event.py | {
"start": 244,
"end": 1052
} | class ____(RuleTestCase):
rule_cls = FirstSeenEventCondition
def test_applies_correctly(self) -> None:
rule = self.get_rule(rule=Rule(environment_id=None))
self.assertPasses(rule, self.event, is_new=True)
self.assertDoesNotPass(rule, self.event, is_new=False)
def test_applies_cor... | FirstSeenEventConditionTest |
python | huggingface__transformers | src/transformers/models/grounding_dino/image_processing_grounding_dino_fast.py | {
"start": 11412,
"end": 30193
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
format = AnnotationFormat.COCO_DETECTION
do_resize = True
do_rescale = True
do_normalize = True
do_pad = True
size = {"shortest_edge": 800, "... | GroundingDinoImageProcessorFast |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 1737,
"end": 1846
} | class ____(Protocol8):
# This should generate an error because x is a ClassVar.
x: ClassVar = 1
| Concrete8 |
python | pyqtgraph__pyqtgraph | pyqtgraph/debug.py | {
"start": 41712,
"end": 43089
} | class ____(object):
"""
Wrapper on stdout/stderr that colors text by the current thread ID.
*stream* must be 'stdout' or 'stderr'.
"""
colors = {}
lock = Mutex()
def __init__(self, stream):
self.stream = getattr(sys, stream)
self.err = stream == 'stderr'
setattr(sys... | ThreadColor |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 19609,
"end": 19930
} | class ____(models.Model):
data = models.CharField(max_length=30)
def get_absolute_url(self):
return reverse("bucket_data-detail", kwargs={"pk": self.pk})
register(
BucketDataRegisterRequestUser,
user_model=BucketMember,
get_user=get_bucket_member_request_user,
)
| BucketDataRegisterRequestUser |
python | pypa__warehouse | tests/unit/utils/test_paginate.py | {
"start": 4065,
"end": 6755
} | class ____:
def test_slices_and_length(self):
wrapper = paginate._OpenSearchWrapper(FakeQuery6([1, 2, 3, 4, 5, 6]))
assert wrapper[1:3] == [2, 3]
assert len(wrapper) == 6
def test_slice_start_clamps_to_max(self):
wrapper = paginate._OpenSearchWrapper(FakeQuery6([1, 2, 3, 4, 5, 6... | TestOpenSearchWrapper6 |
python | TheAlgorithms__Python | machine_learning/astar.py | {
"start": 1395,
"end": 4181
} | class ____:
"""
Gridworld class represents the external world here a grid M*M
matrix.
world_size: create a numpy array with the given world_size default is 5.
"""
def __init__(self, world_size=(5, 5)):
self.w = np.zeros(world_size)
self.world_x_limit = world_size[0]
sel... | Gridworld |
python | conda__conda | tests/test_solvers.py | {
"start": 322,
"end": 1203
} | class ____(SolverTests):
@property
def solver_class(self) -> type[Solver]:
from conda_libmamba_solver.solver import LibMambaSolver
return LibMambaSolver
@property
def tests_to_skip(self):
return {
"conda-libmamba-solver does not support features": [
... | TestLibMambaSolver |
python | wandb__wandb | wandb/sdk/launch/agent/config.py | {
"start": 856,
"end": 990
} | class ____(str, Enum):
"""Enum of valid builder types."""
docker = "docker"
kaniko = "kaniko"
noop = "noop"
| BuilderType |
python | bottlepy__bottle | bottle.py | {
"start": 75934,
"end": 76384
} | class ____(BaseRequest):
""" A thread-local subclass of :class:`BaseRequest` with a different
set of attributes for each thread. There is usually only one global
instance of this class (:data:`request`). If accessed during a
request/response cycle, this instance always refers to the *current... | LocalRequest |
python | huggingface__transformers | src/transformers/integrations/executorch.py | {
"start": 34870,
"end": 37040
} | class ____(torch.nn.Module):
"""
A wrapper module designed to make a Seq2Seq LM decoder exportable with `torch.export`,
specifically for use with static caching. This module ensures the exported decoder
is compatible with ExecuTorch.
"""
def __init__(self, model, max_static_cache_length, batch_... | Seq2SeqLMDecoderExportableModuleWithStaticCache |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_impls.py | {
"start": 47083,
"end": 48800
} | class ____(
AutoMaterializeRule,
NamedTuple("_SkipOnBackfillInProgressRule", [("all_partitions", bool)]),
):
@property
def decision_type(self) -> AutoMaterializeDecisionType:
return AutoMaterializeDecisionType.SKIP
@property
def description(self) -> str:
if self.all_partitions:
... | SkipOnBackfillInProgressRule |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/models.py | {
"start": 8351,
"end": 20150
} | class ____:
hashed_connection_id: str
actor_id: str
configured_catalog: ConfiguredAirbyteCatalog
connector_under_test: ConnectorUnderTest
command: Command
stdout_file_path: Path
stderr_file_path: Path
success: bool
executed_container: Optional[dagger.Container]
config: Optional[S... | ExecutionResult |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 42702,
"end": 42766
} | class ____(ApiErrorTest):
INTERPRET = True
| ApiErrorInterpretTest |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/groupby.py | {
"start": 21929,
"end": 22811
} | class ____(GroupBy):
"""Builder for GroupBy aggregation functions for Series."""
@classmethod
def _call_groupby(cls, df, *args, **kwargs): # noqa: PR01
"""Call .groupby() on passed `df` squeezed to Series."""
# We can end up here by two means - either by "true" call
# like Series()... | SeriesGroupBy |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 27424,
"end": 27611
} | class ____(Integer):
"""
Handles the unsignedByte datatype. Unsigned 8-bit integer.
"""
format = "u1"
val_range = (0, 255)
bit_size = "8-bit unsigned"
| UnsignedByte |
python | getsentry__sentry | src/sentry/analytics/events/release_set_commits.py | {
"start": 82,
"end": 308
} | class ____(analytics.Event):
user_id: int | None = None
organization_id: int
project_ids: list[int] | None
user_agent: str | None = None
analytics.register(ReleaseSetCommitsLocalEvent)
| ReleaseSetCommitsLocalEvent |
python | django__django | django/forms/fields.py | {
"start": 36555,
"end": 41957
} | class ____(Field):
"""
Aggregate the logic of multiple Fields.
Its clean() method takes a "decompressed" list of values, which are then
cleaned into a single value according to self.fields. Each value in
this list is cleaned by the corresponding field -- the first value is
cleaned by the first ... | MultiValueField |
python | tornadoweb__tornado | tornado/test/netutil_test.py | {
"start": 3540,
"end": 3988
} | class ____(_ResolverErrorTestMixin):
def setUp(self):
super().setUp()
self.resolver = BlockingResolver()
self.real_getaddrinfo = socket.getaddrinfo
socket.getaddrinfo = _failing_getaddrinfo
def tearDown(self):
socket.getaddrinfo = self.real_getaddrinfo
super().te... | ThreadedResolverErrorTest |
python | HIPS__autograd | autograd/misc/tracers.py | {
"start": 183,
"end": 1663
} | class ____(Node):
__slots__ = ["parents", "partial_fun"]
def __init__(self, value, fun, args, kwargs, parent_argnums, parents):
args = subvals(args, zip(parent_argnums, repeat(None)))
def partial_fun(partial_args):
return fun(*subvals(args, zip(parent_argnums, partial_args)), **kwa... | ConstGraphNode |
python | scipy__scipy | scipy/stats/_new_distributions.py | {
"start": 418,
"end": 4805
} | class ____(ContinuousDistribution):
r"""Normal distribution with prescribed mean and standard deviation.
The probability density function of the normal distribution is:
.. math::
f(x) = \frac{1}{\sigma \sqrt{2 \pi}} \exp {
\left( -\frac{1}{2}\left( \frac{x - \mu}{\sigma} \right)^2 \ri... | Normal |
python | tensorflow__tensorflow | tensorflow/python/eager/monitoring.py | {
"start": 14590,
"end": 16679
} | class ____(object):
"""A context manager to measure the walltime and increment a Counter cell."""
__slots__ = [
"cell",
"t",
"monitored_section_name",
"_counting",
"_avoid_repetitive_counting",
]
def __init__(
self, cell, monitored_section_name=None, avoid_repetitive_counti... | MonitoredTimer |
python | openai__openai-python | src/openai/resources/fine_tuning/checkpoints/permissions.py | {
"start": 15738,
"end": 16223
} | class ____:
def __init__(self, permissions: AsyncPermissions) -> None:
self._permissions = permissions
self.create = _legacy_response.async_to_raw_response_wrapper(
permissions.create,
)
self.retrieve = _legacy_response.async_to_raw_response_wrapper(
permissi... | AsyncPermissionsWithRawResponse |
python | automl__auto-sklearn | test/test_pipeline/test_regression.py | {
"start": 1125,
"end": 27908
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def test_io_dict(self):
regressors = regression_components._regressors
for r in regressors:
if regressors[r] == regression_components.RegressorChoice:
continue
props = regressors[r].get_proper... | SimpleRegressionPipelineTest |
python | django__django | tests/signals/tests.py | {
"start": 18155,
"end": 21115
} | class ____(SimpleTestCase):
async def test_asend(self):
sync_handler = SyncHandler()
async_handler = AsyncHandler()
signal = dispatch.Signal()
signal.connect(sync_handler)
signal.connect(async_handler)
result = await signal.asend(self.__class__)
self.assertEqu... | AsyncReceiversTests |
python | mlflow__mlflow | tests/tracing/test_fluent.py | {
"start": 3699,
"end": 3959
} | class ____:
@mlflow.trace()
async def predict(self, x, y):
return await self.some_operation_raise_error(x, y)
@mlflow.trace()
async def some_operation_raise_error(self, x, y):
raise ValueError("Some error")
| ErroringAsyncTestModel |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 10930,
"end": 11332
} | class ____(Type):
"""An object with an unknown type.
All assignments to an UnknownType result in the type of the assigned object except
`None` which results in a InvalidType.
"""
name = "unknown"
types: t.ClassVar[t.List[type]] = []
def assign_type(self, wb_type: "Type") -> "Type":
... | UnknownType |
python | sphinx-doc__sphinx | sphinx/directives/other.py | {
"start": 10770,
"end": 13121
} | class ____(SphinxDirective):
"""Directive to only include text if the given tag(s) are enabled."""
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
node = addnodes.o... | Only |
python | google__jax | tests/errors_test.py | {
"start": 2572,
"end": 12232
} | class ____(jtu.JaxTestCase):
def test_nested_jit(self, filter_mode):
@jit
def innermost(x):
assert False
@jit
def inbetween(x):
return 1 + innermost(x)
@jit
def outermost(x):
return 2 + inbetween(x)
f = lambda: outermost(jnp.array([1, 2]))
check_filtered_stack_trac... | FilteredTracebackTest |
python | huggingface__transformers | src/transformers/models/resnet/modeling_resnet.py | {
"start": 2907,
"end": 3561
} | class ____(nn.Module):
"""
ResNet shortcut, used to project the residual features to the correct size. If needed, it is also used to
downsample the input using `stride=2`.
"""
def __init__(self, in_channels: int, out_channels: int, stride: int = 2):
super().__init__()
self.convoluti... | ResNetShortCut |
python | sqlalchemy__sqlalchemy | examples/generic_associations/table_per_association.py | {
"start": 2165,
"end": 3049
} | class ____(HasAddresses, Base):
company_name: Mapped[str]
engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
session = Session(engine)
session.add_all(
[
Customer(
name="customer 1",
addresses=[
Address(
street=... | Supplier |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1122596,
"end": 1124004
} | class ____(sgqlc.types.Type, UniformResourceLocatable, Node):
"""Represents a mention made by one issue or pull request to another."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "is_cross_repository", "referenced_at", "source", "target", "will_close_target")
actor = sgqlc.type... | CrossReferencedEvent |
python | apache__airflow | providers/snowflake/tests/unit/snowflake/operators/test_snowflake.py | {
"start": 2294,
"end": 2965
} | class ____:
@mock.patch("airflow.providers.common.sql.operators.sql.SQLExecuteQueryOperator.get_db_hook")
def test_snowflake_operator(self, mock_get_db_hook, dag_maker):
sql = """
CREATE TABLE IF NOT EXISTS test_airflow (
dummy VARCHAR(50)
);
"""
with dag_mak... | TestSnowflakeOperator |
python | pytransitions__transitions | transitions/extensions/asyncio.py | {
"start": 3082,
"end": 3942
} | class ____(Condition):
"""A helper class to await condition checks in the intended way."""
async def check(self, event_data):
"""Check whether the condition passes.
Args:
event_data (EventData): An EventData instance to pass to the
condition (if event sending is enab... | AsyncCondition |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass2.py | {
"start": 130,
"end": 474
} | class ____:
optional: int | None = field(default=None, kw_only=True)
x: int
y: int
obj = Point(1, 2)
match obj:
case Point(x, y, optional=opt):
reveal_type(x, expected_text="int")
reveal_type(y, expected_text="int")
reveal_type(opt, expected_text="int | None")
distance ... | Point |
python | getsentry__sentry | src/sentry/models/commitauthor.py | {
"start": 1045,
"end": 2965
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
organization_id = BoundedBigIntegerField(db_index=True)
# display name
name = models.CharField(max_length=128, null=True)
email = models.CharField(max_length=200)
# Format varies by provider:
# - GitHub/GitHub Enterprise: "... | CommitAuthor |
python | PrefectHQ__prefect | src/prefect/logging/highlighters.py | {
"start": 730,
"end": 1187
} | class ____(RegexHighlighter):
"""Apply style to names."""
base_style = "name."
highlights: list[str] = [
# ?i means case insensitive
# ?<= means find string right after the words: flow run
r"(?i)(?P<flow_run_name>(?<=flow run) \'(.*?)\')",
r"(?i)(?P<flow_name>(?<=flow) \'(.*... | NameHighlighter |
python | getsentry__sentry | src/sentry/api/validators/auth.py | {
"start": 99,
"end": 739
} | class ____(serializers.Serializer):
password = serializers.CharField(required=False, trim_whitespace=False)
# For u2f
challenge = serializers.CharField(required=False, trim_whitespace=False)
response = serializers.CharField(required=False, trim_whitespace=False)
def validate(self, data):
if... | AuthVerifyValidator |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 5298,
"end": 5350
} | class ____(A13):
def g(self):
return 0
| B13 |
python | kamyu104__LeetCode-Solutions | Python/cut-off-trees-for-golf-event.py | {
"start": 114,
"end": 1984
} | class ____(object):
def cutOffTree(self, forest):
"""
:type forest: List[List[int]]
:rtype: int
"""
def dot(p1, p2):
return p1[0]*p2[0]+p1[1]*p2[1]
def minStep(p1, p2):
min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1])
closer, detour =... | Solution |
python | Textualize__textual | tests/test_message_pump.py | {
"start": 323,
"end": 1071
} | class ____(Widget):
called_by = None
def key_x(self):
self.called_by = self.key_x
def key_ctrl_i(self):
self.called_by = self.key_ctrl_i
async def test_dispatch_key_valid_key():
widget = ValidWidget()
result = await dispatch_key(widget, Key(key="x", character="x"))
assert res... | ValidWidget |
python | google__jax | jax/_src/pallas/pipelining/schedulers.py | {
"start": 4634,
"end": 6693
} | class ____:
"""A scoreboard used to book-keep data dependencies.
Attributes:
which_stage_writes: A mapping from buffer index to the stage index that
writes to it.
which_stages_read: A mapping from buffer index to the stages that read
from it.
stage_counters: A list of length num_stages that... | Scoreboard |
python | faif__python-patterns | patterns/behavioral/publish_subscribe.py | {
"start": 173,
"end": 785
} | class ____:
def __init__(self) -> None:
self.msg_queue = []
self.subscribers = {}
def notify(self, msg: str) -> None:
self.msg_queue.append(msg)
def subscribe(self, msg: str, subscriber: Subscriber) -> None:
self.subscribers.setdefault(msg, []).append(subscriber)
def u... | Provider |
python | fluentpython__example-code-2e | 10-dp-1class-func/untyped/strategy_best2.py | {
"start": 1565,
"end": 3148
} | class ____: # the Context
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self):
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
... | Order |
python | walkccc__LeetCode | solutions/985. Sum of Even Numbers After Queries/985.py | {
"start": 0,
"end": 401
} | class ____:
def sumEvenAfterQueries(
self,
nums: list[int],
queries: list[list[int]],
) -> list[int]:
ans = []
summ = sum(a for a in nums if a % 2 == 0)
for val, index in queries:
if nums[index] % 2 == 0:
summ -= nums[index]
nums[index] += val
if nums[index] ... | Solution |
python | doocs__leetcode | solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/Solution.py | {
"start": 0,
"end": 987
} | class ____:
def findTheCity(
self, n: int, edges: List[List[int]], distanceThreshold: int
) -> int:
def dijkstra(u: int) -> int:
dist = [inf] * n
dist[u] = 0
vis = [False] * n
for _ in range(n):
k = -1
for j in range... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hardcoded-records/source_hardcoded_records/streams.py | {
"start": 171,
"end": 557
} | class ____(Stream, ABC):
primary_key = None
sample_record = None
def __init__(self, count: int, **kwargs):
super().__init__(**kwargs)
self.count = count
def read_records(self, **kwargs) -> Iterable[Mapping[str, Any]]:
"""Generate records from the stream."""
for _ in ran... | HardcodedStream |
python | doocs__leetcode | solution/1200-1299/1252.Cells with Odd Values in a Matrix/Solution2.py | {
"start": 0,
"end": 268
} | class ____:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
row = [0] * m
col = [0] * n
for r, c in indices:
row[r] += 1
col[c] += 1
return sum((i + j) % 2 for i in row for j in col)
| Solution |
python | spack__spack | lib/spack/spack/cmd/commands.py | {
"start": 4216,
"end": 5182
} | class ____(ArgparseWriter):
"""Write argparse output as a list of subcommands."""
def format(self, cmd: Command) -> str:
"""Return the string representation of a single node in the parser tree.
Args:
cmd: Parsed information about a command or subcommand.
Returns:
... | SubcommandWriter |
python | celery__celery | t/unit/app/test_exceptions.py | {
"start": 101,
"end": 510
} | class ____:
def test_when_datetime(self):
x = Retry('foo', KeyError(), when=datetime.now(timezone.utc))
assert x.humanize()
def test_pickleable(self):
x = Retry('foo', KeyError(), when=datetime.now(timezone.utc))
y = pickle.loads(pickle.dumps(x))
assert x.message == y.m... | test_Retry |
python | pytorch__pytorch | test/distributed/tensor/test_op_schema.py | {
"start": 314,
"end": 4641
} | class ____(TestCase):
def test_equality_checks_lists_of_dtensor_spec(self):
"""If x == y, then we must have h(x) == h(y)."""
dts = DTensorSpec(mesh=None, placements=tuple(), tensor_meta=None)
schema1 = OpSchema(op=None, args_schema=(dts, [dts]), kwargs_schema={})
schema2 = OpSchema(o... | TestOpSchema |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/composer.py | {
"start": 649,
"end": 8439
} | class ____:
def __init__(self, loader=None):
# type: (Any) -> None
self.loader = loader
if self.loader is not None and getattr(self.loader, '_composer', None) is None:
self.loader._composer = self
self.anchors = {} # type: Dict[Any, Any]
@property
def parser(sel... | Composer |
python | ray-project__ray | doc/source/ray-core/doc_code/actors.py | {
"start": 87,
"end": 529
} | class ____:
async def f(self):
try:
await asyncio.sleep(5)
except asyncio.CancelledError:
print("Actor task canceled.")
actor = Actor.remote()
ref = actor.f.remote()
# Wait until task is scheduled.
time.sleep(1)
ray.cancel(ref)
try:
ray.get(ref)
except ray.exceptions.... | Actor |
python | ray-project__ray | rllib/examples/_old_api_stack/models/shared_weights_model.py | {
"start": 2044,
"end": 3723
} | class ____(TFModelV2):
"""Example of weight sharing between two different TFModelV2s.
NOTE: This will only work for tf1 (static graph). When running with
config.framework_str=tf2, use TF2SharedWeightsModel, instead!
Here, we share the variables defined in the 'shared' variable scope
by entering it... | SharedWeightsModel1 |
python | ray-project__ray | python/ray/tune/logger/json.py | {
"start": 2042,
"end": 4179
} | class ____(LoggerCallback):
"""Logs trial results in json format.
Also writes to a results file and param.json file when results or
configurations are updated. Experiments must be executed with the
JsonLoggerCallback to be compatible with the ExperimentAnalysis tool.
"""
_SAVED_FILE_TEMPLATES ... | JsonLoggerCallback |
python | spack__spack | lib/spack/spack/cmd/create.py | {
"start": 19168,
"end": 20037
} | class ____(PackageTemplate):
"""Provides appropriate overrides for octave packages"""
base_class_name = "OctavePackage"
package_class_import = "from spack_repo.builtin.build_systems.octave import OctavePackage"
dependencies = """\
extends("octave")
# FIXME: Add additional dependencies if requ... | OctavePackageTemplate |
python | qdrant__qdrant-client | tools/async_client_generator/base_generator.py | {
"start": 86,
"end": 425
} | class ____:
def __init__(self) -> None:
self.transformers: list[ast.NodeTransformer] = []
def generate(self, code: str) -> str:
nodes = ast.parse(code)
for transformer in self.transformers:
nodes = transformer.visit(nodes)
return AUTOGEN_WARNING_MESSAGE + ast.unpar... | BaseGenerator |
python | conda__conda | conda/common/configuration.py | {
"start": 3699,
"end": 4239
} | class ____(ValidationError):
def __init__(
self, parameter_name, parameter_value, source, wrong_type, valid_types, msg=None
):
self.wrong_type = wrong_type
self.valid_types = valid_types
if msg is None:
msg = (
f"Parameter {parameter_name} = {parameter... | InvalidTypeError |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 14485,
"end": 15168
} | class ____(StringIORewind):
params = ([True, False], ["c", "python"])
param_names = ["do_cache", "engine"]
def setup(self, do_cache, engine):
data = ("\n".join([f"10/{year}" for year in range(2000, 2100)]) + "\n") * 10
self.StringIO_input = StringIO(data)
def time_read_csv_cached(self,... | ReadCSVCachedParseDates |
python | realpython__materials | python-sqlite-sqlalchemy/project/examples/example_3/app/models.py | {
"start": 2276,
"end": 2654
} | class ____(db.Model):
__tablename__ = "albums"
album_id = db.Column("AlbumId", db.Integer, primary_key=True)
title = db.Column("Title", db.String(160), nullable=False)
artist_id = db.Column(
"ArtistId",
db.ForeignKey("artists.ArtistId"),
nullable=False,
index=True,
)
... | Album |
python | django__django | django/forms/widgets.py | {
"start": 2830,
"end": 7982
} | class ____:
def __init__(self, media=None, css=None, js=None):
if media is not None:
css = getattr(media, "css", {})
js = getattr(media, "js", [])
else:
if css is None:
css = {}
if js is None:
js = []
self._css_l... | Media |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/delete/tutorial001_py310.py | {
"start": 434,
"end": 2559
} | class ____(SQLModel):
name: str | None = None
secret_name: str | None = None
age: int | 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, echo=True, connect_args=connect_args)
def crea... | HeroUpdate |
python | gevent__gevent | src/greentest/3.10/test_ftplib.py | {
"start": 3571,
"end": 9048
} | class ____(asynchat.async_chat):
dtp_handler = DummyDTPHandler
def __init__(self, conn, encoding=DEFAULT_ENCODING):
asynchat.async_chat.__init__(self, conn)
# tells the socket to handle urgent data inline (ABOR command)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
... | DummyFTPHandler |
python | scikit-learn__scikit-learn | sklearn/utils/_repr_html/base.py | {
"start": 217,
"end": 4773
} | class ____:
"""Mixin class allowing to generate a link to the API documentation.
This mixin relies on three attributes:
- `_doc_link_module`: it corresponds to the root module (e.g. `sklearn`). Using this
mixin, the default value is `sklearn`.
- `_doc_link_template`: it corresponds to the templat... | _HTMLDocumentationLinkMixin |
python | psf__requests | src/requests/exceptions.py | {
"start": 2837,
"end": 2948
} | class ____(RequestException, ValueError):
"""The URL scheme (e.g. http or https) is missing."""
| MissingSchema |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/logger.py | {
"start": 273,
"end": 1450
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
description = graphene.String()
configField = graphene.Field(GrapheneConfigTypeField)
class Meta:
name = "Logger"
def __init__(
self,
get_config_type: Callable[[str], ConfigTypeSnap],
logger_d... | GrapheneLogger |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_logout.py | {
"start": 220,
"end": 1870
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return reverse("sentry-logout")
def test_get_shows_page(self) -> None:
self.login_as(self.user)
resp = self.client.get(self.path)
assert resp.status_code == 200
assert self.client.session.keys(), "Not log... | AuthLogoutTest |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 1850,
"end": 2173
} | class ____(BaseSimpleType):
@classmethod
def convert_from_xml(cls, str_value: str) -> int:
return int(str_value)
@classmethod
def convert_to_xml(cls, value: int) -> str:
return str(value)
@classmethod
def validate(cls, value: Any) -> None:
cls.validate_int(value)
| BaseIntType |
python | kamyu104__LeetCode-Solutions | Python/minimum-changes-to-make-k-semi-palindromes.py | {
"start": 106,
"end": 1595
} | class ____(object):
def minimumChanges(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
divisors = [[] for _ in xrange(len(s)+1)]
for i in xrange(1, len(divisors)): # Time: O(nlogn), Space: O(nlogn)
for j in xrange(i, len(divisors), i):
... | Solution |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 33523,
"end": 34384
} | class ____(Source):
"""Points to the actual `torch` module - used instead of GlobalSource
in case the user has overridden `torch` in their local namespace"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
from .guards import GuardBuilder, install_gu... | TorchSource |
python | pennersr__django-allauth | allauth/socialaccount/providers/globus/provider.py | {
"start": 514,
"end": 1251
} | class ____(OAuth2Provider):
id = "globus"
name = "Globus"
account_class = GlobusAccount
oauth2_adapter_class = GlobusOAuth2Adapter
def extract_uid(self, data):
if "sub" not in data:
raise ProviderException("Globus OAuth error", data)
return str(data["sub"])
def extr... | GlobusProvider |
python | huggingface__transformers | src/transformers/models/umt5/modeling_umt5.py | {
"start": 5427,
"end": 6106
} | class ____(nn.Module):
def __init__(self, config: UMT5Config):
super().__init__()
if config.is_gated_act:
self.DenseReluDense = UMT5DenseGatedActDense(config)
else:
self.DenseReluDense = UMT5DenseActDense(config)
self.layer_norm = UMT5LayerNorm(config.d_model... | UMT5LayerFF |
python | ray-project__ray | python/ray/data/tests/test_iceberg.py | {
"start": 27747,
"end": 34488
} | class ____:
"""Test basic write operations for APPEND, UPSERT, and OVERWRITE modes."""
def test_append_basic(self, clean_table):
"""Test basic APPEND mode - add new rows without schema changes."""
initial_data = _create_typed_dataframe(
{"col_a": [1, 2], "col_b": ["row_1", "row_2"],... | TestBasicWriteModes |
python | dask__dask | dask/layers.py | {
"start": 1815,
"end": 2322
} | class ____(ArrayBlockwiseDep):
"""Produce slice(s) into the full-sized array given a chunk index"""
starts: tuple[tuple[int, ...], ...]
def __init__(self, chunks: tuple[tuple[int, ...], ...]):
super().__init__(chunks)
self.starts = tuple(cached_cumsum(c, initial_zero=True) for c in chunks)... | ArraySliceDep |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-hologres/llama_index/vector_stores/hologres/base.py | {
"start": 522,
"end": 6420
} | class ____(BasePydanticVectorStore):
"""
Hologres Vector Store.
Hologres is a one-stop real-time data warehouse, which can support high performance OLAP analysis and high QPS online services.
Hologres supports vector processing and allows you to use vector data
to show the characteristics of unstru... | HologresVectorStore |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 106388,
"end": 135460
} | class ____(_Style):
"""
`ArrowStyle` is a container class which defines several
arrowstyle classes, which is used to create an arrow path along a
given path. These are mainly used with `FancyArrowPatch`.
An arrowstyle object can be either created as::
ArrowStyle.Fancy(head_length=.4, h... | ArrowStyle |
python | pypa__packaging | tests/test_tags.py | {
"start": 17476,
"end": 19748
} | class ____:
def test_non_android(self) -> None:
non_android_error = pytest.raises(TypeError)
with non_android_error:
list(tags.android_platforms())
with non_android_error:
list(tags.android_platforms(api_level=18))
with non_android_error:
list(tags... | TestAndroidPlatforms |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_elastic_transform_test.py | {
"start": 164,
"end": 2998
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.RandomElasticTransform,
init_kwargs={
"factor": 1.0,
"scale": 0.5,
"interpolation": "bilinear",
... | RandomElasticTransformTest |
python | keon__algorithms | tests/test_matrix.py | {
"start": 12788,
"end": 13188
} | class ____(unittest.TestCase):
def test_sort_diagonally(self):
mat = [
[3, 3, 1, 1],
[2, 2, 1, 2],
[1, 1, 1, 2]
]
self.assertEqual(sort_matrix_diagonally.sort_diagonally(mat), [
[1, 1, 1, 1],
[1, 2, 2, 2],
[1, 2, 3, 3]
... | TestSortMatrixDiagonally |
python | django__django | django/contrib/staticfiles/finders.py | {
"start": 1188,
"end": 5125
} | class ____(BaseFinder):
"""
A static files finder that uses the ``STATICFILES_DIRS`` setting
to locate files.
"""
def __init__(self, app_names=None, *args, **kwargs):
# List of locations with static files
self.locations = []
# Maps dir paths to an appropriate storage instanc... | FileSystemFinder |
python | encode__django-rest-framework | tests/test_throttling.py | {
"start": 686,
"end": 775
} | class ____(UserRateThrottle):
rate = '3/sec'
scope = 'seconds'
| User3SecRateThrottle |
python | dask__dask | dask/order.py | {
"start": 2010,
"end": 33619
} | class ____(NamedTuple):
priority: int
critical_path: float | int
@overload
def order(
dsk: Mapping[Key, Any],
dependencies: Mapping[Key, set[Key]] | None = None,
*,
return_stats: Literal[True],
) -> dict[Key, Order]: ...
@overload
def order(
dsk: Mapping[Key, Any],
dependencies: Mapp... | Order |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.