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 | python/ray/train/torch/torch_detection_predictor.py | {
"start": 291,
"end": 2931
} | class ____(TorchPredictor):
"""A predictor for TorchVision detection models.
Unlike other Torch models, instance segmentation models return
`List[Dict[str, Tensor]]`. This predictor extends :class:`TorchPredictor` to support
the non-standard outputs.
To learn more about instance segmentation model... | TorchDetectionPredictor |
python | great-expectations__great_expectations | great_expectations/expectations/row_conditions.py | {
"start": 872,
"end": 1064
} | class ____(ValueError):
"""Raised when an AND group contains OR conditions."""
def __init__(self):
super().__init__("AND groups cannot contain OR conditions")
| AndContainsOrError |
python | weaviate__weaviate-python-client | integration/test_batch_v4.py | {
"start": 1536,
"end": 1677
} | class ____:
"""Handles pandas and polars series."""
array: list
def to_list(self) -> list:
return self.array
| MockDFSeries |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks.py | {
"start": 25284,
"end": 28862
} | class ____(session_run_hook.SessionRunHook):
"""Hook that counts steps per second."""
def __init__(self,
every_n_steps=100,
every_n_secs=None,
output_dir=None,
summary_writer=None):
if (every_n_steps is None) == (every_n_secs is None):
raise Va... | StepCounterHook |
python | tensorflow__tensorflow | tensorflow/compiler/tests/pooling_ops_test.py | {
"start": 9806,
"end": 21361
} | class ____(xla_test.XLATestCase):
CPU_DEVICE = "/job:localhost/replica:0/task:0/cpu:0"
def _VerifyOneTest(self,
pool_func,
pool_grad_func,
input_sizes,
ksize,
strides,
padding,
... | PoolGradTest |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 12429,
"end": 12573
} | class ____(SubclassSelectorProxyModel):
concrete_field = models.CharField(max_length=30, default="test_cf")
| SubclassSelectorProxyConcreteModel |
python | kamyu104__LeetCode-Solutions | Python/chalkboard-xor-game.py | {
"start": 85,
"end": 288
} | class ____(object):
def xorGame(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return reduce(xor, nums) == 0 or \
len(nums) % 2 == 0
| Solution |
python | sqlalchemy__sqlalchemy | test/sql/test_values.py | {
"start": 793,
"end": 24621
} | class ____(fixtures.TablesTest, AssertsCompiledSQL):
__dialect__ = default.DefaultDialect(supports_native_boolean=True)
run_setup_bind = None
run_create_tables = None
@classmethod
def define_tables(cls, metadata):
Table(
"people",
metadata,
Column("peop... | ValuesTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 1622,
"end": 2754
} | class ____(ConcreteTemplate):
cases = [
signature(types.slice2_type, types.intp),
signature(types.slice2_type, types.none),
signature(types.slice2_type, types.none, types.none),
signature(types.slice2_type, types.none, types.intp),
signature(types.slice2_type, types.intp, typ... | Slice |
python | django-compressor__django-compressor | compressor/offline/jinja2.py | {
"start": 450,
"end": 1478
} | class ____(Extension):
"""
Functional "spaceless" extension equivalent to Django's.
See: https://github.com/django/django/blob/master/django/template/defaulttags.py
"""
tags = set(["spaceless"])
def parse(self, parser):
lineno = next(parser.stream).lineno
body = parser.parse_s... | SpacelessExtension |
python | ray-project__ray | release/ray_release/reporter/db.py | {
"start": 300,
"end": 2329
} | class ____(Reporter):
def __init__(self):
self.firehose = boto3.client("firehose", config=Config(region_name="us-west-2"))
def report_result(self, test: Test, result: Result):
logger.info("Persisting result to the databricks delta lake...")
# Prometheus metrics are saved as buildkite a... | DBReporter |
python | wandb__wandb | wandb/vendor/pygments/lexers/dotnet.py | {
"start": 21757,
"end": 27668
} | class ____(RegexLexer):
"""
For the F# language (version 3.0).
AAAAACK Strings
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc335818775
.. versionadded:: 1.5
"""
name = 'FSharp'
aliases = ['fsharp']
filenames = ['*.fs', '*.fsi']
mimetypes... | FSharpLexer |
python | keon__algorithms | tests/test_backtrack.py | {
"start": 3534,
"end": 4865
} | class ____(unittest.TestCase):
def test_get_factors(self):
target1 = 32
answer1 = [
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]
self.assertEqual(sorted(get_factors(target1)), sorted(an... | TestFactorCombinations |
python | Lightning-AI__lightning | tests/parity_fabric/models.py | {
"start": 804,
"end": 1283
} | class ____(ABC, nn.Module):
"""Defines the interface for a model in a Fabric-PyTorch parity test."""
# Benchmarking parameters that should be model-specific
batch_size = 1
num_steps = 1
@abstractmethod
def get_optimizer(self, *args, **kwargs) -> Optimizer:
pass
@abstractmethod
... | ParityModel |
python | keras-team__keras | keras/src/distribution/distribution_lib_test.py | {
"start": 13745,
"end": 20259
} | class ____(testing.TestCase):
def setUp(self):
super().setUp()
self.devices = [f"cpu:{i}" for i in range(8)]
shape = (4, 2)
axis_names = ["data", "model"]
self.device_mesh = distribution_lib.DeviceMesh(
shape, axis_names, self.devices
)
self.shard... | LayoutMapTest |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 65145,
"end": 68512
} | class ____(Response):
"""
Response of events.get_task_events endpoint.
:param events: Events list
:type events: Sequence[dict]
:param returned: Number of results returned
:type returned: int
:param total: Total number of results available for this query
:type total: float
:param scr... | GetTaskEventsResponse |
python | cython__cython | tests/run/pep557_dataclasses.py | {
"start": 108,
"end": 540
} | class ____:
"""
>>> list(Color.__dataclass_fields__.keys())
['red', 'green', 'blue', 'alpha']
>>> Color(1, 2, 3)
Color(red=1, green=2, blue=3, alpha=255)
>>> Color(1, 2, 3, 4)
Color(red=1, green=2, blue=3, alpha=4)
>>> Color(green=1, blue=2, red=3, alpha=40)
Color(red=3, green=1, blu... | Color |
python | jina-ai__jina | tests/unit/jaml/parsers/executors/test_legacy.py | {
"start": 419,
"end": 542
} | class ____(A, B, C):
def __init__(self, d, *args, **kwargs):
super.__init__(*args, **kwargs)
self.d = d
| D |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 122,
"end": 309
} | class ____(analytics.Event):
organization_id: int
project_id: int
user_id: int | None = None
@analytics.eventclass("preprod_artifact.api.update")
| PreprodArtifactApiAssembleEvent |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 1268,
"end": 1361
} | class ____(ReleaseTestPackageError):
exit_code = ExitCode.SETUP_ERROR
| ReleaseTestSetupError |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 1771,
"end": 1979
} | class ____(InstanceView):
"""
A model with a slug-field.
"""
queryset = SlugBasedModel.objects.all()
serializer_class = SlugSerializer
lookup_field = 'slug'
# Tests
| SlugBasedInstanceView |
python | realpython__materials | inheritance-and-composition/inheritance/productivity.py | {
"start": 623,
"end": 727
} | class ____:
def work(self, hours):
return f"manufactures gadgets for {hours} hours."
| FactoryRole |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 22369,
"end": 22722
} | class ____(IOWarning):
"""
Raised when the VO service database can not be updated (possibly
due to a network outage). This is only a warning, since an older
and possible out-of-date VO service database was available
locally.
"""
message_template = "Unable to update service information for ... | W23 |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/run_tests/test_schema_only.py | {
"start": 270,
"end": 3067
} | class ____:
"""Test the Run schema model."""
def test_run_creation_minimal(self):
"""Test creating run with minimal required fields."""
run = DgApiRun(
id="test-run-123",
status=DgApiRunStatus.QUEUED,
created_at=1705311000.0, # 2024-01-15T10:30:00Z
)... | TestRunSchema |
python | astropy__astropy | astropy/coordinates/angles/errors.py | {
"start": 2247,
"end": 2818
} | class ____(AstropyWarning):
"""
Raised when a minute value is 60.
Parameters
----------
minute : int, float
"""
def __init__(self, minute, alternativeactionstr=None):
self.minute = minute
self.alternativeactionstr = alternativeactionstr
def __str__(self):
messa... | IllegalMinuteWarning |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 7048,
"end": 7558
} | class ____:
def __init__(self, val, config):
if is_nonstr_iter(val):
self.val = tuple(val)
else:
val = tuple(filter(None, val.split('/')))
self.val = ('',) + val
def text(self):
return f'physical_path = {self.val}'
phash = text
def __call__(... | PhysicalPathPredicate |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py | {
"start": 1751,
"end": 3262
} | class ____(object):
"""Abstraction for the state of the CFG walk for reaching definition analysis.
This is a value type. Only implements the strictly necessary operators.
Attributes:
value: Dict[qual_names.QN, Set[Definition, ...]], the defined symbols and
their possible definitions
"""
def __i... | _NodeState |
python | getsentry__sentry | src/sentry/analytics/events/sentry_app_installation_token_created.py | {
"start": 94,
"end": 306
} | class ____(analytics.Event):
user_id: int
organization_id: int
sentry_app_installation_id: int
sentry_app: str
analytics.register(SentryAppInstallationTokenCreated)
| SentryAppInstallationTokenCreated |
python | joke2k__faker | faker/providers/person/ar_PS/__init__.py | {
"start": 55,
"end": 884
} | class ____(ArabicPersonProvider):
last_names = (
"أبو اسنينة",
"أبو شقدم",
"أبو شلبك",
"أبو غليون",
"أبو قمر",
"أستيتية",
"الأدغم",
"الإغباري",
"البرغوثي",
"التركمان",
"التميمي",
"الجنيدي",
"الحسيني",
"ال... | Provider |
python | pypa__pip | tests/unit/test_options.py | {
"start": 7213,
"end": 8507
} | class ____(AddFakeCommandMixin):
def test_general_option_after_subcommand(self) -> None:
# FakeCommand intentionally returns the wrong type.
options, args = cast(
tuple[Values, list[str]], main(["fake", "--timeout", "-1"])
)
assert options.timeout == -1
def test_opti... | TestOptionsInterspersed |
python | ray-project__ray | python/ray/experimental/raysort/types.py | {
"start": 145,
"end": 303
} | class ____(NamedTuple):
part_id: PartId
node: NodeAddress
path: Path
def __repr__(self):
return f"Part({self.node}:{self.path})"
| PartInfo |
python | pytorch__pytorch | torch/_jit_internal.py | {
"start": 27404,
"end": 51307
} | class ____(contextlib.AbstractContextManager):
def __init__(self, **kwargs):
pass
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
pass
def ignore(drop=False, **kwargs):
"""
This decorator indicates to the compiler that a function or method should
be igno... | _IgnoreContextManager |
python | getsentry__sentry | src/sentry/models/releaseprojectenvironment.py | {
"start": 453,
"end": 590
} | class ____(str, Enum):
ADOPTED = "adopted"
LOW_ADOPTION = "low_adoption"
REPLACED = "replaced"
@region_silo_model
| ReleaseStages |
python | modin-project__modin | modin/config/envvars.py | {
"start": 41283,
"end": 41492
} | class ____(EnvironmentVariable, type=int):
"""Maximum number of rows which can be processed using local, native, pandas."""
varname = "MODIN_NATIVE_MAX_ROWS"
default = 10_000_000
| NativePandasMaxRows |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP042.py | {
"start": 50,
"end": 76
} | class ____(Enum, str): ...
| B |
python | doocs__leetcode | solution/3200-3299/3270.Find the Key of the Numbers/Solution.py | {
"start": 0,
"end": 264
} | class ____:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
ans, k = 0, 1
for _ in range(4):
x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10)
ans += x * k
k *= 10
return ans
| Solution |
python | walkccc__LeetCode | solutions/2029. Stone Game IX/2029.py | {
"start": 0,
"end": 238
} | class ____:
def stoneGameIX(self, stones: list[int]) -> bool:
count = collections.Counter(stone % 3 for stone in stones)
if count[0] % 2 == 0:
return min(count[1], count[2]) > 0
return abs(count[1] - count[2]) > 2
| Solution |
python | django__django | tests/foreign_object/models/article.py | {
"start": 1779,
"end": 2475
} | class ____(models.Model):
active_translation = ActiveTranslationField(
"ArticleTranslation",
from_fields=["id"],
to_fields=["article"],
related_name="+",
on_delete=models.CASCADE,
null=True,
)
active_translation_q = ActiveTranslationFieldWithQ(
"Articl... | Article |
python | google__jax | jax/_src/pallas/fuser/block_spec.py | {
"start": 4524,
"end": 5490
} | class ____:
scalar_prefetch: Any | None
program_ids: tuple[int | jax.Array, ...] | None
avals_in: tuple[core.AbstractValue, ...] | None
avals_out: tuple[core.AbstractValue, ...] | None
in_block_specs: tuple[pallas_core.BlockSpec, ...]
out_block_specs: tuple[pallas_core.BlockSpec, ...]
grid: tuple[int | ja... | KernelEvalContext |
python | pytorch__pytorch | test/distributed/checkpoint/test_fsspec.py | {
"start": 6239,
"end": 7071
} | class ____(TestCase):
@with_temp_dir
def test_remove_on_fail(self):
fs = FileSystem()
path = fs.init_path(self.temp_dir)
write_file = fs.concat_path(path, "writeable")
with self.assertRaises(OSError):
with fs.create_stream(write_file, "w") as s:
s.wri... | TestFileSystem |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/events.py | {
"start": 6671,
"end": 8720
} | class ____(Event):
"""The server-side view of an event that has happened to a Resource after it has
been received by the server"""
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="ignore", from_attributes=True
)
received: prefect.types._datetime.DateTime = Field(
default_fac... | ReceivedEvent |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/callbacks/fake_callback_handler.py | {
"start": 6642,
"end": 9397
} | class ____(AsyncCallbackHandler, BaseFakeCallbackHandlerMixin):
"""Fake async callback handler for testing."""
@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_
@property
def ignore_chain(self) -> bool:
"""Whether to igno... | FakeAsyncCallbackHandler |
python | django-haystack__django-haystack | test_haystack/discovery/search_indexes.py | {
"start": 83,
"end": 249
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, model_attr="body")
def get_model(self):
return Foo
| FooIndex |
python | kamyu104__LeetCode-Solutions | Python/find-the-k-beauty-of-a-number.py | {
"start": 52,
"end": 512
} | class ____(object):
def divisorSubstrings(self, num, k):
"""
:type num: int
:type k: int
:rtype: int
"""
result = curr = 0
s = map(int, str(num))
base = 10**(k-1)
for i, x in enumerate(s):
if i-k >= 0:
curr -= s[i-k]... | Solution |
python | plotly__plotly.py | plotly/graph_objs/sunburst/_legendgrouptitle.py | {
"start": 233,
"end": 2946
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst"
_path_str = "sunburst.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be speci... | Legendgrouptitle |
python | walkccc__LeetCode | solutions/1656. Design an Ordered Stream/1656.py | {
"start": 0,
"end": 412
} | class ____:
def __init__(self, n: int):
self.values = [''] * n
self.i = 0 # self.values' index (0-indexed)
def insert(self, idKey: int, value: str) -> list[str]:
idKey -= 1 # Converts to 0-indexed.
self.values[idKey] = value
if idKey > self.i:
return []
while self.i < len(self.value... | OrderedStream |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/data_loss_prevention.py | {
"start": 3993,
"end": 4269
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Data Loss Prevention link."""
name = "Cloud DLP Inspect Templates List"
key = "cloud_dlp_inspect_templates_list_key"
format_str = DLP_INSPECT_TEMPLATES_LIST_LINK
| CloudDLPInspectTemplatesListLink |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/groupsearchview.py | {
"start": 610,
"end": 1928
} | class ____(serializers.Serializer):
id = serializers.CharField(required=False)
name = serializers.CharField(required=True)
query = serializers.CharField(required=True, allow_blank=True)
querySort = serializers.ChoiceField(
required=False, choices=SortOptions.as_choices(), default=SortOptions.DAT... | ViewValidator |
python | pytorch__pytorch | torch/ao/quantization/pt2e/_affine_quantization.py | {
"start": 29917,
"end": 33819
} | class ____(AffineQuantizedObserverBase):
def __init__(
self,
mapping_type: MappingType,
target_dtype: torch.dtype,
granularity: Granularity,
averaging_constant=0.01,
quant_min: int | None = None,
quant_max: int | None = None,
eps: float | None = None,
... | AffineQuantizedMovingAverageMinMaxObserver |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 575,
"end": 774
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.NonIntegerPk
sqlalchemy_session = models.session
id = factory.Sequence(lambda n: 'foo%d' % n)
| NonIntegerPkFactory |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 12591,
"end": 16222
} | class ____(TestBaseItemExporter):
def _get_exporter(self, **kwargs):
return XmlItemExporter(self.output, **kwargs)
def assertXmlEquivalent(self, first, second, msg=None):
def xmltuple(elem):
children = list(elem.iterchildren())
if children:
return [(child... | TestXmlItemExporter |
python | numba__numba | numba/tests/test_fastmath.py | {
"start": 162,
"end": 4564
} | class ____(unittest.TestCase):
def test_jit(self):
def foo(x):
return x + math.sin(x)
fastfoo = njit(fastmath=True)(foo)
slowfoo = njit(foo)
self.assertEqual(fastfoo(0.5), slowfoo(0.5))
fastllvm = fastfoo.inspect_llvm(fastfoo.signatures[0])
slowllvm = slow... | TestFastMath |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-steps-to-make-two-strings-anagram-ii.py | {
"start": 63,
"end": 346
} | class ____(object):
def minSteps(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
cnt1, cnt2 = collections.Counter(s), collections.Counter(t)
return sum((cnt1-cnt2).itervalues())+sum((cnt2-cnt1).itervalues())
| Solution |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3425,
"end": 3561
} | class ____(semaphore_dtype):
"""Regular semaphore dtype.
Like its superclass, this class should never be instantiated.
"""
| semaphore |
python | google__jax | examples/ffi/tests/cpu_examples_test.py | {
"start": 2994,
"end": 3460
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cpu"]):
self.skipTest("Unsupported platform")
def test_basic_array(self):
x = jnp.linspace(0, 0.5, 10)
self.assertAllClose(cpu_examples.aliasing(x), x)
def test_basic_scalar(self):
x = jnp.in... | AliasingTests |
python | celery__celery | examples/eventlet/bulk_task_producer.py | {
"start": 529,
"end": 1673
} | class ____:
"""Usage::
>>> app = Celery(broker='amqp://')
>>> ProducerPool(app)
"""
Receipt = Receipt
def __init__(self, app, size=20):
self.app = app
self.size = size
self.inqueue = LightQueue()
self._running = None
self._producers = None
... | ProducerPool |
python | fluentpython__example-code-2e | 22-dyn-attr-prop/bulkfood/bulkfood_v2b.py | {
"start": 911,
"end": 1441
} | class ____:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
def get_weight(self): # <1>
return self.__weight
def set_weight(self, value)... | LineItem |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 6782,
"end": 7048
} | class ____(Binding):
"""
A binding that defines a function or a class.
"""
def redefines(self, other):
return (
super().redefines(other) or
(isinstance(other, Assignment) and self.name == other.name)
)
| Definition |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_cloud_formation.py | {
"start": 1214,
"end": 3271
} | class ____:
@mock_aws
def setup_method(self, method):
self.client = boto3.client("cloudformation", region_name="us-east-1")
def test_init(self):
sensor = CloudFormationCreateStackSensor(
task_id="cf_create_stack_init",
stack_name="fake-stack",
# Generic h... | TestCloudFormationCreateStackSensor |
python | openai__openai-python | src/openai/types/beta/realtime/response_output_item_added_event.py | {
"start": 254,
"end": 713
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
item: ConversationItem
"""The item to add to the conversation."""
output_index: int
"""The index of the output item in the Response."""
response_id: str
"""The ID of the Response to which the item belongs.""... | ResponseOutputItemAddedEvent |
python | wandb__wandb | wandb/sdk/wandb_run.py | {
"start": 14680,
"end": 14844
} | class ____:
sync_items_total: int = field(default=0)
sync_items_pending: int = field(default=0)
sync_time: datetime | None = field(default=None)
| RunStatus |
python | allegroai__clearml | clearml/binding/frameworks/tensorflow_bind.py | {
"start": 10606,
"end": 41792
} | class ____(object):
"""
TF SummaryWriter implementation that converts the tensorboard's summary into
ClearML events and reports the events (metrics) for an ClearML task (logger).
"""
_current_task = None
__report_hparams = True
_add_lock = threading.RLock()
_series_name_lookup = {}
... | EventTrainsWriter |
python | huggingface__transformers | src/transformers/models/univnet/feature_extraction_univnet.py | {
"start": 1036,
"end": 22813
} | class ____(SequenceFeatureExtractor):
r"""
Constructs a UnivNet feature extractor.
This class extracts log-mel-filter bank features from raw speech using the short time Fourier Transform (STFT). The
STFT implementation follows that of TacoTron 2 and Hifi-GAN.
This feature extractor inherits from [... | UnivNetFeatureExtractor |
python | doocs__leetcode | solution/3500-3599/3590.Kth Smallest Path XOR Sum/Solution.py | {
"start": 1528,
"end": 3048
} | class ____:
def kthSmallest(
self, par: List[int], vals: List[int], queries: List[List[int]]
) -> List[int]:
n = len(par)
tree = [[] for _ in range(n)]
for i in range(1, n):
tree[par[i]].append(i)
path_xor = vals[:]
narvetholi = path_xor
def ... | Solution |
python | viewflow__viewflow | tests/_cases/test_workflow_undo_tasks.py | {
"start": 289,
"end": 2670
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.admin = User.objects.create_superuser(username="admin", password="admin")
def reverse(self, flow_task, name):
task = TestUndoFlow.task_class.objects.get(flow_task=flow_task)
return flow_task.reverse(name, args=[task.proc... | Test |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/index_add__test.py | {
"start": 554,
"end": 1589
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, dim, dtype, device):
# creating the original tensor
tensor = torch.rand(M, N, K, dtype=dtype, device=device)
# creating index
index_max_len = tensor.shape[dim]
index_len = numpy.random.randint(1, index_max_len ... | IndexAddBenchmark |
python | fastai__fastai | fastai/text/models/core.py | {
"start": 1414,
"end": 2380
} | class ____(Module):
"To go on top of a RNNCore module and create a Language Model."
initrange=0.1
def __init__(self,
n_out:int, # Number of output channels
n_hid:int, # Number of features in encoder last layer output
output_p:float=0.1, # Input dropout probability
tie_enco... | LinearDecoder |
python | fastapi__sqlmodel | sqlmodel/sql/sqltypes.py | {
"start": 110,
"end": 558
} | class ____(types.TypeDecorator): # type: ignore
impl = types.String
cache_ok = True
mysql_default_length = 255
def load_dialect_impl(self, dialect: Dialect) -> "types.TypeEngine[Any]":
impl = cast(types.String, self.impl)
if impl.length is None and dialect.name == "mysql":
... | AutoString |
python | spyder-ide__spyder | spyder/widgets/dock.py | {
"start": 902,
"end": 3208
} | class ____(QObject, SpyderConfigurationAccessor):
"""Filter event attached to each DockWidget QTabBar."""
CONF_SECTION = 'main'
def __init__(self, dock_tabbar, main):
QObject.__init__(self)
self.dock_tabbar: QTabBar = dock_tabbar
self.main = main
self.from_index = None
... | TabFilter |
python | great-expectations__great_expectations | docs/docusaurus/docs/snippets/expect_column_values_to_equal_three.py | {
"start": 1554,
"end": 4983
} | class ____(ColumnMapMetricProvider):
# </snippet>
# This is the id string that will be used to reference your metric.
# <snippet name="docs/docusaurus/docs/snippets/expect_column_values_to_equal_three.py metric_name">
condition_metric_name = "column_values.equal_three"
# </snippet>
# This meth... | ColumnValuesEqualThree |
python | lazyprogrammer__machine_learning_examples | nlp_class2/glove_theano.py | {
"start": 1124,
"end": 8591
} | class ____:
def __init__(self, D, V, context_sz):
self.D = D
self.V = V
self.context_sz = context_sz
def fit(self, sentences, cc_matrix=None, learning_rate=1e-4, reg=0.1, xmax=100, alpha=0.75, epochs=10, gd=False, use_theano=False, use_tensorflow=False):
# build co-occurrence ma... | Glove |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_health_checks.py | {
"start": 4624,
"end": 4742
} | class ____(RuleBasedStateMachine):
@rule()
def r(self):
return "any non-None value"
| ReturningRuleMachine |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1150504,
"end": 1157657
} | class ____(sgqlc.types.Type, Node, AnnouncementBanner):
"""An account to manage multiple organizations with consolidated
policy and billing.
"""
__schema__ = github_schema
__field_names__ = (
"avatar_url",
"billing_info",
"created_at",
"database_id",
"descrip... | Enterprise |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/metrics_test.py | {
"start": 167465,
"end": 169487
} | class ____(test.TestCase):
def setUp(self):
np.random.seed(1)
ops.reset_default_graph()
@test_util.run_deprecated_v1
def testVars(self):
metrics.false_negatives_at_thresholds(
predictions=array_ops.ones((10, 1)),
labels=array_ops.ones((10, 1)),
thresholds=[0.15, 0.5, 0.85])
... | FalseNegativesAtThresholdsTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/sharedstrings/test_initialisation.py | {
"start": 309,
"end": 872
} | class ____(unittest.TestCase):
"""
Test initialisation of the SharedStrings class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.sharedstrings = SharedStrings()
self.sharedstrings._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test S... | TestInitialisation |
python | huggingface__transformers | src/transformers/generation/continuous_batching/cache.py | {
"start": 20311,
"end": 34222
} | class ____:
"""A helper class to determine the best number of pages and maximum number of tokens per batch for the paged
attention cache, providing automatic sizing based on available GPU memory.
The helper works using the number of pages, which is tied to the number of blocks by:
num_blocks = num_p... | PagedAttentionMemoryHandler |
python | pypa__warehouse | warehouse/oidc/models/_core.py | {
"start": 2895,
"end": 3470
} | class ____(db.Model):
__tablename__ = "oidc_publisher_project_association"
__table_args__ = (UniqueConstraint("oidc_publisher_id", "project_id"),)
oidc_publisher_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("oidc_publishers.id"),
nullable=False,
primar... | OIDCPublisherProjectAssociation |
python | kamyu104__LeetCode-Solutions | Python/count-good-numbers.py | {
"start": 32,
"end": 541
} | class ____(object):
def countGoodNumbers(self, n):
"""
:type n: int
:rtype: int
"""
def powmod(a, b, mod):
a %= mod
result = 1
while b:
if b&1:
result = (result*a)%mod
a = (a*a)%mod
... | Solution |
python | mlflow__mlflow | tests/crewai/test_crewai_autolog.py | {
"start": 4535,
"end": 29728
} | class ____(BaseTool):
name: str = "TestTool"
description: str = "test tool"
def _run(self, argument: str) -> str:
return "Tool Answer"
@pytest.fixture
def tool_agent_1():
return Agent(
role="City Selection Expert",
goal=_AGENT_1_GOAL,
backstory=_AGENT_1_BACKSTORY,
... | SampleTool |
python | pytorch__pytorch | test/dynamo/test_autograd_function.py | {
"start": 1138,
"end": 1240
} | class ____(torch.nn.Module):
def forward(self, foo):
return CustomFunc1().apply(foo)
| Module1 |
python | PyCQA__pylint | tests/functional/u/unused/unused_private_member.py | {
"start": 8886,
"end": 9034
} | class ____:
def __bar(self, x):
print(x)
fizz = partialmethod(__bar, 'fizz')
test = FalsePositive4756a()
test.fizz()
| FalsePositive4756a |
python | encode__django-rest-framework | tests/test_api_client.py | {
"start": 5381,
"end": 6159
} | class ____(APIView):
def get(self, request):
headers = {
key[5:].replace('_', '-'): value
for key, value in request.META.items()
if key.startswith('HTTP_')
}
return Response({
'method': request.method,
'headers': headers
})
... | HeadersView |
python | ray-project__ray | python/ray/serve/tests/test_custom_autoscaling_metrics.py | {
"start": 1591,
"end": 11438
} | class ____:
"""Check that redeploying a deployment doesn't reset its start time."""
def test_custom_serve_metrics(self, serve_instance):
@serve.deployment(
autoscaling_config={
"min_replicas": 1,
"max_replicas": 5,
"upscale_delay_s": 0.5,
... | TestCustomServeMetrics |
python | sphinx-doc__sphinx | tests/roots/test-api-set-translator/conf.py | {
"start": 951,
"end": 1002
} | class ____(XMLTranslator):
pass
| ConfXMLTranslator |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/console/kernelapp.py | {
"start": 675,
"end": 1413
} | class ____(Thread):
"""
Daemon thread that terminates the program immediately when the parent
process no longer exists.
Notes
-----
This is based on the ParentPollerUnix class from ipykernel.
"""
def __init__(self, parent_pid=0):
"""Initialize the poller."""
super().__i... | SpyderParentPoller |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_lower_triangular.py | {
"start": 1324,
"end": 8976
} | class ____(linear_operator.LinearOperator):
"""`LinearOperator` acting like a [batch] square lower triangular matrix.
This operator acts like a [batch] lower triangular matrix `A` with shape
`[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a
batch member. For every batch index `(i1,...,ib)`... | LinearOperatorLowerTriangular |
python | doocs__leetcode | solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py | {
"start": 0,
"end": 683
} | class ____:
__slots__ = ("children",)
def __init__(self):
self.children: List[Trie | None] = [None, None]
def insert(self, x: int):
node = self
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
... | Trie |
python | walkccc__LeetCode | solutions/3467. Transform Array by Parity/3467.py | {
"start": 0,
"end": 181
} | class ____:
def transformArray(self, nums: list[int]) -> list[int]:
return ([0] * sum(num % 2 == 0 for num in nums) +
[1] * sum(num % 2 == 1 for num in nums))
| Solution |
python | walkccc__LeetCode | solutions/2127. Maximum Employees to Be Invited to a Meeting/2127.py | {
"start": 85,
"end": 1732
} | class ____:
def maximumInvitations(self, favorite: list[int]) -> int:
n = len(favorite)
sumComponentsLength = 0 # the component: a -> b -> c <-> x <- y
graph = [[] for _ in range(n)]
inDegrees = [0] * n
maxChainLength = [1] * n
# Build the graph.
for i, f in enumerate(favorite):
gr... | Solution |
python | realpython__materials | python-serialize/http-payload/django-rest-api/rest_api/serializers.py | {
"start": 190,
"end": 313
} | class ____(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ["name"]
| UserSerializerIn |
python | jina-ai__jina | tests/integration/runtimes/test_runtimes.py | {
"start": 21712,
"end": 30390
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
if doc.text == 'slow':
time.sleep(1.0)
async def _create_worker(pod, port_generator, type='worker', executor=None):
worker_port = port_generator()
worker_process = multiprocessing.Proces... | FastSlowExecutor |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 166440,
"end": 167637
} | class ____(Response):
"""
Response of tasks.delete_artifacts endpoint.
:param deleted: Indicates if the task was updated successfully
:type deleted: int
"""
_service = "tasks"
_action = "delete_artifacts"
_version = "2.20"
_schema = {
"definitions": {},
"properties"... | DeleteArtifactsResponse |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/pytest/test_statistics.py | {
"start": 2759,
"end": 3287
} | class ____(TestCase):
@given(integers())
def test_all_valid(self, x):
pass
"""
def test_prints_statistics_for_unittest_tests(testdir):
script = testdir.makepyfile(UNITTEST_TESTSUITE)
result = testdir.runpytest(script, PRINT_STATISTICS_OPTION)
out = "\n".join(result.stdout.lines)
assert... | TestStuff |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 24966,
"end": 25085
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Devuan'
strategy_class = FileStrategy
| DevuanHostname |
python | weaviate__weaviate-python-client | weaviate/collections/classes/generative.py | {
"start": 44283,
"end": 45000
} | class ____(BaseModel):
prompt: str
non_blob_properties: Optional[List[str]]
image_properties: Optional[List[str]]
images: Optional[Iterable[str]]
metadata: bool = False
def _to_grpc(
self, provider: _GenerativeConfigRuntime
) -> generative_pb2.GenerativeSearch.Grouped:
retur... | _GroupedTask |
python | astropy__astropy | astropy/convolution/tests/test_convolve.py | {
"start": 24946,
"end": 43480
} | class ____:
def test_list(self):
"""
Test that convolve works correctly when inputs are lists
"""
x = [
[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
[[1, 1, 1], [1, 1, 1], [1, 1, 1]],
]
z = convolve(x, x, b... | TestConvolve3D |
python | neetcode-gh__leetcode | python/0283-move-zeroes.py | {
"start": 0,
"end": 395
} | class ____:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0 and nums[slow] == 0:
nums[slow], nums[fast] = nums[fast]... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 15817,
"end": 16031
} | class ____(VegaLiteSchema):
"""AnyMarkConfig schema wrapper."""
_schema = {"$ref": "#/definitions/AnyMarkConfig"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| AnyMarkConfig |
python | keras-team__keras | keras/src/distillation/distillation_loss.py | {
"start": 2983,
"end": 9661
} | class ____(DistillationLoss):
"""Feature distillation loss.
Feature distillation transfers knowledge from intermediate layers of the
teacher model to corresponding layers of the student model. This approach
helps the student learn better internal representations and often leads
to better performanc... | FeatureDistillation |
python | encode__httpx | httpx/_exceptions.py | {
"start": 4818,
"end": 4999
} | class ____(ProtocolError):
"""
The protocol was violated by the server.
For example, returning malformed HTTP.
"""
# Other request exceptions...
| RemoteProtocolError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.