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 | pytorch__pytorch | torch/_functorch/partitioners.py | {
"start": 3019,
"end": 4081
} | class ____:
# Be careful about iterating over these explicitly, as their order may not
# be deterministic
inputs: list[fx.Node]
_required_fw_nodes: OrderedSet[fx.Node]
required_bw_nodes: OrderedSet[fx.Node]
unclaimed_nodes: OrderedSet[fx.Node]
fw_order: dict[fx.Node, int]
# Effectively m... | NodeInfo |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_test.py | {
"start": 2610,
"end": 2772
} | class ____(extension_type.ExtensionType):
"""Example subclass of ExtensionType, used for testing."""
values: tensor.Tensor
mask: tensor.Tensor
| MaskedTensorV1 |
python | kamyu104__LeetCode-Solutions | Python/maximum-points-tourist-can-earn.py | {
"start": 40,
"end": 472
} | class ____(object):
def maxScore(self, n, k, stayScore, travelScore):
"""
:type n: int
:type k: int
:type stayScore: List[List[int]]
:type travelScore: List[List[int]]
:rtype: int
"""
dp = [0]*n
for i in xrange(k):
dp = [max(dp[u]+s... | Solution |
python | PrefectHQ__prefect | tests/server/utilities/test_database.py | {
"start": 880,
"end": 1060
} | class ____(pydantic.BaseModel):
x: int
y: datetime.datetime = pydantic.Field(
default_factory=lambda: datetime.datetime.now(datetime.timezone.utc)
)
| PydanticModel |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 58432,
"end": 58625
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin = nn.Linear(10, 10, bias=False)
def forward(self, x):
return self.lin(x)
| SkipModule |
python | nedbat__coveragepy | tests/test_collector.py | {
"start": 380,
"end": 1698
} | class ____(CoverageTest):
"""Test specific aspects of the collection process."""
def test_should_trace_cache(self) -> None:
# The tracers should only invoke should_trace once for each file name.
# Make some files that invoke each other.
self.make_file(
"f1.py",
... | CollectorTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/contrib/regular_languages/validation.py | {
"start": 270,
"end": 2059
} | class ____(Validator):
"""
Validator which can be used for validation according to variables in
the grammar. Each variable can have its own validator.
:param compiled_grammar: `GrammarCompleter` instance.
:param validators: `dict` mapping variable names of the grammar to the
... | GrammarValidator |
python | tensorflow__tensorflow | tensorflow/python/client/session.py | {
"start": 66984,
"end": 71306
} | class ____(BaseSession):
"""A TensorFlow `Session` for use in interactive contexts, such as a shell.
The only difference with a regular `Session` is that an `InteractiveSession`
installs itself as the default session on construction.
The methods `tf.Tensor.eval`
and `tf.Operation.run`
will use that session... | InteractiveSession |
python | getsentry__sentry | src/sentry/audit_log/manager.py | {
"start": 234,
"end": 1304
} | class ____(Exception):
pass
"""
The audit log system records changes made to an organization and displays them in
organization settings.
To add a new audit log event:
1. Create a new instance of AuditLogEvent. You'll need an event_id, name, api_name,
and optional template.
Note: The template uses AuditLo... | AuditLogEventNotRegistered |
python | allegroai__clearml | clearml/utilities/pyhocon/exceptions.py | {
"start": 231,
"end": 294
} | class ____(ConfigException):
pass
| ConfigSubstitutionException |
python | django__django | tests/auth_tests/models/is_active.py | {
"start": 104,
"end": 432
} | class ____(AbstractBaseUser):
"""
This test user class and derivatives test the default is_active behavior
"""
username = models.CharField(max_length=30, unique=True)
custom_objects = BaseUserManager()
USERNAME_FIELD = "username"
# the is_active attr is provided by AbstractBaseUser
| IsActiveTestUser1 |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 37242,
"end": 37661
} | class ____(ProjectAdminMixin, PrivateViewMixin):
"""Environment variables to be added when building the Project."""
model = EnvironmentVariable
form_class = EnvironmentVariableForm
lookup_url_kwarg = "environmentvariable_pk"
def get_success_url(self):
return reverse(
"projects_... | EnvironmentVariableMixin |
python | facebookresearch__faiss | tests/test_standalone_codec.py | {
"start": 2116,
"end": 3497
} | class ____(unittest.TestCase):
def do_test(self, key1, key2):
d = 96
nb = 1000
nq = 0
nt = 2000
xt, x, _ = get_dataset_2(d, nt, nb, nq)
codec_ref = faiss.index_factory(d, key1)
codec_ref.train(xt)
code_ref = codec_ref.sa_encode(x)
x_recons_... | TestIndexEquiv |
python | protocolbuffers__protobuf | python/google/protobuf/json_format.py | {
"start": 1931,
"end": 5360
} | class ____(ParseError):
"""Thrown if unknown string enum value is encountered.
This exception is suppressed if ignore_unknown_fields is set.
"""
def MessageToJson(
message,
preserving_proto_field_name=False,
indent=2,
sort_keys=False,
use_integers_for_enums=False,
descriptor_pool=None,
... | EnumStringValueParseError |
python | keras-team__keras | keras/src/callbacks/monitor_callback_test.py | {
"start": 212,
"end": 2875
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_monitor_op_logic(self):
x_train = np.random.random((10, 5))
y_train = np.random.random((10, 1))
x_test = np.random.random((10, 5))
y_test = np.random.random((10, 1))
model = models.Sequential(
... | MonitorCallbackTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB189.py | {
"start": 476,
"end": 543
} | class ____(list[str]):
pass
# currently not detected
| SubscriptList |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 6508,
"end": 7297
} | class ____(BaseConverter):
"""This converter only accepts UUID strings::
Rule('/object/<uuid:identifier>')
.. versionadded:: 0.10
:param map: the :class:`Map`.
"""
regex = (
r"[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-"
r"[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}"
)
def ... | UUIDConverter |
python | huggingface__transformers | src/transformers/models/esm/modeling_esm.py | {
"start": 22652,
"end": 29367
} | class ____(EsmPreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
all you need](https://huggingface.co/papers/... | EsmModel |
python | fluentpython__example-code-2e | 05-data-classes/cards.py | {
"start": 58,
"end": 208
} | class ____:
rank: str
suit: str
ranks = [str(n) for n in range(2, 10)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
| Card |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 5021,
"end": 5626
} | class ____:
"""Subclass of unittest.TestCase with thread-safe cleanup methods.
This subclass protects the addCleanup() and doCleanups() methods
with a recursive lock.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cleanup_lock = threading.RLock()
... | ThreadSafeCleanupTestCase |
python | python__mypy | mypy/server/astmerge.py | {
"start": 15438,
"end": 20982
} | class ____(SyntheticTypeVisitor[None]):
"""Similar to NodeReplaceVisitor, but for type objects.
Note: this visitor may sometimes visit unanalyzed types
such as 'UnboundType' and 'RawExpressionType' For example, see
NodeReplaceVisitor.process_base_func.
"""
def __init__(self, replacements: dict... | TypeReplaceVisitor |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 22585,
"end": 23920
} | class ____(LayoutNode):
"""Span a form field over several columns.
Example::
layout = Layout(
Row(Span('first_name'), Span('last_name'))
Row(
Span('email', tablet=6, mobile=3),
'sex'
)
)
By default span is auto-sized. On a... | Span |
python | huggingface__transformers | tests/models/pop2piano/test_tokenization_pop2piano.py | {
"start": 1310,
"end": 17241
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano")
def get_input_notes(self):
notes = [
[
pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77),
... | Pop2PianoTokenizerTest |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 4601,
"end": 8451
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, query_mask, key_mask, query, key, value, config):
if query_mask.size(0) != key_mask.size(0):
raise ValueError("Query mask and Key mask differ in sizes in dimension 0")
if query_mask.size(0) != query.size(0):
... | YosoLSHCumulation |
python | squidfunk__mkdocs-material | material/plugins/blog/structure/options.py | {
"start": 4366,
"end": 4870
} | class ____(BaseConfigOption[Navigation]):
# Create navigation from structured items - we don't need to provide a
# configuration object to the function, because it will not be used
def run_validation(self, value: object):
items = _data_to_navigation(value, Files([]), None)
_add_parent_links... | PostLinks |
python | python__mypy | mypy/nodes.py | {
"start": 148652,
"end": 157767
} | class ____:
"""Description of a name binding in a symbol table.
These are only used as values in module (global), function (local)
and class symbol tables (see SymbolTable). The name that is bound is
the key in SymbolTable.
Symbol tables don't contain direct references to AST nodes primarily
b... | SymbolTableNode |
python | huggingface__transformers | src/transformers/models/superglue/modeling_superglue.py | {
"start": 19587,
"end": 20137
} | class ____(PreTrainedModel):
config: SuperGlueConfig
base_model_prefix = "superglue"
main_input_name = "pixel_values"
input_modalities = ("image",)
@torch.no_grad()
def _init_weights(self, module: nn.Module) -> None:
"""Initialize the weights"""
super()._init_weights(module)
... | SuperGluePreTrainedModel |
python | tensorflow__tensorflow | tensorflow/python/keras/mixed_precision/test_util.py | {
"start": 5258,
"end": 7458
} | class ____(AssertTypeLayer):
"""A layer which multiplies its input by a scalar variable."""
def __init__(self,
regularizer=None,
activity_regularizer=None,
use_operator=False,
var_name='v',
**kwargs):
"""Initializes the MultiplyLayer.
... | MultiplyLayer |
python | patrick-kidger__equinox | equinox/_module/_module.py | {
"start": 2995,
"end": 3468
} | class ____(eqx.Module):
vmap_linear: Callable
def __init__(self, ...):
self.vmap_linear = jax.vmap(eqx.nn.Linear(...))
def __call__(self, ...):
... = self.vmap_linear(...)
```
This is because the callable returned from `jax.vmap` is *not* a PyTree. This means that
the parameters inside the... | MyModule |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink44.py | {
"start": 315,
"end": 910
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink44.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_cross_op_test.py | {
"start": 2869,
"end": 21206
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def test_simple(self):
"""Tests a simple scenario."""
op = sparse_ops.sparse_cross([
self._sparse_tensor([['batch1-FC1-F1'],
['batch2-FC1-F1', 'batch2-FC1-F2']]),
self._sparse_tensor([['batch1-FC2-F1'],
... | SparseCrossOpTest |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 22148,
"end": 22665
} | class ____(object):
"""*
jina gRPC service to trigger a restore at the Executor Runtime.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.restore = channel.unary_unary(
'/jina.JinaExecutorRestore/restore',
... | JinaExecutorRestoreStub |
python | matplotlib__matplotlib | lib/matplotlib/hatch.py | {
"start": 5825,
"end": 8206
} | class ____(Shapes):
size = 1.0 / 3.0
filled = True
def __init__(self, hatch, density):
self.num_rows = (hatch.count('*')) * density
path = Path.unit_regular_star(5)
self.shape_vertices = path.vertices
self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO,
... | Stars |
python | huggingface__transformers | tests/models/zamba2/test_modeling_zamba2.py | {
"start": 1562,
"end": 10474
} | class ____:
def __init__(
self,
parent,
batch_size=14,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=16,
mamba_d_state=2,
chunk_size=8,
mamba_dt_rank="auto",
num... | Zamba2ModelTester |
python | pytorch__pytorch | torch/cuda/__init__.py | {
"start": 18551,
"end": 19015
} | class ____(RuntimeError):
def __init__(self, code: int) -> None:
# pyrefly: ignore [missing-attribute]
msg = _cudart.cudaGetErrorString(_cudart.cudaError(code))
super().__init__(f"{msg} ({code})")
def check_error(res: int) -> None:
r"""Raise an error if the result of a CUDA runtime API... | CudaError |
python | encode__starlette | starlette/datastructures.py | {
"start": 418,
"end": 733
} | class ____(NamedTuple):
host: str
port: int
_KeyType = TypeVar("_KeyType")
# Mapping keys are invariant but their values are covariant since
# you can only read them
# that is, you can't do `Mapping[str, Animal]()["fido"] = Dog()`
_CovariantValueType = TypeVar("_CovariantValueType", covariant=True)
| Address |
python | ansible__ansible | lib/ansible/module_utils/six/__init__.py | {
"start": 19156,
"end": 19805
} | class ____(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
_urllib_robotparser_moved_attributes = [
MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
]
for attr in _urllib_robotparser_moved_attributes:
setattr(Module_six_moves_urllib_robotparser, at... | Module_six_moves_urllib_robotparser |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 15777,
"end": 16269
} | class ____(BaseSafeMigrationTest, ColExistsMixin):
app = "good_flow_delete_field_simple_app"
migrate_from = "0001"
migrate_to = "0003"
def test(self) -> None:
self._run_migration(self.app, "0001_initial")
assert self.col_exists("field")
self._run_migration(self.app, "0002_set_pe... | DeletionFieldGoodDeleteSimple |
python | Pylons__pyramid | docs/quick_tutorial/static_assets/tutorial/tests.py | {
"start": 675,
"end": 1265
} | class ____(unittest.TestCase):
def setUp(self):
from tutorial import main
app = main({})
from webtest import TestApp
self.testapp = TestApp(app)
def test_home(self):
res = self.testapp.get('/', status=200)
self.assertIn(b'<h1>Hi Home View', res.body)
def te... | TutorialFunctionalTests |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar03.py | {
"start": 315,
"end": 1972
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | pydantic__pydantic | pydantic/types.py | {
"start": 33703,
"end": 35268
} | class ____:
"""A field metadata class to indicate a [UUID](https://docs.python.org/3/library/uuid.html) version.
Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
Attributes:
uuid_version: The version of the UUID. Must... | UuidVersion |
python | getsentry__sentry | src/sentry/integrations/bitbucket/integration.py | {
"start": 6684,
"end": 9919
} | class ____(IntegrationProvider):
key = IntegrationProviderSlug.BITBUCKET.value
name = "Bitbucket"
metadata = metadata
scopes = scopes
integration_cls = BitbucketIntegration
features = frozenset(
[
IntegrationFeatures.ISSUE_BASIC,
IntegrationFeatures.COMMITS,
... | BitbucketIntegrationProvider |
python | pytorch__pytorch | torch/_export/db/examples/cond_branch_class_method.py | {
"start": 231,
"end": 1327
} | class ____(torch.nn.Module):
"""
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
- both branches must take the same args, which must also match the branch args passed to cond.
- both branches must return a single tensor
- returned tensor must have the ... | CondBranchClassMethod |
python | lazyprogrammer__machine_learning_examples | nlp_class2/bow_classifier.py | {
"start": 941,
"end": 2398
} | class ____:
def __init__(self):
# load in pre-trained word vectors
print('Loading word vectors...')
word2vec = {}
embedding = []
idx2word = []
with open('../large_files/glove.6B/glove.6B.50d.txt') as f:
# is just a space-separated text file in the format:
# word vec[0] vec[1] vec[2... | GloveVectorizer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 459108,
"end": 459841
} | class ____(sgqlc.types.Interface):
"""A subject that may be upvoted."""
__schema__ = github_schema
__field_names__ = ("upvote_count", "viewer_can_upvote", "viewer_has_upvoted")
upvote_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="upvoteCount")
"""Number of upvotes that this sub... | Votable |
python | huggingface__transformers | tests/models/llava_next/test_modeling_llava_next.py | {
"start": 12034,
"end": 23000
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
self.image = Image.open(requests... | LlavaNextForConditionalGenerationIntegrationTest |
python | protocolbuffers__protobuf | python/google/protobuf/message.py | {
"start": 565,
"end": 639
} | class ____(Exception):
"""Base error type for this module."""
pass
| Error |
python | doocs__leetcode | solution/1400-1499/1473.Paint House III/Solution.py | {
"start": 0,
"end": 1460
} | class ____:
def minCost(
self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int
) -> int:
f = [[[inf] * (target + 1) for _ in range(n + 1)] for _ in range(m)]
if houses[0] == 0:
for j, c in enumerate(cost[0], 1):
f[0][j][1] = c
els... | Solution |
python | keras-team__keras | keras/src/backend/numpy/core.py | {
"start": 12708,
"end": 13515
} | class ____:
"""Decorator for custom gradients.
Args:
fun: Forward pass function.
"""
def __init__(self, fun):
warnings.warn(
"`custom_gradient` for the numpy backend acts as a pass-through to "
"support the forward pass. No gradient computation or modification "... | custom_gradient |
python | openai__openai-python | src/openai/resources/beta/assistants.py | {
"start": 45007,
"end": 45662
} | class ____:
def __init__(self, assistants: Assistants) -> None:
self._assistants = assistants
self.create = _legacy_response.to_raw_response_wrapper(
assistants.create,
)
self.retrieve = _legacy_response.to_raw_response_wrapper(
assistants.retrieve,
)... | AssistantsWithRawResponse |
python | kamyu104__LeetCode-Solutions | Python/queries-on-a-permutation-with-key.py | {
"start": 406,
"end": 964
} | class ____(object):
def processQueries(self, queries, m):
"""
:type queries: List[int]
:type m: int
:rtype: List[int]
"""
bit = BIT(2*m+1)
lookup = {}
for i in xrange(1, m+1):
bit.add(m+i, 1)
lookup[i] = m+i
result, curr... | Solution |
python | scipy__scipy | scipy/stats/tests/test_qmc.py | {
"start": 25900,
"end": 27223
} | class ____(QMCEngineTests):
qmce = qmc.Halton
can_scramble = True
# theoretical values known from Van der Corput
unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3],
[1 / 4, 2 / 3], [3 / 4, 1 / 9],
[1 / 8, 4 / 9], [5 / 8, 7 / 9],
... | TestHalton |
python | ray-project__ray | python/ray/_private/telemetry/metric_cardinality.py | {
"start": 399,
"end": 2395
} | class ____(str, Enum):
"""Cardinality level configuration for all Ray metrics (ray_tasks, ray_actors,
etc.). This configurtion is used to determine whether to globally drop high
cardinality labels. This is important for high scale clusters that might consist
thousands of workers, millions of tasks.
... | MetricCardinality |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 23552,
"end": 24562
} | class ____(_BaseFixedShapeArrowTensorType):
"""Arrow ExtensionType (v1) for tensors.
NOTE: This type does *NOT* support tensors larger than 4Gb (due to
overflow of int32 offsets utilized inside Pyarrow `ListType`)
"""
OFFSET_DTYPE = pa.int32()
def __init__(self, shape: Tuple[int, ...], ... | ArrowTensorType |
python | pytorch__pytorch | torch/_higher_order_ops/scan.py | {
"start": 17244,
"end": 18724
} | class ____(enum.Enum):
"""
Partitioner can add interemdiates to the output of original graph.
These intermediates fall into 4 categories and we want to have different policies for handling them by
modifying the graph:
CLONE: we clone the intermediate when it is a carried input (i.e. init). In this ... | ScanForwardIntermediatesHandlingPolicy |
python | huggingface__transformers | src/transformers/models/efficientloftr/image_processing_efficientloftr.py | {
"start": 1561,
"end": 5140
} | class ____(ImagesKwargs, total=False):
r"""
do_grayscale (`bool`, *optional*, defaults to `True`):
Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method.
"""
do_grayscale: bool
# Copied from transformers.models.superpoint.image_processing_su... | EfficientLoFTRImageProcessorKwargs |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 4224,
"end": 5255
} | class ____:
"""
>>> N().method().__name__
'N'
"""
__class__ = 'N'
def method(self):
return __class__
if cython.compiled:
@cython.cclass
class CDefFuncTest:
"""
>>> obj = CDefFuncTest()
>>> obj.call_cfunc1().__name__
'CDefFuncTest'
#>>> ob... | N |
python | huggingface__transformers | src/transformers/models/esm/openfold_utils/rigid_utils.py | {
"start": 7696,
"end": 24209
} | class ____:
"""
A 3D rotation. Depending on how the object is initialized, the rotation is represented by either a rotation matrix
or a quaternion, though both formats are made available by helper functions. To simplify gradient computation, the
underlying format of the rotation cannot be changed in-pla... | Rotation |
python | doocs__leetcode | solution/3600-3699/3633.Earliest Finish Time for Land and Water Rides I/Solution.py | {
"start": 0,
"end": 547
} | class ____:
def earliestFinishTime(
self,
landStartTime: List[int],
landDuration: List[int],
waterStartTime: List[int],
waterDuration: List[int],
) -> int:
def calc(a1, t1, a2, t2):
min_end = min(a + t for a, t in zip(a1, t1))
return min(ma... | Solution |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type.py | {
"start": 15230,
"end": 21123
} | class ____(type_spec.TypeSpec):
"""Base class for tf.ExtensionType TypeSpec."""
def _serialize(self): # TypeSpec API.
# Use a tuple of (name, value) pairs, to ensure we preserve field ordering.
fields = [f.name for f in self._tf_extension_type_fields()]
if self._tf_extension_type_is_packed:
fiel... | ExtensionTypeSpec |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py | {
"start": 14353,
"end": 16254
} | class ____(RNNCell):
"""Subclass of RNNCells that act like proper `tf.Layer` objects.
For backwards compatibility purposes, most `RNNCell` instances allow their
`call` methods to instantiate variables via `tf.compat.v1.get_variable`. The
underlying
variable scope thus keeps track of any variables, and retur... | LayerRNNCell |
python | sqlalchemy__sqlalchemy | test/orm/test_dynamic.py | {
"start": 4919,
"end": 24172
} | class ____(_DynamicFixture, _fixtures.FixtureTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_basic(self, user_address_fixture):
User, Address = user_address_fixture()
sess = fixture_session()
q = sess.query(User)
eq_(
[
User(
... | DynamicTest |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 23237,
"end": 23914
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter BlockSchemas"""
block_type_id: Optional[BlockSchemaFilterBlockTypeId] = Field(
default=None, description="Filter criteria for `BlockSchema.block_type_id`"
)
block_capabilities: Optional[BlockSchemaFilterCapabilities] = Field(
defaul... | BlockSchemaFilter |
python | pytest-dev__pytest | src/_pytest/junitxml.py | {
"start": 16050,
"end": 25522
} | class ____:
def __init__(
self,
logfile,
prefix: str | None,
suite_name: str = "pytest",
logging: str = "no",
report_duration: str = "total",
family="xunit1",
log_passing_tests: bool = True,
) -> None:
logfile = os.path.expanduser(os.path.e... | LogXML |
python | getsentry__sentry | src/sentry/preprod/migrations/0017_break_commit_fks.py | {
"start": 222,
"end": 1781
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | spyder-ide__spyder | spyder/plugins/statusbar/confpage.py | {
"start": 352,
"end": 2068
} | class ____(PluginConfigPage):
def setup_page(self):
newcb = self.create_checkbox
# --- Status bar
sbar_group = QGroupBox(_("Display"))
memory_box = newcb(_("Show memory usage every"), 'memory_usage/enable')
memory_spin = self.create_spinbox("", _(" ms"), 'memory_usage/time... | StatusBarConfigPage |
python | ansible__ansible | lib/ansible/modules/file.py | {
"start": 8705,
"end": 8903
} | class ____(Exception):
def __init__(self, results):
self.results = results
def __repr__(self):
return 'AnsibleModuleError(results={0})'.format(self.results)
| AnsibleModuleError |
python | pypa__pipenv | pipenv/patched/pip/_internal/models/pylock.py | {
"start": 1959,
"end": 5344
} | class ____:
name: str
version: Optional[str] = None
# (not supported) marker: Optional[str]
# (not supported) requires_python: Optional[str]
# (not supported) dependencies
vcs: Optional[PackageVcs] = None
directory: Optional[PackageDirectory] = None
archive: Optional[PackageArchive] = No... | Package |
python | keon__algorithms | algorithms/graph/cycle_detection.py | {
"start": 288,
"end": 1634
} | class ____(Enum):
"""
For a given node:
- WHITE: has not been visited yet
- GRAY: is currently being investigated for a cycle
- BLACK: is not part of a cycle
"""
WHITE = 0
GRAY = 1
BLACK = 2
def is_in_cycle(graph, traversal_states, vertex):
"""
Determines if the ... | TraversalState |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 42305,
"end": 43160
} | class ____:
"""
Key for the FakeTensor dispatch cache.
"""
key: tuple[object, ...]
hashvalue: int
def __init__(self, tup: tuple[object, ...]) -> None:
self.key = tup
self.hashvalue = hash(tup)
def __eq__(self, other: object) -> bool:
return isinstance(other, _Dispa... | _DispatchCacheKey |
python | pytorch__pytorch | .ci/lumen_cli/tests/test_cli_helper.py | {
"start": 1324,
"end": 3892
} | class ____(unittest.TestCase):
def test_metavar_lists_targets(self):
specs: dict[str, TargetSpec] = {
"foo": {"runner": FooRunner, "add_arguments": add_foo_args},
"bar": {"runner": BarRunner},
}
parser = build_parser(specs)
subparsers_action = next(
... | TestRegisterTargets |
python | mlflow__mlflow | mlflow/pyfunc/model.py | {
"start": 9536,
"end": 10712
} | class ____(PythonModel):
"""
When a user specifies a ``python_model`` argument that is a function, we wrap the function
in an instance of this class.
"""
def __init__(self, func, signature=None):
self.signature = signature
# only wrap `func` if @pyfunc is not already applied
... | _FunctionPythonModel |
python | PrefectHQ__prefect | src/prefect/settings/models/server/services.py | {
"start": 7430,
"end": 8921
} | class ____(ServicesBaseSetting):
"""
Settings for controlling the late runs service
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(
("server", "services", "late_runs")
)
enabled: bool = Field(
default=True,
description="Whether or not to start th... | ServerServicesLateRunsSettings |
python | huggingface__transformers | tests/models/siglip2/test_modeling_siglip2.py | {
"start": 13658,
"end": 16885
} | class ____:
def __init__(
self,
parent,
batch_size=12,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=64,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37... | Siglip2TextModelTester |
python | openai__openai-python | tests/api_resources/audio/test_translations.py | {
"start": 2283,
"end": 4357
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_create(self, async_client: AsyncOpenAI) -> None:
translation = await async_client.audio.tr... | TestAsyncTranslations |
python | walkccc__LeetCode | solutions/2264. Largest 3-Same-Digit Number in String/2264.py | {
"start": 0,
"end": 202
} | class ____:
def largestGoodInteger(self, num: str) -> str:
return max(num[i - 2:i + 1]
if num[i] == num[i - 1] == num[i - 2]
else '' for i in range(2, len(num)))
| Solution |
python | boto__boto3 | boto3/resources/model.py | {
"start": 1389,
"end": 2415
} | class ____:
"""
A service operation action.
:type name: string
:param name: The name of the action
:type definition: dict
:param definition: The JSON definition
:type resource_defs: dict
:param resource_defs: All resources defined in the service
"""
def __init__(self, name, def... | Action |
python | huggingface__transformers | src/transformers/generation/continuous_batching/cache_manager.py | {
"start": 15444,
"end": 20690
} | class ____(CacheAllocator):
"""Cache manager for sliding window attention layers."""
def __init__(self, index: int, block_size: int, sliding_window: int) -> None:
"""Initializes the cache manager for a group of sliding window attention layers.
Args:
- index: the index of the associa... | SlidingAttentionCacheAllocator |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py | {
"start": 1062,
"end": 2541
} | class ____(ColumnAggregateMetricProvider):
# </snippet>
# This is the id string that will be used to reference your Metric.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py metric_name">
metric_name = "METRIC NAME GOES H... | ColumnAggregateMatchesSomeCriteria |
python | ray-project__ray | rllib/utils/spaces/simplex.py | {
"start": 107,
"end": 1881
} | class ____(gym.Space):
"""Represents a d - 1 dimensional Simplex in R^d.
That is, all coordinates are in [0, 1] and sum to 1.
The dimension d of the simplex is assumed to be shape[-1].
Additionally one can specify the underlying distribution of
the simplex as a Dirichlet distribution by providing ... | Simplex |
python | mlflow__mlflow | tests/langchain/test_langchain_databricks_dependency_extraction.py | {
"start": 2721,
"end": 21398
} | class ____(VectorSearchIndex):
def __init__(self, endpoint_name, index_name, has_embedding_endpoint=False) -> None:
self.endpoint_name = endpoint_name
self.name = index_name
self.has_embedding_endpoint = has_embedding_endpoint
def describe(self):
if self.has_embedding_endpoint:
... | MockVectorSearchIndex |
python | google__pytype | pytype/vm_utils.py | {
"start": 3848,
"end": 4196
} | class ____(_NameErrorDetails):
def __init__(self, attr, class_name):
super().__init__()
self._attr = attr
self._class_name = class_name
def to_error_message(self):
return (
f"Cannot reference {self._attr!r} from class {self._class_name!r} "
"before the class is fully defined"
)... | _NameInInnerClassErrorDetails |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 49135,
"end": 49947
} | class ____(gdb.Function, CythonBase, EvaluateOrExecuteCodeMixin):
"""
Evaluate Python code in the nearest Python or Cython frame and return
"""
@libpython.dont_suppress_errors
@gdb_function_value_to_unicode
def invoke(self, python_expression):
input_type = libpython.PythonCodeExecutor.P... | CyEval |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 71439,
"end": 76054
} | class ____(TestCase):
x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
res1 = np.array([[1.0, -1.0], [-1.0, 1.0]])
x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
frequencies = np.array([1, 4, 1])
x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T
res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])
... | TestCov |
python | pennersr__django-allauth | allauth/headless/mfa/inputs.py | {
"start": 857,
"end": 1292
} | class ____(inputs.Input):
id = inputs.ModelChoiceField(queryset=Authenticator.objects.none())
name = inputs.CharField(required=True, max_length=100)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
self.fields["id"].queryset = Aut... | UpdateWebAuthnInput |
python | fluentpython__example-code | attic/functions/accgen.py | {
"start": 162,
"end": 483
} | class ____:
def __init__(self, n):
self.n = n
def __call__(self, i):
self.n += i
return self.n
def foo0(n):
def bar(i):
bar.s += i
return bar.s
bar.s = n
return bar
def foo(n):
def bar(i):
nonlocal n
n += i
return n
return bar... | foo0 |
python | facebook__pyre-check | tools/upgrade/commands/pysa_version_update.py | {
"start": 492,
"end": 2509
} | class ____(Command):
def __init__(
self,
*,
repository: Repository,
hash: str,
no_commit: bool,
) -> None:
super().__init__(repository)
self._hash: str = hash
self._no_commit: bool = no_commit
@staticmethod
def from_arguments(
argu... | PysaVersionUpdate |
python | great-expectations__great_expectations | tests/core/factory/test_validation_definition_factory.py | {
"start": 14868,
"end": 22083
} | class ____:
def _build_batch_definition(self, context: AbstractDataContext):
name = random_name()
ds = context.data_sources.add_pandas(name=name)
asset = ds.add_csv_asset(name=name, filepath_or_buffer=pathlib.Path("data.csv"))
return asset.add_batch_definition(name=name)
def _bu... | TestValidationDefinitionFactoryAddOrUpdate |
python | django__django | tests/gis_tests/inspectapp/tests.py | {
"start": 2424,
"end": 9637
} | class ____(SimpleTestCase):
maxDiff = 1024
def test_poly(self):
shp_file = os.path.join(TEST_DATA, "test_poly", "test_poly.shp")
model_def = ogrinspect(shp_file, "MyModel")
expected = [
"# This is an auto-generated Django model module created by ogrinspect.",
"f... | OGRInspectTest |
python | scikit-learn__scikit-learn | sklearn/externals/array_api_compat/common/_typing.py | {
"start": 1109,
"end": 1341
} | class ____(Protocol):
@property
def __class__(self, /) -> type[float]: ...
@__class__.setter
def __class__(self, value: type[float], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride]
@final
| JustFloat |
python | google__jax | examples/ffi/tests/cpu_examples_test.py | {
"start": 2166,
"end": 2994
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cpu"]):
self.skipTest("Unsupported platform")
def test_basic(self):
self.assertEqual(cpu_examples.counter(0), 0)
self.assertEqual(cpu_examples.counter(0), 1)
self.assertEqual(cpu_examples.count... | CounterTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-rabbitmq/destination_rabbitmq/destination.py | {
"start": 1116,
"end": 3618
} | class ____(Destination):
def write(
self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]
) -> Iterable[AirbyteMessage]:
exchange = config.get("exchange")
routing_key = config["routing_key"]
connection = create_con... | DestinationRabbitmq |
python | django__django | django/contrib/staticfiles/storage.py | {
"start": 496,
"end": 1530
} | class ____(FileSystemStorage):
"""
Standard file system storage for static files.
The defaults for ``location`` and ``base_url`` are
``STATIC_ROOT`` and ``STATIC_URL``.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None:
location = se... | StaticFilesStorage |
python | optuna__optuna | optuna/cli.py | {
"start": 5835,
"end": 9619
} | class ____:
def __init__(self, value: Any) -> None:
self.value = value
if value is None:
self.value_type = ValueType.NONE
elif isinstance(value, (int, float)):
self.value_type = ValueType.NUMERIC
else:
self.value_type = ValueType.STRING
def __... | CellValue |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 5973,
"end": 7268
} | class ____(TestBase):
def testCreateRevisionFollow(self):
reversion.register(TestModel, follow=("related",))
reversion.register(TestModelRelated)
obj_related = TestModelRelated.objects.create()
with reversion.create_revision():
obj = TestModel.objects.create()
... | CreateRevisionFollowTest |
python | getsentry__sentry | src/sentry/shared_integrations/exceptions/__init__.py | {
"start": 5354,
"end": 5664
} | class ____(IntegrationError):
def __init__(self, field_errors: Mapping[str, Any] | None = None) -> None:
error = "Invalid integration action"
if field_errors:
error = str(field_errors)
super().__init__(error)
self.field_errors = field_errors
| IntegrationFormError |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 756,
"end": 865
} | class ____(str, Enum):
ALWAYS = "Always"
IF_NOT_PRESENT = "IfNotPresent"
NEVER = "Never"
| PullPolicy |
python | huggingface__transformers | src/transformers/models/pop2piano/modeling_pop2piano.py | {
"start": 19961,
"end": 23858
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.is_decoder = config.is_decoder
self.layer = nn.ModuleList()
self.layer.append(
Pop2PianoLayerSelfAttention(
... | Pop2PianoBlock |
python | django__django | tests/admin_utils/models.py | {
"start": 1615,
"end": 1800
} | class ____(models.Model):
event = models.OneToOneField(Event, models.CASCADE)
name = models.CharField(max_length=255)
class Meta:
verbose_name = "awesome guest"
| Guest |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/utils.py | {
"start": 237,
"end": 2109
} | class ____(IterDataPipe[_T]):
r"""
Wraps an iterable object to create an IterDataPipe.
Args:
iterable: Iterable object to be wrapped into an IterDataPipe
deepcopy: Option to deepcopy input iterable object for each
iterator. The copy is made when the first element is read in ``it... | IterableWrapperIterDataPipe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.