language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pytorch__pytorch | torch/onnx/_internal/torchscript_exporter/_experimental.py | {
"start": 235,
"end": 1033
} | class ____:
"""Arguments used by :func:`torch.onnx.export`."""
# TODO(justinchuby): Deprecate and remove this class.
export_params: bool = True
verbose: bool = False
training: _C_onnx.TrainingMode = _C_onnx.TrainingMode.EVAL
input_names: Optional[Sequence[str]] = None
output_names: Optional[Sequence[str]] = None
operator_export_type: _C_onnx.OperatorExportTypes = _C_onnx.OperatorExportTypes.ONNX
opset_version: Optional[int] = None
do_constant_folding: bool = True
dynamic_axes: Optional[Mapping[str, Union[Mapping[int, str], Sequence[int]]]] = None
keep_initializers_as_inputs: Optional[bool] = None
custom_opsets: Optional[Mapping[str, int]] = None
export_modules_as_functions: Union[bool, set[type[torch.nn.Module]]] = False
| ExportOptions |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 63225,
"end": 69486
} | class ____(XLNetPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.transformer = XLNetModel(config)
self.sequence_summary = XLNetSequenceSummary(config)
self.logits_proj = nn.Linear(config.d_model, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
mems: Optional[torch.Tensor] = None,
perm_mask: Optional[torch.Tensor] = None,
target_mapping: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
input_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
use_mems: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs, # delete when `use_cache` is removed in XLNetModel
) -> Union[tuple, XLNetForSequenceClassificationOutput]:
r"""
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
they have already been computed.
`use_mems` has to be set to `True` to make use of `mems`.
perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
- if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
- if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
If not set, each token attends to all the others (full bidirectional attention). Only used during
pretraining (to define factorization order) or for sequential decoding (generation).
target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
(generation).
input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
real tokens and 1 for padding which is kept for compatibility with the original code base.
Mask values selected in `[0, 1]`:
- 1 for tokens that are **masked**,
- 0 for tokens that are **not masked**.
You can only uses one of `input_mask` and `attention_mask`.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
use_mems (`bool`, *optional*):
Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
states from previous forward passes to compute attention, which can significantly improve performance for
sequential decoding tasks.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
mems=mems,
perm_mask=perm_mask,
target_mapping=target_mapping,
token_type_ids=token_type_ids,
input_mask=input_mask,
inputs_embeds=inputs_embeds,
use_mems=use_mems,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
**kwargs,
)
output = transformer_outputs[0]
output = self.sequence_summary(output)
logits = self.logits_proj(output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return XLNetForSequenceClassificationOutput(
loss=loss,
logits=logits,
mems=transformer_outputs.mems,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
@auto_docstring
| XLNetForSequenceClassification |
python | boto__boto3 | boto3/resources/base.py | {
"start": 632,
"end": 1977
} | class ____:
"""
An object containing metadata about a resource.
"""
def __init__(
self,
service_name,
identifiers=None,
client=None,
data=None,
resource_model=None,
):
#: (``string``) The service name, e.g. 's3'
self.service_name = service_name
if identifiers is None:
identifiers = []
#: (``list``) List of identifier names
self.identifiers = identifiers
#: (:py:class:`~botocore.client.BaseClient`) Low-level Botocore client
self.client = client
#: (``dict``) Loaded resource data attributes
self.data = data
# The resource model for that resource
self.resource_model = resource_model
def __repr__(self):
return f'ResourceMeta(\'{self.service_name}\', identifiers={self.identifiers})'
def __eq__(self, other):
# Two metas are equal if their components are all equal
if other.__class__.__name__ != self.__class__.__name__:
return False
return self.__dict__ == other.__dict__
def copy(self):
"""
Create a copy of this metadata object.
"""
params = self.__dict__.copy()
service_name = params.pop('service_name')
return ResourceMeta(service_name, **params)
| ResourceMeta |
python | pytorch__pytorch | test/test_mps.py | {
"start": 380014,
"end": 381950
} | class ____(TestCase):
def _test_topk(self, shape, largest):
cpu_x = torch.randn(shape, device='cpu', dtype=torch.float, requires_grad=False)
x = cpu_x.detach().clone().to('mps')
if isinstance(shape, tuple):
for curr_dim, dim_size in enumerate(shape):
for k in range(1, dim_size + 1):
topk_values, topk_indices = torch.topk(x, k, dim=curr_dim, largest=largest)
topk_values_cpu, topk_indices_cpu = torch.topk(cpu_x, k, dim=curr_dim, largest=largest)
self.assertEqual(topk_values, topk_values_cpu)
self.assertEqual(topk_indices, topk_indices_cpu)
else:
for k in range(1, shape):
topk_values, topk_indices = torch.topk(x, k, dim=0, largest=largest)
topk_values_cpu, topk_indices_cpu = torch.topk(cpu_x, k, dim=0, largest=largest)
self.assertEqual(topk_values, topk_values_cpu)
self.assertEqual(topk_indices, topk_indices_cpu)
def test_topk(self):
largest_vals = [True, False]
shapes = [
# Zero Element Tensors
0,
(1, 0),
(0, 1),
(1, 0, 1),
# Multiple Element Tensors
1,
2,
(5, 1),
(1, 5),
(5, 9, 7, 4),
]
for shape in shapes:
for largest_val in largest_vals:
with self.subTest(shape=shape, largest_val=largest_val):
self._test_topk(shape, largest_val)
def test_topk_gt_4d(self):
a = torch.ones(5, 4, 3, 2, 1, dtype=torch.float).to('mps')
try:
t_mps = torch.ops.aten.topk(a, k=5, dim=0)
except Exception as e:
e_string = str(e)
self.assertEqual(e_string, "On-going issue on MPSGraph topk when ndims() - axis > 4, see issue #154890")
| TestTopK |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 28267,
"end": 28551
} | class ____(NamedTuple("_CancelExecutionResult", [("can_cancel", bool)])):
def __new__(cls, can_cancel: bool):
return super().__new__(
cls,
can_cancel=check.bool_param(can_cancel, "can_cancel"),
)
@whitelist_for_serdes
| CanCancelExecutionResult |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1060251,
"end": 1060411
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (Gist, Repository)
| PinnableItem |
python | doocs__leetcode | solution/0700-0799/0706.Design HashMap/Solution.py | {
"start": 0,
"end": 444
} | class ____:
def __init__(self):
self.data = [-1] * 1000001
def put(self, key: int, value: int) -> None:
self.data[key] = value
def get(self, key: int) -> int:
return self.data[key]
def remove(self, key: int) -> None:
self.data[key] = -1
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
| MyHashMap |
python | django__django | tests/apps/apps.py | {
"start": 374,
"end": 412
} | class ____:
name = "apps"
| NotAConfig |
python | PrefectHQ__prefect | src/prefect/server/schemas/core.py | {
"start": 45080,
"end": 45493
} | class ____(ORMBaseModel):
flow_run_id: UUID = Field(description="The flow run ID associated with the input.")
key: Annotated[str, AfterValidator(raise_on_name_alphanumeric_dashes_only)] = Field(
description="The key of the input."
)
value: str = Field(description="The value of the input.")
sender: Optional[str] = Field(default=None, description="The sender of the input.")
| FlowRunInput |
python | doocs__leetcode | solution/2500-2599/2501.Longest Square Streak in an Array/Solution2.py | {
"start": 0,
"end": 306
} | class ____:
def longestSquareStreak(self, nums: List[int]) -> int:
@cache
def dfs(x: int) -> int:
if x not in s:
return 0
return 1 + dfs(x * x)
s = set(nums)
ans = max(dfs(x) for x in s)
return -1 if ans < 2 else ans
| Solution |
python | fluentpython__example-code | attic/concurrency/wikipedia/orig/sync.py | {
"start": 607,
"end": 3459
} | class ____(ValueError):
"""Raised if unable to parse POTD MediaWiki source"""
def fetch_potd_url(iso_date):
"""Fetch picture name from iso_date ('YYYY-MM-DD' format)"""
potd_url = POTD_BASE_URL + iso_date
with contextlib.closing(urllib2.urlopen(potd_url)) as fp:
html = fp.read()
thumb_src = THUMB_SRC_RE.search(html)
if not thumb_src:
msg = 'cannot find thumbnail source for ' + potd_url
raise ParsingException(msg)
thumb_url = THUMB_BASE_URL+thumb_src.group(1)
return thumb_url
def gen_month_days(year, month):
a_date = datetime.date(year, month, 1)
one_day = datetime.timedelta(1)
while a_date.month == month:
yield a_date
a_date += one_day
def get_img_names(iso_month):
"""Fetch picture names from iso_month ('YYYY-MM' format)"""
year, month = (int(part) for part in iso_month.split('-'))
for day in gen_month_days(year, month):
iso_date = '{:%Y-%m-%d}'.format(day)
if verbose:
print(iso_date)
try:
img_url = fetch_potd_url(iso_date)
except urllib2.HTTPError:
break
yield (iso_date, img_url)
def fetch_image(iso_date, img_url):
if verbose:
print('\t' + img_url)
with contextlib.closing(urllib2.urlopen(img_url)) as fp:
img = fp.read()
img_filename = iso_date + '__' + img_url.split('/')[-1]
if verbose:
print('\t\twriting %0.1f Kbytes' % (len(img)/1024.0))
img_path = os.path.join(LOCAL_IMG_PATH, img_filename)
with io.open(img_path, 'wb') as fp:
fp.write(img)
return len(img)
def get_images(iso_month, max_count=0):
if max_count is 0:
max_count = sys.maxsize
img_count = 0
total_size = 0
for iso_date, img_url in get_img_names(iso_month):
total_size += fetch_image(iso_date, img_url)
img_count += 1
if img_count == max_count:
break
return (img_count, total_size)
def main():
"""Get "Pictures of The Day" from English Wikipedia for a given month"""
global verbose
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('year_month', help='year and month in YYYY-MM format')
parser.add_argument('-q', '--max_qty', type=int,
help='maximum number of files to download')
parser.add_argument('-v', '--verbose', action='store_true',
help='display progress information')
args = parser.parse_args()
verbose = args.verbose
t0 = time.time()
img_count, total_size = get_images(args.year_month, args.max_qty)
elapsed = time.time() - t0
print("images: %3d | total size: %6.1f Kbytes | elapsed time: %3ds" %
(img_count, total_size/1024.0, elapsed))
if __name__ == '__main__':
main()
| ParsingException |
python | plotly__plotly.py | plotly/graph_objs/funnel/_marker.py | {
"start": 233,
"end": 22994
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnel"
_path_str = "funnel.marker"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorbar",
"colorscale",
"colorsrc",
"line",
"opacity",
"opacitysrc",
"reversescale",
"showscale",
}
@property
def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in `marker.color` is
set to a numerical array. In case `colorscale` is unspecified
or `autocolorscale` is true, the default palette will be chosen
according to whether numbers in the `color` array are all
positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["autocolorscale"]
@autocolorscale.setter
def autocolorscale(self, val):
self["autocolorscale"] = val
@property
def cauto(self):
"""
Determines whether or not the color domain is computed with
respect to the input data (here in `marker.color`) or the
bounds set in `marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical array. Defaults
to `false` when `marker.cmin` and `marker.cmax` are set by the
user.
The 'cauto' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["cauto"]
@cauto.setter
def cauto(self, val):
self["cauto"] = val
@property
def cmax(self):
"""
Sets the upper bound of the color domain. Has an effect only if
in `marker.color` is set to a numerical array. Value should
have the same units as in `marker.color` and if set,
`marker.cmin` must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmax"]
@cmax.setter
def cmax(self, val):
self["cmax"] = val
@property
def cmid(self):
"""
Sets the mid-point of the color domain by scaling `marker.cmin`
and/or `marker.cmax` to be equidistant to this point. Has an
effect only if in `marker.color` is set to a numerical array.
Value should have the same units as in `marker.color`. Has no
effect when `marker.cauto` is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmid"]
@cmid.setter
def cmid(self, val):
self["cmid"] = val
@property
def cmin(self):
"""
Sets the lower bound of the color domain. Has an effect only if
in `marker.color` is set to a numerical array. Value should
have the same units as in `marker.color` and if set,
`marker.cmax` must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmin"]
@cmin.setter
def cmin(self, val):
self["cmin"] = val
@property
def color(self):
"""
Sets the marker color. It accepts either a specific color or an
array of numbers that are mapped to the colorscale relative to
the max and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
The 'color' 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
- A number that will be interpreted as a color
according to funnel.marker.colorscale
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def coloraxis(self):
"""
Sets a reference to a shared color axis. References to these
shared color axes are "coloraxis", "coloraxis2", "coloraxis3",
etc. Settings for these shared color axes are set in the
layout, under `layout.coloraxis`, `layout.coloraxis2`, etc.
Note that multiple color scales can be linked to the same color
axis.
The 'coloraxis' property is an identifier of a particular
subplot, of type 'coloraxis', that may be specified as the string 'coloraxis'
optionally followed by an integer >= 1
(e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.)
Returns
-------
str
"""
return self["coloraxis"]
@coloraxis.setter
def coloraxis(self, val):
self["coloraxis"] = val
@property
def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.funnel.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Returns
-------
plotly.graph_objs.funnel.marker.ColorBar
"""
return self["colorbar"]
@colorbar.setter
def colorbar(self, val):
self["colorbar"] = val
@property
def colorscale(self):
"""
Sets the colorscale. Has an effect only if in `marker.color` is
set to a numerical array. The colorscale must be an array
containing arrays mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At minimum, a mapping for
the lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To
control the bounds of the colorscale in color space, use
`marker.cmin` and `marker.cmax`. Alternatively, `colorscale`
may be a palette name string of the following list: Blackbody,B
luered,Blues,Cividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic
,Portland,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl',
'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn',
'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu',
'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar',
'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn',
'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid',
'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr',
'ylorrd'].
Appending '_r' to a named colorscale reverses it.
Returns
-------
str
"""
return self["colorscale"]
@colorscale.setter
def colorscale(self, val):
self["colorscale"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.funnel.marker.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Returns
-------
plotly.graph_objs.funnel.marker.Line
"""
return self["line"]
@line.setter
def line(self, val):
self["line"] = val
@property
def opacity(self):
"""
Sets the opacity of the bars.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
@property
def opacitysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `opacity`.
The 'opacitysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["opacitysrc"]
@opacitysrc.setter
def opacitysrc(self, val):
self["opacitysrc"] = val
@property
def reversescale(self):
"""
Reverses the color mapping if true. Has an effect only if in
`marker.color` is set to a numerical array. If true,
`marker.cmin` will correspond to the last color in the array
and `marker.cmax` will correspond to the first color.
The 'reversescale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["reversescale"]
@reversescale.setter
def reversescale(self, val):
self["reversescale"] = val
@property
def showscale(self):
"""
Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color` is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showscale"]
@showscale.setter
def showscale(self, val):
self["showscale"] = val
@property
def _prop_descriptions(self):
return """\
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in
`marker.color` is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in `marker.color`)
or the bounds set in `marker.cmin` and `marker.cmax`
Has an effect only if in `marker.color` is set to a
numerical array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.color` is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.cmin` and/or `marker.cmax` to be equidistant to
this point. Has an effect only if in `marker.color` is
set to a numerical array. Value should have the same
units as in `marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.color` is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a specific
color or an array of numbers that are mapped to the
colorscale relative to the max and min values of the
array or relative to `marker.cmin` and `marker.cmax` if
set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorbar
:class:`plotly.graph_objects.funnel.marker.ColorBar`
instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use `marker.cmin` and `marker.cmax`. Alternatively,
`colorscale` may be a palette name string of the
following list: Blackbody,Bluered,Blues,Cividis,Earth,E
lectric,Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
line
:class:`plotly.graph_objects.funnel.marker.Line`
instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud for
`opacity`.
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.color` is set to a numerical array. If
true, `marker.cmin` will correspond to the last color
in the array and `marker.cmax` will correspond to the
first color.
showscale
Determines whether or not a colorbar is displayed for
this trace. Has an effect only if in `marker.color` is
set to a numerical array.
"""
def __init__(
self,
arg=None,
autocolorscale=None,
cauto=None,
cmax=None,
cmid=None,
cmin=None,
color=None,
coloraxis=None,
colorbar=None,
colorscale=None,
colorsrc=None,
line=None,
opacity=None,
opacitysrc=None,
reversescale=None,
showscale=None,
**kwargs,
):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.funnel.Marker`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in
`marker.color` is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in `marker.color`)
or the bounds set in `marker.cmin` and `marker.cmax`
Has an effect only if in `marker.color` is set to a
numerical array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.color` is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.cmin` and/or `marker.cmax` to be equidistant to
this point. Has an effect only if in `marker.color` is
set to a numerical array. Value should have the same
units as in `marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.color` is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a specific
color or an array of numbers that are mapped to the
colorscale relative to the max and min values of the
array or relative to `marker.cmin` and `marker.cmax` if
set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorbar
:class:`plotly.graph_objects.funnel.marker.ColorBar`
instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use `marker.cmin` and `marker.cmax`. Alternatively,
`colorscale` may be a palette name string of the
following list: Blackbody,Bluered,Blues,Cividis,Earth,E
lectric,Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
line
:class:`plotly.graph_objects.funnel.marker.Line`
instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud for
`opacity`.
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.color` is set to a numerical array. If
true, `marker.cmin` will correspond to the last color
in the array and `marker.cmax` will correspond to the
first color.
showscale
Determines whether or not a colorbar is displayed for
this trace. Has an effect only if in `marker.color` is
set to a numerical array.
Returns
-------
Marker
"""
super().__init__("marker")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.funnel.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.funnel.Marker`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("autocolorscale", arg, autocolorscale)
self._set_property("cauto", arg, cauto)
self._set_property("cmax", arg, cmax)
self._set_property("cmid", arg, cmid)
self._set_property("cmin", arg, cmin)
self._set_property("color", arg, color)
self._set_property("coloraxis", arg, coloraxis)
self._set_property("colorbar", arg, colorbar)
self._set_property("colorscale", arg, colorscale)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("line", arg, line)
self._set_property("opacity", arg, opacity)
self._set_property("opacitysrc", arg, opacitysrc)
self._set_property("reversescale", arg, reversescale)
self._set_property("showscale", arg, showscale)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Marker |
python | kamyu104__LeetCode-Solutions | Python/maximum-level-sum-of-a-binary-tree.py | {
"start": 227,
"end": 802
} | class ____(object):
def maxLevelSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, i, level_sums):
if not node:
return
if i == len(level_sums):
level_sums.append(0)
level_sums[i] += node.val
dfs(node.left, i+1, level_sums)
dfs(node.right, i+1, level_sums)
level_sums = []
dfs(root, 0, level_sums)
return level_sums.index(max(level_sums))+1
# Time: O(n)
# Space: O(w)
# bfs solution
| Solution |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 50305,
"end": 50833
} | class ____:
"""Configuration for mocking client method calls."""
method_path: str
"""Path to the client method to mock (e.g., 'connections.get', 'variables.set')."""
args: tuple = field(default_factory=tuple)
"""Positional arguments the client method should be called with."""
kwargs: dict = field(default_factory=dict)
"""Keyword arguments the client method should be called with."""
response: Any = None
"""What the mocked client method should return when called."""
@dataclass
| ClientMock |
python | google__pytype | pytype/tests/test_typing2.py | {
"start": 33984,
"end": 35467
} | class ____(test_base.BaseTest):
"""Tests for typing.TypeAlias."""
def test_basic(self):
for suffix in ("", "_extensions"):
typing_module = f"typing{suffix}"
with self.subTest(typing_module=typing_module):
ty = self.Infer(f"""
from {typing_module} import TypeAlias
X: TypeAlias = int
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Type
X: Type[int]
""",
)
def test_bad_alias(self):
self.CheckWithErrors("""
from typing import TypeAlias
X: TypeAlias = 0 # invalid-annotation
""")
def test_pyi(self):
for suffix in ("", "_extensions"):
typing_module = f"typing{suffix}"
with self.subTest(typing_module=typing_module):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
f"""
from {typing_module} import TypeAlias
X: TypeAlias = int
""",
)
self.Check(
"""
import foo
assert_type(foo.X, "type[int]")
""",
pythonpath=[d.path],
)
def test_forward_ref(self):
ty = self.Infer("""
from typing import TypeAlias
X: TypeAlias = "int"
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Type
X: Type[int]
""",
)
if __name__ == "__main__":
test_base.main()
| TypeAliasTest |
python | walkccc__LeetCode | solutions/2247. Maximum Cost of Trip With K Highways/2247.py | {
"start": 0,
"end": 768
} | class ____:
def maximumCost(self, n: int, highways: list[list[int]], k: int) -> int:
if k + 1 > n:
return -1
graph = [[] for _ in range(n)]
for u, v, w in highways:
graph[u].append((v, w))
graph[v].append((u, w))
@functools.lru_cache(None)
def dp(u: int, mask: int) -> int:
"""
Returns the maximum cost of trip starting from u, where `mask` is the
bitmask of the visited cities.
"""
if mask.bit_count() == k + 1:
return 0
res = -1
for v, w in graph[u]:
if mask >> v & 1:
continue
nextCost = dp(v, mask | 1 << v)
if nextCost != -1:
res = max(res, w + nextCost)
return res
return max(dp(i, 1 << i) for i in range(n))
| Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ColorMapWidget.py | {
"start": 202,
"end": 1687
} | class ____(ptree.ParameterTree):
"""
This class provides a widget allowing the user to customize color mapping
for multi-column data. Given a list of field names, the user may specify
multiple criteria for assigning colors to each record in a numpy record array.
Multiple criteria are evaluated and combined into a single color for each
record by user-defined compositing methods.
For simpler color mapping using a single gradient editor, see
:class:`GradientWidget <pyqtgraph.GradientWidget>`
"""
sigColorMapChanged = QtCore.Signal(object)
def __init__(self, parent=None):
ptree.ParameterTree.__init__(self, parent=parent, showHeader=False)
self.params = ColorMapParameter()
self.setParameters(self.params)
self.params.sigTreeStateChanged.connect(self.mapChanged)
## wrap a couple methods
self.setFields = self.params.setFields
self.map = self.params.map
def mapChanged(self):
self.sigColorMapChanged.emit(self)
def widgetGroupInterface(self):
return (self.sigColorMapChanged, self.saveState, self.restoreState)
def saveState(self):
return self.params.saveState()
def restoreState(self, state):
self.params.restoreState(state)
def addColorMap(self, name):
"""Add a new color mapping and return the created parameter.
"""
return self.params.addNew(name)
| ColorMapWidget |
python | openai__openai-python | src/openai/types/conversations/conversation_item.py | {
"start": 4085,
"end": 4496
} | class ____(BaseModel):
id: str
"""The unique ID of the list."""
server_label: str
"""The label of the MCP server."""
tools: List[McpListToolsTool]
"""The tools available on the server."""
type: Literal["mcp_list_tools"]
"""The type of the item. Always `mcp_list_tools`."""
error: Optional[str] = None
"""Error message if the server could not list tools."""
| McpListTools |
python | getsentry__sentry | tests/sentry/web/frontend/test_oauth_authorize.py | {
"start": 31275,
"end": 46498
} | class ____(TestCase):
"""Tests for OAuth flows using custom URI schemes (sentry-mobile-agent://)."""
@cached_property
def path(self) -> str:
return "/oauth/authorize/"
def setUp(self) -> None:
super().setUp()
self.custom_uri = "sentry-mobile-agent://sentry.io/auth"
self.application = ApiApplication.objects.create(
owner=self.user, redirect_uris=self.custom_uri
)
def test_code_flow_custom_scheme_approve(self) -> None:
"""Test authorization code flow with custom scheme redirect."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(self.path, {"op": "approve"})
grant = ApiGrant.objects.get(user=self.user)
assert grant.redirect_uri == self.custom_uri
assert grant.application == self.application
assert resp.status_code == 302
# Verify custom scheme is used in Location header
assert resp["Location"].startswith("sentry-mobile-agent://")
assert f"code={grant.code}" in resp["Location"]
def test_code_flow_custom_scheme_deny(self) -> None:
"""Test authorization code flow denial with custom scheme redirect."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 200
resp = self.client.post(self.path, {"op": "deny"})
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert "error=access_denied" in resp["Location"]
assert "code=" not in resp["Location"]
assert not ApiGrant.objects.filter(user=self.user).exists()
def test_token_flow_custom_scheme_approve(self) -> None:
"""Test implicit grant flow with custom scheme redirect."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=token&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(self.path, {"op": "approve"})
token = ApiToken.objects.get(user=self.user)
assert token.application == self.application
assert resp.status_code == 302
# Verify custom scheme is used with fragment for token
assert resp["Location"].startswith("sentry-mobile-agent://")
assert "#" in resp["Location"]
assert "access_token=" in resp["Location"]
def test_token_flow_custom_scheme_deny(self) -> None:
"""Test implicit grant flow denial with custom scheme redirect."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=token&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 200
resp = self.client.post(self.path, {"op": "deny"})
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert "#" in resp["Location"]
assert "error=access_denied" in resp["Location"]
assert "access_token=" not in resp["Location"]
assert not ApiToken.objects.filter(user=self.user).exists()
def test_code_flow_with_state_custom_scheme(self) -> None:
"""Test authorization code flow with state parameter and custom scheme."""
self.login_as(self.user)
state = "test-state-123"
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&state={state}"
)
assert resp.status_code == 200
resp = self.client.post(self.path, {"op": "approve"})
grant = ApiGrant.objects.get(user=self.user)
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert f"code={grant.code}" in resp["Location"]
assert f"state={state}" in resp["Location"]
def test_code_flow_rich_params_custom_scheme(self) -> None:
"""Test authorization code flow with scopes and state using custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=org%3Aread&state=foo"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(self.path, {"op": "approve"})
grant = ApiGrant.objects.get(user=self.user)
assert grant.redirect_uri == self.custom_uri
assert grant.application == self.application
assert grant.get_scopes() == ["org:read"]
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert f"code={grant.code}" in resp["Location"]
assert "state=foo" in resp["Location"]
def test_code_flow_bypass_prompt_custom_scheme(self) -> None:
"""Test that existing authorization bypasses prompt with custom scheme."""
self.login_as(self.user)
ApiAuthorization.objects.create(user=self.user, application=self.application)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
grant = ApiGrant.objects.get(user=self.user)
assert grant.redirect_uri == self.custom_uri
assert grant.application == self.application
assert not grant.get_scopes()
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert f"code={grant.code}" in resp["Location"]
def test_code_flow_force_prompt_custom_scheme(self) -> None:
"""Test force prompt even with existing authorization using custom scheme."""
self.login_as(self.user)
ApiAuthorization.objects.create(user=self.user, application=self.application)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&force_prompt=1"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
def test_code_flow_new_scope_custom_scheme(self) -> None:
"""Test that requesting new scope requires prompt with custom scheme."""
self.login_as(self.user)
authorization = ApiAuthorization.objects.create(
user=self.user, application=self.application, scope_list=["org:write"]
)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=org:read"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(self.path, {"op": "approve"})
authorization = ApiAuthorization.objects.get(id=authorization.id)
assert sorted(authorization.get_scopes()) == ["org:read", "org:write"]
def test_code_flow_non_scope_set_custom_scheme(self) -> None:
"""Test non-scope-set authorization with custom scheme."""
self.login_as(self.user)
ApiAuthorization.objects.create(user=self.user, application=self.application)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=member:read member:admin"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
assert resp.context["scopes"] == ["member:read", "member:admin"]
assert resp.context["permissions"] == [
"Read, write, and admin access to organization members."
]
def test_code_flow_unauthenticated_custom_scheme(self) -> None:
"""Test unauthenticated user login flow with custom scheme."""
full_path = f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
resp = self.client.get(full_path)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/login.html")
assert resp.context["banner"] == f"Connect Sentry to {self.application.name}"
resp = self.client.post(
full_path, {"username": self.user.username, "password": "admin", "op": "login"}
)
self.assertRedirects(resp, full_path)
resp = self.client.get(full_path)
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(full_path, {"op": "approve"})
grant = ApiGrant.objects.get(user=self.user)
assert grant.redirect_uri == self.custom_uri
assert grant.application == self.application
assert not grant.get_scopes()
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert f"code={grant.code}" in resp["Location"]
def test_invalid_scope_custom_scheme(self) -> None:
"""Test invalid scope error with custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=foo"
)
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert "error=invalid_scope" in resp["Location"]
assert "code=" not in resp["Location"]
assert not ApiGrant.objects.filter(user=self.user).exists()
def test_token_flow_rich_params_custom_scheme(self) -> None:
"""Test implicit grant flow with scopes and state using custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=token&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=org%3Aread&state=foo"
)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/oauth-authorize.html")
assert resp.context["application"] == self.application
resp = self.client.post(self.path, {"op": "approve"})
token = ApiToken.objects.get(user=self.user)
assert token.application == self.application
assert token.get_scopes() == ["org:read"]
assert resp.status_code == 302
location, fragment = resp["Location"].split("#", 1)
assert location.startswith("sentry-mobile-agent://")
fragment_d = parse_qs(fragment)
assert fragment_d["access_token"] == [token.token]
assert fragment_d["state"] == ["foo"]
def test_token_flow_invalid_scope_custom_scheme(self) -> None:
"""Test invalid scope error in implicit grant flow with custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=token&redirect_uri={self.custom_uri}&client_id={self.application.client_id}&scope=foo"
)
assert resp.status_code == 302
assert resp["Location"].startswith("sentry-mobile-agent://")
assert "#" in resp["Location"]
assert "error=invalid_scope" in resp["Location"]
assert "access_token" not in resp["Location"]
assert not ApiToken.objects.filter(user=self.user).exists()
def test_missing_response_type_custom_scheme(self) -> None:
"""Test missing response_type parameter with custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 400
self.assertTemplateUsed("sentry/oauth-error.html")
assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter."
def test_invalid_response_type_custom_scheme(self) -> None:
"""Test invalid response_type parameter with custom scheme."""
self.login_as(self.user)
resp = self.client.get(
f"{self.path}?response_type=foobar&redirect_uri={self.custom_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 400
self.assertTemplateUsed("sentry/oauth-error.html")
assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter."
def test_missing_client_id_custom_scheme(self) -> None:
"""Test missing client_id parameter with custom scheme."""
self.login_as(self.user)
resp = self.client.get(f"{self.path}?response_type=code&redirect_uri={self.custom_uri}")
assert resp.status_code == 400
self.assertTemplateUsed("sentry/oauth-error.html")
assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter."
def test_invalid_redirect_uri_custom_scheme(self) -> None:
"""Test invalid redirect URI with custom scheme."""
self.login_as(self.user)
# Try to use a different custom scheme that's not registered
invalid_uri = "sentry-mobile-agent://different.com/auth"
resp = self.client.get(
f"{self.path}?response_type=code&redirect_uri={invalid_uri}&client_id={self.application.client_id}"
)
assert resp.status_code == 400
self.assertTemplateUsed("sentry/oauth-error.html")
assert resp.context["error"] == "Missing or invalid <em>redirect_uri</em> parameter."
def test_requires_redirect_uri_when_multiple_custom_schemes(self) -> None:
"""Test that redirect_uri is required when multiple custom schemes are registered."""
self.login_as(self.user)
# Update application to have multiple redirect URIs
self.application.redirect_uris = (
f"{self.custom_uri}\nsentry-mobile-agent://sentry.io/callback"
)
self.application.save()
resp = self.client.get(
f"{self.path}?response_type=code&client_id={self.application.client_id}"
)
# Must require redirect_uri when multiple are registered (RFC 6749 §3.1.2.3)
assert resp.status_code == 400
self.assertTemplateUsed("sentry/oauth-error.html")
assert resp.context["error"] == "Missing or invalid <em>redirect_uri</em> parameter."
@control_silo_test
| OAuthAuthorizeCustomSchemeTest |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 30896,
"end": 31905
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: Optional[torch.FloatTensor] = None
seq_relationship_logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
| ErnieForPreTrainingOutput |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 32129,
"end": 33253
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a work pool."""
name: NonEmptyishName = Field(..., description="The name of the work pool.")
description: Optional[str] = Field(
default=None, description="The work pool description."
)
type: str = Field(description="The work pool type.", default="prefect-agent")
base_job_template: Dict[str, Any] = Field(
default_factory=dict, description="The work pool's base job template."
)
is_paused: bool = Field(
default=False,
description="Pausing the work pool stops the delivery of all work.",
)
concurrency_limit: Optional[NonNegativeInteger] = Field(
default=None, description="A concurrency limit for the work pool."
)
storage_configuration: schemas.core.WorkPoolStorageConfiguration = Field(
default_factory=schemas.core.WorkPoolStorageConfiguration,
description="The storage configuration for the work pool.",
)
_validate_base_job_template = field_validator("base_job_template")(
validate_base_job_template
)
| WorkPoolCreate |
python | huggingface__transformers | src/transformers/modeling_layers.py | {
"start": 3814,
"end": 7051
} | class ____:
base_model_prefix = "model"
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
# Similar to `self.model = AutoModel.from_config(config)` but allows to change the base model name if needed in the child class
setattr(self, self.base_model_prefix, AutoModel.from_config(config))
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@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,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
**kwargs: Unpack[TransformersKwargs],
) -> SequenceClassifierOutputWithPast:
transformer_outputs: BaseModelOutputWithPast = getattr(self, self.base_model_prefix)(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
**kwargs,
)
hidden_states = transformer_outputs.last_hidden_state
logits = self.score(hidden_states)
if input_ids is not None:
batch_size = input_ids.shape[0]
else:
batch_size = inputs_embeds.shape[0]
if self.config.pad_token_id is None and batch_size != 1:
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
if self.config.pad_token_id is None:
last_non_pad_token = -1
elif input_ids is not None:
# To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
else:
last_non_pad_token = -1
logger.warning_once(
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
)
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
return SequenceClassifierOutputWithPast(
loss=loss,
logits=pooled_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
@auto_docstring
| GenericForSequenceClassification |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 962,
"end": 1278
} | class ____:
params = ["first", "last", "all"]
param_names = ["keep"]
def setup(self, keep):
self.s = Series(np.random.randint(1, 10, 100000))
def time_nlargest(self, keep):
self.s.nlargest(3, keep=keep)
def time_nsmallest(self, keep):
self.s.nsmallest(3, keep=keep)
| NSort |
python | celery__celery | celery/utils/collections.py | {
"start": 3237,
"end": 3761
} | class ____:
"""Mixin for Mapping interface that adds attribute access.
I.e., `d.key -> d[key]`).
"""
def __getattr__(self, k):
# type: (str) -> Any
"""`d.key -> d[key]`."""
try:
return self[k]
except KeyError:
raise AttributeError(
f'{type(self).__name__!r} object has no attribute {k!r}')
def __setattr__(self, key: str, value) -> None:
"""`d[key] = value -> d.key = value`."""
self[key] = value
| AttributeDictMixin |
python | paramiko__paramiko | paramiko/_winapi.py | {
"start": 7554,
"end": 8230
} | class ____(ctypes.Structure):
"""
typedef struct _SECURITY_DESCRIPTOR
{
UCHAR Revision;
UCHAR Sbz1;
SECURITY_DESCRIPTOR_CONTROL Control;
PSID Owner;
PSID Group;
PACL Sacl;
PACL Dacl;
} SECURITY_DESCRIPTOR;
"""
SECURITY_DESCRIPTOR_CONTROL = ctypes.wintypes.USHORT
REVISION = 1
_fields_ = [
("Revision", ctypes.c_ubyte),
("Sbz1", ctypes.c_ubyte),
("Control", SECURITY_DESCRIPTOR_CONTROL),
("Owner", ctypes.c_void_p),
("Group", ctypes.c_void_p),
("Sacl", ctypes.c_void_p),
("Dacl", ctypes.c_void_p),
]
| SECURITY_DESCRIPTOR |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/background/main.py | {
"start": 857,
"end": 1020
} | class ____(webapp2.RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "text/plain"
self.response.write(str(val))
| MainHandler |
python | huggingface__transformers | src/transformers/models/table_transformer/modeling_table_transformer.py | {
"start": 45323,
"end": 53547
} | class ____(TableTransformerPreTrainedModel):
# Copied from transformers.models.detr.modeling_detr.DetrModel.__init__ with Detr->TableTransformer
def __init__(self, config: TableTransformerConfig):
super().__init__(config)
# Create backbone + positional encoding
backbone = TableTransformerConvEncoder(config)
object_queries = build_position_encoding(config)
self.backbone = TableTransformerConvModel(backbone, object_queries)
# Create projection layer
self.input_projection = nn.Conv2d(backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)
self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
self.encoder = TableTransformerEncoder(config)
self.decoder = TableTransformerDecoder(config)
# Initialize weights and apply final processing
self.post_init()
def freeze_backbone(self):
for name, param in self.backbone.conv_encoder.model.named_parameters():
param.requires_grad_(False)
def unfreeze_backbone(self):
for name, param in self.backbone.conv_encoder.model.named_parameters():
param.requires_grad_(True)
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
pixel_mask: Optional[torch.FloatTensor] = None,
decoder_attention_mask: Optional[torch.FloatTensor] = None,
encoder_outputs: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple[torch.FloatTensor], TableTransformerModelOutput]:
r"""
decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
Not used by default. Can be used to mask object queries.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
can choose to directly pass a flattened representation of an image.
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
embedded representation.
Examples:
```python
>>> from transformers import AutoImageProcessor, TableTransformerModel
>>> from huggingface_hub import hf_hub_download
>>> from PIL import Image
>>> file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png")
>>> image = Image.open(file_path).convert("RGB")
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")
>>> model = TableTransformerModel.from_pretrained("microsoft/table-transformer-detection")
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> # forward pass
>>> outputs = model(**inputs)
>>> # the last hidden states are the final query embeddings of the Transformer decoder
>>> # these are of shape (batch_size, num_queries, hidden_size)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 15, 256]
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
batch_size, num_channels, height, width = pixel_values.shape
device = pixel_values.device
if pixel_mask is None:
pixel_mask = torch.ones(((batch_size, height, width)), device=device)
# First, sent pixel_values + pixel_mask through Backbone to obtain the features
# pixel_values should be of shape (batch_size, num_channels, height, width)
# pixel_mask should be of shape (batch_size, height, width)
features, position_embeddings_list = self.backbone(pixel_values, pixel_mask)
# get final feature map and downsampled mask
feature_map, mask = features[-1]
if mask is None:
raise ValueError("Backbone does not return downsampled pixel mask")
# Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
projected_feature_map = self.input_projection(feature_map)
# Third, flatten the feature map + object queries of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
# In other words, turn their shape into (batch_size, sequence_length, hidden_size)
flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
object_queries = position_embeddings_list[-1].flatten(2).permute(0, 2, 1)
flattened_mask = mask.flatten(1)
# Fourth, sent flattened_features + flattened_mask + object queries through encoder
# flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
# flattened_mask is a Tensor of shape (batch_size, height*width)
if encoder_outputs is None:
encoder_outputs = self.encoder(
inputs_embeds=flattened_features,
attention_mask=flattened_mask,
object_queries=object_queries,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
encoder_outputs = BaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
# Fifth, sent query embeddings + object queries through the decoder (which is conditioned on the encoder output)
query_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
queries = torch.zeros_like(query_position_embeddings)
# decoder outputs consists of (dec_features, dec_hidden, dec_attn)
decoder_outputs = self.decoder(
inputs_embeds=queries,
attention_mask=None,
object_queries=object_queries,
query_position_embeddings=query_position_embeddings,
encoder_hidden_states=encoder_outputs[0],
encoder_attention_mask=flattened_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if not return_dict:
return decoder_outputs + encoder_outputs
return TableTransformerModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
)
@auto_docstring(
custom_intro="""
Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on
top, for tasks such as COCO detection.
"""
)
| TableTransformerModel |
python | pyinstaller__pyinstaller | PyInstaller/utils/hooks/conda.py | {
"start": 2389,
"end": 6471
} | class ____:
"""
A bucket class representation of a Conda distribution.
This bucket exports the following attributes:
:ivar name: The distribution's name.
:ivar version: Its version.
:ivar files: All filenames as :meth:`PackagePath`\\ s included with this distribution.
:ivar dependencies: Names of other distributions that this distribution depends on (with version constraints
removed).
:ivar packages: Names of importable packages included in this distribution.
This class is not intended to be constructed directly by users. Rather use :meth:`distribution` or
:meth:`package_distribution` to provide one for you.
"""
def __init__(self, json_path: str):
try:
self._json_path = pathlib.Path(json_path)
assert self._json_path.exists()
except (TypeError, AssertionError):
raise TypeError(
"Distribution requires a path to a conda-meta json. Perhaps you want "
"`distribution({})` instead?".format(repr(json_path))
)
# Everything we need (including this distribution's name) is kept in the metadata json.
self.raw: dict = json.loads(self._json_path.read_text())
# Unpack the more useful contents of the json.
self.name: str = self.raw["name"]
self.version: str = self.raw["version"]
self.files = [PackagePath(i) for i in self.raw["files"]]
self.dependencies = self._init_dependencies()
self.packages = self._init_package_names()
def __repr__(self):
return "{}(name=\"{}\", packages={})".format(type(self).__name__, self.name, self.packages)
def _init_dependencies(self):
"""
Read dependencies from ``self.raw["depends"]``.
:return: Dependent distribution names.
:rtype: list
The names in ``self.raw["depends"]`` come with extra version constraint information which must be stripped.
"""
dependencies = []
# For each dependency:
for dependency in self.raw["depends"]:
# ``dependency`` is a string of the form: "[name] [version constraints]"
name, *version_constraints = dependency.split(maxsplit=1)
dependencies.append(name)
return dependencies
def _init_package_names(self):
"""
Search ``self.files`` for package names shipped by this distribution.
:return: Package names.
:rtype: list
These are names you would ``import`` rather than names you would install.
"""
packages = []
for file in self.files:
package = _get_package_name(file)
if package is not None:
packages.append(package)
return packages
@classmethod
def from_name(cls, name: str):
"""
Get distribution information for a given distribution **name** (i.e., something you would ``conda install``).
:rtype: :class:`Distribution`
"""
if name in distributions:
return distributions[name]
raise ModuleNotFoundError(
"Distribution {} is either not installed or was not installed using Conda.".format(name)
)
@classmethod
def from_package_name(cls, name: str):
"""
Get distribution information for a **package** (i.e., something you would import).
:rtype: :class:`Distribution`
For example, the package ``pkg_resources`` belongs to the distribution ``setuptools``, which contains three
packages.
>>> package_distribution("pkg_resources")
Distribution(name="setuptools",
packages=['easy_install', 'pkg_resources', 'setuptools'])
"""
if name in distributions_by_package:
return distributions_by_package[name]
raise ModuleNotFoundError("Package {} is either not installed or was not installed using Conda.".format(name))
distribution = Distribution.from_name
package_distribution = Distribution.from_package_name
| Distribution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_write_sheet.py | {
"start": 299,
"end": 1430
} | class ____(unittest.TestCase):
"""
Test the Workbook _write_sheet() method.
"""
def setUp(self):
self.fh = StringIO()
self.workbook = Workbook()
self.workbook._set_filehandle(self.fh)
def test_write_sheet1(self):
"""Test the _write_sheet() method"""
self.workbook._write_sheet("Sheet1", 1, 0)
exp = """<sheet name="Sheet1" sheetId="1" r:id="rId1"/>"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet2(self):
"""Test the _write_sheet() method"""
self.workbook._write_sheet("Sheet1", 1, 1)
exp = """<sheet name="Sheet1" sheetId="1" state="hidden" r:id="rId1"/>"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet3(self):
"""Test the _write_sheet() method"""
self.workbook._write_sheet("Bits & Bobs", 1, 0)
exp = """<sheet name="Bits & Bobs" sheetId="1" r:id="rId1"/>"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
def tearDown(self):
self.workbook.fileclosed = 1
| TestWriteSheet |
python | kamyu104__LeetCode-Solutions | Python/4sum.py | {
"start": 85,
"end": 1370
} | class ____(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = []
for i in xrange(len(nums) - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in xrange(i + 1, len(nums) - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
total = target - nums[i] - nums[j]
left, right = j + 1, len(nums) - 1
while left < right:
if nums[left] + nums[right] == total:
result.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > total:
right -= 1
else:
left += 1
return result
# Time: O(n^2 * p)
# Space: O(n^2 * p)
# Hash solution. (224ms)
| Solution |
python | keras-team__keras | guides/writing_a_custom_training_loop_in_jax.py | {
"start": 15776,
"end": 17063
} | class ____(keras.layers.Layer):
def call(self, inputs):
self.add_loss(1e-2 * jax.numpy.sum(inputs))
return inputs
"""
Let's build a really simple model that uses it:
"""
inputs = keras.Input(shape=(784,), name="digits")
x = keras.layers.Dense(64, activation="relu")(inputs)
# Insert activity regularization as a layer
x = ActivityRegularizationLayer()(x)
x = keras.layers.Dense(64, activation="relu")(x)
outputs = keras.layers.Dense(10, name="predictions")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
"""
Here's what our `compute_loss_and_updates` function should look like now:
- Pass `return_losses=True` to `model.stateless_call()`.
- Sum the resulting `losses` and add them to the main loss.
"""
def compute_loss_and_updates(
trainable_variables, non_trainable_variables, metric_variables, x, y
):
y_pred, non_trainable_variables, losses = model.stateless_call(
trainable_variables, non_trainable_variables, x, return_losses=True
)
loss = loss_fn(y, y_pred)
if losses:
loss += jax.numpy.sum(losses)
metric_variables = train_acc_metric.stateless_update_state(
metric_variables, y, y_pred
)
return loss, non_trainable_variables, metric_variables
"""
That's it!
"""
| ActivityRegularizationLayer |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 36078,
"end": 37472
} | class ____(SetitemCastingEquivalents):
# GH#24024
@pytest.fixture
def obj(self):
return Series(date_range("2000", periods=2, tz="US/Central"))
@pytest.fixture
def val(self):
return Timestamp("2000", tz="US/Eastern")
@pytest.fixture
def key(self):
return 0
@pytest.fixture
def expected(self, obj, val):
# pre-2.0 this would cast to object, in 2.0 we cast the val to
# the target tz
expected = Series(
[
val.tz_convert("US/Central"),
Timestamp("2000-01-02 00:00:00-06:00", tz="US/Central"),
],
dtype=obj.dtype,
)
return expected
@pytest.fixture
def raises(self):
return False
@pytest.mark.parametrize(
"obj,expected",
[
# For numeric series, we should coerce to NaN.
(Series([1, 2, 3]), Series([np.nan, 2, 3])),
(Series([1.0, 2.0, 3.0]), Series([np.nan, 2.0, 3.0])),
# For datetime series, we should coerce to NaT.
(
Series([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)]),
Series([NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]),
),
# For objects, we should preserve the None value.
(Series(["foo", "bar", "baz"]), Series([None, "bar", "baz"])),
],
)
| TestSetitemMismatchedTZCastsToObject |
python | kamyu104__LeetCode-Solutions | Python/maximum-array-hopping-score-ii.py | {
"start": 50,
"end": 332
} | class ____(object):
def maxScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = mx = 0
for i in reversed(xrange(1, len(nums))):
mx = max(mx, nums[i])
result += mx
return result
| Solution |
python | spack__spack | lib/spack/docs/conf.py | {
"start": 3909,
"end": 4600
} | class ____(PygmentsBridge):
def get_formatter(self, **options):
return NoWhitespaceHtmlFormatter(**options)
# Use custom HTML formatter to avoid redundant <span class="w"> </span> elements.
# See https://github.com/pygments/pygments/issues/1905#issuecomment-3170486995.
PygmentsBridge.html_formatter = NoWhitespaceHtmlFormatter
from spack.llnl.util.lang import classproperty
from spack.spec_parser import SpecTokens
# replace classproperty.__get__ to return `self` so Sphinx can document it correctly. Otherwise
# it evaluates the callback, and it documents the result, which is not what we want.
classproperty.__get__ = lambda self, instance, owner: self
| CustomPygmentsBridge |
python | getsentry__sentry | src/sentry/core/endpoints/team_projects.py | {
"start": 5488,
"end": 11186
} | class ____(TeamEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
permission_classes = (TeamProjectPermission,)
owner = ApiOwner.ENTERPRISE
@extend_schema(
operation_id="List a Team's Projects",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.TEAM_ID_OR_SLUG,
CursorQueryParam,
],
request=None,
responses={
200: inline_sentry_response_serializer(
"ListTeamProjectResponse", list[OrganizationProjectResponse]
),
403: RESPONSE_FORBIDDEN,
404: OpenApiResponse(description="Team not found."),
},
examples=TeamExamples.LIST_TEAM_PROJECTS,
)
def get(self, request: Request, team) -> Response:
"""
Return a list of projects bound to a team.
"""
if request.auth and hasattr(request.auth, "project"):
queryset = Project.objects.filter(id=request.auth.project.id)
else:
queryset = Project.objects.filter(teams=team, status=ObjectStatus.ACTIVE)
stats_period = request.GET.get("statsPeriod")
if stats_period not in (None, "", "24h", "14d", "30d"):
return Response(
{"error": {"params": {"stats_period": {"message": ERR_INVALID_STATS_PERIOD}}}},
status=400,
)
elif not stats_period:
# disable stats
stats_period = None
return self.paginate(
request=request,
queryset=queryset,
order_by="slug",
on_results=lambda x: serialize(
x,
request.user,
ProjectSummarySerializer(
environment_id=get_environment_id(request, team.organization.id),
stats_period=stats_period,
),
),
paginator_cls=OffsetPaginator,
)
@extend_schema(
# Ensure POST is in the projects tab
tags=["Projects"],
operation_id="Create a New Project",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.TEAM_ID_OR_SLUG,
],
request=ProjectPostSerializer,
responses={
201: ProjectSummarySerializer,
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
404: OpenApiResponse(description="Team not found."),
409: OpenApiResponse(description="A project with this slug already exists."),
},
examples=ProjectExamples.CREATE_PROJECT,
description="""Create a new project bound to a team.
Note: If your organization has disabled member project creation, the `org:write` or `team:admin` scope is required.
""",
)
def post(self, request: Request, team: Team) -> Response:
from sentry.core.endpoints.organization_projects_experiment import (
DISABLED_FEATURE_ERROR_STRING,
)
serializer = ProjectPostSerializer(
data=request.data, context={"organization": team.organization}
)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
if team.organization.flags.disable_member_project_creation and not (
request.access.has_scope("org:write")
):
# Only allow project creation if the user is an admin of the team
if not request.access.has_team_scope(team, "team:admin"):
return Response({"detail": DISABLED_FEATURE_ERROR_STRING}, status=403)
result = serializer.validated_data
with transaction.atomic(router.db_for_write(Project)):
try:
with transaction.atomic(router.db_for_write(Project)):
project = Project.objects.create(
name=result["name"],
slug=result.get("slug"),
organization=team.organization,
platform=result.get("platform"),
)
except (IntegrityError, MaxSnowflakeRetryError):
return Response({"detail": "A project with this slug already exists."}, status=409)
else:
project.add_team(team)
apply_default_project_settings(team.organization, project)
common_audit_data: AuditData = {
"request": request,
"organization": team.organization,
"target_object": project.id,
}
origin = request.data.get("origin")
if origin:
self.create_audit_entry(
**common_audit_data,
event=audit_log.get_event_id("PROJECT_ADD_WITH_ORIGIN"),
data={
**project.get_audit_log_data(),
"origin": origin,
},
)
else:
self.create_audit_entry(
**common_audit_data,
event=audit_log.get_event_id("PROJECT_ADD"),
data={**project.get_audit_log_data()},
)
project_created.send_robust(
project=project,
user=request.user,
default_rules=result.get("default_rules", True),
origin=origin,
sender=self,
)
return Response(
serialize(project, request.user, ProjectSummarySerializer(collapse=["unusedFeatures"])),
status=201,
)
| TeamProjectsEndpoint |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/extensions/init_appbuilder.py | {
"start": 2835,
"end": 22376
} | class ____:
"""This is the base class for all the framework."""
baseviews: list[BaseView | Session] = []
# Database Session
session = None
# Security Manager Class
sm: BaseSecurityManager
# Babel Manager Class
bm = None
# dict with addon name has key and instantiated class has value
addon_managers: dict
# temporary list that hold addon_managers config key
_addon_managers: list
menu = None
indexview = None
static_folder = None
static_url_path = None
template_filters = None
def __init__(
self,
app=None,
session: Session | None = None,
menu=None,
indexview=None,
base_template="airflow/main.html",
static_folder="static/appbuilder",
static_url_path="/appbuilder",
enable_plugins: bool = False,
):
"""
App-builder constructor.
:param app:
The flask app object
:param session:
The SQLAlchemy session object
:param menu:
optional, a previous constructed menu
:param indexview:
optional, your customized indexview
:param static_folder:
optional, your override for the global static folder
:param static_url_path:
optional, your override for the global static url path
:param enable_plugins:
optional, whether plugins are enabled for this app. AirflowAppBuilder from FAB provider can be
instantiated in two modes:
- Plugins enabled. The Flask application is responsible to execute Airflow 2 plugins.
This application is only running if there are Airflow 2 plugins defined as part of the Airflow
environment
- Plugins disabled. The Flask application is responsible to execute the FAB auth manager login
process. This application is only running if FAB auth manager is the auth manager configured
in the Airflow environment
"""
from airflow.providers_manager import ProvidersManager
providers_manager = ProvidersManager()
providers_manager.initialize_providers_configuration()
self.baseviews = []
self._addon_managers = []
self.addon_managers = {}
self.menu = menu
self.base_template = base_template
self.indexview = indexview
self.static_folder = static_folder
self.static_url_path = static_url_path
self.enable_plugins = enable_plugins
self.update_perms = conf.getboolean("fab", "UPDATE_FAB_PERMS")
self.auth_rate_limited = conf.getboolean("fab", "AUTH_RATE_LIMITED")
self.auth_rate_limit = conf.get("fab", "AUTH_RATE_LIMIT")
if app is not None:
self.init_app(app, session)
def init_app(self, app, session):
"""
Will initialize the Flask app, supporting the app factory pattern.
:param app:
:param session: The SQLAlchemy session
"""
log.info("Initializing AppBuilder")
app.config.setdefault("APP_NAME", "F.A.B.")
app.config.setdefault("APP_THEME", "")
app.config.setdefault("APP_ICON", "")
app.config.setdefault("LANGUAGES", {"en": {"flag": "gb", "name": "English"}})
app.config.setdefault("ADDON_MANAGERS", [])
app.config.setdefault("RATELIMIT_ENABLED", self.auth_rate_limited)
app.config.setdefault("FAB_BASE_TEMPLATE", self.base_template)
app.config.setdefault("FAB_STATIC_FOLDER", self.static_folder)
app.config.setdefault("FAB_STATIC_URL_PATH", self.static_url_path)
app.config.setdefault("AUTH_RATE_LIMITED", self.auth_rate_limited)
app.config.setdefault("AUTH_RATE_LIMIT", self.auth_rate_limit)
self.base_template = app.config.get("FAB_BASE_TEMPLATE", self.base_template)
self.static_folder = app.config.get("FAB_STATIC_FOLDER", self.static_folder)
self.static_url_path = app.config.get("FAB_STATIC_URL_PATH", self.static_url_path)
_index_view = app.config.get("FAB_INDEX_VIEW", None)
if _index_view is not None:
self.indexview = dynamic_class_import(_index_view)
elif not self.enable_plugins:
self.indexview = FabIndexView
else:
self.indexview = IndexView
_menu = app.config.get("FAB_MENU", None)
if _menu is not None:
self.menu = dynamic_class_import(_menu)
else:
self.menu = self.menu or Menu()
self._addon_managers = app.config["ADDON_MANAGERS"]
self.session = session
auth_manager = create_auth_manager()
auth_manager.appbuilder = self
if hasattr(auth_manager, "init_flask_resources"):
auth_manager.init_flask_resources()
if hasattr(auth_manager, "security_manager"):
self.sm = auth_manager.security_manager
else:
self.sm = AirflowSecurityManagerV2(self)
self.bm = BabelManager(self)
self._add_global_static()
self._add_global_filters()
app.before_request(self.sm.before_request)
self._add_admin_views()
self._add_addon_views()
self._init_extension(app)
self._swap_url_filter()
def _swap_url_filter(self):
"""Use our url filtering util function so there is consistency between FAB and Airflow routes."""
from flask_appbuilder.security import views as fab_sec_views
from airflow.providers.fab.www.views import get_safe_url
fab_sec_views.get_safe_redirect = get_safe_url
fab_sec_views.redirect = redirect
def _init_extension(self, app):
app.appbuilder = self
if not hasattr(app, "extensions"):
app.extensions = {}
app.extensions["appbuilder"] = self
@property
def app(self) -> Flask:
log.warning(
"appbuilder.app is deprecated and will be removed in a future version. Use current_app instead"
)
return current_app
@property
def get_app(self) -> Flask:
log.warning(
"appbuilder.get_app is deprecated and will be removed in a future version. "
"Use current_app instead"
)
return self.app
@property
def app_name(self):
"""
Get the App name.
:return: String with app name
"""
return current_app.config["APP_NAME"]
@property
def app_theme(self):
"""
Get the App theme name.
:return: String app theme name
"""
return current_app.config["APP_THEME"]
@property
def app_icon(self):
"""
Get the App icon location.
:return: String with relative app icon location
"""
return current_app.config["APP_ICON"]
@property
def languages(self):
return current_app.config["LANGUAGES"]
@property
def version(self):
"""
Get the current F.A.B. version.
:return: String with the current F.A.B. version
"""
return __version__
def _add_global_filters(self):
self.template_filters = TemplateFilters(current_app, self.sm)
def _add_global_static(self):
bp = Blueprint(
"appbuilder",
"flask_appbuilder.base",
url_prefix="/static",
template_folder="templates",
static_folder=self.static_folder,
static_url_path=self.static_url_path,
)
current_app.register_blueprint(bp)
def _add_admin_views(self):
"""Register indexview, utilview (back function), babel views and Security views."""
self.indexview = self._check_and_init(self.indexview)
self.add_view_no_menu(self.indexview)
self.add_view_no_menu(UtilView())
auth_manager = get_auth_manager()
if hasattr(auth_manager, "register_views"):
auth_manager.register_views()
def _add_addon_views(self):
"""Register declared addons."""
for addon in self._addon_managers:
addon_class = dynamic_class_import(addon)
if addon_class:
# Instantiate manager with appbuilder (self)
addon_class = addon_class(self)
try:
addon_class.pre_process()
addon_class.register_views()
addon_class.post_process()
self.addon_managers[addon] = addon_class
log.info(LOGMSG_INF_FAB_ADDON_ADDED, addon)
except Exception as e:
log.exception(e)
log.error(LOGMSG_ERR_FAB_ADDON_PROCESS, addon, e)
def _check_and_init(self, baseview):
if callable(baseview):
baseview = baseview()
return baseview
def add_view(
self,
baseview,
name,
href="",
icon="",
label="",
category="",
category_icon="",
category_label="",
menu_cond=None,
):
"""
Add your views associated with menus using this method.
:param baseview:
A BaseView type class instantiated or not.
This method will instantiate the class for you if needed.
:param name:
The string name that identifies the menu.
:param href:
Override the generated link for the menu.
You can use an url string or an endpoint name
if non provided default_view from view will be set as link.
:param icon:
Font-Awesome icon name, optional.
:param label:
The label that will be displayed on the menu,
if absent param name will be used
:param category:
The menu category where the menu will be included,
if non provided the view will be accessible as a top menu.
:param category_icon:
Font-Awesome icon name for the category, optional.
:param category_label:
The label that will be displayed on the menu,
if absent param name will be used
:param menu_cond:
If a callable, :code:`menu_cond` will be invoked when
constructing the menu items. If it returns :code:`True`,
then this link will be a part of the menu. Otherwise, it
will not be included in the menu items. Defaults to
:code:`None`, meaning the item will always be present.
Examples::
appbuilder = AppBuilder(app, db)
# Register a view, rendering a top menu without icon.
appbuilder.add_view(MyModelView(), "My View")
# or not instantiated
appbuilder.add_view(MyModelView, "My View")
# Register a view, a submenu "Other View" from "Other" with a phone icon.
appbuilder.add_view(MyOtherModelView, "Other View", icon="fa-phone", category="Others")
# Register a view, with category icon and translation.
appbuilder.add_view(
YetOtherModelView,
"Other View",
icon="fa-phone",
label=_("Other View"),
category="Others",
category_icon="fa-envelop",
category_label=_("Other View"),
)
# Register a view whose menu item will be conditionally displayed
appbuilder.add_view(
YourFeatureView,
"Your Feature",
icon="fa-feature",
label=_("Your Feature"),
menu_cond=lambda: is_feature_enabled("your-feature"),
)
# Add a link
appbuilder.add_link("google", href="www.google.com", icon="fa-google-plus")
"""
baseview = self._check_and_init(baseview)
log.debug(LOGMSG_INF_FAB_ADD_VIEW, baseview.__class__.__name__, name)
if not self._view_exists(baseview):
baseview.appbuilder = self
self.baseviews.append(baseview)
self._process_inner_views()
self.register_blueprint(baseview)
self._add_permission(baseview)
self.add_limits(baseview)
self.add_link(
name=name,
href=href,
icon=icon,
label=label,
category=category,
category_icon=category_icon,
category_label=category_label,
baseview=baseview,
cond=menu_cond,
)
return baseview
def add_link(
self,
name,
href,
icon="",
label="",
category="",
category_icon="",
category_label="",
baseview=None,
cond=None,
):
"""
Add your own links to menu using this method.
:param name:
The string name that identifies the menu.
:param href:
Override the generated link for the menu.
You can use an url string or an endpoint name
:param icon:
Font-Awesome icon name, optional.
:param label:
The label that will be displayed on the menu,
if absent param name will be used
:param category:
The menu category where the menu will be included,
if non provided the view will be accessible as a top menu.
:param category_icon:
Font-Awesome icon name for the category, optional.
:param category_label:
The label that will be displayed on the menu,
if absent param name will be used
:param baseview:
A BaseView type class instantiated.
:param cond:
If a callable, :code:`cond` will be invoked when
constructing the menu items. If it returns :code:`True`,
then this link will be a part of the menu. Otherwise, it
will not be included in the menu items. Defaults to
:code:`None`, meaning the item will always be present.
"""
self.menu.add_link(
name=name,
href=href,
icon=icon,
label=label,
category=category,
category_icon=category_icon,
category_label=category_label,
baseview=baseview,
cond=cond,
)
if current_app:
self._add_permissions_menu(name)
if category:
self._add_permissions_menu(category)
def add_separator(self, category, cond=None):
"""
Add a separator to the menu, you will sequentially create the menu.
:param category:
The menu category where the separator will be included.
:param cond:
If a callable, :code:`cond` will be invoked when
constructing the menu items. If it returns :code:`True`,
then this separator will be a part of the menu. Otherwise,
it will not be included in the menu items. Defaults to
:code:`None`, meaning the separator will always be present.
"""
self.menu.add_separator(category, cond=cond)
def add_view_no_menu(self, baseview, endpoint=None, static_folder=None):
"""
Add your views without creating a menu.
:param baseview: A BaseView type class instantiated.
"""
baseview = self._check_and_init(baseview)
log.debug(LOGMSG_INF_FAB_ADD_VIEW, baseview.__class__.__name__, "")
if not self._view_exists(baseview):
baseview.appbuilder = self
self.baseviews.append(baseview)
self._process_inner_views()
self.register_blueprint(baseview, endpoint=endpoint, static_folder=static_folder)
self._add_permission(baseview)
else:
log.warning(LOGMSG_WAR_FAB_VIEW_EXISTS, baseview.__class__.__name__)
return baseview
def add_api(self, baseview):
"""
Add a BaseApi class or child to AppBuilder.
:param baseview: A BaseApi type class
"""
return self.add_view_no_menu(baseview)
@property
def get_url_for_index(self):
return url_for(f"{self.indexview.endpoint}.{self.indexview.default_view}")
def get_url_for_login_with(self, next_url: str | None = None) -> str:
return get_auth_manager().get_url_login(next_url=next_url)
@property
def get_url_for_login(self):
return get_auth_manager().get_url_login()
def get_url_for_locale(self, lang):
return url_for(
f"{self.bm.locale_view.endpoint}.{self.bm.locale_view.default_view}",
locale=lang,
)
def add_limits(self, baseview) -> None:
if hasattr(baseview, "limits"):
self.sm.add_limit_view(baseview)
def _add_permission(self, baseview, update_perms=False):
if self.update_perms or update_perms:
try:
if hasattr(self.sm, "add_permissions_view"):
self.sm.add_permissions_view(baseview.base_permissions, baseview.class_permission_name)
except Exception as e:
log.exception(e)
log.error(LOGMSG_ERR_FAB_ADD_PERMISSION_VIEW, e)
def add_permissions(self, update_perms=False):
if self.update_perms or update_perms:
for baseview in self.baseviews:
self._add_permission(baseview, update_perms=update_perms)
self._add_menu_permissions(update_perms=update_perms)
def _add_permissions_menu(self, name, update_perms=False):
if self.update_perms or update_perms:
try:
if hasattr(self.sm, "add_permissions_menu"):
self.sm.add_permissions_menu(name)
except Exception as e:
log.exception(e)
log.error(LOGMSG_ERR_FAB_ADD_PERMISSION_MENU, e)
def _add_menu_permissions(self, update_perms=False):
if self.update_perms or update_perms:
for category in self.menu.get_list():
self._add_permissions_menu(category.name, update_perms=update_perms)
for item in category.childs:
# don't add permission for menu separator
if item.name != "-":
self._add_permissions_menu(item.name, update_perms=update_perms)
def register_blueprint(self, baseview, endpoint=None, static_folder=None):
current_app.register_blueprint(
baseview.create_blueprint(self, endpoint=endpoint, static_folder=static_folder)
)
def _view_exists(self, view):
return any(baseview.__class__ == view.__class__ for baseview in self.baseviews)
def _process_inner_views(self):
for view in self.baseviews:
for inner_class in view.get_uninit_inner_views():
for v in self.baseviews:
if isinstance(v, inner_class) and v not in view.get_init_inner_views():
view.get_init_inner_views().append(v)
def init_appbuilder(app: Flask, enable_plugins: bool) -> AirflowAppBuilder:
"""Init `Flask App Builder <https://flask-appbuilder.readthedocs.io/en/latest/>`__."""
if settings.Session is None:
raise RuntimeError("Session not configured. Call configure_orm() first.")
return AirflowAppBuilder(
app=app,
session=settings.Session(),
base_template="airflow/main.html",
enable_plugins=enable_plugins,
)
| AirflowAppBuilder |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_tk.py | {
"start": 44878,
"end": 45058
} | class ____(_Backend):
backend_version = tk.TkVersion
FigureCanvas = FigureCanvasTk
FigureManager = FigureManagerTk
mainloop = FigureManagerTk.start_main_loop
| _BackendTk |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 584222,
"end": 584788
} | class ____(sgqlc.types.Type):
"""A User who is an administrator of an enterprise."""
__schema__ = github_schema
__field_names__ = ("cursor", "node", "role")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("User", graphql_name="node")
"""The item at the end of the edge."""
role = sgqlc.types.Field(sgqlc.types.non_null(EnterpriseAdministratorRole), graphql_name="role")
"""The role of the administrator."""
| EnterpriseAdministratorEdge |
python | getsentry__sentry | src/sentry/sentry_metrics/consumers/indexer/common.py | {
"start": 679,
"end": 859
} | class ____(NamedTuple):
partition: Partition
offset: int
MessageBatch = list[Message[KafkaPayload]]
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
| BrokerMeta |
python | wireservice__csvkit | tests/utils.py | {
"start": 802,
"end": 2587
} | class ____(unittest.TestCase):
warnings.filterwarnings(action='ignore', module='agate')
def get_output(self, args):
output_file = io.TextIOWrapper(io.BytesIO(), encoding='utf-8', newline='', write_through=True)
utility = self.Utility(args, output_file)
utility.run()
output = output_file.buffer.getvalue().decode('utf-8')
output_file.close()
return output
def get_output_as_io(self, args):
return io.StringIO(self.get_output(args))
def get_output_as_list(self, args):
return self.get_output(args).split('\n')
def get_output_as_reader(self, args):
return agate.csv.reader(self.get_output_as_io(args))
def assertError(self, launch_new_instance, options, message, args=None):
command = self.Utility.__name__.lower()
if args is None:
args = ['examples/dummy.csv']
f = io.StringIO()
with redirect_stderr(f):
with patch.object(sys, 'argv', [command] + options + args):
with self.assertRaises(SystemExit) as e:
launch_new_instance()
self.assertEqual(e.exception.code, 2)
self.assertEqual(f.getvalue().splitlines()[-1], f'{command}: error: {message}')
def assertRows(self, args, rows):
reader = self.get_output_as_reader(args)
for row in rows:
self.assertEqual(next(reader), row)
self.assertRaises(StopIteration, next, reader)
def assertLines(self, args, rows, newline_at_eof=True):
lines = self.get_output_as_list(args)
if newline_at_eof:
rows.append('')
for i, row in enumerate(rows):
self.assertEqual(lines[i], row)
self.assertEqual(len(lines), len(rows))
| CSVKitTestCase |
python | coleifer__peewee | tests/mysql_ext.py | {
"start": 3668,
"end": 4533
} | class ____(ModelDatabaseTestCase):
requires = [Person]
def test_match_expression(self):
query = (Person
.select()
.where(Match(Person.first, 'charlie')))
self.assertSQL(query, (
'SELECT "t1"."id", "t1"."first", "t1"."last", "t1"."dob" '
'FROM "person" AS "t1" '
'WHERE MATCH("t1"."first") AGAINST(?)'), ['charlie'])
query = (Person
.select()
.where(Match((Person.first, Person.last), 'huey AND zaizee',
'IN BOOLEAN MODE')))
self.assertSQL(query, (
'SELECT "t1"."id", "t1"."first", "t1"."last", "t1"."dob" '
'FROM "person" AS "t1" '
'WHERE MATCH("t1"."first", "t1"."last") '
'AGAINST(? IN BOOLEAN MODE)'), ['huey AND zaizee'])
| TestMatchExpression |
python | kamyu104__LeetCode-Solutions | Python/find-the-number-of-good-pairs-ii.py | {
"start": 90,
"end": 516
} | class ____(object):
def numberOfPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: int
"""
cnt = [0]*(max(nums1)+1)
for x, c in collections.Counter(k*x for x in nums2).iteritems():
for i in xrange(1, (len(cnt)-1)//x+1):
cnt[i*x] += c
return sum(cnt[x] for x in nums1)
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-cart/source_cart/source.py | {
"start": 3116,
"end": 6341
} | class ____(AbstractSource):
def validate_config_values(func):
"""Check input config values for check_connection and stream functions. It will raise an exception if there is an parsing error"""
@wraps(func)
def decorator(self_, *args, **kwargs):
for arg in args:
if isinstance(arg, Mapping):
try:
# parse date strings by the pendulum library. It will raise the exception ParserError if it is some format mistakes.
pendulum.parse(arg["start_date"])
# try to check an end_date value. It can be ussed for different CI tests
end_date = arg.get("end_date")
if end_date:
pendulum.parse(end_date)
except ParserError as e:
raise Exception(f"{str(e)}. Example: 2021-01-01T00:00:00Z")
break
return func(self_, *args, **kwargs)
return decorator
def get_auth(self, config):
credentials = config.get("credentials", {})
auth_method = credentials.get("auth_type")
if auth_method == AuthMethod.CENTRAL_API_ROUTER.name:
authenticator = CentralAPIHeaderAuthenticator(
user_name=credentials["user_name"], user_secret=credentials["user_secret"], site_id=credentials["site_id"]
)
elif auth_method == AuthMethod.SINGLE_STORE_ACCESS_TOKEN.name:
authenticator = CustomHeaderAuthenticator(access_token=credentials["access_token"], store_name=credentials["store_name"])
else:
raise NotImplementedError(f"Authentication method: {auth_method} not implemented.")
return authenticator
@validate_config_values
def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Any]:
try:
authenticator = self.get_auth(config)
stream = Products(authenticator=authenticator, start_date=config["start_date"])
records = stream.read_records(sync_mode=SyncMode.full_refresh)
next(records)
return True, None
except Exception as e:
if isinstance(e, requests.exceptions.HTTPError) and e.response.status_code == 401:
return False, f"Please check your access token. Error: {repr(e)}"
if isinstance(e, requests.exceptions.ConnectionError):
err_message = f"Please check your `store_name` or internet connection. Error: {repr(e)}"
return False, err_message
return False, repr(e)
@validate_config_values
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
authenticator = self.get_auth(config)
args = {
"authenticator": authenticator,
"start_date": config["start_date"],
"end_date": config.get("end_date"),
}
return [
CustomersCart(**args),
Orders(**args),
OrderPayments(**args),
OrderStatuses(**args),
OrderItems(**args),
Products(**args),
Addresses(**args),
]
| SourceCart |
python | openai__openai-python | src/openai/types/responses/tool_choice_shell.py | {
"start": 192,
"end": 297
} | class ____(BaseModel):
type: Literal["shell"]
"""The tool to call. Always `shell`."""
| ToolChoiceShell |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol6.py | {
"start": 349,
"end": 480
} | class ____(Ungulate[bytes], Protocol):
species: Literal["camel"] # pyright: ignore[reportIncompatibleVariableOverride]
| CamelLike |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 53163,
"end": 62840
} | class ____(PolyCollection):
"""
`.PolyCollection` that fills the area between two x- or y-curves.
"""
def __init__(
self, t_direction, t, f1, f2, *,
where=None, interpolate=False, step=None, **kwargs):
"""
Parameters
----------
t_direction : {{'x', 'y'}}
The axes on which the variable lies.
- 'x': the curves are ``(t, f1)`` and ``(t, f2)``.
- 'y': the curves are ``(f1, t)`` and ``(f2, t)``.
t : array-like
The ``t_direction`` coordinates of the nodes defining the curves.
f1 : array-like or float
The other coordinates of the nodes defining the first curve.
f2 : array-like or float
The other coordinates of the nodes defining the second curve.
where : array-like of bool, optional
Define *where* to exclude some {dir} regions from being filled.
The filled regions are defined by the coordinates ``t[where]``.
More precisely, fill between ``t[i]`` and ``t[i+1]`` if
``where[i] and where[i+1]``. Note that this definition implies
that an isolated *True* value between two *False* values in *where*
will not result in filling. Both sides of the *True* position
remain unfilled due to the adjacent *False* values.
interpolate : bool, default: False
This option is only relevant if *where* is used and the two curves
are crossing each other.
Semantically, *where* is often used for *f1* > *f2* or
similar. By default, the nodes of the polygon defining the filled
region will only be placed at the positions in the *t* array.
Such a polygon cannot describe the above semantics close to the
intersection. The t-sections containing the intersection are
simply clipped.
Setting *interpolate* to *True* will calculate the actual
intersection point and extend the filled region up to this point.
step : {{'pre', 'post', 'mid'}}, optional
Define *step* if the filling should be a step function,
i.e. constant in between *t*. The value determines where the
step will occur:
- 'pre': The f value is continued constantly to the left from
every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the
value ``f[i]``.
- 'post': The y value is continued constantly to the right from
every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the
value ``f[i]``.
- 'mid': Steps occur half-way between the *t* positions.
**kwargs
Forwarded to `.PolyCollection`.
See Also
--------
.Axes.fill_between, .Axes.fill_betweenx
"""
self.t_direction = t_direction
self._interpolate = interpolate
self._step = step
verts = self._make_verts(t, f1, f2, where)
super().__init__(verts, **kwargs)
@staticmethod
def _f_dir_from_t(t_direction):
"""The direction that is other than `t_direction`."""
if t_direction == "x":
return "y"
elif t_direction == "y":
return "x"
else:
msg = f"t_direction must be 'x' or 'y', got {t_direction!r}"
raise ValueError(msg)
@property
def _f_direction(self):
"""The direction that is other than `self.t_direction`."""
return self._f_dir_from_t(self.t_direction)
def set_data(self, t, f1, f2, *, where=None):
"""
Set new values for the two bounding curves.
Parameters
----------
t : array-like
The ``self.t_direction`` coordinates of the nodes defining the curves.
f1 : array-like or float
The other coordinates of the nodes defining the first curve.
f2 : array-like or float
The other coordinates of the nodes defining the second curve.
where : array-like of bool, optional
Define *where* to exclude some {dir} regions from being filled.
The filled regions are defined by the coordinates ``t[where]``.
More precisely, fill between ``t[i]`` and ``t[i+1]`` if
``where[i] and where[i+1]``. Note that this definition implies
that an isolated *True* value between two *False* values in *where*
will not result in filling. Both sides of the *True* position
remain unfilled due to the adjacent *False* values.
See Also
--------
.PolyCollection.set_verts, .Line2D.set_data
"""
t, f1, f2 = self.axes._fill_between_process_units(
self.t_direction, self._f_direction, t, f1, f2)
verts = self._make_verts(t, f1, f2, where)
self.set_verts(verts)
def get_datalim(self, transData):
"""Calculate the data limits and return them as a `.Bbox`."""
datalim = transforms.Bbox.null()
datalim.update_from_data_xy((self.get_transform() - transData).transform(
np.concatenate([self._bbox, [self._bbox.minpos]])))
return datalim
def _make_verts(self, t, f1, f2, where):
"""
Make verts that can be forwarded to `.PolyCollection`.
"""
self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2)
where = self._get_data_mask(t, f1, f2, where)
t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True)
self._bbox = transforms.Bbox.null()
self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([
np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)])))
return [
self._make_verts_for_region(t, f1, f2, idx0, idx1)
for idx0, idx1 in cbook.contiguous_regions(where)
]
def _get_data_mask(self, t, f1, f2, where):
"""
Return a bool array, with True at all points that should eventually be rendered.
The array is True at a point if none of the data inputs
*t*, *f1*, *f2* is masked and if the input *where* is true at that point.
"""
if where is None:
where = True
else:
where = np.asarray(where, dtype=bool)
if where.size != t.size:
msg = "where size ({}) does not match {!r} size ({})".format(
where.size, self.t_direction, t.size)
raise ValueError(msg)
return where & ~functools.reduce(
np.logical_or, map(np.ma.getmaskarray, [t, f1, f2]))
@staticmethod
def _validate_shapes(t_dir, f_dir, t, f1, f2):
"""Validate that t, f1 and f2 are 1-dimensional and have the same length."""
names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2")))
for name, array in zip(names, [t, f1, f2]):
if array.ndim > 1:
raise ValueError(f"{name!r} is not 1-dimensional")
if t.size > 1 and array.size > 1 and t.size != array.size:
msg = "{!r} has size {}, but {!r} has an unequal size of {}".format(
t_dir, t.size, name, array.size)
raise ValueError(msg)
def _make_verts_for_region(self, t, f1, f2, idx0, idx1):
"""
Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking
into account ``step`` and ``interpolate``.
"""
t_slice = t[idx0:idx1]
f1_slice = f1[idx0:idx1]
f2_slice = f2[idx0:idx1]
if self._step is not None:
step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step]
t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice)
if self._interpolate:
start = self._get_interpolating_points(t, f1, f2, idx0)
end = self._get_interpolating_points(t, f1, f2, idx1)
else:
# Handle scalar f2 (e.g. 0): the fill should go all
# the way down to 0 even if none of the dep1 sample points do.
start = t_slice[0], f2_slice[0]
end = t_slice[-1], f2_slice[-1]
pts = np.concatenate((
np.asarray([start]),
np.stack((t_slice, f1_slice), axis=-1),
np.asarray([end]),
np.stack((t_slice, f2_slice), axis=-1)[::-1]))
return self._fix_pts_xy_order(pts)
@classmethod
def _get_interpolating_points(cls, t, f1, f2, idx):
"""Calculate interpolating points."""
im1 = max(idx - 1, 0)
t_values = t[im1:idx+1]
diff_values = f1[im1:idx+1] - f2[im1:idx+1]
f1_values = f1[im1:idx+1]
if len(diff_values) == 2:
if np.ma.is_masked(diff_values[1]):
return t[im1], f1[im1]
elif np.ma.is_masked(diff_values[0]):
return t[idx], f1[idx]
diff_root_t = cls._get_diff_root(0, diff_values, t_values)
diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values)
return diff_root_t, diff_root_f
@staticmethod
def _get_diff_root(x, xp, fp):
"""Calculate diff root."""
order = xp.argsort()
return np.interp(x, xp[order], fp[order])
def _fix_pts_xy_order(self, pts):
"""
Fix pts calculation results with `self.t_direction`.
In the workflow, it is assumed that `self.t_direction` is 'x'. If this
is not true, we need to exchange the coordinates.
"""
return pts[:, ::-1] if self.t_direction == "y" else pts
| FillBetweenPolyCollection |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/output_parsers/test_fix.py | {
"start": 1232,
"end": 7554
} | class ____(SuccessfulParseAfterRetries):
def get_format_instructions(self) -> str:
return "instructions"
@pytest.mark.parametrize(
"base_parser",
[
SuccessfulParseAfterRetries(attemp_count_before_success=5),
SuccessfulParseAfterRetriesWithGetFormatInstructions(
attemp_count_before_success=5,
),
],
)
def test_output_fixing_parser_parse(
base_parser: SuccessfulParseAfterRetries,
) -> None:
# preparation
n: int = base_parser.attemp_count_before_success # Success on the (n+1)-th attempt
base_parser = SuccessfulParseAfterRetries(attemp_count_before_success=n)
parser = OutputFixingParser[str](
parser=base_parser,
max_retries=n, # n times to retry, that is, (n+1) times call
retry_chain=RunnablePassthrough(),
legacy=False,
)
# test
assert parser.parse("completion") == "parsed"
assert base_parser.parse_count == n + 1
# TODO: test whether "instructions" is passed to the retry_chain
def test_output_fixing_parser_from_llm() -> None:
def fake_llm(_: str) -> AIMessage:
return AIMessage("2024-07-08T00:00:00.000000Z")
llm = RunnableLambda(fake_llm)
n = 1
parser = OutputFixingParser.from_llm(
llm=llm,
parser=DatetimeOutputParser(),
max_retries=n,
)
assert parser.parse("not a date")
@pytest.mark.parametrize(
"base_parser",
[
SuccessfulParseAfterRetries(attemp_count_before_success=5),
SuccessfulParseAfterRetriesWithGetFormatInstructions(
attemp_count_before_success=5,
),
],
)
async def test_output_fixing_parser_aparse(
base_parser: SuccessfulParseAfterRetries,
) -> None:
n: int = base_parser.attemp_count_before_success # Success on the (n+1)-th attempt
base_parser = SuccessfulParseAfterRetries(attemp_count_before_success=n)
parser = OutputFixingParser[str](
parser=base_parser,
max_retries=n, # n times to retry, that is, (n+1) times call
retry_chain=RunnablePassthrough(),
legacy=False,
)
assert (await parser.aparse("completion")) == "parsed"
assert base_parser.parse_count == n + 1
# TODO: test whether "instructions" is passed to the retry_chain
def test_output_fixing_parser_parse_fail() -> None:
n: int = 5 # Success on the (n+1)-th attempt
base_parser = SuccessfulParseAfterRetries(attemp_count_before_success=n)
parser = OutputFixingParser[str](
parser=base_parser,
max_retries=n - 1, # n-1 times to retry, that is, n times call
retry_chain=RunnablePassthrough(),
legacy=False,
)
with pytest.raises(OutputParserException):
parser.parse("completion")
assert base_parser.parse_count == n
async def test_output_fixing_parser_aparse_fail() -> None:
n: int = 5 # Success on the (n+1)-th attempt
base_parser = SuccessfulParseAfterRetries(attemp_count_before_success=n)
parser = OutputFixingParser[str](
parser=base_parser,
max_retries=n - 1, # n-1 times to retry, that is, n times call
retry_chain=RunnablePassthrough(),
legacy=False,
)
with pytest.raises(OutputParserException):
await parser.aparse("completion")
assert base_parser.parse_count == n
@pytest.mark.parametrize(
"base_parser",
[
BooleanOutputParser(),
DatetimeOutputParser(),
],
)
def test_output_fixing_parser_output_type(
base_parser: BaseOutputParser,
) -> None:
parser = OutputFixingParser[str](
parser=base_parser,
retry_chain=RunnablePassthrough(),
)
assert parser.OutputType is base_parser.OutputType
@pytest.mark.parametrize(
("completion", "base_parser", "retry_chain", "expected"),
[
(
"2024/07/08",
DatetimeOutputParser(format="%Y-%m-%dT%H:%M:%S.%f%z"),
NAIVE_FIX_PROMPT | RunnableLambda(lambda _: "2024-07-08T00:00:00.000000Z"),
dt(2024, 7, 8, tzinfo=timezone.utc),
),
(
# Case: retry_chain.InputType does not have 'instructions' key
"2024/07/08",
DatetimeOutputParser(format="%Y-%m-%dT%H:%M:%S.%f%z"),
PromptTemplate.from_template("{completion}\n{error}")
| RunnableLambda(lambda _: "2024-07-08T00:00:00.000000Z"),
dt(2024, 7, 8, tzinfo=timezone.utc),
),
],
)
def test_output_fixing_parser_parse_with_retry_chain(
completion: str,
base_parser: BaseOutputParser[T],
retry_chain: Runnable[dict[str, Any], str],
expected: T,
) -> None:
# NOTE: get_format_instructions of some parsers behave randomly
instructions = base_parser.get_format_instructions()
object.__setattr__(base_parser, "get_format_instructions", lambda: instructions)
# test
parser = OutputFixingParser[str](
parser=base_parser,
retry_chain=retry_chain,
legacy=False,
)
assert parser.parse(completion) == expected
@pytest.mark.parametrize(
("completion", "base_parser", "retry_chain", "expected"),
[
(
"2024/07/08",
DatetimeOutputParser(format="%Y-%m-%dT%H:%M:%S.%f%z"),
NAIVE_FIX_PROMPT | RunnableLambda(lambda _: "2024-07-08T00:00:00.000000Z"),
dt(2024, 7, 8, tzinfo=timezone.utc),
),
(
# Case: retry_chain.InputType does not have 'instructions' key
"2024/07/08",
DatetimeOutputParser(format="%Y-%m-%dT%H:%M:%S.%f%z"),
PromptTemplate.from_template("{completion}\n{error}")
| RunnableLambda(lambda _: "2024-07-08T00:00:00.000000Z"),
dt(2024, 7, 8, tzinfo=timezone.utc),
),
],
)
async def test_output_fixing_parser_aparse_with_retry_chain(
completion: str,
base_parser: BaseOutputParser[T],
retry_chain: Runnable[dict[str, Any], str],
expected: T,
) -> None:
instructions = base_parser.get_format_instructions()
object.__setattr__(base_parser, "get_format_instructions", lambda: instructions)
# test
parser = OutputFixingParser[str](
parser=base_parser,
retry_chain=retry_chain,
legacy=False,
)
assert (await parser.aparse(completion)) == expected
| SuccessfulParseAfterRetriesWithGetFormatInstructions |
python | ray-project__ray | python/ray/data/_internal/compute.py | {
"start": 888,
"end": 1896
} | class ____(ComputeStrategy):
"""Specify the task-based compute strategy for a Dataset transform.
TaskPoolStrategy executes dataset transformations using Ray tasks that are
scheduled through a pool. Provide ``size`` to cap the number of concurrent
tasks; leave it unset to allow Ray Data to scale the task count
automatically.
"""
def __init__(
self,
size: Optional[int] = None,
):
"""Construct TaskPoolStrategy for a Dataset transform.
Args:
size: Specify the maximum size of the task pool.
"""
if size is not None and size < 1:
raise ValueError("`size` must be >= 1", size)
self.size = size
def __eq__(self, other: Any) -> bool:
return (isinstance(other, TaskPoolStrategy) and self.size == other.size) or (
other == "tasks" and self.size is None
)
def __repr__(self) -> str:
return f"TaskPoolStrategy(size={self.size})"
@PublicAPI
| TaskPoolStrategy |
python | walkccc__LeetCode | solutions/3186. Maximum Total Damage With Spell Casting/3186.py | {
"start": 0,
"end": 800
} | class ____:
def maximumTotalDamage(self, power: list[int]) -> int:
count = collections.Counter(power)
uniqueDamages = sorted(count.keys())
# dp[i][k] := the maximum damage using uniqueDamages[0..i], where k
# indicates if the i-th damage is used
dp = [[0] * 2 for _ in range(len(uniqueDamages))]
for i, damage in enumerate(uniqueDamages):
if i == 0:
dp[0] = [0, damage * count[damage]]
continue
dp[i][0] = max(dp[i - 1])
dp[i][1] = damage * count[damage]
if i >= 1 and uniqueDamages[i - 1] not in (damage - 1, damage - 2):
dp[i][1] += max(dp[i - 1])
elif i >= 2 and uniqueDamages[i - 2] != damage - 2:
dp[i][1] += max(dp[i - 2])
elif i >= 3:
dp[i][1] += max(dp[i - 3])
return max(dp[-1])
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/__generated__/dagster_api_pb2_grpc.py | {
"start": 8308,
"end": 24146
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def Ping(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Heartbeat(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def StreamingPing(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def GetServerId(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExecutionPlanSnapshot(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ListRepositories(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalPartitionNames(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalNotebookData(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalPartitionConfig(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalPartitionTags(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalPartitionSetExecutionParams(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalPipelineSubsetSnapshot(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalRepository(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalJob(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def StreamingExternalRepository(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalScheduleExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def SyncExternalScheduleExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ExternalSensorExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def SyncExternalSensorExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ShutdownServer(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def CancelExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def CanCancelExecution(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def StartRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def GetCurrentImage(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def GetCurrentRuns(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def ReloadCode(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def add_DagsterApiServicer_to_server(servicer, server):
rpc_method_handlers = {
"Ping": grpc.unary_unary_rpc_method_handler(
servicer.Ping,
request_deserializer=dagster__api__pb2.PingRequest.FromString,
response_serializer=dagster__api__pb2.PingReply.SerializeToString,
),
"Heartbeat": grpc.unary_unary_rpc_method_handler(
servicer.Heartbeat,
request_deserializer=dagster__api__pb2.PingRequest.FromString,
response_serializer=dagster__api__pb2.PingReply.SerializeToString,
),
"StreamingPing": grpc.unary_stream_rpc_method_handler(
servicer.StreamingPing,
request_deserializer=dagster__api__pb2.StreamingPingRequest.FromString,
response_serializer=dagster__api__pb2.StreamingPingEvent.SerializeToString,
),
"GetServerId": grpc.unary_unary_rpc_method_handler(
servicer.GetServerId,
request_deserializer=dagster__api__pb2.Empty.FromString,
response_serializer=dagster__api__pb2.GetServerIdReply.SerializeToString,
),
"ExecutionPlanSnapshot": grpc.unary_unary_rpc_method_handler(
servicer.ExecutionPlanSnapshot,
request_deserializer=dagster__api__pb2.ExecutionPlanSnapshotRequest.FromString,
response_serializer=dagster__api__pb2.ExecutionPlanSnapshotReply.SerializeToString,
),
"ListRepositories": grpc.unary_unary_rpc_method_handler(
servicer.ListRepositories,
request_deserializer=dagster__api__pb2.ListRepositoriesRequest.FromString,
response_serializer=dagster__api__pb2.ListRepositoriesReply.SerializeToString,
),
"ExternalPartitionNames": grpc.unary_unary_rpc_method_handler(
servicer.ExternalPartitionNames,
request_deserializer=dagster__api__pb2.ExternalPartitionNamesRequest.FromString,
response_serializer=dagster__api__pb2.ExternalPartitionNamesReply.SerializeToString,
),
"ExternalNotebookData": grpc.unary_unary_rpc_method_handler(
servicer.ExternalNotebookData,
request_deserializer=dagster__api__pb2.ExternalNotebookDataRequest.FromString,
response_serializer=dagster__api__pb2.ExternalNotebookDataReply.SerializeToString,
),
"ExternalPartitionConfig": grpc.unary_unary_rpc_method_handler(
servicer.ExternalPartitionConfig,
request_deserializer=dagster__api__pb2.ExternalPartitionConfigRequest.FromString,
response_serializer=dagster__api__pb2.ExternalPartitionConfigReply.SerializeToString,
),
"ExternalPartitionTags": grpc.unary_unary_rpc_method_handler(
servicer.ExternalPartitionTags,
request_deserializer=dagster__api__pb2.ExternalPartitionTagsRequest.FromString,
response_serializer=dagster__api__pb2.ExternalPartitionTagsReply.SerializeToString,
),
"ExternalPartitionSetExecutionParams": grpc.unary_stream_rpc_method_handler(
servicer.ExternalPartitionSetExecutionParams,
request_deserializer=dagster__api__pb2.ExternalPartitionSetExecutionParamsRequest.FromString,
response_serializer=dagster__api__pb2.StreamingChunkEvent.SerializeToString,
),
"ExternalPipelineSubsetSnapshot": grpc.unary_unary_rpc_method_handler(
servicer.ExternalPipelineSubsetSnapshot,
request_deserializer=dagster__api__pb2.ExternalPipelineSubsetSnapshotRequest.FromString,
response_serializer=dagster__api__pb2.ExternalPipelineSubsetSnapshotReply.SerializeToString,
),
"ExternalRepository": grpc.unary_unary_rpc_method_handler(
servicer.ExternalRepository,
request_deserializer=dagster__api__pb2.ExternalRepositoryRequest.FromString,
response_serializer=dagster__api__pb2.ExternalRepositoryReply.SerializeToString,
),
"ExternalJob": grpc.unary_unary_rpc_method_handler(
servicer.ExternalJob,
request_deserializer=dagster__api__pb2.ExternalJobRequest.FromString,
response_serializer=dagster__api__pb2.ExternalJobReply.SerializeToString,
),
"StreamingExternalRepository": grpc.unary_stream_rpc_method_handler(
servicer.StreamingExternalRepository,
request_deserializer=dagster__api__pb2.ExternalRepositoryRequest.FromString,
response_serializer=dagster__api__pb2.StreamingExternalRepositoryEvent.SerializeToString,
),
"ExternalScheduleExecution": grpc.unary_stream_rpc_method_handler(
servicer.ExternalScheduleExecution,
request_deserializer=dagster__api__pb2.ExternalScheduleExecutionRequest.FromString,
response_serializer=dagster__api__pb2.StreamingChunkEvent.SerializeToString,
),
"SyncExternalScheduleExecution": grpc.unary_unary_rpc_method_handler(
servicer.SyncExternalScheduleExecution,
request_deserializer=dagster__api__pb2.ExternalScheduleExecutionRequest.FromString,
response_serializer=dagster__api__pb2.ExternalScheduleExecutionReply.SerializeToString,
),
"ExternalSensorExecution": grpc.unary_stream_rpc_method_handler(
servicer.ExternalSensorExecution,
request_deserializer=dagster__api__pb2.ExternalSensorExecutionRequest.FromString,
response_serializer=dagster__api__pb2.StreamingChunkEvent.SerializeToString,
),
"SyncExternalSensorExecution": grpc.unary_unary_rpc_method_handler(
servicer.SyncExternalSensorExecution,
request_deserializer=dagster__api__pb2.ExternalSensorExecutionRequest.FromString,
response_serializer=dagster__api__pb2.ExternalSensorExecutionReply.SerializeToString,
),
"ShutdownServer": grpc.unary_unary_rpc_method_handler(
servicer.ShutdownServer,
request_deserializer=dagster__api__pb2.Empty.FromString,
response_serializer=dagster__api__pb2.ShutdownServerReply.SerializeToString,
),
"CancelExecution": grpc.unary_unary_rpc_method_handler(
servicer.CancelExecution,
request_deserializer=dagster__api__pb2.CancelExecutionRequest.FromString,
response_serializer=dagster__api__pb2.CancelExecutionReply.SerializeToString,
),
"CanCancelExecution": grpc.unary_unary_rpc_method_handler(
servicer.CanCancelExecution,
request_deserializer=dagster__api__pb2.CanCancelExecutionRequest.FromString,
response_serializer=dagster__api__pb2.CanCancelExecutionReply.SerializeToString,
),
"StartRun": grpc.unary_unary_rpc_method_handler(
servicer.StartRun,
request_deserializer=dagster__api__pb2.StartRunRequest.FromString,
response_serializer=dagster__api__pb2.StartRunReply.SerializeToString,
),
"GetCurrentImage": grpc.unary_unary_rpc_method_handler(
servicer.GetCurrentImage,
request_deserializer=dagster__api__pb2.Empty.FromString,
response_serializer=dagster__api__pb2.GetCurrentImageReply.SerializeToString,
),
"GetCurrentRuns": grpc.unary_unary_rpc_method_handler(
servicer.GetCurrentRuns,
request_deserializer=dagster__api__pb2.Empty.FromString,
response_serializer=dagster__api__pb2.GetCurrentRunsReply.SerializeToString,
),
"ReloadCode": grpc.unary_unary_rpc_method_handler(
servicer.ReloadCode,
request_deserializer=dagster__api__pb2.ReloadCodeRequest.FromString,
response_serializer=dagster__api__pb2.ReloadCodeReply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler("api.DagsterApi", rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
| DagsterApiServicer |
python | huggingface__transformers | src/transformers/models/cohere2/modeling_cohere2.py | {
"start": 16328,
"end": 16879
} | class ____(PreTrainedModel):
config: Cohere2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Cohere2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": Cohere2DecoderLayer,
"attentions": Cohere2Attention,
}
@auto_docstring
| Cohere2PreTrainedModel |
python | arrow-py__arrow | tests/test_arrow.py | {
"start": 3591,
"end": 7101
} | class ____:
def test_now(self):
result = arrow.Arrow.now()
assert_datetime_equality(result._datetime, datetime.now().astimezone())
def test_utcnow(self):
result = arrow.Arrow.utcnow()
assert_datetime_equality(
result._datetime, datetime.now(timezone.utc).replace(tzinfo=timezone.utc)
)
assert result.fold == 0
def test_fromtimestamp(self):
timestamp = time.time()
result = arrow.Arrow.fromtimestamp(timestamp)
assert_datetime_equality(result._datetime, datetime.now().astimezone())
result = arrow.Arrow.fromtimestamp(timestamp, tzinfo=ZoneInfo("Europe/Paris"))
assert_datetime_equality(
result._datetime,
datetime.fromtimestamp(timestamp, ZoneInfo("Europe/Paris")),
)
result = arrow.Arrow.fromtimestamp(timestamp, tzinfo="Europe/Paris")
assert_datetime_equality(
result._datetime,
datetime.fromtimestamp(timestamp, ZoneInfo("Europe/Paris")),
)
with pytest.raises(ValueError):
arrow.Arrow.fromtimestamp("invalid timestamp")
def test_utcfromtimestamp(self):
timestamp = time.time()
result = arrow.Arrow.utcfromtimestamp(timestamp)
assert_datetime_equality(
result._datetime, datetime.now(timezone.utc).replace(tzinfo=timezone.utc)
)
with pytest.raises(ValueError):
arrow.Arrow.utcfromtimestamp("invalid timestamp")
def test_fromdatetime(self):
dt = datetime(2013, 2, 3, 12, 30, 45, 1)
result = arrow.Arrow.fromdatetime(dt)
assert result._datetime == dt.replace(tzinfo=tz.tzutc())
def test_fromdatetime_dt_tzinfo(self):
dt = datetime(2013, 2, 3, 12, 30, 45, 1, tzinfo=ZoneInfo("US/Pacific"))
result = arrow.Arrow.fromdatetime(dt)
assert result._datetime == dt.replace(tzinfo=ZoneInfo("US/Pacific"))
def test_fromdatetime_tzinfo_arg(self):
dt = datetime(2013, 2, 3, 12, 30, 45, 1)
result = arrow.Arrow.fromdatetime(dt, ZoneInfo("US/Pacific"))
assert result._datetime == dt.replace(tzinfo=ZoneInfo("US/Pacific"))
def test_fromdate(self):
dt = date(2013, 2, 3)
result = arrow.Arrow.fromdate(dt, ZoneInfo("US/Pacific"))
assert result._datetime == datetime(2013, 2, 3, tzinfo=ZoneInfo("US/Pacific"))
def test_strptime(self):
formatted = datetime(2013, 2, 3, 12, 30, 45).strftime("%Y-%m-%d %H:%M:%S")
result = arrow.Arrow.strptime(formatted, "%Y-%m-%d %H:%M:%S")
assert result._datetime == datetime(2013, 2, 3, 12, 30, 45, tzinfo=tz.tzutc())
result = arrow.Arrow.strptime(
formatted, "%Y-%m-%d %H:%M:%S", tzinfo=ZoneInfo("Europe/Paris")
)
assert result._datetime == datetime(
2013, 2, 3, 12, 30, 45, tzinfo=ZoneInfo("Europe/Paris")
)
def test_fromordinal(self):
timestamp = 1607066909.937968
with pytest.raises(TypeError):
arrow.Arrow.fromordinal(timestamp)
with pytest.raises(ValueError):
arrow.Arrow.fromordinal(int(timestamp))
ordinal = arrow.Arrow.utcnow().toordinal()
with pytest.raises(TypeError):
arrow.Arrow.fromordinal(str(ordinal))
result = arrow.Arrow.fromordinal(ordinal)
dt = datetime.fromordinal(ordinal)
assert result.naive == dt
@pytest.mark.usefixtures("time_2013_02_03")
| TestTestArrowFactory |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 1616,
"end": 1811
} | class ____(G1[_P, _R]):
# This should generate an error because f is missing ParamSpec parameters.
def f(self) -> _R: ...
def g(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...
| G2 |
python | bokeh__bokeh | tests/unit/bokeh/document/test_events__document.py | {
"start": 2620,
"end": 4055
} | class ____:
def test_init(self) -> None:
doc = Document()
e = bde.DocumentChangedEvent(doc)
assert e.document == doc
assert e.setter is None
assert e.callback_invoker is None
doc = Document()
e = bde.DocumentChangedEvent(doc, "setter")
assert e.document == doc
assert e.setter == "setter"
assert e.callback_invoker is None
doc = Document()
e = bde.DocumentChangedEvent(doc, callback_invoker="invoker")
assert e.document == doc
assert e.setter is None
assert e.callback_invoker == "invoker"
doc = Document()
e = bde.DocumentChangedEvent(doc, "setter", "invoker")
assert e.document == doc
assert e.setter == "setter"
assert e.callback_invoker == "invoker"
def test_dispatch(self) -> None:
doc = Document()
e = bde.DocumentChangedEvent(doc, "setter", "invoker")
e.dispatch(FakeEmptyDispatcher())
d = FakeFullDispatcher()
e.dispatch(d)
assert d.called == ['_document_changed']
def test_combine_ignores_all(self) -> None:
doc = Document()
e = bde.DocumentChangedEvent(doc, "setter", "invoker")
e2 = bde.DocumentChangedEvent(doc, "setter", "invoker")
assert e.combine(e2) is False
# DocumentPatchedEvent --------------------------------------------------------
| TestDocumentChangedEvent |
python | pytorch__pytorch | test/inductor/test_autoheuristic.py | {
"start": 741,
"end": 7251
} | class ____(TestCase):
def count_lines_in_file(self, file_path):
with open(file_path) as file:
line_count = sum(1 for line in file)
return line_count
def run_mm(self):
def f(a, b):
return torch.mm(a, b)
cf = torch.compile(f)
a = torch.randn(2047, 2048, device=GPU_TYPE, dtype=torch.float16)
b = torch.randn(2048, 2048, device=GPU_TYPE, dtype=torch.float16)
cf(a, b)
def get_path_to_autoheuristic_log(self, name):
device_name = AutoHeuristic.get_device_identifier()
path = cache_dir() + "/autoheuristic/" + device_name + "/" + name + ".txt"
return path
def test_autoheuristic_pad_mm_default(self):
# this test ensures that data is not collected for pad_mm when autoheuristic config is set to its default value
self.run_mm()
self.assertFalse(os.path.exists(self.get_path_to_autoheuristic_log("pad_mm")))
@inductor_config.patch(autoheuristic_collect="foo")
def test_autoheuristic_pad_mm_off(self):
# this test ensures that data is not collected for pad_mm when autoheuristic_collect does not contain "pad_mm"
self.run_mm()
self.assertFalse(os.path.exists(self.get_path_to_autoheuristic_log("pad_mm")))
def assert_autoheuristic_collected_data(self):
self.run_mm()
AutoHeuristic.get_device_identifier()
path = self.get_path_to_autoheuristic_log("pad_mm")
self.assertTrue(os.path.exists(path))
num_lines = self.count_lines_in_file(path)
# 1 line for metadata, 1 line for header, 1 line per choice (orig, padded)
self.assertEqual(num_lines, 4)
@inductor_config.patch(autoheuristic_collect="pad_mm")
def test_autoheuristic_pad_mm_collect_data(self):
# this test ensures that data is collected for pad_mm when autoheuristic_collect="pad_mm"
self.assert_autoheuristic_collected_data()
@inductor_config.patch(autoheuristic_collect="foo,pad_mm")
def test_autoheuristic_pad_mm_collect_data2(self):
# this test ensures that data is collected for "pad_mm" when autoheuristic_collect contains "pad_mm"
self.assert_autoheuristic_collected_data()
@inductor_config.patch(autoheuristic_collect="test")
def test_autoheuristic(self):
# test basic functionality of autoheuristic
def fallback():
return "fallback"
choices = ["a", "b", "c"]
def feedback_fn(choice):
if choice == "a":
return 1
elif choice == "b":
return 2
elif choice == "c":
return 3
else:
raise RuntimeError("unexpected choice")
feedback = LocalFeedback(feedback_fn)
context = AHContext()
context.add_feature("fa", 5)
name = "test"
autoheuristic = AutoHeuristic(fallback, choices, feedback, context, name)
# when autoheuristic is configured to only collect data, we always return fallback
self.assertEqual(autoheuristic.get_choice(), "fallback")
self.assertEqual(autoheuristic.get_collected_feedback("a"), 1)
self.assertEqual(autoheuristic.get_collected_feedback("b"), 2)
self.assertEqual(autoheuristic.get_collected_feedback("c"), 3)
path = self.get_path_to_autoheuristic_log(name)
self.assertTrue(os.path.exists(path))
num_lines = self.count_lines_in_file(path)
self.assertEqual(num_lines, 5)
shared_memory = get_gpu_shared_memory()
(fst, snd) = get_interface_for_device(GPU_TYPE).get_device_capability()
with open(path) as file:
lines = file.readlines()
self.assertTrue('"numerical_features": ["fa"]' in lines[0])
self.assertTrue('"categorical_features": []' in lines[0])
self.assertTrue(f'"shared_memory": {shared_memory}' in lines[0])
self.assertTrue(f'"device_capa": [{fst}, {snd}]' in lines[0])
self.assertTrue('"name": "test"' in lines[0])
self.assertEqual("fa,choice,feedback", lines[1].rstrip())
self.assertEqual("5,a,1", lines[2].rstrip())
self.assertEqual("5,b,2", lines[3].rstrip())
self.assertEqual("5,c,3", lines[4].rstrip())
@unittest.skipIf(not IS_A100, "heuristic only run on A100")
@inductor_config.patch(autoheuristic_use="pad_mm")
def test_autoheuristic_a100(self):
# Make sure heuristic does not break anything
# TODO (AlnisM): Find a way to check whether heuristic is used
self.run_mm()
@unittest.skipIf(not IS_H100, "heuristic only run on H100")
@inductor_config.patch(autoheuristic_use="pad_mm")
def test_autoheuristic_h100(self):
# Make sure heuristic does not break anything
# TODO (AlnisM): Find a way to check whether heuristic is used
self.run_mm()
def run_mixed_mm(self):
def fn(a, b):
return torch.mm(a, b.to(a.dtype))
a = torch.randn(8, 1024, device=GPU_TYPE, dtype=torch.float16)
b = torch.randint(
-128, 127, (1024, 1024), dtype=torch.int8, device=GPU_TYPE
).t()
torch.compile(fn, mode="max-autotune-no-cudagraphs")(a, b)
# have to set autoheuristic_use="" because if autoheuristic_use="mixed_mm",
# autoheuristic creates a precompile key, puts it into the registry, and then
# a choice made by the heuristic might be added to the list of choices
# and if select_algorithm now creates a new precompile key, it will be
# different from the precompile key created by autoheuristic
@inductor_config.patch(
autoheuristic_collect="mixed_mm",
autoheuristic_use="",
fx_graph_cache=False,
fx_graph_remote_cache=False,
)
def test_global_feedback(self):
self.run_mixed_mm()
path = self.get_path_to_autoheuristic_log("mixed_mm")
self.assertTrue(os.path.exists(path))
num_lines = self.count_lines_in_file(path)
# 1 line for metadata, 1 line for header
# 1 line for fallback + at least 1 config
self.assertTrue(num_lines > 4)
@inductor_config.patch(autoheuristic_use="mixed_mm")
@unittest.skipIf(not IS_A100, "heuristic only run on A100")
def test_mixed_mm_a100(self):
self.run_mixed_mm()
# TODO (AlnisM): Find a way to check whether heuristic is used
if __name__ == "__main__":
if HAS_GPU:
run_tests()
| AutoHeuristicTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1125386,
"end": 1129936
} | class ____(VegaLiteSchema):
"""
ScaleInvalidDataConfig schema wrapper.
Parameters
----------
angle : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsangle`, :class:`ScaleInvalidDataShowAsValueangle`
color : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAscolor`, :class:`ScaleInvalidDataShowAsValuecolor`
fill : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsfill`, :class:`ScaleInvalidDataShowAsValuefill`
fillOpacity : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsfillOpacity`, :class:`ScaleInvalidDataShowAsValuefillOpacity`
opacity : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsopacity`, :class:`ScaleInvalidDataShowAsValueopacity`
radius : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsradius`, :class:`ScaleInvalidDataShowAsValueradius`
shape : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsshape`, :class:`ScaleInvalidDataShowAsValueshape`
size : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAssize`, :class:`ScaleInvalidDataShowAsValuesize`
stroke : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsstroke`, :class:`ScaleInvalidDataShowAsValuestroke`
strokeDash : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsstrokeDash`, :class:`ScaleInvalidDataShowAsValuestrokeDash`
strokeOpacity : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsstrokeOpacity`, :class:`ScaleInvalidDataShowAsValuestrokeOpacity`
strokeWidth : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsstrokeWidth`, :class:`ScaleInvalidDataShowAsValuestrokeWidth`
theta : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAstheta`, :class:`ScaleInvalidDataShowAsValuetheta`
time : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAstime`, :class:`ScaleInvalidDataShowAsValuetime`
x : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsx`, :class:`ScaleInvalidDataShowAsValuex`
xOffset : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsxOffset`, :class:`ScaleInvalidDataShowAsValuexOffset`
y : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsy`, :class:`ScaleInvalidDataShowAsValuey`
yOffset : dict, Literal['zero-or-min'], :class:`ScaleInvalidDataShowAsyOffset`, :class:`ScaleInvalidDataShowAsValueyOffset`
"""
_schema = {"$ref": "#/definitions/ScaleInvalidDataConfig"}
def __init__(
self,
angle: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
color: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
fill: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
fillOpacity: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
opacity: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
radius: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
shape: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
size: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
stroke: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
strokeDash: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
strokeOpacity: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
strokeWidth: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
theta: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
time: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
x: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
xOffset: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
y: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
yOffset: Optional[SchemaBase | Literal["zero-or-min"] | Map] = Undefined,
**kwds,
):
super().__init__(
angle=angle,
color=color,
fill=fill,
fillOpacity=fillOpacity,
opacity=opacity,
radius=radius,
shape=shape,
size=size,
stroke=stroke,
strokeDash=strokeDash,
strokeOpacity=strokeOpacity,
strokeWidth=strokeWidth,
theta=theta,
time=time,
x=x,
xOffset=xOffset,
y=y,
yOffset=yOffset,
**kwds,
)
| ScaleInvalidDataConfig |
python | wandb__wandb | wandb/sdk/lib/exit_hooks.py | {
"start": 207,
"end": 1540
} | class ____:
exception: Optional[BaseException] = None
def __init__(self) -> None:
self.exit_code = 0
self.exception = None
def hook(self) -> None:
self._orig_exit = sys.exit
sys.exit = self.exit
self._orig_excepthook = (
sys.excepthook
if sys.excepthook
!= sys.__excepthook__ # respect hooks by other libraries like pdb
else None
)
sys.excepthook = self.exc_handler # type: ignore
def exit(self, code: object = 0) -> "NoReturn":
orig_code = code
code = code if code is not None else 0
code = code if isinstance(code, int) else 1
self.exit_code = code
self._orig_exit(orig_code) # type: ignore
def was_ctrl_c(self) -> bool:
return isinstance(self.exception, KeyboardInterrupt)
def exc_handler(
self, exc_type: Type[BaseException], exc: BaseException, tb: TracebackType
) -> None:
self.exit_code = 1
self.exception = exc
if issubclass(exc_type, Error):
wandb.termerror(str(exc), repeat=False)
if self.was_ctrl_c():
self.exit_code = 255
traceback.print_exception(exc_type, exc, tb)
if self._orig_excepthook:
self._orig_excepthook(exc_type, exc, tb)
| ExitHooks |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 46161,
"end": 47018
} | class ____(BaseAPIIntegrationTest):
def test_remove(self):
container = self.client.create_container(TEST_IMG, ['true'])
id = container['Id']
self.client.start(id)
self.client.wait(id)
self.client.remove_container(id)
containers = self.client.containers(all=True)
res = [x for x in containers if 'Id' in x and x['Id'].startswith(id)]
assert len(res) == 0
def test_remove_with_dict_instead_of_id(self):
container = self.client.create_container(TEST_IMG, ['true'])
id = container['Id']
self.client.start(id)
self.client.wait(id)
self.client.remove_container(container)
containers = self.client.containers(all=True)
res = [x for x in containers if 'Id' in x and x['Id'].startswith(id)]
assert len(res) == 0
| RemoveContainerTest |
python | streamlit__streamlit | lib/streamlit/runtime/session_manager.py | {
"start": 1652,
"end": 2123
} | class ____:
"""Type containing data related to an active session.
This type is nearly identical to SessionInfo. The difference is that when using it,
we are guaranteed that SessionClient is not None.
"""
client: SessionClient
session: AppSession
# The number of times the script has been run for this session.
# At the moment, this is only used for testing and debugging purposes.
script_run_count: int = 0
@dataclass
| ActiveSessionInfo |
python | RaRe-Technologies__gensim | gensim/examples/dmlcz/dmlcorpus.py | {
"start": 2266,
"end": 8459
} | class ____(interfaces.CorpusABC):
"""
DmlCorpus implements a collection of articles. It is initialized via a DmlConfig
object, which holds information about where to look for the articles and how
to process them.
Apart from being a regular corpus (bag-of-words iterable with a `len()` method),
DmlCorpus has methods for building a dictionary (mapping between words and
their ids).
"""
def __init__(self):
self.documents = []
self.config = None
self.dictionary = dictionary.Dictionary()
def __len__(self):
return len(self.documents)
def __iter__(self):
"""
The function that defines a corpus -- iterating over the corpus yields
bag-of-words vectors, one for each document.
A bag-of-words vector is simply a list of ``(tokenId, tokenCount)`` 2-tuples.
"""
for docNo, (sourceId, docUri) in enumerate(self.documents):
source = self.config.sources[sourceId]
contents = source.getContent(docUri)
words = [source.normalizeWord(word) for word in source.tokenize(contents)]
yield self.dictionary.doc2bow(words, allowUpdate=False)
def buildDictionary(self):
"""
Populate dictionary mapping and statistics.
This is done by sequentially retrieving the article fulltexts, splitting
them into tokens and converting tokens to their ids (creating new ids as
necessary).
"""
logger.info("creating dictionary from %i articles", len(self.documents))
self.dictionary = dictionary.Dictionary()
numPositions = 0
for docNo, (sourceId, docUri) in enumerate(self.documents):
if docNo % 1000 == 0:
logger.info("PROGRESS: at document #%i/%i (%s, %s)", docNo, len(self.documents), sourceId, docUri)
source = self.config.sources[sourceId]
contents = source.getContent(docUri)
words = [source.normalizeWord(word) for word in source.tokenize(contents)]
numPositions += len(words)
# convert to bag-of-words, but ignore the result -- here we only care about updating token ids
_ = self.dictionary.doc2bow(words, allowUpdate=True) # noqa:F841
logger.info(
"built %s from %i documents (total %i corpus positions)",
self.dictionary, len(self.documents), numPositions
)
def processConfig(self, config, shuffle=False):
"""
Parse the directories specified in the config, looking for suitable articles.
This updates the self.documents var, which keeps a list of (source id,
article uri) 2-tuples. Each tuple is a unique identifier of one article.
Note that some articles are ignored based on config settings (for example
if the article's language doesn't match any language specified in the
config etc.).
"""
self.config = config
self.documents = []
logger.info("processing config %s", config)
for sourceId, source in config.sources.iteritems():
logger.info("processing source '%s'", sourceId)
accepted = []
for articleUri in source.findArticles():
meta = source.getMeta(articleUri) # retrieve metadata (= dictionary of key->value)
if config.acceptArticle(meta): # do additional filtering on articles, based on the article's metadata
accepted.append((sourceId, articleUri))
logger.info("accepted %i articles for source '%s'", len(accepted), sourceId)
self.documents.extend(accepted)
if not self.documents:
logger.warning('no articles at all found from the config; something went wrong!')
if shuffle:
logger.info("shuffling %i documents for random order", len(self.documents))
import random
random.shuffle(self.documents)
logger.info("accepted total of %i articles for %s", len(self.documents), str(config))
def saveDictionary(self, fname):
logger.info("saving dictionary mapping to %s", fname)
fout = open(fname, 'w')
for tokenId, token in self.dictionary.id2token.iteritems():
fout.write("%i\t%s\n" % (tokenId, token))
fout.close()
@staticmethod
def loadDictionary(fname):
result = {}
for lineNo, line in enumerate(open(fname)):
pair = line[:-1].split('\t')
if len(pair) != 2:
continue
wordId, word = pair
result[int(wordId)] = word
return result
def saveDocuments(self, fname):
logger.info("saving documents mapping to %s", fname)
fout = open(fname, 'w')
for docNo, docId in enumerate(self.documents):
sourceId, docUri = docId
intId, pathId = docUri
fout.write("%i\t%s\n" % (docNo, repr(docId)))
fout.close()
def saveAsText(self):
"""
Store the corpus to disk, in a human-readable text format.
This actually saves multiple files:
1. Pure document-term co-occurence frequency counts, as a Matrix Market file.
2. Token to integer mapping, as a text file.
3. Document to document URI mapping, as a text file.
The exact filesystem paths and filenames are determined from the config.
"""
self.saveDictionary(self.config.resultFile('wordids.txt'))
self.saveDocuments(self.config.resultFile('docids.txt'))
matutils.MmWriter.writeCorpus(self.config.resultFile('bow.mm'), self)
def articleDir(self, docNo):
"""
Return absolute normalized path on filesystem to article no. `docNo`.
"""
sourceId, (_, outPath) = self.documents[docNo]
source = self.config.sources[sourceId]
return os.path.join(source.baseDir, outPath)
def getMeta(self, docNo):
"""
Return metadata for article no. `docNo`.
"""
sourceId, uri = self.documents[docNo]
source = self.config.sources[sourceId]
return source.getMeta(uri)
# endclass DmlCorpus
| DmlCorpus |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/78_class_body_cond.py | {
"start": 0,
"end": 55
} | class ____:
if a:
pass
else:
pass
| C |
python | django__django | tests/gis_tests/geoapp/feeds.py | {
"start": 65,
"end": 341
} | class ____(feeds.Feed):
link = "/city/"
title = "Test GeoDjango Cities"
def items(self):
return City.objects.all()
def item_link(self, item):
return "/city/%s/" % item.pk
def item_geometry(self, item):
return item.point
| TestGeoRSS1 |
python | ray-project__ray | python/ray/_common/test_utils.py | {
"start": 689,
"end": 1429
} | class ____:
"""A Ray actor for coordinating test execution through signals.
Useful for testing async coordination, waiting for specific states,
and synchronizing multiple actors or tasks in tests.
"""
def __init__(self):
self.ready_event = asyncio.Event()
self.num_waiters = 0
def send(self, clear: bool = False):
self.ready_event.set()
if clear:
self.ready_event.clear()
async def wait(self, should_wait: bool = True):
if should_wait:
self.num_waiters += 1
await self.ready_event.wait()
self.num_waiters -= 1
async def cur_num_waiters(self) -> int:
return self.num_waiters
@ray.remote(num_cpus=0)
| SignalActor |
python | PrefectHQ__prefect | src/prefect/server/schemas/core.py | {
"start": 31674,
"end": 31902
} | class ____(ORMBaseModel):
"""An ORM representation of account info."""
key: str = Field(default=..., description="Account info key")
value: Dict[str, Any] = Field(default=..., description="Account info")
| Configuration |
python | python__mypy | mypyc/codegen/emit.py | {
"start": 2719,
"end": 3944
} | class ____:
"""Shared emitter state for a compilation group."""
def __init__(
self,
names: NameGenerator,
group_name: str | None = None,
group_map: dict[str, str | None] | None = None,
) -> None:
"""Setup shared emitter state.
Args:
names: The name generator to use
group_map: Map from module names to group name
group_name: Current group name
"""
self.temp_counter = 0
self.names = names
self.group_name = group_name
self.group_map = group_map or {}
# Groups that this group depends on
self.group_deps: set[str] = set()
# The map below is used for generating declarations and
# definitions at the top of the C file. The main idea is that they can
# be generated at any time during the emit phase.
# A map of a C identifier to whatever the C identifier declares. Currently this is
# used for declaring structs and the key corresponds to the name of the struct.
# The declaration contains the body of the struct.
self.declarations: dict[str, HeaderDeclaration] = {}
self.literals = Literals()
| EmitterContext |
python | spyder-ide__spyder | spyder/widgets/printer.py | {
"start": 510,
"end": 1537
} | class ____(QPrinter):
def __init__(
self, mode=QPrinter.PrinterMode.ScreenResolution, header_font=None
):
QPrinter.__init__(self, mode)
self.setColorMode(QPrinter.ColorMode.Color)
self.setPageOrder(QPrinter.PageOrder.FirstPageFirst)
self.date = time.ctime()
if header_font is not None:
self.header_font = header_font
# <!> The following method is simply ignored by QPlainTextEdit
# (this is a copy from QsciEditor's Printer)
def formatPage(self, painter, drawing, area, pagenr):
header = '%s - %s - Page %s' % (self.docName(), self.date, pagenr)
painter.save()
painter.setFont(self.header_font)
painter.setPen(QColor(Qt.black))
if drawing:
painter.drawText(area.right()-painter.fontMetrics().width(header),
area.top()+painter.fontMetrics().ascent(), header)
area.setTop(area.top()+painter.fontMetrics().height()+5)
painter.restore()
| SpyderPrinter |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 19436,
"end": 19927
} | class ____(Task):
spec: ShuffleSpec
__slots__ = tuple(__annotations__)
def __init__(
self,
key: Any,
func: Callable[..., Any],
/,
*args: Any,
spec: ShuffleSpec,
**kwargs: Any,
):
self.spec = spec
super().__init__(key, func, *args, **kwargs)
def __repr__(self) -> str:
return f"P2PBarrierTask({self.key!r})"
@property
def block_fusion(self) -> bool:
return True
| P2PBarrierTask |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/test_base_data_condition.py | {
"start": 399,
"end": 697
} | class ____(DataConditionHandler[dict[str, str]]):
comparison_json_schema = {"type": "number"}
condition_result_schema = {"type": "boolean"}
@mock.patch(
"sentry.workflow_engine.registry.condition_handler_registry.get",
return_value=MockDataConditionHandler,
)
| MockDataConditionHandler |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 469,
"end": 709
} | class ____(JoseError):
error = "invalid_header_parameter_name"
def __init__(self, name):
description = f"Invalid Header Parameter Name: {name}"
super().__init__(description=description)
| InvalidHeaderParameterNameError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/operator1.py | {
"start": 1909,
"end": 2037
} | class ____:
def __add__(self, other: int) -> Self:
return self
def method1(self) -> Self:
return self + 0
| G |
python | FactoryBoy__factory_boy | examples/django_demo/generic_foreignkey/apps.py | {
"start": 36,
"end": 110
} | class ____(AppConfig):
name = 'generic_foreignkey'
| GenericForeignKeyConfig |
python | graphql-python__graphene | graphene/types/definitions.py | {
"start": 659,
"end": 742
} | class ____(GrapheneGraphQLType, GraphQLInterfaceType):
pass
| GrapheneInterfaceType |
python | realpython__materials | qt-designer-python/sample_editor/main_window_ui.py | {
"start": 342,
"end": 9117
} | class ____(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(413, 299)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(1, 1, 1, 1)
self.verticalLayout.setObjectName("verticalLayout")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 413, 20))
self.menubar.setObjectName("menubar")
self.menu_File = QtWidgets.QMenu(self.menubar)
self.menu_File.setObjectName("menu_File")
self.menuOpen_Recent = QtWidgets.QMenu(self.menu_File)
self.menuOpen_Recent.setObjectName("menuOpen_Recent")
self.menu_Edit = QtWidgets.QMenu(self.menubar)
self.menu_Edit.setObjectName("menu_Edit")
self.menu_Help = QtWidgets.QMenu(self.menubar)
self.menu_Help.setObjectName("menu_Help")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.action_New = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon()
icon.addPixmap(
QtGui.QPixmap("ui/resources/file-new.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_New.setIcon(icon)
self.action_New.setObjectName("action_New")
self.action_Open = QtWidgets.QAction(MainWindow)
icon1 = QtGui.QIcon()
icon1.addPixmap(
QtGui.QPixmap("ui/resources/file-open.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Open.setIcon(icon1)
self.action_Open.setObjectName("action_Open")
self.action_Save = QtWidgets.QAction(MainWindow)
icon2 = QtGui.QIcon()
icon2.addPixmap(
QtGui.QPixmap("ui/resources/file-save.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Save.setIcon(icon2)
self.action_Save.setObjectName("action_Save")
self.action_Exit = QtWidgets.QAction(MainWindow)
icon3 = QtGui.QIcon()
icon3.addPixmap(
QtGui.QPixmap("ui/resources/file-exit.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Exit.setIcon(icon3)
self.action_Exit.setObjectName("action_Exit")
self.action_Copy = QtWidgets.QAction(MainWindow)
icon4 = QtGui.QIcon()
icon4.addPixmap(
QtGui.QPixmap("ui/resources/edit-copy.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Copy.setIcon(icon4)
self.action_Copy.setObjectName("action_Copy")
self.action_Paste = QtWidgets.QAction(MainWindow)
icon5 = QtGui.QIcon()
icon5.addPixmap(
QtGui.QPixmap("ui/resources/edit-paste.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Paste.setIcon(icon5)
self.action_Paste.setObjectName("action_Paste")
self.action_Cut = QtWidgets.QAction(MainWindow)
icon6 = QtGui.QIcon()
icon6.addPixmap(
QtGui.QPixmap("ui/resources/edit-cut.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_Cut.setIcon(icon6)
self.action_Cut.setObjectName("action_Cut")
self.actionOpen_All = QtWidgets.QAction(MainWindow)
self.actionOpen_All.setObjectName("actionOpen_All")
self.action_About = QtWidgets.QAction(MainWindow)
icon7 = QtGui.QIcon()
icon7.addPixmap(
QtGui.QPixmap("ui/resources/help-content.png"),
QtGui.QIcon.Normal,
QtGui.QIcon.Off,
)
self.action_About.setIcon(icon7)
self.action_About.setObjectName("action_About")
self.action_Find_Replace = QtWidgets.QAction(MainWindow)
self.action_Find_Replace.setObjectName("action_Find_Replace")
self.menuOpen_Recent.addAction(self.actionOpen_All)
self.menu_File.addAction(self.action_New)
self.menu_File.addSeparator()
self.menu_File.addAction(self.action_Open)
self.menu_File.addAction(self.menuOpen_Recent.menuAction())
self.menu_File.addSeparator()
self.menu_File.addAction(self.action_Save)
self.menu_File.addSeparator()
self.menu_File.addAction(self.action_Exit)
self.menu_Edit.addAction(self.action_Copy)
self.menu_Edit.addAction(self.action_Paste)
self.menu_Edit.addAction(self.action_Cut)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_Find_Replace)
self.menu_Help.addAction(self.action_About)
self.menubar.addAction(self.menu_File.menuAction())
self.menubar.addAction(self.menu_Edit.menuAction())
self.menubar.addAction(self.menu_Help.menuAction())
self.toolBar.addAction(self.action_New)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_Open)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_Save)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_Copy)
self.toolBar.addAction(self.action_Paste)
self.toolBar.addAction(self.action_Cut)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_About)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Sample Editor"))
self.menu_File.setTitle(_translate("MainWindow", "&File"))
self.menuOpen_Recent.setTitle(_translate("MainWindow", "Open &Recent"))
self.menu_Edit.setTitle(_translate("MainWindow", "&Edit"))
self.menu_Help.setTitle(_translate("MainWindow", "&Help"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.action_New.setText(_translate("MainWindow", "&New..."))
self.action_New.setToolTip(
_translate("MainWindow", "Create a New Document")
)
self.action_New.setShortcut(_translate("MainWindow", "Ctrl+N"))
self.action_Open.setText(_translate("MainWindow", "&Open..."))
self.action_Open.setToolTip(
_translate("MainWindow", "Open a Document")
)
self.action_Open.setShortcut(_translate("MainWindow", "Ctrl+O"))
self.action_Save.setText(_translate("MainWindow", "&Save"))
self.action_Save.setToolTip(
_translate("MainWindow", "Save the Current Document")
)
self.action_Save.setShortcut(_translate("MainWindow", "Ctrl+S"))
self.action_Exit.setText(_translate("MainWindow", "&Exit"))
self.action_Copy.setText(_translate("MainWindow", "&Copy"))
self.action_Copy.setToolTip(
_translate("MainWindow", "Copy Slected Text")
)
self.action_Copy.setShortcut(_translate("MainWindow", "Ctrl+C"))
self.action_Paste.setText(_translate("MainWindow", "&Paste"))
self.action_Paste.setToolTip(
_translate("MainWindow", "Paste Copied Text")
)
self.action_Paste.setShortcut(_translate("MainWindow", "Ctrl+V"))
self.action_Cut.setText(_translate("MainWindow", "C&ut"))
self.action_Cut.setToolTip(
_translate("MainWindow", "Cut Selected Text")
)
self.action_Cut.setShortcut(_translate("MainWindow", "Ctrl+X"))
self.actionOpen_All.setText(_translate("MainWindow", "Open All"))
self.actionOpen_All.setToolTip(
_translate("MainWindow", "Open All Recent Documents")
)
self.action_About.setText(_translate("MainWindow", "&About..."))
self.action_Find_Replace.setText(
_translate("MainWindow", "&Find and Replace...")
)
self.action_Find_Replace.setToolTip(
_translate("MainWindow", "Launch Find and Replace Dialog")
)
self.action_Find_Replace.setShortcut(
_translate("MainWindow", "Ctrl+F")
)
| Ui_MainWindow |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 63652,
"end": 64761
} | class ____(WebTestCase):
def get_handlers(self):
return []
def get_app_kwargs(self):
return {"default_host": "www.example.com"}
def test_default_host_matching(self):
self.app.add_handlers(
"www.example.com", [("/foo", HostMatchingTest.Handler, {"reply": "[0]"})]
)
self.app.add_handlers(
r"www\.example\.com", [("/bar", HostMatchingTest.Handler, {"reply": "[1]"})]
)
self.app.add_handlers(
"www.test.com", [("/baz", HostMatchingTest.Handler, {"reply": "[2]"})]
)
response = self.fetch("/foo")
self.assertEqual(response.body, b"[0]")
response = self.fetch("/bar")
self.assertEqual(response.body, b"[1]")
response = self.fetch("/baz")
self.assertEqual(response.code, 404)
response = self.fetch("/foo", headers={"X-Real-Ip": "127.0.0.1"})
self.assertEqual(response.code, 404)
self.app.default_host = "www.test.com"
response = self.fetch("/baz")
self.assertEqual(response.body, b"[2]")
| DefaultHostMatchingTest |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/nan_to_num_test.py | {
"start": 764,
"end": 1744
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, dtype, replace_inf, op_func):
input = torch.randn(M, N, dtype=dtype)
input[0][0] = float("nan")
self.inputs = {"input": input, "replace_inf": replace_inf}
self.op_func = op_func
self.set_module_name("nan_to_num")
# To make casename unique as nan_to_num and nan_to_num_ are two different functions.
if op_func is torch.nan_to_num_:
self.set_module_name("nan_to_num_")
def forward(self, input, replace_inf: bool):
# compare inplace
if replace_inf:
return self.op_func(input, nan=1.0)
else:
return self.op_func(input, nan=1.0, posinf=math.inf, neginf=-math.inf)
op_bench.generate_pt_tests_from_op_list(
nan_to_num_ops_list,
nan_to_num_long_configs + nan_to_num_short_configs,
ReplaceNaNBenchmark,
)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
| ReplaceNaNBenchmark |
python | ray-project__ray | python/ray/tests/test_client_reconnect.py | {
"start": 7642,
"end": 19423
} | class ____:
"""
Helper class that wraps the RPC server that middlemans the connection
between the client and the real ray server. Useful for injecting
errors between a client and server pair.
"""
def __init__(
self,
listen_addr: str,
real_addr,
on_log_response: Optional[Hook] = None,
on_data_request: Optional[Hook] = None,
on_data_response: Optional[Hook] = None,
on_task_request: Optional[Hook] = None,
on_task_response: Optional[Hook] = None,
):
"""
Args:
listen_addr: The address the middleman server will listen on
real_addr: The address of the real ray server
on_log_response: Optional hook to inject errors before sending back
a log response
on_data_response: Optional hook to inject errors before sending
back a data response
on_task_request: Optional hook to inject errors before forwarding
a raylet driver request
on_task_response: Optional hook to inject errors before sending
back a raylet driver response
"""
self.listen_addr = listen_addr
self.real_addr = real_addr
self.server = grpc.server(
futures.ThreadPoolExecutor(max_workers=CLIENT_SERVER_MAX_THREADS),
options=GRPC_OPTIONS,
)
self.task_servicer = MiddlemanRayletServicer(
on_response=on_task_response, on_request=on_task_request
)
self.data_servicer = MiddlemanDataServicer(
on_response=on_data_response, on_request=on_data_request
)
self.logs_servicer = MiddlemanLogServicer(on_response=on_log_response)
ray_client_pb2_grpc.add_RayletDriverServicer_to_server(
self.task_servicer, self.server
)
ray_client_pb2_grpc.add_RayletDataStreamerServicer_to_server(
self.data_servicer, self.server
)
ray_client_pb2_grpc.add_RayletLogStreamerServicer_to_server(
self.logs_servicer, self.server
)
self.server.add_insecure_port(self.listen_addr)
self.channel = None
self.reset_channel()
def reset_channel(self) -> None:
"""
Manually close and reopen the channel to the real ray server. This
simulates a disconnection between the client and the server.
"""
if self.channel:
self.channel.close()
self.channel = grpc.insecure_channel(self.real_addr, options=GRPC_OPTIONS)
grpc.channel_ready_future(self.channel)
self.task_servicer.set_channel(self.channel)
self.data_servicer.set_channel(self.channel)
self.logs_servicer.set_channel(self.channel)
def start(self) -> None:
self.server.start()
def stop(self, grace: int) -> None:
self.server.stop(grace)
@contextlib.contextmanager
def start_middleman_server(
on_log_response=None,
on_data_request=None,
on_data_response=None,
on_task_request=None,
on_task_response=None,
):
"""
Helper context that starts a middleman server listening on port 10011,
and a ray client server on port 50051.
"""
ray._inside_client_test = True
middleman = None
try:
middleman = MiddlemanServer(
listen_addr="localhost:10011",
real_addr="localhost:50051",
on_log_response=on_log_response,
on_data_request=on_data_request,
on_data_response=on_data_response,
on_task_request=on_task_request,
on_task_response=on_task_response,
)
middleman.start()
ray.init("ray://localhost:10011")
yield middleman
finally:
ray._inside_client_test = False
ray.util.disconnect()
if middleman:
middleman.stop(0)
def test_disconnect_during_get(call_ray_start_shared):
"""
Disconnect the proxy and the client in the middle of a long running get
"""
@ray.remote
def slow_result():
time.sleep(20)
return 12345
def disconnect(middleman):
time.sleep(3)
middleman.reset_channel()
with start_middleman_server() as middleman:
disconnect_thread = threading.Thread(target=disconnect, args=(middleman,))
disconnect_thread.start()
result = ray.get(slow_result.remote())
assert result == 12345
disconnect_thread.join()
def test_disconnects_during_large_get(call_ray_start_shared):
"""
Disconnect repeatedly during a large (multi-chunk) get.
"""
i = 0
started = False
def fail_every_three(_):
# Inject an error every third time this method is called
nonlocal i, started
if not started:
return
i += 1
if i % 3 == 0:
raise RuntimeError
@ray.remote
def large_result():
# 1024x1024x6 float64 matrix (96 MiB). With 5MiB chunk size,
# it will take at least 16 chunks to transfer this object. Since
# the failure is injected every 3 chunks, this transfer can only
# work if the chunked get request retries at the last received chunk
# (instead of starting from the beginning each retry)
return np.random.random((1024, 1024, 6))
with start_middleman_server(on_task_response=fail_every_three):
started = True
result = ray.get(large_result.remote())
assert result.shape == (1024, 1024, 6)
def test_disconnects_during_large_async_get(call_ray_start_shared):
"""
Disconnect repeatedly during a large (multi-chunk) async get.
"""
i = 0
started = False
def fail_every_three(_):
# Inject an error every third time this method is called
nonlocal i, started
if not started:
return
i += 1
if i % 3 == 0:
raise RuntimeError
@ray.remote
def large_result():
# 1024x1024x6 float64 matrix (96 MiB). With 5MiB chunk size,
# it will take at least 16 chunks to transfer this object. Since
# the failure is injected every 3 chunks, this transfer can only
# work if the chunked get request retries at the last received chunk
# (instead of starting from the beginning each retry)
return np.random.random((1024, 1024, 6))
with start_middleman_server(on_data_response=fail_every_three):
started = True
async def get_large_result():
return await large_result.remote()
result = get_or_create_event_loop().run_until_complete(get_large_result())
assert result.shape == (1024, 1024, 6)
def test_disconnect_during_large_put(call_ray_start_shared):
"""
Disconnect during a large (multi-chunk) put.
"""
i = 0
started = False
def fail_halfway(_):
# Inject an error halfway through the object transfer
nonlocal i, started
if not started:
return
i += 1
if i == 8:
raise RuntimeError
with start_middleman_server(on_data_request=fail_halfway):
started = True
objref = ray.put(np.random.random((1024, 1024, 6)))
assert i > 8 # Check that the failure was injected
result = ray.get(objref)
assert result.shape == (1024, 1024, 6)
def test_disconnect_during_large_schedule(call_ray_start_shared):
"""
Disconnect during a remote call with a large (multi-chunk) argument.
"""
i = 0
started = False
def fail_halfway(_):
# Inject an error halfway through the object transfer
nonlocal i, started
if not started:
return
i += 1
if i == 8:
raise RuntimeError
@ray.remote
def f(a):
return a.shape
with start_middleman_server(on_data_request=fail_halfway):
started = True
a = np.random.random((1024, 1024, 6))
result = ray.get(f.remote(a))
assert i > 8 # Check that the failure was injected
assert result == (1024, 1024, 6)
def test_valid_actor_state(call_ray_start_shared):
"""
Repeatedly inject errors in the middle of mutating actor calls. Check
at the end that the final state of the actor is consistent with what
we would expect had the disconnects not occurred.
"""
@ray.remote
class IncrActor:
def __init__(self):
self.val = 0
def incr(self):
self.val += 1
return self.val
i = 0
# This is to prevent erroring in the initial connection logic.
started = False
def fail_every_seven(_):
# Inject an error every seventh time this method is called
nonlocal i, started
i += 1
if i % 7 == 0 and started:
raise RuntimeError
with start_middleman_server(
on_data_response=fail_every_seven,
on_task_request=fail_every_seven,
on_task_response=fail_every_seven,
):
started = True
actor = IncrActor.remote()
for _ in range(100):
ref = actor.incr.remote()
assert ray.get(ref) == 100
def test_valid_actor_state_2(call_ray_start_shared):
"""
Do a full disconnect (cancel channel) every 11 requests. Failure
happens:
- before request sent: request never reaches server
- before response received: response never reaches server
- while get's are being processed
"""
@ray.remote
class IncrActor:
def __init__(self):
self.val = 0
def incr(self):
self.val += 1
return self.val
i = 0
with start_middleman_server() as middleman:
def fail_every_eleven(_):
nonlocal i
i += 1
if i % 11 == 0:
middleman.reset_channel()
middleman.data_servicer.on_response = fail_every_eleven
middleman.task_servicer.on_request = fail_every_eleven
middleman.task_servicer.on_response = fail_every_eleven
actor = IncrActor.remote()
for _ in range(100):
ref = actor.incr.remote()
assert ray.get(ref) == 100
def test_noisy_puts(call_ray_start_shared):
"""
Randomly kills the data channel with 10% chance when receiving response
(requests made it to server, responses dropped) and checks that final
result is still consistent
"""
random.seed(12345)
with start_middleman_server() as middleman:
def fail_randomly(response: ray_client_pb2.DataResponse):
if random.random() < 0.1:
raise RuntimeError
middleman.data_servicer.on_response = fail_randomly
refs = [ray.put(i * 123) for i in range(500)]
results = ray.get(refs)
for i, result in enumerate(results):
assert result == i * 123
def test_client_reconnect_grace_period(call_ray_start_shared):
"""
Tests that the client gives up attempting to reconnect the channel
after the grace period expires.
"""
# Lower grace period to 5 seconds to save time
with patch.dict(
os.environ, {"RAY_CLIENT_RECONNECT_GRACE_PERIOD": "5"}
), start_middleman_server() as middleman:
assert ray.get(ray.put(42)) == 42
# Close channel
middleman.channel.close()
start_time = time.time()
with pytest.raises(ConnectionError):
ray.get(ray.put(42))
# Connection error should have been raised within a reasonable
# amount of time. Set to significantly higher than 5 seconds
# to account for reconnect backoff timing
assert time.time() - start_time < 20
if __name__ == "__main__":
sys.exit(pytest.main(["-sv", __file__]))
| MiddlemanServer |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-oxylabs/llama_index/readers/oxylabs/google_base.py | {
"start": 522,
"end": 13528
} | class ____(OxylabsBaseReader):
parsing_recursion_depth: int = 5
image_binary_content_attributes: list[str] = ["image_data", "data"]
excluded_result_attributes: list[str] = ["pos_overall"]
image_binary_content_array_attribute: str = "images"
binary_content_replacement: str = "Redacted base64 image string..."
include_binary_image_data: bool = False
def __init__(self, username: str, password: str, **data) -> None:
super().__init__(username=username, password=password, **data)
def _get_document_from_response(
self, response: list[dict] | list[list[dict]]
) -> Document:
processed_content = self._process_responses(response)
return Document(text=processed_content)
def get_response(self, payload: dict) -> Response:
raise NotImplementedError(
"Not implemented in the base class! Use one the child classes instead!"
)
async def aget_response(self, payload: dict) -> Response:
raise NotImplementedError(
"Not implemented in the base class! Use one the child classes instead!"
)
@staticmethod
def validate_response_categories(result_categories: list) -> list:
validated_categories = []
for result_category in result_categories:
if result_category in RESULT_CATEGORIES:
validated_categories.append(result_category)
return validated_categories
def _process_responses(self, res: list[dict], **kwargs: Any) -> str:
result_ = "No good search result found"
result_category_processing_map = {
"knowledge_graph": self._create_knowledge_graph_snippets,
"combined_search_result": self._create_combined_search_result_snippets,
"product_information": self._create_product_information_snippets,
"local_information": self._create_local_information_snippets,
"search_information": self._create_search_information_snippets,
}
snippets: list[str] = []
validated_categories = self.validate_response_categories(
kwargs.get("result_categories", [])
)
result_categories_ = validated_categories or []
for validated_response in res:
if result_categories_:
for result_category in result_categories_:
result_category_processing_map[result_category](
validated_response, snippets
)
else:
for result_category in result_category_processing_map:
result_category_processing_map[result_category](
validated_response, snippets
)
if snippets:
result_ = "\n\n".join(snippets)
return result_
def _process_tags(
self, snippets_: list, tags_: list, results: dict, group_name: str = ""
) -> None:
check_tags = [tag_[0] in results for tag_ in tags_]
if any(check_tags):
for tag in tags_:
tag_content = results.get(tag[0], {}) or {}
if tag_content:
collected_snippets = self._recursive_snippet_collector(
tag_content,
max_depth=self.parsing_recursion_depth,
current_depth=0,
parent_=ResponseElement(
path_=f"{group_name}-{tag[0]}",
tag=tag[0],
display_tag=tag[1],
python_type=str(type(tag_content)),
parent=None,
),
)
if collected_snippets:
snippets_.append(collected_snippets)
def _recursive_snippet_collector(
self,
target_structure: Any,
max_depth: int,
current_depth: int,
parent_: ResponseElement,
) -> str:
target_snippets: list[str] = []
padding_multiplier = current_depth + 1
recursion_padding = " " * padding_multiplier
if current_depth >= max_depth:
return "\n".join(target_snippets)
if isinstance(target_structure, (str, float, int)):
self._recursion_process_simple_types(
parent_, recursion_padding, target_snippets, target_structure
)
elif isinstance(target_structure, dict):
self.recursion_process_dict(
current_depth,
max_depth,
parent_,
recursion_padding,
target_snippets,
target_structure,
)
elif isinstance(target_structure, (list, tuple)):
self.recursion_process_array(
current_depth,
max_depth,
parent_,
recursion_padding,
target_snippets,
target_structure,
)
return "\n".join(target_snippets)
def recursion_process_array(
self,
current_depth: int,
max_depth: int,
parent_: ResponseElement,
recursion_padding: str,
target_snippets: list,
target_structure: Any,
) -> None:
if target_structure:
target_snippets.append(
f"{recursion_padding}{parent_.display_tag.upper()} ITEMS: "
)
for nr_, element_ in enumerate(target_structure):
target_snippets.append(
self._recursive_snippet_collector(
element_,
max_depth=max_depth,
current_depth=current_depth + 1,
parent_=ResponseElement(
path_=f"{parent_.path_.upper()}-ITEM-{nr_ + 1}",
tag=parent_.tag.upper(),
display_tag=f"{parent_.tag.upper()}-ITEM-{nr_ + 1}",
python_type=str(type(target_structure)),
parent=parent_,
),
)
)
def recursion_process_dict(
self,
current_depth: int,
max_depth: int,
parent_: ResponseElement,
recursion_padding: str,
target_snippets: list,
target_structure: Any,
) -> None:
if not target_structure:
return
target_snippets.append(f"{recursion_padding}{parent_.display_tag.upper()}: ")
for key_, value_ in target_structure.items():
if isinstance(value_, dict) and value_:
target_snippets.append(f"{recursion_padding}{key_.upper()}: ")
target_snippets.append(
self._recursive_snippet_collector(
value_,
max_depth=max_depth,
current_depth=current_depth + 1,
parent_=ResponseElement(
path_=f"{parent_.path_.upper()}-{key_.upper()}",
tag=key_.upper(),
display_tag=key_.upper(),
python_type=str(type(value_)),
parent=parent_,
),
)
)
elif isinstance(value_, (list, tuple)) and value_:
target_snippets.append(f"{recursion_padding}{key_.upper()} ITEMS: ")
for nr_, _element in enumerate(value_):
target_snippets.append(
self._recursive_snippet_collector(
_element,
max_depth=max_depth,
current_depth=current_depth + 1,
parent_=ResponseElement(
path_=f"{parent_.path_.upper()}"
f"-{key_.upper()}-ITEM-{nr_ + 1}",
tag=key_.upper(),
display_tag=f"{key_.upper()}-ITEM-{nr_ + 1}",
python_type=str(type(value_)),
parent=parent_,
),
)
)
elif isinstance(value_, (str, float, int)) and value_:
if (
key_ in self.image_binary_content_attributes
and not self.include_binary_image_data
):
value_ = self.binary_content_replacement
if key_ not in self.excluded_result_attributes:
target_snippets.append(
f"{recursion_padding}{key_.upper()}: {value_!s}"
)
def _recursion_process_simple_types(
self,
parent_: ResponseElement,
recursion_padding: str,
target_snippets: list,
target_structure: Any,
) -> None:
if not target_structure:
return
if parent_.python_type == str(type([])):
if (
self.image_binary_content_array_attribute.upper()
in parent_.path_.split("-")[-3:]
or parent_.tag.lower() in self.image_binary_content_attributes
) and not self.include_binary_image_data:
target_structure = self.binary_content_replacement
target_snippets.append(
f"{recursion_padding}{parent_.display_tag}: {target_structure!s}"
)
elif parent_.python_type == str(type({})):
if (
parent_.tag.lower() in self.image_binary_content_attributes
and not self.include_binary_image_data
):
target_structure = self.binary_content_replacement
if parent_.tag.lower() not in self.excluded_result_attributes:
target_snippets.append(
f"{recursion_padding}{parent_.display_tag}: {target_structure!s}"
)
def _create_knowledge_graph_snippets(
self, results: dict, knowledge_graph_snippets: list
) -> None:
knowledge_graph_tags = [
("knowledge", "Knowledge Graph"),
("recipes", "Recipes"),
("item_carousel", "Item Carousel"),
("apps", "Apps"),
]
self._process_tags(
knowledge_graph_snippets, knowledge_graph_tags, results, "Knowledge"
)
def _create_combined_search_result_snippets(
self, results: dict, combined_search_result_snippets: list
) -> None:
combined_search_result_tags = [
("organic", "Organic Results"),
("organic_videos", "Organic Videos"),
("paid", "Paid Results"),
("featured_snipped", "Feature Snipped"),
("top_stories", "Top Stories"),
("finance", "Finance"),
("sports_games", "Sports Games"),
("twitter", "Twitter"),
("discussions_and_forums", "Discussions and Forums"),
("images", "Images"),
("videos", "Videos"),
("video_box", "Video box"),
]
self._process_tags(
combined_search_result_snippets,
combined_search_result_tags,
results,
"Combined Search Results",
)
def _create_product_information_snippets(
self, results: dict, product_information_snippets: list
) -> None:
product_information_tags = [
("popular_products", "Popular Products"),
("pla", "Product Listing Ads (PLA)"),
]
self._process_tags(
product_information_snippets,
product_information_tags,
results,
"Product Information",
)
def _create_local_information_snippets(
self, results: dict, local_information_snippets: list
) -> None:
local_information_tags = [
("top_sights", "Top Sights"),
("flights", "Flights"),
("hotels", "Hotels"),
("local_pack", "Local Pack"),
("local_service_ads", "Local Service Ads"),
("jobs", "Jobs"),
]
self._process_tags(
local_information_snippets,
local_information_tags,
results,
"Local Information",
)
def _create_search_information_snippets(
self, results: dict, search_information_snippets: list
) -> None:
search_information_tags = [
("search_information", "Search Information"),
("related_searches", "Related Searches"),
("related_searches_categorized", "Related Searches Categorized"),
("related_questions", "Related Questions"),
]
self._process_tags(
search_information_snippets,
search_information_tags,
results,
"Search Information",
)
| OxylabsGoogleBaseReader |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3962,
"end": 4209
} | class ____(Protocol):
"""Base class for compiler parameters."""
BACKEND: ClassVar[Backend]
# Subclasses must be dataclasses.
__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
@dataclasses.dataclass(frozen=True)
| CompilerParams |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 12964,
"end": 13106
} | class ____(models.Model):
text = models.CharField(max_length=32)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
| Permission |
python | lazyprogrammer__machine_learning_examples | unsupervised_class3/vae_theano.py | {
"start": 792,
"end": 7743
} | class ____:
def __init__(self, D, hidden_layer_sizes):
# hidden_layer_sizes specifies the size of every layer
# in the encoder
# up to the final hidden layer Z
# the decoder will have the reverse shape
# represents a batch of training data
self.X = T.matrix('X')
# encoder
self.encoder_layers = []
M_in = D
for M_out in hidden_layer_sizes[:-1]:
h = DenseLayer(M_in, M_out)
self.encoder_layers.append(h)
M_in = M_out
# for convenience, we'll refer to the final encoder size as M
# also the input to the decoder size
M = hidden_layer_sizes[-1]
# the encoder's final layer output is unbounded
# so there is no activation function
# we also need 2 times as many units as specified by M_out
# since there needs to be M_out means + M_out variances
h = DenseLayer(M_in, 2 * M, f=lambda x: x)
self.encoder_layers.append(h)
# get the mean and variance / std dev of Z.
# note that the variance must be > 0
# we can get a sigma (standard dev) > 0 from an unbounded variable by
# passing it through the softplus function.
# add a small amount for smoothing.
current_layer_value = self.X
for layer in self.encoder_layers:
current_layer_value = layer.forward(current_layer_value)
self.means = current_layer_value[:, :M]
self.stddev = T.nnet.softplus(current_layer_value[:, M:]) + 1e-6
# get a sample of Z
self.rng = RandomStreams()
eps = self.rng.normal((self.means.shape[0], M))
self.Z = self.means + self.stddev * eps
# decoder
self.decoder_layers = []
M_in = M
for M_out in reversed(hidden_layer_sizes[:-1]):
h = DenseLayer(M_in, M_out)
self.decoder_layers.append(h)
M_in = M_out
# the decoder's final layer should go through a sigmoid
h = DenseLayer(M_in, D, f=T.nnet.sigmoid)
self.decoder_layers.append(h)
# get the posterior predictive
current_layer_value = self.Z
for layer in self.decoder_layers:
current_layer_value = layer.forward(current_layer_value)
self.posterior_predictive_probs = current_layer_value
# take samples from X_hat
# we will call this the posterior predictive sample
self.posterior_predictive = self.rng.binomial(
size=self.posterior_predictive_probs.shape,
n=1,
p=self.posterior_predictive_probs
)
# take sample from a Z ~ N(0, 1)
# and put it through the decoder
# we will call this the prior predictive sample
Z_std = self.rng.normal((1, M))
current_layer_value = Z_std
for layer in self.decoder_layers:
current_layer_value = layer.forward(current_layer_value)
self.prior_predictive_probs = current_layer_value
self.prior_predictive = self.rng.binomial(
size=self.prior_predictive_probs.shape,
n=1,
p=self.prior_predictive_probs
)
# prior predictive from input
# only used for generating visualization
Z_input = T.matrix('Z_input')
current_layer_value = Z_input
for layer in self.decoder_layers:
current_layer_value = layer.forward(current_layer_value)
prior_predictive_probs_from_Z_input = current_layer_value
# now build the cost
# https://stats.stackexchange.com/questions/7440/kl-divergence-between-two-univariate-gaussians
# https://stats.stackexchange.com/questions/60680/kl-divergence-between-two-multivariate-gaussians
kl = -T.log(self.stddev) + 0.5*(self.stddev**2 + self.means**2) - 0.5
kl = T.sum(kl, axis=1)
expected_log_likelihood = -T.nnet.binary_crossentropy(
output=self.posterior_predictive_probs,
target=self.X,
)
expected_log_likelihood = T.sum(expected_log_likelihood, axis=1)
self.elbo = T.sum(expected_log_likelihood - kl)
# define the updates
params = []
for layer in self.encoder_layers:
params += layer.params
for layer in self.decoder_layers:
params += layer.params
grads = T.grad(-self.elbo, params)
# rmsprop
decay = 0.9
learning_rate = 0.001
# for rmsprop
cache = [theano.shared(np.ones_like(p.get_value())) for p in params]
new_cache = [decay*c + (1-decay)*g*g for p, c, g in zip(params, cache, grads)]
updates = [
(c, new_c) for c, new_c in zip(cache, new_cache)
] + [
(p, p - learning_rate*g/T.sqrt(new_c + 1e-10)) for p, new_c, g in zip(params, new_cache, grads)
]
# now define callable functions
self.train_op = theano.function(
inputs=[self.X],
outputs=self.elbo,
updates=updates
)
# returns a sample from p(x_new | X)
self.posterior_predictive_sample = theano.function(
inputs=[self.X],
outputs=self.posterior_predictive,
)
# returns a sample from p(x_new | z), z ~ N(0, 1)
self.prior_predictive_sample_with_probs = theano.function(
inputs=[],
outputs=[self.prior_predictive, self.prior_predictive_probs]
)
# return mean of q(z | x)
self.transform = theano.function(
inputs=[self.X],
outputs=self.means
)
# returns a sample from p(x_new | z), from a given z
self.prior_predictive_with_input = theano.function(
inputs=[Z_input],
outputs=prior_predictive_probs_from_Z_input
)
def fit(self, X, epochs=30, batch_sz=64):
costs = []
n_batches = len(X) // batch_sz
print("n_batches:", n_batches)
for i in range(epochs):
print("epoch:", i)
np.random.shuffle(X)
for j in range(n_batches):
batch = X[j*batch_sz:(j+1)*batch_sz]
c = self.train_op(batch)
c /= batch_sz # just debugging
costs.append(c)
if j % 100 == 0:
print("iter: %d, cost: %.3f" % (j, c))
plt.plot(costs)
plt.show()
def main():
X, Y = util.get_mnist()
# convert X to binary variable
X = (X > 0.5).astype(np.float32)
vae = VariationalAutoencoder(784, [200, 100])
vae.fit(X)
# plot reconstruction
done = False
while not done:
i = np.random.choice(len(X))
x = X[i]
im = vae.posterior_predictive_sample([x]).reshape(28, 28)
plt.subplot(1,2,1)
plt.imshow(x.reshape(28, 28), cmap='gray')
plt.title("Original")
plt.subplot(1,2,2)
plt.imshow(im, cmap='gray')
plt.title("Sampled")
plt.show()
ans = input("Generate another?")
if ans and ans[0] in ('n' or 'N'):
done = True
# plot output from random samples in latent space
done = False
while not done:
im, probs = vae.prior_predictive_sample_with_probs()
im = im.reshape(28, 28)
probs = probs.reshape(28, 28)
plt.subplot(1,2,1)
plt.imshow(im, cmap='gray')
plt.title("Prior predictive sample")
plt.subplot(1,2,2)
plt.imshow(probs, cmap='gray')
plt.title("Prior predictive probs")
plt.show()
ans = input("Generate another?")
if ans and ans[0] in ('n' or 'N'):
done = True
if __name__ == '__main__':
main()
| VariationalAutoencoder |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 78156,
"end": 78342
} | class ____:
xlOartHorizontalOverflowClip = 1 # from enum XlOartHorizontalOverflow
xlOartHorizontalOverflowOverflow = 0 # from enum XlOartHorizontalOverflow
| OartHorizontalOverflow |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_modelresource/test_resource_factory.py | {
"start": 126,
"end": 9472
} | class ____(TestCase):
def test_create(self):
BookResource = resources.modelresource_factory(Book)
self.assertIn("id", BookResource.fields)
self.assertEqual(BookResource._meta.model, Book)
def test_create_with_meta(self):
BookResource = resources.modelresource_factory(
Book, meta_options={"clean_model_instances": True}
)
self.assertEqual(BookResource._meta.clean_model_instances, True)
def test_create_with_meta_options(self):
BookResource = resources.modelresource_factory(
Book,
meta_options={
"fields": ("id", "name"),
"exclude": ("imported",),
"use_bulk": True,
"clean_model_instances": True,
},
)
self.assertEqual(BookResource._meta.fields, ("id", "name"))
self.assertEqual(BookResource._meta.exclude, ("imported",))
self.assertTrue(BookResource._meta.use_bulk)
self.assertTrue(BookResource._meta.clean_model_instances)
def test_custom_fields(self):
custom_field = fields.Field(column_name="Custom Title", readonly=True)
BookResource = resources.modelresource_factory(
Book, custom_fields={"custom_title": custom_field}
)
self.assertIn("custom_title", BookResource.fields)
self.assertEqual(BookResource.fields["custom_title"], custom_field)
self.assertEqual(
BookResource.fields["custom_title"].column_name, "Custom Title"
)
self.assertTrue(BookResource.fields["custom_title"].readonly)
def test_custom_fields_validation(self):
with self.assertRaises(ValueError) as cm:
resources.modelresource_factory(
Book, custom_fields={"invalid_field": "not a field object"}
)
self.assertIn("must be a Field instance", str(cm.exception))
self.assertIn("custom_fields['invalid_field']", str(cm.exception))
def test_dehydrate_methods(self):
def custom_dehydrate_custom_title(obj):
return f"{obj.name} - Custom"
BookResource = resources.modelresource_factory(
Book,
custom_fields={"custom_title": fields.Field(column_name="Custom Title")},
dehydrate_methods={"custom_title": custom_dehydrate_custom_title},
)
self.assertTrue(hasattr(BookResource, "dehydrate_custom_title"))
resource = BookResource()
book = Book.objects.create(name="Test Book")
result = resource.dehydrate_custom_title(book)
self.assertEqual(result, "Test Book - Custom")
def test_dehydrate_methods_validation(self):
with self.assertRaises(ValueError) as cm:
resources.modelresource_factory(
Book, dehydrate_methods={"field_name": "not callable"}
)
self.assertIn("must be callable", str(cm.exception))
self.assertIn("dehydrate_methods['field_name']", str(cm.exception))
def test_lambda_dehydrate_methods(self):
BookResource = resources.modelresource_factory(
Book,
custom_fields={"custom_title": fields.Field(column_name="Custom Title")},
dehydrate_methods={
"custom_title": (
lambda obj: (
f"{obj.name} by {getattr(obj.author, 'name', 'Unknown')}"
)
)
},
)
author = Author.objects.create(name="Test Author")
book = Book.objects.create(name="Test Book", author=author)
resource = BookResource()
result = resource.dehydrate_custom_title(book)
self.assertEqual(result, "Test Book by Test Author")
book_no_author = Book.objects.create(name="Book")
result = resource.dehydrate_custom_title(book_no_author)
self.assertEqual(result, "Book by Unknown")
def test_comprehensive_example(self):
"""Test a comprehensive example with multiple features"""
BookResource = resources.modelresource_factory(
Book,
meta_options={
"fields": ("id", "name", "author", "custom_title", "status"),
"import_id_fields": ("name",),
"use_bulk": True,
},
custom_fields={
"custom_title": fields.Field(column_name="Custom Title", readonly=True),
"status": fields.Field(
attribute="imported",
column_name="Import Status",
widget=widgets.BooleanWidget(),
),
},
dehydrate_methods={"custom_title": lambda obj: f"{obj.name} - {obj.pk}"},
)
resource = BookResource()
self.assertEqual(
resource._meta.fields, ("id", "name", "author", "custom_title", "status")
)
self.assertEqual(resource._meta.import_id_fields, ("name",))
self.assertTrue(resource._meta.use_bulk)
self.assertIn("custom_title", resource.fields)
self.assertIn("status", resource.fields)
self.assertTrue(resource.fields["custom_title"].readonly)
self.assertTrue(hasattr(resource, "dehydrate_custom_title"))
book = Book.objects.create(name="Test Book")
custom_title_result = resource.dehydrate_custom_title(book)
self.assertEqual(custom_title_result, f"Test Book - {book.pk}")
dataset = resource.export([book])
self.assertEqual(len(dataset), 1)
def test_field_with_dehydrate_method_attribute(self):
BookResource1 = resources.modelresource_factory(
Book,
custom_fields={
"custom_title": fields.Field(
column_name="Custom Title",
dehydrate_method=lambda obj: f"Field method: {obj.name}",
)
},
)
BookResource2 = resources.modelresource_factory(
Book,
custom_fields={"custom_title": fields.Field(column_name="Custom Title")},
dehydrate_methods={
"custom_title": lambda obj: f"Factory method: {obj.name}"
},
)
book = Book.objects.create(name="Test Book")
resource1 = BookResource1()
field1 = resource1.fields["custom_title"]
self.assertTrue(callable(field1.dehydrate_method))
resource2 = BookResource2()
self.assertTrue(hasattr(resource2, "dehydrate_custom_title"))
result2 = resource2.dehydrate_custom_title(book)
self.assertEqual(result2, "Factory method: Test Book")
def test_empty_parameters(self):
BookResource = resources.modelresource_factory(
Book,
custom_fields={},
dehydrate_methods={},
)
self.assertIn("id", BookResource.fields)
self.assertEqual(BookResource._meta.model, Book)
def test_resource_class_inheritance(self):
class CustomModelResource(resources.ModelResource):
def custom_method(self):
return "custom"
BookResource = resources.modelresource_factory(
Book,
resource_class=CustomModelResource,
)
resource = BookResource()
self.assertTrue(hasattr(resource, "custom_method"))
self.assertEqual(resource.custom_method(), "custom")
def test_widgets_in_meta_options(self):
BookResource = resources.modelresource_factory(
Book,
meta_options={
"fields": ("id", "name", "price"),
"widgets": {
"price": {"coerce_to_string": True},
"name": {"coerce_to_string": True},
},
},
)
# Check that meta options were set correctly
self.assertEqual(BookResource._meta.fields, ("id", "name", "price"))
self.assertIn("price", BookResource._meta.widgets)
self.assertIn("name", BookResource._meta.widgets)
def test_complex_meta_options(self):
"""Test complex meta options configuration"""
BookResource = resources.modelresource_factory(
Book,
meta_options={
"fields": ("id", "name", "author", "price"),
"exclude": ("imported",),
"import_id_fields": ("name",),
"export_order": ("name", "author", "price", "id"),
"use_bulk": True,
"batch_size": 500,
"skip_unchanged": True,
"clean_model_instances": True,
"widgets": {"price": {"coerce_to_string": True}},
},
)
resource = BookResource()
# Verify all meta options
self.assertEqual(resource._meta.fields, ("id", "name", "author", "price"))
self.assertEqual(resource._meta.exclude, ("imported",))
self.assertEqual(resource._meta.import_id_fields, ("name",))
self.assertEqual(resource._meta.export_order, ("name", "author", "price", "id"))
self.assertTrue(resource._meta.use_bulk)
self.assertEqual(resource._meta.batch_size, 500)
self.assertTrue(resource._meta.skip_unchanged)
self.assertTrue(resource._meta.clean_model_instances)
self.assertIn("price", resource._meta.widgets)
| ModelResourceFactoryTest |
python | simonw__datasette | datasette/views/special.py | {
"start": 37471,
"end": 38819
} | class ____(SchemaBaseView):
"""
Displays schema for all databases in the instance.
Supports HTML, JSON, and Markdown formats.
"""
name = "instance_schema"
async def get(self, request):
format_ = request.url_vars.get("format") or "html"
# Get all databases the actor can view
allowed_databases_page = await self.ds.allowed_resources(
"view-database",
request.actor,
)
allowed_databases = [r.parent async for r in allowed_databases_page.all()]
# Get schema for each database
schemas = []
for database_name in allowed_databases:
schema = await self.get_database_schema(database_name)
schemas.append({"database": database_name, "schema": schema})
if format_ == "json":
return self.format_json_response({"schemas": schemas})
elif format_ == "md":
md_parts = [
f"# Schema for {item['database']}\n\n```sql\n{item['schema']}\n```"
for item in schemas
]
return Response.text(
"\n\n".join(md_parts),
headers={"content-type": "text/markdown; charset=utf-8"},
)
else:
return await self.format_html_response(request, schemas, is_instance=True)
| InstanceSchemaView |
python | matplotlib__matplotlib | lib/matplotlib/sphinxext/plot_directive.py | {
"start": 9460,
"end": 12507
} | class ____(Directive):
"""The ``.. plot::`` directive, as documented in the module's docstring."""
has_content = True
required_arguments = 0
optional_arguments = 2
final_argument_whitespace = False
option_spec = {
'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.nonnegative_int,
'align': Image.align,
'class': directives.class_option,
'filename-prefix': directives.unchanged,
'include-source': _option_boolean,
'show-source-link': _option_boolean,
'format': _option_format,
'context': _option_context,
'nofigs': directives.flag,
'caption': directives.unchanged,
'code-caption': directives.unchanged,
}
def run(self):
"""Run the plot directive."""
try:
return run(self.arguments, self.content, self.options,
self.state_machine, self.state, self.lineno)
except Exception as e:
raise self.error(str(e))
def _copy_css_file(app, exc):
if exc is None and app.builder.format == 'html':
src = cbook._get_data_path('plot_directive/plot_directive.css')
dst = app.outdir / Path('_static')
dst.mkdir(exist_ok=True)
# Use copyfile because we do not want to copy src's permissions.
shutil.copyfile(src, dst / Path('plot_directive.css'))
def setup(app):
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
app.add_directive('plot', PlotDirective)
app.add_config_value('plot_pre_code', None, True)
app.add_config_value('plot_include_source', False, True)
app.add_config_value('plot_html_show_source_link', True, True)
app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
app.add_config_value('plot_basedir', None, True)
app.add_config_value('plot_html_show_formats', True, True)
app.add_config_value('plot_rcparams', {}, True)
app.add_config_value('plot_apply_rcparams', False, True)
app.add_config_value('plot_working_directory', None, True)
app.add_config_value('plot_template', None, True)
app.add_config_value('plot_srcset', [], True)
app.connect('doctree-read', mark_plot_labels)
app.add_css_file('plot_directive.css')
app.connect('build-finished', _copy_css_file)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
'version': matplotlib.__version__}
app.connect('builder-inited', init_filename_registry)
app.add_env_collector(_FilenameCollector)
return metadata
# -----------------------------------------------------------------------------
# Handle Duplicate Filenames
# -----------------------------------------------------------------------------
def init_filename_registry(app):
env = app.builder.env
if not hasattr(env, 'mpl_plot_image_basenames'):
env.mpl_plot_image_basenames = defaultdict(set)
| PlotDirective |
python | Lightning-AI__lightning | examples/pytorch/basics/backbone_image_classifier.py | {
"start": 1751,
"end": 3179
} | class ____(LightningModule):
"""
>>> LitClassifier(Backbone()) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
LitClassifier(
(backbone): ...
)
"""
def __init__(self, backbone: Optional[Backbone] = None, learning_rate: float = 0.0001):
super().__init__()
self.save_hyperparameters(ignore=["backbone"])
if backbone is None:
backbone = Backbone()
self.backbone = backbone
def forward(self, x):
# use forward for inference/predictions
return self.backbone(x)
def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
self.log("train_loss", loss, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
self.log("valid_loss", loss, on_step=True)
def test_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
self.log("test_loss", loss)
def predict_step(self, batch, batch_idx, dataloader_idx=None):
x, _ = batch
return self(x)
def configure_optimizers(self):
# self.hparams available because we called self.save_hyperparameters()
return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)
| LitClassifier |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/bounding_box.py | {
"start": 227,
"end": 16260
} | class ____:
def __init__(self):
self.backend = backend_utils.DynamicBackend()
def convert_format(
self,
boxes,
source,
target,
height=None,
width=None,
dtype="float32",
):
if isinstance(boxes, dict):
boxes["boxes"] = self.convert_format(
boxes["boxes"],
source=source,
target=target,
height=height,
width=width,
dtype=dtype,
)
return boxes
to_xyxy_converters = {
"xyxy": self._xyxy_to_xyxy,
"yxyx": self._yxyx_to_xyxy,
"xywh": self._xywh_to_xyxy,
"center_xywh": self._center_xywh_to_xyxy,
"center_yxhw": self._center_yxhw_to_xyxy,
"rel_xyxy": self._rel_xyxy_to_xyxy,
"rel_yxyx": self._rel_yxyx_to_xyxy,
"rel_xywh": self._rel_xywh_to_xyxy,
"rel_center_xywh": self._rel_center_xywh_to_xyxy,
}
from_xyxy_converters = {
"xyxy": self._xyxy_to_xyxy,
"yxyx": self._xyxy_to_yxyx,
"xywh": self._xyxy_to_xywh,
"center_xywh": self._xyxy_to_center_xywh,
"center_yxhw": self._xyxy_to_center_yxhw,
"rel_xyxy": self._xyxy_to_rel_xyxy,
"rel_yxyx": self._xyxy_to_rel_yxyx,
"rel_xywh": self._xyxy_to_rel_xywh,
"rel_center_xywh": self._xyxy_to_rel_center_xywh,
}
ops = self.backend
boxes_shape = ops.shape(boxes)
if boxes_shape[-1] != 4:
raise ValueError(
"`boxes` must be a tensor with the last dimension of 4. "
f"Received: boxes.shape={boxes_shape}"
)
source = source.lower()
target = target.lower()
if source not in SUPPORTED_FORMATS or target not in SUPPORTED_FORMATS:
raise ValueError(
f"Invalid source or target format. "
f"Supported formats: {SUPPORTED_FORMATS}"
)
if (source.startswith("rel_") or target.startswith("rel_")) and (
width is None or height is None
):
raise ValueError(
"convert_format() must receive `height` and `width` "
"transforming between relative and absolute formats."
f"convert_format() received source=`{source}`, "
f"target=`{target}, "
f"but height={height} and width={width}."
)
boxes = ops.cast(boxes, dtype)
if source == target:
return boxes
if width is not None:
width = ops.cast(width, dtype)
if height is not None:
height = ops.cast(height, dtype)
if source.startswith("rel_") and target.startswith("rel_"):
source = source.replace("rel_", "", 1)
target = target.replace("rel_", "", 1)
to_xyxy_converter = to_xyxy_converters[source]
from_xyxy_converter = from_xyxy_converters[target]
in_xyxy_boxes = to_xyxy_converter(boxes, height, width)
return from_xyxy_converter(in_xyxy_boxes, height, width)
def clip_to_image_size(
self,
bounding_boxes,
height=None,
width=None,
bounding_box_format="xyxy",
):
if bounding_box_format not in ("xyxy", "rel_xyxy"):
raise NotImplementedError
if bounding_box_format == "xyxy" and (height is None or width is None):
raise ValueError(
"`height` and `width` must be set if `format='xyxy'`."
)
ops = self.backend
boxes, labels = bounding_boxes["boxes"], bounding_boxes["labels"]
if width is not None:
width = ops.cast(width, boxes.dtype)
if height is not None:
height = ops.cast(height, boxes.dtype)
if bounding_box_format == "xyxy":
x1, y1, x2, y2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = ops.numpy.clip(x1, 0, width)
y1 = ops.numpy.clip(y1, 0, height)
x2 = ops.numpy.clip(x2, 0, width)
y2 = ops.numpy.clip(y2, 0, height)
boxes = ops.numpy.concatenate([x1, y1, x2, y2], axis=-1)
areas = self._compute_area(boxes)
areas = ops.numpy.squeeze(areas, axis=-1)
labels = ops.numpy.where(areas > 0, labels, -1)
elif bounding_box_format == "rel_xyxy":
x1, y1, x2, y2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = ops.numpy.clip(x1, 0.0, 1.0)
y1 = ops.numpy.clip(y1, 0.0, 1.0)
x2 = ops.numpy.clip(x2, 0.0, 1.0)
y2 = ops.numpy.clip(y2, 0.0, 1.0)
boxes = ops.numpy.concatenate([x1, y1, x2, y2], axis=-1)
areas = self._compute_area(boxes)
areas = ops.numpy.squeeze(areas, axis=-1)
labels = ops.numpy.where(areas > 0, labels, -1)
result = bounding_boxes.copy()
result["boxes"] = boxes
result["labels"] = labels
return result
def affine(
self,
boxes,
angle,
translate_x,
translate_y,
scale,
shear_x,
shear_y,
height,
width,
center_x=None,
center_y=None,
):
ops = self.backend
boxes_shape = ops.shape(boxes)
batch_size = boxes_shape[0]
n_boxes = boxes_shape[1]
if center_x is None:
center_x = 0.5
if center_y is None:
center_y = 0.5
matrix = self._compute_inverse_affine_matrix(
center_x,
center_y,
angle,
translate_x,
translate_y,
scale,
shear_x,
shear_y,
height,
width,
)
boxes = ops.cast(boxes, dtype=matrix.dtype)
transposed_matrix = ops.numpy.transpose(matrix[:, :2, :], [0, 2, 1])
points = boxes # [B, N, 4]
points = ops.numpy.stack(
[
points[..., 0],
points[..., 1],
points[..., 2],
points[..., 1],
points[..., 2],
points[..., 3],
points[..., 0],
points[..., 3],
],
axis=-1,
)
points = ops.numpy.reshape(points, [batch_size, n_boxes, 4, 2])
points = ops.numpy.concatenate(
[
points,
ops.numpy.ones([batch_size, n_boxes, 4, 1], points.dtype),
],
axis=-1,
)
transformed_points = ops.numpy.einsum(
"bnxy,byz->bnxz", points, transposed_matrix
)
boxes_min = ops.numpy.amin(transformed_points, axis=2)
boxes_max = ops.numpy.amax(transformed_points, axis=2)
outputs = ops.numpy.concatenate([boxes_min, boxes_max], axis=-1)
return outputs
def crop(self, boxes, top, left, height, width):
ops = self.backend
x1, y1, x2, y2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = x1 - left
y1 = y1 - top
x2 = x2 - left
y2 = y2 - top
x1 = ops.numpy.clip(x1, 0, width)
y1 = ops.numpy.clip(y1, 0, height)
x2 = ops.numpy.clip(x2, 0, width)
y2 = ops.numpy.clip(y2, 0, height)
outputs = ops.numpy.concatenate([x1, y1, x2, y2], axis=-1)
return outputs
def pad(self, boxes, top, left):
ops = self.backend
x1, y1, x2, y2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = x1 + left
y1 = y1 + top
x2 = x2 + left
y2 = y2 + top
outputs = ops.numpy.concatenate([x1, y1, x2, y2], axis=-1)
return outputs
# Converters
def _xyxy_to_xyxy(self, boxes, height=None, width=None):
return boxes
def _yxyx_to_xyxy(self, boxes, height=None, width=None):
y1, x1, y2, x2 = self.backend.numpy.split(boxes, 4, axis=-1)
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _xywh_to_xyxy(self, boxes, height=None, width=None):
x1, y1, w, h = self.backend.numpy.split(boxes, 4, axis=-1)
x2 = x1 + w
y2 = y1 + h
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _center_xywh_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
cx, cy, w, h = ops.numpy.split(boxes, 4, axis=-1)
half_w = w / 2.0
half_h = h / 2.0
x1 = cx - half_w
y1 = cy - half_h
x2 = cx + half_w
y2 = cy + half_h
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _center_yxhw_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
cy, cx, h, w = ops.numpy.split(boxes, 4, axis=-1)
half_w = w / 2.0
half_h = h / 2.0
x1 = cx - half_w
y1 = cy - half_h
x2 = cx + half_w
y2 = cy + half_h
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _rel_xyxy_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
rel_x1, rel_y1, rel_x2, rel_y2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = rel_x1 * width
y1 = rel_y1 * height
x2 = rel_x2 * width
y2 = rel_y2 * height
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _rel_yxyx_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
rel_y1, rel_x1, rel_y2, rel_x2 = ops.numpy.split(boxes, 4, axis=-1)
x1 = rel_x1 * width
y1 = rel_y1 * height
x2 = rel_x2 * width
y2 = rel_y2 * height
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _rel_xywh_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
rel_x1, rel_y1, rel_w, rel_h = ops.numpy.split(boxes, 4, axis=-1)
x1 = rel_x1 * width
y1 = rel_y1 * height
x2 = (rel_x1 + rel_w) * width
y2 = (rel_y1 + rel_h) * height
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _rel_center_xywh_to_xyxy(self, boxes, height=None, width=None):
ops = self.backend
rel_cx, rel_cy, rel_w, rel_h = ops.numpy.split(boxes, 4, axis=-1)
half_rel_w = rel_w / 2.0
half_rel_h = rel_h / 2.0
x1 = (rel_cx - half_rel_w) * height
y1 = (rel_cy - half_rel_h) * width
x2 = (rel_cx + half_rel_w) * height
y2 = (rel_cy + half_rel_h) * width
return self.backend.numpy.concatenate([x1, y1, x2, y2], axis=-1)
def _xyxy_to_yxyx(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
return self.backend.numpy.concatenate([y1, x1, y2, x2], axis=-1)
def _xyxy_to_xywh(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
w = x2 - x1
h = y2 - y1
return self.backend.numpy.concatenate([x1, y1, w, h], axis=-1)
def _xyxy_to_center_xywh(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
cx = x1 + ((x2 - x1) / 2.0)
cy = y1 + ((y2 - y1) / 2.0)
w = x2 - x1
h = y2 - y1
return self.backend.numpy.concatenate([cx, cy, w, h], axis=-1)
def _xyxy_to_center_yxhw(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
cx = x1 + ((x2 - x1) / 2.0)
cy = y1 + ((y2 - y1) / 2.0)
w = x2 - x1
h = y2 - y1
return self.backend.numpy.concatenate([cy, cx, h, w], axis=-1)
def _xyxy_to_rel_xyxy(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
rel_x1 = self.backend.numpy.divide(x1, width)
rel_y1 = self.backend.numpy.divide(y1, height)
rel_x2 = self.backend.numpy.divide(x2, width)
rel_y2 = self.backend.numpy.divide(y2, height)
return self.backend.numpy.concatenate(
[rel_x1, rel_y1, rel_x2, rel_y2], axis=-1
)
def _xyxy_to_rel_yxyx(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
rel_x1 = self.backend.numpy.divide(x1, width)
rel_y1 = self.backend.numpy.divide(y1, height)
rel_x2 = self.backend.numpy.divide(x2, width)
rel_y2 = self.backend.numpy.divide(y2, height)
return self.backend.numpy.concatenate(
[rel_y1, rel_x1, rel_y2, rel_x2], axis=-1
)
def _xyxy_to_rel_xywh(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
rel_x1 = x1 / width
rel_y1 = y1 / height
rel_w = (x2 - x1) / width
rel_h = (y2 - y1) / height
return self.backend.numpy.concatenate(
[rel_x1, rel_y1, rel_w, rel_h], axis=-1
)
def _xyxy_to_rel_center_xywh(self, boxes, height=None, width=None):
x1, y1, x2, y2 = self.backend.numpy.split(boxes, 4, axis=-1)
rel_cx = (x1 + ((x2 - x1) / 2.0)) / width
rel_cy = (y1 + ((y2 - y1) / 2.0)) / height
rel_w = (x2 - x1) / width
rel_h = (y2 - y1) / height
return self.backend.numpy.concatenate(
[rel_cx, rel_cy, rel_w, rel_h], axis=-1
)
# Clip
def _compute_area(self, boxes, format="xyxy"):
if format not in ("xyxy", "rel_xyxy"):
raise NotImplementedError
ops = self.backend
x1, y1, x2, y2 = ops.numpy.split(boxes, 4, axis=-1)
widths = x2 - x1
heights = y2 - y1
return widths * heights
def _compute_inverse_affine_matrix(
self,
center_x,
center_y,
angle,
translate_x,
translate_y,
scale,
shear_x,
shear_y,
height,
width,
):
# Ref: TF._geometry._get_inverse_affine_matrix
ops = self.backend
batch_size = ops.shape(angle)[0]
dtype = angle.dtype
angle = -angle
shear_x = -shear_x
shear_y = -shear_y
cx = ops.numpy.multiply(center_x, (width - 1))
cy = ops.numpy.multiply(center_y, (height - 1))
rot = ops.numpy.multiply(angle, 1.0 / 180.0 * math.pi)
tx = ops.numpy.multiply(-translate_x, (width - 1))
ty = ops.numpy.multiply(-translate_y, (height - 1))
sx = ops.numpy.multiply(shear_x, 1.0 / 180.0 * math.pi)
sy = ops.numpy.multiply(shear_y, 1.0 / 180.0 * math.pi)
# Cached results
cos_sy = ops.numpy.cos(sy)
tan_sx = ops.numpy.tan(sx)
rot_minus_sy = rot - sy
cx_plus_tx = cx + tx
cy_plus_ty = cy + ty
# Rotate Scale Shear (RSS) without scaling
a = ops.numpy.cos(rot_minus_sy) / cos_sy
b = a * tan_sx + ops.numpy.sin(rot)
c = -ops.numpy.sin(rot_minus_sy) / cos_sy
d = ops.numpy.cos(rot) - c * tan_sx
# Inverted rotation matrix with scale and shear
# det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1
a0 = ops.numpy.multiply(d, scale)
a1 = ops.numpy.multiply(-b, scale)
b0 = ops.numpy.multiply(-c, scale)
b1 = ops.numpy.multiply(a, scale)
a2 = cx - a0 * cx_plus_tx - a1 * cy_plus_ty
b2 = cy - b0 * cx_plus_tx - b1 * cy_plus_ty
# Shape of matrix: [[batch_size], ...] -> [batch_size, 6]
matrix = ops.numpy.stack(
[
a0,
a1,
a2,
b0,
b1,
b2,
ops.numpy.zeros([batch_size], dtype),
ops.numpy.zeros([batch_size], dtype),
ops.numpy.ones([batch_size], dtype),
],
axis=-1,
)
matrix = ops.numpy.reshape(matrix, [batch_size, 3, 3])
return matrix
| BoundingBox |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/subscript4.py | {
"start": 190,
"end": 233
} | class ____(NamedTuple):
value: int
| OneInt |
python | python-pillow__Pillow | src/PIL/ImageShow.py | {
"start": 4442,
"end": 5675
} | class ____(Viewer):
"""The default viewer on macOS using ``Preview.app``."""
format = "PNG"
options = {"compress_level": 1, "save_all": True}
def get_command(self, file: str, **options: Any) -> str:
# on darwin open returns immediately resulting in the temp
# file removal while app is opening
command = "open -a Preview.app"
command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
return command
def show_file(self, path: str, **options: Any) -> int:
"""
Display given file.
"""
if not os.path.exists(path):
raise FileNotFoundError
subprocess.call(["open", "-a", "Preview.app", path])
pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
executable = (not pyinstaller and sys.executable) or shutil.which("python3")
if executable:
subprocess.Popen(
[
executable,
"-c",
"import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
path,
]
)
return 1
if sys.platform == "darwin":
register(MacViewer)
| MacViewer |
python | python-attrs__attrs | typing-examples/baseline.py | {
"start": 3602,
"end": 3857
} | class ____:
pass
cp: attrs.ClassProps = attrs.inspect(Hashable)
cp.added_init
if cp.hashability is attrs.ClassProps.Hashability.UNHASHABLE:
cp.is_slotted
def test(cls: type) -> None:
if attrs.has(cls):
attrs.resolve_types(cls)
| Hashable |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/memory.py | {
"start": 9753,
"end": 10820
} | class ____(_Publisher):
def __init__(self, topic: str, cache: Cache, deduplicate_by: Optional[str] = None):
self.topic: Topic = Topic.by_name(topic)
self.deduplicate_by = deduplicate_by
self._cache = cache
async def __aenter__(self) -> Self:
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
return None
async def publish_data(self, data: bytes, attributes: Mapping[str, str]) -> None:
to_publish = [MemoryMessage(data, attributes)]
if self.deduplicate_by:
to_publish = await self._cache.without_duplicates(
self.deduplicate_by, to_publish
)
try:
for message in to_publish:
await self.topic.publish(message)
except Exception:
if self.deduplicate_by:
await self._cache.forget_duplicates(self.deduplicate_by, to_publish)
raise
| Publisher |
python | dagster-io__dagster | python_modules/automation/automation/dagster_dev/commands/diff_summarizer.py | {
"start": 163,
"end": 485
} | class ____(Enum):
"""Categories of code changes for different analysis approaches."""
DOCUMENTATION = "documentation"
TESTS = "tests"
CONFIGURATION = "configuration"
NEW_FEATURE = "new_feature"
BUG_FIX = "bug_fix"
REFACTOR = "refactor"
MAJOR_REFACTOR = "major_refactor"
@dataclass
| ChangeType |
python | getsentry__sentry | src/sentry/relocation/api/endpoints/index.py | {
"start": 6495,
"end": 12619
} | class ____(Endpoint):
owner = ApiOwner.HYBRID_CLOUD
publish_status = {
# TODO(getsentry/team-ospo#214): Stabilize before GA.
"GET": ApiPublishStatus.EXPERIMENTAL,
"POST": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (SentryIsAuthenticated,)
def get(self, request: Request) -> Response:
"""
A list of relocations, ordered by creation date.
``````````````````````````````````````````````````
:qparam string query: string to match in importing org slugs, username, or relocation UUID.
:qparam string status: filter by status.
:auth: required
"""
logger.info("relocations.index.get.start", extra={"caller": request.user.id})
if not request.user.is_authenticated:
return Response(status=status.HTTP_400_BAD_REQUEST)
queryset = Relocation.objects.all()
# TODO(schew2381): Remove the superuser reference below after feature flag is removed.
# Non-superuser/staff can only see their own relocations.
if not has_elevated_mode(request):
queryset = queryset.filter(owner_id=request.user.id)
query = request.GET.get("query")
if query:
tokens = tokenize_query(query)
for key, value in tokens.items():
if key == "query":
# Every supplied search term must appear at least once in ANY of the UUID, org
# slug list, or username list for the relocation to be matched.
for term in value:
queryset = queryset.filter(
Q(uuid__icontains=term)
| Q(want_org_slugs__icontains=term)
| Q(want_usernames__icontains=term)
)
status_str = request.GET.get("status")
if status_str:
try:
stat = Relocation.Status[status_str.upper()]
except KeyError:
return Response(
{"detail": ERR_UNKNOWN_RELOCATION_STATUS.substitute(status=status_str)},
status=status.HTTP_400_BAD_REQUEST,
)
queryset = queryset.filter(status=stat.value)
return self.paginate(
request=request,
queryset=queryset,
order_by="-date_added",
on_results=lambda x: serialize(x, request.user, RelocationSerializer()),
paginator_cls=OffsetPaginator,
)
def post(self, request: Request) -> Response:
"""
Upload an encrypted export tarball for relocation.
``````````````````````````````````````````````````
Upload an encrypted relocation tarball for relocation.
This is currently an experimental API, and for the time being is only meant to be called by
admins.
:param file file: the multipart encoded tarball file.
:param string owner: the username of the "owner" of this relocation; not necessarily
identical to the user who made the API call.
:param list[string] orgs: A list of org slugs from those included in the associated
encrypted backup tarball that should be imported.
:auth: required
"""
logger.info("relocations.index.post.start", extra={"caller": request.user.id})
if not request.user.is_authenticated:
return Response(status=status.HTTP_400_BAD_REQUEST)
serializer = RelocationsPostSerializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
validated = serializer.validated_data
fileobj = validated.get("file")
file_size = fileobj.size
owner_username = validated.get("owner")
promo_code = validated.get("promo_code")
org_slugs = [org.strip() for org in validated.get("orgs").split(",")]
err = validate_new_relocation_request(request, owner_username, org_slugs, file_size)
if err is not None:
return err
try:
owner = user_service.get_by_username(username=owner_username)[0]
except IndexError:
return Response(
{"detail": ERR_OWNER_NOT_FOUND.substitute(owner_username=owner_username)},
status=status.HTTP_400_BAD_REQUEST,
)
err = validate_relocation_uniqueness(owner)
if err is not None:
return err
file = File.objects.create(name="raw-relocation-data.tar", type=RELOCATION_FILE_TYPE)
file.putfile(fileobj, blob_size=RELOCATION_BLOB_SIZE, logger=logger)
with atomic_transaction(
using=(router.db_for_write(Relocation), router.db_for_write(RelocationFile))
):
provenance = Relocation.Provenance.SELF_HOSTED
relocation: Relocation = Relocation.objects.create(
creator_id=request.user.id,
owner_id=owner.id,
want_org_slugs=org_slugs,
step=Relocation.Step.UPLOADING.value,
scheduled_pause_at_step=get_autopause_value(provenance),
provenance=provenance,
)
RelocationFile.objects.create(
relocation=relocation,
file=file,
kind=RelocationFile.Kind.RAW_USER_DATA.value,
)
relocation_link_promo_code.send_robust(
relocation_uuid=relocation.uuid, promo_code=promo_code, sender=self.__class__
)
uploading_start.apply_async(args=[str(relocation.uuid), None, None])
try:
analytics.record(
RelocationCreatedEvent(
creator_id=request.user.id,
owner_id=owner.id,
uuid=str(relocation.uuid),
)
)
except Exception as e:
capture_exception(e)
return Response(serialize(relocation), status=status.HTTP_201_CREATED)
| RelocationIndexEndpoint |
python | tiangolo__fastapi | docs_src/additional_responses/tutorial001.py | {
"start": 156,
"end": 506
} | class ____(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
return JSONResponse(status_code=404, content={"message": "Item not found"})
| Message |
python | h5py__h5py | h5py/tests/test_h5d_direct_chunk.py | {
"start": 5165,
"end": 7751
} | class ____:
def test_uncompressed_data(self, writable_file):
ref_data = numpy.arange(16).reshape(4, 4)
dataset = writable_file.create_dataset(
make_name(), data=ref_data, chunks=ref_data.shape)
out = bytearray(ref_data.nbytes)
filter_mask, chunk = dataset.id.read_direct_chunk((0, 0), out=out)
assert numpy.array_equal(
numpy.frombuffer(out, dtype=ref_data.dtype).reshape(ref_data.shape),
ref_data,
)
assert filter_mask == 0
assert len(chunk) == ref_data.nbytes
@pytest.mark.skipif(
'gzip' not in h5py.filters.encode,
reason="DEFLATE is not installed",
)
def test_compressed_data(self, writable_file):
ref_data = numpy.arange(16).reshape(4, 4)
dataset = writable_file.create_dataset(
make_name(),
data=ref_data,
chunks=ref_data.shape,
compression="gzip",
compression_opts=9,
)
chunk_info = dataset.id.get_chunk_info(0)
out = bytearray(chunk_info.size)
filter_mask, chunk = dataset.id.read_direct_chunk(
chunk_info.chunk_offset,
out=out,
)
assert filter_mask == chunk_info.filter_mask
assert len(chunk) == chunk_info.size
assert out == dataset.id.read_direct_chunk(chunk_info.chunk_offset)[1]
def test_fail_buffer_too_small(self, writable_file):
ref_data = numpy.arange(16).reshape(4, 4)
dataset = writable_file.create_dataset(
make_name(), data=ref_data, chunks=ref_data.shape)
out = bytearray(ref_data.nbytes // 2)
with pytest.raises(ValueError):
dataset.id.read_direct_chunk((0, 0), out=out)
def test_fail_buffer_readonly(self, writable_file):
ref_data = numpy.arange(16).reshape(4, 4)
dataset = writable_file.create_dataset(
make_name(), data=ref_data, chunks=ref_data.shape)
out = bytes(ref_data.nbytes)
with pytest.raises(BufferError):
dataset.id.read_direct_chunk((0, 0), out=out)
def test_fail_buffer_not_contiguous(self, writable_file):
ref_data = numpy.arange(16).reshape(4, 4)
dataset = writable_file.create_dataset(
make_name(), data=ref_data, chunks=ref_data.shape)
array = numpy.empty(ref_data.shape + (2,), dtype=ref_data.dtype)
out = array[:, :, ::2] # Array is not contiguous
with pytest.raises(ValueError):
dataset.id.read_direct_chunk((0, 0), out=out)
| TestReadDirectChunkToOut |
python | boto__boto3 | tests/unit/dynamodb/test_table.py | {
"start": 642,
"end": 18810
} | class ____(unittest.TestCase):
maxDiff = None
def setUp(self):
self.client = mock.Mock()
self.client.batch_write_item.return_value = {'UnprocessedItems': {}}
self.table_name = 'tablename'
self.flush_amount = 2
self.batch_writer = BatchWriter(
self.table_name, self.client, self.flush_amount
)
def assert_batch_write_calls_are(self, expected_batch_writes):
assert self.client.batch_write_item.call_count == len(
expected_batch_writes
)
batch_write_calls = [
args[1] for args in self.client.batch_write_item.call_args_list
]
assert batch_write_calls == expected_batch_writes
def test_batch_write_does_not_immediately_write(self):
self.batch_writer.put_item(Item={'Hash': 'foo'})
assert not self.client.batch_write_item.called
def test_batch_write_flushes_at_flush_amount(self):
self.batch_writer.put_item(Item={'Hash': 'foo1'})
self.batch_writer.put_item(Item={'Hash': 'foo2'})
expected = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
self.assert_batch_write_calls_are([expected])
def test_multiple_flushes_reset_items_to_put(self):
self.batch_writer.put_item(Item={'Hash': 'foo1'})
self.batch_writer.put_item(Item={'Hash': 'foo2'})
self.batch_writer.put_item(Item={'Hash': 'foo3'})
self.batch_writer.put_item(Item={'Hash': 'foo4'})
# We should have two batch calls, one for foo1,foo2 and
# one for foo3,foo4.
first_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
second_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
{'PutRequest': {'Item': {'Hash': 'foo4'}}},
]
}
}
self.assert_batch_write_calls_are([first_batch, second_batch])
def test_can_handle_puts_and_deletes(self):
self.batch_writer.put_item(Item={'Hash': 'foo1'})
self.batch_writer.delete_item(Key={'Hash': 'foo2'})
expected = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'DeleteRequest': {'Key': {'Hash': 'foo2'}}},
]
}
}
self.assert_batch_write_calls_are([expected])
def test_multiple_batch_calls_with_mixed_deletes(self):
self.batch_writer.put_item(Item={'Hash': 'foo1'})
self.batch_writer.delete_item(Key={'Hash': 'foo2'})
self.batch_writer.delete_item(Key={'Hash': 'foo3'})
self.batch_writer.put_item(Item={'Hash': 'foo4'})
first_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'DeleteRequest': {'Key': {'Hash': 'foo2'}}},
]
}
}
second_batch = {
'RequestItems': {
self.table_name: [
{'DeleteRequest': {'Key': {'Hash': 'foo3'}}},
{'PutRequest': {'Item': {'Hash': 'foo4'}}},
]
}
}
self.assert_batch_write_calls_are([first_batch, second_batch])
def test_unprocessed_items_added_to_next_batch(self):
self.client.batch_write_item.side_effect = [
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo2'}}}
],
},
},
# Then the last response shows that everything went through
{'UnprocessedItems': {}},
]
self.batch_writer.put_item(Item={'Hash': 'foo1'})
self.batch_writer.put_item(Item={'Hash': 'foo2'})
self.batch_writer.put_item(Item={'Hash': 'foo3'})
# We should have sent two batch requests consisting of 2
# 2 requests. foo1,foo2 and foo2,foo3.
# foo2 is sent twice because the first response has it listed
# as an unprocessed item which means it needs to be part
# of the next batch.
first_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
second_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
]
}
}
self.assert_batch_write_calls_are([first_batch, second_batch])
def test_all_items_flushed_on_exit(self):
with self.batch_writer as b:
b.put_item(Item={'Hash': 'foo1'})
self.assert_batch_write_calls_are(
[
{
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
]
},
},
]
)
def test_never_send_more_than_max_batch_size(self):
# Suppose the server sends backs a response that indicates that
# all the items were unprocessed.
self.client.batch_write_item.side_effect = [
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
],
},
},
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
],
},
},
{'UnprocessedItems': {}},
]
with BatchWriter(self.table_name, self.client, flush_amount=2) as b:
b.put_item(Item={'Hash': 'foo1'})
b.put_item(Item={'Hash': 'foo2'})
b.put_item(Item={'Hash': 'foo3'})
# Note how we're never sending more than flush_amount=2.
first_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
# Even when the server sends us unprocessed items of 2 elements,
# we'll still only send 2 at a time, in order.
second_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
# And then we still see one more unprocessed item so
# we need to send another batch.
third_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
self.assert_batch_write_calls_are(
[first_batch, second_batch, third_batch]
)
def test_repeated_flushing_on_exit(self):
# We're going to simulate unprocessed_items
# returning multiple unprocessed items across calls.
self.client.batch_write_item.side_effect = [
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
],
},
},
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
],
},
},
{'UnprocessedItems': {}},
]
with BatchWriter(self.table_name, self.client, flush_amount=4) as b:
b.put_item(Item={'Hash': 'foo1'})
b.put_item(Item={'Hash': 'foo2'})
b.put_item(Item={'Hash': 'foo3'})
# So when we exit, we expect three calls.
# First we try the normal batch write with 3 items:
first_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
]
}
}
# Then we see two unprocessed items so we send another batch.
second_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
]
}
}
# And then we still see one more unprocessed item so
# we need to send another batch.
third_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
]
}
}
self.assert_batch_write_calls_are(
[first_batch, second_batch, third_batch]
)
def test_auto_dedup_for_dup_requests(self):
with BatchWriter(
self.table_name,
self.client,
flush_amount=5,
overwrite_by_pkeys=["pkey", "skey"],
) as b:
# dup 1
b.put_item(
Item={'pkey': 'foo1', 'skey': 'bar1', 'other': 'other1'}
)
b.put_item(
Item={'pkey': 'foo1', 'skey': 'bar1', 'other': 'other2'}
)
# dup 2
b.delete_item(
Key={
'pkey': 'foo1',
'skey': 'bar2',
}
)
b.put_item(
Item={'pkey': 'foo1', 'skey': 'bar2', 'other': 'other3'}
)
# dup 3
b.put_item(
Item={'pkey': 'foo2', 'skey': 'bar2', 'other': 'other3'}
)
b.delete_item(
Key={
'pkey': 'foo2',
'skey': 'bar2',
}
)
# dup 4
b.delete_item(
Key={
'pkey': 'foo2',
'skey': 'bar3',
}
)
b.delete_item(
Key={
'pkey': 'foo2',
'skey': 'bar3',
}
)
# 5
b.delete_item(
Key={
'pkey': 'foo3',
'skey': 'bar3',
}
)
# 2nd batch
b.put_item(
Item={'pkey': 'foo1', 'skey': 'bar1', 'other': 'other1'}
)
b.put_item(
Item={'pkey': 'foo1', 'skey': 'bar1', 'other': 'other2'}
)
first_batch = {
'RequestItems': {
self.table_name: [
{
'PutRequest': {
'Item': {
'pkey': 'foo1',
'skey': 'bar1',
'other': 'other2',
}
}
},
{
'PutRequest': {
'Item': {
'pkey': 'foo1',
'skey': 'bar2',
'other': 'other3',
}
}
},
{
'DeleteRequest': {
'Key': {
'pkey': 'foo2',
'skey': 'bar2',
}
}
},
{
'DeleteRequest': {
'Key': {
'pkey': 'foo2',
'skey': 'bar3',
}
}
},
{
'DeleteRequest': {
'Key': {
'pkey': 'foo3',
'skey': 'bar3',
}
}
},
]
}
}
second_batch = {
'RequestItems': {
self.table_name: [
{
'PutRequest': {
'Item': {
'pkey': 'foo1',
'skey': 'bar1',
'other': 'other2',
}
}
},
]
}
}
self.assert_batch_write_calls_are([first_batch, second_batch])
def test_added_unsent_request_not_flushed_put(self):
# If n requests that get sent fail to process where n = flush_amount
# and at least one more request gets created before the second attempt,
# then previously if n requests were successful on the next run and
# returned an empty dict, _item_buffer would be emptied before sending
# the next batch of n requests
self.client.batch_write_item.side_effect = [
{
'UnprocessedItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
],
},
},
{
'UnprocessedItems': {},
},
{
'UnprocessedItems': {},
},
]
self.batch_writer.put_item({'Hash': 'foo1'})
self.batch_writer.put_item({'Hash': 'foo2'})
self.batch_writer.put_item({'Hash': 'foo3'})
self.assertIn(
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
self.batch_writer._items_buffer,
)
batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo1'}}},
{'PutRequest': {'Item': {'Hash': 'foo2'}}},
]
}
}
final_batch = {
'RequestItems': {
self.table_name: [
{'PutRequest': {'Item': {'Hash': 'foo3'}}},
{'PutRequest': {'Item': {'Hash': 'foo4'}}},
]
}
}
# same batch sent twice since all failed on first try
# and flush_items = 2
self.assert_batch_write_calls_are([batch, batch])
# test that the next two items get sent
self.batch_writer.put_item({'Hash': 'foo4'})
self.assert_batch_write_calls_are([batch, batch, final_batch])
# the buffer should be empty now
self.assertEqual(self.batch_writer._items_buffer, [])
def test_added_unsent_request_not_flushed_delete(self):
# If n requests that get sent fail to process where n = flush_amount
# and at least one more request gets created before the second attempt,
# then previously if n requests were successful on the next run and
# returned an empty dict, _item_buffer would be emptied before sending
# the next batch of n requests
self.client.batch_write_item.side_effect = [
{
'UnprocessedItems': {
self.table_name: [
{'DeleteRequest': {'Key': {'Hash': 'foo1'}}},
{'DeleteRequest': {'Key': {'Hash': 'foo2'}}},
],
},
},
{
'UnprocessedItems': {},
},
{
'UnprocessedItems': {},
},
]
self.batch_writer.delete_item({'Hash': 'foo1'})
self.batch_writer.delete_item({'Hash': 'foo2'})
self.batch_writer.delete_item({'Hash': 'foo3'})
self.assertIn(
{'DeleteRequest': {'Key': {'Hash': 'foo3'}}},
self.batch_writer._items_buffer,
)
batch = {
'RequestItems': {
self.table_name: [
{'DeleteRequest': {'Key': {'Hash': 'foo1'}}},
{'DeleteRequest': {'Key': {'Hash': 'foo2'}}},
]
}
}
final_batch = {
'RequestItems': {
self.table_name: [
{'DeleteRequest': {'Key': {'Hash': 'foo3'}}},
{'DeleteRequest': {'Key': {'Hash': 'foo4'}}},
]
}
}
# same batch sent twice since all failed on first try
# and flush_items = 2
self.assert_batch_write_calls_are([batch, batch])
# test that the next two items get sent
self.batch_writer.delete_item({'Hash': 'foo4'})
self.assert_batch_write_calls_are([batch, batch, final_batch])
# the buffer should be empty now
self.assertEqual(self.batch_writer._items_buffer, [])
| BaseTransformationTest |
python | plotly__plotly.py | plotly/graph_objs/layout/_scene.py | {
"start": 235,
"end": 14488
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.scene"
_valid_props = {
"annotationdefaults",
"annotations",
"aspectmode",
"aspectratio",
"bgcolor",
"camera",
"domain",
"dragmode",
"hovermode",
"uirevision",
"xaxis",
"yaxis",
"zaxis",
}
@property
def annotations(self):
"""
The 'annotations' property is a tuple of instances of
Annotation that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.scene.Annotation
- A list or tuple of dicts of string/value properties that
will be passed to the Annotation constructor
Returns
-------
tuple[plotly.graph_objs.layout.scene.Annotation]
"""
return self["annotations"]
@annotations.setter
def annotations(self, val):
self["annotations"] = val
@property
def annotationdefaults(self):
"""
When used in a template (as
layout.template.layout.scene.annotationdefaults), sets the
default property values to use for elements of
layout.scene.annotations
The 'annotationdefaults' property is an instance of Annotation
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.Annotation`
- A dict of string/value properties that will be passed
to the Annotation constructor
Returns
-------
plotly.graph_objs.layout.scene.Annotation
"""
return self["annotationdefaults"]
@annotationdefaults.setter
def annotationdefaults(self, val):
self["annotationdefaults"] = val
@property
def aspectmode(self):
"""
If "cube", this scene's axes are drawn as a cube, regardless of
the axes' ranges. If "data", this scene's axes are drawn in
proportion with the axes' ranges. If "manual", this scene's
axes are drawn in proportion with the input of "aspectratio"
(the default behavior if "aspectratio" is provided). If "auto",
this scene's axes are drawn using the results of "data" except
when one axis is more than four times the size of the two
others, where in that case the results of "cube" are used.
The 'aspectmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'cube', 'data', 'manual']
Returns
-------
Any
"""
return self["aspectmode"]
@aspectmode.setter
def aspectmode(self, val):
self["aspectmode"] = val
@property
def aspectratio(self):
"""
Sets this scene's axis aspectratio.
The 'aspectratio' property is an instance of Aspectratio
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.Aspectratio`
- A dict of string/value properties that will be passed
to the Aspectratio constructor
Returns
-------
plotly.graph_objs.layout.scene.Aspectratio
"""
return self["aspectratio"]
@aspectratio.setter
def aspectratio(self, val):
self["aspectratio"] = val
@property
def bgcolor(self):
"""
The 'bgcolor' 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
Returns
-------
str
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def camera(self):
"""
The 'camera' property is an instance of Camera
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.Camera`
- A dict of string/value properties that will be passed
to the Camera constructor
Returns
-------
plotly.graph_objs.layout.scene.Camera
"""
return self["camera"]
@camera.setter
def camera(self, val):
self["camera"] = val
@property
def domain(self):
"""
The 'domain' property is an instance of Domain
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.Domain`
- A dict of string/value properties that will be passed
to the Domain constructor
Returns
-------
plotly.graph_objs.layout.scene.Domain
"""
return self["domain"]
@domain.setter
def domain(self, val):
self["domain"] = val
@property
def dragmode(self):
"""
Determines the mode of drag interactions for this scene.
The 'dragmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['orbit', 'turntable', 'zoom', 'pan', False]
Returns
-------
Any
"""
return self["dragmode"]
@dragmode.setter
def dragmode(self, val):
self["dragmode"] = val
@property
def hovermode(self):
"""
Determines the mode of hover interactions for this scene.
The 'hovermode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['closest', False]
Returns
-------
Any
"""
return self["hovermode"]
@hovermode.setter
def hovermode(self, val):
self["hovermode"] = val
@property
def uirevision(self):
"""
Controls persistence of user-driven changes in camera
attributes. Defaults to `layout.uirevision`.
The 'uirevision' property accepts values of any type
Returns
-------
Any
"""
return self["uirevision"]
@uirevision.setter
def uirevision(self, val):
self["uirevision"] = val
@property
def xaxis(self):
"""
The 'xaxis' property is an instance of XAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.XAxis`
- A dict of string/value properties that will be passed
to the XAxis constructor
Returns
-------
plotly.graph_objs.layout.scene.XAxis
"""
return self["xaxis"]
@xaxis.setter
def xaxis(self, val):
self["xaxis"] = val
@property
def yaxis(self):
"""
The 'yaxis' property is an instance of YAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.YAxis`
- A dict of string/value properties that will be passed
to the YAxis constructor
Returns
-------
plotly.graph_objs.layout.scene.YAxis
"""
return self["yaxis"]
@yaxis.setter
def yaxis(self, val):
self["yaxis"] = val
@property
def zaxis(self):
"""
The 'zaxis' property is an instance of ZAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.ZAxis`
- A dict of string/value properties that will be passed
to the ZAxis constructor
Returns
-------
plotly.graph_objs.layout.scene.ZAxis
"""
return self["zaxis"]
@zaxis.setter
def zaxis(self, val):
self["zaxis"] = val
@property
def _prop_descriptions(self):
return """\
annotations
A tuple of
:class:`plotly.graph_objects.layout.scene.Annotation`
instances or dicts with compatible properties
annotationdefaults
When used in a template (as
layout.template.layout.scene.annotationdefaults), sets
the default property values to use for elements of
layout.scene.annotations
aspectmode
If "cube", this scene's axes are drawn as a cube,
regardless of the axes' ranges. If "data", this scene's
axes are drawn in proportion with the axes' ranges. If
"manual", this scene's axes are drawn in proportion
with the input of "aspectratio" (the default behavior
if "aspectratio" is provided). If "auto", this scene's
axes are drawn using the results of "data" except when
one axis is more than four times the size of the two
others, where in that case the results of "cube" are
used.
aspectratio
Sets this scene's axis aspectratio.
bgcolor
camera
:class:`plotly.graph_objects.layout.scene.Camera`
instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.scene.Domain`
instance or dict with compatible properties
dragmode
Determines the mode of drag interactions for this
scene.
hovermode
Determines the mode of hover interactions for this
scene.
uirevision
Controls persistence of user-driven changes in camera
attributes. Defaults to `layout.uirevision`.
xaxis
:class:`plotly.graph_objects.layout.scene.XAxis`
instance or dict with compatible properties
yaxis
:class:`plotly.graph_objects.layout.scene.YAxis`
instance or dict with compatible properties
zaxis
:class:`plotly.graph_objects.layout.scene.ZAxis`
instance or dict with compatible properties
"""
def __init__(
self,
arg=None,
annotations=None,
annotationdefaults=None,
aspectmode=None,
aspectratio=None,
bgcolor=None,
camera=None,
domain=None,
dragmode=None,
hovermode=None,
uirevision=None,
xaxis=None,
yaxis=None,
zaxis=None,
**kwargs,
):
"""
Construct a new Scene object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Scene`
annotations
A tuple of
:class:`plotly.graph_objects.layout.scene.Annotation`
instances or dicts with compatible properties
annotationdefaults
When used in a template (as
layout.template.layout.scene.annotationdefaults), sets
the default property values to use for elements of
layout.scene.annotations
aspectmode
If "cube", this scene's axes are drawn as a cube,
regardless of the axes' ranges. If "data", this scene's
axes are drawn in proportion with the axes' ranges. If
"manual", this scene's axes are drawn in proportion
with the input of "aspectratio" (the default behavior
if "aspectratio" is provided). If "auto", this scene's
axes are drawn using the results of "data" except when
one axis is more than four times the size of the two
others, where in that case the results of "cube" are
used.
aspectratio
Sets this scene's axis aspectratio.
bgcolor
camera
:class:`plotly.graph_objects.layout.scene.Camera`
instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.scene.Domain`
instance or dict with compatible properties
dragmode
Determines the mode of drag interactions for this
scene.
hovermode
Determines the mode of hover interactions for this
scene.
uirevision
Controls persistence of user-driven changes in camera
attributes. Defaults to `layout.uirevision`.
xaxis
:class:`plotly.graph_objects.layout.scene.XAxis`
instance or dict with compatible properties
yaxis
:class:`plotly.graph_objects.layout.scene.YAxis`
instance or dict with compatible properties
zaxis
:class:`plotly.graph_objects.layout.scene.ZAxis`
instance or dict with compatible properties
Returns
-------
Scene
"""
super().__init__("scene")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.Scene
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Scene`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("annotations", arg, annotations)
self._set_property("annotationdefaults", arg, annotationdefaults)
self._set_property("aspectmode", arg, aspectmode)
self._set_property("aspectratio", arg, aspectratio)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("camera", arg, camera)
self._set_property("domain", arg, domain)
self._set_property("dragmode", arg, dragmode)
self._set_property("hovermode", arg, hovermode)
self._set_property("uirevision", arg, uirevision)
self._set_property("xaxis", arg, xaxis)
self._set_property("yaxis", arg, yaxis)
self._set_property("zaxis", arg, zaxis)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Scene |
python | scipy__scipy | scipy/special/tests/test_pdtr.py | {
"start": 738,
"end": 1366
} | class ____:
def test_value(self):
val = sc.pdtrc(0, 1)
assert_allclose(val, 1 - np.exp(-1), atol=1.5e-7, rtol=0)
def test_m_zero(self):
val = sc.pdtrc([0, 1, 2], 0.0)
assert_array_equal(val, [0, 0, 0])
def test_rounding(self):
double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0)
int_val = sc.pdtrc([0, 1, 2], 1.0)
assert_array_equal(double_val, int_val)
def test_inf(self):
val = sc.pdtrc(np.inf, 1.0)
assert_allclose(val, 0.0, atol=1.5e-7, rtol=0)
def test_domain(self):
val = sc.pdtrc(-1.1, 1.0)
assert np.isnan(val)
| TestPdtrc |
python | networkx__networkx | networkx/tests/test_convert_scipy.py | {
"start": 148,
"end": 10381
} | class ____:
def setup_method(self):
self.G1 = nx.barbell_graph(10, 3)
self.G2 = nx.cycle_graph(10, create_using=nx.DiGraph)
self.G3 = self.create_weighted(nx.Graph())
self.G4 = self.create_weighted(nx.DiGraph())
def test_exceptions(self):
class G:
format = None
pytest.raises(nx.NetworkXError, nx.to_networkx_graph, G)
def create_weighted(self, G):
g = nx.cycle_graph(4)
e = list(g.edges())
source = [u for u, v in e]
dest = [v for u, v in e]
weight = [s + 10 for s in source]
ex = zip(source, dest, weight)
G.add_weighted_edges_from(ex)
return G
def identity_conversion(self, G, A, create_using):
GG = nx.from_scipy_sparse_array(A, create_using=create_using)
assert nx.is_isomorphic(G, GG)
GW = nx.to_networkx_graph(A, create_using=create_using)
assert nx.is_isomorphic(G, GW)
GI = nx.empty_graph(0, create_using).__class__(A)
assert nx.is_isomorphic(G, GI)
ACSR = A.tocsr()
GI = nx.empty_graph(0, create_using).__class__(ACSR)
assert nx.is_isomorphic(G, GI)
ACOO = A.tocoo()
GI = nx.empty_graph(0, create_using).__class__(ACOO)
assert nx.is_isomorphic(G, GI)
ACSC = A.tocsc()
GI = nx.empty_graph(0, create_using).__class__(ACSC)
assert nx.is_isomorphic(G, GI)
AD = A.todense()
GI = nx.empty_graph(0, create_using).__class__(AD)
assert nx.is_isomorphic(G, GI)
AA = A.toarray()
GI = nx.empty_graph(0, create_using).__class__(AA)
assert nx.is_isomorphic(G, GI)
def test_shape(self):
"Conversion from non-square sparse array."
A = sp.sparse.lil_array([[1, 2, 3], [4, 5, 6]])
pytest.raises(nx.NetworkXError, nx.from_scipy_sparse_array, A)
def test_identity_graph_matrix(self):
"Conversion from graph to sparse matrix to graph."
A = nx.to_scipy_sparse_array(self.G1)
self.identity_conversion(self.G1, A, nx.Graph())
def test_identity_digraph_matrix(self):
"Conversion from digraph to sparse matrix to digraph."
A = nx.to_scipy_sparse_array(self.G2)
self.identity_conversion(self.G2, A, nx.DiGraph())
def test_identity_weighted_graph_matrix(self):
"""Conversion from weighted graph to sparse matrix to weighted graph."""
A = nx.to_scipy_sparse_array(self.G3)
self.identity_conversion(self.G3, A, nx.Graph())
def test_identity_weighted_digraph_matrix(self):
"""Conversion from weighted digraph to sparse matrix to weighted digraph."""
A = nx.to_scipy_sparse_array(self.G4)
self.identity_conversion(self.G4, A, nx.DiGraph())
def test_nodelist(self):
"""Conversion from graph to sparse matrix to graph with nodelist."""
P4 = nx.path_graph(4)
P3 = nx.path_graph(3)
nodelist = list(P3.nodes())
A = nx.to_scipy_sparse_array(P4, nodelist=nodelist)
GA = nx.Graph(A)
assert nx.is_isomorphic(GA, P3)
pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=[])
# Test nodelist duplicates.
long_nl = nodelist + [0]
pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=long_nl)
# Test nodelist contains non-nodes
non_nl = [-1, 0, 1, 2]
pytest.raises(nx.NetworkXError, nx.to_scipy_sparse_array, P3, nodelist=non_nl)
def test_weight_keyword(self):
WP4 = nx.Graph()
WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
P4 = nx.path_graph(4)
A = nx.to_scipy_sparse_array(P4)
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
np.testing.assert_equal(
0.5 * A.todense(), nx.to_scipy_sparse_array(WP4).todense()
)
np.testing.assert_equal(
0.3 * A.todense(), nx.to_scipy_sparse_array(WP4, weight="other").todense()
)
def test_format_keyword(self):
WP4 = nx.Graph()
WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
P4 = nx.path_graph(4)
A = nx.to_scipy_sparse_array(P4, format="csr")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="csc")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="coo")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="bsr")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="lil")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="dia")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
A = nx.to_scipy_sparse_array(P4, format="dok")
np.testing.assert_equal(
A.todense(), nx.to_scipy_sparse_array(WP4, weight=None).todense()
)
def test_format_keyword_raise(self):
with pytest.raises(nx.NetworkXError):
WP4 = nx.Graph()
WP4.add_edges_from(
(n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3)
)
P4 = nx.path_graph(4)
nx.to_scipy_sparse_array(P4, format="any_other")
def test_null_raise(self):
with pytest.raises(nx.NetworkXError):
nx.to_scipy_sparse_array(nx.Graph())
def test_empty(self):
G = nx.Graph()
G.add_node(1)
M = nx.to_scipy_sparse_array(G)
np.testing.assert_equal(M.toarray(), np.array([[0]]))
def test_ordering(self):
G = nx.DiGraph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
M = nx.to_scipy_sparse_array(G, nodelist=[3, 2, 1])
np.testing.assert_equal(
M.toarray(), np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
)
def test_selfloop_graph(self):
G = nx.Graph([(1, 1)])
M = nx.to_scipy_sparse_array(G)
np.testing.assert_equal(M.toarray(), np.array([[1]]))
G.add_edges_from([(2, 3), (3, 4)])
M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
np.testing.assert_equal(
M.toarray(), np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
)
def test_selfloop_digraph(self):
G = nx.DiGraph([(1, 1)])
M = nx.to_scipy_sparse_array(G)
np.testing.assert_equal(M.toarray(), np.array([[1]]))
G.add_edges_from([(2, 3), (3, 4)])
M = nx.to_scipy_sparse_array(G, nodelist=[2, 3, 4])
np.testing.assert_equal(
M.toarray(), np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
)
def test_from_scipy_sparse_array_parallel_edges(self):
"""Tests that the :func:`networkx.from_scipy_sparse_array` function
interprets integer weights as the number of parallel edges when
creating a multigraph.
"""
A = sp.sparse.csr_array([[1, 1], [1, 2]])
# First, with a simple graph, each integer entry in the adjacency
# matrix is interpreted as the weight of a single edge in the graph.
expected = nx.DiGraph()
edges = [(0, 0), (0, 1), (1, 0)]
expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
expected.add_edge(1, 1, weight=2)
actual = nx.from_scipy_sparse_array(
A, parallel_edges=True, create_using=nx.DiGraph
)
assert graphs_equal(actual, expected)
actual = nx.from_scipy_sparse_array(
A, parallel_edges=False, create_using=nx.DiGraph
)
assert graphs_equal(actual, expected)
# Now each integer entry in the adjacency matrix is interpreted as the
# number of parallel edges in the graph if the appropriate keyword
# argument is specified.
edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
expected = nx.MultiDiGraph()
expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
actual = nx.from_scipy_sparse_array(
A, parallel_edges=True, create_using=nx.MultiDiGraph
)
assert graphs_equal(actual, expected)
expected = nx.MultiDiGraph()
expected.add_edges_from(set(edges), weight=1)
# The sole self-loop (edge 0) on vertex 1 should have weight 2.
expected[1][1][0]["weight"] = 2
actual = nx.from_scipy_sparse_array(
A, parallel_edges=False, create_using=nx.MultiDiGraph
)
assert graphs_equal(actual, expected)
def test_symmetric(self):
"""Tests that a symmetric matrix has edges added only once to an
undirected multigraph when using
:func:`networkx.from_scipy_sparse_array`.
"""
A = sp.sparse.csr_array([[0, 1], [1, 0]])
G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph)
expected = nx.MultiGraph()
expected.add_edge(0, 1, weight=1)
assert graphs_equal(G, expected)
@pytest.mark.parametrize("sparse_format", ("csr", "csc", "dok"))
def test_from_scipy_sparse_array_formats(sparse_format):
"""Test all formats supported by _generate_weighted_edges."""
# trinode complete graph with non-uniform edge weights
expected = nx.Graph()
expected.add_edges_from(
[
(0, 1, {"weight": 3}),
(0, 2, {"weight": 2}),
(1, 0, {"weight": 3}),
(1, 2, {"weight": 1}),
(2, 0, {"weight": 2}),
(2, 1, {"weight": 1}),
]
)
A = sp.sparse.coo_array([[0, 3, 2], [3, 0, 1], [2, 1, 0]]).asformat(sparse_format)
assert graphs_equal(expected, nx.from_scipy_sparse_array(A))
| TestConvertScipy |
python | encode__django-rest-framework | tests/test_validation.py | {
"start": 3791,
"end": 3964
} | class ____(serializers.ModelSerializer):
class Meta:
model = ValidationMaxValueValidatorModel
fields = '__all__'
| ValidationMaxValueValidatorModelSerializer |
python | joke2k__faker | tests/providers/test_lorem.py | {
"start": 39051,
"end": 41872
} | class ____:
"""Test es_AR lorem provider"""
word_list = [word.lower() for word in EsArLoremProvider.word_list]
def test_paragraph(self, faker, num_samples):
num_sentences = 10
for _ in range(num_samples):
paragraph = faker.paragraph(nb_sentences=num_sentences)
assert isinstance(paragraph, str)
words = paragraph.replace(".", "").split()
assert all(word.lower() in self.word_list for word in words)
def test_paragraphs(self, faker, num_samples):
num_paragraphs = 5
for _ in range(num_samples):
paragraphs = faker.paragraphs(nb=num_paragraphs)
for paragraph in paragraphs:
assert isinstance(paragraph, str)
words = paragraph.replace(".", "").split()
assert all(word.lower() in self.word_list for word in words)
def test_sentence(self, faker, num_samples):
num_words = 10
for _ in range(num_samples):
sentence = faker.sentence(nb_words=num_words)
assert isinstance(sentence, str)
words = sentence.replace(".", "").split()
assert all(word.lower() in self.word_list for word in words)
def test_sentences(self, faker, num_samples):
num_sentences = 5
for _ in range(num_samples):
sentences = faker.sentences(nb=num_sentences)
for sentence in sentences:
assert isinstance(sentence, str)
words = sentence.replace(".", "").split()
assert all(word.lower() in self.word_list for word in words)
def test_text(self, faker, num_samples):
num_chars = 25
for _ in range(num_samples):
text = faker.text(max_nb_chars=num_chars)
assert isinstance(text, str)
words = re.sub(r"[.\n]+", " ", text).split()
assert all(word.lower() in self.word_list for word in words)
def test_texts(self, faker, num_samples):
num_texts = 5
num_chars = 25
for _ in range(num_samples):
texts = faker.texts(max_nb_chars=num_chars, nb_texts=num_texts)
for text in texts:
assert isinstance(text, str)
words = re.sub(r"[.\n]+", " ", text).split()
assert all(word.lower() in self.word_list for word in words)
def test_word(self, faker, num_samples):
for _ in range(num_samples):
word = faker.word()
assert isinstance(word, str) and word in EsEsLoremProvider.word_list
def test_words(self, faker, num_samples):
num_words = 5
for _ in range(num_samples):
words = faker.words(num_words)
assert all(isinstance(word, str) and word in EsEsLoremProvider.word_list for word in words)
| TestEsAr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.