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 | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_tasks.py | {
"start": 2793,
"end": 3703
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.tasks.CloudTasksHook")
def test_update_queue(self, mock_hook):
mock_hook.return_value.update_queue.return_value = TEST_QUEUE
operator = CloudTasksQueueUpdateOperator(task_queue=Queue(name=FULL_QUEUE_PATH), task_id="id")
r... | TestCloudTasksQueueUpdate |
python | wandb__wandb | wandb/vendor/pygments/lexers/theorem.py | {
"start": 15815,
"end": 18983
} | class ____(RegexLexer):
"""
For the `Lean <https://github.com/leanprover/lean>`_
theorem prover.
.. versionadded:: 2.0
"""
name = 'Lean'
aliases = ['lean']
filenames = ['*.lean']
mimetypes = ['text/x-lean']
flags = re.MULTILINE | re.UNICODE
keywords1 = (
'import', ... | LeanLexer |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 43151,
"end": 43342
} | class ____(BaseModel, extra="forbid"):
origin: "GeoPoint" = Field(..., description="")
to: str = Field(..., description="Payload field with the destination geo point")
| GeoDistanceParams |
python | huggingface__transformers | src/transformers/models/omdet_turbo/modeling_omdet_turbo.py | {
"start": 65656,
"end": 74124
} | class ____(OmDetTurboPreTrainedModel):
def __init__(self, config: OmDetTurboConfig):
super().__init__(config)
self.vision_backbone = OmDetTurboVisionBackbone(config)
self.language_backbone = OmDetTurboLanguageBackbone(config)
self.encoder = OmDetTurboHybridEncoder(config)
sel... | OmDetTurboForObjectDetection |
python | tensorflow__tensorflow | third_party/xla/xla/python/xla_client.py | {
"start": 3106,
"end": 3463
} | class ____:
"""Python representation of a xla.PrecisionConfig protobuf."""
__slots__ = ('operand_precision',)
Precision = ops.PrecisionConfig_Precision # pylint: disable=invalid-name
def __init__(self):
self.operand_precision = []
FftType = ops.FftType
ShapeIndex = ops.ShapeIndex
ResultAccuracyMode = ... | PrecisionConfig |
python | realpython__materials | python-copy/rectangle.py | {
"start": 14,
"end": 246
} | class ____:
def __init__(self, top_left, bottom_right):
self.top_left = top_left
self.bottom_right = bottom_right
def __repr__(self):
return f"Rectangle({self.top_left}, {self.bottom_right})"
| Rectangle |
python | sympy__sympy | sympy/physics/mechanics/pathway.py | {
"start": 406,
"end": 3182
} | class ____(ABC):
"""Abstract base class for all pathway classes to inherit from.
Notes
=====
Instances of this class cannot be directly instantiated by users. However,
it can be used to created custom pathway types through subclassing.
"""
def __init__(self, *attachments):
"""Ini... | PathwayBase |
python | google__jax | tests/tree_util_test.py | {
"start": 4668,
"end": 4751
} | class ____(dict):
pass
@tree_util.register_static
@dataclasses.dataclass
| StaticDict |
python | tensorflow__tensorflow | tensorflow/compiler/tests/concat_ops_test.py | {
"start": 13222,
"end": 13744
} | class ____(xla_test.XLATestCase):
def testBasic(self):
with self.session():
with self.test_scope():
cdim = constant_op.constant(1, dtypes.int32)
s0 = constant_op.constant([2, 3, 5], dtypes.int32)
s1 = constant_op.constant([2, 7, 5], dtypes.int32)
s2 = constant_op.constant([2... | ConcatOffsetTest |
python | keras-team__keras | keras/src/metrics/metrics_utils.py | {
"start": 858,
"end": 995
} | class ____(Enum):
TRUE_POSITIVES = "tp"
FALSE_POSITIVES = "fp"
TRUE_NEGATIVES = "tn"
FALSE_NEGATIVES = "fn"
| ConfusionMatrix |
python | kamyu104__LeetCode-Solutions | Python/split-array-largest-sum.py | {
"start": 55,
"end": 714
} | class ____(object):
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
def check(nums, m, s):
cnt, curr_sum = 1, 0
for num in nums:
curr_sum += num
if curr_sum > s:
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/smallest-divisible-digit-product-ii.py | {
"start": 2232,
"end": 4138
} | class ____(object):
def smallestNumber(self, num, t):
"""
:type num: str
:type t: int
:rtype: str
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def find_candidates(t, l): # Time: O(logt)
candidates = [... | Solution2 |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_aliases.py | {
"start": 10356,
"end": 11234
} | class ____(GenerationBase):
"""
Test the ``generate_aliases_global`` signal handler behaviour.
"""
def get_signal_handler(self):
return signal_handlers.generate_aliases_global
def test_no_change(self):
"""
Thumbnails are only generated when the file is modified.
"""... | GlobalGenerationTest |
python | apache__airflow | helm-tests/tests/helm_tests/redis/test_labels_networkpolicy.py | {
"start": 900,
"end": 4278
} | class ____:
"""Tests redis network policy labels."""
AIRFLOW_EXECUTOR = "CeleryExecutor"
TEMPLATE_FILE = "templates/redis/redis-networkpolicy.yaml"
def test_should_add_global_labels(self):
"""Test adding only .Values.labels."""
docs = render_chart(
values={
... | TestRedisNetworkPolicy |
python | pytorch__pytorch | test/quantization/eager/test_quantize_eager_qat.py | {
"start": 1744,
"end": 9738
} | class ____(torch.nn.Conv2d, torch.nn.modules.conv._ConvNd):
"""
Conv-BN fusion implemented with explicit folding. Useful
to verify numerical equivalency with non-folded version.
"""
def __init__(
self,
# ConvNd args
in_channels,
out_channels,
kernel_size,
... | _ReferenceConvBnNd |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/repository_definition/repository_data.py | {
"start": 7428,
"end": 22442
} | class ____(RepositoryData):
"""Default implementation of RepositoryData used by the :py:func:`@repository <repository>` decorator."""
_all_jobs: Optional[Sequence[JobDefinition]]
_all_pipelines: Optional[Sequence[JobDefinition]]
def __init__(
self,
jobs: Mapping[str, Union[JobDefinitio... | CachingRepositoryData |
python | getsentry__sentry | tests/sentry/mail/activity/test_release.py | {
"start": 1028,
"end": 12338
} | class ____(ActivityTestCase):
def setUp(self) -> None:
super().setUp()
self.user5_alt_email = "privateEmail@gmail.com"
self.org = self.create_organization(owner=None)
self.org.flags.allow_joinleave = False
self.org.save()
self.team = self.create_team(organization=s... | ReleaseTestCase |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 26928,
"end": 33050
} | class ____(MaskedArraySetup):
@pytest.mark.parametrize("op", (operator.add, operator.sub))
def test_add_subtract(self, op):
mapmb = op(self.ma, self.mb)
expected_data = op(self.a, self.b)
expected_mask = self.ma.mask | self.mb.mask
# Note: assert_array_equal also checks type, i.e... | MaskedOperatorTests |
python | kamyu104__LeetCode-Solutions | Python/subtree-removal-game-with-fibonacci-tree.py | {
"start": 29,
"end": 1072
} | class ____(object):
def findGameWinner(self, n):
"""
:type n: int
:rtype: bool
"""
# a pattern appears every 6 grundy numbers in binary forms:
# 0000, (0000)01, (0000)11, ((0000)^(0000+1))10, (0000)11, (0000)11
# 0000, ... | Solution |
python | ray-project__ray | release/nightly_tests/stress_tests/test_threaded_actors.py | {
"start": 445,
"end": 5216
} | class ____:
def __init__(self, metadata):
# -- Read only variables --
self.metadata = metadata
self.sample_batch = 1000000
# -- Variables that are accessed by mulitple threads --
self.lock = threading.Lock()
self.result_queue = Queue()
self.is_running = False
... | PiCalculator |
python | walkccc__LeetCode | solutions/1235. Maximum Profit in Job Scheduling/1235-3.py | {
"start": 0,
"end": 647
} | class ____:
def jobScheduling(
self,
startTime: list[int],
endTime: list[int],
profit: list[int],
) -> int:
maxProfit = 0
jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)])
minHeap = [] # (endTime, profit)
# Will use binary search to find the first av... | Solution |
python | getsentry__sentry | tests/acceptance/test_trace_view_waterfall.py | {
"start": 401,
"end": 3542
} | class ____(AcceptanceTestCase, TraceTestCase, SnubaTestCase):
viewname = "sentry-api-0-organization-trace"
FEATURES = [
"organizations:visibility-explore-view",
"organizations:performance-view",
"organizations:trace-spans-format",
]
def setUp(self) -> None:
super().setUp... | TraceViewWaterfallTest |
python | pytorch__pytorch | torch/fx/experimental/unification/variable.py | {
"start": 223,
"end": 2057
} | class ____:
"""Logic Variable"""
_id = 1
def __new__(cls, *token):
if len(token) == 0:
token = f"_{Var._id}" # type: ignore[assignment]
Var._id += 1
elif len(token) == 1:
token = token[0]
obj = object.__new__(cls)
obj.token = token # t... | Var |
python | ray-project__ray | rllib/algorithms/cql/cql.py | {
"start": 10152,
"end": 14430
} | class ____(SAC):
"""CQL (derived from SAC)."""
@classmethod
@override(SAC)
def get_default_config(cls) -> CQLConfig:
return CQLConfig()
@classmethod
@override(SAC)
def get_default_policy_class(
cls, config: AlgorithmConfig
) -> Optional[Type[Policy]]:
if config[... | CQL |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 7261,
"end": 7398
} | class ____(BaseClass):
def method(self, arg, param1=42, *, param2=42):
print(arg, param1, param2)
| DerivedClassWithoutAnnotation |
python | getsentry__sentry | src/sentry/api/endpoints/api_token_details.py | {
"start": 998,
"end": 3370
} | class ____(Endpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
"DELETE": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.SECURITY
permission_classes = (SentryIsAuthenticated,)
@method_decorator(never_cache)
def get(self, request: ... | ApiTokenDetailsEndpoint |
python | realpython__materials | document-python-code-with-chatgpt/circle.py | {
"start": 81,
"end": 268
} | class ____:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return round(math.pi * self.radius ** 2, 2)
"""
import math
# Output:
| Circle |
python | kamyu104__LeetCode-Solutions | Python/fair-distribution-of-cookies.py | {
"start": 63,
"end": 808
} | class ____(object):
def distributeCookies(self, cookies, k):
"""
:type cookies: List[int]
:type k: int
:rtype: int
"""
total = [0]*(1<<len(cookies))
for mask in xrange(1<<len(cookies)):
total[mask] = sum(cookies[i] for i in xrange(len(cookies)) if ... | Solution |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 115727,
"end": 123886
} | class ____(fixtures.TestBase):
"""test issues related to #8880, #8878, #8876"""
def test_straight_decl_usage(self, decl_base):
"""test use of assoc prox as the default descriptor for a
dataclasses.field.
"""
class User(decl_base):
__allow_unmapped__ = True
... | DeclOrmForms |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py | {
"start": 2599,
"end": 3152
} | class ____(BaseGoogleLink):
"""Helper class for constructing Dataproc Metastore resource link."""
name = "Dataproc Metastore"
key = "conf"
def get_link(
self,
operator: BaseOperator,
*,
ti_key: TaskInstanceKey,
) -> str:
conf = self.get_config(operator, ti_k... | DataprocMetastoreLink |
python | plotly__plotly.py | plotly/graph_objs/waterfall/_increasing.py | {
"start": 233,
"end": 2458
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall"
_path_str = "waterfall.increasing"
_valid_props = {"marker"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly... | Increasing |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 131777,
"end": 141481
} | class ____(stages.Executable):
__slots__ = [
"xla_executable", "_unsafe_call", "build_unsafe_call", "in_avals",
"out_avals", "_in_shardings", "_out_shardings", "_auto_spmd_lowering",
"_kept_var_idx", "_xla_in_layouts", "_dispatch_in_layouts",
"_xla_out_layouts", "_mut", "_all_args_info", "_unl... | MeshExecutable |
python | spack__spack | lib/spack/spack/test/util/package_hash.py | {
"start": 7446,
"end": 9074
} | class ____:
for variant in ["+foo", "+bar", "+baz"]:
conflicts("quux" + variant)
for variant in ["+foo", "+bar", "+baz"]:
# logic in the loop prevents our dumb analyzer from having it removed. This
# is uncommon so we don't (yet?) implement logic to detect that spec is unused.
p... | ComplexPackageLogic |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 63945,
"end": 64642
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(self, name: str, destination_path: str):
"""Airbyte Destination for Csv.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/csv
Args:
name (str): The name of the destination.
... | CsvDestination |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_no_member_7631.py | {
"start": 250,
"end": 343
} | class ____(Parent):
attr = 2
def __init__(self):
self.attr = self.attr | 4
| Child |
python | lazyprogrammer__machine_learning_examples | unsupervised_class2/vanishing.py | {
"start": 960,
"end": 3936
} | class ____(object):
def __init__(self, hidden_layer_sizes):
self.hidden_layer_sizes = hidden_layer_sizes
def fit(self, X, Y, learning_rate=0.01, mu=0.99, epochs=30, batch_sz=100):
# cast to float32
learning_rate = np.float32(learning_rate)
mu = np.float32(mu)
N, D = X.s... | ANN |
python | walkccc__LeetCode | solutions/2053. Kth Distinct String in an Array/2053.py | {
"start": 0,
"end": 220
} | class ____:
def kthDistinct(self, arr: list[str], k: int) -> str:
count = collections.Counter(arr)
for a in arr:
if count[a] == 1:
k -= 1
if k == 0:
return a
return ''
| Solution |
python | django__django | tests/cache/tests.py | {
"start": 46129,
"end": 50657
} | class ____(BaseCacheTests, TransactionTestCase):
available_apps = ["cache"]
def setUp(self):
# The super calls needs to happen first for the settings override.
super().setUp()
self.create_table()
self.addCleanup(self.drop_table)
def create_table(self):
management.ca... | DBCacheTests |
python | charliermarsh__ruff | scripts/ty_benchmark/src/benchmark/__init__.py | {
"start": 476,
"end": 2331
} | class ____(NamedTuple):
name: str
"""The benchmark to run."""
commands: list[Command]
"""The commands to benchmark."""
warmup: int
"""The number of warmup runs to perform."""
min_runs: int
"""The minimum number of runs to perform."""
verbose: bool
"""Whether to print verbose ... | Hyperfine |
python | getsentry__sentry | tests/snuba/metrics/test_units.py | {
"start": 165,
"end": 1826
} | class ____(TestCase):
def test_format_value_using_unit(self) -> None:
assert format_value_using_unit(543200, "nanosecond") == "0.54 ms"
assert format_value_using_unit(54320, "microsecond") == "54.32 ms"
assert format_value_using_unit(123456, "millisecond") == "2.06 m"
assert format_v... | TestUnitsUtils |
python | ethereum__web3.py | web3/_utils/encoding.py | {
"start": 8739,
"end": 9563
} | class ____(json.JSONEncoder):
def default(self, obj: Any) -> dict[Any, Any] | HexStr:
if isinstance(obj, AttributeDict):
return obj.__dict__
elif isinstance(obj, (HexBytes, bytes)):
return to_hex(obj)
elif isinstance(obj, BaseModel):
# TODO: For now we can... | Web3JsonEncoder |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 5782,
"end": 6068
} | class ____:
params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]]
param_names = ["N", "dtype"]
def setup(self, N, dtype):
self.s = Series(np.random.randint(0, N, size=10 * N)).astype(dtype)
def time_mode(self, N, dtype):
self.s.mode()
| Mode |
python | pytorch__pytorch | test/inductor/test_smoke.py | {
"start": 637,
"end": 1836
} | class ____(TestCase):
@unittest.skipIf(not HAS_GPU, "Triton is not available")
def test_mlp(self):
torch._logging.set_logs(
dynamo=logging.DEBUG, inductor=logging.DEBUG, aot=logging.DEBUG
)
mlp = torch.compile(MLP().to(GPU_TYPE))
for _ in range(3):
mlp(to... | SmokeTest |
python | sympy__sympy | sympy/physics/quantum/hilbert.py | {
"start": 970,
"end": 2856
} | class ____(Basic):
"""An abstract Hilbert space for quantum mechanics.
In short, a Hilbert space is an abstract vector space that is complete
with inner products defined [1]_.
Examples
========
>>> from sympy.physics.quantum.hilbert import HilbertSpace
>>> hs = HilbertSpace()
>>> hs
... | HilbertSpace |
python | django__django | django/db/migrations/serializer.py | {
"start": 7733,
"end": 8286
} | class ____(BaseSerializer):
def serialize(self):
imports = set()
strings = []
for item in self.value:
item_string, item_imports = serializer_factory(item).serialize()
imports.update(item_imports)
strings.append(item_string)
# When len(strings)==0, ... | IterableSerializer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/objects.py | {
"start": 2203,
"end": 2591
} | class ____(Enum):
# An error that occurs while executing framework code
FRAMEWORK_ERROR = "FRAMEWORK_ERROR"
# An error that occurs while executing user code
USER_CODE_ERROR = "USER_CODE_ERROR"
# An error occurred at an unexpected time
UNEXPECTED_ERROR = "UNEXPECTED_ERROR"
# Execution was int... | ErrorSource |
python | ray-project__ray | python/ray/util/multiprocessing/pool.py | {
"start": 5276,
"end": 12770
} | class ____(threading.Thread):
"""Thread that collects results from distributed actors.
It winds down when either:
- A pre-specified number of objects has been processed
- When the END_SENTINEL (submitted through self.add_object_ref())
has been received and all objects received befor... | ResultThread |
python | numba__numba | numba/core/byteflow.py | {
"start": 12158,
"end": 69087
} | class ____(object):
"""Trace runner contains the states for the trace and the opcode dispatch.
"""
def __init__(self, debug_filename):
self.debug_filename = debug_filename
self.pending = deque()
self.finished = set()
def get_debug_loc(self, lineno):
return Loc(self.debug... | TraceRunner |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-chroma/unit_tests/test_destination.py | {
"start": 319,
"end": 3665
} | class ____(unittest.TestCase):
def setUp(self):
self.config = {
"processing": {"text_fields": ["str_col"], "metadata_fields": [], "chunk_size": 1000},
"embedding": {"mode": "openai", "openai_key": "mykey"},
"indexing": {
"auth_method": {"mode": "persistent... | TestDestinationChroma |
python | fluentpython__example-code | 05-1class-func/bingocall.py | {
"start": 168,
"end": 544
} | class ____:
def __init__(self, items):
self._items = list(items) # <1>
random.shuffle(self._items) # <2>
def pick(self): # <3>
try:
return self._items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage') # <4>
def __call__(sel... | BingoCage |
python | ray-project__ray | python/ray/serve/tests/unit/test_schema.py | {
"start": 13770,
"end": 22714
} | class ____:
def get_valid_serve_application_schema(self):
return {
"import_path": "module.graph",
"runtime_env": {},
"deployments": [
{
"name": "shallow",
"num_replicas": 2,
"route_prefix": "/shal... | TestServeApplicationSchema |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/gcs.py | {
"start": 12260,
"end": 18984
} | class ____(GCSPrefixBlobTrigger):
"""
Return Trigger Event if the inactivity period has passed with no increase in the number of objects.
:param bucket: The Google Cloud Storage bucket where the objects are expected.
:param prefix: The name of the prefix to check in the Google cloud storage bucket.
... | GCSUploadSessionTrigger |
python | huggingface__transformers | tests/models/visual_bert/test_modeling_visual_bert.py | {
"start": 11500,
"end": 23578
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
VisualBertModel,
VisualBertForMultipleChoice,
VisualBertForVisualReasoning,
VisualBertForRegionToPhraseAlignment,
VisualBertForQuestionAnswering,
... | VisualBertModelTest |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 1244,
"end": 1408
} | class ____(factory.django.DjangoModelFactory):
class Meta:
model = models.StandardModel
foo = factory.Sequence(lambda n: "foo%d" % n)
| StandardFactory |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/via_attribute_name.py | {
"start": 262,
"end": 839
} | class ____:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def test_tito_attribute_x():
c = TitoAttributes(**_test_source())
_test_sink(c.x)
def test_tito_attribute_y():
c = TitoAttributes(**_test_source())
_test_sink(c.y)
def test_tito_attribute_z_with_t... | TitoAttributes |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py312.py | {
"start": 378,
"end": 440
} | class ____[T](Parent[T, S]): # [undefined-variable]
...
| Child |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 26292,
"end": 26407
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Neon'
strategy_class = FileStrategy
| NeonHostname |
python | pypa__pipenv | pipenv/vendor/tomlkit/items.py | {
"start": 27284,
"end": 28162
} | class ____:
__slots__ = ("value", "indent", "comma", "comment")
def __init__(
self,
value: Item | None = None,
indent: Whitespace | None = None,
comma: Whitespace | None = None,
comment: Comment | None = None,
) -> None:
self.value = value
self.indent... | _ArrayItemGroup |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 7804,
"end": 12603
} | class ____(greentest.TestCase):
def test_minimal_id(self):
g = gevent.spawn(lambda: 1)
self.assertGreaterEqual(g.minimal_ident, 0)
self.assertGreaterEqual(g.parent.minimal_ident, 0)
g.join() # don't leave dangling, breaks the leak checks
def test_wait_noerrors(self):
x ... | TestStuff |
python | plotly__plotly.py | plotly/missing_anywidget.py | {
"start": 40,
"end": 512
} | class ____(BaseFigure):
"""
FigureWidget stand-in for use when anywidget is not installed. The only purpose
of this class is to provide something to import as
`plotly.graph_objs.FigureWidget` when anywidget is not installed. This class
simply raises an informative error message when the constructor ... | FigureWidget |
python | pydata__xarray | xarray/tests/test_conventions.py | {
"start": 4135,
"end": 10732
} | class ____:
def test_incompatible_attributes(self) -> None:
invalid_vars = [
Variable(
["t"], pd.date_range("2000-01-01", periods=3), {"units": "foobar"}
),
Variable(["t"], pd.to_timedelta(["1 day"]), {"units": "foobar"}), # type: ignore[arg-type, unused-... | TestEncodeCFVariable |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/plugins/databricks_workflow.py | {
"start": 18980,
"end": 20020
} | class ____(AirflowPlugin):
"""
Databricks Workflows plugin for Airflow.
.. seealso::
For more information on how to use this plugin, take a look at the guide:
:ref:`howto/plugin:DatabricksWorkflowPlugin`
"""
name = "databricks_workflow"
# Conditionally set operator_extra_links... | DatabricksWorkflowPlugin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chartsheet01.py | {
"start": 315,
"end": 1429
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chartsheet01.xlsx")
def test_create_file(self):
"""Test the worksheet properties of an XlsxWriter chartsheet file."""
workbook = W... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/options/store.py | {
"start": 1699,
"end": 12698
} | class ____:
"""
Abstraction for the Option storage logic that should be driven
by the OptionsManager.
OptionsStore is gooey and raw. It provides no protection over
what goes into the store. It only knows that it's reading/writing
to the right place. If using the OptionsStore directly, it's your... | OptionsStore |
python | pymupdf__PyMuPDF | pipcl.py | {
"start": 1312,
"end": 93264
} | class ____:
'''
Our constructor takes a definition of a Python package similar to that
passed to `distutils.core.setup()` or `setuptools.setup()` (name, version,
summary etc) plus callbacks for building, getting a list of sdist
filenames, and cleaning.
We provide methods that can be used to imp... | Package |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 3309,
"end": 3427
} | class ____(TypedDict):
sessions_lower_bound: FormattedIsoTime
sessions_upper_bound: FormattedIsoTime
| _TimeBounds |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/callbacks/test_stdout.py | {
"start": 254,
"end": 1336
} | class ____(Chain):
"""Fake chain class for testing purposes."""
be_correct: bool = True
the_input_keys: list[str] = ["foo"]
the_output_keys: list[str] = ["bar"]
@property
def input_keys(self) -> list[str]:
"""Input keys."""
return self.the_input_keys
@property
def outp... | FakeChain |
python | ray-project__ray | python/ray/data/_internal/execution/operators/zip_operator.py | {
"start": 784,
"end": 12753
} | class ____(InternalQueueOperatorMixin, NAryOperator):
"""An operator that zips its inputs together.
NOTE: the implementation is bulk for now, which materializes all its inputs in
object store, before starting execution. Should re-implement it as a streaming
operator in the future.
"""
def __in... | ZipOperator |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 102128,
"end": 102357
} | class ____:
xlAbsRowRelColumn = 2 # from enum XlReferenceType
xlAbsolute = 1 # from enum XlReferenceType
xlRelRowAbsColumn = 3 # from enum XlReferenceType
xlRelative = 4 # from enum XlReferenceType
| ReferenceType |
python | huggingface__transformers | src/transformers/models/audioflamingo3/processing_audioflamingo3.py | {
"start": 1643,
"end": 13037
} | class ____(ProcessorMixin):
r"""
Constructs an AudioFlamingo3 processor which wraps an AudioFlamingo3 feature extractor and an AudioFlamingo3
tokenizer into a single processor.
[`AudioFlamingo3Processor`] offers all the functionalities of [`WhisperFeatureExtractor`] and
[`Qwen2TokenizerFast`]. See ... | AudioFlamingo3Processor |
python | pypa__warehouse | tests/common/db/organizations.py | {
"start": 6231,
"end": 6755
} | class ____(WarehouseFactory):
class Meta:
model = OrganizationOIDCIssuer
organization_id = factory.SelfAttribute("organization.id")
organization = factory.SubFactory(OrganizationFactory)
issuer_type = factory.LazyFunction(
lambda: fake.random_element(elements=[e.value for e in OIDCIssue... | OrganizationOIDCIssuerFactory |
python | rushter__MLAlgorithms | mla/neuralnet/optimizers.py | {
"start": 1967,
"end": 3163
} | class ____(Optimizer):
def __init__(self, learning_rate=0.01, momentum=0.9, decay=0.0, nesterov=False):
self.nesterov = nesterov
self.decay = decay
self.momentum = momentum
self.lr = learning_rate
self.iteration = 0
self.velocity = None
def update(self, network):... | SGD |
python | coleifer__peewee | playhouse/psycopg3_ext.py | {
"start": 1186,
"end": 1623
} | class ____(_Psycopg3JsonLookupBase):
def __getitem__(self, value):
return JsonLookup(self.node, self.parts + [value], self._as_json)
def __sql__(self, ctx):
ctx.sql(self.node)
for part in self.parts[:-1]:
ctx.literal('->').sql(part)
if self.parts:
(ctx
... | JsonLookup |
python | kamyu104__LeetCode-Solutions | Python/plus-one-linked-list.py | {
"start": 832,
"end": 1524
} | class ____(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def reverseList(head):
dummy = ListNode(0)
curr = head
while curr:
dummy.next, curr.next, curr = curr, dummy.next, curr.next
... | Solution2 |
python | hynek__structlog | src/structlog/testing.py | {
"start": 854,
"end": 2973
} | class ____:
"""
Class for capturing log messages in its entries list.
Generally you should use `structlog.testing.capture_logs`,
but you can use this class if you want to capture logs with other patterns.
:ivar List[structlog.typing.EventDict] entries: The captured log entries.
.. versionadded... | LogCapture |
python | huggingface__transformers | src/transformers/models/clipseg/modeling_clipseg.py | {
"start": 49880,
"end": 57913
} | class ____(CLIPSegPreTrainedModel):
config: CLIPSegConfig
def __init__(self, config: CLIPSegConfig):
super().__init__(config)
self.config = config
self.clip = CLIPSegModel(config)
self.extract_layers = config.extract_layers
self.decoder = CLIPSegDecoder(config)
... | CLIPSegForImageSegmentation |
python | walkccc__LeetCode | solutions/3439. Reschedule Meetings for Maximum Free Time I/3439.py | {
"start": 0,
"end": 482
} | class ____:
def maxFreeTime(
self,
eventTime: int,
k: int,
startTime: list[int],
endTime: list[int]
) -> int:
gaps = ([startTime[0]] +
[startTime[i] - endTime[i - 1] for i in range(1, len(startTime))] +
[eventTime - endTime[-1]])
windowSum = sum(gaps[:k ... | Solution |
python | Textualize__textual | docs/examples/app/event01.py | {
"start": 57,
"end": 574
} | class ____(App):
COLORS = [
"white",
"maroon",
"red",
"purple",
"fuchsia",
"olive",
"yellow",
"navy",
"teal",
"aqua",
]
def on_mount(self) -> None:
self.screen.styles.background = "darkblue"
def on_key(self, event... | EventApp |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 18233,
"end": 18372
} | class ____(IRule):
def eval(self) -> Expr:
a, b, x = self.a, self.b, self.variable
return li(a*x + b)/a
@dataclass
| LiRule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 590670,
"end": 591125
} | class ____(sgqlc.types.Type):
"""A User who is a member of an enterprise through one or more
organizations.
"""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."... | EnterpriseMemberEdge |
python | run-llama__llama_index | llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/answer_consistency.py | {
"start": 358,
"end": 1985
} | class ____(BaseEvaluator):
"""
Tonic Validate's answer consistency metric.
The output score is a float between 0.0 and 1.0.
See https://docs.tonic.ai/validate/ for more details.
Args:
openai_service(OpenAIService): The OpenAI service to use. Specifies the chat
completion model... | AnswerConsistencyEvaluator |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/base.py | {
"start": 732,
"end": 2113
} | class ____(ABC, Generic[T]):
"""Abstract base class for parsing the outputs of a model."""
@abstractmethod
def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
"""Parse a list of candidate model `Generation` objects into a specific format.
Args:
resu... | BaseLLMOutputParser |
python | scikit-learn__scikit-learn | sklearn/utils/_metadata_requests.py | {
"start": 11617,
"end": 19381
} | class ____:
"""Container for metadata requests associated with a single method.
Instances of this class get used within a :class:`MetadataRequest` - one per each
public method (`fit`, `transform`, ...) that its owning consumer has.
.. versionadded:: 1.3
Parameters
----------
owner : objec... | MethodMetadataRequest |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 9895,
"end": 10081
} | class ____(Node):
"""Node that represents a template. This must be the outermost node that
is passed to the compiler.
"""
fields = ("body",)
body: list[Node]
| Template |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_dynamic_getitiem.py | {
"start": 60,
"end": 296
} | class ____:
def __getitem__(self, key):
if key == 'attributes':
return []
return {'world': 123}
ex = DynamicGetitem()
a = ex['hello']['world'] # [invalid-sequence-index] known false-positive
| DynamicGetitem |
python | pypa__twine | twine/auth.py | {
"start": 2688,
"end": 10847
} | class ____:
_tp_token: t.Optional[TrustedPublishingToken] = None
_expires: t.Optional[int] = None
def __init__(
self,
config: utils.RepositoryConfig,
input: CredentialInput,
) -> None:
self.config = config
self.input = input
@property
@functools.lru_cach... | Resolver |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/prompt.py | {
"start": 10414,
"end": 12462
} | class ____(PromptBase[bool]):
"""A yes / no confirmation prompt.
Example:
>>> if Confirm.ask("Continue"):
run_job()
"""
response_type = bool
validate_error_message = "[prompt.invalid]Please enter Y or N"
choices: List[str] = ["y", "n"]
def render_default(self, def... | Confirm |
python | pytorch__pytorch | test/test_fx.py | {
"start": 151116,
"end": 152810
} | class ____(JitTestCase):
def setUp(self):
# Checking for mutable operations while tracing is feature flagged
# Enable it in testing but not by default
self.orig_tracer_mutable_flag = (
torch.fx.proxy.TracerBase.check_mutable_operations
)
torch.fx.proxy.TracerBase.... | TestOperatorSignatures |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/models/ci_requirements.py | {
"start": 148,
"end": 700
} | class ____:
"""
A dataclass to store the CI requirements.
It used to make airbyte-ci client define the CI runners it will run on.
"""
dagger_version = metadata.version("dagger-io")
@property
def dagger_engine_image(self) -> str:
return f"registry.dagger.io/engine:v{self.dagger_vers... | CIRequirements |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/mapped_covariant.py | {
"start": 1294,
"end": 1467
} | class ____(Base):
__tablename__ = "parent"
name: Mapped[str] = mapped_column(primary_key=True)
children: Mapped[Sequence["Child"]] = relationship("Child")
| Parent |
python | doocs__leetcode | solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/Solution.py | {
"start": 0,
"end": 601
} | class ____:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
n = len(dist)
f = [[inf] * (n + 1) for _ in range(n + 1)]
f[0][0] = 0
eps = 1e-8
for i, x in enumerate(dist, 1):
for j in range(i + 1):
if j < i:
... | Solution |
python | ray-project__ray | python/ray/tune/tests/test_tuner_restore.py | {
"start": 5348,
"end": 37746
} | class ____:
def __init__(self):
import numpy as np
self.data = np.random.rand((2 * 1024 * 1024))
def test_tuner_restore_num_trials(ray_start_2_cpus, tmpdir):
"""Number of trials after restoring a finished run should be the same"""
tuner = Tuner(
_dummy_train_fn,
tune_confi... | MockData |
python | doocs__leetcode | lcof/面试题67. 把字符串转换成整数/Solution.py | {
"start": 0,
"end": 764
} | class ____:
def strToInt(self, str: str) -> int:
if not str:
return 0
n = len(str)
if n == 0:
return 0
i = 0
while str[i] == ' ':
i += 1
# 仅包含空格
if i == n:
return 0
sign = -1 if str[i] == '-' ... | Solution |
python | doocs__leetcode | solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/Solution.py | {
"start": 0,
"end": 702
} | class ____:
def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:
def dfs(a: int, fa: int) -> List[int]:
res = [cost[a]]
for b in g[a]:
if b != fa:
res.extend(dfs(b, a))
res.sort()
if len(res) >= 3:
... | Solution |
python | huggingface__transformers | src/transformers/models/vaultgemma/modeling_vaultgemma.py | {
"start": 10815,
"end": 12622
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: VaultGemmaConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.config = config
self.attention_type = config.layer_types[layer_idx]
self.self_attn = VaultGemmaAttention(config=... | VaultGemmaDecoderLayer |
python | getsentry__sentry | src/sentry/issues/highlights.py | {
"start": 381,
"end": 1131
} | class ____(serializers.Field):
def to_internal_value(self, data: object) -> dict[str, list[str]]:
if not isinstance(data, dict):
raise serializers.ValidationError("Expected a dictionary.")
for key, value in data.items():
if not VALID_KEY_PATTERN.match(key):
ra... | HighlightContextField |
python | bokeh__bokeh | tests/support/plugins/file_server.py | {
"start": 1707,
"end": 2436
} | class ____(BaseHTTPRequestHandler):
"""Http handler."""
def do_GET(self) -> None:
"""GET method handler."""
# depending on Python version, leading / may be present or not
path = self.path.split("?")[0].removeprefix("/")
try:
with open(HTML_ROOT / path, mode="rb") as f... | HtmlOnlyHandler |
python | django__django | tests/db_functions/text/test_trim.py | {
"start": 207,
"end": 1416
} | class ____(TestCase):
def test_trim(self):
Author.objects.create(name=" John ", alias="j")
Author.objects.create(name="Rhonda", alias="r")
authors = Author.objects.annotate(
ltrim=LTrim("name"),
rtrim=RTrim("name"),
trim=Trim("name"),
)
se... | TrimTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/reduce_util.py | {
"start": 882,
"end": 1673
} | class ____(enum.Enum):
"""Indicates how a set of values should be reduced.
* `SUM`: Add all the values.
* `MEAN`: Take the arithmetic mean ("average") of the values.
"""
# TODO(priyag): Add the following types:
# `MIN`: Return the minimum of all values.
# `MAX`: Return the maximum of all values.
SUM = ... | ReduceOp |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/custom_io_manager.py | {
"start": 897,
"end": 1291
} | class ____(dg.IOManager):
def __init__(self, api_token):
self._api_token = api_token
# setup stateful cache
self._cache = {}
def handle_output(self, context: dg.OutputContext, obj): ...
def load_input(self, context: dg.InputContext):
if context.asset_key in self._cache:
... | ExternalIOManager |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.