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 | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 150436,
"end": 150901
} | class ____(CompileState):
@util.memoized_property
def _label_resolve_dict(
self,
) -> Tuple[
Dict[str, ColumnElement[Any]],
Dict[str, ColumnElement[Any]],
Dict[str, ColumnElement[Any]],
]:
# TODO: this is hacky and slow
hacky_subquery = self.statement.subquery()
hacky_subquery.named_with_column = False
d = {c.key: c for c in hacky_subquery.c}
return d, d, d
| CompoundSelectState |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 18813,
"end": 19219
} | class ____(StringIORewind):
def setup(self):
count_elem = 100_000
data = "a\n" + "2019-12-31\n" * count_elem
self.StringIO_input = StringIO(data)
def time_read_csv_index_col(self):
read_csv(
self.data(self.StringIO_input),
parse_dates=["a"],
engine="pyarrow",
dtype_backend="pyarrow",
)
| ReadCSVDatePyarrowEngine |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1585370,
"end": 1585542
} | class ____(sgqlc.types.Union):
"""Types that can initiate an audit log event."""
__schema__ = github_schema
__types__ = (Bot, Organization, User)
| AuditEntryActor |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 84003,
"end": 85212
} | class ____(Response):
"""
Response of tasks.add_or_update_model endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_model"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, updated: Optional[int] = None, **kwargs: Any) -> None:
super(AddOrUpdateModelResponse, self).__init__(**kwargs)
self.updated = updated
@schema_property("updated")
def updated(self) -> Optional[int]:
return self._property_updated
@updated.setter
def updated(self, value: Optional[int]) -> None:
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
| AddOrUpdateModelResponse |
python | numba__numba | numba/cpython/setobj.py | {
"start": 3481,
"end": 12301
} | class ____(object):
def __init__(self, context, builder, set_type, ptr):
payload = get_payload_struct(context, builder, set_type, ptr)
self._context = context
self._builder = builder
self._ty = set_type
self._payload = payload
self._entries = payload._get_ptr_by_name('entries')
self._ptr = ptr
@property
def mask(self):
return self._payload.mask
@mask.setter
def mask(self, value):
# CAUTION: mask must be a power of 2 minus 1
self._payload.mask = value
@property
def used(self):
return self._payload.used
@used.setter
def used(self, value):
self._payload.used = value
@property
def fill(self):
return self._payload.fill
@fill.setter
def fill(self, value):
self._payload.fill = value
@property
def finger(self):
return self._payload.finger
@finger.setter
def finger(self, value):
self._payload.finger = value
@property
def dirty(self):
return self._payload.dirty
@dirty.setter
def dirty(self, value):
self._payload.dirty = value
@property
def entries(self):
"""
A pointer to the start of the entries array.
"""
return self._entries
@property
def ptr(self):
"""
A pointer to the start of the NRT-allocated area.
"""
return self._ptr
def get_entry(self, idx):
"""
Get entry number *idx*.
"""
entry_ptr = cgutils.gep(self._builder, self._entries, idx)
entry = self._context.make_data_helper(self._builder,
types.SetEntry(self._ty),
ref=entry_ptr)
return entry
def _lookup(self, item, h, for_insert=False):
"""
Lookup the *item* with the given hash values in the entries.
Return a (found, entry index) tuple:
- If found is true, <entry index> points to the entry containing
the item.
- If found is false, <entry index> points to the empty entry that
the item can be written to (only if *for_insert* is true)
"""
context = self._context
builder = self._builder
intp_t = h.type
mask = self.mask
dtype = self._ty.dtype
tyctx = context.typing_context
fnty = tyctx.resolve_value_type(operator.eq)
sig = fnty.get_call_type(tyctx, (dtype, dtype), {})
eqfn = context.get_function(fnty, sig)
one = ir.Constant(intp_t, 1)
five = ir.Constant(intp_t, 5)
# The perturbation value for probing
perturb = cgutils.alloca_once_value(builder, h)
# The index of the entry being considered: start with (hash & mask)
index = cgutils.alloca_once_value(builder,
builder.and_(h, mask))
if for_insert:
# The index of the first deleted entry in the lookup chain
free_index_sentinel = mask.type(-1) # highest unsigned index
free_index = cgutils.alloca_once_value(builder, free_index_sentinel)
bb_body = builder.append_basic_block("lookup.body")
bb_found = builder.append_basic_block("lookup.found")
bb_not_found = builder.append_basic_block("lookup.not_found")
bb_end = builder.append_basic_block("lookup.end")
def check_entry(i):
"""
Check entry *i* against the value being searched for.
"""
entry = self.get_entry(i)
entry_hash = entry.hash
with builder.if_then(builder.icmp_unsigned('==', h, entry_hash)):
# Hashes are equal, compare values
# (note this also ensures the entry is used)
eq = eqfn(builder, (item, entry.key))
with builder.if_then(eq):
builder.branch(bb_found)
with builder.if_then(is_hash_empty(context, builder, entry_hash)):
builder.branch(bb_not_found)
if for_insert:
# Memorize the index of the first deleted entry
with builder.if_then(is_hash_deleted(context, builder, entry_hash)):
j = builder.load(free_index)
j = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel),
i, j)
builder.store(j, free_index)
# First linear probing. When the number of collisions is small,
# the lineary probing loop achieves better cache locality and
# is also slightly cheaper computationally.
with cgutils.for_range(builder, ir.Constant(intp_t, LINEAR_PROBES)):
i = builder.load(index)
check_entry(i)
i = builder.add(i, one)
i = builder.and_(i, mask)
builder.store(i, index)
# If not found after linear probing, switch to a non-linear
# perturbation keyed on the unmasked hash value.
# XXX how to tell LLVM this branch is unlikely?
builder.branch(bb_body)
with builder.goto_block(bb_body):
i = builder.load(index)
check_entry(i)
# Perturb to go to next entry:
# perturb >>= 5
# i = (i * 5 + 1 + perturb) & mask
p = builder.load(perturb)
p = builder.lshr(p, five)
i = builder.add(one, builder.mul(i, five))
i = builder.and_(mask, builder.add(i, p))
builder.store(i, index)
builder.store(p, perturb)
# Loop
builder.branch(bb_body)
with builder.goto_block(bb_not_found):
if for_insert:
# Not found => for insertion, return the index of the first
# deleted entry (if any), to avoid creating an infinite
# lookup chain (issue #1913).
i = builder.load(index)
j = builder.load(free_index)
i = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel),
i, j)
builder.store(i, index)
builder.branch(bb_end)
with builder.goto_block(bb_found):
builder.branch(bb_end)
builder.position_at_end(bb_end)
found = builder.phi(ir.IntType(1), 'found')
found.add_incoming(cgutils.true_bit, bb_found)
found.add_incoming(cgutils.false_bit, bb_not_found)
return found, builder.load(index)
@contextlib.contextmanager
def _iterate(self, start=None):
"""
Iterate over the payload's entries. Yield a SetLoop.
"""
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
one = ir.Constant(intp_t, 1)
size = builder.add(self.mask, one)
with cgutils.for_range(builder, size, start=start) as range_loop:
entry = self.get_entry(range_loop.index)
is_used = is_hash_used(context, builder, entry.hash)
with builder.if_then(is_used):
loop = SetLoop(index=range_loop.index, entry=entry,
do_break=range_loop.do_break)
yield loop
@contextlib.contextmanager
def _next_entry(self):
"""
Yield a random entry from the payload. Caller must ensure the
set isn't empty, otherwise the function won't end.
"""
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
zero = ir.Constant(intp_t, 0)
one = ir.Constant(intp_t, 1)
mask = self.mask
# Start walking the entries from the stored "search finger" and
# break as soon as we find a used entry.
bb_body = builder.append_basic_block('next_entry_body')
bb_end = builder.append_basic_block('next_entry_end')
index = cgutils.alloca_once_value(builder, self.finger)
builder.branch(bb_body)
with builder.goto_block(bb_body):
i = builder.load(index)
# ANDing with mask ensures we stay inside the table boundaries
i = builder.and_(mask, builder.add(i, one))
builder.store(i, index)
entry = self.get_entry(i)
is_used = is_hash_used(context, builder, entry.hash)
builder.cbranch(is_used, bb_end, bb_body)
builder.position_at_end(bb_end)
# Update the search finger with the next position. This avoids
# O(n**2) behaviour when pop() is called in a loop.
i = builder.load(index)
self.finger = i
yield self.get_entry(i)
| _SetPayload |
python | geekcomputers__Python | Industrial_developed_hangman/src/hangman/main.py | {
"start": 303,
"end": 2488
} | class ____(Enum):
"""Enum that represents switch between local and web word parsing."""
FROM_FILE = 0 # noqa: WPS115
FROM_INTERNET = 1 # noqa: WPS115
def print_wrong(text: str, print_function: Callable[[str], None]) -> None:
"""
Print styled text(red).
:parameter text: text to print.
:parameter print_function: Function that will be used to print in game.
"""
text_to_print = Style.RESET_ALL + Fore.RED + text
print_function(text_to_print)
def print_right(text: str, print_function: Callable[[str], None]) -> None:
"""
Print styled text(red).
:parameter text: text to print.
:parameter print_function: Function that will be used to print in game.
"""
print_function(Style.RESET_ALL + Fore.GREEN + text)
def parse_word_from_local(
choice_function: Callable[[List[str]], str] = random.choice,
) -> str:
# noqa: DAR201
"""
Parse word from local file.
:parameter choice_function: Function that will be used to choice a word from file.
:returns str: string that contains the word.
:raises FileNotFoundError: file to read words not found.
"""
try:
with open(data_path / "local_words.txt", encoding="utf8") as words_file:
return choice_function(words_file.read().split("\n"))
except FileNotFoundError:
raise FileNotFoundError("File local_words.txt was not found")
def parse_word_from_site(
url: str = "https://random-word-api.herokuapp.com/word",
) -> str:
# noqa: DAR201
"""
Parse word from website.
:param url: url that word will be parsed from.
:return Optional[str]: string that contains the word.
:raises ConnectionError: no connection to the internet.
:raises RuntimeError: something go wrong with getting the word from site.
"""
try:
response: requests.Response = requests.get(url, timeout=request_timeout)
except ConnectionError:
raise ConnectionError("There is no connection to the internet")
if response.status_code == success_code:
return json.loads(response.content.decode())[0]
raise RuntimeError("Something go wrong with getting the word from site")
| Source |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/deadcode.py | {
"start": 1673,
"end": 1890
} | class ____:
a: MyCallable
def dead_code_by_type_refinement(d: Optional[Foo]) -> None:
if d is not None:
if isinstance(d.a, MyCallable):
print("..")
else:
_test_sink(d)
| Foo |
python | doocs__leetcode | solution/3200-3299/3285.Find Indices of Stable Mountains/Solution.py | {
"start": 0,
"end": 174
} | class ____:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
return [i for i in range(1, len(height)) if height[i - 1] > threshold]
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_collections.py | {
"start": 409,
"end": 1584
} | class ____(StreamTestCase):
_STREAM_NAME = "collections"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).build(),
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id")).build(),
)
output = read_full_refresh(self._config, _STREAM_NAME)
assert len(output.records) == 1
@HttpMocker()
def test_given_multiple_pages_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).with_next_page_token(NEXT_PAGE_TOKEN).build(),
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id")).build(),
)
http_mocker.get(
self.stream_request().with_limit(250).build(),
get_stream_response(_STREAM_NAME).with_pagination().with_record(get_stream_record(_STREAM_NAME, "id")).build(),
)
output = read_full_refresh(self._config, _STREAM_NAME)
assert len(output.records) == 2
| TestFullRefresh |
python | readthedocs__readthedocs.org | readthedocs/storage/rclone.py | {
"start": 4127,
"end": 6129
} | class ____(BaseRClone):
"""
RClone remote implementation for S3.
All secrets will be passed as environ variables to the rclone command.
See https://rclone.org/s3/ and https://rclone.org/s3/#configuration.
:params bucket_name: Name of the S3 bucket.
:params access_key_id: AWS access key id.
:params secret_access_key: AWS secret access key.
:params session_token: AWS session token,
useful for temporary credentials from AWS STS.
See https://docs.readthedocs.com/dev/latest/aws-temporary-credentials.html.
:params region: AWS region.
:params provider: S3 provider, defaults to ``AWS``.
Useful to use Minio during development.
See https://rclone.org/s3/#s3-provider.
:param acl: Canned ACL used when creating buckets and storing or copying objects.
See https://rclone.org/s3/#s3-acl.
:param endpoint: Custom S3 endpoint, useful for development.
"""
remote_type = "s3"
def __init__(
self,
bucket_name,
access_key_id,
secret_access_key,
region,
provider="AWS",
session_token=None,
acl=None,
endpoint=None,
):
# rclone S3 options passed as env vars.
# https://rclone.org/s3/#standard-options.
self.env_vars = {
"RCLONE_S3_PROVIDER": provider,
"RCLONE_S3_ACCESS_KEY_ID": access_key_id,
"RCLONE_S3_SECRET_ACCESS_KEY": secret_access_key,
"RCLONE_S3_REGION": region,
"RCLONE_S3_LOCATION_CONSTRAINT": region,
}
if session_token:
self.env_vars["RCLONE_S3_SESSION_TOKEN"] = session_token
if acl:
self.env_vars["RCLONE_S3_ACL"] = acl
if endpoint:
self.env_vars["RCLONE_S3_ENDPOINT"] = endpoint
self.bucket_name = bucket_name
def _get_target_path(self, path):
"""Overridden to prepend the bucket name to the path."""
return safe_join(self.bucket_name, path)
| RCloneS3Remote |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 12703,
"end": 13207
} | class ____(AnsibleAction):
"""
An action runtime skip.
This exception provides a result dictionary via the ContributesToTaskResult mixin.
"""
@property
def result_contribution(self) -> _c.Mapping[str, object]:
return self._result | dict(
skipped=True,
msg=self.message,
)
@property
def omit_failed_key(self) -> bool:
return True
@property
def omit_exception_key(self) -> bool:
return True
| AnsibleActionSkip |
python | google__pytype | pytype/rewrite/flow/conditions.py | {
"start": 360,
"end": 482
} | class ____(Condition):
def __repr__(self):
return 'FALSE'
TRUE = _True()
FALSE = _False()
@_frozen_dataclass
| _False |
python | fluentpython__example-code | 20-descriptor/bulkfood/model_v5.py | {
"start": 30,
"end": 540
} | class ____: # <1>
__counter = 0
def __init__(self):
cls = self.__class__
prefix = cls.__name__
index = cls.__counter
self.storage_name = '_{}#{}'.format(prefix, index)
cls.__counter += 1
def __get__(self, instance, owner):
if instance is None:
return self
else:
return getattr(instance, self.storage_name)
def __set__(self, instance, value):
setattr(instance, self.storage_name, value) # <2>
| AutoStorage |
python | pytorch__pytorch | torch/nn/modules/loss.py | {
"start": 87856,
"end": 96445
} | class ____(_Loss):
r"""The Connectionist Temporal Classification loss.
Calculates loss between a continuous (unsegmented) time series and a target sequence. CTCLoss sums over the
probability of possible alignments of input to target, producing a loss value which is differentiable
with respect to each input node. The alignment of input to target is assumed to be "many-to-one", which
limits the length of the target sequence such that it must be :math:`\leq` the input length.
Args:
blank (int, optional): blank label. Default :math:`0`.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the output losses will be divided by the target lengths and
then the mean over the batch is taken, ``'sum'``: the output losses will be summed.
Default: ``'mean'``
zero_infinity (bool, optional):
Whether to zero infinite losses and the associated gradients.
Default: ``False``
Infinite losses mainly occur when the inputs are too short
to be aligned to the targets.
Shape:
- Log_probs: Tensor of size :math:`(T, N, C)` or :math:`(T, C)`,
where :math:`T = \text{input length}`,
:math:`N = \text{batch size}`, and
:math:`C = \text{number of classes (including blank)}`.
The logarithmized probabilities of the outputs (e.g. obtained with
:func:`torch.nn.functional.log_softmax`).
- Targets: Tensor of size :math:`(N, S)` or
:math:`(\operatorname{sum}(\text{target\_lengths}))`,
where :math:`N = \text{batch size}` and
:math:`S = \text{max target length, if shape is } (N, S)`.
It represents the target sequences. Each element in the target
sequence is a class index. And the target index cannot be blank (default=0).
In the :math:`(N, S)` form, targets are padded to the
length of the longest sequence, and stacked.
In the :math:`(\operatorname{sum}(\text{target\_lengths}))` form,
the targets are assumed to be un-padded and
concatenated within 1 dimension.
- Input_lengths: Tuple or tensor of size :math:`(N)` or :math:`()`,
where :math:`N = \text{batch size}`. It represents the lengths of the
inputs (must each be :math:`\leq T`). And the lengths are specified
for each sequence to achieve masking under the assumption that sequences
are padded to equal lengths.
- Target_lengths: Tuple or tensor of size :math:`(N)` or :math:`()`,
where :math:`N = \text{batch size}`. It represents lengths of the targets.
Lengths are specified for each sequence to achieve masking under the
assumption that sequences are padded to equal lengths. If target shape is
:math:`(N,S)`, target_lengths are effectively the stop index
:math:`s_n` for each target sequence, such that ``target_n = targets[n,0:s_n]`` for
each target in a batch. Lengths must each be :math:`\leq S`
If the targets are given as a 1d tensor that is the concatenation of individual
targets, the target_lengths must add up to the total length of the tensor.
- Output: scalar if :attr:`reduction` is ``'mean'`` (default) or
``'sum'``. If :attr:`reduction` is ``'none'``, then :math:`(N)` if input is batched or
:math:`()` if input is unbatched, where :math:`N = \text{batch size}`.
Examples:
>>> # Target are to be padded
>>> T = 50 # Input sequence length
>>> C = 20 # Number of classes (including blank)
>>> N = 16 # Batch size
>>> S = 30 # Target sequence length of longest target in batch (padding length)
>>> S_min = 10 # Minimum target length, for demonstration purposes
>>>
>>> # Initialize random batch of input vectors, for *size = (T,N,C)
>>> input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
>>>
>>> # Initialize random batch of targets (0 = blank, 1:C = classes)
>>> target = torch.randint(low=1, high=C, size=(N, S), dtype=torch.long)
>>>
>>> input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
>>> target_lengths = torch.randint(
... low=S_min,
... high=S,
... size=(N,),
... dtype=torch.long,
... )
>>> ctc_loss = nn.CTCLoss()
>>> loss = ctc_loss(input, target, input_lengths, target_lengths)
>>> loss.backward()
>>>
>>>
>>> # Target are to be un-padded
>>> T = 50 # Input sequence length
>>> C = 20 # Number of classes (including blank)
>>> N = 16 # Batch size
>>>
>>> # Initialize random batch of input vectors, for *size = (T,N,C)
>>> input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
>>> input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
>>>
>>> # Initialize random batch of targets (0 = blank, 1:C = classes)
>>> target_lengths = torch.randint(low=1, high=T, size=(N,), dtype=torch.long)
>>> target = torch.randint(
... low=1,
... high=C,
... size=(sum(target_lengths),),
... dtype=torch.long,
... )
>>> ctc_loss = nn.CTCLoss()
>>> loss = ctc_loss(input, target, input_lengths, target_lengths)
>>> loss.backward()
>>>
>>>
>>> # Target are to be un-padded and unbatched (effectively N=1)
>>> T = 50 # Input sequence length
>>> C = 20 # Number of classes (including blank)
>>>
>>> # Initialize random batch of input vectors, for *size = (T,C)
>>> # xdoctest: +SKIP("FIXME: error in doctest")
>>> input = torch.randn(T, C).log_softmax(1).detach().requires_grad_()
>>> input_lengths = torch.tensor(T, dtype=torch.long)
>>>
>>> # Initialize random batch of targets (0 = blank, 1:C = classes)
>>> target_lengths = torch.randint(low=1, high=T, size=(), dtype=torch.long)
>>> target = torch.randint(
... low=1,
... high=C,
... size=(target_lengths,),
... dtype=torch.long,
... )
>>> ctc_loss = nn.CTCLoss()
>>> loss = ctc_loss(input, target, input_lengths, target_lengths)
>>> loss.backward()
Reference:
A. Graves et al.: Connectionist Temporal Classification:
Labelling Unsegmented Sequence Data with Recurrent Neural Networks:
https://www.cs.toronto.edu/~graves/icml_2006.pdf
Note:
In order to use CuDNN, the following must be satisfied: the :attr:`targets` must be
in concatenated format, all :attr:`input_lengths` must be `T`. :math:`blank=0`,
:attr:`target_lengths` :math:`\leq 256`, the integer arguments must be of
dtype :attr:`torch.int32`, and the :attr:`log_probs` itself must be of
dtype :attr:`torch.float32`.
The regular implementation uses the (more common in PyTorch) `torch.long` dtype.
Note:
In some circumstances when using the CUDA backend with CuDNN, this operator
may select a nondeterministic algorithm to increase performance. If this is
undesirable, you can try to make the operation deterministic (potentially at
a performance cost) by setting ``torch.backends.cudnn.deterministic =
True``.
Please see the notes on :doc:`/notes/randomness` for background.
"""
__constants__ = ["blank", "reduction"]
blank: int
zero_infinity: bool
def __init__(
self, blank: int = 0, reduction: str = "mean", zero_infinity: bool = False
) -> None:
super().__init__(reduction=reduction)
self.blank = blank
self.zero_infinity = zero_infinity
def forward(
self,
log_probs: Tensor,
targets: Tensor,
input_lengths: Tensor,
target_lengths: Tensor,
) -> Tensor:
"""Runs the forward pass."""
return F.ctc_loss(
log_probs,
targets,
input_lengths,
target_lengths,
self.blank,
self.reduction,
self.zero_infinity,
)
# TODO: L1HingeEmbeddingCriterion
# TODO: MSECriterion weight
# TODO: ClassSimplexCriterion
| CTCLoss |
python | doocs__leetcode | solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py | {
"start": 0,
"end": 445
} | class ____:
def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int:
f = [[0] * (budget + 1) for _ in range(len(present) + 1)]
for i, w in enumerate(present, 1):
for j in range(budget + 1):
f[i][j] = f[i - 1][j]
if j >= w and future[i - 1] > w:
f[i][j] = max(f[i][j], f[i - 1][j - w] + future[i - 1] - w)
return f[-1][-1]
| Solution |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_details.py | {
"start": 28109,
"end": 45139
} | class ____(APITestCase):
@patch("sentry.tasks.commits.fetch_commits")
def test_simple(self, mock_fetch_commits: MagicMock) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
repo = Repository.objects.create(
organization_id=org.id, name="example/example", provider="dummy"
)
repo2 = Repository.objects.create(
organization_id=org.id, name="example/example2", provider="dummy"
)
team1 = self.create_team(organization=org)
team2 = self.create_team(organization=org)
project = self.create_project(teams=[team1], organization=org)
project2 = self.create_project(teams=[team2], organization=org)
base_release = Release.objects.create(organization_id=org.id, version="000000000")
base_release.add_project(project)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release2 = Release.objects.create(organization_id=org.id, version="12345678")
release.add_project(project)
release2.add_project(project2)
self.create_member(teams=[team1], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": base_release.version},
)
self.client.put(
url,
{
"ref": "master",
"headCommits": [
{"currentId": "0" * 40, "repository": repo.name},
{"currentId": "0" * 40, "repository": repo2.name},
],
},
)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
{
"ref": "master",
"refs": [
{"commit": "a" * 40, "repository": repo.name},
{"commit": "b" * 40, "repository": repo2.name},
],
},
)
mock_fetch_commits.apply_async.assert_called_with(
kwargs={
"release_id": release.id,
"user_id": user.id,
"refs": [
{"commit": "a" * 40, "repository": repo.name},
{"commit": "b" * 40, "repository": repo2.name},
],
"prev_release_id": base_release.id,
}
)
assert response.status_code == 200, response.content
assert response.data["version"] == release.version
release = Release.objects.get(id=release.id)
assert release.ref == "master"
# no access
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release2.version},
)
response = self.client.put(url, {"ref": "master"})
assert response.status_code == 404
@patch("sentry.tasks.commits.fetch_commits")
def test_deprecated_head_commits(self, mock_fetch_commits: MagicMock) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
repo = Repository.objects.create(
organization_id=org.id, name="example/example", provider="dummy"
)
repo2 = Repository.objects.create(
organization_id=org.id, name="example/example2", provider="dummy"
)
team1 = self.create_team(organization=org)
team2 = self.create_team(organization=org)
project = self.create_project(teams=[team1], organization=org)
project2 = self.create_project(teams=[team2], organization=org)
base_release = Release.objects.create(organization_id=org.id, version="000000000")
base_release.add_project(project)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release2 = Release.objects.create(organization_id=org.id, version="12345678")
release.add_project(project)
release2.add_project(project2)
self.create_member(teams=[team1], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": base_release.version},
)
self.client.put(
url,
{
"ref": "master",
"headCommits": [
{"currentId": "0" * 40, "repository": repo.name},
{"currentId": "0" * 40, "repository": repo2.name},
],
},
)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
{
"ref": "master",
"headCommits": [
{"currentId": "a" * 40, "repository": repo.name},
{"currentId": "b" * 40, "repository": repo2.name},
],
},
)
mock_fetch_commits.apply_async.assert_called_with(
kwargs={
"release_id": release.id,
"user_id": user.id,
"refs": [
{"commit": "a" * 40, "previousCommit": None, "repository": repo.name},
{"commit": "b" * 40, "previousCommit": None, "repository": repo2.name},
],
"prev_release_id": base_release.id,
}
)
assert response.status_code == 200, response.content
assert response.data["version"] == release.version
release = Release.objects.get(id=release.id)
assert release.ref == "master"
# no access
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release2.version},
)
response = self.client.put(url, {"ref": "master"})
assert response.status_code == 404
def test_commits(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(url, data={"commits": [{"id": "a" * 40}, {"id": "b" * 40}]})
assert response.status_code == 200, (response.status_code, response.content)
rc_list = list(
ReleaseCommit.objects.filter(release=release)
.select_related("commit", "commit__author")
.order_by("order")
)
assert len(rc_list) == 2
for rc in rc_list:
assert rc.organization_id == org.id
def test_commits_patchset_character_limit_255(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
data={
"commits": [
{
"id": "a" * 40,
"patch_set": [{"path": "/a/really/long/path/" + ("z" * 255), "type": "A"}],
}
]
},
)
assert response.status_code == 200, (response.status_code, response.content)
rc_list = list(
ReleaseCommit.objects.filter(release=release)
.select_related("commit", "commit__author")
.order_by("order")
)
assert len(rc_list) == 1
for rc in rc_list:
assert rc.organization_id == org.id
def test_commits_patchset_character_limit_reached(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
data={
"commits": [
{
"id": "a" * 40,
"patch_set": [{"path": "z" * (255 * 2 + 1), "type": "A"}],
}
]
},
)
assert response.status_code == 400, (response.status_code, response.content)
def test_commits_lock_conflict(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(name="foo", organization=org, teams=[team])
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
release = self.create_release(project, self.user, version="1.2.1")
release.add_project(project)
# Simulate a concurrent request by using an existing release
# that has its commit lock taken out.
lock = locks.get(Release.get_lock_key(org.id, release.id), duration=10, name="release")
lock.acquire()
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(url, data={"commits": [{"id": "a" * 40}, {"id": "b" * 40}]})
assert response.status_code == 409, (response.status_code, response.content)
assert "Release commits" in response.data["detail"]
def test_release_archiving(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(url, data={"status": "archived"})
assert response.status_code == 200, (response.status_code, response.content)
assert Release.objects.get(id=release.id).status == ReleaseStatus.ARCHIVED
def test_activity_generation(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(url, data={"dateReleased": datetime.now(UTC).isoformat()})
assert response.status_code == 200, (response.status_code, response.content)
release = Release.objects.get(id=release.id)
assert release.date_released
activity = Activity.objects.filter(
type=ActivityType.RELEASE.value, project=project, ident=release.version
)
assert activity.exists()
def test_activity_generation_long_release(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="x" * 65)
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(url, data={"dateReleased": datetime.now(UTC).isoformat()})
assert response.status_code == 200, (response.status_code, response.content)
release = Release.objects.get(id=release.id)
assert release.date_released
activity = Activity.objects.filter(
type=ActivityType.RELEASE.value, project=project, ident=release.version[:64]
)
assert activity.exists()
def test_org_auth_token(self) -> None:
org = self.organization
with assume_test_silo_mode(SiloMode.CONTROL):
good_token_str = generate_token(org.slug, "")
OrgAuthToken.objects.create(
organization_id=org.id,
name="token 1",
token_hashed=hash_token(good_token_str),
token_last_characters="ABCD",
scope_list=["org:ci"],
date_last_used=None,
)
repo = Repository.objects.create(
organization_id=org.id, name="example/example", provider="dummy"
)
team1 = self.create_team(organization=org)
project = self.create_project(teams=[team1], organization=org)
base_release = Release.objects.create(organization_id=org.id, version="000000000")
base_release.add_project(project)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": base_release.version},
)
self.client.put(
url,
data={
"ref": "master",
"headCommits": [
{"currentId": "0" * 40, "repository": repo.name},
],
},
HTTP_AUTHORIZATION=f"Bearer {good_token_str}",
)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
data={
"ref": "master",
"refs": [
{"commit": "a" * 40, "repository": repo.name},
],
},
HTTP_AUTHORIZATION=f"Bearer {good_token_str}",
)
assert response.status_code == 200, response.content
assert response.data["version"] == release.version
release = Release.objects.get(id=release.id)
assert release.ref == "master"
| UpdateReleaseDetailsTest |
python | huggingface__transformers | src/transformers/models/ernie4_5/modeling_ernie4_5.py | {
"start": 15508,
"end": 18653
} | class ____(Ernie4_5PreTrainedModel):
def __init__(self, config: Ernie4_5Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[Ernie4_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Ernie4_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = Ernie4_5RotaryEmbedding(config=config)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
@check_model_inputs()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
cache_position: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position: torch.Tensor = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask,
position_embeddings=position_embeddings,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
@auto_docstring
| Ernie4_5Model |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 22015,
"end": 22426
} | class ____(ProjectAdminMixin, PrivateViewMixin):
form_class = EmailHookForm
def get_success_url(self):
return reverse(
"projects_notifications",
args=[self.get_project().slug],
)
def get_form(self, data=None, files=None, **kwargs):
kwargs["project"] = self.get_project()
return super().get_form(data, files, **kwargs)
| ProjectNotificationsMixin |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 16567,
"end": 17022
} | class ____(Token):
""" Represents a goto statement in Fortran
Examples
========
>>> from sympy.codegen.fnodes import GoTo
>>> go = GoTo([10, 20, 30], 'i')
>>> from sympy import fcode
>>> fcode(go, source_format='free')
'go to (10, 20, 30), i'
"""
__slots__ = _fields = ('labels', 'expr')
defaults = {'expr': none}
_construct_labels = staticmethod(_mk_Tuple)
_construct_expr = staticmethod(sympify)
| GoTo |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 7617,
"end": 7847
} | class ____(Protocol):
"""An object that may be 'cast' to a console renderable."""
def __rich__(
self,
) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover
...
@runtime_checkable
| RichCast |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 10570,
"end": 10872
} | class ____(A23):
def m1(self, a):
return add_feature_e(a)
def issue_precise_tito_intervals(b: B23):
# False positive: Should see feature_c and feature_d but not feature_e, due to distinguishing
# the breadcrumbs from different tito intervals
_test_sink(b.m0(_test_source()))
| E23 |
python | google__pytype | pytype/tests/test_utils.py | {
"start": 8274,
"end": 8623
} | class ____:
"""Match a sequence of substrings in order."""
def __init__(self, seq):
self.seq = seq
def match(self, message):
start = 0
for s in self.seq:
i = message.find(s, start)
if i == -1:
return False
start = i + len(s)
return True
def __repr__(self):
return repr(self.seq)
| SequenceMatcher |
python | davidhalter__jedi | jedi/inference/compiled/subprocess/__main__.py | {
"start": 372,
"end": 1076
} | class ____(MetaPathFinder):
def __init__(self, path_dct):
self._path_dct = path_dct
def find_spec(self, fullname, path=None, target=None):
if path is None and fullname in self._path_dct:
p = self._path_dct[fullname]
spec = PathFinder.find_spec(fullname, path=[p], target=target)
return spec
return None
# Try to import jedi/parso.
sys.meta_path.insert(0, _ExactImporter(_get_paths()))
from jedi.inference.compiled import subprocess # noqa: E402
sys.meta_path.pop(0)
# Retrieve the pickle protocol.
host_sys_version = [int(x) for x in sys.argv[2].split('.')]
# And finally start the client.
subprocess.Listener().listen()
| _ExactImporter |
python | openai__openai-python | src/openai/resources/evals/runs/runs.py | {
"start": 23611,
"end": 24359
} | class ____:
def __init__(self, runs: AsyncRuns) -> None:
self._runs = runs
self.create = async_to_streamed_response_wrapper(
runs.create,
)
self.retrieve = async_to_streamed_response_wrapper(
runs.retrieve,
)
self.list = async_to_streamed_response_wrapper(
runs.list,
)
self.delete = async_to_streamed_response_wrapper(
runs.delete,
)
self.cancel = async_to_streamed_response_wrapper(
runs.cancel,
)
@cached_property
def output_items(self) -> AsyncOutputItemsWithStreamingResponse:
return AsyncOutputItemsWithStreamingResponse(self._runs.output_items)
| AsyncRunsWithStreamingResponse |
python | pydata__xarray | xarray/namedarray/parallelcompat.py | {
"start": 921,
"end": 6172
} | class ____(Protocol):
def rechunk(self, chunks: Any, **kwargs: Any) -> Any: ...
@property
def dtype(self) -> np.dtype[Any]: ...
@property
def chunks(self) -> _NormalizedChunks: ...
def compute(
self, *data: Any, **kwargs: Any
) -> tuple[np.ndarray[Any, _DType_co], ...]: ...
T_ChunkedArray = TypeVar("T_ChunkedArray", bound=ChunkedArrayMixinProtocol)
KNOWN_CHUNKMANAGERS = {
"dask": "dask",
"cubed": "cubed-xarray",
"arkouda": "arkouda-xarray",
}
@functools.lru_cache(maxsize=1)
def list_chunkmanagers() -> dict[str, ChunkManagerEntrypoint[Any]]:
"""
Return a dictionary of available chunk managers and their ChunkManagerEntrypoint subclass objects.
Returns
-------
chunkmanagers : dict
Dictionary whose values are registered ChunkManagerEntrypoint subclass instances, and whose values
are the strings under which they are registered.
"""
entrypoints = entry_points(group="xarray.chunkmanagers")
return load_chunkmanagers(entrypoints)
def load_chunkmanagers(
entrypoints: Sequence[EntryPoint],
) -> dict[str, ChunkManagerEntrypoint[Any]]:
"""Load entrypoints and instantiate chunkmanagers only once."""
loaded_entrypoints = {}
for entrypoint in entrypoints:
try:
loaded_entrypoints[entrypoint.name] = entrypoint.load()
except ModuleNotFoundError as e:
emit_user_level_warning(
f"Failed to load chunk manager entrypoint {entrypoint.name} due to {e}. Skipping.",
)
available_chunkmanagers = {
name: chunkmanager()
for name, chunkmanager in loaded_entrypoints.items()
if chunkmanager.available
}
return available_chunkmanagers
def guess_chunkmanager(
manager: str | ChunkManagerEntrypoint[Any] | None,
) -> ChunkManagerEntrypoint[Any]:
"""
Get namespace of chunk-handling methods, guessing from what's available.
If the name of a specific ChunkManager is given (e.g. "dask"), then use that.
Else use whatever is installed, defaulting to dask if there are multiple options.
"""
available_chunkmanagers = list_chunkmanagers()
if manager is None:
if len(available_chunkmanagers) == 1:
# use the only option available
manager = next(iter(available_chunkmanagers.keys()))
else:
# use the one in options (default dask)
manager = OPTIONS["chunk_manager"]
if isinstance(manager, str):
if manager not in available_chunkmanagers and manager in KNOWN_CHUNKMANAGERS:
raise ImportError(
f"chunk manager {manager!r} is not available."
f" Please make sure {KNOWN_CHUNKMANAGERS[manager]!r} is installed"
" and importable."
)
elif len(available_chunkmanagers) == 0:
raise ImportError(
"no chunk managers available. Try installing `dask` or another package"
" that provides a chunk manager."
)
elif manager not in available_chunkmanagers:
raise ValueError(
f"unrecognized chunk manager {manager!r} - must be one of the installed"
f" chunk managers: {list(available_chunkmanagers)}"
)
return available_chunkmanagers[manager]
elif isinstance(manager, ChunkManagerEntrypoint):
# already a valid ChunkManager so just pass through
return manager
else:
raise TypeError(
"manager must be a string or instance of ChunkManagerEntrypoint,"
f" but received type {type(manager)}"
)
def get_chunked_array_type(*args: Any) -> ChunkManagerEntrypoint[Any]:
"""
Detects which parallel backend should be used for given set of arrays.
Also checks that all arrays are of same chunking type (i.e. not a mix of cubed and dask).
"""
# TODO this list is probably redundant with something inside xarray.apply_ufunc
ALLOWED_NON_CHUNKED_TYPES = {int, float, np.ndarray}
chunked_arrays = [
a
for a in args
if is_chunked_array(a) and type(a) not in ALLOWED_NON_CHUNKED_TYPES
]
# Asserts all arrays are the same type (or numpy etc.)
chunked_array_types = {type(a) for a in chunked_arrays}
if len(chunked_array_types) > 1:
raise TypeError(
f"Mixing chunked array types is not supported, but received multiple types: {chunked_array_types}"
)
elif len(chunked_array_types) == 0:
raise TypeError("Expected a chunked array but none were found")
# iterate over defined chunk managers, seeing if each recognises this array type
chunked_arr = chunked_arrays[0]
chunkmanagers = list_chunkmanagers()
selected = [
chunkmanager
for chunkmanager in chunkmanagers.values()
if chunkmanager.is_chunked_array(chunked_arr)
]
if not selected:
raise TypeError(
f"Could not find a Chunk Manager which recognises type {type(chunked_arr)}"
)
elif len(selected) >= 2:
raise TypeError(f"Multiple ChunkManagers recognise type {type(chunked_arr)}")
else:
return selected[0]
| ChunkedArrayMixinProtocol |
python | falconry__falcon | tests/test_headers.py | {
"start": 8373,
"end": 8652
} | class ____:
def on_get(self, req, resp):
resp.media = {
'raw': req.headers,
'lower': req.headers_lower,
}
def on_get_header(self, req, resp, header):
resp.media = {header.lower(): req.get_header(header)}
| HeadersDebugResource |
python | walkccc__LeetCode | solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py | {
"start": 0,
"end": 82
} | class ____:
def findGameWinner(self, n: int) -> bool:
return n % 6 != 1
| Solution |
python | pandas-dev__pandas | web/tests/test_pandas_web.py | {
"start": 147,
"end": 2154
} | class ____:
def __init__(self, status_code: int, response: dict) -> None:
self.status_code = status_code
self._resp = response
def json(self):
return self._resp
@staticmethod
def raise_for_status() -> None:
return
@pytest.fixture
def context() -> dict:
return {
"main": {"github_repo_url": "pandas-dev/pandas"},
"target_path": "test_target_path",
}
@pytest.fixture
def mock_response(monkeypatch, request) -> None:
def mocked_resp(*args, **kwargs):
status_code, response = request.param
return MockResponse(status_code, response)
monkeypatch.setattr(requests, "get", mocked_resp)
_releases_list = [
{
"prerelease": False,
"published_at": "2024-01-19T03:34:05Z",
"tag_name": "v1.5.6",
"assets": None,
},
{
"prerelease": False,
"published_at": "2023-11-10T19:07:37Z",
"tag_name": "v2.1.3",
"assets": None,
},
{
"prerelease": False,
"published_at": "2023-08-30T13:24:32Z",
"tag_name": "v2.1.0",
"assets": None,
},
{
"prerelease": False,
"published_at": "2023-04-30T13:24:32Z",
"tag_name": "v2.0.0",
"assets": None,
},
{
"prerelease": True,
"published_at": "2023-01-19T03:34:05Z",
"tag_name": "v1.5.3xd",
"assets": None,
},
{
"prerelease": False,
"published_at": "2027-01-19T03:34:05Z",
"tag_name": "v10.0.1",
"assets": None,
},
]
@pytest.mark.parametrize("mock_response", [(200, _releases_list)], indirect=True)
def test_web_preprocessor_creates_releases(mock_response, context) -> None:
m = mock_open()
with patch("builtins.open", m):
context = Preprocessors.home_add_releases(context)
release_versions = [release["name"] for release in context["releases"]]
assert release_versions == ["10.0.1", "2.1.3", "2.0.0", "1.5.6"]
| MockResponse |
python | huggingface__transformers | src/transformers/models/jetmoe/modeling_jetmoe.py | {
"start": 12024,
"end": 18917
} | class ____(nn.Module):
"""
A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: JetMoeConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.input_size = config.hidden_size
self.hidden_size = config.kv_channels * config.num_key_value_heads
self.top_k = config.num_experts_per_tok
self.bias = torch.nn.Parameter(torch.empty(self.input_size))
self.input_linear = JetMoeParallelExperts(self.num_experts, self.input_size, self.hidden_size)
self.output_linear = JetMoeParallelExperts(self.num_experts, self.hidden_size, self.input_size)
self.router = JetMoeTopKGating(
input_size=self.input_size,
num_experts=self.num_experts,
top_k=self.top_k,
)
def map(self, layer_input):
"""
Map inputs to attention experts according to routing decision and compute query projection inside each experts.
"""
# Compute gating topology
bsz, length, emb_size = layer_input.size()
layer_input = layer_input.reshape(-1, emb_size) # [bsz * length, emb_size]
index_sorted_experts, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
topo_info = (index_sorted_experts, batch_index, batch_gates, expert_size)
# Group inputs according to topology and compute query projection
expert_inputs = layer_input[batch_index] # [bsz * length * top_k, emb_size]
expert_outputs = self.input_linear(expert_inputs, expert_size) # [bsz * length * top_k, hidden_size]
# Ungroup queries back to original order
zeros = torch.zeros(
(bsz * length * self.top_k, self.hidden_size), dtype=expert_outputs.dtype, device=expert_outputs.device
)
layer_output = zeros.index_add(0, index_sorted_experts, expert_outputs)
layer_output = layer_output.view(bsz, length, self.top_k, -1) # [bsz, length, top_k, hidden_size]
return layer_output, router_logits, topo_info
def reduce(self, layer_input, topo_info):
"""
Compute output projection inside each attention experts and merge the outputs of different experts.
"""
bsz, length, k, hidden_size = layer_input.size()
layer_input = layer_input.reshape(-1, hidden_size) # [bsz * length * k, hidden_size]
index_sorted_experts, batch_index, batch_gates, expert_size = topo_info
# Group inputs according to topology and compute output projection
expert_inputs = layer_input[index_sorted_experts] # [bsz * length * top_k, hidden_size]
expert_outputs = self.output_linear(expert_inputs, expert_size) # [bsz * length * top_k, emb_size]
# Apply gates to attention expert outputs
expert_outputs = expert_outputs * batch_gates[:, None]
# Ungroup and merge outputs to original order
zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
layer_output = zeros.index_add(0, batch_index, expert_outputs)
layer_output = layer_output.view(bsz, length, self.input_size)
layer_output = layer_output + self.bias
return layer_output
def forward(self, layer_input):
raise NotImplementedError("This module doesn't support call and forward.")
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| JetMoeMoA |
python | pytorch__pytorch | test/distributed/test_dynamo_distributed.py | {
"start": 4262,
"end": 4790
} | class ____(torch.nn.Module):
def __init__(self, device):
super().__init__()
self.linear = torch.nn.Linear(1, 1)
self.__dict__["forced_linear"] = torch.nn.Linear(1, 1).to(device=device)
self.counter = 0
def forward(self, x):
self.counter += 1
return x * self.linear(x) * self.forced_linear.weight
def get_forced_getattr_module(device):
mod = ForcedGetAttrMod(device).to(device=device)
x = torch.randn(1, 1, device=device)
return mod, x, mod(x)
| ForcedGetAttrMod |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 1883,
"end": 1964
} | class ____(Parent):
def _protected(self): # [method-hidden]
pass
| Child |
python | scrapy__scrapy | tests/test_scheduler.py | {
"start": 9662,
"end": 9789
} | class ____(
DownloaderAwareSchedulerTestMixin, TestSchedulerInMemoryBase
):
pass
| TestSchedulerWithDownloaderAwareInMemory |
python | dask__distributed | distributed/dashboard/components/shared.py | {
"start": 15563,
"end": 20315
} | class ____(DashboardComponent):
def __init__(self, worker, height=150, last_count=None, **kwargs):
self.worker = worker
names = worker.monitor.quantities
self.last_count = 0
if last_count is not None:
names = worker.monitor.range_query(start=last_count)
self.last_count = last_count
self.source = ColumnDataSource({name: [] for name in names})
self.label_source = ColumnDataSource(
{
"x": [5] * 3,
"y": [70, 55, 40],
"cpu": ["max: 45%", "min: 45%", "mean: 45%"],
"memory": ["max: 133.5MiB", "min: 23.6MiB", "mean: 115.4MiB"],
}
)
update(self.source, self.get_data())
x_range = DataRange1d(follow="end", follow_interval=20000, range_padding=0)
tools = "reset,xpan,xwheel_zoom"
self.cpu = figure(
title="CPU",
x_axis_type="datetime",
height=height,
tools=tools,
toolbar_location="above",
x_range=x_range,
**kwargs,
)
self.cpu.line(source=self.source, x="time", y="cpu")
self.cpu.yaxis.axis_label = "Percentage"
self.cpu.add_layout(
LabelSet(
x="x",
y="y",
x_units="screen",
y_units="screen",
text="cpu",
text_font_size="1em",
source=self.label_source,
)
)
self.mem = figure(
title="Memory",
x_axis_type="datetime",
height=height,
tools=tools,
toolbar_location="above",
x_range=x_range,
**kwargs,
)
self.mem.line(source=self.source, x="time", y="memory")
self.mem.yaxis.axis_label = "Bytes"
self.mem.add_layout(
LabelSet(
x="x",
y="y",
x_units="screen",
y_units="screen",
text="memory",
text_font_size="1em",
source=self.label_source,
)
)
self.bandwidth = figure(
title="Bandwidth",
x_axis_type="datetime",
height=height,
x_range=x_range,
tools=tools,
toolbar_location="above",
**kwargs,
)
self.bandwidth.line(
source=self.source,
x="time",
y="host_net_io.read_bps",
color="red",
legend_label="read",
)
self.bandwidth.line(
source=self.source,
x="time",
y="host_net_io.write_bps",
color="blue",
legend_label="write",
)
self.bandwidth.yaxis.axis_label = "Bytes / second"
# self.cpu.yaxis[0].formatter = NumeralTickFormatter(format='0%')
self.bandwidth.yaxis[0].formatter = NumeralTickFormatter(format="0.0b")
self.mem.yaxis[0].formatter = NumeralTickFormatter(format="0.0b")
plots = [self.cpu, self.mem, self.bandwidth]
if not WINDOWS:
self.num_fds = figure(
title="Number of File Descriptors",
x_axis_type="datetime",
height=height,
x_range=x_range,
tools=tools,
toolbar_location="above",
**kwargs,
)
self.num_fds.line(source=self.source, x="time", y="num_fds")
plots.append(self.num_fds)
if "sizing_mode" in kwargs:
kw = {"sizing_mode": kwargs["sizing_mode"]}
else:
kw = {}
if not WINDOWS:
self.num_fds.y_range.start = 0
self.mem.y_range.start = 0
self.cpu.y_range.start = 0
self.bandwidth.y_range.start = 0
self.root = column(*plots, **kw)
self.worker.monitor.update()
def get_data(self):
d = self.worker.monitor.range_query(start=self.last_count)
d["time"] = [x * 1000 for x in d["time"]]
self.last_count = self.worker.monitor.count
return d
@without_property_validation
@log_errors
def update(self):
def mean(x):
return sum(x) / len(x)
self.source.stream(self.get_data(), 1000)
self.label_source.data["cpu"] = [
"{}: {:.1f}%".format(f.__name__, f(self.source.data["cpu"]))
for f in [min, max, mean]
]
self.label_source.data["memory"] = [
"{}: {}".format(
f.__name__, dask.utils.format_bytes(f(self.source.data["memory"]))
)
for f in [min, max, mean]
]
| SystemMonitor |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3490,
"end": 3620
} | class ____(APIStatusError):
status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
| NotFoundError |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataplex.py | {
"start": 86025,
"end": 88637
} | class ____(GoogleBaseAsyncHook):
"""
Asynchronous Hook for Google Cloud Dataplex APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
sync_hook_class = DataplexHook
def __init__(
self,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(gcp_conn_id=gcp_conn_id, impersonation_chain=impersonation_chain, **kwargs)
async def get_dataplex_data_scan_client(self) -> DataScanServiceAsyncClient:
"""Return DataScanServiceAsyncClient."""
client_options = ClientOptions(api_endpoint="dataplex.googleapis.com:443")
return DataScanServiceAsyncClient(
credentials=(await self.get_sync_hook()).get_credentials(),
client_info=CLIENT_INFO,
client_options=client_options,
)
@GoogleBaseHook.fallback_to_default_project_id
async def get_data_scan_job(
self,
project_id: str,
region: str,
data_scan_id: str | None = None,
job_id: str | None = None,
retry: AsyncRetry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> Any:
"""
Get a DataScan Job resource.
:param project_id: Required. The ID of the Google Cloud project that the lake belongs to.
:param region: Required. The ID of the Google Cloud region that the lake belongs to.
:param data_scan_id: Required. DataScan identifier.
:param job_id: Required. The resource name of the DataScanJob:
projects/{project_id}/locations/{region}/dataScans/{data_scan_id}/jobs/{data_scan_job_id}
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = await self.get_dataplex_data_scan_client()
name = f"projects/{project_id}/locations/{region}/dataScans/{data_scan_id}/jobs/{job_id}"
result = await client.get_data_scan_job(
request={"name": name, "view": "FULL"},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return result
| DataplexAsyncHook |
python | getsentry__sentry | src/sentry/new_migrations/monkey/models.py | {
"start": 373,
"end": 3905
} | class ____(DeleteModel):
def __init__(self, *args, deletion_action: DeletionAction, **kwargs):
super().__init__(*args, **kwargs)
self.deletion_action = deletion_action
def state_forwards(self, app_label: str, state: SentryProjectState) -> None: # type: ignore[override]
if self.deletion_action == DeletionAction.MOVE_TO_PENDING:
model = state.apps.get_model(app_label, self.name)
fields_with_constraints = [
f.name for f in model._meta.fields if getattr(f, "db_constraint", False)
]
if fields_with_constraints:
raise UnsafeOperationException(
"Foreign key db constraints must be removed before dropping "
f"{app_label}.{self.name}. Fields with constraints: {fields_with_constraints}"
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-tables"
)
state.remove_model(app_label, self.name_lower, deletion_action=self.deletion_action)
def database_forwards(
self,
app_label: str,
schema_editor: SafePostgresDatabaseSchemaEditor, # type: ignore[override]
from_state: SentryProjectState, # type: ignore[override]
to_state: SentryProjectState, # type: ignore[override]
) -> None:
if self.deletion_action == DeletionAction.MOVE_TO_PENDING:
return
model = from_state.get_pending_deletion_model(app_label, self.name)
table = model._meta.db_table
# Check if we can determine the model's database to detect missing
# historical_silo_assignments entries
resolved_db = None
for db_router in router.routers:
if hasattr(db_router, "_db_for_table"):
resolved_db = db_router._db_for_table(table, app_label)
if resolved_db is not None:
break
# If we can't determine the database and we're in CI/tests, fail loudly
# This indicates the table is missing from historical_silo_assignments
if resolved_db is None and in_test_environment():
raise ValueError(
f"Cannot determine database for deleted model {app_label}.{self.name} "
f"(table: {table}). This table must be added to historical_silo_assignments "
f"in src/sentry/db/router.py (or getsentry/db/router.py for getsentry models) "
f"with the appropriate SiloMode before the deletion migration can run. "
)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.delete_model(model, is_safe=True)
def database_backwards(
self,
app_label: str,
schema_editor: SafePostgresDatabaseSchemaEditor, # type: ignore[override]
from_state: SentryProjectState, # type: ignore[override]
to_state: SentryProjectState, # type: ignore[override]
) -> None:
if self.deletion_action == DeletionAction.MOVE_TO_PENDING:
return
model = to_state.get_pending_deletion_model(app_label, self.name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.create_model(model)
def describe(self) -> str:
if self.deletion_action == DeletionAction.MOVE_TO_PENDING:
return f"Moved model {self.name} to pending deletion state"
else:
return super().describe()
| SafeDeleteModel |
python | ansible__ansible | test/units/parsing/yaml/test_dumper.py | {
"start": 1512,
"end": 4437
} | class ____(unittest.TestCase, YamlTestUtils):
def setUp(self):
self.vault_password = "hunter42"
vault_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('vault_secret', vault_secret)]
self.good_vault = vault.VaultLib(self.vault_secrets)
self.vault = self.good_vault
self.stream = self._build_stream()
self.dumper = AnsibleDumper
def _build_stream(self, yaml_text=None):
text = yaml_text or u''
stream = io.StringIO(text)
return stream
def _loader(self, stream):
return AnsibleLoader(stream)
def test_bytes(self):
b_text = u'tréma'.encode('utf-8')
unsafe_object = TrustedAsTemplate().tag(b_text)
yaml_out = self._dump_string(unsafe_object, dumper=self.dumper)
stream = self._build_stream(yaml_out)
data_from_yaml = yaml.load(stream, Loader=AnsibleLoader)
result = b_text
self.assertEqual(result, data_from_yaml)
def test_unicode(self):
u_text = u'nöel'
unsafe_object = TrustedAsTemplate().tag(u_text)
yaml_out = self._dump_string(unsafe_object, dumper=self.dumper)
stream = self._build_stream(yaml_out)
data_from_yaml = yaml.load(stream, Loader=AnsibleLoader)
self.assertEqual(u_text, data_from_yaml)
def test_undefined(self):
with pytest.raises(MarkerError):
self._dump_string(_DEFAULT_UNDEF, dumper=self.dumper)
@pytest.mark.parametrize("filter_impl, expected_output", [
(to_yaml, "!vault |-\n ciphertext\n"),
(to_nice_yaml, "!vault |-\n ciphertext\n"),
])
def test_vaulted_value_dump(
filter_impl: t.Callable,
expected_output: str,
mocker: pytest_mock.MockerFixture
) -> None:
"""Validate that strings tagged VaultedValue are represented properly."""
value = VaultedValue(ciphertext="ciphertext").tag("secret plaintext")
from ansible.utils.display import Display
_deprecated_spy = mocker.spy(Display(), 'deprecated')
res = filter_impl(value)
assert res == expected_output
_test_tag = Deprecated(msg="test")
@pytest.mark.parametrize("value, expected", (
(CustomMapping(dict(a=1)), "a: 1"),
(CustomSequence([1]), "- 1"),
(_test_tag.tag(dict(a=1)), "a: 1"),
(_test_tag.tag([1]), "- 1"),
(_test_tag.tag(1), "1"),
(_test_tag.tag("Ansible"), "Ansible"),
))
def test_dump(value: t.Any, expected: str) -> None:
"""Verify supported types can be dumped."""
result = yaml.dump(value, Dumper=AnsibleDumper).strip()
assert result == expected
def test_dump_tripwire() -> None:
"""Verify dumping a tripwire trips it."""
class Tripped(Exception):
pass
class CustomTripwire(Tripwire):
def trip(self) -> t.NoReturn:
raise Tripped()
with pytest.raises(Tripped):
yaml.dump(CustomTripwire(), Dumper=AnsibleDumper)
| TestAnsibleDumper |
python | walkccc__LeetCode | solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py | {
"start": 0,
"end": 353
} | class ____:
def longestSubsequence(self, s: str, k: int) -> int:
oneCount = 0
num = 0
pow = 1
# Take as many 1s as possible from the right.
for i in reversed(range(len(s))):
if num + pow > k:
break
if s[i] == '1':
oneCount += 1
num += pow
pow *= 2
return s.count('0') + oneCount
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_quote_name10.py | {
"start": 314,
"end": 1510
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("quote_name10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
sheet_name = "Sh.eet.1"
worksheet = workbook.add_worksheet(sheet_name)
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [46905600, 46796800]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
worksheet.repeat_rows(0, 1)
worksheet.set_portrait()
worksheet.vertical_dpi = 200
chart.add_series({"values": [sheet_name, 0, 0, 4, 0]})
chart.add_series({"values": [sheet_name, 0, 1, 4, 1]})
chart.add_series({"values": [sheet_name, 0, 2, 4, 2]})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | wandb__wandb | tests/system_tests/test_launch/test_launch_kubernetes.py | {
"start": 7904,
"end": 8060
} | class ____(dict):
# use a dict to mock an object
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
| MockDict |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 35777,
"end": 37319
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
MSE loss.
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, -1)`):
Prediction outputs of the time series modeling heads.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
loc: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
scale: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
"""
loss: Optional[torch.FloatTensor] = None
prediction_outputs: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
loc: Optional[torch.FloatTensor] = None
scale: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`PatchTSTForClassification`].
"""
)
| PatchTSTForPredictionOutput |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent.py | {
"start": 11176,
"end": 11453
} | class ____(BaseOutputParser[AgentAction | AgentFinish]):
"""Base class for parsing agent output into agent action/finish."""
@abstractmethod
def parse(self, text: str) -> AgentAction | AgentFinish:
"""Parse text into agent action/finish."""
| AgentOutputParser |
python | huggingface__transformers | src/transformers/models/bark/configuration_bark.py | {
"start": 5893,
"end": 6924
} | class ____(BarkSubModelConfig):
model_type = "coarse_acoustics"
base_config_key = "coarse_acoustics_config"
@add_start_docstrings(
BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig", model="BarkFineModel"),
"""
n_codes_total (`int`, *optional*, defaults to 8):
The total number of audio codebooks predicted. Used in the fine acoustics sub-model.
n_codes_given (`int`, *optional*, defaults to 1):
The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics
sub-models.
Example:
```python
>>> from transformers import BarkFineConfig, BarkFineModel
>>> # Initializing a Bark sub-module style configuration
>>> configuration = BarkFineConfig()
>>> # Initializing a model (with random weights) from the suno/bark style configuration
>>> model = BarkFineModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```""",
)
| BarkCoarseConfig |
python | allegroai__clearml | clearml/config/__init__.py | {
"start": 1505,
"end": 8626
} | class ____(object):
_config_sdk = None
@classmethod
def _init(cls) -> None:
if cls._config_sdk is None:
cls._config_sdk = ConfigWrapper.get("sdk")
@classmethod
def get(cls, *args: Any, **kwargs: Any) -> Any:
cls._init()
return cls._config_sdk.get(*args, **kwargs)
@classmethod
def set_overrides(cls, *args: Any, **kwargs: Any) -> None:
cls._init()
return cls._config_sdk.set_overrides(*args, **kwargs)
@classmethod
def clear_config_impl(cls) -> None:
cls._config_sdk = None
def deferred_config(
key: Optional[str] = None,
default: Any = Config.MISSING,
transform: Optional[Callable[[], Any]] = None,
multi: Optional[Iterable[Tuple[Any]]] = None,
) -> LazyEvalWrapper:
return LazyEvalWrapper(
callback=lambda: (
ConfigSDKWrapper.get(key, default)
if not multi
else next(
(ConfigSDKWrapper.get(*a) for a in multi if ConfigSDKWrapper.get(*a)),
None,
)
)
if transform is None
else (
transform()
if key is None
else transform(
ConfigSDKWrapper.get(key, default)
if not multi
else next(
(ConfigSDKWrapper.get(*a) for a in multi if ConfigSDKWrapper.get(*a)),
None,
) # noqa
)
)
)
config_obj = ConfigWrapper
config = ConfigSDKWrapper
""" Configuration object reflecting the merged SDK section of all available configuration files """
def get_cache_dir() -> Path:
cache_base_dir = Path( # noqa: F405
expandvars(
expanduser(
CLEARML_CACHE_DIR.get() # noqa: F405
or config.get("storage.cache.default_base_dir")
or DEFAULT_CACHE_DIR # noqa: F405
)
)
)
return cache_base_dir
def get_offline_dir(task_id: str = None) -> Path:
if not task_id:
return get_cache_dir() / "offline"
return get_cache_dir() / "offline" / task_id
def get_config_for_bucket(base_url: str, extra_configurations: Optional[List[Any]] = None) -> Any:
config_list = S3BucketConfigurations.from_config(config.get("aws.s3"))
for configuration in extra_configurations or []:
config_list.add_config(configuration)
return config_list.get_config_by_uri(base_url)
def get_remote_task_id() -> str:
return _running_remotely_task_id
def running_remotely() -> bool:
return bool(_running_remotely_task_id)
def get_log_to_backend(default: Optional[bool] = None) -> bool:
return LOG_TO_BACKEND_ENV_VAR.get(default=default) # noqa: F405
def get_node_count() -> Optional[int]:
# noinspection PyBroadException
try:
mpi_world_rank = int(os.environ.get("OMPI_COMM_WORLD_NODE_RANK", os.environ.get("PMI_RANK")))
return mpi_world_rank
except Exception:
pass
# noinspection PyBroadException
try:
mpi_rank = int(os.environ.get("OMPI_COMM_WORLD_RANK", os.environ.get("SLURM_JOB_NUM_NODES")))
return mpi_rank
except Exception:
pass
# check if we have pyTorch node/worker ID (only if torch was already imported)
if "torch" in sys.modules:
# noinspection PyBroadException
try:
from torch.utils.data.dataloader import get_worker_info # noqa
worker_info = get_worker_info()
if worker_info:
return int(worker_info.num_workers)
except Exception:
pass
return None
def get_node_id(default: int = 0) -> int:
node_id = NODE_ID_ENV_VAR.get() # noqa: F405
# noinspection PyBroadException
try:
mpi_world_rank = int(os.environ.get("OMPI_COMM_WORLD_NODE_RANK", os.environ.get("PMI_RANK")))
except Exception:
mpi_world_rank = None
# noinspection PyBroadException
try:
mpi_rank = int(
os.environ.get(
"OMPI_COMM_WORLD_RANK",
os.environ.get("SLURM_PROCID", os.environ.get("SLURM_NODEID")),
)
)
except Exception:
mpi_rank = None
# if we have no node_id, use the mpi rank
if node_id is None and (mpi_world_rank is not None or mpi_rank is not None):
node_id = mpi_world_rank if mpi_world_rank is not None else mpi_rank
# if node is still None, use the global RANK
if node_id is None:
# noinspection PyBroadException
try:
node_id = int(os.environ.get("RANK"))
except Exception:
pass
# if node is still None, use the default
if node_id is None:
node_id = default
torch_rank = None
# check if we have pyTorch node/worker ID (only if torch was already imported)
if "torch" in sys.modules:
# noinspection PyBroadException
try:
from torch.utils.data.dataloader import get_worker_info # noqa
worker_info = get_worker_info()
if not worker_info:
torch_rank = None
else:
w_id = worker_info.id
# noinspection PyBroadException
try:
torch_rank = int(w_id)
except Exception:
# guess a number based on wid hopefully unique value
import hashlib
h = hashlib.md5()
h.update(str(w_id).encode("utf-8"))
torch_rank = int(h.hexdigest(), 16)
except Exception:
torch_rank = None
# if we also have a torch rank add it to the node rank
if torch_rank is not None:
# Since we dont know the world rank, we assume it is not bigger than 10k
node_id = (10000 * node_id) + torch_rank
return node_id
def get_is_master_node() -> bool:
global __force_master_node
if __force_master_node:
return True
return get_node_id(default=0) == 0
def get_log_redirect_level() -> Optional[int]:
"""Returns which log level (and up) should be redirected to stderr. None means no redirection."""
value = LOG_STDERR_REDIRECT_LEVEL.get() # noqa: F405
try:
if value:
return logging._checkLevel(value) # noqa
except (ValueError, TypeError, AttributeError):
pass
def dev_worker_name() -> str:
return DEV_WORKER_NAME.get() # noqa: F405
def __set_is_master_node() -> Optional[bool]:
# noinspection PyBroadException
try:
# pop both set the first
env_a = os.environ.pop("CLEARML_FORCE_MASTER_NODE", None)
env_b = os.environ.pop("TRAINS_FORCE_MASTER_NODE", None)
force_master_node = env_a or env_b
except Exception:
force_master_node = None
if force_master_node is not None:
# noinspection PyBroadException
try:
force_master_node = bool(int(force_master_node))
except Exception:
force_master_node = None
return force_master_node
__force_master_node = __set_is_master_node()
| ConfigSDKWrapper |
python | pytorch__pytorch | test/jit/test_dataclasses.py | {
"start": 959,
"end": 1018
} | class ____(Enum):
A = 1
B = 2
@dataclass
| MixupScheme2 |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py | {
"start": 3268,
"end": 30237
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def testDocStringExamples(self):
"""Example from ragged_to_tensor.__doc__."""
rt = ragged_factory_ops.constant([[9, 8, 7], [], [6, 5], [4]])
dt = rt.to_tensor()
self.assertAllEqual(dt, [[9, 8, 7], [0, 0, 0], [6, 5, 0], [4, 0, 0]])
@parameterized.named_parameters(
# Simple 2D ragged tensors (with one ragged dimension)
{
'testcase_name': 'shape_2xN',
'rt_input': [[0, 1, 2], [], [3]],
'expected': [[0, 1, 2], [0, 0, 0], [3, 0, 0]]
},
{
'testcase_name': 'shape_2xN_default_0D',
'rt_input': [[0, 1, 2], [], [3]],
'default': 5,
'expected': [[0, 1, 2], [5, 5, 5], [3, 5, 5]]
},
{
'testcase_name': 'empty_first_row',
'rt_input': [[], [], [3, 4], []],
'expected': [[0, 0], [0, 0], [3, 4], [0, 0]]
},
{
'testcase_name': 'empty_last_row',
'rt_input': [[0, 1, 2], [], [3], []],
'expected': [[0, 1, 2], [0, 0, 0], [3, 0, 0], [0, 0, 0]]
},
{
'testcase_name': 'shape_4xN',
'rt_input': [[1, 2, 3], [], [4], [5, 6]],
'expected': [[1, 2, 3], [0, 0, 0], [4, 0, 0], [5, 6, 0]]
},
{
'testcase_name': 'shape_4xN_default_0D',
'rt_input': [[1, 2, 3], [], [4], [5, 6]],
'default': 9,
'expected': [[1, 2, 3], [9, 9, 9], [4, 9, 9], [5, 6, 9]]
},
{
'testcase_name': 'shape_2xN_already_dense',
'rt_input': [[6, 7, 8], [9, 10, 11]],
'expected': [[6, 7, 8], [9, 10, 11]],
},
{
'testcase_name': 'shape_2xN_string_already_dense',
'rt_input': [[b'a', b'b', b'c'],
[b'd', b'e', b'antidisestablishmentarianism']],
'ragged_rank': 1,
'expected': [[b'a', b'b', b'c'],
[b'd', b'e', b'antidisestablishmentarianism']],
},
# 3D ragged tensors with two ragged dimensions
{
'testcase_name': 'shape_4xNxM',
'rt_input': [[[1, 2], [], [3, 4]], [], [[5]], [[6, 7], [8]]],
'expected': [
[[1, 2], [0, 0], [3, 4]], #
[[0, 0], [0, 0], [0, 0]], #
[[5, 0], [0, 0], [0, 0]], #
[[6, 7], [8, 0], [0, 0]], #
]
},
{
'testcase_name': 'shape_4xNxM_default_0D',
'rt_input': [[[1, 2], [], [3, 4]], [], [[5]], [[6, 7], [8]]],
'default': 9,
'expected': [
[[1, 2], [9, 9], [3, 4]], #
[[9, 9], [9, 9], [9, 9]], #
[[5, 9], [9, 9], [9, 9]], #
[[6, 7], [8, 9], [9, 9]], #
]
},
{
'testcase_name': 'shape_1xNx1_default_0D',
'rt_input': [[[1], [2], [3]]],
'ragged_rank': 1,
'default': 0,
'expected': [[[1], [2], [3]]],
},
{
'testcase_name': 'shape_2xNx2_already_dense',
'rt_input': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]],
'ragged_rank': 1,
'expected': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]],
},
{
'testcase_name': 'shape_2xNx2_already_dense_default_1D',
'rt_input': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]],
'ragged_rank': 1,
'default': [31, 32],
'expected': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]],
},
{
'testcase_name': 'shape_2xNx2_string_already_dense',
'rt_input': [[[b'a', b'b'], [b'c', b'd'], [b'e', b'f']],
[[b'g', b'jalapeno'], [b'kangaroo', b'llama'],
[b'manzana', b'nectar']]],
'ragged_rank': 1,
'expected': [[[b'a', b'b'], [b'c', b'd'], [b'e', b'f']],
[[b'g', b'jalapeno'], [b'kangaroo', b'llama'],
[b'manzana', b'nectar']]],
},
# 3D ragged tensors with one ragged dimension
{
'testcase_name': 'shape_4xNx1_default_1D',
'rt_input': [[[1], [2], [3]], [], [[4]], [[5], [6]]],
'ragged_rank': 1,
'default': [9],
'expected': [[[1], [2], [3]],
[[9], [9], [9]],
[[4], [9], [9]],
[[5], [6], [9]]]
},
{
'testcase_name': 'shape_2xNx2_default_0D',
'rt_input': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15]]],
'ragged_rank': 1,
'default': 2,
'expected': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [2, 2]]],
},
{
'testcase_name': 'shape_2xNx2_default_1D',
'rt_input': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15]]],
'ragged_rank': 1,
'default': [2, 3],
'expected': [[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [2, 3]]],
},
# 4D ragged tensors with 3 ragged dimensions
{
'testcase_name': 'shape_1xNxMxK_default_0D',
'rt_input': [[[[1], [2]], [], [[3]]]],
'default': 9,
'expected': [[[[1], [2]], [[9], [9]], [[3], [9]]]],
},
# Broadcast default
{
'testcase_name': 'shape_2xNx2x2_default_2x1',
'rt_input': [[[[1, 2], [3, 4]]], []],
'ragged_rank': 1,
'default': [[5], [6]],
'expected': [[[[1, 2], [3, 4]]],
[[[5, 5], [6, 6]]]],
},
{
'testcase_name': 'shape_2xNx2x2_default_1x2',
'rt_input': [[[[1, 2], [3, 4]]], []],
'ragged_rank': 1,
'default': [[5, 6]],
'expected': [[[[1, 2], [3, 4]]],
[[[5, 6], [5, 6]]]],
},
# Explicit shape
{
'testcase_name': 'shape_4xN_with_crop',
'rt_input': [[0, 1, 2, 3], [], [4], []],
'shape': [2, 3],
'expected': [[0, 1, 2], [0, 0, 0]],
},
{
'testcase_name': 'shape_2xN_with_pad',
'rt_input': [[1, 2], [3]],
'shape': [3, 3],
'expected': [[1, 2, 0], [3, 0, 0], [0, 0, 0]],
},
{
'testcase_name': 'shape_4xN_with_crop_and_pad',
'rt_input': [[0, 1, 2, 3], [], [4], []],
'shape': [2, 8],
'expected': [[0, 1, 2, 3, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
},
{
'testcase_name': 'shape_4xN_with_tuple_shape',
'rt_input': [[0, 1, 2, 3], [], [4], []],
'shape': (2, 3),
'expected': [[0, 1, 2], [0, 0, 0]],
},
{
'testcase_name': 'shape_4xN_with_tensorshape_shape',
'rt_input': [[0, 1, 2, 3], [], [4], []],
'shape': tensor_shape.TensorShape([2, 3]),
'expected': [[0, 1, 2], [0, 0, 0]],
},
{
'testcase_name': 'shape_4xN_with_partial_shape',
'rt_input': [[0, 1, 2, 3], [], [4], []],
'shape': tensor_shape.TensorShape([2, None]),
'expected': [[0, 1, 2, 3], [0, 0, 0, 0]],
},
# Empty tensors
{
'testcase_name': 'shape_0xN',
'rt_input': [],
'ragged_rank': 1,
'expected': [],
'expected_shape': [0, 0],
},
{
'testcase_name': 'shape_0xNxM',
'rt_input': [],
'ragged_rank': 2,
'expected': [],
'expected_shape': [0, 0, 0],
},
# {
# 'testcase_name': 'shape_0xNx2',
# 'rt_input': [],
# 'ragged_rank': 1,
# 'inner_shape': [2],
# 'expected': [],
# 'expected_shape': [0, 0, 2],
# },
{
'testcase_name': 'shape_2xN_empty',
'rt_input': [[], []],
'expected': [[], []],
'expected_shape': [2, 0],
},
) # pyformat: disable
def testRaggedTensorToTensor(self,
rt_input,
expected,
ragged_rank=None,
inner_shape=None,
default=None,
shape=None,
expected_shape=None):
rt1 = ragged_factory_ops.constant(
rt_input, ragged_rank=ragged_rank, inner_shape=inner_shape)
rt2 = rebuild_ragged_tensor_with_value_rowids(rt1)
for rt in [rt1, rt2]:
for use_placeholder in [False, True]:
if use_placeholder:
if default is not None:
default = make_placeholder(default)
rt = nest.map_structure(make_placeholder, rt, expand_composites=True)
dt = rt.to_tensor(default_value=default, shape=shape)
self.assertIsInstance(dt, tensor_lib.Tensor)
self.assertEqual(rt.dtype, dt.dtype)
if shape is not None:
self.assertTrue(dt.shape.is_compatible_with(shape))
else:
self.assertTrue(dt.shape.is_compatible_with(rt.shape))
if expected_shape is not None:
expected = np.ndarray(expected_shape, buffer=np.array(expected))
self.assertAllEqual(dt, expected)
@parameterized.parameters([
{
'rt_input': [[1, 2, 3]],
'default': 'a',
'error_type': TypeError,
'error': r'Expected int32|Cannot convert',
},
{
'rt_input': [[1, 2, 3]],
'default': [0],
'error': r'default_value\.shape=.* and '
r'rt_input\.flat_values\.shape=.* are incompatible: '
r'default_value\.rank = 1 must be less than '
r'rt_input\.flat_values\.rank = 1'
},
{
'rt_input': [[[1, 2], [3, 4]], [[5, 6]]],
'ragged_rank': 1,
'default': [7, 8, 9],
'error': r'default_value\.shape.* and '
r'rt_input\.flat_values\.shape.* are incompatible: '
r'default_value\.shape\[-1\] = 3 but '
r'rt_input\.flat_values\.shape\[-1\] = 2'
},
{
'rt_input': [[1, 2, 3]],
'shape': [3, 3, 3],
'error': r'rt_input\.shape and shape=\[.,.,.\] are incompatible: '
r'rt_input\.rank = 2 but shape\.rank = 3'
},
{
'rt_input': [[[1, 2, 3]]],
'ragged_rank': 1,
'shape': [1, 1, 4],
'error': r'rt_input\.shape and shape=\[1,1,4\] are incompatible: '
r'rt_input\.shape\[2\] = 3 but shape\[2\] = 4'
},
])
def testError(self,
rt_input,
error,
error_type=(ValueError, errors.InvalidArgumentError),
default=None,
ragged_rank=None,
shape=None):
rt = ragged_factory_ops.constant(rt_input, ragged_rank=ragged_rank)
with self.assertRaisesRegex(error_type, error):
self.evaluate(rt.to_tensor(default_value=default, shape=shape))
rt_placeholder = nest.map_structure(
make_placeholder, rt, expand_composites=True)
with self.assertRaisesRegex(error_type, error):
self.evaluate(
rt_placeholder.to_tensor(default_value=default, shape=shape))
def test_shape_limit_shape_is_tensor(self):
input_data = ragged_factory_ops.constant([[0, 1, 2, 3], [], [4], []])
actual = input_data.to_tensor(
shape=constant_op.constant([2, 3], dtype=dtypes.int64))
self.assertAllEqual(actual, [[0, 1, 2], [0, 0, 0]])
self.assertEqual(actual.shape.as_list(), [2, 3])
def test_shape_limit_shape_is_tensor_unknown_rank(self):
input_data = ragged_factory_ops.constant([[0, 1, 2, 3], [], [4], []])
actual = input_data.to_tensor(
shape=constant_op.constant(-1, dtype=dtypes.int64))
self.assertAllEqual(
actual, [[0, 1, 2, 3], [0, 0, 0, 0], [4, 0, 0, 0], [0, 0, 0, 0]])
self.assertTrue(actual.shape.is_compatible_with([4, 4]))
def test_shape_limit_shape_is_tensor_unknown_dim(self):
input_data = ragged_factory_ops.constant([[0, 1, 2, 3], [], [4], []])
actual = input_data.to_tensor(
shape=constant_op.constant([2, -1], dtype=dtypes.int64))
self.assertAllEqual(actual, [[0, 1, 2, 3], [0, 0, 0, 0]])
self.assertTrue(actual.shape.is_compatible_with([2, None]))
def test_shape_limit_shape_is_tensor_int32(self):
input_data = ragged_factory_ops.constant([[0, 1, 2, 3], [], [4], []])
actual = input_data.to_tensor(
shape=constant_op.constant([2, 3], dtype=dtypes.int32))
self.assertAllEqual(actual, [[0, 1, 2], [0, 0, 0]])
self.assertEqual(actual.shape.as_list(), [2, 3])
def test_shape_expand_first_dim(self):
input_data = ragged_factory_ops.constant([[0, 1, 2], [], [3]])
actual = input_data.to_tensor(shape=[4, 4])
self.assertAllEqual(
actual, [[0, 1, 2, 0], [0, 0, 0, 0], [3, 0, 0, 0], [0, 0, 0, 0]])
self.assertEqual(actual.shape.as_list(), [4, 4])
def test_value_transposed(self):
# Check that transposed data is not an issue.
my_value = array_ops.transpose(
constant_op.constant([[0, 1, 2, 3], [4, 5, 6, 7]]))
input_data = RaggedTensor.from_value_rowids(
values=my_value,
value_rowids=constant_op.constant([0, 1, 2, 3], dtype=dtypes.int64),
nrows=constant_op.constant(4, dtype=dtypes.int64),
validate=True)
self.assertAllEqual(input_data, [[[0, 4]], [[1, 5]], [[2, 6]], [[3, 7]]])
def test_broadcast_default(self):
# The dense dimension here is 2 x 2
input_data = ragged_factory_ops.constant([[[[1, 2], [3, 4]]], []],
ragged_rank=1)
# This placeholder has a 2 x 1 dimension.
default_value = make_placeholder([[5], [6]])
actual = input_data.to_tensor(default_value=default_value)
expected = [[[[1, 2], [3, 4]]], [[[5, 5], [6, 6]]]]
self.assertAllEqual(actual, expected)
def test_broadcast_default_no_placeholder(self):
input_data = ragged_factory_ops.constant([[[[1, 2], [3, 4]]], []],
ragged_rank=1)
# default_value has a 2 x 1 dimension.
default_value = constant_op.constant([[5], [6]], shape=None)
actual = input_data.to_tensor(default_value=default_value)
expected = [[[[1, 2], [3, 4]]], [[[5, 5], [6, 6]]]]
self.assertAllEqual(actual, expected)
def test_shape_expand_second_dim(self):
input_data = ragged_factory_ops.constant([[0, 1, 2], [], [3], []])
actual = input_data.to_tensor(shape=[3, 4])
self.assertAllEqual(actual, [[0, 1, 2, 0], [0, 0, 0, 0], [3, 0, 0, 0]])
@parameterized.parameters(
([2, 3, 4], None, [2, 3, 4]),
([2, 3, 4], [None, None, None], [2, 3, 4]),
([2, 3, 4], [None, 3, None], [2, 3, 4]),
([2, 3, 4], [None, 3, 4], [2, 3, 4]),
([2, 3, 4], [2, 3, 4], [2, 3, 4]),
)
def test_preserve_shape_roundtrip(
self, input_shape, to_tensor_shape, expected_shape):
tensor = array_ops.zeros(input_shape)
ragged_from_tensor = RaggedTensor.from_tensor(tensor, ragged_rank=2)
recovered_tensor = ragged_from_tensor.to_tensor(shape=to_tensor_shape)
self.assertAllEqual(tensor.shape.as_list(), expected_shape)
self.assertAllEqual(ragged_from_tensor.shape.as_list(), expected_shape)
self.assertAllEqual(recovered_tensor.shape.as_list(), expected_shape)
def test_empty_tensor_with_shape(self):
input_data = RaggedTensor.from_value_rowids(
values=constant_op.constant([], dtype=dtypes.int64),
value_rowids=constant_op.constant([], dtype=dtypes.int64),
nrows=constant_op.constant(2, dtype=dtypes.int64),
validate=True)
actual = input_data.to_tensor(default_value=3, shape=[2, 3])
self.assertAllEqual(actual, [[3, 3, 3], [3, 3, 3]])
# pylint: disable=bad-whitespace
@parameterized.named_parameters([
dict(
testcase_name = '2d_default_shape',
shape = None,
rt_value = [[1, 2, 3], [4], [5, 6]],
rt_grad = [[9, 8, 7], [6], [3, 2]],
default_value = 0,
default_grad = sum([5, 4, 1]),
output_value = [[1, 2, 3], [4, 0, 0], [5, 6, 0]],
output_grad = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]),
dict(
testcase_name = '2d_pad',
shape = [4, 4],
rt_value = [[1, 2, 3], [4], [5, 6]],
rt_grad = [[9, 8, 7], [5], [1, 0]],
default_value = 0,
default_grad = sum([6, 4, 3, 2, 1, 2, 3, 4, 5, 6]),
output_value = [
[1, 2, 3, 0], [4, 0, 0, 0], [5, 6, 0, 0], [0, 0, 0, 0]],
output_grad = [
[9, 8, 7, 6], [5, 4, 3, 2], [1, 0, 1, 2], [3, 4, 5, 6]]),
dict(
testcase_name = '2d_pad_and_crop',
shape = [5, 3],
rt_value = [[1, 2, 3], [4], [5, 6, 7, 8, 9], [8]],
rt_grad = [[9, 8, 7], [6], [3, 2, 1, 0, 0], [2]],
default_value = 0,
default_grad = sum([5, 4, 3, 4, 5, 6, 7]),
output_value = [
[1, 2, 3], [4, 0, 0], [5, 6, 7], [8, 0, 0], [0, 0, 0]],
output_grad = [
[9, 8, 7], [6, 5, 4], [3, 2, 1], [2, 3, 4], [5, 6, 7]]),
dict(
testcase_name = '3d_rrank_2',
shape = [2, 2, 2],
rt_value = [[[9, 8, 7], [6]], [[5, 4]]],
rt_grad = [[[1, 2, 0], [3]], [[5, 6]]],
default_value = 3,
default_grad = sum([4, 7, 8]),
output_value = [[[9, 8], [6, 3]], [[5, 4], [3, 3]]],
output_grad = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
dict(
testcase_name = '3d_rrank_1_with_0d_default',
ragged_rank = 1,
shape = [2, 2, 2],
rt_value = [[[9, 8], [7, 6]], [[5, 4]]],
rt_grad = [[[1, 2], [3, 4]], [[5, 6]]],
default_value = 3,
default_grad = sum([7, 8]),
output_value = [[[9, 8], [7, 6]], [[5, 4], [3, 3]]],
output_grad = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
dict(
testcase_name = '3d_rrank_1_with_1d_default',
ragged_rank = 1,
shape = [2, 2, 2],
rt_value = [[[9, 8], [7, 6]], [[5, 4]]],
rt_grad = [[[1, 2], [3, 4]], [[5, 6]]],
default_value = [3, 2],
default_grad = [7, 8],
output_value = [[[9, 8], [7, 6]], [[5, 4], [3, 2]]],
output_grad = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
dict(
testcase_name = '3d_rrank_1_with_1d_broadcast_default',
ragged_rank = 1,
shape = [2, 2, 2],
rt_value = [[[9, 8], [7, 6]], [[5, 4]]],
rt_grad = [[[1, 2], [3, 4]], [[5, 6]]],
default_value = [3],
default_grad = [7 + 8],
output_value = [[[9, 8], [7, 6]], [[5, 4], [3, 3]]],
output_grad = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]),
dict(
testcase_name = '4d_rrank_1_with_2d_default',
ragged_rank = 1,
shape = [3, 3, 2, 1],
rt_value = [[[[9], [8]], [[7], [6]]], [[[5], [4]]]],
rt_grad = [[[[1], [2]], [[3], [4]]], [[[7], [8]]]],
default_value = [[3], [2]],
default_grad = [[5 + 9 + 2 + 4 + 6 + 8], [6 + 1 + 3 + 5 + 7 + 9]],
output_value = [[[[9], [8]], [[7], [6]], [[3], [2]]],
[[[5], [4]], [[3], [2]], [[3], [2]]],
[[[3], [2]], [[3], [2]], [[3], [2]]]],
output_grad = [[[[1], [2]], [[3], [4]], [[5], [6]]],
[[[7], [8]], [[9], [1]], [[2], [3]]],
[[[4], [5]], [[6], [7]], [[8], [9]]]]),
dict(
testcase_name = '4d_rrank_1_with_with_0d_default',
ragged_rank = 1,
shape = [3, 3, 2, 1],
rt_value = [[[[9], [8]], [[7], [6]]], [[[5], [4]]]],
rt_grad = [[[[1], [2]], [[3], [4]]], [[[7], [8]]]],
default_value = 3,
default_grad = 5 + 9 + 2 + 4 + 6 + 8 + 6 + 1 + 3 + 5 + 7 + 9,
output_value = [[[[9], [8]], [[7], [6]], [[3], [3]]],
[[[5], [4]], [[3], [3]], [[3], [3]]],
[[[3], [3]], [[3], [3]], [[3], [3]]]],
output_grad = [[[[1], [2]], [[3], [4]], [[5], [6]]],
[[[7], [8]], [[9], [1]], [[2], [3]]],
[[[4], [5]], [[6], [7]], [[8], [9]]]]),
dict(
testcase_name = 'zero_size',
shape = [0, 0],
rt_value = [[9, 8], [7, 6, 5], [4]],
rt_grad = [[0, 0], [0, 0, 0], [0]],
default_value = 3,
default_grad = 0,
output_value = [],
output_grad = [])
]) # pyformat: disable
def test_gradient(self,
shape,
rt_value,
rt_grad,
default_value,
default_grad,
output_value,
output_grad,
ragged_rank=None):
"""Tests that ragged_to_dense generates the right gradient.
Args:
shape: The `shape` arg for `ragged_to_dense`.
rt_value: The `rt_input` arg for `ragged_to_dense`.
rt_grad: The expected gradient for `rt_value`. Corresponds 1:1 with
`rt_value`.
default_value: The `default_value` arg for `ragged_to_dense`.
default_grad: The expected gradient for `default_value`. Corresponds 1:1
with `default_value`.
output_value: The expected output of `ragged_to_dense`.
output_grad: The gradient for the output (used to generate the gradients
`rt_grad` and `default_grad`). Corresponds 1:1 with `output_value`.
ragged_rank: Ragged rank for `rt_value`.
"""
rt_value = ragged_factory_ops.constant(
rt_value, dtype=dtypes.float32, ragged_rank=ragged_rank)
rt_grad = ragged_factory_ops.constant(
rt_grad, dtype=dtypes.float32, ragged_rank=ragged_rank)
default_value = constant_op.constant(default_value, dtype=dtypes.float32)
default_grad = constant_op.constant(default_grad, dtype=dtypes.float32)
output_value = constant_op.constant(
output_value, dtype=dtypes.float32, shape=shape)
output_grad = constant_op.constant(
output_grad, dtype=dtypes.float32, shape=shape)
shape = tensor_shape.as_shape(shape)
# There are different code paths for ragged_to_dense, depending on whether
# the RaggedTensor was created from row_splits or value_rowids. Make sure
# that we test both.
for partition_type in ['row_splits', 'value_rowids']:
rt_val = self.rt_with_partition_type(rt_value, partition_type)
if context.executing_eagerly():
self._test_gradient_helper(rt_val, default_value, shape, output_grad,
output_value, rt_grad, default_grad)
else:
# There are different code paths when computing the gradient for
# default_value, depending on whether shape info is statically
# available; make sure that we test all code paths.
for shape_info in ['known', 'unknown_dims', 'unknown_rank']:
rt_val = self.wrap_in_placeholder(rt_val, shape_info)
default_val = self.wrap_in_placeholder(default_value, shape_info)
shape_val = self.wrap_in_placeholder(shape, shape_info)
self._test_gradient_helper(rt_val, default_val, shape_val,
output_grad, output_value, rt_grad,
default_grad)
def _test_gradient_helper(self, rt_val, default_val, shape_val, output_grad,
expected_output_val, expected_rt_grad,
expected_default_grad):
if context.executing_eagerly():
with backprop.GradientTape() as tape:
tape.watch([rt_val, default_val])
out = rt_val.to_tensor(default_val, shape=shape_val)
actual_rt_grad, actual_default_grad = tape.gradient(
out, (rt_val, default_val), output_gradients=output_grad)
else:
out = rt_val.to_tensor(default_val, shape=shape_val)
actual_rt_grad, actual_default_grad = gradients_impl.gradients(
ys=out, xs=(rt_val, default_val), grad_ys=output_grad)
self.assertAllClose(out, expected_output_val)
self.assertIsInstance(actual_rt_grad, RaggedTensor)
self.assertAllClose(actual_rt_grad, expected_rt_grad)
self.assertAllClose(actual_default_grad, expected_default_grad)
def rt_with_partition_type(self, rt, partition_type):
if isinstance(rt, tensor_lib.Tensor):
return rt
if partition_type == 'row_splits':
return rt
if partition_type == 'value_rowids':
return ragged_tensor.RaggedTensor.from_value_rowids(
self.rt_with_partition_type(rt.values, partition_type),
rt.value_rowids(), rt.nrows())
raise AssertionError('Unexpected partition_type %r' % partition_type)
def wrap_in_placeholder(self, arg, shape_info):
"""Wraps `arg` in a placeholder to limit static shape info.
Args:
arg: The value to wrap. A Tensor, RaggedTensor, or TensorShape.
shape_info: One of ['known', 'unknown_dims', 'unknown_rank'].
Returns:
* If shape_info is 'known': returns `arg`.
* If shape_info is 'unknown_dims': returns a placeholder wrapping `arg`
where the dimension sizes are unknown. If `arg` is a TensorShape,
then convert it to a vector first. If `arg` is a RaggedTensor, then
wrap the flat_values.
* If shape_info is 'unknown_rank': returns a placeholder wrapping `arg`
where the rank is unknown. If `arg` is a TensorShape, then convert it
to a vector first. If `arg` is a RaggedTensor, then wrap the
flat_values.
"""
if shape_info == 'known':
return arg
if isinstance(arg, ragged_tensor.RaggedTensor):
return arg.with_flat_values(
self.wrap_in_placeholder(arg.flat_values, shape_info))
if isinstance(arg, tensor_shape.TensorShape):
if arg.ndims is None:
return arg
arg = constant_op.constant(arg.as_list())
if shape_info == 'unknown_rank':
return array_ops.placeholder_with_default(arg, None)
if shape_info == 'unknown_dims':
return array_ops.placeholder_with_default(arg, [None] * arg.shape.rank)
raise AssertionError('Unexpected shape_info %r' % shape_info)
def test_shape_is_list_including_tensor_element(self):
rt = ragged_factory_ops.constant([[1, 2, 3], [4], [5, 6]])
result = rt.to_tensor(shape=[2, constant_op.constant(2)])
self.assertAllEqual(result, [[1, 2], [4, 0]])
| RaggedTensorToTensorOpTest |
python | cython__cython | Cython/Plex/Regexps.py | {
"start": 6310,
"end": 6789
} | class ____(RE):
"""
RawNewline is a low-level RE which matches a newline character.
For internal use only.
"""
nullable = 0
match_nl = 1
def build_machine(self, m, initial_state, final_state, match_bol, nocase):
if match_bol:
initial_state = self.build_opt(m, initial_state, BOL)
s = self.build_opt(m, initial_state, EOL)
s.add_transition((nl_code, nl_code + 1), final_state)
RawNewline = _RawNewline()
| _RawNewline |
python | numba__numba | numba/core/bytecode.py | {
"start": 1752,
"end": 8571
} | class ____(object):
'''
Attributes
----------
- offset:
byte offset of opcode
- opcode:
opcode integer value
- arg:
instruction arg
- lineno:
-1 means unknown
'''
__slots__ = 'offset', 'next', 'opcode', 'opname', 'arg', 'lineno'
def __init__(self, offset, opcode, arg, nextoffset):
self.offset = offset
self.next = nextoffset
self.opcode = opcode
self.opname = dis.opname[opcode]
self.arg = arg
self.lineno = -1 # unknown line number
@property
def is_jump(self):
return self.opcode in JUMP_OPS
@property
def is_terminator(self):
return self.opcode in TERM_OPS
def get_jump_target(self):
# With Python 3.10 the addressing of "bytecode" instructions has
# changed from using bytes to using 16-bit words instead. As a
# consequence the code to determine where a jump will lead had to be
# adapted.
# See also:
# https://bugs.python.org/issue26647
# https://bugs.python.org/issue27129
# https://github.com/python/cpython/pull/25069
assert self.is_jump
if PYVERSION in ((3, 13), (3, 14)):
if self.opcode in (dis.opmap[k]
for k in ["JUMP_BACKWARD",
"JUMP_BACKWARD_NO_INTERRUPT"]):
return self.next - (self.arg * 2)
elif PYVERSION in ((3, 12),):
if self.opcode in (dis.opmap[k]
for k in ["JUMP_BACKWARD"]):
return self.offset - (self.arg - 1) * 2
elif PYVERSION in ((3, 11), ):
if self.opcode in (dis.opmap[k]
for k in ("JUMP_BACKWARD",
"POP_JUMP_BACKWARD_IF_TRUE",
"POP_JUMP_BACKWARD_IF_FALSE",
"POP_JUMP_BACKWARD_IF_NONE",
"POP_JUMP_BACKWARD_IF_NOT_NONE",)):
return self.offset - (self.arg - 1) * 2
elif PYVERSION in ((3, 10),):
pass
else:
raise NotImplementedError(PYVERSION)
if PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13), (3, 14)):
if self.opcode in JREL_OPS:
return self.next + self.arg * 2
else:
assert self.opcode in JABS_OPS
return self.arg * 2 - 2
else:
raise NotImplementedError(PYVERSION)
def __repr__(self):
return '%s(arg=%s, lineno=%d)' % (self.opname, self.arg, self.lineno)
@property
def block_effect(self):
"""Effect of the block stack
Returns +1 (push), 0 (none) or -1 (pop)
"""
if self.opname.startswith('SETUP_'):
return 1
elif self.opname == 'POP_BLOCK':
return -1
else:
return 0
CODE_LEN = 1
ARG_LEN = 1
NO_ARG_LEN = 1
OPCODE_NOP = dis.opname.index('NOP')
if PYVERSION in ((3, 13), (3, 14)):
def _unpack_opargs(code):
buf = []
for i, start_offset, op, arg in dis._unpack_opargs(code):
buf.append((start_offset, op, arg))
for i, (start_offset, op, arg) in enumerate(buf):
if i + 1 < len(buf):
next_offset = buf[i + 1][0]
else:
next_offset = len(code)
yield (start_offset, op, arg, next_offset)
elif PYVERSION in ((3, 10), (3, 11), (3, 12)):
# Adapted from Lib/dis.py
def _unpack_opargs(code):
"""
Returns a 4-int-tuple of
(bytecode offset, opcode, argument, offset of next bytecode).
"""
extended_arg = 0
n = len(code)
offset = i = 0
while i < n:
op = code[i]
i += CODE_LEN
if op >= HAVE_ARGUMENT:
arg = code[i] | extended_arg
for j in range(ARG_LEN):
arg |= code[i + j] << (8 * j)
i += ARG_LEN
if PYVERSION in ((3, 12),):
# Python 3.12 introduced cache slots. We need to account for
# cache slots when we determine the offset of the next
# opcode. The number of cache slots is specific to each
# opcode and can be looked up in the _inline_cache_entries
# dictionary.
i += _inline_cache_entries[op] * INSTR_LEN
elif PYVERSION in ((3, 10), (3, 11)):
pass
else:
raise NotImplementedError(PYVERSION)
if op == EXTENDED_ARG:
# This is a deviation from what dis does...
# In python 3.11 it seems like EXTENDED_ARGs appear more
# often and are also used as jump targets. So as to not have
# to do "book keeping" for where EXTENDED_ARGs have been
# "skipped" they are replaced with NOPs so as to provide a
# legal jump target and also ensure that the bytecode
# offsets are correct.
yield (offset, OPCODE_NOP, arg, i)
extended_arg = arg << 8 * ARG_LEN
offset = i
continue
else:
arg = None
i += NO_ARG_LEN
if PYVERSION in ((3, 12),):
# Python 3.12 introduced cache slots. We need to account for
# cache slots when we determine the offset of the next
# opcode. The number of cache slots is specific to each
# opcode and can be looked up in the _inline_cache_entries
# dictionary.
i += _inline_cache_entries[op] * INSTR_LEN
elif PYVERSION in ((3, 10), (3, 11)):
pass
else:
raise NotImplementedError(PYVERSION)
extended_arg = 0
yield (offset, op, arg, i)
offset = i # Mark inst offset at first extended
else:
raise NotImplementedError(PYVERSION)
def _patched_opargs(bc_stream):
"""Patch the bytecode stream.
- Adds a NOP bytecode at the start to avoid jump target being at the entry.
"""
# Injected NOP
yield (0, OPCODE_NOP, None, _FIXED_OFFSET)
# Adjust bytecode offset for the rest of the stream
for offset, opcode, arg, nextoffset in bc_stream:
# If the opcode has an absolute jump target, adjust it.
if opcode in JABS_OPS:
arg += _FIXED_OFFSET
yield offset + _FIXED_OFFSET, opcode, arg, nextoffset + _FIXED_OFFSET
| ByteCodeInst |
python | Textualize__textual | docs/examples/guide/screens/questions01.py | {
"start": 703,
"end": 1142
} | class ____(App):
"""Demonstrates wait_for_dismiss"""
CSS_PATH = "questions01.tcss"
@work # (3)!
async def on_mount(self) -> None:
if await self.push_screen_wait( # (4)!
QuestionScreen("Do you like Textual?"),
):
self.notify("Good answer!")
else:
self.notify(":-(", severity="error")
if __name__ == "__main__":
app = QuestionsApp()
app.run()
| QuestionsApp |
python | pytorch__pytorch | torch/_dynamo/variables/streams.py | {
"start": 12304,
"end": 16799
} | class ____(VariableTracker):
def __init__(
self,
proxy: Proxy,
value: torch.Event,
user_object_index: Optional[int],
**kwargs: Any,
) -> None:
if proxy is not None and "example_value" in proxy.node.meta:
assert proxy.node.meta["example_value"] == value
super().__init__(**kwargs)
self.proxy = proxy
self.value = value
self.user_object_index = user_object_index
def call_method(
self,
tx: "InstructionTranslator",
name: str,
args: list[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
from ..utils import proxy_args_kwargs
from .builder import wrap_fx_proxy_cls
if name == "wait":
tx.output.create_proxy(
"call_function",
torch.ops.streams.wait_event,
(
self.user_object_index,
EventVariable._get_stream_arg(tx, args, kwargs).user_object_index,
),
{},
)
return ConstantVariable(None)
elif name == "record":
tx.output.create_proxy(
"call_function",
torch.ops.streams.record_event,
(
self.user_object_index,
EventVariable._get_stream_arg(tx, args, kwargs).user_object_index,
),
{},
)
return ConstantVariable(None)
elif name == "synchronize":
tx.output.create_proxy(
"call_method", name, *proxy_args_kwargs([self] + args, kwargs)
)
return ConstantVariable(None)
elif name == "query":
return wrap_fx_proxy_cls(
target_cls=ConstantVariable,
tx=tx,
proxy=tx.output.create_proxy(
"call_method", name, *proxy_args_kwargs([self] + args, kwargs)
),
)
else:
method_name = (
f"{type(self.value).__module__}.{type(self.value).__qualname__}.{name}"
)
unimplemented(
gb_type="Unsupported event method",
context=str(name),
explanation=f"Dynamo doesn't support tracing the {method_name} method. "
f"We currently support wait, record, synchronize, and query.",
hints=[
*graph_break_hints.SUPPORTABLE,
],
)
def as_proxy(self) -> Proxy:
return self.proxy
@staticmethod
def _get_stream_arg(
tx: "InstructionTranslator",
args: list[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> "StreamVariable":
stream_arg = None
if args:
stream_arg = args[0]
elif kwargs:
stream_arg = kwargs.get("stream")
if not stream_arg:
stream_arg = tx.symbolic_stream_state.cur_stream()
return stream_arg # type: ignore[return-value]
@staticmethod
def make_construct_in_graph_event_fn(
args: TupleVariable, kwargs: ConstDictVariable
) -> Callable[[int, "PyCodegen"], None]:
def fn(index: int, codegen: "PyCodegen") -> None:
codegen.add_push_null(
lambda: codegen.load_import_from(
torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports]
"stash_graph_created_object",
)
)
codegen.add_push_null(
lambda: codegen.load_import_from(
torch._dynamo.utils.__name__, "build_event"
)
)
codegen(args)
codegen(kwargs)
codegen.extend_output(create_call_function(2, False))
codegen.extend_output(create_call_function(1, False))
return fn
def reconstruct(self, codegen: "PyCodegen") -> None:
# If we got here, this event is fully subsumed by the graph - this means it is
# not an input or global
assert not self.source
# Similar to stream handling, we lift the event into a global and then codegen bytecode to load it from there.
prefix = "_event"
name = codegen.tx.output.install_global_by_id(prefix, self.value)
codegen.append_output(codegen.create_load_global(name, add=True))
| EventVariable |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 34573,
"end": 44440
} | class ____(BaseValidator):
"""
"color": {
"description": "A string describing color. Supported formats:
- hex (e.g. '#d3d3d3')
- rgb (e.g. 'rgb(255, 0, 0)')
- rgba (e.g. 'rgb(255, 0, 0, 0.5)')
- hsl (e.g. 'hsl(0, 100%, 50%)')
- hsv (e.g. 'hsv(0, 100%, 100%)')
- named colors(full list:
http://www.w3.org/TR/css3-color/#svg-color)",
"requiredOpts": [],
"otherOpts": [
"dflt",
"arrayOk"
]
},
"""
re_hex = re.compile(r"#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})")
re_rgb_etc = re.compile(r"(rgb|hsl|hsv)a?\([\d.]+%?(,[\d.]+%?){2,3}\)")
re_ddk = re.compile(r"var\(\-\-.*\)")
named_colors = [
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgrey",
"darkgreen",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"grey",
"green",
"greenyellow",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgrey",
"lightgreen",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"red",
"rosybrown",
"royalblue",
"rebeccapurple",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
]
def __init__(
self, plotly_name, parent_name, array_ok=False, colorscale_path=None, **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
self.array_ok = array_ok
# colorscale_path is the path to the colorscale associated with this
# color property, or None if no such colorscale exists. Only colors
# with an associated colorscale may take on numeric values
self.colorscale_path = colorscale_path
def numbers_allowed(self):
return self.colorscale_path is not None
def description(self):
valid_color_description = """\
The '{plotly_name}' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list""".format(
plotly_name=self.plotly_name
)
if self.colorscale_path:
valid_color_description = (
valid_color_description
+ """
- A number that will be interpreted as a color
according to {colorscale_path}""".format(colorscale_path=self.colorscale_path)
)
if self.array_ok:
valid_color_description = (
valid_color_description
+ """
- A list or array of any of the above"""
)
return valid_color_description
def validate_coerce(self, v, should_raise=True):
if is_none_or_typed_array_spec(v):
pass
elif self.array_ok and is_homogeneous_array(v):
v = copy_to_readonly_numpy_array(v)
if self.numbers_allowed() and v.dtype.kind in ["u", "i", "f"]:
# Numbers are allowed and we have an array of numbers.
# All good
pass
else:
validated_v = [self.validate_coerce(e, should_raise=False) for e in v]
invalid_els = self.find_invalid_els(v, validated_v)
if invalid_els and should_raise:
self.raise_invalid_elements(invalid_els)
# ### Check that elements have valid colors types ###
elif self.numbers_allowed() or invalid_els:
v = copy_to_readonly_numpy_array(validated_v, kind="O")
else:
v = copy_to_readonly_numpy_array(validated_v, kind="U")
elif self.array_ok and is_simple_array(v):
validated_v = [self.validate_coerce(e, should_raise=False) for e in v]
invalid_els = self.find_invalid_els(v, validated_v)
if invalid_els and should_raise:
self.raise_invalid_elements(invalid_els)
else:
v = validated_v
else:
# Validate scalar color
validated_v = self.vc_scalar(v)
if validated_v is None and should_raise:
self.raise_invalid_val(v)
v = validated_v
return v
def find_invalid_els(self, orig, validated, invalid_els=None):
"""
Helper method to find invalid elements in orig array.
Elements are invalid if their corresponding element in
the validated array is None.
This method handles deeply nested list structures
"""
if invalid_els is None:
invalid_els = []
for orig_el, validated_el in zip(orig, validated):
if is_array(orig_el):
self.find_invalid_els(orig_el, validated_el, invalid_els)
else:
if validated_el is None:
invalid_els.append(orig_el)
return invalid_els
def vc_scalar(self, v):
"""Helper to validate/coerce a scalar color"""
return ColorValidator.perform_validate_coerce(
v, allow_number=self.numbers_allowed()
)
@staticmethod
def perform_validate_coerce(v, allow_number=None):
"""
Validate, coerce, and return a single color value. If input cannot be
coerced to a valid color then return None.
Parameters
----------
v : number or str
Candidate color value
allow_number : bool
True if numbers are allowed as colors
Returns
-------
number or str or None
"""
if isinstance(v, numbers.Number) and allow_number:
# If allow_numbers then any number is ok
return v
elif not isinstance(v, str):
# If not allow_numbers then value must be a string
return None
else:
# Remove spaces so regexes don't need to bother with them.
v_normalized = v.replace(" ", "").lower()
# if ColorValidator.re_hex.fullmatch(v_normalized):
if fullmatch(ColorValidator.re_hex, v_normalized):
# valid hex color (e.g. #f34ab3)
return v
elif fullmatch(ColorValidator.re_rgb_etc, v_normalized):
# elif ColorValidator.re_rgb_etc.fullmatch(v_normalized):
# Valid rgb(a), hsl(a), hsv(a) color
# (e.g. rgba(10, 234, 200, 50%)
return v
elif fullmatch(ColorValidator.re_ddk, v_normalized):
# Valid var(--*) DDK theme variable, inspired by CSS syntax
# (e.g. var(--accent) )
# DDK will crawl & eval var(-- colors for Graph theming
return v
elif v_normalized in ColorValidator.named_colors:
# Valid named color (e.g. 'coral')
return v
else:
# Not a valid color
return None
| ColorValidator |
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 20964,
"end": 27702
} | class ____:
def test_revoked_basics(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
)
for i, rev in enumerate(crl):
assert isinstance(rev, x509.RevokedCertificate)
assert isinstance(rev.serial_number, int)
with pytest.warns(utils.DeprecatedIn42):
assert isinstance(rev.revocation_date, datetime.datetime)
assert isinstance(rev.revocation_date_utc, datetime.datetime)
assert isinstance(rev.extensions, x509.Extensions)
assert rev.serial_number == i
with pytest.warns(utils.DeprecatedIn42):
assert rev.revocation_date.isoformat() == "2015-01-01T00:00:00"
assert (
rev.revocation_date_utc.isoformat()
== "2015-01-01T00:00:00+00:00"
)
def test_revoked_extensions(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
)
exp_issuer = [
x509.DirectoryName(
x509.Name(
[
x509.NameAttribute(x509.OID_COUNTRY_NAME, "US"),
x509.NameAttribute(
x509.OID_COMMON_NAME, "cryptography.io"
),
]
)
)
]
# First revoked cert doesn't have extensions, test if it is handled
# correctly.
rev0 = crl[0]
# It should return an empty Extensions object.
assert isinstance(rev0.extensions, x509.Extensions)
assert len(rev0.extensions) == 0
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_CRL_REASON)
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_CERTIFICATE_ISSUER)
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_INVALIDITY_DATE)
# Test manual retrieval of extension values.
rev1 = crl[1]
assert isinstance(rev1.extensions, x509.Extensions)
reason = rev1.extensions.get_extension_for_class(x509.CRLReason).value
assert reason == x509.CRLReason(x509.ReasonFlags.unspecified)
issuer = rev1.extensions.get_extension_for_class(
x509.CertificateIssuer
).value
assert issuer == x509.CertificateIssuer(exp_issuer)
date = rev1.extensions.get_extension_for_class(
x509.InvalidityDate
).value
assert date == x509.InvalidityDate(datetime.datetime(2015, 1, 1, 0, 0))
# Check if all reason flags can be found in the CRL.
flags = set(x509.ReasonFlags)
for rev in crl:
try:
r = rev.extensions.get_extension_for_class(x509.CRLReason)
except x509.ExtensionNotFound:
# Not all revoked certs have a reason extension.
pass
else:
flags.discard(r.value.reason)
assert len(flags) == 0
def test_no_revoked_certs(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_empty.pem"),
x509.load_pem_x509_crl,
)
assert len(crl) == 0
def test_duplicate_entry_ext(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_dup_entry_ext.pem"),
x509.load_pem_x509_crl,
)
with pytest.raises(x509.DuplicateExtension):
crl[0].extensions
def test_unsupported_crit_entry_ext(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_md2_unknown_crit_entry_ext.pem"
),
x509.load_pem_x509_crl,
)
ext = crl[0].extensions.get_extension_for_oid(
x509.ObjectIdentifier("1.2.3.4")
)
assert isinstance(ext.value, x509.UnrecognizedExtension)
assert ext.value.value == b"\n\x01\x00"
def test_unsupported_reason(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_unsupported_reason.pem"),
x509.load_pem_x509_crl,
)
with pytest.raises(ValueError):
crl[0].extensions
def test_invalid_cert_issuer_ext(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_inval_cert_issuer_entry_ext.pem"
),
x509.load_pem_x509_crl,
)
with pytest.raises(ValueError):
crl[0].extensions
def test_indexing(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
)
with pytest.raises(IndexError):
crl[-13]
with pytest.raises(IndexError):
crl[12]
assert crl[-1].serial_number == crl[11].serial_number
assert len(crl[2:4]) == 2
assert crl[2:4][0].serial_number == crl[2].serial_number
assert crl[2:4][1].serial_number == crl[3].serial_number
def test_get_revoked_certificate_doesnt_reorder(
self, rsa_key_2048: rsa.RSAPrivateKey, backend
):
private_key = rsa_key_2048
last_update = datetime.datetime(2002, 1, 1, 12, 1)
next_update = datetime.datetime(2030, 1, 1, 12, 1)
builder = (
x509.CertificateRevocationListBuilder()
.issuer_name(
x509.Name(
[
x509.NameAttribute(
NameOID.COMMON_NAME, "cryptography.io CA"
)
]
)
)
.last_update(last_update)
.next_update(next_update)
)
for i in [2, 500, 3, 49, 7, 1]:
revoked_cert = (
x509.RevokedCertificateBuilder()
.serial_number(i)
.revocation_date(datetime.datetime(2012, 1, 1, 1, 1))
.build(backend)
)
builder = builder.add_revoked_certificate(revoked_cert)
crl = builder.sign(private_key, hashes.SHA256(), backend)
assert crl[0].serial_number == 2
assert crl[2].serial_number == 3
# make sure get_revoked_certificate_by_serial_number doesn't affect
# ordering after being invoked
crl.get_revoked_certificate_by_serial_number(500)
assert crl[0].serial_number == 2
assert crl[2].serial_number == 3
| TestRevokedCertificate |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001.py | {
"start": 330,
"end": 3364
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship(back_populates="heroes")
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
with Session(engine) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar")
hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team=team_z_force
)
hero_rusty_man = Hero(
name="Rusty-Man", secret_name="Tommy Sharp", age=48, team=team_preventers
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_deadpond)
session.refresh(hero_rusty_man)
session.refresh(hero_spider_boy)
print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)
hero_spider_boy.team = team_preventers
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_spider_boy)
print("Updated hero:", hero_spider_boy)
hero_black_lion = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_sure_e = Hero(name="Princess Sure-E", secret_name="Sure-E")
team_wakaland = Team(
name="Wakaland",
headquarters="Wakaland Capital City",
heroes=[hero_black_lion, hero_sure_e],
)
session.add(team_wakaland)
session.commit()
session.refresh(team_wakaland)
print("Team Wakaland:", team_wakaland)
hero_tarantula = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_dr_weird = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_cap = Hero(
name="Captain North America", secret_name="Esteban Rogelios", age=93
)
team_preventers.heroes.append(hero_tarantula)
team_preventers.heroes.append(hero_dr_weird)
team_preventers.heroes.append(hero_cap)
session.add(team_preventers)
session.commit()
session.refresh(hero_tarantula)
session.refresh(hero_dr_weird)
session.refresh(hero_cap)
print("Preventers new hero:", hero_tarantula)
print("Preventers new hero:", hero_dr_weird)
print("Preventers new hero:", hero_cap)
def main():
create_db_and_tables()
create_heroes()
if __name__ == "__main__":
main()
| Hero |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 42571,
"end": 50095
} | class ____(BlenderbotSmallPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
_tied_weights_keys = {
"lm_head.weight": "model.shared.weight",
}
def __init__(self, config: BlenderbotSmallConfig):
super().__init__(config)
self.model = BlenderbotSmallModel(config)
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
# Initialize weights and apply final processing
self.post_init()
def resize_token_embeddings(
self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
) -> nn.Embedding:
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
return new_embeddings
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
old_num_tokens = self.final_logits_bias.shape[-1]
if new_num_tokens <= old_num_tokens:
new_bias = self.final_logits_bias[:, :new_num_tokens]
else:
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
self.register_buffer("final_logits_bias", new_bias)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[Union[tuple, BaseModelOutput]] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.Tensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
r"""
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are decoder input IDs?](../glossary#decoder-input-ids)
BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
`past_key_values`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example Conversation:
```python
>>> from transformers import AutoTokenizer, BlenderbotSmallForConditionalGeneration
>>> mname = "facebook/blenderbot_small-90M"
>>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
>>> print("Human: ", UTTERANCE)
Human: My friends are cool but they eat too many carbs.
>>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
>>> reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
Bot: what kind of carbs do they eat? i don't know much about carbs.
>>> REPLY = "I'm not sure"
>>> print("Human: ", REPLY)
Human: I'm not sure
>>> NEXT_UTTERANCE = (
... "My friends are cool but they eat too many carbs.__end__ __start__what kind of carbs do they eat? "
... "i don't know much about carbs__end__ "
... "__start__ I'm not sure."
... )
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
>>> next_reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
Bot: they eat a lot of carbs. carbs are high in fat, protein, and fats.
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
if use_cache:
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
use_cache = False
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(
labels, self.config.pad_token_id, self.config.decoder_start_token_id
)
outputs = self.model(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
encoder_outputs=encoder_outputs,
decoder_attention_mask=decoder_attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (lm_logits,) + outputs[1:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return Seq2SeqLMOutput(
loss=masked_lm_loss,
logits=lm_logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
)
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->BlenderbotSmall
| BlenderbotSmallForConditionalGeneration |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 6403,
"end": 6934
} | class ____(Rule):
"""Apply PartsRule multiple times to integrate exp(x)*sin(x)"""
parts_rules: list[PartsRule]
coefficient: Expr
def eval(self) -> Expr:
result = []
sign = 1
for rule in self.parts_rules:
result.append(sign * rule.u * rule.v_step.eval())
sign *= -1
return Add(*result) / (1 - self.coefficient)
def contains_dont_know(self) -> bool:
return any(substep.contains_dont_know() for substep in self.parts_rules)
@dataclass
| CyclicPartsRule |
python | pytorch__pytorch | torch/testing/_internal/distributed/common_state_dict.py | {
"start": 6293,
"end": 6725
} | class ____(FusionEmbeddingWithHook):
# _fqn_modifiers is a private function as a contract between DSD. When users change the state_dict
# keys, they need to provide a mapping from the new key to the original key. This is used to ensure
# consistency between the state_dict keys and fqn.
def _fqn_modifiers(self) -> dict[str, str]:
return {
"weight": "embedding",
}
| FusionEmbeddingWithModifier |
python | pikepdf__pikepdf | src/pikepdf/_methods.py | {
"start": 27707,
"end": 28165
} | class ____:
def keys(self):
return KeysView(self._as_map())
def values(self):
return ValuesView(self._as_map())
def items(self):
return ItemsView(self._as_map())
get = MutableMapping.get
pop = MutableMapping.pop
popitem = MutableMapping.popitem
clear = MutableMapping.clear
update = MutableMapping.update
setdefault = MutableMapping.setdefault
MutableMapping.register(NumberTree)
| Extend_NumberTree |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 158807,
"end": 161397
} | class ____:
@mock.patch(DATAPROC_PATH.format("DataprocHook"))
def test_execute(self, mock_hook):
op = DataprocDiagnoseClusterOperator(
task_id=TASK_ID,
region=GCP_REGION,
project_id=GCP_PROJECT,
cluster_name=CLUSTER_NAME,
gcp_conn_id=GCP_CONN_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context={})
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.diagnose_cluster.assert_called_once_with(
region=GCP_REGION,
project_id=GCP_PROJECT,
cluster_name=CLUSTER_NAME,
tarball_gcs_dir=None,
diagnosis_interval=None,
jobs=None,
yarn_application_ids=None,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(DATAPROC_PATH.format("DataprocHook"))
@mock.patch(DATAPROC_TRIGGERS_PATH.format("DataprocAsyncHook"))
def test_create_execute_call_defer_method(self, mock_trigger_hook, mock_hook):
mock_hook.return_value.create_cluster.return_value = None
operator = DataprocDiagnoseClusterOperator(
task_id=TASK_ID,
region=GCP_REGION,
project_id=GCP_PROJECT,
cluster_name=CLUSTER_NAME,
gcp_conn_id=GCP_CONN_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
impersonation_chain=IMPERSONATION_CHAIN,
deferrable=True,
)
with pytest.raises(TaskDeferred) as exc:
operator.execute(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.diagnose_cluster.assert_called_once_with(
region=GCP_REGION,
project_id=GCP_PROJECT,
cluster_name=CLUSTER_NAME,
tarball_gcs_dir=None,
diagnosis_interval=None,
jobs=None,
yarn_application_ids=None,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
mock_hook.return_value.wait_for_operation.assert_not_called()
assert isinstance(exc.value.trigger, DataprocOperationTrigger)
assert exc.value.method_name == GOOGLE_DEFAULT_DEFERRABLE_METHOD_NAME
| TestDataprocDiagnoseClusterOperator |
python | doocs__leetcode | solution/1000-1099/1053.Previous Permutation With One Swap/Solution.py | {
"start": 0,
"end": 405
} | class ____:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
n = len(arr)
for i in range(n - 1, 0, -1):
if arr[i - 1] > arr[i]:
for j in range(n - 1, i - 1, -1):
if arr[j] < arr[i - 1] and arr[j] != arr[j - 1]:
arr[i - 1], arr[j] = arr[j], arr[i - 1]
return arr
return arr
| Solution |
python | matplotlib__matplotlib | lib/matplotlib/backend_bases.py | {
"start": 136172,
"end": 136409
} | class ____(_Backend):
"""
Simple base class to generate a ``show()`` function in backends.
Subclass must override ``mainloop()`` method.
"""
def __call__(self, block=None):
return self.show(block=block)
| ShowBase |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_button01.py | {
"start": 315,
"end": 805
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("button01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_button("C2", {})
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format14.py | {
"start": 315,
"end": 1590
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format14.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [51819264, 52499584]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"data_labels": {"value": 1, "category": 1, "series_name": 1},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc_metastore.py | {
"start": 9463,
"end": 11124
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
@mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.MetadataExport")
@mock.patch(
"airflow.providers.google.cloud.operators.dataproc_metastore"
".DataprocMetastoreExportMetadataOperator._wait_for_export_metadata"
)
def test_assert_valid_hook_call(self, mock_wait, mock_export_metadata, mock_hook) -> None:
task = DataprocMetastoreExportMetadataOperator(
task_id=TASK_ID,
service_id=TEST_SERVICE_ID,
destination_gcs_folder=TEST_DESTINATION_GCS_FOLDER,
project_id=GCP_PROJECT_ID,
region=GCP_LOCATION,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_wait.return_value = None
mock_export_metadata.return_value.to_dict.return_value = None
task.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.export_metadata.assert_called_once_with(
database_dump_type=None,
destination_gcs_folder=TEST_DESTINATION_GCS_FOLDER,
project_id=GCP_PROJECT_ID,
region=GCP_LOCATION,
service_id=TEST_SERVICE_ID,
request_id=None,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestDataprocMetastoreExportMetadataOperator |
python | google__pytype | pytype/abstract/_pytd_function.py | {
"start": 1307,
"end": 1699
} | class ____(Exception):
"""Raise an error for invalid signature mutation in a pyi file."""
def __init__(self, pytd_sig: "PyTDSignature"):
self.pytd_sig = pytd_sig
def _is_literal(annot: _base.BaseValue | None) -> bool:
if isinstance(annot, _typing.Union):
return all(_is_literal(o) for o in annot.options)
return isinstance(annot, _classes.LiteralClass)
| SignatureMutationError |
python | walkccc__LeetCode | solutions/1615. Maximal Network Rank/1615.py | {
"start": 0,
"end": 2244
} | class ____:
def maximalNetworkRank(self, n: int, roads: list[list[int]]) -> int:
degrees = [0] * n
for u, v in roads:
degrees[u] += 1
degrees[v] += 1
# Find the first maximum and the second maximum degrees.
maxDegree1 = 0
maxDegree2 = 0
for degree in degrees:
if degree > maxDegree1:
maxDegree2 = maxDegree1
maxDegree1 = degree
elif degree > maxDegree2:
maxDegree2 = degree
# There can be multiple nodes with `maxDegree1` or `maxDegree2`.
# Find the counts of such nodes.
countMaxDegree1 = 0
countMaxDegree2 = 0
for degree in degrees:
if degree == maxDegree1:
countMaxDegree1 += 1
elif degree == maxDegree2:
countMaxDegree2 += 1
if countMaxDegree1 == 1:
# 1. If there is only one node with degree = `maxDegree1`, then we'll
# need to use the node with degree = `maxDegree2`. The answer in general
# will be (maxDegree1 + maxDegree2), but if the two nodes that we're
# considering are connected, then we'll have to subtract 1.
edgeCount = (self._getEdgeCount(roads, degrees, maxDegree1, maxDegree2) +
self._getEdgeCount(roads, degrees, maxDegree2, maxDegree1))
return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount)
else:
# 2. If there are more than one node with degree = `maxDegree1`, then we
# can consider `maxDegree1` twice, and we don't need to use `maxDegree2`.
# The answer in general will be 2 * maxDegree1, but if the two nodes that
# we're considering are connected, then we'll have to subtract 1.
edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree1)
maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) // 2
return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount)
def _getEdgeCount(
self,
roads: list[list[int]],
degrees: list[int],
degreeU: int, degreeV: int,
) -> int:
"""
Returns the number of edges (u, v) where degress[u] == degreeU and
degrees[v] == degreeV.
"""
edgeCount = 0
for u, v in roads:
if degrees[u] == degreeU and degrees[v] == degreeV:
edgeCount += 1
return edgeCount
| Solution |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 10452,
"end": 17954
} | class ____(DataDocsAction):
"""Sends a Slack notification to a given webhook.
```yaml
- name: send_slack_notification_on_validation_result
action:
class_name: SlackNotificationAction
# put the actual webhook URL in the uncommitted/config_variables.yml file
# or pass in as environment variable
# use slack_webhook when not using slack bot token
slack_webhook: ${validation_notification_slack_webhook}
slack_token:
slack_channel:
notify_on: all
notify_with:
renderer:
# the class that implements the message to be sent
# this is the default implementation, but you can
# implement a custom one
module_name: great_expectations.render.renderer.slack_renderer
class_name: SlackRenderer
show_failed_expectations: True
```
Args:
renderer: Specifies the Renderer used to generate a query consumable by Slack API.
slack_webhook: The incoming Slack webhook to which to send notification.
slack_token: Token from Slack app. Used when not using slack_webhook.
slack_channel: Slack channel to receive notification. Used when not using slack_webhook.
notify_on: Specifies validation status that triggers notification. One of "all", "failure", "success".
notify_with: List of DataDocs site names to display in Slack messages. Defaults to all.
show_failed_expectations: Shows a list of failed expectation types.
Examples:
**renderer:**
```python
{
"module_name": "great_expectations.render.renderer.slack_renderer",
"class_name": "SlackRenderer",
}
```
""" # noqa: E501 # FIXME CoP
type: Literal["slack"] = "slack"
slack_webhook: Optional[Union[ConfigStr, str]] = None
slack_token: Optional[Union[ConfigStr, str]] = None
slack_channel: Optional[Union[ConfigStr, str]] = None
notify_on: NotifyOn = "all"
notify_with: Optional[List[str]] = None
show_failed_expectations: bool = False
renderer: SlackRenderer = Field(default_factory=SlackRenderer)
@validator("renderer", pre=True)
def _validate_renderer(cls, renderer: dict | SlackRenderer) -> SlackRenderer:
if isinstance(renderer, dict):
_renderer = _build_renderer(config=renderer)
if not isinstance(_renderer, SlackRenderer):
raise ValueError( # noqa: TRY003, TRY004 # FIXME CoP
"renderer must be a SlackRenderer or a valid configuration for one."
)
renderer = _renderer
return renderer
@root_validator
def _root_validate_slack_params(cls, values: dict) -> dict:
slack_webhook = values["slack_webhook"]
slack_token = values["slack_token"]
slack_channel = values["slack_channel"]
try:
if slack_webhook:
assert not slack_token and not slack_channel
else:
assert slack_token and slack_channel
except AssertionError:
raise ValueError("Please provide either slack_webhook or slack_token and slack_channel") # noqa: TRY003 # FIXME CoP
return values
@override
def run(
self, checkpoint_result: CheckpointResult, action_context: ActionContext | None = None
) -> dict:
success = checkpoint_result.success or False
checkpoint_name = checkpoint_result.checkpoint_config.name
result = {"slack_notification_result": "none required"}
max_severity = self._get_max_severity_failure_from_checkpoint_result(checkpoint_result)
if not should_notify(success=success, notify_on=self.notify_on, max_severity=max_severity):
return result
checkpoint_text_blocks: list[dict] = []
for (
validation_result_suite_identifier,
validation_result_suite,
) in checkpoint_result.run_results.items():
validation_text_blocks = self._render_validation_result(
result_identifier=validation_result_suite_identifier,
result=validation_result_suite,
action_context=action_context,
)
checkpoint_text_blocks.extend(validation_text_blocks)
payload = self.renderer.concatenate_text_blocks(
action_name=self.name,
text_blocks=checkpoint_text_blocks,
success=success,
checkpoint_name=checkpoint_name,
run_id=checkpoint_result.run_id,
)
return self._send_slack_notification(payload=payload)
def _render_validation_result(
self,
result_identifier: ValidationResultIdentifier,
result: ExpectationSuiteValidationResult,
action_context: ActionContext | None = None,
) -> list[dict]:
data_docs_pages = None
if action_context:
data_docs_pages = self._get_data_docs_pages_from_prior_action(
action_context=action_context
)
# Assemble complete GX Cloud URL for a specific validation result
data_docs_urls: list[dict[str, str]] = self._get_docs_sites_urls(
resource_identifier=result_identifier
)
validation_result_urls: list[str] = [
data_docs_url["site_url"]
for data_docs_url in data_docs_urls
if data_docs_url["site_url"]
]
if result.result_url:
result.result_url += "?slack=true"
validation_result_urls.append(result.result_url)
return self.renderer.render(
validation_result=result,
data_docs_pages=data_docs_pages,
notify_with=self.notify_with,
validation_result_urls=validation_result_urls,
)
def _send_slack_notification(self, payload: dict) -> dict:
slack_webhook = self._substitute_config_str_if_needed(self.slack_webhook)
slack_token = self._substitute_config_str_if_needed(self.slack_token)
slack_channel = self._substitute_config_str_if_needed(self.slack_channel)
session = requests.Session()
url = slack_webhook
headers = None
# Slack doc about overwritting the channel when using the legacy Incoming Webhooks
# https://api.slack.com/legacy/custom-integrations/messaging/webhooks
# ** Since it is legacy, it could be deprecated or removed in the future **
if slack_channel:
payload["channel"] = slack_channel
if not slack_webhook:
url = "https://slack.com/api/chat.postMessage"
headers = {"Authorization": f"Bearer {slack_token}"}
if not url:
raise ValueError("No Slack webhook URL provided.") # noqa: TRY003 # FIXME CoP
try:
response = session.post(url=url, headers=headers, json=payload)
response.raise_for_status()
except requests.ConnectionError:
logger.warning(f"Failed to connect to Slack webhook after {10} retries.")
return {"slack_notification_result": None}
except requests.HTTPError:
logger.warning(
f"Request to Slack webhook returned error {response.status_code}: {response.text}" # type: ignore[possibly-undefined] # ok for httperror
)
return {"slack_notification_result": None}
return {"slack_notification_result": "Slack notification succeeded."}
| SlackNotificationAction |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/rag.py | {
"start": 2685,
"end": 3697
} | class ____(BaseLlamaPredictionDataset):
"""RagDataset class."""
_prediction_type = RagExamplePrediction
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
"pandas is required for this function. Please install it with `pip install pandas`."
)
data: Dict[str, List] = {
"response": [],
"contexts": [],
}
for pred in self.predictions:
if not isinstance(pred, RagExamplePrediction):
raise ValueError(
"All predictions in the dataset must be of type RagExamplePrediction."
)
data["response"].append(pred.response)
data["contexts"].append(pred.contexts)
return pd.DataFrame(data)
@property
def class_name(self) -> str:
"""Class name."""
return "RagPredictionDataset"
| RagPredictionDataset |
python | allegroai__clearml | clearml/utilities/dicts.py | {
"start": 3421,
"end": 5878
} | class ____(dict):
@property
def pip(self) -> Optional[Any]:
return self.get("pip")
@property
def conda(self) -> Optional[Any]:
return self.get("conda")
@property
def orig_pip(self) -> Optional[Any]:
return self.get("orig_pip")
def merge_dicts(dict1: dict, dict2: dict) -> dict:
"""Recursively merges dict2 into dict1"""
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for k in dict2:
if k in dict1:
dict1[k] = merge_dicts(dict1[k], dict2[k])
else:
dict1[k] = dict2[k]
return dict1
def hocon_quote_key(a_obj: Any) -> Any:
"""Recursively quote key with '.' to \"key\" """
if isinstance(a_obj, list):
return [hocon_quote_key(a) for a in a_obj]
elif isinstance(a_obj, tuple):
return tuple(hocon_quote_key(a) for a in a_obj)
elif not isinstance(a_obj, dict):
return a_obj
# preserve dict type
a_dict = a_obj
new_dict = type(a_dict)()
for k, v in a_dict.items():
if isinstance(k, str) and "." in k:
new_dict['"{}"'.format(k)] = hocon_quote_key(v)
else:
new_dict[k] = hocon_quote_key(v)
return new_dict
def hocon_unquote_key(a_obj: Any) -> Any:
"""Recursively unquote \"key\" with '.' to key"""
if isinstance(a_obj, list):
return [hocon_unquote_key(a) for a in a_obj]
elif isinstance(a_obj, tuple):
return tuple(hocon_unquote_key(a) for a in a_obj)
elif not isinstance(a_obj, dict):
return a_obj
a_dict = a_obj
# ConfigTree to dict
if hasattr(a_dict, "as_plain_ordered_dict"):
a_dict = a_dict.as_plain_ordered_dict()
# preserve dict type
new_dict = type(a_dict)()
for k, v in a_dict.items():
if isinstance(k, str) and k[0] == '"' and k[-1] == '"' and "." in k:
new_dict[k[1:-1]] = hocon_unquote_key(v)
else:
new_dict[k] = hocon_unquote_key(v)
return new_dict
def cast_str_to_bool(value: Any, strip: bool = True) -> Optional[bool]:
a_strip_v = value if not strip else str(value).lower().strip()
if a_strip_v == "false" or not a_strip_v:
return False
elif a_strip_v == "true":
return True
else:
# first try to cast to integer
try:
return bool(int(a_strip_v))
except (ValueError, TypeError):
return None
| RequirementsDict |
python | wandb__wandb | wandb/vendor/pygments/lexer.py | {
"start": 8824,
"end": 9031
} | class ____(object):
"""
Indicates the a state should inherit from its superclass.
"""
def __repr__(self):
return 'inherit'
inherit = _inherit() # pylint: disable=invalid-name
| _inherit |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/base.py | {
"start": 4327,
"end": 6419
} | class ____:
# NamedExpr does not inherit from Expr since it does not appear
# when evaluating expressions themselves, only when constructing
# named return values in dataframe (IR) nodes.
__slots__ = ("name", "value")
value: Expr
name: str
def __init__(self, name: str, value: Expr) -> None:
self.name = name
self.value = value
def __hash__(self) -> int:
"""Hash of the expression."""
return hash((type(self), self.name, self.value))
def __repr__(self) -> str:
"""Repr of the expression."""
return f"NamedExpr({self.name}, {self.value})"
def __eq__(self, other: Any) -> bool:
"""Equality of two expressions."""
return (
type(self) is type(other)
and self.name == other.name
and self.value == other.value
)
def __ne__(self, other: Any) -> bool:
"""Inequality of expressions."""
return not self.__eq__(other)
def evaluate(
self, df: DataFrame, *, context: ExecutionContext = ExecutionContext.FRAME
) -> Column:
"""
Evaluate this expression given a dataframe for context.
Parameters
----------
df
DataFrame providing context
context
Execution context
Returns
-------
Evaluated Column with name attached.
See Also
--------
:meth:`Expr.evaluate` for details, this function just adds the
name to a column produced from an expression.
"""
return self.value.evaluate(df, context=context).rename(self.name)
def reconstruct(self, expr: Expr) -> Self:
"""
Rebuild with a new `Expr` value.
Parameters
----------
expr
New `Expr` value
Returns
-------
New `NamedExpr` with `expr` as the underlying expression.
The name of the original `NamedExpr` is preserved.
"""
if expr is self.value:
return self
return type(self)(self.name, expr)
| NamedExpr |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 8265,
"end": 8485
} | class ____:
def items(self, request, *args, **kwargs):
return self.get_stream()(
self.get_object(request, *args, **kwargs),
**self.get_stream_kwargs(request)
)
| StreamKwargsMixin |
python | huggingface__transformers | src/transformers/models/qwen3_next/modeling_qwen3_next.py | {
"start": 43005,
"end": 44435
} | class ____(PreTrainedModel):
config: Qwen3NextConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3NextDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn_2 = True
_supports_sdpa = True
_keys_to_ignore_on_load_unexpected = [r"^mtp.*"]
_can_record_outputs = {
"router_logits": OutputRecorder(Qwen3NextSparseMoeBlock, index=1),
"hidden_states": Qwen3NextDecoderLayer,
"attentions": Qwen3NextAttention,
}
_is_stateful = True
@torch.no_grad()
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, Qwen3NextGatedDeltaNet):
init.ones_(module.dt_bias)
init.copy_(module.A_log, torch.empty_like(module.A_log).uniform_(0, 16).log_())
# We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
elif isinstance(module, Qwen3NextRMSNorm):
init.zeros_(module.weight)
elif isinstance(module, Qwen3NextExperts):
init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
elif isinstance(module, Qwen3NextSparseMoeBlock):
init.normal_(module.gate.weight, mean=0.0, std=self.config.initializer_range)
| Qwen3NextPreTrainedModel |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 76730,
"end": 78281
} | class ____(SocketDummyServerTestCase):
def _test_broken_header_parsing(
self, headers: list[bytes], unparsed_data_check: str | None = None
) -> None:
self.start_response_handler(
(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 0\r\n"
b"Content-type: text/plain\r\n"
)
+ b"\r\n".join(headers)
+ b"\r\n\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
with LogRecorder() as logs:
pool.request("GET", "/")
for record in logs:
if (
"Failed to parse headers" in record.msg
and type(record.args) is tuple
and _url_from_pool(pool, "/") == record.args[0]
):
if (
unparsed_data_check is None
or unparsed_data_check in record.getMessage()
):
return
pytest.fail("Missing log about unparsed headers")
def test_header_without_name(self) -> None:
self._test_broken_header_parsing([b": Value", b"Another: Header"])
def test_header_without_name_or_value(self) -> None:
self._test_broken_header_parsing([b":", b"Another: Header"])
def test_header_without_colon_or_value(self) -> None:
self._test_broken_header_parsing(
[b"Broken Header", b"Another: Header"], "Broken Header"
)
| TestBrokenHeaders |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/entities/snippets.py | {
"start": 4923,
"end": 5334
} | class ____(ndb.Expando):
pass
def create_entity_using_expando_model():
e = Mine()
e.foo = 1
e.bar = "blah"
e.tags = ["exp", "and", "oh"]
e.put()
return e
def get_properties_defined_on_expando(e):
return e._properties
# {
# 'foo': GenericProperty('foo'),
# 'bar': GenericProperty('bar'),
# 'tags': GenericProperty('tags', repeated=True)
# }
| Mine |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_media/query/sync.py | {
"start": 308,
"end": 449
} | class ____(
Generic[Properties, References],
_NearMediaQueryExecutor[ConnectionSync, Properties, References],
):
pass
| _NearMediaQuery |
python | django__django | django/db/models/fields/reverse_related.py | {
"start": 9862,
"end": 10656
} | class ____(ManyToOneRel):
"""
Used by OneToOneField to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
def __init__(
self,
field,
to,
field_name,
related_name=None,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
on_delete=None,
):
super().__init__(
field,
to,
field_name,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
self.multiple = False
| OneToOneRel |
python | django__django | django/forms/fields.py | {
"start": 13959,
"end": 15976
} | class ____(IntegerField):
default_error_messages = {
"invalid": _("Enter a number."),
}
def __init__(
self,
*,
max_value=None,
min_value=None,
max_digits=None,
decimal_places=None,
**kwargs,
):
self.max_digits, self.decimal_places = max_digits, decimal_places
super().__init__(max_value=max_value, min_value=min_value, **kwargs)
self.validators.append(validators.DecimalValidator(max_digits, decimal_places))
def to_python(self, value):
"""
Validate that the input is a decimal number. Return a Decimal
instance or None for empty values. Ensure that there are no more
than max_digits in the number and no more than decimal_places digits
after the decimal point.
"""
if value in self.empty_values:
return None
if self.localize:
value = formats.sanitize_separators(value)
try:
value = Decimal(str(value))
except DecimalException:
raise ValidationError(self.error_messages["invalid"], code="invalid")
return value
def validate(self, value):
super().validate(value)
if value in self.empty_values:
return
if not value.is_finite():
raise ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
)
def widget_attrs(self, widget):
attrs = super().widget_attrs(widget)
if isinstance(widget, NumberInput) and "step" not in widget.attrs:
if self.decimal_places is not None:
# Use exponential notation for small values since they might
# be parsed as 0 otherwise. ref #20765
step = str(Decimal(1).scaleb(-self.decimal_places)).lower()
else:
step = "any"
attrs.setdefault("step", step)
return attrs
| DecimalField |
python | python__mypy | mypyc/test-data/fixtures/ir.py | {
"start": 12300,
"end": 12519
} | class ____(Iterable[int]):
def __init__(self, x: int, y: int = ..., z: int = ...) -> None: pass
def __iter__(self) -> Iterator[int]: pass
def __len__(self) -> int: pass
def __next__(self) -> int: pass
| range |
python | pytorch__pytorch | test/jit/test_list_dict.py | {
"start": 66591,
"end": 73253
} | class ____(JitTestCase):
def test_namedtuple(self):
class FeatureVector(NamedTuple):
float_features: float
sequence_features: List[float]
time_since_first: float
@torch.jit.script
def foo(x) -> float:
fv = FeatureVector(3.0, [3.0], 3.0)
rv = fv.float_features
for val in fv.sequence_features:
rv += val
rv *= fv.time_since_first
return rv
self.assertEqual(foo(torch.rand(3, 4)), 18.0)
def test_namedtuple_constant(self):
class Tup(NamedTuple):
a: int
b: int
@torch.jit.script
def foo():
return Tup(1, 2)
self.assertEqual(foo(), Tup(1, 2))
def test_return_named_tuple(self):
class FeatureVector(NamedTuple):
float_features: float
sequence_features: List[float]
time_since_first: float
@torch.jit.script
def foo(x):
fv = FeatureVector(3.0, [3.0], 3.0)
return fv
out = foo(torch.rand(3, 4))
out = foo(torch.rand(3, 4))
self.assertEqual(out.float_features, 3.0)
self.assertEqual(out.sequence_features, [3.0])
self.assertEqual(out.time_since_first, 3.0)
def test_namedtuple_as_attr(self):
class Config(NamedTuple):
size: int
class MyMod(nn.Module):
configs: Dict[int, Config]
def __init__(self, configs):
super().__init__()
self.configs = configs
def forward(self, x):
for config in self.configs.values():
x += config.size
return x
s = torch.jit.script(MyMod({0: Config(size=16)}))
def test_namedtuple_resolution(self):
class TheType(NamedTuple):
t: int
class MyModule(types.ModuleType):
def __init__(self) -> None:
super().__init__("MyModule")
def __getattr__(self, attr):
return TheType
some_module = MyModule()
def fn() -> some_module.Type:
return some_module.Type(1)
self.checkScript(fn, [])
def test_namedtuple_slice_unpack(self):
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
@torch.jit.script
def foo(a: int, b: float, c: List[int]):
tup = MyCoolNamedTuple(a, b, c)
my_a, my_b, my_c = tup
return tup[:1], my_a, my_c
self.assertEqual(foo(3, 3.5, [6]), ((3,), 3, [6]))
def test_namedtuple_lower(self):
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
@torch.jit.script
def foo(a: int):
tup = MyCoolNamedTuple(a, 3.14, [9])
return tup
FileCheck().check("TupleConstruct").run(foo.graph)
torch._C._jit_pass_lower_all_tuples(foo.graph)
FileCheck().check_not("TupleConstruct").run(foo.graph)
def test_namedtuple_type_annotation(self):
global MyCoolNamedTuple # see [local resolution in python]
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
@torch.jit.script
def foo(x: MyCoolNamedTuple) -> MyCoolNamedTuple:
return x
mnt = MyCoolNamedTuple(42, 420.0, [666])
self.assertEqual(foo(mnt), mnt)
def test_namedtuple_wrong_types(self):
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
with self.assertRaisesRegex(
RuntimeError,
"Expected a value of type 'int' for argument 'a'"
" but instead found type 'str'",
):
@torch.jit.script
def foo():
tup = MyCoolNamedTuple("foo", "bar", "baz")
return tup
def test_namedtuple_kwarg_construct(self):
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
@torch.jit.script
def foo():
tup = MyCoolNamedTuple(c=[1, 2, 3], b=3.5, a=9)
return tup
tup = foo()
self.assertEqual(tup.a, 9)
self.assertEqual(tup.b, 3.5)
self.assertEqual(tup.c, [1, 2, 3])
@unittest.skipIf(True, "broken while these tests were not in CI")
def test_namedtuple_serialization(self):
class MyCoolNamedTuple(NamedTuple):
a: int
b: float
c: List[int]
class MyMod(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self):
return MyCoolNamedTuple(3, 3.5, [3, 4, 5])
mm = MyMod()
mm.save("foo.zip")
torch.testing._internal.jit_utils.clear_class_registry()
loaded = torch.jit.load("foo.zip")
out = mm()
out_loaded = loaded()
for name in ["a", "b", "c"]:
self.assertEqual(getattr(out_loaded, name), getattr(out, name))
def test_namedtuple_inside_forwardref(self):
class FeatureVector(NamedTuple):
float_features: "float"
sequence_features: "List[float]"
time_since_first: "float"
@torch.jit.script
def foo(x) -> float:
fv = FeatureVector(3.0, [3.0], 3.0)
rv = fv.float_features
for val in fv.sequence_features:
rv += val
rv *= fv.time_since_first
return rv
self.assertEqual(foo(torch.rand(3, 4)), 18.0)
def test_namedtuple_input_forwardref(self):
class MyNamedTuple(NamedTuple):
a: "int"
b: "float"
c: "torch.Tensor"
make_global(MyNamedTuple)
nt = MyNamedTuple(4, 2.5, torch.rand((2, 2)))
def fn(obj: MyNamedTuple):
return ((obj.c + obj.b) ** obj.a).sin()
expected = fn(nt)
fn_s = torch.jit.script(fn)
actual = fn_s(nt)
self.assertEqual(expected, actual)
# see #95858
@unittest.expectedFailure
def test_namedtuple_resolution_forwardref(self):
class TheType(NamedTuple):
t: "int"
class MyModule(types.ModuleType):
def __init__(self) -> None:
super().__init__("MyModule")
def __getattr__(self, attr):
return TheType
some_module = MyModule()
def fn() -> some_module.Type:
return some_module.Type(1)
self.checkScript(fn, [])
| TestNamedTuple |
python | keras-team__keras | keras/src/layers/rnn/conv_lstm1d_test.py | {
"start": 160,
"end": 2838
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basics(self):
channels_last = backend.config.image_data_format() == "channels_last"
self.run_layer_test(
layers.ConvLSTM1D,
init_kwargs={"filters": 5, "kernel_size": 3, "padding": "same"},
input_shape=(3, 2, 4, 3) if channels_last else (3, 2, 3, 4),
expected_output_shape=(3, 4, 5) if channels_last else (3, 5, 4),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
self.run_layer_test(
layers.ConvLSTM1D,
init_kwargs={
"filters": 5,
"kernel_size": 3,
"padding": "valid",
"recurrent_dropout": 0.5,
},
input_shape=(3, 2, 8, 3) if channels_last else (3, 2, 3, 8),
call_kwargs={"training": True},
expected_output_shape=(3, 6, 5) if channels_last else (3, 5, 6),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
self.run_layer_test(
layers.ConvLSTM1D,
init_kwargs={
"filters": 5,
"kernel_size": 3,
"padding": "valid",
"return_sequences": True,
},
input_shape=(3, 2, 8, 3) if channels_last else (3, 2, 3, 8),
expected_output_shape=(
(3, 2, 6, 5) if channels_last else (3, 2, 5, 6)
),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
def test_correctness(self):
sequence = np.arange(120).reshape((2, 3, 4, 5)).astype("float32") / 10
expected_output = np.array(
[
[[0.40807986, 0.40807986], [0.46421072, 0.46421072]],
[[0.80933154, 0.80933154], [0.8233646, 0.8233646]],
]
)
if backend.config.image_data_format() == "channels_first":
sequence = sequence.transpose((0, 1, 3, 2))
expected_output = expected_output.transpose((0, 2, 1))
layer = layers.ConvLSTM1D(
filters=2,
kernel_size=3,
kernel_initializer=initializers.Constant(0.01),
recurrent_initializer=initializers.Constant(0.02),
bias_initializer=initializers.Constant(0.03),
)
output = layer(sequence)
self.assertAllClose(
expected_output,
output,
)
| ConvLSTM1DTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/response_synthesizers/no_text.py | {
"start": 220,
"end": 796
} | class ____(BaseSynthesizer):
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
return {}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
def get_response(
self,
query_str: str,
text_chunks: Sequence[str],
**response_kwargs: Any,
) -> RESPONSE_TEXT_TYPE:
return ""
async def aget_response(
self,
query_str: str,
text_chunks: Sequence[str],
**response_kwargs: Any,
) -> RESPONSE_TEXT_TYPE:
return ""
| NoText |
python | celery__celery | t/unit/events/test_snapshot.py | {
"start": 2262,
"end": 3359
} | class ____:
class MockReceiver:
raise_keyboard_interrupt = False
def capture(self, **kwargs):
if self.__class__.raise_keyboard_interrupt:
raise KeyboardInterrupt()
class MockEvents(Events):
def Receiver(self, *args, **kwargs):
return test_evcam.MockReceiver()
def setup_method(self):
self.app.events = self.MockEvents()
self.app.events.app = self.app
def test_evcam(self, restore_logging):
evcam(Polaroid, timer=timer, app=self.app)
evcam(Polaroid, timer=timer, loglevel='CRITICAL', app=self.app)
self.MockReceiver.raise_keyboard_interrupt = True
try:
with pytest.raises(SystemExit):
evcam(Polaroid, timer=timer, app=self.app)
finally:
self.MockReceiver.raise_keyboard_interrupt = False
@patch('celery.platforms.create_pidlock')
def test_evcam_pidfile(self, create_pidlock):
evcam(Polaroid, timer=timer, pidfile='/var/pid', app=self.app)
create_pidlock.assert_called_with('/var/pid')
| test_evcam |
python | django__django | tests/delete_regress/models.py | {
"start": 3432,
"end": 3793
} | class ____(models.Model):
name = models.CharField(max_length=32)
lives_in = models.ForeignKey(House, models.CASCADE)
class Meta:
ordering = ["name"]
def get_best_toy():
toy, _ = Toy.objects.get_or_create(name="best")
return toy
def get_worst_toy():
toy, _ = Toy.objects.get_or_create(name="worst")
return toy
| OrderedPerson |
python | apache__airflow | providers/teradata/tests/unit/teradata/transfers/test_teradata_to_teradata.py | {
"start": 1439,
"end": 4285
} | class ____:
dest_teradata_conn_id = "dest_teradata_conn_id"
destination_table = "destination_table"
source_teradata_conn_id = "source_teradata_conn_id"
sql = (r"""select DATE where DATE > {{ sql_params.ref_date }} ;""",)
sql_params = {"ref_date": "2018-01-01"}
def test_source_hook(self):
op = TeradataToTeradataOperator(
task_id="transfer_data",
dest_teradata_conn_id=self.dest_teradata_conn_id,
destination_table=self.destination_table,
source_teradata_conn_id=self.source_teradata_conn_id,
sql=self.sql,
sql_params=self.sql_params,
)
hook = op.src_hook
assert hook
assert hook is op.src_hook
assert hook.teradata_conn_id == "source_teradata_conn_id"
def test_destination_hook(self):
op = TeradataToTeradataOperator(
task_id="transfer_data",
dest_teradata_conn_id=self.dest_teradata_conn_id,
destination_table=self.destination_table,
source_teradata_conn_id=self.source_teradata_conn_id,
sql=self.sql,
sql_params=self.sql_params,
)
hook = op.dest_hook
assert hook
assert hook is op.dest_hook
assert hook.teradata_conn_id == "dest_teradata_conn_id"
def test_execution(self, mocked_src_hook, mocked_dest_hook):
cursor_description = [
["user_id", Decimal, None, 8, 10, 0, False],
["user_name", str, None, 60, None, None, True],
]
cursor_rows = [[Decimal("1"), "User1"], [Decimal("2"), "User2"], [Decimal("3"), "User3"]]
mock_src_conn = mocked_src_hook.get_conn.return_value.__enter__.return_value
mock_cursor = mock_src_conn.cursor.return_value
mock_cursor.description.__iter__.return_value = cursor_description
mock_cursor.fetchmany.side_effect = [cursor_rows, []]
rows_chunk = 5000
op = TeradataToTeradataOperator(
task_id="transfer_data",
dest_teradata_conn_id=self.dest_teradata_conn_id,
destination_table=self.destination_table,
source_teradata_conn_id=self.source_teradata_conn_id,
sql=self.sql,
sql_params=self.sql_params,
)
op.execute({})
assert mocked_src_hook.get_conn.called
assert mock_src_conn.cursor.called
mock_cursor.execute.assert_called_once_with(self.sql, self.sql_params)
calls = [
mock.call(rows_chunk),
]
mock_cursor.fetchmany.assert_has_calls(calls)
mocked_dest_hook.insert_rows.assert_called_once_with(
self.destination_table,
cursor_rows,
commit_every=rows_chunk,
target_fields=["user_id", "user_name"],
)
| TestTeradataToTeradataTransfer |
python | pennersr__django-allauth | allauth/socialaccount/providers/basecamp/provider.py | {
"start": 404,
"end": 1263
} | class ____(OAuth2Provider):
id = "basecamp"
name = "Basecamp"
account_class = BasecampAccount
oauth2_adapter_class = BasecampOAuth2Adapter
def get_auth_params_from_request(self, request, action):
data = super().get_auth_params_from_request(request, action)
data["type"] = "web_server"
return data
def extract_uid(self, data):
data = data["identity"]
return str(data["id"])
def extract_common_fields(self, data):
data = data["identity"]
return dict(
email=data.get("email_address"),
username=data.get("email_address"),
first_name=data.get("first_name"),
last_name=data.get("last_name"),
name="%s %s" % (data.get("first_name"), data.get("last_name")),
)
provider_classes = [BasecampProvider]
| BasecampProvider |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 16535,
"end": 16743
} | class ____(threading.local):
"""Thread local values for Console context."""
theme_stack: ThemeStack
buffer: List[Segment] = field(default_factory=list)
buffer_index: int = 0
| ConsoleThreadLocals |
python | pandas-dev__pandas | asv_bench/benchmarks/join_merge.py | {
"start": 8841,
"end": 9785
} | class ____:
params = [
[
"Int64",
"Int32",
"Int16",
"UInt64",
"UInt32",
"UInt16",
"Float64",
"Float32",
],
[True, False],
]
param_names = ["dtype", "monotonic"]
def setup(self, dtype, monotonic):
N = 10_000
indices = np.arange(1, N)
key = np.tile(indices[:8000], 10)
self.left = DataFrame(
{"key": Series(key, dtype=dtype), "value": np.random.randn(80000)}
)
self.right = DataFrame(
{
"key": Series(indices[2000:], dtype=dtype),
"value2": np.random.randn(7999),
}
)
if monotonic:
self.left = self.left.sort_values("key")
self.right = self.right.sort_values("key")
def time_merge(self, dtype, monotonic):
merge(self.left, self.right)
| MergeEA |
python | ray-project__ray | python/ray/dashboard/modules/aggregator/publisher/ray_event_publisher.py | {
"start": 993,
"end": 1441
} | class ____(ABC):
"""Abstract interface for publishing Ray event batches to external destinations."""
@abstractmethod
async def run_forever(self) -> None:
"""Run the publisher forever until cancellation or process death."""
pass
@abstractmethod
async def wait_until_running(self, timeout: Optional[float] = None) -> bool:
"""Wait until the publisher has started."""
pass
| RayEventPublisherInterface |
python | pyinstaller__pyinstaller | tests/unit/test_pyimodulegraph.py | {
"start": 2639,
"end": 8309
} | class ____(analysis.PyiModuleGraph):
def _analyze_base_modules(self):
# suppress this to speed up set-up
self._base_modules = ()
@pytest.fixture
def fresh_pyi_modgraph(monkeypatch):
"""
Get a fresh PyiModuleGraph
"""
def fake_base_modules(self):
# speed up set up
self._base_modules = ()
logging.logger.setLevel(logging.DEBUG)
# ensure we get a fresh PyiModuleGraph
monkeypatch.setattr(analysis, "_cached_module_graph_", None)
# speed up setup
monkeypatch.setattr(analysis.PyiModuleGraph, "_analyze_base_modules", fake_base_modules)
return analysis.initialize_modgraph()
def test_cached_graph_is_not_leaking(fresh_pyi_modgraph, monkeypatch, tmp_path):
"""
Ensure cached PyiModulegraph can separate imports between scripts.
"""
mg = fresh_pyi_modgraph
# self-test 1: uuid is not included in the graph by default
src = gen_sourcefile(tmp_path, """print""", test_id="1")
mg.add_script(str(src))
assert not mg.find_node("uuid") # self-test
# self-test 2: uuid is available and included when imported
src = gen_sourcefile(tmp_path, """import uuid""", test_id="2")
node = mg.add_script(str(src))
assert node is not None
names = [n.identifier for n in mg.iter_graph(start=node)]
assert "uuid" in names
# the actual test: uuid is not leaking to the other script
src = gen_sourcefile(tmp_path, """print""", test_id="3")
node = mg.add_script(str(src))
assert node is not None
names = [n.identifier for n in mg.iter_graph(start=node)]
assert "uuid" not in names
def test_cached_graph_is_not_leaking_hidden_imports(fresh_pyi_modgraph, tmp_path):
"""
Ensure cached PyiModulegraph can separate hidden imports between scripts.
"""
mg = fresh_pyi_modgraph
# self-test 1: skipped here, see test_cached_graph_is_not_leaking
# self-test 2: uuid is included when hidden imported
src = gen_sourcefile(tmp_path, """print""", test_id="2")
node = mg.add_script(str(src))
assert node is not None
mg.add_hiddenimports(["uuid"])
names = [n.identifier for n in mg.iter_graph(start=node)]
assert "uuid" in names
# the actual test: uuid is not leaking to the other script
src = gen_sourcefile(tmp_path, """print""", test_id="3")
node = mg.add_script(str(src))
assert node is not None
names = [n.identifier for n in mg.iter_graph(start=node)]
assert "uuid" not in names
def test_graph_collects_script_dependencies(fresh_pyi_modgraph, tmp_path):
mg = fresh_pyi_modgraph
# self-test 1: uuid is not included in the graph by default
src1 = gen_sourcefile(tmp_path, """print""", test_id="1")
node = mg.add_script(str(src1))
assert node is not None
assert not mg.find_node("uuid") # self-test
# Add script importing uuid
src2 = gen_sourcefile(tmp_path, """import uuid""", test_id="2")
mg.add_script(str(src2))
assert mg.find_node("uuid") # self-test
# The actual test: uuid is (indirectly) linked to the first script
names = [n.identifier for n in mg.iter_graph(start=node)]
assert str(src2) in names
assert "uuid" in names
def _gen_pseudo_rthooks(name, rthook_dat, tmp_path, gen_files=True):
# Create hooks directory
hooks_dir = tmp_path / name
rthooks_dir = hooks_dir / 'rthooks'
rthooks_dir.mkdir(parents=True)
# Create hook files
if gen_files:
for hook_file in itertools.chain(*rthook_dat.values()):
(rthooks_dir / hook_file).touch() # Create empty hook file
# Create rthooks.dat file
(hooks_dir / 'rthooks.dat').write_text(repr(rthook_dat), encoding='utf-8')
return hooks_dir
def test_collect_rthooks_1(tmp_path, monkeypatch):
rh1 = {"test_pyimodulegraph_mymod1": ["m1.py"]}
hd1 = _gen_pseudo_rthooks("h1", rh1, tmp_path)
mg = FakePyiModuleGraph(
HOMEPATH,
user_hook_dirs=[
(str(hd1), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
],
)
assert len(mg._available_rthooks["test_pyimodulegraph_mymod1"]) == 1
def test_collect_rthooks_2(tmp_path, monkeypatch):
rh1 = {"test_pyimodulegraph_mymod1": ["m1.py"]}
rh2 = {"test_pyimodulegraph_mymod2": ["rth1.py", "rth1.py"]}
hd1 = _gen_pseudo_rthooks("h1", rh1, tmp_path)
hd2 = _gen_pseudo_rthooks("h2", rh2, tmp_path)
mg = FakePyiModuleGraph(
HOMEPATH,
user_hook_dirs=[
(str(hd1), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
(str(hd2), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
],
)
assert len(mg._available_rthooks["test_pyimodulegraph_mymod1"]) == 1
assert len(mg._available_rthooks["test_pyimodulegraph_mymod2"]) == 2
def test_collect_rthooks_3(tmp_path, monkeypatch):
rh1 = {"test_pyimodulegraph_mymod1": ["m1.py"]}
rh2 = {"test_pyimodulegraph_mymod1": ["rth1.py", "rth1.py"]}
hd1 = _gen_pseudo_rthooks("h1", rh1, tmp_path)
hd2 = _gen_pseudo_rthooks("h2", rh2, tmp_path)
mg = FakePyiModuleGraph(
HOMEPATH,
user_hook_dirs=[
(str(hd1), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
(str(hd2), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
],
)
assert len(mg._available_rthooks["test_pyimodulegraph_mymod1"]) == 1
def test_collect_rthooks_fail_1(tmp_path, monkeypatch):
rh1 = {"test_pyimodulegraph_mymod1": ["m1.py"]}
hd1 = _gen_pseudo_rthooks("h1", rh1, tmp_path, False)
with pytest.raises(AssertionError):
FakePyiModuleGraph(
HOMEPATH,
user_hook_dirs=[
(str(hd1), analysis.HOOK_PRIORITY_BUILTIN_HOOKS),
],
)
| FakePyiModuleGraph |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py | {
"start": 1307,
"end": 2157
} | class ____(BaseModel):
"""Options for Cloudflare AI Gateway requests."""
cache_key: Optional[str] = Field(default=None, description="Custom cache key")
cache_ttl: Optional[int] = Field(
default=None, ge=0, description="Cache time-to-live in seconds"
)
skip_cache: bool = Field(default=False, description="Bypass caching")
metadata: Optional[Dict[str, Union[str, int, bool, None]]] = Field(
default=None, description="Custom metadata for the request"
)
collect_log: Optional[bool] = Field(
default=None, description="Enable/disable log collection"
)
event_id: Optional[str] = Field(default=None, description="Custom event identifier")
request_timeout_ms: Optional[int] = Field(
default=None, ge=0, description="Request timeout in milliseconds"
)
| CloudflareAIGatewayOptions |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cuda.py | {
"start": 204,
"end": 314
} | class ____:
pass
def cuDeviceGetCount():
return (CUresult.CUDA_SUCCESS, torch.cuda.device_count())
| nvrtc |
python | tox-dev__tox | src/tox/session/state.py | {
"start": 441,
"end": 1712
} | class ____:
"""Runtime state holder."""
def __init__(self, options: Options, args: Sequence[str]) -> None:
(extended_envs,) = tee(chain.from_iterable(MANAGER.tox_extend_envs()), 1)
self.conf = Config.make(options.parsed, options.pos_args, options.source, extended_envs)
self.conf.core.add_constant(
keys=["on_platform"],
desc="platform we are running on",
value=sys.platform,
)
self._options = options
self.args = args
self._journal: Journal = Journal(getattr(options.parsed, "result_json", None) is not None)
self._selector: EnvSelector | None = None
@property
def envs(self) -> EnvSelector:
""":return: provides access to the tox environments"""
if self._selector is None:
self._selector = EnvSelector(self)
return self._selector
@impl
def tox_add_option(parser: ToxParser) -> None:
from tox.tox_env.register import REGISTER # noqa: PLC0415
parser.add_argument(
"--runner",
dest="default_runner",
help="the tox run engine to use when not explicitly stated in tox env configuration",
default=REGISTER.default_env_runner,
choices=list(REGISTER.env_runners),
)
| State |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/GradientEditorItem.py | {
"start": 767,
"end": 14399
} | class ____(GraphicsWidget):
## public class
"""**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
A rectangular item with tick marks along its length that can (optionally) be moved by the user."""
sigTicksChanged = QtCore.Signal(object)
sigTicksChangeFinished = QtCore.Signal(object)
def __init__(self, orientation='bottom', allowAdd=True, allowRemove=True, **kargs):
"""
============== =================================================================================
**Arguments:**
orientation Set the orientation of the gradient. Options are: 'left', 'right'
'top', and 'bottom'.
allowAdd Specifies whether the user can add ticks.
allowRemove Specifies whether the user can remove new ticks.
tickPen Default is white. Specifies the color of the outline of the ticks.
Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>`
============== =================================================================================
"""
## public
GraphicsWidget.__init__(self)
self.orientation = orientation
self.length = 100
self.tickSize = 15
self.ticks = {}
self.maxDim = 20
self.allowAdd = allowAdd
self.allowRemove = allowRemove
if 'tickPen' in kargs:
self.tickPen = fn.mkPen(kargs['tickPen'])
else:
self.tickPen = fn.mkPen('w')
self.orientations = {
'left': (90, 1, 1),
'right': (90, 1, 1),
'top': (0, 1, -1),
'bottom': (0, 1, 1)
}
self.setOrientation(orientation)
#self.setFrameStyle(QtWidgets.QFrame.Shape.NoFrame | QtWidgets.QFrame.Shadow.Plain)
#self.setBackgroundRole(QtGui.QPalette.ColorRole.NoRole)
#self.setMouseTracking(True)
#def boundingRect(self):
#return self.mapRectFromParent(self.geometry()).normalized()
#def shape(self): ## No idea why this is necessary, but rotated items do not receive clicks otherwise.
#p = QtGui.QPainterPath()
#p.addRect(self.boundingRect())
#return p
def paint(self, p, opt, widget):
#p.setPen(fn.mkPen('g', width=3))
#p.drawRect(self.boundingRect())
return
def keyPressEvent(self, ev):
ev.ignore()
def setMaxDim(self, mx=None):
if mx is None:
mx = self.maxDim
else:
self.maxDim = mx
if self.orientation in ['bottom', 'top']:
self.setFixedHeight(mx)
self.setMaximumWidth(16777215)
else:
self.setFixedWidth(mx)
self.setMaximumHeight(16777215)
def setOrientation(self, orientation):
## public
"""Set the orientation of the TickSliderItem.
============== ===================================================================
**Arguments:**
orientation Options are: 'left', 'right', 'top', 'bottom'
The orientation option specifies which side of the slider the
ticks are on, as well as whether the slider is vertical ('right'
and 'left') or horizontal ('top' and 'bottom').
============== ===================================================================
"""
self.orientation = orientation
self.setMaxDim()
self.resetTransform()
ort = orientation
if ort == 'top':
transform = QtGui.QTransform.fromScale(1, -1)
transform.translate(0, -self.height())
self.setTransform(transform)
elif ort == 'left':
transform = QtGui.QTransform()
transform.rotate(270)
transform.scale(1, -1)
transform.translate(-self.height(), -self.maxDim)
self.setTransform(transform)
elif ort == 'right':
transform = QtGui.QTransform()
transform.rotate(270)
transform.translate(-self.height(), 0)
self.setTransform(transform)
elif ort != 'bottom':
raise Exception("%s is not a valid orientation. Options are 'left', 'right', 'top', and 'bottom'" %str(ort))
tr = QtGui.QTransform.fromTranslate(self.tickSize/2., 0)
self.setTransform(tr, True)
def addTick(self, x, color=None, movable=True, finish=True):
## public
"""
Add a tick to the item.
============== ==================================================================
**Arguments:**
x Position where tick should be added.
color Color of added tick. If color is not specified, the color will be
white.
movable Specifies whether the tick is movable with the mouse.
============== ==================================================================
"""
if color is None:
color = QtGui.QColor(255,255,255)
tick = Tick([x*self.length, 0], color, movable, self.tickSize, pen=self.tickPen, removeAllowed=self.allowRemove)
self.ticks[tick] = x
tick.setParentItem(self)
tick.sigMoving.connect(self.tickMoved)
tick.sigMoved.connect(self.tickMoveFinished)
tick.sigClicked.connect(self.tickClicked)
self.sigTicksChanged.emit(self)
if finish:
self.sigTicksChangeFinished.emit(self)
return tick
def removeTick(self, tick, finish=True):
## public
"""
Removes the specified tick.
"""
del self.ticks[tick]
tick.setParentItem(None)
if self.scene() is not None:
self.scene().removeItem(tick)
self.sigTicksChanged.emit(self)
if finish:
self.sigTicksChangeFinished.emit(self)
@QtCore.Slot(object, object)
def tickMoved(self, tick, pos):
#print "tick changed"
## Correct position of tick if it has left bounds.
newX = min(max(0, pos.x()), self.length)
pos.setX(newX)
tick.setPos(pos)
self.ticks[tick] = float(newX) / self.length
self.sigTicksChanged.emit(self)
@QtCore.Slot(object)
def tickMoveFinished(self, tick):
self.sigTicksChangeFinished.emit(self)
def tickClicked(self, tick, ev):
if ev.button() == QtCore.Qt.MouseButton.RightButton and tick.removeAllowed:
self.removeTick(tick)
def widgetLength(self):
if self.orientation in ['bottom', 'top']:
return self.width()
else:
return self.height()
def resizeEvent(self, ev):
wlen = max(40, self.widgetLength())
self.setLength(wlen-self.tickSize-2)
self.setOrientation(self.orientation)
#bounds = self.scene().itemsBoundingRect()
#bounds.setLeft(min(-self.tickSize*0.5, bounds.left()))
#bounds.setRight(max(self.length + self.tickSize, bounds.right()))
#self.setSceneRect(bounds)
#self.fitInView(bounds, QtCore.Qt.AspectRatioMode.KeepAspectRatio)
def setLength(self, newLen):
#private
for t, x in list(self.ticks.items()):
t.setPos(x * newLen + 1, t.pos().y())
self.length = float(newLen)
#def mousePressEvent(self, ev):
#QtWidgets.QGraphicsView.mousePressEvent(self, ev)
#self.ignoreRelease = False
#for i in self.items(ev.pos()):
#if isinstance(i, Tick):
#self.ignoreRelease = True
#break
##if len(self.items(ev.pos())) > 0: ## Let items handle their own clicks
##self.ignoreRelease = True
#def mouseReleaseEvent(self, ev):
#QtWidgets.QGraphicsView.mouseReleaseEvent(self, ev)
#if self.ignoreRelease:
#return
#pos = self.mapToScene(ev.pos())
#if ev.button() == QtCore.Qt.MouseButton.LeftButton and self.allowAdd:
#if pos.x() < 0 or pos.x() > self.length:
#return
#if pos.y() < 0 or pos.y() > self.tickSize:
#return
#pos.setX(min(max(pos.x(), 0), self.length))
#self.addTick(pos.x()/self.length)
#elif ev.button() == QtCore.Qt.MouseButton.RightButton:
#self.showMenu(ev)
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.LeftButton and self.allowAdd:
pos = ev.pos()
if pos.x() < 0 or pos.x() > self.length:
return
if pos.y() < 0 or pos.y() > self.tickSize:
return
pos.setX(min(max(pos.x(), 0), self.length))
self.addTick(pos.x()/self.length)
elif ev.button() == QtCore.Qt.MouseButton.RightButton:
self.showMenu(ev)
#if ev.button() == QtCore.Qt.MouseButton.RightButton:
#if self.moving:
#ev.accept()
#self.setPos(self.startPosition)
#self.moving = False
#self.sigMoving.emit(self)
#self.sigMoved.emit(self)
#else:
#pass
#self.view().tickClicked(self, ev)
###remove
def hoverEvent(self, ev):
if (not ev.isExit()) and ev.acceptClicks(QtCore.Qt.MouseButton.LeftButton):
ev.acceptClicks(QtCore.Qt.MouseButton.RightButton)
## show ghost tick
#self.currentPen = fn.mkPen(255, 0,0)
#else:
#self.currentPen = self.pen
#self.update()
def showMenu(self, ev):
pass
def setTickColor(self, tick, color):
"""Set the color of the specified tick.
============== ==================================================================
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
color The color to make the tick. Can be any argument that is valid for
:func:`mkBrush <pyqtgraph.mkBrush>`
============== ==================================================================
"""
tick = self.getTick(tick)
tick.color = color
tick.update()
#tick.setBrush(QtGui.QBrush(QtGui.QColor(tick.color)))
self.sigTicksChanged.emit(self)
self.sigTicksChangeFinished.emit(self)
def setTickValue(self, tick, val):
## public
"""
Set the position (along the slider) of the tick.
============== ==================================================================
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted to change the middle tick, the index would be 1.
val The desired position of the tick. If val is < 0, position will be
set to 0. If val is > 1, position will be set to 1.
============== ==================================================================
"""
tick = self.getTick(tick)
val = min(max(0.0, val), 1.0)
x = val * self.length
pos = tick.pos()
pos.setX(x)
tick.setPos(pos)
self.ticks[tick] = val
self.update()
self.sigTicksChanged.emit(self)
self.sigTicksChangeFinished.emit(self)
def tickValue(self, tick):
## public
"""Return the value (from 0.0 to 1.0) of the specified tick.
============== ==================================================================
**Arguments:**
tick Can be either an integer corresponding to the index of the tick
or a Tick object. Ex: if you had a slider with 3 ticks and you
wanted the value of the middle tick, the index would be 1.
============== ==================================================================
"""
tick = self.getTick(tick)
return self.ticks[tick]
def getTick(self, tick):
## public
"""Return the Tick object at the specified index.
============== ==================================================================
**Arguments:**
tick An integer corresponding to the index of the desired tick. If the
argument is not an integer it will be returned unchanged.
============== ==================================================================
"""
if type(tick) is int:
tick = self.listTicks()[tick][0]
return tick
#def mouseMoveEvent(self, ev):
#QtWidgets.QGraphicsView.mouseMoveEvent(self, ev)
def listTicks(self):
"""Return a sorted list of all the Tick objects on the slider."""
## public
ticks = sorted(self.ticks.items(), key=operator.itemgetter(1))
return ticks
| TickSliderItem |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_nbagg.py | {
"start": 1558,
"end": 2026
} | class ____(NavigationToolbar2WebAgg):
# Use the standard toolbar items + download button
toolitems = [(text, tooltip_text,
_FONT_AWESOME_CLASSES[image_file], name_of_method)
for text, tooltip_text, image_file, name_of_method
in (NavigationToolbar2.toolitems +
(('Download', 'Download plot', 'download', 'download'),))
if image_file in _FONT_AWESOME_CLASSES]
| NavigationIPy |
python | spack__spack | lib/spack/spack/oci/opener.py | {
"start": 1989,
"end": 5913
} | class ____:
__slots__ = ["scheme", "params"]
def __init__(
self, scheme: Optional[str] = None, params: Optional[List[Tuple[str, str]]] = None
) -> None:
self.scheme = scheme or ""
self.params = params or []
def __repr__(self) -> str:
return f"Challenge({self.scheme}, {self.params})"
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Challenge)
and self.scheme == other.scheme
and self.params == other.params
)
def parse_www_authenticate(input: str):
"""Very basic parsing of www-authenticate parsing (RFC7235 section 4.1)
Notice: this omits token68 support."""
# auth-scheme = token
# auth-param = token BWS "=" BWS ( token / quoted-string )
# challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ]
# WWW-Authenticate = 1#challenge
challenges: List[Challenge] = []
_unquote = re.compile(quoted_pair).sub
unquote = lambda s: _unquote(r"\1", s[1:-1])
mode: State = State.CHALLENGE
tokens = WWW_AUTHENTICATE_TOKENIZER.tokenize(input)
current_challenge = Challenge()
def extract_auth_param(input: str) -> Tuple[str, str]:
key, value = input.split("=", 1)
key = key.rstrip()
value = value.lstrip()
if value.startswith('"'):
value = unquote(value)
return key, value
while True:
token: spack.tokenize.Token = next(tokens)
if mode == State.CHALLENGE:
if token.kind == WwwAuthenticateTokens.EOF:
raise ValueError(token)
elif token.kind == WwwAuthenticateTokens.TOKEN:
current_challenge.scheme = token.value
mode = State.AUTH_PARAM_LIST_START
else:
raise ValueError(token)
elif mode == State.AUTH_PARAM_LIST_START:
if token.kind == WwwAuthenticateTokens.EOF:
challenges.append(current_challenge)
break
elif token.kind == WwwAuthenticateTokens.COMMA:
# Challenge without param list, followed by another challenge.
challenges.append(current_challenge)
current_challenge = Challenge()
mode = State.CHALLENGE
elif token.kind == WwwAuthenticateTokens.SPACE:
# A space means it must be followed by param list
mode = State.AUTH_PARAM
else:
raise ValueError(token)
elif mode == State.AUTH_PARAM:
if token.kind == WwwAuthenticateTokens.EOF:
raise ValueError(token)
elif token.kind == WwwAuthenticateTokens.AUTH_PARAM:
key, value = extract_auth_param(token.value)
current_challenge.params.append((key, value))
mode = State.NEXT_IN_LIST
else:
raise ValueError(token)
elif mode == State.NEXT_IN_LIST:
if token.kind == WwwAuthenticateTokens.EOF:
challenges.append(current_challenge)
break
elif token.kind == WwwAuthenticateTokens.COMMA:
mode = State.AUTH_PARAM_OR_SCHEME
else:
raise ValueError(token)
elif mode == State.AUTH_PARAM_OR_SCHEME:
if token.kind == WwwAuthenticateTokens.EOF:
raise ValueError(token)
elif token.kind == WwwAuthenticateTokens.TOKEN:
challenges.append(current_challenge)
current_challenge = Challenge(token.value)
mode = State.AUTH_PARAM_LIST_START
elif token.kind == WwwAuthenticateTokens.AUTH_PARAM:
key, value = extract_auth_param(token.value)
current_challenge.params.append((key, value))
mode = State.NEXT_IN_LIST
return challenges
| Challenge |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/name_conflict/__init__.py | {
"start": 23,
"end": 94
} | class ____:
"""docstring of target.name_conflict::foo."""
pass
| foo |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_internal_app_tokens.py | {
"start": 1155,
"end": 3974
} | class ____(SentryAppBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
authentication_classes = (SessionNoAuthTokenAuthentication,)
permission_classes = (SentryInternalAppTokenPermission,)
def get(self, request: Request, sentry_app) -> Response:
if not sentry_app.is_internal:
return Response([])
tokens = ApiToken.objects.filter(application_id=sentry_app.application_id)
attrs = {"application": None}
token_list = [
ApiTokenSerializer().serialize(token, attrs, request.user, include_token=False)
for token in tokens
]
if not sentry_app.show_auth_info(request.access):
for token in token_list:
token["token"] = MASKED_VALUE
token["refreshToken"] = MASKED_VALUE
return Response(token_list)
def post(self, request: Request, sentry_app) -> Response:
if not sentry_app.is_internal:
return Response(
"This route is limited to internal integrations only",
status=status.HTTP_403_FORBIDDEN,
)
if sentry_app.metadata.get("partnership_restricted", False):
return Response(
{"detail": PARTNERSHIP_RESTRICTED_ERROR_MESSAGE},
status=403,
)
sentry_app_installation = SentryAppInstallation.objects.get(sentry_app_id=sentry_app.id)
try:
assert isinstance(
request.user, (User, RpcUser)
), "User must be authenticated to install a sentry app"
api_token = SentryAppInstallationTokenCreator(
sentry_app_installation=sentry_app_installation
).run(request=request, user=request.user)
create_audit_entry(
request=request,
organization_id=sentry_app_installation.organization_id,
target_object=api_token.id,
event=audit_log.get_event_id("INTERNAL_INTEGRATION_ADD_TOKEN"),
data={
"sentry_app_slug": sentry_app.slug,
"sentry_app_installation_uuid": sentry_app_installation.uuid,
},
)
except ApiTokenLimitError as e:
return Response(str(e), status=status.HTTP_403_FORBIDDEN)
# hack so the token is included in the response
attrs = {"application": None}
token = ApiTokenSerializer().serialize(api_token, attrs, request.user)
if not sentry_app.show_auth_info(request.access):
token["token"] = MASKED_VALUE
token["refreshToken"] = MASKED_VALUE
return Response(token, status=201)
| SentryInternalAppTokensEndpoint |
python | openai__openai-python | src/openai/types/beta/threads/runs/run_step.py | {
"start": 486,
"end": 838
} | class ____(BaseModel):
code: Literal["server_error", "rate_limit_exceeded"]
"""One of `server_error` or `rate_limit_exceeded`."""
message: str
"""A human-readable description of the error."""
StepDetails: TypeAlias = Annotated[
Union[MessageCreationStepDetails, ToolCallsStepDetails], PropertyInfo(discriminator="type")
]
| LastError |
python | kamyu104__LeetCode-Solutions | Python/check-if-digits-are-equal-in-string-after-operations-i.py | {
"start": 55,
"end": 1000
} | class ____(object):
def hasSameDigits(self, s):
"""
:type s: str
:rtype: bool
"""
def check(mod):
def decompose(x, mod): # x = a * mod^cnt
cnt = 0
while x > 1 and x%mod == 0:
x //= mod
cnt += 1
return x, cnt
result = cnt = 0
curr = 1
for i in xrange(len(s)-1):
if cnt == 0:
result = (result+curr*(ord(s[i])-ord(s[i+1])))%mod
x, c = decompose(len(s)-2-i, mod)
curr = (curr*x)%mod
cnt += c
x, c = decompose(i+1, mod)
curr = (curr*pow(x, mod-2, mod))%mod
cnt -= c
return result == 0
return check(2) and check(5)
# Time: O(nlogn)
# Space: O(1)
LOOKUP = [[-1]*(5+1) for _ in xrange(5+1)]
# lucas's theorem
| Solution |
python | tensorflow__tensorflow | tensorflow/tools/docs/fenced_doctest_lib.py | {
"start": 2580,
"end": 7995
} | class ____(doctest.DocTestParser):
"""Implements test parsing for ``` fenced cells.
https://docs.python.org/3/library/doctest.html#doctestparser-objects
The `get_examples` method receives a string and returns an
iterable of `doctest.Example` objects.
"""
patched = False
def __init__(self, fence_label='python'):
super().__init__()
if not self.patched:
# The default doctest compiles in "single" mode. The fenced block may
# contain multiple statements. The `_patch_compile` function fixes the
# compile mode.
doctest.compile = _patch_compile
print(
textwrap.dedent("""
*********************************************************************
* Caution: `fenced_doctest` patches `doctest.compile` don't use this
* in the same binary as any other doctests.
*********************************************************************
"""))
type(self).patched = True
# Match anything, except if the look-behind sees a closing fence.
no_fence = '(.(?<!```))*?'
self.fence_cell_re = re.compile(
rf"""
^( # After a newline
\s*```\s*({fence_label})\n # Open a labeled ``` fence
(?P<doctest>{no_fence}) # Match anything except a closing fence
\n\s*```\s*(\n|$) # Close the fence.
)
( # Optional!
[\s\n]* # Any number of blank lines.
```\s*\n # Open ```
(?P<output>{no_fence}) # Anything except a closing fence
\n\s*``` # Close the fence.
)?
""",
# Multiline so ^ matches after a newline
re.MULTILINE |
# Dotall so `.` matches newlines.
re.DOTALL |
# Verbose to allow comments/ignore-whitespace.
re.VERBOSE)
def get_examples(self,
string: str,
name: str = '<string>') -> Iterable[doctest.Example]:
# Check for a file-level skip comment.
if re.search('<!--.*?doctest.*?skip.*?all.*?-->', string, re.IGNORECASE):
return
for match in self.fence_cell_re.finditer(string):
if re.search('doctest.*skip', match.group(0), re.IGNORECASE):
continue
groups = match.groupdict()
source = textwrap.dedent(groups['doctest'])
want = groups['output']
if want is not None:
want = textwrap.dedent(want)
yield doctest.Example(
lineno=string[:match.start()].count('\n') + 1,
source=source,
want=want)
def _print_if_not_none(obj):
"""Print like a notebook: Show the repr if the object is not None.
`_patch_compile` Uses this on the final expression in each cell.
This way the outputs feel like notebooks.
Args:
obj: the object to print.
"""
if obj is not None:
print(repr(obj))
def _patch_compile(source,
filename,
mode,
flags=0,
dont_inherit=False,
optimize=-1):
"""Patch `doctest.compile` to make doctest to behave like a notebook.
Default settings for doctest are configured to run like a repl: one statement
at a time. The doctest source uses `compile(..., mode="single")`
So to let doctest act like a notebook:
1. We need `mode="exec"` (easy)
2. We need the last expression to be printed (harder).
To print the last expression, just wrap the last expression in
`_print_if_not_none(expr)`. To detect the last expression use `AST`.
If the last node is an expression modify the ast to call
`_print_if_not_none` on it, convert the ast back to source and compile that.
https://docs.python.org/3/library/functions.html#compile
Args:
source: Can either be a normal string, a byte string, or an AST object.
filename: Argument should give the file from which the code was read; pass
some recognizable value if it wasn’t read from a file ('<string>' is
commonly used).
mode: [Ignored] always use exec.
flags: Compiler options.
dont_inherit: Compiler options.
optimize: Compiler options.
Returns:
The resulting code object.
"""
# doctest passes some dummy string as the file name, AFAICT
# but tf.function freaks-out if this doesn't look like a
# python file name.
del filename
# Doctest always passes "single" here, you need exec for multiple lines.
del mode
source_ast = ast.parse(source)
final = source_ast.body[-1]
if isinstance(final, ast.Expr):
# Wrap the final expression as `_print_if_not_none(expr)`
print_it = ast.Expr(
lineno=-1,
col_offset=-1,
value=ast.Call(
func=ast.Name(
id='_print_if_not_none',
ctx=ast.Load(),
lineno=-1,
col_offset=-1),
lineno=-1,
col_offset=-1,
args=[final], # wrap the final Expression
keywords=[]))
source_ast.body[-1] = print_it
# It's not clear why this step is necessary. `compile` is supposed to handle
# AST directly.
source = astor.to_source(source_ast)
return compile(
source,
filename='dummy.py',
mode='exec',
flags=flags,
dont_inherit=dont_inherit,
optimize=optimize)
| FencedCellParser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.