hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72c35766d755e29c14dd797ad91e44ab34914bc | 1,757 | py | Python | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | loading.py | hawkarcane/Hangman | 905640b087b747e6934ed7f18829b12784d0ed08 | [
"MIT"
] | null | null | null | #!/usr/bin/python
##### ~ http://stackoverflow.com/questions/7960600/python-tkinter-display-animated-gif-using-pil ~
## source of code can be found at the above web page, I have modified the code to suit my needs.
from Tkinter import *
from PIL import Image, ImageTk
class MyLabel(Label):
def __init__(self, master, filename):
im = Image.open(filename)
seq = []
try:
while 1:
seq.append(im.copy())
im.seek(len(seq)) # skip to next frame
except EOFError:
pass # we're done
try:
self.delay = im.info['duration']
except KeyError:
self.delay = 100
first = seq[0].convert('RGBA')
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0],
highlightthickness=0, bg='white')
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
root = Tk()
anim = MyLabel(root, 'HangMan_img/loading/google.gif')
anim.place(x=140, y=90)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.config(bg='white')
root.overrideredirect(1)
x = screen_width / 2 - 500 / 2
y = screen_height / 2 - 400 / 2
root.geometry('%dx%d+%d+%d' % (500, 400, x, y))
anim.after(2000, root.destroy)
root.mainloop()
| 25.463768 | 98 | 0.59078 |
)
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0],
highlightthickness=0, bg='white')
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
root = Tk()
anim = MyLabel(root, 'HangMan_img/loading/google.gif')
anim.place(x=140, y=90)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.config(bg='white')
root.overrideredirect(1)
x = screen_width / 2 - 500 / 2
y = screen_height / 2 - 400 / 2
root.geometry('%dx%d+%d+%d' % (500, 400, x, y))
anim.after(2000, root.destroy)
root.mainloop()
| true | true |
f72c37376707907e2c5dcac2d81f5c1e1aad10ec | 397 | py | Python | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | maillerApp/wsgi.py | Stblacq/Xmailer | 37cfd79f4c4b616fd449e78ef5587d1300090063 | [
"bzip2-1.0.6"
] | null | null | null | """
WSGI config for maillerApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maillerApp.settings')
application = get_wsgi_application()
| 23.352941 | 78 | 0.788413 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maillerApp.settings')
application = get_wsgi_application()
| true | true |
f72c3830b52635d5830fd38ce38096456c2b9555 | 388 | py | Python | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | 21 | 2020-08-24T13:27:03.000Z | 2021-10-15T09:17:46.000Z | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | null | null | null | bbb/migrations/0007_room_hangout_room.py | cmd-ev/voctoconf | 5d2c1ca4f1da01b66983f5a562eb8eb6babe0452 | [
"MIT"
] | 5 | 2020-08-25T16:34:51.000Z | 2021-02-19T04:48:10.000Z | # Generated by Django 2.2.15 on 2020-08-14 21:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bbb', '0006_auto_20200813_1954'),
]
operations = [
migrations.AddField(
model_name='room',
name='hangout_room',
field=models.BooleanField(default=False),
),
]
| 20.421053 | 53 | 0.600515 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bbb', '0006_auto_20200813_1954'),
]
operations = [
migrations.AddField(
model_name='room',
name='hangout_room',
field=models.BooleanField(default=False),
),
]
| true | true |
f72c386148900925f8177edd4f614faab95b090b | 704 | py | Python | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11 | 2015-10-04T02:17:46.000Z | 2018-02-07T18:23:00.000Z | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 22 | 2017-08-01T22:45:10.000Z | 2022-03-10T07:46:31.000Z | var/spack/repos/builtin/packages/r-biocversion/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 4 | 2016-06-10T17:57:39.000Z | 2018-09-11T04:59:38.000Z | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBiocversion(RPackage):
"""Set the appropriate version of Bioconductor packages.
This package provides repository information for the appropriate
version of Bioconductor."""
bioc = "BiocVersion"
version('3.14.0', commit='aa56d93d0ea5dcdbf301f120502981740fd91e1e')
version('3.12.0', commit='23b971963c6b73550a7e330dab5a046d58ce0223')
depends_on('r@4.0.0:', type=('build', 'run'))
depends_on('r@4.1.0:', type=('build', 'run'), when='@3.14.0:')
| 32 | 73 | 0.72017 |
from spack import *
class RBiocversion(RPackage):
bioc = "BiocVersion"
version('3.14.0', commit='aa56d93d0ea5dcdbf301f120502981740fd91e1e')
version('3.12.0', commit='23b971963c6b73550a7e330dab5a046d58ce0223')
depends_on('r@4.0.0:', type=('build', 'run'))
depends_on('r@4.1.0:', type=('build', 'run'), when='@3.14.0:')
| true | true |
f72c389a4d7bf918cd68d55d1048f404a1165eda | 274,814 | py | Python | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xarray/core/dataset.py | aha66/xarray | 3cbd21aa8fd3a57c0dd324f2a276d83829518331 | [
"CC-BY-4.0",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | import copy
import datetime
import functools
import inspect
import sys
import warnings
from collections import defaultdict
from distutils.version import LooseVersion
from html import escape
from numbers import Number
from operator import methodcaller
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import pandas as pd
import xarray as xr
from ..coding.cftimeindex import _parse_array_of_cftime_strings
from ..plot.dataset_plot import _Dataset_PlotMethods
from . import (
alignment,
dtypes,
duck_array_ops,
formatting,
formatting_html,
groupby,
ops,
resample,
rolling,
utils,
weighted,
)
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
from .common import (
DataWithCoords,
ImplementsDatasetReduce,
_contains_datetime_like_objects,
)
from .coordinates import (
DatasetCoordinates,
assert_coordinate_consistent,
remap_label_indexers,
)
from .duck_array_ops import datetime_to_numeric
from .indexes import (
Indexes,
default_indexes,
isel_variable_and_index,
propagate_indexes,
remove_unused_levels_categories,
roll_index,
)
from .indexing import is_fancy_indexer
from .merge import (
dataset_merge_method,
dataset_update_method,
merge_coordinates_without_align,
merge_data_and_coords,
)
from .missing import get_clean_interp_index
from .options import OPTIONS, _get_keep_attrs
from .pycompat import is_duck_dask_array, sparse_array_type
from .utils import (
Default,
Frozen,
HybridMappingProxy,
SortedKeysDict,
_default,
decode_numpy_dict_values,
drop_dims_from_indexers,
either_dict_or_kwargs,
hashable,
infix_dims,
is_dict_like,
is_scalar,
maybe_wrap_array,
)
from .variable import (
IndexVariable,
Variable,
as_variable,
assert_unique_multiindex_level_names,
broadcast_variables,
)
if TYPE_CHECKING:
from ..backends import AbstractDataStore, ZarrStore
from .dataarray import DataArray
from .merge import CoercibleMapping
T_DSorDA = TypeVar("T_DSorDA", DataArray, "Dataset")
try:
from dask.delayed import Delayed
except ImportError:
Delayed = None
# list of attributes of pd.DatetimeIndex that are ndarrays of time info
_DATETIMEINDEX_COMPONENTS = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"microsecond",
"nanosecond",
"date",
"time",
"dayofyear",
"weekofyear",
"dayofweek",
"quarter",
]
def _get_virtual_variable(
variables, key: Hashable, level_vars: Mapping = None, dim_sizes: Mapping = None
) -> Tuple[Hashable, Hashable, Variable]:
"""Get a virtual variable (e.g., 'time.year' or a MultiIndex level)
from a dict of xarray.Variable objects (if possible)
"""
if level_vars is None:
level_vars = {}
if dim_sizes is None:
dim_sizes = {}
if key in dim_sizes:
data = pd.Index(range(dim_sizes[key]), name=key)
variable = IndexVariable((key,), data)
return key, key, variable
if not isinstance(key, str):
raise KeyError(key)
split_key = key.split(".", 1)
var_name: Optional[str]
if len(split_key) == 2:
ref_name, var_name = split_key
elif len(split_key) == 1:
ref_name, var_name = key, None
else:
raise KeyError(key)
if ref_name in level_vars:
dim_var = variables[level_vars[ref_name]]
ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
else:
ref_var = variables[ref_name]
if var_name is None:
virtual_var = ref_var
var_name = key
else:
if _contains_datetime_like_objects(ref_var):
ref_var = xr.DataArray(ref_var)
data = getattr(ref_var.dt, var_name).data
else:
data = getattr(ref_var, var_name).data
virtual_var = Variable(ref_var.dims, data)
return ref_name, var_name, virtual_var
def calculate_dimensions(variables: Mapping[Hashable, Variable]) -> Dict[Hashable, int]:
"""Calculate the dimensions corresponding to a set of variables.
Returns dictionary mapping from dimension names to sizes. Raises ValueError
if any of the dimension sizes conflict.
"""
dims: Dict[Hashable, int] = {}
last_used = {}
scalar_vars = {k for k, v in variables.items() if not v.dims}
for k, var in variables.items():
for dim, size in zip(var.dims, var.shape):
if dim in scalar_vars:
raise ValueError(
"dimension %r already exists as a scalar variable" % dim
)
if dim not in dims:
dims[dim] = size
last_used[dim] = k
elif dims[dim] != size:
raise ValueError(
"conflicting sizes for dimension %r: "
"length %s on %r and length %s on %r"
% (dim, size, k, dims[dim], last_used[dim])
)
return dims
def merge_indexes(
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
append: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
"""Merge variables into multi-indexes.
Not public API. Used in Dataset and DataArray set_index
methods.
"""
vars_to_replace: Dict[Hashable, Variable] = {}
vars_to_remove: List[Hashable] = []
dims_to_replace: Dict[Hashable, Hashable] = {}
error_msg = "{} is not the name of an existing variable."
for dim, var_names in indexes.items():
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
var_names = [var_names]
names: List[Hashable] = []
codes: List[List[int]] = []
levels: List[List[int]] = []
current_index_variable = variables.get(dim)
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
if (
current_index_variable is not None
and var.dims != current_index_variable.dims
):
raise ValueError(
"dimension mismatch between %r %s and %r %s"
% (dim, current_index_variable.dims, n, var.dims)
)
if current_index_variable is not None and append:
current_index = current_index_variable.to_index()
if isinstance(current_index, pd.MultiIndex):
names.extend(current_index.names)
codes.extend(current_index.codes)
levels.extend(current_index.levels)
else:
names.append("%s_level_0" % dim)
cat = pd.Categorical(current_index.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
if not len(names) and len(var_names) == 1:
idx = pd.Index(variables[var_names[0]].values)
else: # MultiIndex
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
names.append(n)
cat = pd.Categorical(var.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
idx = pd.MultiIndex(levels, codes, names=names)
for n in names:
dims_to_replace[n] = dim
vars_to_replace[dim] = IndexVariable(dim, idx)
vars_to_remove.extend(var_names)
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}
new_variables.update(vars_to_replace)
# update dimensions if necessary, GH: 3512
for k, v in new_variables.items():
if any(d in dims_to_replace for d in v.dims):
new_dims = [dims_to_replace.get(d, d) for d in v.dims]
new_variables[k] = v._replace(dims=new_dims)
new_coord_names = coord_names | set(vars_to_replace)
new_coord_names -= set(vars_to_remove)
return new_variables, new_coord_names
def split_indexes(
dims_or_levels: Union[Hashable, Sequence[Hashable]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
level_coords: Mapping[Hashable, Hashable],
drop: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
"""Extract (multi-)indexes (levels) as variables.
Not public API. Used in Dataset and DataArray reset_index
methods.
"""
if isinstance(dims_or_levels, str) or not isinstance(dims_or_levels, Sequence):
dims_or_levels = [dims_or_levels]
dim_levels: DefaultDict[Any, List[Hashable]] = defaultdict(list)
dims = []
for k in dims_or_levels:
if k in level_coords:
dim_levels[level_coords[k]].append(k)
else:
dims.append(k)
vars_to_replace = {}
vars_to_create: Dict[Hashable, Variable] = {}
vars_to_remove = []
for d in dims:
index = variables[d].to_index()
if isinstance(index, pd.MultiIndex):
dim_levels[d] = index.names
else:
vars_to_remove.append(d)
if not drop:
vars_to_create[str(d) + "_"] = Variable(d, index, variables[d].attrs)
for d, levs in dim_levels.items():
index = variables[d].to_index()
if len(levs) == index.nlevels:
vars_to_remove.append(d)
else:
vars_to_replace[d] = IndexVariable(d, index.droplevel(levs))
if not drop:
for lev in levs:
idx = index.get_level_values(lev)
vars_to_create[idx.name] = Variable(d, idx, variables[d].attrs)
new_variables = dict(variables)
for v in set(vars_to_remove):
del new_variables[v]
new_variables.update(vars_to_replace)
new_variables.update(vars_to_create)
new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove)
return new_variables, new_coord_names
def _assert_empty(args: tuple, msg: str = "%s") -> None:
if args:
raise ValueError(msg % args)
def _check_chunks_compatibility(var, chunks, preferred_chunks):
for dim in var.dims:
if dim not in chunks or (dim not in preferred_chunks):
continue
preferred_chunks_dim = preferred_chunks.get(dim)
chunks_dim = chunks.get(dim)
if isinstance(chunks_dim, int):
chunks_dim = (chunks_dim,)
else:
chunks_dim = chunks_dim[:-1]
if any(s % preferred_chunks_dim for s in chunks_dim):
warnings.warn(
f"Specified Dask chunks {chunks[dim]} would separate "
f"on disks chunk shape {preferred_chunks[dim]} for dimension {dim}. "
"This could degrade performance. "
"Consider rechunking after loading instead.",
stacklevel=2,
)
def _get_chunk(var, chunks):
# chunks need to be explicity computed to take correctly into accout
# backend preferred chunking
import dask.array as da
if isinstance(var, IndexVariable):
return {}
if isinstance(chunks, int) or (chunks == "auto"):
chunks = dict.fromkeys(var.dims, chunks)
preferred_chunks = var.encoding.get("preferred_chunks", {})
preferred_chunks_list = [
preferred_chunks.get(dim, shape) for dim, shape in zip(var.dims, var.shape)
]
chunks_list = [
chunks.get(dim, None) or preferred_chunks.get(dim, None) for dim in var.dims
]
output_chunks_list = da.core.normalize_chunks(
chunks_list,
shape=var.shape,
dtype=var.dtype,
previous_chunks=preferred_chunks_list,
)
output_chunks = dict(zip(var.dims, output_chunks_list))
_check_chunks_compatibility(var, output_chunks, preferred_chunks)
return output_chunks
def _maybe_chunk(
name,
var,
chunks,
token=None,
lock=None,
name_prefix="xarray-",
overwrite_encoded_chunks=False,
):
from dask.base import tokenize
if chunks is not None:
chunks = {dim: chunks[dim] for dim in var.dims if dim in chunks}
if var.ndim:
# when rechunking by different amounts, make sure dask names change
# by provinding chunks as an input to tokenize.
# subtle bugs result otherwise. see GH3350
token2 = tokenize(name, token if token else var._data, chunks)
name2 = f"{name_prefix}{name}-{token2}"
var = var.chunk(chunks, name=name2, lock=lock)
if overwrite_encoded_chunks and var.chunks is not None:
var.encoding["chunks"] = tuple(x[0] for x in var.chunks)
return var
else:
return var
def as_dataset(obj: Any) -> "Dataset":
"""Cast the given object to a Dataset.
Handles Datasets, DataArrays and dictionaries of variables. A new Dataset
object is only created if the provided object is not already one.
"""
if hasattr(obj, "to_dataset"):
obj = obj.to_dataset()
if not isinstance(obj, Dataset):
obj = Dataset(obj)
return obj
def _get_func_args(func, param_names):
"""Use `inspect.signature` to try accessing `func` args. Otherwise, ensure
they are provided by user.
"""
try:
func_args = inspect.signature(func).parameters
except ValueError:
func_args = {}
if not param_names:
raise ValueError(
"Unable to inspect `func` signature, and `param_names` was not provided."
)
if param_names:
params = param_names
else:
params = list(func_args)[1:]
if any(
[(p.kind in [p.VAR_POSITIONAL, p.VAR_KEYWORD]) for p in func_args.values()]
):
raise ValueError(
"`param_names` must be provided because `func` takes variable length arguments."
)
return params, func_args
def _initialize_curvefit_params(params, p0, bounds, func_args):
"""Set initial guess and bounds for curvefit.
Priority: 1) passed args 2) func signature 3) scipy defaults
"""
def _initialize_feasible(lb, ub):
# Mimics functionality of scipy.optimize.minpack._initialize_feasible
lb_finite = np.isfinite(lb)
ub_finite = np.isfinite(ub)
p0 = np.nansum(
[
0.5 * (lb + ub) * int(lb_finite & ub_finite),
(lb + 1) * int(lb_finite & ~ub_finite),
(ub - 1) * int(~lb_finite & ub_finite),
]
)
return p0
param_defaults = {p: 1 for p in params}
bounds_defaults = {p: (-np.inf, np.inf) for p in params}
for p in params:
if p in func_args and func_args[p].default is not func_args[p].empty:
param_defaults[p] = func_args[p].default
if p in bounds:
bounds_defaults[p] = tuple(bounds[p])
if param_defaults[p] < bounds[p][0] or param_defaults[p] > bounds[p][1]:
param_defaults[p] = _initialize_feasible(bounds[p][0], bounds[p][1])
if p in p0:
param_defaults[p] = p0[p]
return param_defaults, bounds_defaults
class DataVariables(Mapping[Hashable, "DataArray"]):
__slots__ = ("_dataset",)
def __init__(self, dataset: "Dataset"):
self._dataset = dataset
def __iter__(self) -> Iterator[Hashable]:
return (
key
for key in self._dataset._variables
if key not in self._dataset._coord_names
)
def __len__(self) -> int:
return len(self._dataset._variables) - len(self._dataset._coord_names)
def __contains__(self, key: Hashable) -> bool:
return key in self._dataset._variables and key not in self._dataset._coord_names
def __getitem__(self, key: Hashable) -> "DataArray":
if key not in self._dataset._coord_names:
return cast("DataArray", self._dataset[key])
raise KeyError(key)
def __repr__(self) -> str:
return formatting.data_vars_repr(self)
@property
def variables(self) -> Mapping[Hashable, Variable]:
all_variables = self._dataset.variables
return Frozen({k: all_variables[k] for k in self})
def _ipython_key_completions_(self):
"""Provide method for the key-autocompletions in IPython. """
return [
key
for key in self._dataset._ipython_key_completions_()
if key not in self._dataset._coord_names
]
class _LocIndexer:
__slots__ = ("dataset",)
def __init__(self, dataset: "Dataset"):
self.dataset = dataset
def __getitem__(self, key: Mapping[Hashable, Any]) -> "Dataset":
if not utils.is_dict_like(key):
raise TypeError("can only lookup dictionaries from Dataset.loc")
return self.dataset.sel(key)
class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
"""A multi-dimensional, in memory, array database.
A dataset resembles an in-memory representation of a NetCDF file,
and consists of variables, coordinates and attributes which
together form a self describing dataset.
Dataset implements the mapping interface with keys given by variable
names and values given by DataArray objects for each variable name.
One dimensional variables with name equal to their dimension are
index coordinates used for label based indexing.
To load data from a file or file-like object, use the `open_dataset`
function.
Parameters
----------
data_vars : dict-like, optional
A mapping from variable names to :py:class:`~xarray.DataArray`
objects, :py:class:`~xarray.Variable` objects or to tuples of
the form ``(dims, data[, attrs])`` which can be used as
arguments to create a new ``Variable``. Each dimension must
have the same length in all variables in which it appears.
The following notations are accepted:
- mapping {var name: DataArray}
- mapping {var name: Variable}
- mapping {var name: (dimension name, array-like)}
- mapping {var name: (tuple of dimension names, array-like)}
- mapping {dimension name: array-like}
(it will be automatically moved to coords, see below)
Each dimension must have the same length in all variables in
which it appears.
coords : dict-like, optional
Another mapping in similar form as the `data_vars` argument,
except the each item is saved on the dataset as a "coordinate".
These variables have an associated meaning: they describe
constant/fixed/independent quantities, unlike the
varying/measured/dependent quantities that belong in
`variables`. Coordinates values may be given by 1-dimensional
arrays or scalars, in which case `dims` do not need to be
supplied: 1D arrays will be assumed to give index values along
the dimension with the same name.
The following notations are accepted:
- mapping {coord name: DataArray}
- mapping {coord name: Variable}
- mapping {coord name: (dimension name, array-like)}
- mapping {coord name: (tuple of dimension names, array-like)}
- mapping {dimension name: array-like}
(the dimension name is implicitly set to be the same as the
coord name)
The last notation implies that the coord name is the same as
the dimension name.
attrs : dict-like, optional
Global attributes to save on this dataset.
Examples
--------
Create data:
>>> np.random.seed(0)
>>> temperature = 15 + 8 * np.random.randn(2, 2, 3)
>>> precipitation = 10 * np.random.rand(2, 2, 3)
>>> lon = [[-99.83, -99.32], [-99.79, -99.23]]
>>> lat = [[42.25, 42.21], [42.63, 42.59]]
>>> time = pd.date_range("2014-09-06", periods=3)
>>> reference_time = pd.Timestamp("2014-09-05")
Initialize a dataset with multiple dimensions:
>>> ds = xr.Dataset(
... data_vars=dict(
... temperature=(["x", "y", "time"], temperature),
... precipitation=(["x", "y", "time"], precipitation),
... ),
... coords=dict(
... lon=(["x", "y"], lon),
... lat=(["x", "y"], lat),
... time=time,
... reference_time=reference_time,
... ),
... attrs=dict(description="Weather related data."),
... )
>>> ds
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
Attributes:
description: Weather related data.
Find out where the coldest temperature was and what values the
other variables had:
>>> ds.isel(ds.temperature.argmin(...))
<xarray.Dataset>
Dimensions: ()
Coordinates:
lon float64 -99.32
lat float64 42.21
time datetime64[ns] 2014-09-08
reference_time datetime64[ns] 2014-09-05
Data variables:
temperature float64 7.182
precipitation float64 8.326
Attributes:
description: Weather related data.
"""
_attrs: Optional[Dict[Hashable, Any]]
_cache: Dict[str, Any]
_coord_names: Set[Hashable]
_dims: Dict[Hashable, int]
_encoding: Optional[Dict[Hashable, Any]]
_close: Optional[Callable[[], None]]
_indexes: Optional[Dict[Hashable, pd.Index]]
_variables: Dict[Hashable, Variable]
__slots__ = (
"_attrs",
"_cache",
"_coord_names",
"_dims",
"_encoding",
"_close",
"_indexes",
"_variables",
"__weakref__",
)
_groupby_cls = groupby.DatasetGroupBy
_rolling_cls = rolling.DatasetRolling
_coarsen_cls = rolling.DatasetCoarsen
_resample_cls = resample.DatasetResample
_weighted_cls = weighted.DatasetWeighted
def __init__(
self,
# could make a VariableArgs to use more generally, and refine these
# categories
data_vars: Mapping[Hashable, Any] = None,
coords: Mapping[Hashable, Any] = None,
attrs: Mapping[Hashable, Any] = None,
):
# TODO(shoyer): expose indexes as a public argument in __init__
if data_vars is None:
data_vars = {}
if coords is None:
coords = {}
both_data_and_coords = set(data_vars) & set(coords)
if both_data_and_coords:
raise ValueError(
"variables %r are found in both data_vars and coords"
% both_data_and_coords
)
if isinstance(coords, Dataset):
coords = coords.variables
variables, coord_names, dims, indexes, _ = merge_data_and_coords(
data_vars, coords, compat="broadcast_equals"
)
self._attrs = dict(attrs) if attrs is not None else None
self._close = None
self._encoding = None
self._variables = variables
self._coord_names = coord_names
self._dims = dims
self._indexes = indexes
@classmethod
def load_store(cls, store, decoder=None) -> "Dataset":
"""Create a new dataset from the contents of a backends.*DataStore
object
"""
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj.set_close(store.close)
return obj
@property
def variables(self) -> Mapping[Hashable, Variable]:
"""Low level interface to Dataset contents as dict of Variable objects.
This ordered dictionary is frozen to prevent mutation that could
violate Dataset invariants. It contains all variable objects
constituting the Dataset, including both data variables and
coordinates.
"""
return Frozen(self._variables)
@property
def attrs(self) -> Dict[Hashable, Any]:
"""Dictionary of global attributes on this dataset"""
if self._attrs is None:
self._attrs = {}
return self._attrs
@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)
@property
def encoding(self) -> Dict:
"""Dictionary of global encoding attributes on this dataset"""
if self._encoding is None:
self._encoding = {}
return self._encoding
@encoding.setter
def encoding(self, value: Mapping) -> None:
self._encoding = dict(value)
@property
def dims(self) -> Mapping[Hashable, int]:
"""Mapping from dimension names to lengths.
Cannot be modified directly, but is updated when adding new variables.
Note that type of this object differs from `DataArray.dims`.
See `Dataset.sizes` and `DataArray.sizes` for consistently named
properties.
"""
return Frozen(SortedKeysDict(self._dims))
@property
def sizes(self) -> Mapping[Hashable, int]:
"""Mapping from dimension names to lengths.
Cannot be modified directly, but is updated when adding new variables.
This is an alias for `Dataset.dims` provided for the benefit of
consistency with `DataArray.sizes`.
See Also
--------
DataArray.sizes
"""
return self.dims
def load(self, **kwargs) -> "Dataset":
"""Manually trigger loading and/or computation of this dataset's data
from disk or a remote source into memory and return this dataset.
Unlike compute, the original dataset is modified and returned.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask.array as da
# evaluate all the dask arrays simultaneously
evaluated_data = da.compute(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
# load everything else sequentially
for k, v in self.variables.items():
if k not in lazy_data:
v.load()
return self
def __dask_tokenize__(self):
from dask.base import normalize_token
return normalize_token(
(type(self), self._variables, self._coord_names, self._attrs)
)
def __dask_graph__(self):
graphs = {k: v.__dask_graph__() for k, v in self.variables.items()}
graphs = {k: v for k, v in graphs.items() if v is not None}
if not graphs:
return None
else:
try:
from dask.highlevelgraph import HighLevelGraph
return HighLevelGraph.merge(*graphs.values())
except ImportError:
from dask import sharedict
return sharedict.merge(*graphs.values())
def __dask_keys__(self):
import dask
return [
v.__dask_keys__()
for v in self.variables.values()
if dask.is_dask_collection(v)
]
def __dask_layers__(self):
import dask
return sum(
[
v.__dask_layers__()
for v in self.variables.values()
if dask.is_dask_collection(v)
],
(),
)
@property
def __dask_optimize__(self):
import dask.array as da
return da.Array.__dask_optimize__
@property
def __dask_scheduler__(self):
import dask.array as da
return da.Array.__dask_scheduler__
def __dask_postcompute__(self):
return self._dask_postcompute, ()
def __dask_postpersist__(self):
return self._dask_postpersist, ()
def _dask_postcompute(self, results: "Iterable[Variable]") -> "Dataset":
import dask
variables = {}
results_iter = iter(results)
for k, v in self._variables.items():
if dask.is_dask_collection(v):
rebuild, args = v.__dask_postcompute__()
v = rebuild(next(results_iter), *args)
variables[k] = v
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def _dask_postpersist(
self, dsk: Mapping, *, rename: Mapping[str, str] = None
) -> "Dataset":
from dask import is_dask_collection
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import cull
variables = {}
for k, v in self._variables.items():
if not is_dask_collection(v):
variables[k] = v
continue
if isinstance(dsk, HighLevelGraph):
# dask >= 2021.3
# __dask_postpersist__() was called by dask.highlevelgraph.
# Don't use dsk.cull(), as we need to prevent partial layers:
# https://github.com/dask/dask/issues/7137
layers = v.__dask_layers__()
if rename:
layers = [rename.get(k, k) for k in layers]
dsk2 = dsk.cull_layers(layers)
elif rename: # pragma: nocover
# At the moment of writing, this is only for forward compatibility.
# replace_name_in_key requires dask >= 2021.3.
from dask.base import flatten, replace_name_in_key
keys = [
replace_name_in_key(k, rename) for k in flatten(v.__dask_keys__())
]
dsk2, _ = cull(dsk, keys)
else:
# __dask_postpersist__() was called by dask.optimize or dask.persist
dsk2, _ = cull(dsk, v.__dask_keys__())
rebuild, args = v.__dask_postpersist__()
# rename was added in dask 2021.3
kwargs = {"rename": rename} if rename else {}
variables[k] = rebuild(dsk2, *args, **kwargs)
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def compute(self, **kwargs) -> "Dataset":
"""Manually trigger loading and/or computation of this dataset's data
from disk or a remote source into memory and return a new dataset.
Unlike load, the original dataset is left unaltered.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.compute``.
See Also
--------
dask.compute
"""
new = self.copy(deep=False)
return new.load(**kwargs)
def _persist_inplace(self, **kwargs) -> "Dataset":
"""Persist all Dask arrays in memory"""
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask
# evaluate all the dask arrays simultaneously
evaluated_data = dask.persist(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
return self
def persist(self, **kwargs) -> "Dataset":
"""Trigger computation, keeping data as dask arrays
This operation can be used to trigger computation on underlying dask
arrays, similar to ``.compute()`` or ``.load()``. However this
operation keeps the data as dask arrays. This is particularly useful
when using the dask.distributed scheduler and you want to load a large
amount of data into distributed memory.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.persist``.
See Also
--------
dask.persist
"""
new = self.copy(deep=False)
return new._persist_inplace(**kwargs)
@classmethod
def _construct_direct(
cls,
variables,
coord_names,
dims=None,
attrs=None,
indexes=None,
encoding=None,
close=None,
):
"""Shortcut around __init__ for internal use when we want to skip
costly validation
"""
if dims is None:
dims = calculate_dimensions(variables)
obj = object.__new__(cls)
obj._variables = variables
obj._coord_names = coord_names
obj._dims = dims
obj._indexes = indexes
obj._attrs = attrs
obj._close = close
obj._encoding = encoding
return obj
def _replace(
self,
variables: Dict[Hashable, Variable] = None,
coord_names: Set[Hashable] = None,
dims: Dict[Any, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Any, pd.Index], None, Default] = _default,
encoding: Union[dict, None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Fastpath constructor for internal use.
Returns an object with optionally with replaced attributes.
Explicitly passed arguments are *not* copied when placed on the new
dataset. It is up to the caller to ensure that they have the right type
and are not used elsewhere.
"""
if inplace:
if variables is not None:
self._variables = variables
if coord_names is not None:
self._coord_names = coord_names
if dims is not None:
self._dims = dims
if attrs is not _default:
self._attrs = attrs
if indexes is not _default:
self._indexes = indexes
if encoding is not _default:
self._encoding = encoding
obj = self
else:
if variables is None:
variables = self._variables.copy()
if coord_names is None:
coord_names = self._coord_names.copy()
if dims is None:
dims = self._dims.copy()
if attrs is _default:
attrs = copy.copy(self._attrs)
if indexes is _default:
indexes = copy.copy(self._indexes)
if encoding is _default:
encoding = copy.copy(self._encoding)
obj = self._construct_direct(
variables, coord_names, dims, attrs, indexes, encoding
)
return obj
def _replace_with_new_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Hashable, pd.Index], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Replace variables with recalculated dimensions."""
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes, inplace=inplace
)
def _replace_vars_and_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
dims: Dict[Hashable, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
"""Deprecated version of _replace_with_new_dims().
Unlike _replace_with_new_dims(), this method always recalculates
indexes from variables.
"""
if dims is None:
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes=None, inplace=inplace
)
def _overwrite_indexes(self, indexes: Mapping[Any, pd.Index]) -> "Dataset":
if not indexes:
return self
variables = self._variables.copy()
new_indexes = dict(self.indexes)
for name, idx in indexes.items():
variables[name] = IndexVariable(name, idx)
new_indexes[name] = idx
obj = self._replace(variables, indexes=new_indexes)
# switch from dimension to level names, if necessary
dim_names: Dict[Hashable, str] = {}
for dim, idx in indexes.items():
if not isinstance(idx, pd.MultiIndex) and idx.name != dim:
dim_names[dim] = idx.name
if dim_names:
obj = obj.rename(dim_names)
return obj
def copy(self, deep: bool = False, data: Mapping = None) -> "Dataset":
"""Returns a copy of this dataset.
If `deep=True`, a deep copy is made of each of the component variables.
Otherwise, a shallow copy of each of the component variable is made, so
that the underlying memory region of the new dataset is the same as in
the original dataset.
Use `data` to create a new object with the same structure as
original but entirely new data.
Parameters
----------
deep : bool, optional
Whether each component variable is loaded into memory and copied onto
the new object. Default is False.
data : dict-like, optional
Data to use in the new object. Each item in `data` must have same
shape as corresponding data variable in original. When `data` is
used, `deep` is ignored for the data variables and only used for
coords.
Returns
-------
object : Dataset
New object with dimensions, attributes, coordinates, name, encoding,
and optionally data copied from original.
Examples
--------
Shallow copy versus deep copy
>>> da = xr.DataArray(np.random.randn(2, 3))
>>> ds = xr.Dataset(
... {"foo": da, "bar": ("x", [-1, 2])},
... coords={"x": ["one", "two"]},
... )
>>> ds.copy()
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds_0 = ds.copy(deep=False)
>>> ds_0["foo"][0, 0] = 7
>>> ds_0
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
Changing the data using the ``data`` argument maintains the
structure of the original object, but with the new data. Original
object is unaffected.
>>> ds.copy(data={"foo": np.arange(6).reshape(2, 3), "bar": ["a", "b"]})
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) int64 0 1 2 3 4 5
bar (x) <U1 'a' 'b'
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Coordinates:
* x (x) <U3 'one' 'two'
Dimensions without coordinates: dim_0, dim_1
Data variables:
foo (dim_0, dim_1) float64 7.0 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
See Also
--------
pandas.DataFrame.copy
"""
if data is None:
variables = {k: v.copy(deep=deep) for k, v in self._variables.items()}
elif not utils.is_dict_like(data):
raise ValueError("Data must be dict-like")
else:
var_keys = set(self.data_vars.keys())
data_keys = set(data.keys())
keys_not_in_vars = data_keys - var_keys
if keys_not_in_vars:
raise ValueError(
"Data must only contain variables in original "
"dataset. Extra variables: {}".format(keys_not_in_vars)
)
keys_missing_from_data = var_keys - data_keys
if keys_missing_from_data:
raise ValueError(
"Data must contain all variables in original "
"dataset. Data is missing {}".format(keys_missing_from_data)
)
variables = {
k: v.copy(deep=deep, data=data.get(k))
for k, v in self._variables.items()
}
attrs = copy.deepcopy(self._attrs) if deep else copy.copy(self._attrs)
return self._replace(variables, attrs=attrs)
@property
def _level_coords(self) -> Dict[str, Hashable]:
"""Return a mapping of all MultiIndex levels and their corresponding
coordinate name.
"""
level_coords: Dict[str, Hashable] = {}
for name, index in self.indexes.items():
if isinstance(index, pd.MultiIndex):
level_names = index.names
(dim,) = self.variables[name].dims
level_coords.update({lname: dim for lname in level_names})
return level_coords
def _copy_listed(self, names: Iterable[Hashable]) -> "Dataset":
"""Create a new Dataset with the listed variables from this dataset and
the all relevant coordinates. Skips all validation.
"""
variables: Dict[Hashable, Variable] = {}
coord_names = set()
indexes: Dict[Hashable, pd.Index] = {}
for name in names:
try:
variables[name] = self._variables[name]
except KeyError:
ref_name, var_name, var = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
variables[var_name] = var
if ref_name in self._coord_names or ref_name in self.dims:
coord_names.add(var_name)
if (var_name,) == var.dims:
indexes[var_name] = var.to_index()
needed_dims: Set[Hashable] = set()
for v in variables.values():
needed_dims.update(v.dims)
dims = {k: self.dims[k] for k in needed_dims}
# preserves ordering of coordinates
for k in self._variables:
if k not in self._coord_names:
continue
if set(self.variables[k].dims) <= needed_dims:
variables[k] = self._variables[k]
coord_names.add(k)
if k in self.indexes:
indexes[k] = self.indexes[k]
return self._replace(variables, coord_names, dims, indexes=indexes)
def _construct_dataarray(self, name: Hashable) -> "DataArray":
"""Construct a DataArray by indexing this dataset"""
from .dataarray import DataArray
try:
variable = self._variables[name]
except KeyError:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
needed_dims = set(variable.dims)
coords: Dict[Hashable, Variable] = {}
# preserve ordering
for k in self._variables:
if k in self._coord_names and set(self.variables[k].dims) <= needed_dims:
coords[k] = self.variables[k]
if self._indexes is None:
indexes = None
else:
indexes = {k: v for k, v in self._indexes.items() if k in coords}
return DataArray(variable, coords, name=name, indexes=indexes, fastpath=True)
def __copy__(self) -> "Dataset":
return self.copy(deep=False)
def __deepcopy__(self, memo=None) -> "Dataset":
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
@property
def _attr_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for attribute-style access"""
yield from self._item_sources
yield self.attrs
@property
def _item_sources(self) -> Iterable[Mapping[Hashable, Any]]:
"""Places to look-up items for key-completion"""
yield self.data_vars
yield HybridMappingProxy(keys=self._coord_names, mapping=self.coords)
# virtual coordinates
yield HybridMappingProxy(keys=self.dims, mapping=self)
# uses empty dict -- everything here can already be found in self.coords.
yield HybridMappingProxy(keys=self._level_coords, mapping={})
def __contains__(self, key: object) -> bool:
"""The 'in' operator will return true or false depending on whether
'key' is an array in the dataset or not.
"""
return key in self._variables
def __len__(self) -> int:
return len(self.data_vars)
def __bool__(self) -> bool:
return bool(self.data_vars)
def __iter__(self) -> Iterator[Hashable]:
return iter(self.data_vars)
def __array__(self, dtype=None):
raise TypeError(
"cannot directly convert an xarray.Dataset into a "
"numpy array. Instead, create an xarray.DataArray "
"first, either with indexing on the Dataset or by "
"invoking the `to_array()` method."
)
@property
def nbytes(self) -> int:
return sum(v.nbytes for v in self.variables.values())
@property
def loc(self) -> _LocIndexer:
"""Attribute for location based indexing. Only supports __getitem__,
and only when the key is a dict of the form {dim: labels}.
"""
return _LocIndexer(self)
# FIXME https://github.com/python/mypy/issues/7328
@overload
def __getitem__(self, key: Mapping) -> "Dataset": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Hashable) -> "DataArray": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Any) -> "Dataset":
...
def __getitem__(self, key):
"""Access variables or coordinates this dataset as a
:py:class:`~xarray.DataArray`.
Indexing with a list of names will return a new ``Dataset`` object.
"""
if utils.is_dict_like(key):
return self.isel(**cast(Mapping, key))
if hashable(key):
return self._construct_dataarray(key)
else:
return self._copy_listed(np.asarray(key))
def __setitem__(self, key: Hashable, value) -> None:
"""Add an array to this dataset.
If value is a `DataArray`, call its `select_vars()` method, rename it
to `key` and merge the contents of the resulting dataset into this
dataset.
If value is an `Variable` object (or tuple of form
``(dims, data[, attrs])``), add it to this dataset as a new
variable.
"""
if utils.is_dict_like(key):
raise NotImplementedError(
"cannot yet use a dictionary as a key to set Dataset values"
)
self.update({key: value})
def __delitem__(self, key: Hashable) -> None:
"""Remove a variable from this dataset."""
del self._variables[key]
self._coord_names.discard(key)
if key in self.indexes:
assert self._indexes is not None
del self._indexes[key]
self._dims = calculate_dimensions(self._variables)
# mutable objects should not be hashable
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore[assignment]
def _all_compat(self, other: "Dataset", compat_str: str) -> bool:
"""Helper function for equals and identical"""
# some stores (e.g., scipy) do not seem to preserve order, so don't
# require matching order for equality
def compat(x: Variable, y: Variable) -> bool:
return getattr(x, compat_str)(y)
return self._coord_names == other._coord_names and utils.dict_equiv(
self._variables, other._variables, compat=compat
)
def broadcast_equals(self, other: "Dataset") -> bool:
"""Two Datasets are broadcast equal if they are equal after
broadcasting all variables against each other.
For example, variables that are scalar in one dataset but non-scalar in
the other dataset can still be broadcast equal if the the non-scalar
variable is a constant.
See Also
--------
Dataset.equals
Dataset.identical
"""
try:
return self._all_compat(other, "broadcast_equals")
except (TypeError, AttributeError):
return False
def equals(self, other: "Dataset") -> bool:
"""Two Datasets are equal if they have matching variables and
coordinates, all of which are equal.
Datasets can still be equal (like pandas objects) if they have NaN
values in the same locations.
This method is necessary because `v1 == v2` for ``Dataset``
does element-wise comparisons (like numpy.ndarrays).
See Also
--------
Dataset.broadcast_equals
Dataset.identical
"""
try:
return self._all_compat(other, "equals")
except (TypeError, AttributeError):
return False
def identical(self, other: "Dataset") -> bool:
"""Like equals, but also checks all dataset attributes and the
attributes on all variables and coordinates.
See Also
--------
Dataset.broadcast_equals
Dataset.equals
"""
try:
return utils.dict_equiv(self.attrs, other.attrs) and self._all_compat(
other, "identical"
)
except (TypeError, AttributeError):
return False
@property
def indexes(self) -> Indexes:
"""Mapping of pandas.Index objects used for label based indexing"""
if self._indexes is None:
self._indexes = default_indexes(self._variables, self._dims)
return Indexes(self._indexes)
@property
def coords(self) -> DatasetCoordinates:
"""Dictionary of xarray.DataArray objects corresponding to coordinate
variables
"""
return DatasetCoordinates(self)
@property
def data_vars(self) -> DataVariables:
"""Dictionary of DataArray objects corresponding to data variables"""
return DataVariables(self)
def set_coords(self, names: "Union[Hashable, Iterable[Hashable]]") -> "Dataset":
"""Given names of one or more variables, set them as coordinates
Parameters
----------
names : hashable or iterable of hashable
Name(s) of variables in this dataset to convert into coordinates.
Returns
-------
Dataset
See Also
--------
Dataset.swap_dims
"""
# TODO: allow inserting new coordinates with this method, like
# DataFrame.set_index?
# nb. check in self._variables, not self.data_vars to insure that the
# operation is idempotent
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
obj = self.copy()
obj._coord_names.update(names)
return obj
def reset_coords(
self,
names: "Union[Hashable, Iterable[Hashable], None]" = None,
drop: bool = False,
) -> "Dataset":
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : hashable or iterable of hashable, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional
If True, remove coordinates instead of converting them into
variables.
Returns
-------
Dataset
"""
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
bad_coords = set(names) & set(self.dims)
if bad_coords:
raise ValueError(
"cannot remove index coordinates with reset_coords: %s" % bad_coords
)
obj = self.copy()
obj._coord_names.difference_update(names)
if drop:
for name in names:
del obj._variables[name]
return obj
def dump_to_store(self, store: "AbstractDataStore", **kwargs) -> None:
"""Store dataset contents to a backends.*DataStore object."""
from ..backends.api import dump_to_store
# TODO: rename and/or cleanup this method to make it more consistent
# with to_netcdf()
dump_to_store(self, store, **kwargs)
def to_netcdf(
self,
path=None,
mode: str = "w",
format: str = None,
group: str = None,
engine: str = None,
encoding: Mapping = None,
unlimited_dims: Iterable[Hashable] = None,
compute: bool = True,
invalid_netcdf: bool = False,
) -> Union[bytes, "Delayed", None]:
"""Write dataset contents to a netCDF file.
Parameters
----------
path : str, Path or file-like, optional
Path to which to save this dataset. File-like objects are only
supported by the scipy engine. If no path is provided, this
function returns the resulting netCDF file as bytes; in this case,
we need to use scipy, which does not support netCDF version 4 (the
default format becomes NETCDF3_64BIT).
mode : {"w", "a"}, default: "w"
Write ('w') or append ('a') mode. If mode='w', any existing file at
this location will be overwritten. If mode='a', existing variables
will be overwritten.
format : {"NETCDF4", "NETCDF4_CLASSIC", "NETCDF3_64BIT", \
"NETCDF3_CLASSIC"}, optional
File format for the resulting netCDF file:
* NETCDF4: Data is stored in an HDF5 file, using netCDF4 API
features.
* NETCDF4_CLASSIC: Data is stored in an HDF5 file, using only
netCDF 3 compatible API features.
* NETCDF3_64BIT: 64-bit offset version of the netCDF 3 file format,
which fully supports 2+ GB files, but is only compatible with
clients linked against netCDF version 3.6.0 or later.
* NETCDF3_CLASSIC: The classic netCDF 3 file format. It does not
handle 2+ GB files very well.
All formats are supported by the netCDF4-python library.
scipy.io.netcdf only supports the last two formats.
The default format is NETCDF4 if you are saving a file to disk and
have the netCDF4-python library available. Otherwise, xarray falls
back to using scipy to write netCDF files and defaults to the
NETCDF3_64BIT format (scipy does not support netCDF4).
group : str, optional
Path to the netCDF4 group in the given file to open (only works for
format='NETCDF4'). The group(s) will be created if necessary.
engine : {"netcdf4", "scipy", "h5netcdf"}, optional
Engine to use when writing netCDF files. If not provided, the
default engine is chosen based on available dependencies, with a
preference for 'netcdf4' if writing to a file on disk.
encoding : dict, optional
Nested dictionary with variable names as keys and dictionaries of
variable specific encodings as values, e.g.,
``{"my_variable": {"dtype": "int16", "scale_factor": 0.1,
"zlib": True}, ...}``
The `h5netcdf` engine supports both the NetCDF4-style compression
encoding parameters ``{"zlib": True, "complevel": 9}`` and the h5py
ones ``{"compression": "gzip", "compression_opts": 9}``.
This allows using any compression plugin installed in the HDF5
library, e.g. LZF.
unlimited_dims : iterable of hashable, optional
Dimension(s) that should be serialized as unlimited dimensions.
By default, no dimensions are treated as unlimited dimensions.
Note that unlimited_dims may also be set via
``dataset.encoding["unlimited_dims"]``.
compute: bool, default: True
If true compute immediately, otherwise return a
``dask.delayed.Delayed`` object that can be computed later.
invalid_netcdf: bool, default: False
Only valid along with ``engine="h5netcdf"``. If True, allow writing
hdf5 files which are invalid netcdf as described in
https://github.com/shoyer/h5netcdf.
"""
if encoding is None:
encoding = {}
from ..backends.api import to_netcdf
return to_netcdf(
self,
path,
mode,
format=format,
group=group,
engine=engine,
encoding=encoding,
unlimited_dims=unlimited_dims,
compute=compute,
invalid_netcdf=invalid_netcdf,
)
def to_zarr(
self,
store: Union[MutableMapping, str, Path] = None,
chunk_store: Union[MutableMapping, str, Path] = None,
mode: str = None,
synchronizer=None,
group: str = None,
encoding: Mapping = None,
compute: bool = True,
consolidated: bool = False,
append_dim: Hashable = None,
region: Mapping[str, slice] = None,
) -> "ZarrStore":
"""Write dataset contents to a zarr group.
.. note:: Experimental
The Zarr backend is new and experimental. Please report any
unexpected behavior via github issues.
Parameters
----------
store : MutableMapping, str or Path, optional
Store or path to directory in file system.
chunk_store : MutableMapping, str or Path, optional
Store or path to directory in file system only for Zarr array chunks.
Requires zarr-python v2.4.0 or later.
mode : {"w", "w-", "a", None}, optional
Persistence mode: "w" means create (overwrite if exists);
"w-" means create (fail if exists);
"a" means override existing variables (create if does not exist).
If ``append_dim`` is set, ``mode`` can be omitted as it is
internally set to ``"a"``. Otherwise, ``mode`` will default to
`w-` if not set.
synchronizer : object, optional
Zarr array synchronizer.
group : str, optional
Group path. (a.k.a. `path` in zarr terminology.)
encoding : dict, optional
Nested dictionary with variable names as keys and dictionaries of
variable specific encodings as values, e.g.,
``{"my_variable": {"dtype": "int16", "scale_factor": 0.1,}, ...}``
compute : bool, optional
If True write array data immediately, otherwise return a
``dask.delayed.Delayed`` object that can be computed to write
array data later. Metadata is always updated eagerly.
consolidated : bool, optional
If True, apply zarr's `consolidate_metadata` function to the store
after writing metadata.
append_dim : hashable, optional
If set, the dimension along which the data will be appended. All
other dimensions on overriden variables must remain the same size.
region : dict, optional
Optional mapping from dimension names to integer slices along
dataset dimensions to indicate the region of existing zarr array(s)
in which to write this dataset's data. For example,
``{'x': slice(0, 1000), 'y': slice(10000, 11000)}`` would indicate
that values should be written to the region ``0:1000`` along ``x``
and ``10000:11000`` along ``y``.
Two restrictions apply to the use of ``region``:
- If ``region`` is set, _all_ variables in a dataset must have at
least one dimension in common with the region. Other variables
should be written in a separate call to ``to_zarr()``.
- Dimensions cannot be included in both ``region`` and
``append_dim`` at the same time. To create empty arrays to fill
in with ``region``, use a separate call to ``to_zarr()`` with
``compute=False``. See "Appending to existing Zarr stores" in
the reference documentation for full details.
References
----------
https://zarr.readthedocs.io/
Notes
-----
Zarr chunking behavior:
If chunks are found in the encoding argument or attribute
corresponding to any DataArray, those chunks are used.
If a DataArray is a dask array, it is written with those chunks.
If not other chunks are found, Zarr uses its own heuristics to
choose automatic chunk sizes.
"""
from ..backends.api import to_zarr
if encoding is None:
encoding = {}
return to_zarr(
self,
store=store,
chunk_store=chunk_store,
mode=mode,
synchronizer=synchronizer,
group=group,
encoding=encoding,
compute=compute,
consolidated=consolidated,
append_dim=append_dim,
region=region,
)
def __repr__(self) -> str:
return formatting.dataset_repr(self)
def _repr_html_(self):
if OPTIONS["display_style"] == "text":
return f"<pre>{escape(repr(self))}</pre>"
return formatting_html.dataset_repr(self)
def info(self, buf=None) -> None:
"""
Concise summary of a Dataset variables and attributes.
Parameters
----------
buf : file-like, default: sys.stdout
writable buffer
See Also
--------
pandas.DataFrame.assign
ncdump : netCDF's ncdump
"""
if buf is None: # pragma: no cover
buf = sys.stdout
lines = []
lines.append("xarray.Dataset {")
lines.append("dimensions:")
for name, size in self.dims.items():
lines.append(f"\t{name} = {size} ;")
lines.append("\nvariables:")
for name, da in self.variables.items():
dims = ", ".join(da.dims)
lines.append(f"\t{da.dtype} {name}({dims}) ;")
for k, v in da.attrs.items():
lines.append(f"\t\t{name}:{k} = {v} ;")
lines.append("\n// global attributes:")
for k, v in self.attrs.items():
lines.append(f"\t:{k} = {v} ;")
lines.append("}")
buf.write("\n".join(lines))
@property
def chunks(self) -> Mapping[Hashable, Tuple[int, ...]]:
"""Block dimensions for this dataset's data or None if it's not a dask
array.
"""
chunks: Dict[Hashable, Tuple[int, ...]] = {}
for v in self.variables.values():
if v.chunks is not None:
for dim, c in zip(v.dims, v.chunks):
if dim in chunks and c != chunks[dim]:
raise ValueError(
f"Object has inconsistent chunks along dimension {dim}. "
"This can be fixed by calling unify_chunks()."
)
chunks[dim] = c
return Frozen(SortedKeysDict(chunks))
def chunk(
self,
chunks: Union[
Number,
str,
Mapping[Hashable, Union[None, Number, str, Tuple[Number, ...]]],
] = {}, # {} even though it's technically unsafe, is being used intentionally here (#4667)
name_prefix: str = "xarray-",
token: str = None,
lock: bool = False,
) -> "Dataset":
"""Coerce all arrays in this dataset into dask arrays with the given
chunks.
Non-dask arrays in this dataset will be converted to dask arrays. Dask
arrays will be rechunked to the given chunk sizes.
If neither chunks is not provided for one or more dimensions, chunk
sizes along that dimension will not be updated; non-dask arrays will be
converted into dask arrays with a single block.
Parameters
----------
chunks : int, 'auto' or mapping, optional
Chunk sizes along each dimension, e.g., ``5`` or
``{"x": 5, "y": 5}``.
name_prefix : str, optional
Prefix for the name of any new dask arrays.
token : str, optional
Token uniquely identifying this dataset.
lock : optional
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
Returns
-------
chunked : xarray.Dataset
"""
if chunks is None:
warnings.warn(
"None value for 'chunks' is deprecated. "
"It will raise an error in the future. Use instead '{}'",
category=FutureWarning,
)
chunks = {}
if isinstance(chunks, (Number, str)):
chunks = dict.fromkeys(self.dims, chunks)
bad_dims = chunks.keys() - self.dims.keys()
if bad_dims:
raise ValueError(
"some chunks keys are not dimensions on this " "object: %s" % bad_dims
)
variables = {
k: _maybe_chunk(k, v, chunks, token, lock, name_prefix)
for k, v in self.variables.items()
}
return self._replace(variables)
def _validate_indexers(
self, indexers: Mapping[Hashable, Any], missing_dims: str = "raise"
) -> Iterator[Tuple[Hashable, Union[int, slice, np.ndarray, Variable]]]:
"""Here we make sure
+ indexer has a valid keys
+ indexer is in a valid data type
+ string indexers are cast to the appropriate date type if the
associated index is a DatetimeIndex or CFTimeIndex
"""
from .dataarray import DataArray
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
# all indexers should be int, slice, np.ndarrays, or Variable
for k, v in indexers.items():
if isinstance(v, (int, slice, Variable)):
yield k, v
elif isinstance(v, DataArray):
yield k, v.variable
elif isinstance(v, tuple):
yield k, as_variable(v)
elif isinstance(v, Dataset):
raise TypeError("cannot use a Dataset as an indexer")
elif isinstance(v, Sequence) and len(v) == 0:
yield k, np.empty((0,), dtype="int64")
else:
v = np.asarray(v)
if v.dtype.kind in "US":
index = self.indexes[k]
if isinstance(index, pd.DatetimeIndex):
v = v.astype("datetime64[ns]")
elif isinstance(index, xr.CFTimeIndex):
v = _parse_array_of_cftime_strings(v, index.date_type)
if v.ndim > 1:
raise IndexError(
"Unlabeled multi-dimensional array cannot be "
"used for indexing: {}".format(k)
)
yield k, v
def _validate_interp_indexers(
self, indexers: Mapping[Hashable, Any]
) -> Iterator[Tuple[Hashable, Variable]]:
"""Variant of _validate_indexers to be used for interpolation"""
for k, v in self._validate_indexers(indexers):
if isinstance(v, Variable):
if v.ndim == 1:
yield k, v.to_index_variable()
else:
yield k, v
elif isinstance(v, int):
yield k, Variable((), v)
elif isinstance(v, np.ndarray):
if v.ndim == 0:
yield k, Variable((), v)
elif v.ndim == 1:
yield k, IndexVariable((k,), v)
else:
raise AssertionError() # Already tested by _validate_indexers
else:
raise TypeError(type(v))
def _get_indexers_coords_and_indexes(self, indexers):
"""Extract coordinates and indexes from indexers.
Only coordinate with a name different from any of self.variables will
be attached.
"""
from .dataarray import DataArray
coords_list = []
for k, v in indexers.items():
if isinstance(v, DataArray):
if v.dtype.kind == "b":
if v.ndim != 1: # we only support 1-d boolean array
raise ValueError(
"{:d}d-boolean array is used for indexing along "
"dimension {!r}, but only 1d boolean arrays are "
"supported.".format(v.ndim, k)
)
# Make sure in case of boolean DataArray, its
# coordinate also should be indexed.
v_coords = v[v.values.nonzero()[0]].coords
else:
v_coords = v.coords
coords_list.append(v_coords)
# we don't need to call align() explicitly or check indexes for
# alignment, because merge_variables already checks for exact alignment
# between dimension coordinates
coords, indexes = merge_coordinates_without_align(coords_list)
assert_coordinate_consistent(self, coords)
# silently drop the conflicted variables.
attached_coords = {k: v for k, v in coords.items() if k not in self._variables}
attached_indexes = {
k: v for k, v in indexes.items() if k not in self._variables
}
return attached_coords, attached_indexes
def isel(
self,
indexers: Mapping[Hashable, Any] = None,
drop: bool = False,
missing_dims: str = "raise",
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed along the specified
dimension(s).
This method selects values from each array using its `__getitem__`
method, except this method does not require knowing the order of
each array's dimensions.
Parameters
----------
indexers : dict, optional
A dict with keys matching dimensions and values given
by integers, slice objects or arrays.
indexer can be a integer, slice, array-like or DataArray.
If DataArrays are passed as indexers, xarray-style indexing will be
carried out. See :ref:`indexing` for the details.
One of indexers or indexers_kwargs must be provided.
drop : bool, optional
If ``drop=True``, drop coordinates variables indexed by integers
instead of making them scalar.
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
Dataset:
- "raise": raise an exception
- "warning": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
**indexers_kwargs : {dim: indexer, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the appropriate indexers.
If indexer DataArrays have coordinates that do not conflict with
this object, then these coordinates will be attached.
In general, each array's data will be a view of the array's data
in this dataset, unless vectorized indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.sel
DataArray.isel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "isel")
if any(is_fancy_indexer(idx) for idx in indexers.values()):
return self._isel_fancy(indexers, drop=drop, missing_dims=missing_dims)
# Much faster algorithm for when all indexers are ints, slices, one-dimensional
# lists, or zero or one-dimensional np.ndarray's
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
variables = {}
dims: Dict[Hashable, Tuple[int, ...]] = {}
coord_names = self._coord_names.copy()
indexes = self._indexes.copy() if self._indexes is not None else None
for var_name, var_value in self._variables.items():
var_indexers = {k: v for k, v in indexers.items() if k in var_value.dims}
if var_indexers:
var_value = var_value.isel(var_indexers)
if drop and var_value.ndim == 0 and var_name in coord_names:
coord_names.remove(var_name)
if indexes:
indexes.pop(var_name, None)
continue
if indexes and var_name in indexes:
if var_value.ndim == 1:
indexes[var_name] = var_value.to_index()
else:
del indexes[var_name]
variables[var_name] = var_value
dims.update(zip(var_value.dims, var_value.shape))
return self._construct_direct(
variables=variables,
coord_names=coord_names,
dims=dims,
attrs=self._attrs,
indexes=indexes,
encoding=self._encoding,
close=self._close,
)
def _isel_fancy(
self,
indexers: Mapping[Hashable, Any],
*,
drop: bool,
missing_dims: str = "raise",
) -> "Dataset":
# Note: we need to preserve the original indexers variable in order to merge the
# coords below
indexers_list = list(self._validate_indexers(indexers, missing_dims))
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for name, var in self.variables.items():
var_indexers = {k: v for k, v in indexers_list if k in var.dims}
if drop and name in var_indexers:
continue # drop this variable
if name in self.indexes:
new_var, new_index = isel_variable_and_index(
name, var, self.indexes[name], var_indexers
)
if new_index is not None:
indexes[name] = new_index
elif var_indexers:
new_var = var.isel(indexers=var_indexers)
else:
new_var = var.copy(deep=False)
variables[name] = new_var
coord_names = self._coord_names & variables.keys()
selected = self._replace_with_new_dims(variables, coord_names, indexes)
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(indexers)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = self._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def sel(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
drop: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed by tick labels
along the specified dimension(s).
In contrast to `Dataset.isel`, indexers for this method should use
labels instead of integers.
Under the hood, this method is powered by using pandas's powerful Index
objects. This makes label based indexing essentially just as fast as
using integer indexing.
It also means this method uses pandas's (well documented) logic for
indexing. This means you can use string shortcuts for datetime indexes
(e.g., '2000-01' to select all values in January 2000). It also means
that slices are treated as inclusive of both the start and stop values,
unlike normal Python indexing.
Parameters
----------
indexers : dict, optional
A dict with keys matching dimensions and values given
by scalars, slices or arrays of tick labels. For dimensions with
multi-index, the indexer may also be a dict-like object with keys
matching index level names.
If DataArrays are passed as indexers, xarray-style indexing will be
carried out. See :ref:`indexing` for the details.
One of indexers or indexers_kwargs must be provided.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for inexact matches:
* None (default): only exact matches
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
drop : bool, optional
If ``drop=True``, drop coordinates variables in `indexers` instead
of making them scalar.
**indexers_kwargs : {dim: indexer, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
variable and dimension is indexed by the appropriate indexers.
If indexer DataArrays have coordinates that do not conflict with
this object, then these coordinates will be attached.
In general, each array's data will be a view of the array's data
in this dataset, unless vectorized indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.isel
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
pos_indexers, new_indexes = remap_label_indexers(
self, indexers=indexers, method=method, tolerance=tolerance
)
result = self.isel(indexers=pos_indexers, drop=drop)
return result._overwrite_indexes(new_indexes)
def head(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with the first `n` values of each array
for the specified dimension(s).
Parameters
----------
indexers : dict or int, default: 5
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.tail
Dataset.thin
DataArray.head
"""
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "head")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {k: slice(val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def tail(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with the last `n` values of each array
for the specified dimension(s).
Parameters
----------
indexers : dict or int, default: 5
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.head
Dataset.thin
DataArray.tail
"""
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "tail")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {
k: slice(-val, None) if val != 0 else slice(val)
for k, val in indexers.items()
}
return self.isel(indexers_slices)
def thin(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
"""Returns a new dataset with each array indexed along every `n`-th
value for the specified dimension(s)
Parameters
----------
indexers : dict or int
A dict with keys matching dimensions and integer values `n`
or a single integer `n` applied over all dimensions.
One of indexers or indexers_kwargs must be provided.
**indexers_kwargs : {dim: n, ...}, optional
The keyword arguments form of ``indexers``.
One of indexers or indexers_kwargs must be provided.
See Also
--------
Dataset.head
Dataset.tail
DataArray.thin
"""
if (
not indexers_kwargs
and not isinstance(indexers, int)
and not is_dict_like(indexers)
):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "thin")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
elif v == 0:
raise ValueError("step cannot be zero")
indexers_slices = {k: slice(None, None, val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def broadcast_like(
self, other: Union["Dataset", "DataArray"], exclude: Iterable[Hashable] = None
) -> "Dataset":
"""Broadcast this DataArray against another Dataset or DataArray.
This is equivalent to xr.broadcast(other, self)[1]
Parameters
----------
other : Dataset or DataArray
Object against which to broadcast this array.
exclude : iterable of hashable, optional
Dimensions that must not be broadcasted
"""
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
args = align(other, self, join="outer", copy=False, exclude=exclude)
dims_map, common_coords = _get_broadcast_dims_map_common_coords(args, exclude)
return _broadcast_helper(args[1], exclude, dims_map, common_coords)
def reindex_like(
self,
other: Union["Dataset", "DataArray"],
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
) -> "Dataset":
"""Conform this object onto the indexes of another object, filling in
missing values with ``fill_value``. The default fill value is NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to pandas.Index objects, which provides coordinates upon
which to index the variables in this dataset. The indexes on this
other object need not be the same as the indexes on this
dataset. Any mis-matched index values will be filled in with
NaN, and any mis-matched dimension names will simply be ignored.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for filling index values from other not found in this
dataset:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like maps
variable names to fill values.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but coordinates from the
other object.
See Also
--------
Dataset.reindex
align
"""
indexers = alignment.reindex_like_indexers(self, other)
return self.reindex(
indexers=indexers,
method=method,
copy=copy,
fill_value=fill_value,
tolerance=tolerance,
)
def reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
**indexers_kwargs: Any,
) -> "Dataset":
"""Conform this object onto a new set of indexes, filling in
missing values with ``fill_value``. The default fill value is NaN.
Parameters
----------
indexers : dict, optional
Dictionary with keys given by dimension names and values given by
arrays of coordinates tick labels. Any mis-matched coordinate
values will be filled in with NaN, and any mis-matched dimension
names will simply be ignored.
One of indexers or indexers_kwargs must be provided.
method : {None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional
Method to use for filling index values in ``indexers`` not found in
this dataset:
* None (default): don't fill gaps
* pad / ffill: propagate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
tolerance : optional
Maximum distance between original and new labels for inexact
matches. The values of the index at the matching locations must
satisfy the equation ``abs(index[indexer] - target) <= tolerance``.
copy : bool, optional
If ``copy=True``, data in the return value is always copied. If
``copy=False`` and reindexing is unnecessary, or can be performed
with only slice operations, then the output may share memory with
the input. In either case, a new xarray object is always returned.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like,
maps variable names (including coordinates) to fill values.
sparse : bool, default: False
use sparse-array.
**indexers_kwargs : {dim: indexer, ...}, optional
Keyword arguments in the same form as ``indexers``.
One of indexers or indexers_kwargs must be provided.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but replaced coordinates.
See Also
--------
Dataset.reindex_like
align
pandas.Index.get_indexer
Examples
--------
Create a dataset with some fictional data.
>>> import xarray as xr
>>> import pandas as pd
>>> x = xr.Dataset(
... {
... "temperature": ("station", 20 * np.random.rand(4)),
... "pressure": ("station", 500 * np.random.rand(4)),
... },
... coords={"station": ["boston", "nyc", "seattle", "denver"]},
... )
>>> x
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'nyc' 'seattle' 'denver'
Data variables:
temperature (station) float64 10.98 14.3 12.06 10.9
pressure (station) float64 211.8 322.9 218.8 445.9
>>> x.indexes
station: Index(['boston', 'nyc', 'seattle', 'denver'], dtype='object', name='station')
Create a new index and reindex the dataset. By default values in the new index that
do not have corresponding records in the dataset are assigned `NaN`.
>>> new_index = ["boston", "austin", "seattle", "lincoln"]
>>> x.reindex({"station": new_index})
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 nan 12.06 nan
pressure (station) float64 211.8 nan 218.8 nan
We can fill in the missing values by passing a value to the keyword `fill_value`.
>>> x.reindex({"station": new_index}, fill_value=0)
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 0.0 12.06 0.0
pressure (station) float64 211.8 0.0 218.8 0.0
We can also use different fill values for each variable.
>>> x.reindex(
... {"station": new_index}, fill_value={"temperature": 0, "pressure": 100}
... )
<xarray.Dataset>
Dimensions: (station: 4)
Coordinates:
* station (station) <U7 'boston' 'austin' 'seattle' 'lincoln'
Data variables:
temperature (station) float64 10.98 0.0 12.06 0.0
pressure (station) float64 211.8 100.0 218.8 100.0
Because the index is not monotonically increasing or decreasing, we cannot use arguments
to the keyword method to fill the `NaN` values.
>>> x.reindex({"station": new_index}, method="nearest")
Traceback (most recent call last):
...
raise ValueError('index must be monotonic increasing or decreasing')
ValueError: index must be monotonic increasing or decreasing
To further illustrate the filling functionality in reindex, we will create a
dataset with a monotonically increasing index (for example, a sequence of dates).
>>> x2 = xr.Dataset(
... {
... "temperature": (
... "time",
... [15.57, 12.77, np.nan, 0.3081, 16.59, 15.12],
... ),
... "pressure": ("time", 500 * np.random.rand(6)),
... },
... coords={"time": pd.date_range("01/01/2019", periods=6, freq="D")},
... )
>>> x2
<xarray.Dataset>
Dimensions: (time: 6)
Coordinates:
* time (time) datetime64[ns] 2019-01-01 2019-01-02 ... 2019-01-06
Data variables:
temperature (time) float64 15.57 12.77 nan 0.3081 16.59 15.12
pressure (time) float64 481.8 191.7 395.9 264.4 284.0 462.8
Suppose we decide to expand the dataset to cover a wider date range.
>>> time_index2 = pd.date_range("12/29/2018", periods=10, freq="D")
>>> x2.reindex({"time": time_index2})
<xarray.Dataset>
Dimensions: (time: 10)
Coordinates:
* time (time) datetime64[ns] 2018-12-29 2018-12-30 ... 2019-01-07
Data variables:
temperature (time) float64 nan nan nan 15.57 ... 0.3081 16.59 15.12 nan
pressure (time) float64 nan nan nan 481.8 ... 264.4 284.0 462.8 nan
The index entries that did not have a value in the original data frame (for example, `2018-12-29`)
are by default filled with NaN. If desired, we can fill in the missing values using one of several options.
For example, to back-propagate the last valid value to fill the `NaN` values,
pass `bfill` as an argument to the `method` keyword.
>>> x3 = x2.reindex({"time": time_index2}, method="bfill")
>>> x3
<xarray.Dataset>
Dimensions: (time: 10)
Coordinates:
* time (time) datetime64[ns] 2018-12-29 2018-12-30 ... 2019-01-07
Data variables:
temperature (time) float64 15.57 15.57 15.57 15.57 ... 16.59 15.12 nan
pressure (time) float64 481.8 481.8 481.8 481.8 ... 284.0 462.8 nan
Please note that the `NaN` value present in the original dataset (at index value `2019-01-03`)
will not be filled by any of the value propagation schemes.
>>> x2.where(x2.temperature.isnull(), drop=True)
<xarray.Dataset>
Dimensions: (time: 1)
Coordinates:
* time (time) datetime64[ns] 2019-01-03
Data variables:
temperature (time) float64 nan
pressure (time) float64 395.9
>>> x3.where(x3.temperature.isnull(), drop=True)
<xarray.Dataset>
Dimensions: (time: 2)
Coordinates:
* time (time) datetime64[ns] 2019-01-03 2019-01-07
Data variables:
temperature (time) float64 nan nan
pressure (time) float64 395.9 nan
This is because filling while reindexing does not look at dataset values, but only compares
the original and desired indexes. If you do want to fill in the `NaN` values present in the
original dataset, use the :py:meth:`~Dataset.fillna()` method.
"""
return self._reindex(
indexers,
method,
tolerance,
copy,
fill_value,
sparse=False,
**indexers_kwargs,
)
def _reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
sparse: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
"""
same to _reindex but support sparse option
"""
indexers = utils.either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
bad_dims = [d for d in indexers if d not in self.dims]
if bad_dims:
raise ValueError("invalid reindex dimensions: %s" % bad_dims)
variables, indexes = alignment.reindex_variables(
self.variables,
self.sizes,
self.indexes,
indexers,
method,
tolerance,
copy=copy,
fill_value=fill_value,
sparse=sparse,
)
coord_names = set(self._coord_names)
coord_names.update(indexers)
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp(
self,
coords: Mapping[Hashable, Any] = None,
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
**coords_kwargs: Any,
) -> "Dataset":
"""Multidimensional interpolation of Dataset.
Parameters
----------
coords : dict, optional
Mapping from dimension names to the new coordinates.
New coordinate can be a scalar, array-like or DataArray.
If DataArrays are passed as new coordinates, their dimensions are
used for the broadcasting. Missing values are skipped.
method : str, optional
{"linear", "nearest"} for multidimensional array,
{"linear", "nearest", "zero", "slinear", "quadratic", "cubic"}
for 1-dimensional array. "linear" is used by default.
assume_sorted : bool, optional
If False, values of coordinates that are interpolated over can be
in any order and they are sorted first. If True, interpolated
coordinates are assumed to be an array of monotonically increasing
values.
kwargs : dict, optional
Additional keyword arguments passed to scipy's interpolator. Valid
options and their behavior depend on if 1-dimensional or
multi-dimensional interpolation is used.
**coords_kwargs : {dim: coordinate, ...}, optional
The keyword arguments form of ``coords``.
One of coords or coords_kwargs must be provided.
Returns
-------
interpolated : Dataset
New dataset on the new coordinates.
Notes
-----
scipy is required.
See Also
--------
scipy.interpolate.interp1d
scipy.interpolate.interpn
Examples
--------
>>> ds = xr.Dataset(
... data_vars={
... "a": ("x", [5, 7, 4]),
... "b": (
... ("x", "y"),
... [[1, 4, 2, 9], [2, 7, 6, np.nan], [6, np.nan, 5, 8]],
... ),
... },
... coords={"x": [0, 1, 2], "y": [10, 12, 14, 16]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 3, y: 4)
Coordinates:
* x (x) int64 0 1 2
* y (y) int64 10 12 14 16
Data variables:
a (x) int64 5 7 4
b (x, y) float64 1.0 4.0 2.0 9.0 2.0 7.0 6.0 nan 6.0 nan 5.0 8.0
1D interpolation with the default method (linear):
>>> ds.interp(x=[0, 0.75, 1.25, 1.75])
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 0.0 0.75 1.25 1.75
Data variables:
a (x) float64 5.0 6.5 6.25 4.75
b (x, y) float64 1.0 4.0 2.0 nan 1.75 6.25 ... nan 5.0 nan 5.25 nan
1D interpolation with a different method:
>>> ds.interp(x=[0, 0.75, 1.25, 1.75], method="nearest")
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 0.0 0.75 1.25 1.75
Data variables:
a (x) float64 5.0 7.0 7.0 4.0
b (x, y) float64 1.0 4.0 2.0 9.0 2.0 7.0 ... 6.0 nan 6.0 nan 5.0 8.0
1D extrapolation:
>>> ds.interp(
... x=[1, 1.5, 2.5, 3.5],
... method="linear",
... kwargs={"fill_value": "extrapolate"},
... )
<xarray.Dataset>
Dimensions: (x: 4, y: 4)
Coordinates:
* y (y) int64 10 12 14 16
* x (x) float64 1.0 1.5 2.5 3.5
Data variables:
a (x) float64 7.0 5.5 2.5 -0.5
b (x, y) float64 2.0 7.0 6.0 nan 4.0 nan ... 4.5 nan 12.0 nan 3.5 nan
2D interpolation:
>>> ds.interp(x=[0, 0.75, 1.25, 1.75], y=[11, 13, 15], method="linear")
<xarray.Dataset>
Dimensions: (x: 4, y: 3)
Coordinates:
* x (x) float64 0.0 0.75 1.25 1.75
* y (y) int64 11 13 15
Data variables:
a (x) float64 5.0 6.5 6.25 4.75
b (x, y) float64 2.5 3.0 nan 4.0 5.625 nan nan nan nan nan nan nan
"""
from . import missing
if kwargs is None:
kwargs = {}
coords = either_dict_or_kwargs(coords, coords_kwargs, "interp")
indexers = dict(self._validate_interp_indexers(coords))
if coords:
# This avoids broadcasting over coordinates that are both in
# the original array AND in the indexing array. It essentially
# forces interpolation along the shared coordinates.
sdims = (
set(self.dims)
.intersection(*[set(nx.dims) for nx in indexers.values()])
.difference(coords.keys())
)
indexers.update({d: self.variables[d] for d in sdims})
obj = self if assume_sorted else self.sortby([k for k in coords])
def maybe_variable(obj, k):
# workaround to get variable for dimension without coordinate.
try:
return obj._variables[k]
except KeyError:
return as_variable((k, range(obj.dims[k])))
def _validate_interp_indexer(x, new_x):
# In the case of datetimes, the restrictions placed on indexers
# used with interp are stronger than those which are placed on
# isel, so we need an additional check after _validate_indexers.
if _contains_datetime_like_objects(
x
) and not _contains_datetime_like_objects(new_x):
raise TypeError(
"When interpolating over a datetime-like "
"coordinate, the coordinates to "
"interpolate to must be either datetime "
"strings or datetimes. "
"Instead got\n{}".format(new_x)
)
return x, new_x
variables: Dict[Hashable, Variable] = {}
for name, var in obj._variables.items():
if name in indexers:
continue
if var.dtype.kind in "uifc":
var_indexers = {
k: _validate_interp_indexer(maybe_variable(obj, k), v)
for k, v in indexers.items()
if k in var.dims
}
variables[name] = missing.interp(var, var_indexers, method, **kwargs)
elif all(d not in indexers for d in var.dims):
# keep unrelated object array
variables[name] = var
coord_names = obj._coord_names & variables.keys()
indexes = {k: v for k, v in obj.indexes.items() if k not in indexers}
selected = self._replace_with_new_dims(
variables.copy(), coord_names, indexes=indexes
)
# attach indexer as coordinate
variables.update(indexers)
for k, v in indexers.items():
assert isinstance(v, Variable)
if v.dims == (k,):
indexes[k] = v.to_index()
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(coords)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = obj._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp_like(
self,
other: Union["Dataset", "DataArray"],
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
) -> "Dataset":
"""Interpolate this object onto the coordinates of another object,
filling the out of range values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to an 1d array-like, which provides coordinates upon
which to index the variables in this dataset. Missing values are skipped.
method : str, optional
{"linear", "nearest"} for multidimensional array,
{"linear", "nearest", "zero", "slinear", "quadratic", "cubic"}
for 1-dimensional array. 'linear' is used by default.
assume_sorted : bool, optional
If False, values of coordinates that are interpolated over can be
in any order and they are sorted first. If True, interpolated
coordinates are assumed to be an array of monotonically increasing
values.
kwargs : dict, optional
Additional keyword passed to scipy's interpolator.
Returns
-------
interpolated : Dataset
Another dataset by interpolating this dataset's data along the
coordinates of the other object.
Notes
-----
scipy is required.
If the dataset has object-type coordinates, reindex is used for these
coordinates instead of the interpolation.
See Also
--------
Dataset.interp
Dataset.reindex_like
"""
if kwargs is None:
kwargs = {}
coords = alignment.reindex_like_indexers(self, other)
numeric_coords: Dict[Hashable, pd.Index] = {}
object_coords: Dict[Hashable, pd.Index] = {}
for k, v in coords.items():
if v.dtype.kind in "uifcMm":
numeric_coords[k] = v
else:
object_coords[k] = v
ds = self
if object_coords:
# We do not support interpolation along object coordinate.
# reindex instead.
ds = self.reindex(object_coords)
return ds.interp(numeric_coords, method, assume_sorted, kwargs)
# Helper methods for rename()
def _rename_vars(self, name_dict, dims_dict):
variables = {}
coord_names = set()
for k, v in self.variables.items():
var = v.copy(deep=False)
var.dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
name = name_dict.get(k, k)
if name in variables:
raise ValueError(f"the new name {name!r} conflicts")
variables[name] = var
if k in self._coord_names:
coord_names.add(name)
return variables, coord_names
def _rename_dims(self, name_dict):
return {name_dict.get(k, k): v for k, v in self.dims.items()}
def _rename_indexes(self, name_dict, dims_set):
if self._indexes is None:
return None
indexes = {}
for k, v in self.indexes.items():
new_name = name_dict.get(k, k)
if new_name not in dims_set:
continue
if isinstance(v, pd.MultiIndex):
new_names = [name_dict.get(k, k) for k in v.names]
index = v.rename(names=new_names)
else:
index = v.rename(new_name)
indexes[new_name] = index
return indexes
def _rename_all(self, name_dict, dims_dict):
variables, coord_names = self._rename_vars(name_dict, dims_dict)
dims = self._rename_dims(dims_dict)
indexes = self._rename_indexes(name_dict, dims.keys())
return variables, coord_names, dims, indexes
def rename(
self,
name_dict: Mapping[Hashable, Hashable] = None,
**names: Hashable,
) -> "Dataset":
"""Returns a new object with renamed variables and dimensions.
Parameters
----------
name_dict : dict-like, optional
Dictionary whose keys are current variable or dimension names and
whose values are the desired names.
**names : optional
Keyword form of ``name_dict``.
One of name_dict or names must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed variables and dimensions.
See Also
--------
Dataset.swap_dims
Dataset.rename_vars
Dataset.rename_dims
DataArray.rename
"""
name_dict = either_dict_or_kwargs(name_dict, names, "rename")
for k in name_dict.keys():
if k not in self and k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"variable or dimension in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict=name_dict
)
assert_unique_multiindex_level_names(variables)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def rename_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims: Hashable
) -> "Dataset":
"""Returns a new object with renamed dimensions only.
Parameters
----------
dims_dict : dict-like, optional
Dictionary whose keys are current dimension names and
whose values are the desired names. The desired names must
not be the name of an existing dimension or Variable in the Dataset.
**dims : optional
Keyword form of ``dims_dict``.
One of dims_dict or dims must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed dimensions.
See Also
--------
Dataset.swap_dims
Dataset.rename
Dataset.rename_vars
DataArray.rename
"""
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"dimension in this dataset" % k
)
if v in self.dims or v in self:
raise ValueError(
f"Cannot rename {k} to {v} because {v} already exists. "
"Try using swap_dims instead."
)
variables, coord_names, sizes, indexes = self._rename_all(
name_dict={}, dims_dict=dims_dict
)
return self._replace(variables, coord_names, dims=sizes, indexes=indexes)
def rename_vars(
self, name_dict: Mapping[Hashable, Hashable] = None, **names: Hashable
) -> "Dataset":
"""Returns a new object with renamed variables including coordinates
Parameters
----------
name_dict : dict-like, optional
Dictionary whose keys are current variable or coordinate names and
whose values are the desired names.
**names : optional
Keyword form of ``name_dict``.
One of name_dict or names must be provided.
Returns
-------
renamed : Dataset
Dataset with renamed variables including coordinates
See Also
--------
Dataset.swap_dims
Dataset.rename
Dataset.rename_dims
DataArray.rename
"""
name_dict = either_dict_or_kwargs(name_dict, names, "rename_vars")
for k in name_dict:
if k not in self:
raise ValueError(
"cannot rename %r because it is not a "
"variable or coordinate in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict={}
)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def swap_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims_kwargs
) -> "Dataset":
"""Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names.
**dims_kwargs : {existing_dim: new_dim, ...}, optional
The keyword arguments form of ``dims_dict``.
One of dims_dict or dims_kwargs must be provided.
Returns
-------
swapped : Dataset
Dataset with swapped dimensions.
Examples
--------
>>> ds = xr.Dataset(
... data_vars={"a": ("x", [5, 7]), "b": ("x", [0.1, 2.4])},
... coords={"x": ["a", "b"], "y": ("x", [0, 1])},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 2)
Coordinates:
* x (x) <U1 'a' 'b'
y (x) int64 0 1
Data variables:
a (x) int64 5 7
b (x) float64 0.1 2.4
>>> ds.swap_dims({"x": "y"})
<xarray.Dataset>
Dimensions: (y: 2)
Coordinates:
x (y) <U1 'a' 'b'
* y (y) int64 0 1
Data variables:
a (y) int64 5 7
b (y) float64 0.1 2.4
>>> ds.swap_dims({"x": "z"})
<xarray.Dataset>
Dimensions: (z: 2)
Coordinates:
x (z) <U1 'a' 'b'
y (z) int64 0 1
Dimensions without coordinates: z
Data variables:
a (z) int64 5 7
b (z) float64 0.1 2.4
See Also
--------
Dataset.rename
DataArray.swap_dims
"""
# TODO: deprecate this method in favor of a (less confusing)
# rename_dims() method that only renames dimensions.
dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, "swap_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot swap from dimension %r because it is "
"not an existing dimension" % k
)
if v in self.variables and self.variables[v].dims != (k,):
raise ValueError(
"replacement dimension %r is not a 1D "
"variable along the old dimension %r" % (v, k)
)
result_dims = {dims_dict.get(dim, dim) for dim in self.dims}
coord_names = self._coord_names.copy()
coord_names.update({dim for dim in dims_dict.values() if dim in self.variables})
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for k, v in self.variables.items():
dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
if k in result_dims:
var = v.to_index_variable()
if k in self.indexes:
indexes[k] = self.indexes[k]
else:
new_index = var.to_index()
if new_index.nlevels == 1:
# make sure index name matches dimension name
new_index = new_index.rename(k)
indexes[k] = new_index
else:
var = v.to_base_variable()
var.dims = dims
variables[k] = var
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def expand_dims(
self,
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
axis: Union[None, int, Sequence[int]] = None,
**dim_kwargs: Any,
) -> "Dataset":
"""Return a new object with an additional axis (or axes) inserted at
the corresponding position in the array shape. The new object is a
view into the underlying array, not a copy.
If dim is already a scalar coordinate, it will be promoted to a 1D
coordinate consisting of a single value.
Parameters
----------
dim : hashable, sequence of hashable, mapping, or None
Dimensions to include on the new variable. If provided as hashable
or sequence of hashable, then dimensions are inserted with length
1. If provided as a mapping, then the keys are the new dimensions
and the values are either integers (giving the length of the new
dimensions) or array-like (giving the coordinates of the new
dimensions).
axis : int, sequence of int, or None
Axis position(s) where new axis is to be inserted (position(s) on
the result array). If a list (or tuple) of integers is passed,
multiple axes are inserted. In this case, dim arguments should be
same length list. If axis=None is passed, all the axes will be
inserted to the start of the result array.
**dim_kwargs : int or sequence or ndarray
The keywords are arbitrary dimensions being inserted and the values
are either the lengths of the new dims (if int is given), or their
coordinates. Note, this is an alternative to passing a dict to the
dim kwarg and will only be used if dim is None.
Returns
-------
expanded : same type as caller
This object, but with an additional dimension(s).
"""
if dim is None:
pass
elif isinstance(dim, Mapping):
# We're later going to modify dim in place; don't tamper with
# the input
dim = dict(dim)
elif isinstance(dim, int):
raise TypeError(
"dim should be hashable or sequence of hashables or mapping"
)
elif isinstance(dim, str) or not isinstance(dim, Sequence):
dim = {dim: 1}
elif isinstance(dim, Sequence):
if len(dim) != len(set(dim)):
raise ValueError("dims should not contain duplicate values.")
dim = {d: 1 for d in dim}
dim = either_dict_or_kwargs(dim, dim_kwargs, "expand_dims")
assert isinstance(dim, MutableMapping)
if axis is None:
axis = list(range(len(dim)))
elif not isinstance(axis, Sequence):
axis = [axis]
if len(dim) != len(axis):
raise ValueError("lengths of dim and axis should be identical.")
for d in dim:
if d in self.dims:
raise ValueError(f"Dimension {d} already exists.")
if d in self._variables and not utils.is_scalar(self._variables[d]):
raise ValueError(
"{dim} already exists as coordinate or"
" variable name.".format(dim=d)
)
variables: Dict[Hashable, Variable] = {}
coord_names = self._coord_names.copy()
# If dim is a dict, then ensure that the values are either integers
# or iterables.
for k, v in dim.items():
if hasattr(v, "__iter__"):
# If the value for the new dimension is an iterable, then
# save the coordinates to the variables dict, and set the
# value within the dim dict to the length of the iterable
# for later use.
variables[k] = xr.IndexVariable((k,), v)
coord_names.add(k)
dim[k] = variables[k].size
elif isinstance(v, int):
pass # Do nothing if the dimensions value is just an int
else:
raise TypeError(
"The value of new dimension {k} must be "
"an iterable or an int".format(k=k)
)
for k, v in self._variables.items():
if k not in dim:
if k in coord_names: # Do not change coordinates
variables[k] = v
else:
result_ndim = len(v.dims) + len(axis)
for a in axis:
if a < -result_ndim or result_ndim - 1 < a:
raise IndexError(
f"Axis {a} of variable {k} is out of bounds of the "
f"expanded dimension size {result_ndim}"
)
axis_pos = [a if a >= 0 else result_ndim + a for a in axis]
if len(axis_pos) != len(set(axis_pos)):
raise ValueError("axis should not contain duplicate values")
# We need to sort them to make sure `axis` equals to the
# axis positions of the result array.
zip_axis_dim = sorted(zip(axis_pos, dim.items()))
all_dims = list(zip(v.dims, v.shape))
for d, c in zip_axis_dim:
all_dims.insert(d, c)
variables[k] = v.set_dims(dict(all_dims))
else:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
variables[k] = v.set_dims(k).to_index_variable()
new_dims = self._dims.copy()
new_dims.update(dim)
return self._replace_vars_and_dims(
variables, dims=new_dims, coord_names=coord_names
)
def set_index(
self,
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
append: bool = False,
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
) -> "Dataset":
"""Set Dataset (multi-)indexes using one or more existing coordinates
or variables.
Parameters
----------
indexes : {dim: index, ...}
Mapping from names matching dimensions and values given
by (lists of) the names of existing coordinates or variables to set
as new (multi-)index.
append : bool, optional
If True, append the supplied index(es) to the existing index(es).
Otherwise replace the existing index(es) (default).
**indexes_kwargs : optional
The keyword arguments form of ``indexes``.
One of indexes or indexes_kwargs must be provided.
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced coordinates.
Examples
--------
>>> arr = xr.DataArray(
... data=np.ones((2, 3)),
... dims=["x", "y"],
... coords={"x": range(2), "y": range(3), "a": ("x", [3, 4])},
... )
>>> ds = xr.Dataset({"v": arr})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* x (x) int64 0 1
* y (y) int64 0 1 2
a (x) int64 3 4
Data variables:
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
>>> ds.set_index(x="a")
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* x (x) int64 3 4
* y (y) int64 0 1 2
Data variables:
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
See Also
--------
Dataset.reset_index
Dataset.swap_dims
"""
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, "set_index")
variables, coord_names = merge_indexes(
indexes, self._variables, self._coord_names, append=append
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reset_index(
self,
dims_or_levels: Union[Hashable, Sequence[Hashable]],
drop: bool = False,
) -> "Dataset":
"""Reset the specified index(es) or multi-index level(s).
Parameters
----------
dims_or_levels : str or list
Name(s) of the dimension(s) and/or multi-index level(s) that will
be reset.
drop : bool, optional
If True, remove the specified indexes and/or multi-index levels
instead of extracting them as new coordinates (default: False).
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced coordinates.
See Also
--------
Dataset.set_index
"""
variables, coord_names = split_indexes(
dims_or_levels,
self._variables,
self._coord_names,
cast(Mapping[Hashable, Hashable], self._level_coords),
drop=drop,
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reorder_levels(
self,
dim_order: Mapping[Hashable, Sequence[int]] = None,
**dim_order_kwargs: Sequence[int],
) -> "Dataset":
"""Rearrange index levels using input order.
Parameters
----------
dim_order : optional
Mapping from names matching dimensions and values given
by lists representing new level orders. Every given dimension
must have a multi-index.
**dim_order_kwargs : optional
The keyword arguments form of ``dim_order``.
One of dim_order or dim_order_kwargs must be provided.
Returns
-------
obj : Dataset
Another dataset, with this dataset's data but replaced
coordinates.
"""
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs, "reorder_levels")
variables = self._variables.copy()
indexes = dict(self.indexes)
for dim, order in dim_order.items():
coord = self._variables[dim]
index = self.indexes[dim]
if not isinstance(index, pd.MultiIndex):
raise ValueError(f"coordinate {dim} has no MultiIndex")
new_index = index.reorder_levels(order)
variables[dim] = IndexVariable(coord.dims, new_index)
indexes[dim] = new_index
return self._replace(variables, indexes=indexes)
def _stack_once(self, dims, new_dim):
if ... in dims:
dims = list(infix_dims(dims, self.dims))
variables = {}
for name, var in self.variables.items():
if name not in dims:
if any(d in var.dims for d in dims):
add_dims = [d for d in dims if d not in var.dims]
vdims = list(var.dims) + add_dims
shape = [self.dims[d] for d in vdims]
exp_var = var.set_dims(vdims, shape)
stacked_var = exp_var.stack(**{new_dim: dims})
variables[name] = stacked_var
else:
variables[name] = var.copy(deep=False)
# consider dropping levels that are unused?
levels = [self.get_index(dim) for dim in dims]
idx = utils.multiindex_from_product_levels(levels, names=dims)
variables[new_dim] = IndexVariable(new_dim, idx)
coord_names = set(self._coord_names) - set(dims) | {new_dim}
indexes = {k: v for k, v in self.indexes.items() if k not in dims}
indexes[new_dim] = idx
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def stack(
self,
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
**dimensions_kwargs: Sequence[Hashable],
) -> "Dataset":
"""
Stack any number of existing dimensions into a single new dimension.
New dimensions will be added at the end, and the corresponding
coordinate variables will be combined into a MultiIndex.
Parameters
----------
dimensions : mapping of hashable to sequence of hashable
Mapping of the form `new_name=(dim1, dim2, ...)`. Names of new
dimensions, and the existing dimensions that they replace. An
ellipsis (`...`) will be replaced by all unlisted dimensions.
Passing a list containing an ellipsis (`stacked_dim=[...]`) will stack over
all dimensions.
**dimensions_kwargs
The keyword arguments form of ``dimensions``.
One of dimensions or dimensions_kwargs must be provided.
Returns
-------
stacked : Dataset
Dataset with stacked data.
See Also
--------
Dataset.unstack
"""
dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, "stack")
result = self
for new_dim, dims in dimensions.items():
result = result._stack_once(dims, new_dim)
return result
def to_stacked_array(
self,
new_dim: Hashable,
sample_dims: Sequence[Hashable],
variable_dim: str = "variable",
name: Hashable = None,
) -> "DataArray":
"""Combine variables of differing dimensionality into a DataArray
without broadcasting.
This method is similar to Dataset.to_array but does not broadcast the
variables.
Parameters
----------
new_dim : hashable
Name of the new stacked coordinate
sample_dims : sequence of hashable
Dimensions that **will not** be stacked. Each array in the dataset
must share these dimensions. For machine learning applications,
these define the dimensions over which samples are drawn.
variable_dim : str, optional
Name of the level in the stacked coordinate which corresponds to
the variables.
name : str, optional
Name of the new data array.
Returns
-------
stacked : DataArray
DataArray with the specified dimensions and data variables
stacked together. The stacked coordinate is named ``new_dim``
and represented by a MultiIndex object with a level containing the
data variable names. The name of this level is controlled using
the ``variable_dim`` argument.
See Also
--------
Dataset.to_array
Dataset.stack
DataArray.to_unstacked_dataset
Examples
--------
>>> data = xr.Dataset(
... data_vars={
... "a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]),
... "b": ("x", [6, 7]),
... },
... coords={"y": ["u", "v", "w"]},
... )
>>> data
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'u' 'v' 'w'
Dimensions without coordinates: x
Data variables:
a (x, y) int64 0 1 2 3 4 5
b (x) int64 6 7
>>> data.to_stacked_array("z", sample_dims=["x"])
<xarray.DataArray 'a' (x: 2, z: 4)>
array([[0, 1, 2, 6],
[3, 4, 5, 7]])
Coordinates:
* z (z) MultiIndex
- variable (z) object 'a' 'a' 'a' 'b'
- y (z) object 'u' 'v' 'w' nan
Dimensions without coordinates: x
"""
stacking_dims = tuple(dim for dim in self.dims if dim not in sample_dims)
for variable in self:
dims = self[variable].dims
dims_include_sample_dims = set(sample_dims) <= set(dims)
if not dims_include_sample_dims:
raise ValueError(
"All variables in the dataset must contain the "
"dimensions {}.".format(dims)
)
def ensure_stackable(val):
assign_coords = {variable_dim: val.name}
for dim in stacking_dims:
if dim not in val.dims:
assign_coords[dim] = None
expand_dims = set(stacking_dims).difference(set(val.dims))
expand_dims.add(variable_dim)
# must be list for .expand_dims
expand_dims = list(expand_dims)
return (
val.assign_coords(**assign_coords)
.expand_dims(expand_dims)
.stack({new_dim: (variable_dim,) + stacking_dims})
)
# concatenate the arrays
stackable_vars = [ensure_stackable(self[key]) for key in self.data_vars]
data_array = xr.concat(stackable_vars, dim=new_dim)
# coerce the levels of the MultiIndex to have the same type as the
# input dimensions. This code is messy, so it might be better to just
# input a dummy value for the singleton dimension.
idx = data_array.indexes[new_dim]
levels = [idx.levels[0]] + [
level.astype(self[level.name].dtype) for level in idx.levels[1:]
]
new_idx = idx.set_levels(levels)
data_array[new_dim] = IndexVariable(new_dim, new_idx)
if name is not None:
data_array.name = name
return data_array
def _unstack_once(self, dim: Hashable, fill_value) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in self.variables.items():
if name != dim:
if dim in var.dims:
if isinstance(fill_value, Mapping):
fill_value_ = fill_value[name]
else:
fill_value_ = fill_value
variables[name] = var._unstack_once(
index=index, dim=dim, fill_value=fill_value_
)
else:
variables[name] = var
for name, lev in zip(index.names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(index.names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def _unstack_full_reindex(
self, dim: Hashable, fill_value, sparse: bool
) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
full_idx = pd.MultiIndex.from_product(index.levels, names=index.names)
# take a shortcut in case the MultiIndex was not modified.
if index.equals(full_idx):
obj = self
else:
obj = self._reindex(
{dim: full_idx}, copy=False, fill_value=fill_value, sparse=sparse
)
new_dim_names = index.names
new_dim_sizes = [lev.size for lev in index.levels]
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in obj.variables.items():
if name != dim:
if dim in var.dims:
new_dims = dict(zip(new_dim_names, new_dim_sizes))
variables[name] = var.unstack({dim: new_dims})
else:
variables[name] = var
for name, lev in zip(new_dim_names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(new_dim_names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def unstack(
self,
dim: Union[Hashable, Iterable[Hashable]] = None,
fill_value: Any = dtypes.NA,
sparse: bool = False,
) -> "Dataset":
"""
Unstack existing dimensions corresponding to MultiIndexes into
multiple new dimensions.
New dimensions will be added at the end.
Parameters
----------
dim : hashable or iterable of hashable, optional
Dimension(s) over which to unstack. By default unstacks all
MultiIndexes.
fill_value : scalar or dict-like, default: nan
value to be filled. If a dict-like, maps variable names to
fill values. If not provided or if the dict-like does not
contain all variables, the dtype's NA value will be used.
sparse : bool, default: False
use sparse-array if True
Returns
-------
unstacked : Dataset
Dataset with unstacked data.
See Also
--------
Dataset.stack
"""
if dim is None:
dims = [
d for d in self.dims if isinstance(self.get_index(d), pd.MultiIndex)
]
else:
if isinstance(dim, str) or not isinstance(dim, Iterable):
dims = [dim]
else:
dims = list(dim)
missing_dims = [d for d in dims if d not in self.dims]
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
non_multi_dims = [
d for d in dims if not isinstance(self.get_index(d), pd.MultiIndex)
]
if non_multi_dims:
raise ValueError(
"cannot unstack dimensions that do not "
"have a MultiIndex: %s" % non_multi_dims
)
result = self.copy(deep=False)
for dim in dims:
if (
# Dask arrays don't support assignment by index, which the fast unstack
# function requires.
# https://github.com/pydata/xarray/pull/4746#issuecomment-753282125
any(is_duck_dask_array(v.data) for v in self.variables.values())
# Sparse doesn't currently support (though we could special-case
# it)
# https://github.com/pydata/sparse/issues/422
or any(
isinstance(v.data, sparse_array_type)
for v in self.variables.values()
)
or sparse
# numpy full_like only added `shape` in 1.17
or LooseVersion(np.__version__) < LooseVersion("1.17")
# Until https://github.com/pydata/xarray/pull/4751 is resolved,
# we check explicitly whether it's a numpy array. Once that is
# resolved, explicitly exclude pint arrays.
# # pint doesn't implement `np.full_like` in a way that's
# # currently compatible.
# # https://github.com/pydata/xarray/pull/4746#issuecomment-753425173
# # or any(
# # isinstance(v.data, pint_array_type) for v in self.variables.values()
# # )
or any(
not isinstance(v.data, np.ndarray) for v in self.variables.values()
)
):
result = result._unstack_full_reindex(dim, fill_value, sparse)
else:
result = result._unstack_once(dim, fill_value)
return result
def update(self, other: "CoercibleMapping") -> "Dataset":
"""Update this dataset's variables with those from another dataset.
Just like :py:meth:`dict.update` this is a in-place operation.
Parameters
----------
other : Dataset or mapping
Variables with which to update this dataset. One of:
- Dataset
- mapping {var name: DataArray}
- mapping {var name: Variable}
- mapping {var name: (dimension name, array-like)}
- mapping {var name: (tuple of dimension names, array-like)}
Returns
-------
updated : Dataset
Updated dataset. Note that since the update is in-place this is the input
dataset.
It is deprecated since version 0.17 and scheduled to be removed in 0.19.
Raises
------
ValueError
If any dimensions would have inconsistent sizes in the updated
dataset.
See Also
--------
Dataset.assign
"""
merge_result = dataset_update_method(self, other)
return self._replace(inplace=True, **merge_result._asdict())
def merge(
self,
other: Union["CoercibleMapping", "DataArray"],
overwrite_vars: Union[Hashable, Iterable[Hashable]] = frozenset(),
compat: str = "no_conflicts",
join: str = "outer",
fill_value: Any = dtypes.NA,
combine_attrs: str = "override",
) -> "Dataset":
"""Merge the arrays of two datasets into a single dataset.
This method generally does not allow for overriding data, with the
exception of attributes, which are ignored on the second dataset.
Variables with the same name are checked for conflicts via the equals
or identical methods.
Parameters
----------
other : Dataset or mapping
Dataset or variables to merge with this dataset.
overwrite_vars : hashable or iterable of hashable, optional
If provided, update variables of these name(s) without checking for
conflicts in this dataset.
compat : {"broadcast_equals", "equals", "identical", \
"no_conflicts"}, optional
String indicating how to compare variables of the same name for
potential conflicts:
- 'broadcast_equals': all values must be equal when variables are
broadcast against each other to ensure common dimensions.
- 'equals': all values and dimensions must be the same.
- 'identical': all values, dimensions and attributes must be the
same.
- 'no_conflicts': only values which are not null in both datasets
must be equal. The returned dataset then contains the combination
of all non-null values.
join : {"outer", "inner", "left", "right", "exact"}, optional
Method for joining ``self`` and ``other`` along shared dimensions:
- 'outer': use the union of the indexes
- 'inner': use the intersection of the indexes
- 'left': use indexes from ``self``
- 'right': use indexes from ``other``
- 'exact': error instead of aligning non-equal indexes
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like, maps
variable names (including coordinates) to fill values.
combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts", \
"override"}, default: "override"
String indicating how to combine attrs of the objects being merged:
- "drop": empty attrs on returned Dataset.
- "identical": all attrs must be the same on every object.
- "no_conflicts": attrs from all objects are combined, any that have
the same name must also have the same value.
- "drop_conflicts": attrs from all objects are combined, any that have
the same name but different values are dropped.
- "override": skip comparing and copy attrs from the first dataset to
the result.
Returns
-------
merged : Dataset
Merged dataset.
Raises
------
MergeError
If any variables conflict (see ``compat``).
"""
other = other.to_dataset() if isinstance(other, xr.DataArray) else other
merge_result = dataset_merge_method(
self,
other,
overwrite_vars=overwrite_vars,
compat=compat,
join=join,
fill_value=fill_value,
combine_attrs=combine_attrs,
)
return self._replace(**merge_result._asdict())
def _assert_all_in_dataset(
self, names: Iterable[Hashable], virtual_okay: bool = False
) -> None:
bad_names = set(names) - set(self._variables)
if virtual_okay:
bad_names -= self.virtual_variables
if bad_names:
raise ValueError(
"One or more of the specified variables "
"cannot be found in this dataset"
)
def drop_vars(
self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
"""Drop variables from this dataset.
Parameters
----------
names : hashable or iterable of hashable
Name(s) of variables to drop.
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if any of the variable
passed are not in the dataset. If 'ignore', any given names that are in the
dataset are dropped and no error is raised.
Returns
-------
dropped : Dataset
"""
# the Iterable check is required for mypy
if is_scalar(names) or not isinstance(names, Iterable):
names = {names}
else:
names = set(names)
if errors == "raise":
self._assert_all_in_dataset(names)
variables = {k: v for k, v in self._variables.items() if k not in names}
coord_names = {k for k in self._coord_names if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k not in names}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def drop(self, labels=None, dim=None, *, errors="raise", **labels_kwargs):
"""Backward compatible method based on `drop_vars` and `drop_sel`
Using either `drop_vars` or `drop_sel` is encouraged
See Also
--------
Dataset.drop_vars
Dataset.drop_sel
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if is_dict_like(labels) and not isinstance(labels, dict):
warnings.warn(
"dropping coordinates using `drop` is be deprecated; use drop_vars.",
FutureWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if labels_kwargs or isinstance(labels, dict):
if dim is not None:
raise ValueError("cannot specify dim and dict-like arguments.")
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop")
if dim is None and (is_scalar(labels) or isinstance(labels, Iterable)):
warnings.warn(
"dropping variables using `drop` will be deprecated; using drop_vars is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if dim is not None:
warnings.warn(
"dropping labels using list-like labels is deprecated; using "
"dict-like arguments with `drop_sel`, e.g. `ds.drop_sel(dim=[labels]).",
DeprecationWarning,
stacklevel=2,
)
return self.drop_sel({dim: labels}, errors=errors, **labels_kwargs)
warnings.warn(
"dropping labels using `drop` will be deprecated; using drop_sel is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_sel(labels, errors=errors)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
"""Drop index labels from this dataset.
Parameters
----------
labels : mapping of hashable to Any
Index labels to drop
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if
any of the index labels passed are not
in the dataset. If 'ignore', any given labels that are in the
dataset are dropped and no error is raised.
**labels_kwargs : {dim: label, ...}, optional
The keyword arguments form of ``dim`` and ``labels``
Returns
-------
dropped : Dataset
Examples
--------
>>> data = np.arange(6).reshape(2, 3)
>>> labels = ["a", "b", "c"]
>>> ds = xr.Dataset({"A": (["x", "y"], data), "y": labels})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'a' 'b' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 1 2 3 4 5
>>> ds.drop_sel(y=["a", "c"])
<xarray.Dataset>
Dimensions: (x: 2, y: 1)
Coordinates:
* y (y) <U1 'b'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 1 4
>>> ds.drop_sel(y="b")
<xarray.Dataset>
Dimensions: (x: 2, y: 2)
Coordinates:
* y (y) <U1 'a' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 2 3 5
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
ds = self
for dim, labels_for_dim in labels.items():
# Don't cast to set, as it would harm performance when labels
# is a large numpy array
if utils.is_scalar(labels_for_dim):
labels_for_dim = [labels_for_dim]
labels_for_dim = np.asarray(labels_for_dim)
try:
index = self.get_index(dim)
except KeyError:
raise ValueError("dimension %r does not have coordinate labels" % dim)
new_index = index.drop(labels_for_dim, errors=errors)
ds = ds.loc[{dim: new_index}]
return ds
def drop_isel(self, indexers=None, **indexers_kwargs):
"""Drop index positions from this Dataset.
Parameters
----------
indexers : mapping of hashable to Any
Index locations to drop
**indexers_kwargs : {dim: position, ...}, optional
The keyword arguments form of ``dim`` and ``positions``
Returns
-------
dropped : Dataset
Raises
------
IndexError
Examples
--------
>>> data = np.arange(6).reshape(2, 3)
>>> labels = ["a", "b", "c"]
>>> ds = xr.Dataset({"A": (["x", "y"], data), "y": labels})
>>> ds
<xarray.Dataset>
Dimensions: (x: 2, y: 3)
Coordinates:
* y (y) <U1 'a' 'b' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 1 2 3 4 5
>>> ds.drop_isel(y=[0, 2])
<xarray.Dataset>
Dimensions: (x: 2, y: 1)
Coordinates:
* y (y) <U1 'b'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 1 4
>>> ds.drop_isel(y=1)
<xarray.Dataset>
Dimensions: (x: 2, y: 2)
Coordinates:
* y (y) <U1 'a' 'c'
Dimensions without coordinates: x
Data variables:
A (x, y) int64 0 2 3 5
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "drop_isel")
ds = self
dimension_index = {}
for dim, pos_for_dim in indexers.items():
# Don't cast to set, as it would harm performance when labels
# is a large numpy array
if utils.is_scalar(pos_for_dim):
pos_for_dim = [pos_for_dim]
pos_for_dim = np.asarray(pos_for_dim)
index = self.get_index(dim)
new_index = index.delete(pos_for_dim)
dimension_index[dim] = new_index
ds = ds.loc[dimension_index]
return ds
def drop_dims(
self, drop_dims: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
"""Drop dimensions and associated variables from this dataset.
Parameters
----------
drop_dims : hashable or iterable of hashable
Dimension or dimensions to drop.
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if any of the
dimensions passed are not in the dataset. If 'ignore', any given
labels that are in the dataset are dropped and no error is raised.
Returns
-------
obj : Dataset
The dataset without the given dimensions (or any variables
containing those dimensions)
errors : {"raise", "ignore"}, optional
If 'raise' (default), raises a ValueError error if
any of the dimensions passed are not
in the dataset. If 'ignore', any given dimensions that are in the
dataset are dropped and no error is raised.
"""
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if isinstance(drop_dims, str) or not isinstance(drop_dims, Iterable):
drop_dims = {drop_dims}
else:
drop_dims = set(drop_dims)
if errors == "raise":
missing_dims = drop_dims - set(self.dims)
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}
return self.drop_vars(drop_vars)
def transpose(self, *dims: Hashable) -> "Dataset":
"""Return a new Dataset object with all array dimensions transposed.
Although the order of dimensions on each array will change, the dataset
dimensions themselves will remain in fixed (sorted) order.
Parameters
----------
*dims : hashable, optional
By default, reverse the dimensions on each array. Otherwise,
reorder the dimensions to this order.
Returns
-------
transposed : Dataset
Each array in the dataset (including) coordinates will be
transposed to the given order.
Notes
-----
This operation returns a view of each array's data. It is
lazy for dask-backed DataArrays but not for numpy-backed DataArrays
-- the data will be fully loaded into memory.
See Also
--------
numpy.transpose
DataArray.transpose
"""
if dims:
if set(dims) ^ set(self.dims) and ... not in dims:
raise ValueError(
"arguments to transpose (%s) must be "
"permuted dataset dimensions (%s)" % (dims, tuple(self.dims))
)
ds = self.copy()
for name, var in self._variables.items():
var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))
ds._variables[name] = var.transpose(*var_dims)
return ds
def dropna(
self,
dim: Hashable,
how: str = "any",
thresh: int = None,
subset: Iterable[Hashable] = None,
):
"""Returns a new dataset with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : hashable
Dimension along which to drop missing values. Dropping along
multiple dimensions simultaneously is not yet supported.
how : {"any", "all"}, default: "any"
* any : if any NA values are present, drop that label
* all : if all values are NA, drop that label
thresh : int, default: None
If supplied, require this many non-NA values.
subset : iterable of hashable, optional
Which variables to check for missing values. By default, all
variables in the dataset are checked.
Returns
-------
Dataset
"""
# TODO: consider supporting multiple dimensions? Or not, given that
# there are some ugly edge cases, e.g., pandas's dropna differs
# depending on the order of the supplied axes.
if dim not in self.dims:
raise ValueError("%s must be a single dataset dimension" % dim)
if subset is None:
subset = iter(self.data_vars)
count = np.zeros(self.dims[dim], dtype=np.int64)
size = np.int_(0) # for type checking
for k in subset:
array = self._variables[k]
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += np.asarray(array.count(dims)) # type: ignore[attr-defined]
size += np.prod([self.dims[d] for d in dims])
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == size
elif how == "all":
mask = count > 0
elif how is not None:
raise ValueError("invalid how option: %s" % how)
else:
raise TypeError("must specify how or thresh")
return self.isel({dim: mask})
def fillna(self, value: Any) -> "Dataset":
"""Fill missing values in this object.
This operation follows the normal broadcasting and alignment rules that
xarray uses for binary arithmetic, except the result is aligned to this
object (``join='left'``) instead of aligned to the intersection of
index coordinates (``join='inner'``).
Parameters
----------
value : scalar, ndarray, DataArray, dict or Dataset
Used to fill all matching missing values in this dataset's data
variables. Scalars, ndarrays or DataArrays arguments are used to
fill all data with aligned coordinates (for DataArrays).
Dictionaries or datasets match data variables and then align
coordinates if necessary.
Returns
-------
Dataset
Examples
--------
>>> import numpy as np
>>> import xarray as xr
>>> ds = xr.Dataset(
... {
... "A": ("x", [np.nan, 2, np.nan, 0]),
... "B": ("x", [3, 4, np.nan, 1]),
... "C": ("x", [np.nan, np.nan, np.nan, 5]),
... "D": ("x", [np.nan, 3, np.nan, 4]),
... },
... coords={"x": [0, 1, 2, 3]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 nan 2.0 nan 0.0
B (x) float64 3.0 4.0 nan 1.0
C (x) float64 nan nan nan 5.0
D (x) float64 nan 3.0 nan 4.0
Replace all `NaN` values with 0s.
>>> ds.fillna(0)
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 0.0 2.0 0.0 0.0
B (x) float64 3.0 4.0 0.0 1.0
C (x) float64 0.0 0.0 0.0 5.0
D (x) float64 0.0 3.0 0.0 4.0
Replace all `NaN` elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.
>>> values = {"A": 0, "B": 1, "C": 2, "D": 3}
>>> ds.fillna(value=values)
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
Data variables:
A (x) float64 0.0 2.0 0.0 0.0
B (x) float64 3.0 4.0 1.0 1.0
C (x) float64 2.0 2.0 2.0 5.0
D (x) float64 3.0 3.0 3.0 4.0
"""
if utils.is_dict_like(value):
value_keys = getattr(value, "data_vars", value).keys()
if not set(value_keys) <= set(self.data_vars.keys()):
raise ValueError(
"all variables in the argument to `fillna` "
"must be contained in the original dataset"
)
out = ops.fillna(self, value)
return out
def interpolate_na(
self,
dim: Hashable = None,
method: str = "linear",
limit: int = None,
use_coordinate: Union[bool, Hashable] = True,
max_gap: Union[
int, float, str, pd.Timedelta, np.timedelta64, datetime.timedelta
] = None,
**kwargs: Any,
) -> "Dataset":
"""Fill in NaNs by interpolating according to different methods.
Parameters
----------
dim : str
Specifies the dimension along which to interpolate.
method : str, optional
String indicating which method to use for interpolation:
- 'linear': linear interpolation (Default). Additional keyword
arguments are passed to :py:func:`numpy.interp`
- 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'polynomial':
are passed to :py:func:`scipy.interpolate.interp1d`. If
``method='polynomial'``, the ``order`` keyword argument must also be
provided.
- 'barycentric', 'krog', 'pchip', 'spline', 'akima': use their
respective :py:class:`scipy.interpolate` classes.
use_coordinate : bool, str, default: True
Specifies which index to use as the x values in the interpolation
formulated as `y = f(x)`. If False, values are treated as if
eqaully-spaced along ``dim``. If True, the IndexVariable `dim` is
used. If ``use_coordinate`` is a string, it specifies the name of a
coordinate variariable to use as the index.
limit : int, default: None
Maximum number of consecutive NaNs to fill. Must be greater than 0
or None for no limit. This filling is done regardless of the size of
the gap in the data. To only interpolate over gaps less than a given length,
see ``max_gap``.
max_gap : int, float, str, pandas.Timedelta, numpy.timedelta64, datetime.timedelta, default: None
Maximum size of gap, a continuous sequence of NaNs, that will be filled.
Use None for no limit. When interpolating along a datetime64 dimension
and ``use_coordinate=True``, ``max_gap`` can be one of the following:
- a string that is valid input for pandas.to_timedelta
- a :py:class:`numpy.timedelta64` object
- a :py:class:`pandas.Timedelta` object
- a :py:class:`datetime.timedelta` object
Otherwise, ``max_gap`` must be an int or a float. Use of ``max_gap`` with unlabeled
dimensions has not been implemented yet. Gap length is defined as the difference
between coordinate values at the first data point after a gap and the last value
before a gap. For gaps at the beginning (end), gap length is defined as the difference
between coordinate values at the first (last) valid data point and the first (last) NaN.
For example, consider::
<xarray.DataArray (x: 9)>
array([nan, nan, nan, 1., nan, nan, 4., nan, nan])
Coordinates:
* x (x) int64 0 1 2 3 4 5 6 7 8
The gap lengths are 3-0 = 3; 6-3 = 3; and 8-6 = 2 respectively
kwargs : dict, optional
parameters passed verbatim to the underlying interpolation function
Returns
-------
interpolated: Dataset
Filled in Dataset.
See Also
--------
numpy.interp
scipy.interpolate
Examples
--------
>>> ds = xr.Dataset(
... {
... "A": ("x", [np.nan, 2, 3, np.nan, 0]),
... "B": ("x", [3, 4, np.nan, 1, 7]),
... "C": ("x", [np.nan, np.nan, np.nan, 5, 0]),
... "D": ("x", [np.nan, 3, np.nan, -1, 4]),
... },
... coords={"x": [0, 1, 2, 3, 4]},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 nan 2.0 3.0 nan 0.0
B (x) float64 3.0 4.0 nan 1.0 7.0
C (x) float64 nan nan nan 5.0 0.0
D (x) float64 nan 3.0 nan -1.0 4.0
>>> ds.interpolate_na(dim="x", method="linear")
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 nan 2.0 3.0 1.5 0.0
B (x) float64 3.0 4.0 2.5 1.0 7.0
C (x) float64 nan nan nan 5.0 0.0
D (x) float64 nan 3.0 1.0 -1.0 4.0
>>> ds.interpolate_na(dim="x", method="linear", fill_value="extrapolate")
<xarray.Dataset>
Dimensions: (x: 5)
Coordinates:
* x (x) int64 0 1 2 3 4
Data variables:
A (x) float64 1.0 2.0 3.0 1.5 0.0
B (x) float64 3.0 4.0 2.5 1.0 7.0
C (x) float64 20.0 15.0 10.0 5.0 0.0
D (x) float64 5.0 3.0 1.0 -1.0 4.0
"""
from .missing import _apply_over_vars_with_dim, interp_na
new = _apply_over_vars_with_dim(
interp_na,
self,
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
**kwargs,
)
return new
def ffill(self, dim: Hashable, limit: int = None) -> "Dataset":
"""Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : Hashable
Specifies the dimension along which to propagate values when
filling.
limit : int, default: None
The maximum number of consecutive NaN values to forward fill. In
other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. Must be greater
than 0 or None for no limit.
Returns
-------
Dataset
"""
from .missing import _apply_over_vars_with_dim, ffill
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
return new
def bfill(self, dim: Hashable, limit: int = None) -> "Dataset":
"""Fill NaN values by propogating values backward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default: None
The maximum number of consecutive NaN values to backward fill. In
other words, if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled. Must be greater
than 0 or None for no limit.
Returns
-------
Dataset
"""
from .missing import _apply_over_vars_with_dim, bfill
new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit)
return new
def combine_first(self, other: "Dataset") -> "Dataset":
"""Combine two Datasets, default to data_vars of self.
The new coordinates follow the normal broadcasting and alignment rules
of ``join='outer'``. Vacant cells in the expanded coordinates are
filled with np.nan.
Parameters
----------
other : Dataset
Used to fill all matching missing values in this array.
Returns
-------
Dataset
"""
out = ops.fillna(self, other, join="outer", dataset_join="outer")
return out
def reduce(
self,
func: Callable,
dim: Union[Hashable, Iterable[Hashable]] = None,
keep_attrs: bool = None,
keepdims: bool = False,
numeric_only: bool = False,
**kwargs: Any,
) -> "Dataset":
"""Reduce this dataset by applying `func` along some dimension(s).
Parameters
----------
func : callable
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim : str or sequence of str, optional
Dimension(s) over which to apply `func`. By default `func` is
applied over all dimensions.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
keepdims : bool, default: False
If True, the dimensions which are reduced are left in the result
as dimensions of size one. Coordinates that use these dimensions
are removed.
numeric_only : bool, optional
If True, only apply ``func`` to variables with a numeric dtype.
**kwargs : Any
Additional keyword arguments passed on to ``func``.
Returns
-------
reduced : Dataset
Dataset with this object's DataArrays replaced with new DataArrays
of summarized data and the indicated dimension(s) removed.
"""
if "axis" in kwargs:
raise ValueError(
"passing 'axis' to Dataset reduce methods is ambiguous."
" Please use 'dim' instead."
)
if dim is None or dim is ...:
dims = set(self.dims)
elif isinstance(dim, str) or not isinstance(dim, Iterable):
dims = {dim}
else:
dims = set(dim)
missing_dimensions = [d for d in dims if d not in self.dims]
if missing_dimensions:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dimensions
)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables: Dict[Hashable, Variable] = {}
for name, var in self._variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if name in self.coords:
if not reduce_dims:
variables[name] = var
else:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
):
if len(reduce_dims) == 1:
# unpack dimensions for the benefit of functions
# like np.argmin which can't handle tuple arguments
(reduce_dims,) = reduce_dims
elif len(reduce_dims) == var.ndim:
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
reduce_dims = None # type: ignore[assignment]
variables[name] = var.reduce(
func,
dim=reduce_dims,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
attrs = self.attrs if keep_attrs else None
return self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
def map(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
"""Apply a function to each variable in this dataset
Parameters
----------
func : callable
Function which can be called in the form `func(x, *args, **kwargs)`
to transform each DataArray `x` in this dataset into another
DataArray.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False, the new object will
be returned without attributes.
args : tuple, optional
Positional arguments passed on to `func`.
**kwargs : Any
Keyword arguments passed on to `func`.
Returns
-------
applied : Dataset
Resulting dataset from applying ``func`` to each data variable.
Examples
--------
>>> da = xr.DataArray(np.random.randn(2, 3))
>>> ds = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])})
>>> ds
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Dimensions without coordinates: dim_0, dim_1, x
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 -0.9773
bar (x) int64 -1 2
>>> ds.map(np.fabs)
<xarray.Dataset>
Dimensions: (dim_0: 2, dim_1: 3, x: 2)
Dimensions without coordinates: dim_0, dim_1, x
Data variables:
foo (dim_0, dim_1) float64 1.764 0.4002 0.9787 2.241 1.868 0.9773
bar (x) float64 1.0 2.0
"""
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables = {
k: maybe_wrap_array(v, func(v, *args, **kwargs))
for k, v in self.data_vars.items()
}
if keep_attrs:
for k, v in variables.items():
v._copy_attrs_from(self.data_vars[k])
attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
def apply(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
"""
Backward compatible implementation of ``map``
See Also
--------
Dataset.map
"""
warnings.warn(
"Dataset.apply may be deprecated in the future. Using Dataset.map is encouraged",
PendingDeprecationWarning,
stacklevel=2,
)
return self.map(func, keep_attrs, args, **kwargs)
def assign(
self, variables: Mapping[Hashable, Any] = None, **variables_kwargs: Hashable
) -> "Dataset":
"""Assign new data variables to a Dataset, returning a new object
with all the original variables in addition to the new ones.
Parameters
----------
variables : mapping of hashable to Any
Mapping from variables names to the new values. If the new values
are callable, they are computed on the Dataset and assigned to new
data variables. If the values are not callable, (e.g. a DataArray,
scalar, or array), they are simply assigned.
**variables_kwargs
The keyword arguments form of ``variables``.
One of variables or variables_kwargs must be provided.
Returns
-------
ds : Dataset
A new Dataset with the new variables in addition to all the
existing variables.
Notes
-----
Since ``kwargs`` is a dictionary, the order of your arguments may not
be preserved, and so the order of the new variables is not well
defined. Assigning multiple variables within the same ``assign`` is
possible, but you cannot reference other variables created within the
same ``assign`` call.
See Also
--------
pandas.DataFrame.assign
Examples
--------
>>> x = xr.Dataset(
... {
... "temperature_c": (
... ("lat", "lon"),
... 20 * np.random.rand(4).reshape(2, 2),
... ),
... "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)),
... },
... coords={"lat": [10, 20], "lon": [150, 160]},
... )
>>> x
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
Where the value is a callable, evaluated on dataset:
>>> x.assign(temperature_f=lambda x: x.temperature_c * 9 / 5 + 32)
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
temperature_f (lat, lon) float64 51.76 57.75 53.7 51.62
Alternatively, the same behavior can be achieved by directly referencing an existing dataarray:
>>> x.assign(temperature_f=x["temperature_c"] * 9 / 5 + 32)
<xarray.Dataset>
Dimensions: (lat: 2, lon: 2)
Coordinates:
* lat (lat) int64 10 20
* lon (lon) int64 150 160
Data variables:
temperature_c (lat, lon) float64 10.98 14.3 12.06 10.9
precipitation (lat, lon) float64 0.4237 0.6459 0.4376 0.8918
temperature_f (lat, lon) float64 51.76 57.75 53.7 51.62
"""
variables = either_dict_or_kwargs(variables, variables_kwargs, "assign")
data = self.copy()
# do all calculations first...
results = data._calc_assign_results(variables)
# ... and then assign
data.update(results)
return data
def to_array(self, dim="variable", name=None):
"""Convert this dataset into an xarray.DataArray
The data variables of this dataset will be broadcast against each other
and stacked along the first axis of the new array. All coordinates of
this dataset will remain coordinates.
Parameters
----------
dim : str, optional
Name of the new dimension.
name : str, optional
Name of the new data array.
Returns
-------
array : xarray.DataArray
"""
from .dataarray import DataArray
data_vars = [self.variables[k] for k in self.data_vars]
broadcast_vars = broadcast_variables(*data_vars)
data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)
coords = dict(self.coords)
coords[dim] = list(self.data_vars)
indexes = propagate_indexes(self._indexes)
dims = (dim,) + broadcast_vars[0].dims
return DataArray(
data, coords, dims, attrs=self.attrs, name=name, indexes=indexes
)
def _normalize_dim_order(
self, dim_order: List[Hashable] = None
) -> Dict[Hashable, int]:
"""
Check the validity of the provided dimensions if any and return the mapping
between dimension name and their size.
Parameters
----------
dim_order
Dimension order to validate (default to the alphabetical order if None).
Returns
-------
result
Validated dimensions mapping.
"""
if dim_order is None:
dim_order = list(self.dims)
elif set(dim_order) != set(self.dims):
raise ValueError(
"dim_order {} does not match the set of dimensions of this "
"Dataset: {}".format(dim_order, list(self.dims))
)
ordered_dims = {k: self.dims[k] for k in dim_order}
return ordered_dims
def _to_dataframe(self, ordered_dims: Mapping[Hashable, int]):
columns = [k for k in self.variables if k not in self.dims]
data = [
self._variables[k].set_dims(ordered_dims).values.reshape(-1)
for k in columns
]
index = self.coords.to_index([*ordered_dims])
return pd.DataFrame(dict(zip(columns, data)), index=index)
def to_dataframe(self, dim_order: List[Hashable] = None) -> pd.DataFrame:
"""Convert this dataset into a pandas.DataFrame.
Non-index variables in this dataset form the columns of the
DataFrame. The DataFrame is indexed by the Cartesian product of
this dataset's indices.
Parameters
----------
dim_order
Hierarchical dimension order for the resulting dataframe. All
arrays are transposed to this order and then written out as flat
vectors in contiguous order, so the last dimension in this list
will be contiguous in the resulting DataFrame. This has a major
influence on which operations are efficient on the resulting
dataframe.
If provided, must include all dimensions of this dataset. By
default, dimensions are sorted alphabetically.
Returns
-------
result
Dataset as a pandas DataFrame.
"""
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
return self._to_dataframe(ordered_dims=ordered_dims)
def _set_sparse_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
from sparse import COO
if isinstance(idx, pd.MultiIndex):
coords = np.stack([np.asarray(code) for code in idx.codes], axis=0)
is_sorted = idx.is_lexsorted()
shape = tuple(lev.size for lev in idx.levels)
else:
coords = np.arange(idx.size).reshape(1, -1)
is_sorted = True
shape = (idx.size,)
for name, values in arrays:
# In virtually all real use cases, the sparse array will now have
# missing values and needs a fill_value. For consistency, don't
# special case the rare exceptions (e.g., dtype=int without a
# MultiIndex).
dtype, fill_value = dtypes.maybe_promote(values.dtype)
values = np.asarray(values, dtype=dtype)
data = COO(
coords,
values,
shape,
has_duplicates=False,
sorted=is_sorted,
fill_value=fill_value,
)
self[name] = (dims, data)
def _set_numpy_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
if not isinstance(idx, pd.MultiIndex):
for name, values in arrays:
self[name] = (dims, values)
return
# NB: similar, more general logic, now exists in
# variable.unstack_once; we could consider combining them at some
# point.
shape = tuple(lev.size for lev in idx.levels)
indexer = tuple(idx.codes)
# We already verified that the MultiIndex has all unique values, so
# there are missing values if and only if the size of output arrays is
# larger that the index.
missing_values = np.prod(shape) > idx.shape[0]
for name, values in arrays:
# NumPy indexing is much faster than using DataFrame.reindex() to
# fill in missing values:
# https://stackoverflow.com/a/35049899/809705
if missing_values:
dtype, fill_value = dtypes.maybe_promote(values.dtype)
data = np.full(shape, fill_value, dtype)
else:
# If there are no missing values, keep the existing dtype
# instead of promoting to support NA, e.g., keep integer
# columns as integers.
# TODO: consider removing this special case, which doesn't
# exist for sparse=True.
data = np.zeros(shape, values.dtype)
data[indexer] = values
self[name] = (dims, data)
@classmethod
def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Dataset":
"""Convert a pandas.DataFrame into an xarray.Dataset
Each column will be converted into an independent variable in the
Dataset. If the dataframe's index is a MultiIndex, it will be expanded
into a tensor product of one-dimensional indices (filling in missing
values with NaN). This method will produce a Dataset very similar to
that on which the 'to_dataframe' method was called, except with
possibly redundant dimensions (since all dataset variables will have
the same dimensionality)
Parameters
----------
dataframe : DataFrame
DataFrame from which to copy data and indices.
sparse : bool, default: False
If true, create a sparse arrays instead of dense numpy arrays. This
can potentially save a large amount of memory if the DataFrame has
a MultiIndex. Requires the sparse package (sparse.pydata.org).
Returns
-------
New Dataset.
See Also
--------
xarray.DataArray.from_series
pandas.DataFrame.to_xarray
"""
# TODO: Add an option to remove dimensions along which the variables
# are constant, to enable consistent serialization to/from a dataframe,
# even if some variables have different dimensionality.
if not dataframe.columns.is_unique:
raise ValueError("cannot convert DataFrame with non-unique columns")
idx = remove_unused_levels_categories(dataframe.index)
if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
raise ValueError(
"cannot convert a DataFrame with a non-unique MultiIndex into xarray"
)
# Cast to a NumPy array first, in case the Series is a pandas Extension
# array (which doesn't have a valid NumPy dtype)
# TODO: allow users to control how this casting happens, e.g., by
# forwarding arguments to pandas.Series.to_numpy?
arrays = [(k, np.asarray(v)) for k, v in dataframe.items()]
obj = cls()
if isinstance(idx, pd.MultiIndex):
dims = tuple(
name if name is not None else "level_%i" % n
for n, name in enumerate(idx.names)
)
for dim, lev in zip(dims, idx.levels):
obj[dim] = (dim, lev)
else:
index_name = idx.name if idx.name is not None else "index"
dims = (index_name,)
obj[index_name] = (dims, idx)
if sparse:
obj._set_sparse_data_from_dataframe(idx, arrays, dims)
else:
obj._set_numpy_data_from_dataframe(idx, arrays, dims)
return obj
def to_dask_dataframe(self, dim_order=None, set_index=False):
"""
Convert this dataset into a dask.dataframe.DataFrame.
The dimensions, coordinates and data variables in this dataset form
the columns of the DataFrame.
Parameters
----------
dim_order : list, optional
Hierarchical dimension order for the resulting dataframe. All
arrays are transposed to this order and then written out as flat
vectors in contiguous order, so the last dimension in this list
will be contiguous in the resulting DataFrame. This has a major
influence on which operations are efficient on the resulting dask
dataframe.
If provided, must include all dimensions of this dataset. By
default, dimensions are sorted alphabetically.
set_index : bool, optional
If set_index=True, the dask DataFrame is indexed by this dataset's
coordinate. Since dask DataFrames do not support multi-indexes,
set_index only works if the dataset only contains one dimension.
Returns
-------
dask.dataframe.DataFrame
"""
import dask.array as da
import dask.dataframe as dd
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
columns = list(ordered_dims)
columns.extend(k for k in self.coords if k not in self.dims)
columns.extend(self.data_vars)
series_list = []
for name in columns:
try:
var = self.variables[name]
except KeyError:
# dimension without a matching coordinate
size = self.dims[name]
data = da.arange(size, chunks=size, dtype=np.int64)
var = Variable((name,), data)
# IndexVariable objects have a dummy .chunk() method
if isinstance(var, IndexVariable):
var = var.to_base_variable()
dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
series = dd.from_array(dask_array.reshape(-1), columns=[name])
series_list.append(series)
df = dd.concat(series_list, axis=1)
if set_index:
dim_order = [*ordered_dims]
if len(dim_order) == 1:
(dim,) = dim_order
df = df.set_index(dim)
else:
# triggers an error about multi-indexes, even if only one
# dimension is passed
df = df.set_index(dim_order)
return df
def to_dict(self, data=True):
"""
Convert this dataset to a dictionary following xarray naming
conventions.
Converts all variables and attributes to native Python objects
Useful for converting to json. To avoid datetime incompatibility
use decode_times=False kwarg in xarrray.open_dataset.
Parameters
----------
data : bool, optional
Whether to include the actual data in the dictionary. When set to
False, returns just the schema.
See Also
--------
Dataset.from_dict
"""
d = {
"coords": {},
"attrs": decode_numpy_dict_values(self.attrs),
"dims": dict(self.dims),
"data_vars": {},
}
for k in self.coords:
d["coords"].update({k: self[k].variable.to_dict(data=data)})
for k in self.data_vars:
d["data_vars"].update({k: self[k].variable.to_dict(data=data)})
return d
@classmethod
def from_dict(cls, d):
"""
Convert a dictionary into an xarray.Dataset.
Input dict can take several forms:
.. code:: python
d = {
"t": {"dims": ("t"), "data": t},
"a": {"dims": ("t"), "data": x},
"b": {"dims": ("t"), "data": y},
}
d = {
"coords": {"t": {"dims": "t", "data": t, "attrs": {"units": "s"}}},
"attrs": {"title": "air temperature"},
"dims": "t",
"data_vars": {
"a": {"dims": "t", "data": x},
"b": {"dims": "t", "data": y},
},
}
where "t" is the name of the dimesion, "a" and "b" are names of data
variables and t, x, and y are lists, numpy.arrays or pandas objects.
Parameters
----------
d : dict-like
Mapping with a minimum structure of
``{"var_0": {"dims": [..], "data": [..]}, \
...}``
Returns
-------
obj : xarray.Dataset
See also
--------
Dataset.to_dict
DataArray.from_dict
"""
if not {"coords", "data_vars"}.issubset(set(d)):
variables = d.items()
else:
import itertools
variables = itertools.chain(
d.get("coords", {}).items(), d.get("data_vars", {}).items()
)
try:
variable_dict = {
k: (v["dims"], v["data"], v.get("attrs")) for k, v in variables
}
except KeyError as e:
raise ValueError(
"cannot convert dict without the key "
"'{dims_data}'".format(dims_data=str(e.args[0]))
)
obj = cls(variable_dict)
# what if coords aren't dims?
coords = set(d.get("coords", {})) - set(d.get("dims", {}))
obj = obj.set_coords(coords)
obj.attrs.update(d.get("attrs", {}))
return obj
@staticmethod
def _unary_op(f):
@functools.wraps(f)
def func(self, *args, **kwargs):
variables = {}
keep_attrs = kwargs.pop("keep_attrs", None)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
for k, v in self._variables.items():
if k in self._coord_names:
variables[k] = v
else:
variables[k] = f(v, *args, **kwargs)
if keep_attrs:
variables[k].attrs = v._attrs
attrs = self._attrs if keep_attrs else None
return self._replace_with_new_dims(variables, attrs=attrs)
return func
@staticmethod
def _binary_op(f, reflexive=False, join=None):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
return NotImplemented
align_type = OPTIONS["arithmetic_join"] if join is None else join
if isinstance(other, (DataArray, Dataset)):
self, other = align(self, other, join=align_type, copy=False)
g = f if not reflexive else lambda x, y: f(y, x)
ds = self._calculate_binary_op(g, other, join=align_type)
return ds
return func
@staticmethod
def _inplace_binary_op(f):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
raise TypeError(
"in-place operations between a Dataset and "
"a grouped object are not permitted"
)
# we don't actually modify arrays in-place with in-place Dataset
# arithmetic -- this lets us automatically align things
if isinstance(other, (DataArray, Dataset)):
other = other.reindex_like(self, copy=False)
g = ops.inplace_to_noninplace_op(f)
ds = self._calculate_binary_op(g, other, inplace=True)
self._replace_with_new_dims(
ds._variables,
ds._coord_names,
attrs=ds._attrs,
indexes=ds._indexes,
inplace=True,
)
return self
return func
def _calculate_binary_op(self, f, other, join="inner", inplace=False):
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
if inplace and set(lhs_data_vars) != set(rhs_data_vars):
raise ValueError(
"datasets must have the same data variables "
"for in-place arithmetic operations: %s, %s"
% (list(lhs_data_vars), list(rhs_data_vars))
)
dest_vars = {}
for k in lhs_data_vars:
if k in rhs_data_vars:
dest_vars[k] = f(lhs_vars[k], rhs_vars[k])
elif join in ["left", "outer"]:
dest_vars[k] = f(lhs_vars[k], np.nan)
for k in rhs_data_vars:
if k not in dest_vars and join in ["right", "outer"]:
dest_vars[k] = f(rhs_vars[k], np.nan)
return dest_vars
if utils.is_dict_like(other) and not isinstance(other, Dataset):
# can't use our shortcut of doing the binary operation with
# Variable objects, so apply over our data vars instead.
new_data_vars = apply_over_both(
self.data_vars, other, self.data_vars, other
)
return Dataset(new_data_vars)
other_coords = getattr(other, "coords", None)
ds = self.coords.merge(other_coords)
if isinstance(other, Dataset):
new_vars = apply_over_both(
self.data_vars, other.data_vars, self.variables, other.variables
)
else:
other_variable = getattr(other, "variable", other)
new_vars = {k: f(self.variables[k], other_variable) for k in self.data_vars}
ds._variables.update(new_vars)
ds._dims = calculate_dimensions(ds._variables)
return ds
def _copy_attrs_from(self, other):
self.attrs = other.attrs
for v in other.variables:
if v in self.variables:
self.variables[v].attrs = other.variables[v].attrs
def diff(self, dim, n=1, label="upper"):
"""Calculate the n-th order discrete difference along given axis.
Parameters
----------
dim : str
Dimension over which to calculate the finite difference.
n : int, optional
The number of times values are differenced.
label : str, optional
The new coordinate in dimension ``dim`` will have the
values of either the minuend's or subtrahend's coordinate
for values 'upper' and 'lower', respectively. Other
values are not supported.
Returns
-------
difference : same type as caller
The n-th order finite difference of this object.
.. note::
`n` matches numpy's behavior and is different from pandas' first
argument named `periods`.
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", [5, 5, 6, 6])})
>>> ds.diff("x")
<xarray.Dataset>
Dimensions: (x: 3)
Dimensions without coordinates: x
Data variables:
foo (x) int64 0 1 0
>>> ds.diff("x", 2)
<xarray.Dataset>
Dimensions: (x: 2)
Dimensions without coordinates: x
Data variables:
foo (x) int64 1 -1
See Also
--------
Dataset.differentiate
"""
if n == 0:
return self
if n < 0:
raise ValueError(f"order `n` must be non-negative but got {n}")
# prepare slices
kwargs_start = {dim: slice(None, -1)}
kwargs_end = {dim: slice(1, None)}
# prepare new coordinate
if label == "upper":
kwargs_new = kwargs_end
elif label == "lower":
kwargs_new = kwargs_start
else:
raise ValueError("The 'label' argument has to be either 'upper' or 'lower'")
variables = {}
for name, var in self.variables.items():
if dim in var.dims:
if name in self.data_vars:
variables[name] = var.isel(**kwargs_end) - var.isel(**kwargs_start)
else:
variables[name] = var.isel(**kwargs_new)
else:
variables[name] = var
indexes = dict(self.indexes)
if dim in indexes:
indexes[dim] = indexes[dim][kwargs_new[dim]]
difference = self._replace_with_new_dims(variables, indexes=indexes)
if n > 1:
return difference.diff(dim, n - 1)
else:
return difference
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""Shift this dataset by an offset along one or more dimensions.
Only data variables are moved; coordinates stay in place. This is
consistent with the behavior of ``shift`` in pandas.
Parameters
----------
shifts : mapping of hashable to int
Integer offset to shift along each of the given dimensions.
Positive offsets shift to the right; negative offsets shift to the
left.
fill_value : scalar or dict-like, optional
Value to use for newly missing values. If a dict-like, maps
variable names (including coordinates) to fill values.
**shifts_kwargs
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
shifted : Dataset
Dataset with the same coordinates and attributes but shifted data
variables.
See Also
--------
roll
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", list("abcde"))})
>>> ds.shift(x=2)
<xarray.Dataset>
Dimensions: (x: 5)
Dimensions without coordinates: x
Data variables:
foo (x) object nan nan 'a' 'b' 'c'
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "shift")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
fill_value_ = (
fill_value.get(name, dtypes.NA)
if isinstance(fill_value, dict)
else fill_value
)
var_shifts = {k: v for k, v in shifts.items() if k in var.dims}
variables[name] = var.shift(fill_value=fill_value_, shifts=var_shifts)
else:
variables[name] = var
return self._replace(variables)
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
Parameters
----------
shifts : dict, optional
A dict with keys matching dimensions and values given
by integers to rotate each of the given dimensions. Positive
offsets roll to the right; negative offsets roll to the left.
roll_coords : bool
Indicates whether to roll the coordinates by the offset
The current default of roll_coords (None, equivalent to True) is
deprecated and will change to False in a future version.
Explicitly pass roll_coords to silence the warning.
**shifts_kwargs : {dim: offset, ...}, optional
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
rolled : Dataset
Dataset with the same coordinates and attributes but rolled
variables.
See Also
--------
shift
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", list("abcde"))})
>>> ds.roll(x=2)
<xarray.Dataset>
Dimensions: (x: 5)
Dimensions without coordinates: x
Data variables:
foo (x) <U1 'd' 'e' 'a' 'b' 'c'
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "roll")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
if roll_coords is None:
warnings.warn(
"roll_coords will be set to False in the future."
" Explicitly set roll_coords to silence warning.",
FutureWarning,
stacklevel=2,
)
roll_coords = True
unrolled_vars = () if roll_coords else self.coords
variables = {}
for k, v in self.variables.items():
if k not in unrolled_vars:
variables[k] = v.roll(
**{k: s for k, s in shifts.items() if k in v.dims}
)
else:
variables[k] = v
if roll_coords:
indexes = {}
for k, v in self.indexes.items():
(dim,) = self.variables[k].dims
if dim in shifts:
indexes[k] = roll_index(v, shifts[dim])
else:
indexes[k] = v
else:
indexes = dict(self.indexes)
return self._replace(variables, indexes=indexes)
def sortby(self, variables, ascending=True):
"""
Sort object by labels or values (along an axis).
Sorts the dataset, either along specified dimensions,
or according to values of 1-D dataarrays that share dimension
with calling object.
If the input variables are dataarrays, then the dataarrays are aligned
(via left-join) to the calling object prior to sorting by cell values.
NaNs are sorted to the end, following Numpy convention.
If multiple sorts along the same dimension is
given, numpy's lexsort is performed along that dimension:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html
and the FIRST key in the sequence is used as the primary sort key,
followed by the 2nd key, etc.
Parameters
----------
variables : str, DataArray, or list of str or DataArray
1D DataArray objects or name(s) of 1D variable(s) in
coords/data_vars whose values are used to sort the dataset.
ascending : bool, optional
Whether to sort by ascending or descending order.
Returns
-------
sorted : Dataset
A new dataset where all the specified dims are sorted by dim
labels.
"""
from .dataarray import DataArray
if not isinstance(variables, list):
variables = [variables]
else:
variables = variables
variables = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *variables, join="left")
aligned_self = aligned_vars[0]
aligned_other_vars = aligned_vars[1:]
vars_by_dim = defaultdict(list)
for data_array in aligned_other_vars:
if data_array.ndim != 1:
raise ValueError("Input DataArray is not 1-D.")
(key,) = data_array.dims
vars_by_dim[key].append(data_array)
indices = {}
for key, arrays in vars_by_dim.items():
order = np.lexsort(tuple(reversed(arrays)))
indices[key] = order if ascending else order[::-1]
return aligned_self.isel(**indices)
def quantile(
self,
q,
dim=None,
interpolation="linear",
numeric_only=False,
keep_attrs=None,
skipna=True,
):
"""Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
----------
q : float or array-like of float
Quantile to compute, which must be between 0 and 1 inclusive.
dim : str or sequence of str, optional
Dimension(s) over which to apply quantile.
interpolation : {"linear", "lower", "higher", "midpoint", "nearest"}, default: "linear"
This optional parameter specifies the interpolation method to
use when the desired quantile lies between two data points
``i < j``:
* linear: ``i + (j - i) * fraction``, where ``fraction`` is
the fractional part of the index surrounded by ``i`` and
``j``.
* lower: ``i``.
* higher: ``j``.
* nearest: ``i`` or ``j``, whichever is nearest.
* midpoint: ``(i + j) / 2``.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
numeric_only : bool, optional
If True, only apply ``func`` to variables with a numeric dtype.
skipna : bool, optional
Whether to skip missing values when aggregating.
Returns
-------
quantiles : Dataset
If `q` is a single quantile, then the result is a scalar for each
variable in data_vars. If multiple percentiles are given, first
axis of the result corresponds to the quantile and a quantile
dimension is added to the return Dataset. The other dimensions are
the dimensions that remain after the reduction of the array.
See Also
--------
numpy.nanquantile, numpy.quantile, pandas.Series.quantile, DataArray.quantile
Examples
--------
>>> ds = xr.Dataset(
... {"a": (("x", "y"), [[0.7, 4.2, 9.4, 1.5], [6.5, 7.3, 2.6, 1.9]])},
... coords={"x": [7, 9], "y": [1, 1.5, 2, 2.5]},
... )
>>> ds.quantile(0) # or ds.quantile(0, dim=...)
<xarray.Dataset>
Dimensions: ()
Coordinates:
quantile float64 0.0
Data variables:
a float64 0.7
>>> ds.quantile(0, dim="x")
<xarray.Dataset>
Dimensions: (y: 4)
Coordinates:
* y (y) float64 1.0 1.5 2.0 2.5
quantile float64 0.0
Data variables:
a (y) float64 0.7 4.2 2.6 1.5
>>> ds.quantile([0, 0.5, 1])
<xarray.Dataset>
Dimensions: (quantile: 3)
Coordinates:
* quantile (quantile) float64 0.0 0.5 1.0
Data variables:
a (quantile) float64 0.7 3.4 9.4
>>> ds.quantile([0, 0.5, 1], dim="x")
<xarray.Dataset>
Dimensions: (quantile: 3, y: 4)
Coordinates:
* y (y) float64 1.0 1.5 2.0 2.5
* quantile (quantile) float64 0.0 0.5 1.0
Data variables:
a (quantile, y) float64 0.7 4.2 2.6 1.5 3.6 ... 1.7 6.5 7.3 9.4 1.9
"""
if isinstance(dim, str):
dims = {dim}
elif dim in [None, ...]:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty(
[d for d in dims if d not in self.dims],
"Dataset does not contain the dimensions: %s",
)
q = np.asarray(q, dtype=np.float64)
variables = {}
for name, var in self.variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
if len(reduce_dims) == var.ndim:
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
reduce_dims = None
variables[name] = var.quantile(
q,
dim=reduce_dims,
interpolation=interpolation,
keep_attrs=keep_attrs,
skipna=skipna,
)
else:
variables[name] = var
# construct the new dataset
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
new = self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
return new.assign_coords(quantile=q)
def rank(self, dim, pct=False, keep_attrs=None):
"""Ranks the data.
Equal values are assigned a rank that is the average of the ranks that
would have been otherwise assigned to all of the values within
that set.
Ranks begin at 1, not 0. If pct is True, computes percentage ranks.
NaNs in the input array are returned as NaNs.
The `bottleneck` library is required.
Parameters
----------
dim : str
Dimension over which to compute rank.
pct : bool, optional
If True, compute percentage ranks, otherwise compute integer ranks.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
Returns
-------
ranked : Dataset
Variables that do not depend on `dim` are dropped.
"""
if dim not in self.dims:
raise ValueError("Dataset does not contain the dimension: %s" % dim)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
if dim in var.dims:
variables[name] = var.rank(dim, pct=pct)
else:
variables[name] = var
coord_names = set(self.coords)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
return self._replace(variables, coord_names, attrs=attrs)
def differentiate(self, coord, edge_order=1, datetime_unit=None):
""" Differentiate with the second order accurate central
differences.
.. note::
This feature is limited to simple cartesian geometry, i.e. coord
must be one dimensional.
Parameters
----------
coord : str
The coordinate to be used to compute the gradient.
edge_order : {1, 2}, default: 1
N-th order accurate differences at the boundaries.
datetime_unit : None or {"Y", "M", "W", "D", "h", "m", "s", "ms", \
"us", "ns", "ps", "fs", "as"}, default: None
Unit to compute gradient. Only valid for datetime coordinate.
Returns
-------
differentiated: Dataset
See also
--------
numpy.gradient: corresponding numpy function
"""
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s" # Default to seconds for cftime objects
coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)
variables = {}
for k, v in self.variables.items():
if k in self.data_vars and dim in v.dims and k not in self.coords:
if _contains_datetime_like_objects(v):
v = v._to_numeric(datetime_unit=datetime_unit)
grad = duck_array_ops.gradient(
v.data, coord_var, edge_order=edge_order, axis=v.get_axis_num(dim)
)
variables[k] = Variable(v.dims, grad)
else:
variables[k] = v
return self._replace(variables)
def integrate(
self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None
) -> "Dataset":
"""Integrate along the given coordinate using the trapezoidal rule.
.. note::
This feature is limited to simple cartesian geometry, i.e. coord
must be one dimensional.
Parameters
----------
coord : hashable, or sequence of hashable
Coordinate(s) used for the integration.
datetime_unit : {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', \
'ps', 'fs', 'as'}, optional
Specify the unit if datetime coordinate is used.
Returns
-------
integrated : Dataset
See also
--------
DataArray.integrate
numpy.trapz : corresponding numpy function
Examples
--------
>>> ds = xr.Dataset(
... data_vars={"a": ("x", [5, 5, 6, 6]), "b": ("x", [1, 2, 1, 0])},
... coords={"x": [0, 1, 2, 3], "y": ("x", [1, 7, 3, 5])},
... )
>>> ds
<xarray.Dataset>
Dimensions: (x: 4)
Coordinates:
* x (x) int64 0 1 2 3
y (x) int64 1 7 3 5
Data variables:
a (x) int64 5 5 6 6
b (x) int64 1 2 1 0
>>> ds.integrate("x")
<xarray.Dataset>
Dimensions: ()
Data variables:
a float64 16.5
b float64 3.5
>>> ds.integrate("y")
<xarray.Dataset>
Dimensions: ()
Data variables:
a float64 20.0
b float64 4.0
"""
if not isinstance(coord, (list, tuple)):
coord = (coord,)
result = self
for c in coord:
result = result._integrate_one(c, datetime_unit=datetime_unit)
return result
def _integrate_one(self, coord, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s" # Default to seconds for cftime objects
coord_var = coord_var._replace(
data=datetime_to_numeric(coord_var.data, datetime_unit=datetime_unit)
)
variables = {}
coord_names = set()
for k, v in self.variables.items():
if k in self.coords:
if dim not in v.dims:
variables[k] = v
coord_names.add(k)
else:
if k in self.data_vars and dim in v.dims:
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
integ = duck_array_ops.trapz(
v.data, coord_var.data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
else:
variables[k] = v
indexes = {k: v for k, v in self.indexes.items() if k in variables}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
@property
def real(self):
return self.map(lambda x: x.real, keep_attrs=True)
@property
def imag(self):
return self.map(lambda x: x.imag, keep_attrs=True)
plot = utils.UncachedAccessor(_Dataset_PlotMethods)
def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for which the attribute ``key``
has the exact value ``value`` or the callable passed into
``key=callable`` returns True. The callable will be passed a single
value, either the value of the attribute ``key`` or ``None`` if the
DataArray does not have an attribute with the name ``key``.
Parameters
----------
**kwargs
key : str
Attribute name.
value : callable or obj
If value is a callable, it should return a boolean in the form
of bool = func(attr) where attr is da.attrs[key].
Otherwise, value will be compared to the each
DataArray's attrs[key].
Returns
-------
new : Dataset
New dataset with variables filtered by attribute.
Examples
--------
>>> # Create an example dataset:
>>> temp = 15 + 8 * np.random.randn(2, 2, 3)
>>> precip = 10 * np.random.rand(2, 2, 3)
>>> lon = [[-99.83, -99.32], [-99.79, -99.23]]
>>> lat = [[42.25, 42.21], [42.63, 42.59]]
>>> dims = ["x", "y", "time"]
>>> temp_attr = dict(standard_name="air_potential_temperature")
>>> precip_attr = dict(standard_name="convective_precipitation_flux")
>>> ds = xr.Dataset(
... {
... "temperature": (dims, temp, temp_attr),
... "precipitation": (dims, precip, precip_attr),
... },
... coords={
... "lon": (["x", "y"], lon),
... "lat": (["x", "y"], lat),
... "time": pd.date_range("2014-09-06", periods=3),
... "reference_time": pd.Timestamp("2014-09-05"),
... },
... )
>>> # Get variables matching a specific standard_name.
>>> ds.filter_by_attrs(standard_name="convective_precipitation_flux")
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
>>> # Get all variables that have a standard_name attribute.
>>> standard_name = lambda v: v is not None
>>> ds.filter_by_attrs(standard_name=standard_name)
<xarray.Dataset>
Dimensions: (time: 3, x: 2, y: 2)
Coordinates:
lon (x, y) float64 -99.83 -99.32 -99.79 -99.23
lat (x, y) float64 42.25 42.21 42.63 42.59
* time (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
reference_time datetime64[ns] 2014-09-05
Dimensions without coordinates: x, y
Data variables:
temperature (x, y, time) float64 29.11 18.2 22.83 ... 18.28 16.15 26.63
precipitation (x, y, time) float64 5.68 9.256 0.7104 ... 7.992 4.615 7.805
"""
selection = []
for var_name, variable in self.variables.items():
has_value_flag = False
for attr_name, pattern in kwargs.items():
attr_value = variable.attrs.get(attr_name)
if (callable(pattern) and pattern(attr_value)) or attr_value == pattern:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
selection.append(var_name)
return self[selection]
def unify_chunks(self) -> "Dataset":
"""Unify chunk size along all chunked dimensions of this Dataset.
Returns
-------
Dataset with consistent chunk sizes for all dask-array variables
See Also
--------
dask.array.core.unify_chunks
"""
try:
self.chunks
except ValueError: # "inconsistent chunks"
pass
else:
# No variables with dask backend, or all chunks are already aligned
return self.copy()
# import dask is placed after the quick exit test above to allow
# running this method if dask isn't installed and there are no chunks
import dask.array
ds = self.copy()
dims_pos_map = {dim: index for index, dim in enumerate(ds.dims)}
dask_array_names = []
dask_unify_args = []
for name, variable in ds.variables.items():
if isinstance(variable.data, dask.array.Array):
dims_tuple = [dims_pos_map[dim] for dim in variable.dims]
dask_array_names.append(name)
dask_unify_args.append(variable.data)
dask_unify_args.append(dims_tuple)
_, rechunked_arrays = dask.array.core.unify_chunks(*dask_unify_args)
for name, new_array in zip(dask_array_names, rechunked_arrays):
ds.variables[name]._data = new_array
return ds
def map_blocks(
self,
func: "Callable[..., T_DSorDA]",
args: Sequence[Any] = (),
kwargs: Mapping[str, Any] = None,
template: Union["DataArray", "Dataset"] = None,
) -> "T_DSorDA":
"""
Apply a function to each block of this Dataset.
.. warning::
This method is experimental and its signature may change.
Parameters
----------
func : callable
User-provided function that accepts a Dataset as its first
parameter. The function will receive a subset or 'block' of this Dataset (see below),
corresponding to one chunk along each chunked dimension. ``func`` will be
executed as ``func(subset_dataset, *subset_args, **kwargs)``.
This function must return either a single DataArray or a single Dataset.
This function cannot add a new chunked dimension.
args : sequence
Passed to func after unpacking and subsetting any xarray objects by blocks.
xarray objects in args must be aligned with obj, otherwise an error is raised.
kwargs : mapping
Passed verbatim to func after unpacking. xarray objects, if any, will not be
subset to blocks. Passing dask collections in kwargs is not allowed.
template : DataArray or Dataset, optional
xarray object representing the final result after compute is called. If not provided,
the function will be first run on mocked-up data, that looks like this object but
has sizes 0, to determine properties of the returned object such as dtype,
variable names, attributes, new dimensions and new indexes (if any).
``template`` must be provided if the function changes the size of existing dimensions.
When provided, ``attrs`` on variables in `template` are copied over to the result. Any
``attrs`` set by ``func`` will be ignored.
Returns
-------
A single DataArray or Dataset with dask backend, reassembled from the outputs of the
function.
Notes
-----
This function is designed for when ``func`` needs to manipulate a whole xarray object
subset to each block. Each block is loaded into memory. In the more common case where
``func`` can work on numpy arrays, it is recommended to use ``apply_ufunc``.
If none of the variables in this object is backed by dask arrays, calling this function is
equivalent to calling ``func(obj, *args, **kwargs)``.
See Also
--------
dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks
xarray.DataArray.map_blocks
Examples
--------
Calculate an anomaly from climatology using ``.groupby()``. Using
``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``,
its indices, and its methods like ``.groupby()``.
>>> def calculate_anomaly(da, groupby_type="time.month"):
... gb = da.groupby(groupby_type)
... clim = gb.mean(dim="time")
... return gb - clim
...
>>> time = xr.cftime_range("1990-01", "1992-01", freq="M")
>>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"])
>>> np.random.seed(123)
>>> array = xr.DataArray(
... np.random.rand(len(time)),
... dims=["time"],
... coords={"time": time, "month": month},
... ).chunk()
>>> ds = xr.Dataset({"a": array})
>>> ds.map_blocks(calculate_anomaly, template=ds).compute()
<xarray.Dataset>
Dimensions: (time: 24)
Coordinates:
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
month (time) int64 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
a (time) float64 0.1289 0.1132 -0.0856 ... 0.2287 0.1906 -0.05901
Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments
to the function being applied in ``xr.map_blocks()``:
>>> ds.map_blocks(
... calculate_anomaly,
... kwargs={"groupby_type": "time.year"},
... template=ds,
... )
<xarray.Dataset>
Dimensions: (time: 24)
Coordinates:
* time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00
month (time) int64 dask.array<chunksize=(24,), meta=np.ndarray>
Data variables:
a (time) float64 dask.array<chunksize=(24,), meta=np.ndarray>
"""
from .parallel import map_blocks
return map_blocks(func, self, args, kwargs, template)
def polyfit(
self,
dim: Hashable,
deg: int,
skipna: bool = None,
rcond: float = None,
w: Union[Hashable, Any] = None,
full: bool = False,
cov: Union[bool, str] = False,
):
"""
Least squares polynomial fit.
This replicates the behaviour of `numpy.polyfit` but differs by skipping
invalid values when `skipna = True`.
Parameters
----------
dim : hashable
Coordinate along which to fit the polynomials.
deg : int
Degree of the fitting polynomial.
skipna : bool, optional
If True, removes all invalid values before fitting each 1D slices of the array.
Default is True if data is stored in a dask.array or if there is any
invalid values, False otherwise.
rcond : float, optional
Relative condition number to the fit.
w : hashable or Any, optional
Weights to apply to the y-coordinate of the sample points.
Can be an array-like object or the name of a coordinate in the dataset.
full : bool, optional
Whether to return the residuals, matrix rank and singular values in addition
to the coefficients.
cov : bool or str, optional
Whether to return to the covariance matrix in addition to the coefficients.
The matrix is not scaled if `cov='unscaled'`.
Returns
-------
polyfit_results : Dataset
A single dataset which contains (for each "var" in the input dataset):
[var]_polyfit_coefficients
The coefficients of the best fit for each variable in this dataset.
[var]_polyfit_residuals
The residuals of the least-square computation for each variable (only included if `full=True`)
When the matrix rank is deficient, np.nan is returned.
[dim]_matrix_rank
The effective rank of the scaled Vandermonde coefficient matrix (only included if `full=True`)
The rank is computed ignoring the NaN values that might be skipped.
[dim]_singular_values
The singular values of the scaled Vandermonde coefficient matrix (only included if `full=True`)
[var]_polyfit_covariance
The covariance matrix of the polynomial coefficient estimates (only included if `full=False` and `cov=True`)
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is deficient.
The warning is not raised with in-memory (not dask) data and `full=True`.
See Also
--------
numpy.polyfit
numpy.polyval
xarray.polyval
"""
variables = {}
skipna_da = skipna
x = get_clean_interp_index(self, dim, strict=False)
xname = "{}_".format(self[dim].name)
order = int(deg) + 1
lhs = np.vander(x, order)
if rcond is None:
rcond = (
x.shape[0] * np.core.finfo(x.dtype).eps # type: ignore[attr-defined]
)
# Weights:
if w is not None:
if isinstance(w, Hashable):
w = self.coords[w]
w = np.asarray(w)
if w.ndim != 1:
raise TypeError("Expected a 1-d array for weights.")
if w.shape[0] != lhs.shape[0]:
raise TypeError("Expected w and {} to have the same length".format(dim))
lhs *= w[:, np.newaxis]
# Scaling
scale = np.sqrt((lhs * lhs).sum(axis=0))
lhs /= scale
degree_dim = utils.get_temp_dimname(self.dims, "degree")
rank = np.linalg.matrix_rank(lhs)
if full:
rank = xr.DataArray(rank, name=xname + "matrix_rank")
variables[rank.name] = rank
sing = np.linalg.svd(lhs, compute_uv=False)
sing = xr.DataArray(
sing,
dims=(degree_dim,),
coords={degree_dim: np.arange(rank - 1, -1, -1)},
name=xname + "singular_values",
)
variables[sing.name] = sing
for name, da in self.data_vars.items():
if dim not in da.dims:
continue
if is_duck_dask_array(da.data) and (
rank != order or full or skipna is None
):
# Current algorithm with dask and skipna=False neither supports
# deficient ranks nor does it output the "full" info (issue dask/dask#6516)
skipna_da = True
elif skipna is None:
skipna_da = bool(np.any(da.isnull()))
dims_to_stack = [dimname for dimname in da.dims if dimname != dim]
stacked_coords: Dict[Hashable, DataArray] = {}
if dims_to_stack:
stacked_dim = utils.get_temp_dimname(dims_to_stack, "stacked")
rhs = da.transpose(dim, *dims_to_stack).stack(
{stacked_dim: dims_to_stack}
)
stacked_coords = {stacked_dim: rhs[stacked_dim]}
scale_da = scale[:, np.newaxis]
else:
rhs = da
scale_da = scale
if w is not None:
rhs *= w[:, np.newaxis]
with warnings.catch_warnings():
if full: # Copy np.polyfit behavior
warnings.simplefilter("ignore", np.RankWarning)
else: # Raise only once per variable
warnings.simplefilter("once", np.RankWarning)
coeffs, residuals = duck_array_ops.least_squares(
lhs, rhs.data, rcond=rcond, skipna=skipna_da
)
if isinstance(name, str):
name = "{}_".format(name)
else:
# Thus a ReprObject => polyfit was called on a DataArray
name = ""
coeffs = xr.DataArray(
coeffs / scale_da,
dims=[degree_dim] + list(stacked_coords.keys()),
coords={degree_dim: np.arange(order)[::-1], **stacked_coords},
name=name + "polyfit_coefficients",
)
if dims_to_stack:
coeffs = coeffs.unstack(stacked_dim)
variables[coeffs.name] = coeffs
if full or (cov is True):
residuals = xr.DataArray(
residuals if dims_to_stack else residuals.squeeze(),
dims=list(stacked_coords.keys()),
coords=stacked_coords,
name=name + "polyfit_residuals",
)
if dims_to_stack:
residuals = residuals.unstack(stacked_dim)
variables[residuals.name] = residuals
if cov:
Vbase = np.linalg.inv(np.dot(lhs.T, lhs))
Vbase /= np.outer(scale, scale)
if cov == "unscaled":
fac = 1
else:
if x.shape[0] <= order:
raise ValueError(
"The number of data points must exceed order to scale the covariance matrix."
)
fac = residuals / (x.shape[0] - order)
covariance = xr.DataArray(Vbase, dims=("cov_i", "cov_j")) * fac
variables[name + "polyfit_covariance"] = covariance
return Dataset(data_vars=variables, attrs=self.attrs.copy())
def pad(
self,
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
mode: str = "constant",
stat_length: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
constant_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
end_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
reflect_type: str = None,
**pad_width_kwargs: Any,
) -> "Dataset":
"""Pad this dataset along one or more dimensions.
.. warning::
This function is experimental and its behaviour is likely to change
especially regarding padding of dimension coordinates (or IndexVariables).
When using one of the modes ("edge", "reflect", "symmetric", "wrap"),
coordinates will be padded with the same mode, otherwise coordinates
are padded using the "constant" mode with fill_value dtypes.NA.
Parameters
----------
pad_width : mapping of hashable to tuple of int
Mapping with the form of {dim: (pad_before, pad_after)}
describing the number of values padded along each dimension.
{dim: pad} is a shortcut for pad_before = pad_after = pad
mode : str, default: "constant"
One of the following string values (taken from numpy docs).
'constant' (default)
Pads with a constant value.
'edge'
Pads with the edge values of array.
'linear_ramp'
Pads with the linear ramp between end_value and the
array edge value.
'maximum'
Pads with the maximum value of all or part of the
vector along each axis.
'mean'
Pads with the mean value of all or part of the
vector along each axis.
'median'
Pads with the median value of all or part of the
vector along each axis.
'minimum'
Pads with the minimum value of all or part of the
vector along each axis.
'reflect'
Pads with the reflection of the vector mirrored on
the first and last values of the vector along each
axis.
'symmetric'
Pads with the reflection of the vector mirrored
along the edge of the array.
'wrap'
Pads with the wrap of the vector along the axis.
The first values are used to pad the end and the
end values are used to pad the beginning.
stat_length : int, tuple or mapping of hashable to tuple, default: None
Used in 'maximum', 'mean', 'median', and 'minimum'. Number of
values at edge of each axis used to calculate the statistic value.
{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)} unique
statistic lengths along each dimension.
((before, after),) yields same before and after statistic lengths
for each dimension.
(stat_length,) or int is a shortcut for before = after = statistic
length for all axes.
Default is ``None``, to use the entire axis.
constant_values : scalar, tuple or mapping of hashable to tuple, default: 0
Used in 'constant'. The values to set the padded values for each
axis.
``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
pad constants along each dimension.
``((before, after),)`` yields same before and after constants for each
dimension.
``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
all dimensions.
Default is 0.
end_values : scalar, tuple or mapping of hashable to tuple, default: 0
Used in 'linear_ramp'. The values used for the ending value of the
linear_ramp and that will form the edge of the padded array.
``{dim_1: (before_1, after_1), ... dim_N: (before_N, after_N)}`` unique
end values along each dimension.
``((before, after),)`` yields same before and after end values for each
axis.
``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for
all axes.
Default is 0.
reflect_type : {"even", "odd"}, optional
Used in "reflect", and "symmetric". The "even" style is the
default with an unaltered reflection around the edge value. For
the "odd" style, the extended part of the array is created by
subtracting the reflected values from two times the edge value.
**pad_width_kwargs
The keyword arguments form of ``pad_width``.
One of ``pad_width`` or ``pad_width_kwargs`` must be provided.
Returns
-------
padded : Dataset
Dataset with the padded coordinates and data.
See Also
--------
Dataset.shift, Dataset.roll, Dataset.bfill, Dataset.ffill, numpy.pad, dask.array.pad
Notes
-----
By default when ``mode="constant"`` and ``constant_values=None``, integer types will be
promoted to ``float`` and padded with ``np.nan``. To avoid type promotion
specify ``constant_values=np.nan``
Examples
--------
>>> ds = xr.Dataset({"foo": ("x", range(5))})
>>> ds.pad(x=(1, 2))
<xarray.Dataset>
Dimensions: (x: 8)
Dimensions without coordinates: x
Data variables:
foo (x) float64 nan 0.0 1.0 2.0 3.0 4.0 nan nan
"""
pad_width = either_dict_or_kwargs(pad_width, pad_width_kwargs, "pad")
if mode in ("edge", "reflect", "symmetric", "wrap"):
coord_pad_mode = mode
coord_pad_options = {
"stat_length": stat_length,
"constant_values": constant_values,
"end_values": end_values,
"reflect_type": reflect_type,
}
else:
coord_pad_mode = "constant"
coord_pad_options = {}
variables = {}
for name, var in self.variables.items():
var_pad_width = {k: v for k, v in pad_width.items() if k in var.dims}
if not var_pad_width:
variables[name] = var
elif name in self.data_vars:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=mode,
stat_length=stat_length,
constant_values=constant_values,
end_values=end_values,
reflect_type=reflect_type,
)
else:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=coord_pad_mode,
**coord_pad_options, # type: ignore[arg-type]
)
return self._replace_vars_and_dims(variables)
def idxmin(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
"""Return the coordinate label of the minimum value along a dimension.
Returns a new `Dataset` named after the dimension with the values of
the coordinate labels along that dimension corresponding to minimum
values along that dimension.
In comparison to :py:meth:`~Dataset.argmin`, this returns the
coordinate label while :py:meth:`~Dataset.argmin` returns the index.
Parameters
----------
dim : str, optional
Dimension over which to apply `idxmin`. This is optional for 1D
variables, but required for variables with 2 or more dimensions.
skipna : bool or None, default: None
If True, skip missing values (as marked by NaN). By default, only
skips missing values for ``float``, ``complex``, and ``object``
dtypes; other dtypes either do not have a sentinel missing value
(``int``) or ``skipna=True`` has not been implemented
(``datetime64`` or ``timedelta64``).
fill_value : Any, default: NaN
Value to be filled in case all of the values along a dimension are
null. By default this is NaN. The fill value and result are
automatically converted to a compatible dtype if possible.
Ignored if ``skipna`` is False.
keep_attrs : bool, default: False
If True, the attributes (``attrs``) will be copied from the
original object to the new one. If False (default), the new object
will be returned without attributes.
Returns
-------
reduced : Dataset
New `Dataset` object with `idxmin` applied to its data and the
indicated dimension removed.
See Also
--------
DataArray.idxmin, Dataset.idxmax, Dataset.min, Dataset.argmin
Examples
--------
>>> array1 = xr.DataArray(
... [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
... )
>>> array2 = xr.DataArray(
... [
... [2.0, 1.0, 2.0, 0.0, -2.0],
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
... ],
... dims=["y", "x"],
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},
... )
>>> ds = xr.Dataset({"int": array1, "float": array2})
>>> ds.min(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 -2
float (y) float64 -2.0 -4.0 1.0
>>> ds.argmin(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 4
float (y) int64 4 0 2
>>> ds.idxmin(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int <U1 'e'
float (y) object 'e' 'a' 'c'
"""
return self.map(
methodcaller(
"idxmin",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def idxmax(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
"""Return the coordinate label of the maximum value along a dimension.
Returns a new `Dataset` named after the dimension with the values of
the coordinate labels along that dimension corresponding to maximum
values along that dimension.
In comparison to :py:meth:`~Dataset.argmax`, this returns the
coordinate label while :py:meth:`~Dataset.argmax` returns the index.
Parameters
----------
dim : str, optional
Dimension over which to apply `idxmax`. This is optional for 1D
variables, but required for variables with 2 or more dimensions.
skipna : bool or None, default: None
If True, skip missing values (as marked by NaN). By default, only
skips missing values for ``float``, ``complex``, and ``object``
dtypes; other dtypes either do not have a sentinel missing value
(``int``) or ``skipna=True`` has not been implemented
(``datetime64`` or ``timedelta64``).
fill_value : Any, default: NaN
Value to be filled in case all of the values along a dimension are
null. By default this is NaN. The fill value and result are
automatically converted to a compatible dtype if possible.
Ignored if ``skipna`` is False.
keep_attrs : bool, default: False
If True, the attributes (``attrs``) will be copied from the
original object to the new one. If False (default), the new object
will be returned without attributes.
Returns
-------
reduced : Dataset
New `Dataset` object with `idxmax` applied to its data and the
indicated dimension removed.
See Also
--------
DataArray.idxmax, Dataset.idxmin, Dataset.max, Dataset.argmax
Examples
--------
>>> array1 = xr.DataArray(
... [0, 2, 1, 0, -2], dims="x", coords={"x": ["a", "b", "c", "d", "e"]}
... )
>>> array2 = xr.DataArray(
... [
... [2.0, 1.0, 2.0, 0.0, -2.0],
... [-4.0, np.NaN, 2.0, np.NaN, -2.0],
... [np.NaN, np.NaN, 1.0, np.NaN, np.NaN],
... ],
... dims=["y", "x"],
... coords={"y": [-1, 0, 1], "x": ["a", "b", "c", "d", "e"]},
... )
>>> ds = xr.Dataset({"int": array1, "float": array2})
>>> ds.max(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 2
float (y) float64 2.0 2.0 1.0
>>> ds.argmax(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int int64 1
float (y) int64 0 2 2
>>> ds.idxmax(dim="x")
<xarray.Dataset>
Dimensions: (y: 3)
Coordinates:
* y (y) int64 -1 0 1
Data variables:
int <U1 'b'
float (y) object 'a' 'c' 'c'
"""
return self.map(
methodcaller(
"idxmax",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def argmin(self, dim=None, **kwargs):
"""Indices of the minima of the member variables.
If there are multiple minima, the indices of the first one found will be
returned.
Parameters
----------
dim : str, optional
The dimension over which to find the minimum. By default, finds minimum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will be an error, since DataArray.argmin will
return a dict with indices for all dimensions, which does not make sense for
a Dataset.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Dataset
See Also
--------
DataArray.argmin
"""
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmin_func = getattr(duck_array_ops, "argmin")
return self.reduce(argmin_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def argmax(self, dim=None, **kwargs):
"""Indices of the maxima of the member variables.
If there are multiple maxima, the indices of the first one found will be
returned.
Parameters
----------
dim : str, optional
The dimension over which to find the maximum. By default, finds maximum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will be an error, since DataArray.argmax will
return a dict with indices for all dimensions, which does not make sense for
a Dataset.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Dataset
See Also
--------
DataArray.argmax
"""
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmax_func = getattr(duck_array_ops, "argmax")
return self.reduce(argmax_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def query(
self,
queries: Mapping[Hashable, Any] = None,
parser: str = "pandas",
engine: str = None,
missing_dims: str = "raise",
**queries_kwargs: Any,
) -> "Dataset":
"""Return a new dataset with each array indexed along the specified
dimension(s), where the indexers are given as strings containing
Python expressions to be evaluated against the data variables in the
dataset.
Parameters
----------
queries : dict, optional
A dict with keys matching dimensions and values given by strings
containing Python expressions to be evaluated against the data variables
in the dataset. The expressions will be evaluated using the pandas
eval() function, and can contain any valid Python expressions but cannot
contain any Python statements.
parser : {"pandas", "python"}, default: "pandas"
The parser to use to construct the syntax tree from the expression.
The default of 'pandas' parses code slightly different than standard
Python. Alternatively, you can parse an expression using the 'python'
parser to retain strict Python semantics.
engine: {"python", "numexpr", None}, default: None
The engine used to evaluate the expression. Supported engines are:
- None: tries to use numexpr, falls back to python
- "numexpr": evaluates expressions using numexpr
- "python": performs operations as if you had eval’d in top level python
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
Dataset:
- "raise": raise an exception
- "warning": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
**queries_kwargs : {dim: query, ...}, optional
The keyword arguments form of ``queries``.
One of queries or queries_kwargs must be provided.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the results of the appropriate
queries.
See Also
--------
Dataset.isel
pandas.eval
"""
# allow queries to be given either as a dict or as kwargs
queries = either_dict_or_kwargs(queries, queries_kwargs, "query")
# check queries
for dim, expr in queries.items():
if not isinstance(expr, str):
msg = f"expr for dim {dim} must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
# evaluate the queries to create the indexers
indexers = {
dim: pd.eval(expr, resolvers=[self], parser=parser, engine=engine)
for dim, expr in queries.items()
}
# apply the selection
return self.isel(indexers, missing_dims=missing_dims)
def curvefit(
self,
coords: Union[Union[str, "DataArray"], Iterable[Union[str, "DataArray"]]],
func: Callable[..., Any],
reduce_dims: Union[Hashable, Iterable[Hashable]] = None,
skipna: bool = True,
p0: Dict[str, Any] = None,
bounds: Dict[str, Any] = None,
param_names: Sequence[str] = None,
kwargs: Dict[str, Any] = None,
):
"""
Curve fitting optimization for arbitrary functions.
Wraps `scipy.optimize.curve_fit` with `apply_ufunc`.
Parameters
----------
coords : DataArray, str or sequence of DataArray, str
Independent coordinate(s) over which to perform the curve fitting. Must share
at least one dimension with the calling object. When fitting multi-dimensional
functions, supply `coords` as a sequence in the same order as arguments in
`func`. To fit along existing dimensions of the calling object, `coords` can
also be specified as a str or sequence of strs.
func : callable
User specified function in the form `f(x, *params)` which returns a numpy
array of length `len(x)`. `params` are the fittable parameters which are optimized
by scipy curve_fit. `x` can also be specified as a sequence containing multiple
coordinates, e.g. `f((x0, x1), *params)`.
reduce_dims : str or sequence of str
Additional dimension(s) over which to aggregate while fitting. For example,
calling `ds.curvefit(coords='time', reduce_dims=['lat', 'lon'], ...)` will
aggregate all lat and lon points and fit the specified function along the
time dimension.
skipna : bool, optional
Whether to skip missing values when fitting. Default is True.
p0 : dictionary, optional
Optional dictionary of parameter names to initial guesses passed to the
`curve_fit` `p0` arg. If none or only some parameters are passed, the rest will
be assigned initial values following the default scipy behavior.
bounds : dictionary, optional
Optional dictionary of parameter names to bounding values passed to the
`curve_fit` `bounds` arg. If none or only some parameters are passed, the rest
will be unbounded following the default scipy behavior.
param_names: seq, optional
Sequence of names for the fittable parameters of `func`. If not supplied,
this will be automatically determined by arguments of `func`. `param_names`
should be manually supplied when fitting a function that takes a variable
number of parameters.
kwargs : dictionary
Additional keyword arguments to passed to scipy curve_fit.
Returns
-------
curvefit_results : Dataset
A single dataset which contains:
[var]_curvefit_coefficients
The coefficients of the best fit.
[var]_curvefit_covariance
The covariance matrix of the coefficient estimates.
See also
--------
Dataset.polyfit
scipy.optimize.curve_fit
"""
from scipy.optimize import curve_fit
if p0 is None:
p0 = {}
if bounds is None:
bounds = {}
if kwargs is None:
kwargs = {}
if not reduce_dims:
reduce_dims_ = []
elif isinstance(reduce_dims, str) or not isinstance(reduce_dims, Iterable):
reduce_dims_ = [reduce_dims]
else:
reduce_dims_ = list(reduce_dims)
if (
isinstance(coords, str)
or isinstance(coords, xr.DataArray)
or not isinstance(coords, Iterable)
):
coords = [coords]
coords_ = [self[coord] if isinstance(coord, str) else coord for coord in coords]
# Determine whether any coords are dims on self
for coord in coords_:
reduce_dims_ += [c for c in self.dims if coord.equals(self[c])]
reduce_dims_ = list(set(reduce_dims_))
preserved_dims = list(set(self.dims) - set(reduce_dims_))
if not reduce_dims_:
raise ValueError(
"No arguments to `coords` were identified as a dimension on the calling "
"object, and no dims were supplied to `reduce_dims`. This would result "
"in fitting on scalar data."
)
# Broadcast all coords with each other
coords_ = xr.broadcast(*coords_)
coords_ = [
coord.broadcast_like(self, exclude=preserved_dims) for coord in coords_
]
params, func_args = _get_func_args(func, param_names)
param_defaults, bounds_defaults = _initialize_curvefit_params(
params, p0, bounds, func_args
)
n_params = len(params)
kwargs.setdefault("p0", [param_defaults[p] for p in params])
kwargs.setdefault(
"bounds",
[
[bounds_defaults[p][0] for p in params],
[bounds_defaults[p][1] for p in params],
],
)
def _wrapper(Y, *coords_, **kwargs):
# Wrap curve_fit with raveled coordinates and pointwise NaN handling
x = np.vstack([c.ravel() for c in coords_])
y = Y.ravel()
if skipna:
mask = np.all([np.any(~np.isnan(x), axis=0), ~np.isnan(y)], axis=0)
x = x[:, mask]
y = y[mask]
if not len(y):
popt = np.full([n_params], np.nan)
pcov = np.full([n_params, n_params], np.nan)
return popt, pcov
x = np.squeeze(x)
popt, pcov = curve_fit(func, x, y, **kwargs)
return popt, pcov
result = xr.Dataset()
for name, da in self.data_vars.items():
if name is xr.core.dataarray._THIS_ARRAY:
name = ""
else:
name = f"{str(name)}_"
popt, pcov = xr.apply_ufunc(
_wrapper,
da,
*coords_,
vectorize=True,
dask="parallelized",
input_core_dims=[reduce_dims_ for d in range(len(coords_) + 1)],
output_core_dims=[["param"], ["cov_i", "cov_j"]],
dask_gufunc_kwargs={
"output_sizes": {
"param": n_params,
"cov_i": n_params,
"cov_j": n_params,
},
},
output_dtypes=(np.float64, np.float64),
exclude_dims=set(reduce_dims_),
kwargs=kwargs,
)
result[name + "curvefit_coefficients"] = popt
result[name + "curvefit_covariance"] = pcov
result = result.assign_coords(
{"param": params, "cov_i": params, "cov_j": params}
)
result.attrs = self.attrs.copy()
return result
ops.inject_all_ops_and_reduce_methods(Dataset, array_only=False)
| 37.573694 | 124 | 0.56107 | import copy
import datetime
import functools
import inspect
import sys
import warnings
from collections import defaultdict
from distutils.version import LooseVersion
from html import escape
from numbers import Number
from operator import methodcaller
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import pandas as pd
import xarray as xr
from ..coding.cftimeindex import _parse_array_of_cftime_strings
from ..plot.dataset_plot import _Dataset_PlotMethods
from . import (
alignment,
dtypes,
duck_array_ops,
formatting,
formatting_html,
groupby,
ops,
resample,
rolling,
utils,
weighted,
)
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
from .common import (
DataWithCoords,
ImplementsDatasetReduce,
_contains_datetime_like_objects,
)
from .coordinates import (
DatasetCoordinates,
assert_coordinate_consistent,
remap_label_indexers,
)
from .duck_array_ops import datetime_to_numeric
from .indexes import (
Indexes,
default_indexes,
isel_variable_and_index,
propagate_indexes,
remove_unused_levels_categories,
roll_index,
)
from .indexing import is_fancy_indexer
from .merge import (
dataset_merge_method,
dataset_update_method,
merge_coordinates_without_align,
merge_data_and_coords,
)
from .missing import get_clean_interp_index
from .options import OPTIONS, _get_keep_attrs
from .pycompat import is_duck_dask_array, sparse_array_type
from .utils import (
Default,
Frozen,
HybridMappingProxy,
SortedKeysDict,
_default,
decode_numpy_dict_values,
drop_dims_from_indexers,
either_dict_or_kwargs,
hashable,
infix_dims,
is_dict_like,
is_scalar,
maybe_wrap_array,
)
from .variable import (
IndexVariable,
Variable,
as_variable,
assert_unique_multiindex_level_names,
broadcast_variables,
)
if TYPE_CHECKING:
from ..backends import AbstractDataStore, ZarrStore
from .dataarray import DataArray
from .merge import CoercibleMapping
T_DSorDA = TypeVar("T_DSorDA", DataArray, "Dataset")
try:
from dask.delayed import Delayed
except ImportError:
Delayed = None
_DATETIMEINDEX_COMPONENTS = [
"year",
"month",
"day",
"hour",
"minute",
"second",
"microsecond",
"nanosecond",
"date",
"time",
"dayofyear",
"weekofyear",
"dayofweek",
"quarter",
]
def _get_virtual_variable(
variables, key: Hashable, level_vars: Mapping = None, dim_sizes: Mapping = None
) -> Tuple[Hashable, Hashable, Variable]:
if level_vars is None:
level_vars = {}
if dim_sizes is None:
dim_sizes = {}
if key in dim_sizes:
data = pd.Index(range(dim_sizes[key]), name=key)
variable = IndexVariable((key,), data)
return key, key, variable
if not isinstance(key, str):
raise KeyError(key)
split_key = key.split(".", 1)
var_name: Optional[str]
if len(split_key) == 2:
ref_name, var_name = split_key
elif len(split_key) == 1:
ref_name, var_name = key, None
else:
raise KeyError(key)
if ref_name in level_vars:
dim_var = variables[level_vars[ref_name]]
ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
else:
ref_var = variables[ref_name]
if var_name is None:
virtual_var = ref_var
var_name = key
else:
if _contains_datetime_like_objects(ref_var):
ref_var = xr.DataArray(ref_var)
data = getattr(ref_var.dt, var_name).data
else:
data = getattr(ref_var, var_name).data
virtual_var = Variable(ref_var.dims, data)
return ref_name, var_name, virtual_var
def calculate_dimensions(variables: Mapping[Hashable, Variable]) -> Dict[Hashable, int]:
dims: Dict[Hashable, int] = {}
last_used = {}
scalar_vars = {k for k, v in variables.items() if not v.dims}
for k, var in variables.items():
for dim, size in zip(var.dims, var.shape):
if dim in scalar_vars:
raise ValueError(
"dimension %r already exists as a scalar variable" % dim
)
if dim not in dims:
dims[dim] = size
last_used[dim] = k
elif dims[dim] != size:
raise ValueError(
"conflicting sizes for dimension %r: "
"length %s on %r and length %s on %r"
% (dim, size, k, dims[dim], last_used[dim])
)
return dims
def merge_indexes(
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
append: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
vars_to_replace: Dict[Hashable, Variable] = {}
vars_to_remove: List[Hashable] = []
dims_to_replace: Dict[Hashable, Hashable] = {}
error_msg = "{} is not the name of an existing variable."
for dim, var_names in indexes.items():
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
var_names = [var_names]
names: List[Hashable] = []
codes: List[List[int]] = []
levels: List[List[int]] = []
current_index_variable = variables.get(dim)
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
if (
current_index_variable is not None
and var.dims != current_index_variable.dims
):
raise ValueError(
"dimension mismatch between %r %s and %r %s"
% (dim, current_index_variable.dims, n, var.dims)
)
if current_index_variable is not None and append:
current_index = current_index_variable.to_index()
if isinstance(current_index, pd.MultiIndex):
names.extend(current_index.names)
codes.extend(current_index.codes)
levels.extend(current_index.levels)
else:
names.append("%s_level_0" % dim)
cat = pd.Categorical(current_index.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
if not len(names) and len(var_names) == 1:
idx = pd.Index(variables[var_names[0]].values)
else:
for n in var_names:
try:
var = variables[n]
except KeyError:
raise ValueError(error_msg.format(n))
names.append(n)
cat = pd.Categorical(var.values, ordered=True)
codes.append(cat.codes)
levels.append(cat.categories)
idx = pd.MultiIndex(levels, codes, names=names)
for n in names:
dims_to_replace[n] = dim
vars_to_replace[dim] = IndexVariable(dim, idx)
vars_to_remove.extend(var_names)
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}
new_variables.update(vars_to_replace)
for k, v in new_variables.items():
if any(d in dims_to_replace for d in v.dims):
new_dims = [dims_to_replace.get(d, d) for d in v.dims]
new_variables[k] = v._replace(dims=new_dims)
new_coord_names = coord_names | set(vars_to_replace)
new_coord_names -= set(vars_to_remove)
return new_variables, new_coord_names
def split_indexes(
dims_or_levels: Union[Hashable, Sequence[Hashable]],
variables: Mapping[Hashable, Variable],
coord_names: Set[Hashable],
level_coords: Mapping[Hashable, Hashable],
drop: bool = False,
) -> Tuple[Dict[Hashable, Variable], Set[Hashable]]:
if isinstance(dims_or_levels, str) or not isinstance(dims_or_levels, Sequence):
dims_or_levels = [dims_or_levels]
dim_levels: DefaultDict[Any, List[Hashable]] = defaultdict(list)
dims = []
for k in dims_or_levels:
if k in level_coords:
dim_levels[level_coords[k]].append(k)
else:
dims.append(k)
vars_to_replace = {}
vars_to_create: Dict[Hashable, Variable] = {}
vars_to_remove = []
for d in dims:
index = variables[d].to_index()
if isinstance(index, pd.MultiIndex):
dim_levels[d] = index.names
else:
vars_to_remove.append(d)
if not drop:
vars_to_create[str(d) + "_"] = Variable(d, index, variables[d].attrs)
for d, levs in dim_levels.items():
index = variables[d].to_index()
if len(levs) == index.nlevels:
vars_to_remove.append(d)
else:
vars_to_replace[d] = IndexVariable(d, index.droplevel(levs))
if not drop:
for lev in levs:
idx = index.get_level_values(lev)
vars_to_create[idx.name] = Variable(d, idx, variables[d].attrs)
new_variables = dict(variables)
for v in set(vars_to_remove):
del new_variables[v]
new_variables.update(vars_to_replace)
new_variables.update(vars_to_create)
new_coord_names = (coord_names | set(vars_to_create)) - set(vars_to_remove)
return new_variables, new_coord_names
def _assert_empty(args: tuple, msg: str = "%s") -> None:
if args:
raise ValueError(msg % args)
def _check_chunks_compatibility(var, chunks, preferred_chunks):
for dim in var.dims:
if dim not in chunks or (dim not in preferred_chunks):
continue
preferred_chunks_dim = preferred_chunks.get(dim)
chunks_dim = chunks.get(dim)
if isinstance(chunks_dim, int):
chunks_dim = (chunks_dim,)
else:
chunks_dim = chunks_dim[:-1]
if any(s % preferred_chunks_dim for s in chunks_dim):
warnings.warn(
f"Specified Dask chunks {chunks[dim]} would separate "
f"on disks chunk shape {preferred_chunks[dim]} for dimension {dim}. "
"This could degrade performance. "
"Consider rechunking after loading instead.",
stacklevel=2,
)
def _get_chunk(var, chunks):
import dask.array as da
if isinstance(var, IndexVariable):
return {}
if isinstance(chunks, int) or (chunks == "auto"):
chunks = dict.fromkeys(var.dims, chunks)
preferred_chunks = var.encoding.get("preferred_chunks", {})
preferred_chunks_list = [
preferred_chunks.get(dim, shape) for dim, shape in zip(var.dims, var.shape)
]
chunks_list = [
chunks.get(dim, None) or preferred_chunks.get(dim, None) for dim in var.dims
]
output_chunks_list = da.core.normalize_chunks(
chunks_list,
shape=var.shape,
dtype=var.dtype,
previous_chunks=preferred_chunks_list,
)
output_chunks = dict(zip(var.dims, output_chunks_list))
_check_chunks_compatibility(var, output_chunks, preferred_chunks)
return output_chunks
def _maybe_chunk(
name,
var,
chunks,
token=None,
lock=None,
name_prefix="xarray-",
overwrite_encoded_chunks=False,
):
from dask.base import tokenize
if chunks is not None:
chunks = {dim: chunks[dim] for dim in var.dims if dim in chunks}
if var.ndim:
token2 = tokenize(name, token if token else var._data, chunks)
name2 = f"{name_prefix}{name}-{token2}"
var = var.chunk(chunks, name=name2, lock=lock)
if overwrite_encoded_chunks and var.chunks is not None:
var.encoding["chunks"] = tuple(x[0] for x in var.chunks)
return var
else:
return var
def as_dataset(obj: Any) -> "Dataset":
if hasattr(obj, "to_dataset"):
obj = obj.to_dataset()
if not isinstance(obj, Dataset):
obj = Dataset(obj)
return obj
def _get_func_args(func, param_names):
try:
func_args = inspect.signature(func).parameters
except ValueError:
func_args = {}
if not param_names:
raise ValueError(
"Unable to inspect `func` signature, and `param_names` was not provided."
)
if param_names:
params = param_names
else:
params = list(func_args)[1:]
if any(
[(p.kind in [p.VAR_POSITIONAL, p.VAR_KEYWORD]) for p in func_args.values()]
):
raise ValueError(
"`param_names` must be provided because `func` takes variable length arguments."
)
return params, func_args
def _initialize_curvefit_params(params, p0, bounds, func_args):
def _initialize_feasible(lb, ub):
lb_finite = np.isfinite(lb)
ub_finite = np.isfinite(ub)
p0 = np.nansum(
[
0.5 * (lb + ub) * int(lb_finite & ub_finite),
(lb + 1) * int(lb_finite & ~ub_finite),
(ub - 1) * int(~lb_finite & ub_finite),
]
)
return p0
param_defaults = {p: 1 for p in params}
bounds_defaults = {p: (-np.inf, np.inf) for p in params}
for p in params:
if p in func_args and func_args[p].default is not func_args[p].empty:
param_defaults[p] = func_args[p].default
if p in bounds:
bounds_defaults[p] = tuple(bounds[p])
if param_defaults[p] < bounds[p][0] or param_defaults[p] > bounds[p][1]:
param_defaults[p] = _initialize_feasible(bounds[p][0], bounds[p][1])
if p in p0:
param_defaults[p] = p0[p]
return param_defaults, bounds_defaults
class DataVariables(Mapping[Hashable, "DataArray"]):
__slots__ = ("_dataset",)
def __init__(self, dataset: "Dataset"):
self._dataset = dataset
def __iter__(self) -> Iterator[Hashable]:
return (
key
for key in self._dataset._variables
if key not in self._dataset._coord_names
)
def __len__(self) -> int:
return len(self._dataset._variables) - len(self._dataset._coord_names)
def __contains__(self, key: Hashable) -> bool:
return key in self._dataset._variables and key not in self._dataset._coord_names
def __getitem__(self, key: Hashable) -> "DataArray":
if key not in self._dataset._coord_names:
return cast("DataArray", self._dataset[key])
raise KeyError(key)
def __repr__(self) -> str:
return formatting.data_vars_repr(self)
@property
def variables(self) -> Mapping[Hashable, Variable]:
all_variables = self._dataset.variables
return Frozen({k: all_variables[k] for k in self})
def _ipython_key_completions_(self):
return [
key
for key in self._dataset._ipython_key_completions_()
if key not in self._dataset._coord_names
]
class _LocIndexer:
__slots__ = ("dataset",)
def __init__(self, dataset: "Dataset"):
self.dataset = dataset
def __getitem__(self, key: Mapping[Hashable, Any]) -> "Dataset":
if not utils.is_dict_like(key):
raise TypeError("can only lookup dictionaries from Dataset.loc")
return self.dataset.sel(key)
class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
_attrs: Optional[Dict[Hashable, Any]]
_cache: Dict[str, Any]
_coord_names: Set[Hashable]
_dims: Dict[Hashable, int]
_encoding: Optional[Dict[Hashable, Any]]
_close: Optional[Callable[[], None]]
_indexes: Optional[Dict[Hashable, pd.Index]]
_variables: Dict[Hashable, Variable]
__slots__ = (
"_attrs",
"_cache",
"_coord_names",
"_dims",
"_encoding",
"_close",
"_indexes",
"_variables",
"__weakref__",
)
_groupby_cls = groupby.DatasetGroupBy
_rolling_cls = rolling.DatasetRolling
_coarsen_cls = rolling.DatasetCoarsen
_resample_cls = resample.DatasetResample
_weighted_cls = weighted.DatasetWeighted
def __init__(
self,
data_vars: Mapping[Hashable, Any] = None,
coords: Mapping[Hashable, Any] = None,
attrs: Mapping[Hashable, Any] = None,
):
if data_vars is None:
data_vars = {}
if coords is None:
coords = {}
both_data_and_coords = set(data_vars) & set(coords)
if both_data_and_coords:
raise ValueError(
"variables %r are found in both data_vars and coords"
% both_data_and_coords
)
if isinstance(coords, Dataset):
coords = coords.variables
variables, coord_names, dims, indexes, _ = merge_data_and_coords(
data_vars, coords, compat="broadcast_equals"
)
self._attrs = dict(attrs) if attrs is not None else None
self._close = None
self._encoding = None
self._variables = variables
self._coord_names = coord_names
self._dims = dims
self._indexes = indexes
@classmethod
def load_store(cls, store, decoder=None) -> "Dataset":
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj.set_close(store.close)
return obj
@property
def variables(self) -> Mapping[Hashable, Variable]:
return Frozen(self._variables)
@property
def attrs(self) -> Dict[Hashable, Any]:
if self._attrs is None:
self._attrs = {}
return self._attrs
@attrs.setter
def attrs(self, value: Mapping[Hashable, Any]) -> None:
self._attrs = dict(value)
@property
def encoding(self) -> Dict:
if self._encoding is None:
self._encoding = {}
return self._encoding
@encoding.setter
def encoding(self, value: Mapping) -> None:
self._encoding = dict(value)
@property
def dims(self) -> Mapping[Hashable, int]:
return Frozen(SortedKeysDict(self._dims))
@property
def sizes(self) -> Mapping[Hashable, int]:
return self.dims
def load(self, **kwargs) -> "Dataset":
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask.array as da
evaluated_data = da.compute(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
for k, v in self.variables.items():
if k not in lazy_data:
v.load()
return self
def __dask_tokenize__(self):
from dask.base import normalize_token
return normalize_token(
(type(self), self._variables, self._coord_names, self._attrs)
)
def __dask_graph__(self):
graphs = {k: v.__dask_graph__() for k, v in self.variables.items()}
graphs = {k: v for k, v in graphs.items() if v is not None}
if not graphs:
return None
else:
try:
from dask.highlevelgraph import HighLevelGraph
return HighLevelGraph.merge(*graphs.values())
except ImportError:
from dask import sharedict
return sharedict.merge(*graphs.values())
def __dask_keys__(self):
import dask
return [
v.__dask_keys__()
for v in self.variables.values()
if dask.is_dask_collection(v)
]
def __dask_layers__(self):
import dask
return sum(
[
v.__dask_layers__()
for v in self.variables.values()
if dask.is_dask_collection(v)
],
(),
)
@property
def __dask_optimize__(self):
import dask.array as da
return da.Array.__dask_optimize__
@property
def __dask_scheduler__(self):
import dask.array as da
return da.Array.__dask_scheduler__
def __dask_postcompute__(self):
return self._dask_postcompute, ()
def __dask_postpersist__(self):
return self._dask_postpersist, ()
def _dask_postcompute(self, results: "Iterable[Variable]") -> "Dataset":
import dask
variables = {}
results_iter = iter(results)
for k, v in self._variables.items():
if dask.is_dask_collection(v):
rebuild, args = v.__dask_postcompute__()
v = rebuild(next(results_iter), *args)
variables[k] = v
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def _dask_postpersist(
self, dsk: Mapping, *, rename: Mapping[str, str] = None
) -> "Dataset":
from dask import is_dask_collection
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import cull
variables = {}
for k, v in self._variables.items():
if not is_dask_collection(v):
variables[k] = v
continue
if isinstance(dsk, HighLevelGraph):
# https://github.com/dask/dask/issues/7137
layers = v.__dask_layers__()
if rename:
layers = [rename.get(k, k) for k in layers]
dsk2 = dsk.cull_layers(layers)
elif rename: # pragma: nocover
# At the moment of writing, this is only for forward compatibility.
# replace_name_in_key requires dask >= 2021.3.
from dask.base import flatten, replace_name_in_key
keys = [
replace_name_in_key(k, rename) for k in flatten(v.__dask_keys__())
]
dsk2, _ = cull(dsk, keys)
else:
# __dask_postpersist__() was called by dask.optimize or dask.persist
dsk2, _ = cull(dsk, v.__dask_keys__())
rebuild, args = v.__dask_postpersist__()
# rename was added in dask 2021.3
kwargs = {"rename": rename} if rename else {}
variables[k] = rebuild(dsk2, *args, **kwargs)
return Dataset._construct_direct(
variables,
self._coord_names,
self._dims,
self._attrs,
self._indexes,
self._encoding,
self._close,
)
def compute(self, **kwargs) -> "Dataset":
new = self.copy(deep=False)
return new.load(**kwargs)
def _persist_inplace(self, **kwargs) -> "Dataset":
# access .data to coerce everything to numpy or dask arrays
lazy_data = {
k: v._data for k, v in self.variables.items() if is_duck_dask_array(v._data)
}
if lazy_data:
import dask
# evaluate all the dask arrays simultaneously
evaluated_data = dask.persist(*lazy_data.values(), **kwargs)
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
return self
def persist(self, **kwargs) -> "Dataset":
new = self.copy(deep=False)
return new._persist_inplace(**kwargs)
@classmethod
def _construct_direct(
cls,
variables,
coord_names,
dims=None,
attrs=None,
indexes=None,
encoding=None,
close=None,
):
if dims is None:
dims = calculate_dimensions(variables)
obj = object.__new__(cls)
obj._variables = variables
obj._coord_names = coord_names
obj._dims = dims
obj._indexes = indexes
obj._attrs = attrs
obj._close = close
obj._encoding = encoding
return obj
def _replace(
self,
variables: Dict[Hashable, Variable] = None,
coord_names: Set[Hashable] = None,
dims: Dict[Any, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Any, pd.Index], None, Default] = _default,
encoding: Union[dict, None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
if inplace:
if variables is not None:
self._variables = variables
if coord_names is not None:
self._coord_names = coord_names
if dims is not None:
self._dims = dims
if attrs is not _default:
self._attrs = attrs
if indexes is not _default:
self._indexes = indexes
if encoding is not _default:
self._encoding = encoding
obj = self
else:
if variables is None:
variables = self._variables.copy()
if coord_names is None:
coord_names = self._coord_names.copy()
if dims is None:
dims = self._dims.copy()
if attrs is _default:
attrs = copy.copy(self._attrs)
if indexes is _default:
indexes = copy.copy(self._indexes)
if encoding is _default:
encoding = copy.copy(self._encoding)
obj = self._construct_direct(
variables, coord_names, dims, attrs, indexes, encoding
)
return obj
def _replace_with_new_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
indexes: Union[Dict[Hashable, pd.Index], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes, inplace=inplace
)
def _replace_vars_and_dims(
self,
variables: Dict[Hashable, Variable],
coord_names: set = None,
dims: Dict[Hashable, int] = None,
attrs: Union[Dict[Hashable, Any], None, Default] = _default,
inplace: bool = False,
) -> "Dataset":
if dims is None:
dims = calculate_dimensions(variables)
return self._replace(
variables, coord_names, dims, attrs, indexes=None, inplace=inplace
)
def _overwrite_indexes(self, indexes: Mapping[Any, pd.Index]) -> "Dataset":
if not indexes:
return self
variables = self._variables.copy()
new_indexes = dict(self.indexes)
for name, idx in indexes.items():
variables[name] = IndexVariable(name, idx)
new_indexes[name] = idx
obj = self._replace(variables, indexes=new_indexes)
# switch from dimension to level names, if necessary
dim_names: Dict[Hashable, str] = {}
for dim, idx in indexes.items():
if not isinstance(idx, pd.MultiIndex) and idx.name != dim:
dim_names[dim] = idx.name
if dim_names:
obj = obj.rename(dim_names)
return obj
def copy(self, deep: bool = False, data: Mapping = None) -> "Dataset":
if data is None:
variables = {k: v.copy(deep=deep) for k, v in self._variables.items()}
elif not utils.is_dict_like(data):
raise ValueError("Data must be dict-like")
else:
var_keys = set(self.data_vars.keys())
data_keys = set(data.keys())
keys_not_in_vars = data_keys - var_keys
if keys_not_in_vars:
raise ValueError(
"Data must only contain variables in original "
"dataset. Extra variables: {}".format(keys_not_in_vars)
)
keys_missing_from_data = var_keys - data_keys
if keys_missing_from_data:
raise ValueError(
"Data must contain all variables in original "
"dataset. Data is missing {}".format(keys_missing_from_data)
)
variables = {
k: v.copy(deep=deep, data=data.get(k))
for k, v in self._variables.items()
}
attrs = copy.deepcopy(self._attrs) if deep else copy.copy(self._attrs)
return self._replace(variables, attrs=attrs)
@property
def _level_coords(self) -> Dict[str, Hashable]:
level_coords: Dict[str, Hashable] = {}
for name, index in self.indexes.items():
if isinstance(index, pd.MultiIndex):
level_names = index.names
(dim,) = self.variables[name].dims
level_coords.update({lname: dim for lname in level_names})
return level_coords
def _copy_listed(self, names: Iterable[Hashable]) -> "Dataset":
variables: Dict[Hashable, Variable] = {}
coord_names = set()
indexes: Dict[Hashable, pd.Index] = {}
for name in names:
try:
variables[name] = self._variables[name]
except KeyError:
ref_name, var_name, var = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
variables[var_name] = var
if ref_name in self._coord_names or ref_name in self.dims:
coord_names.add(var_name)
if (var_name,) == var.dims:
indexes[var_name] = var.to_index()
needed_dims: Set[Hashable] = set()
for v in variables.values():
needed_dims.update(v.dims)
dims = {k: self.dims[k] for k in needed_dims}
# preserves ordering of coordinates
for k in self._variables:
if k not in self._coord_names:
continue
if set(self.variables[k].dims) <= needed_dims:
variables[k] = self._variables[k]
coord_names.add(k)
if k in self.indexes:
indexes[k] = self.indexes[k]
return self._replace(variables, coord_names, dims, indexes=indexes)
def _construct_dataarray(self, name: Hashable) -> "DataArray":
from .dataarray import DataArray
try:
variable = self._variables[name]
except KeyError:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
needed_dims = set(variable.dims)
coords: Dict[Hashable, Variable] = {}
# preserve ordering
for k in self._variables:
if k in self._coord_names and set(self.variables[k].dims) <= needed_dims:
coords[k] = self.variables[k]
if self._indexes is None:
indexes = None
else:
indexes = {k: v for k, v in self._indexes.items() if k in coords}
return DataArray(variable, coords, name=name, indexes=indexes, fastpath=True)
def __copy__(self) -> "Dataset":
return self.copy(deep=False)
def __deepcopy__(self, memo=None) -> "Dataset":
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
@property
def _attr_sources(self) -> Iterable[Mapping[Hashable, Any]]:
yield from self._item_sources
yield self.attrs
@property
def _item_sources(self) -> Iterable[Mapping[Hashable, Any]]:
yield self.data_vars
yield HybridMappingProxy(keys=self._coord_names, mapping=self.coords)
# virtual coordinates
yield HybridMappingProxy(keys=self.dims, mapping=self)
# uses empty dict -- everything here can already be found in self.coords.
yield HybridMappingProxy(keys=self._level_coords, mapping={})
def __contains__(self, key: object) -> bool:
return key in self._variables
def __len__(self) -> int:
return len(self.data_vars)
def __bool__(self) -> bool:
return bool(self.data_vars)
def __iter__(self) -> Iterator[Hashable]:
return iter(self.data_vars)
def __array__(self, dtype=None):
raise TypeError(
"cannot directly convert an xarray.Dataset into a "
"numpy array. Instead, create an xarray.DataArray "
"first, either with indexing on the Dataset or by "
"invoking the `to_array()` method."
)
@property
def nbytes(self) -> int:
return sum(v.nbytes for v in self.variables.values())
@property
def loc(self) -> _LocIndexer:
return _LocIndexer(self)
# FIXME https://github.com/python/mypy/issues/7328
@overload
def __getitem__(self, key: Mapping) -> "Dataset": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Hashable) -> "DataArray": # type: ignore[misc]
...
@overload
def __getitem__(self, key: Any) -> "Dataset":
...
def __getitem__(self, key):
if utils.is_dict_like(key):
return self.isel(**cast(Mapping, key))
if hashable(key):
return self._construct_dataarray(key)
else:
return self._copy_listed(np.asarray(key))
def __setitem__(self, key: Hashable, value) -> None:
if utils.is_dict_like(key):
raise NotImplementedError(
"cannot yet use a dictionary as a key to set Dataset values"
)
self.update({key: value})
def __delitem__(self, key: Hashable) -> None:
del self._variables[key]
self._coord_names.discard(key)
if key in self.indexes:
assert self._indexes is not None
del self._indexes[key]
self._dims = calculate_dimensions(self._variables)
# mutable objects should not be hashable
# https://github.com/python/mypy/issues/4266
__hash__ = None # type: ignore[assignment]
def _all_compat(self, other: "Dataset", compat_str: str) -> bool:
# some stores (e.g., scipy) do not seem to preserve order, so don't
def compat(x: Variable, y: Variable) -> bool:
return getattr(x, compat_str)(y)
return self._coord_names == other._coord_names and utils.dict_equiv(
self._variables, other._variables, compat=compat
)
def broadcast_equals(self, other: "Dataset") -> bool:
try:
return self._all_compat(other, "broadcast_equals")
except (TypeError, AttributeError):
return False
def equals(self, other: "Dataset") -> bool:
try:
return self._all_compat(other, "equals")
except (TypeError, AttributeError):
return False
def identical(self, other: "Dataset") -> bool:
try:
return utils.dict_equiv(self.attrs, other.attrs) and self._all_compat(
other, "identical"
)
except (TypeError, AttributeError):
return False
@property
def indexes(self) -> Indexes:
if self._indexes is None:
self._indexes = default_indexes(self._variables, self._dims)
return Indexes(self._indexes)
@property
def coords(self) -> DatasetCoordinates:
return DatasetCoordinates(self)
@property
def data_vars(self) -> DataVariables:
return DataVariables(self)
def set_coords(self, names: "Union[Hashable, Iterable[Hashable]]") -> "Dataset":
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
obj = self.copy()
obj._coord_names.update(names)
return obj
def reset_coords(
self,
names: "Union[Hashable, Iterable[Hashable], None]" = None,
drop: bool = False,
) -> "Dataset":
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, str) or not isinstance(names, Iterable):
names = [names]
else:
names = list(names)
self._assert_all_in_dataset(names)
bad_coords = set(names) & set(self.dims)
if bad_coords:
raise ValueError(
"cannot remove index coordinates with reset_coords: %s" % bad_coords
)
obj = self.copy()
obj._coord_names.difference_update(names)
if drop:
for name in names:
del obj._variables[name]
return obj
def dump_to_store(self, store: "AbstractDataStore", **kwargs) -> None:
from ..backends.api import dump_to_store
dump_to_store(self, store, **kwargs)
def to_netcdf(
self,
path=None,
mode: str = "w",
format: str = None,
group: str = None,
engine: str = None,
encoding: Mapping = None,
unlimited_dims: Iterable[Hashable] = None,
compute: bool = True,
invalid_netcdf: bool = False,
) -> Union[bytes, "Delayed", None]:
if encoding is None:
encoding = {}
from ..backends.api import to_netcdf
return to_netcdf(
self,
path,
mode,
format=format,
group=group,
engine=engine,
encoding=encoding,
unlimited_dims=unlimited_dims,
compute=compute,
invalid_netcdf=invalid_netcdf,
)
def to_zarr(
self,
store: Union[MutableMapping, str, Path] = None,
chunk_store: Union[MutableMapping, str, Path] = None,
mode: str = None,
synchronizer=None,
group: str = None,
encoding: Mapping = None,
compute: bool = True,
consolidated: bool = False,
append_dim: Hashable = None,
region: Mapping[str, slice] = None,
) -> "ZarrStore":
from ..backends.api import to_zarr
if encoding is None:
encoding = {}
return to_zarr(
self,
store=store,
chunk_store=chunk_store,
mode=mode,
synchronizer=synchronizer,
group=group,
encoding=encoding,
compute=compute,
consolidated=consolidated,
append_dim=append_dim,
region=region,
)
def __repr__(self) -> str:
return formatting.dataset_repr(self)
def _repr_html_(self):
if OPTIONS["display_style"] == "text":
return f"<pre>{escape(repr(self))}</pre>"
return formatting_html.dataset_repr(self)
def info(self, buf=None) -> None:
if buf is None:
buf = sys.stdout
lines = []
lines.append("xarray.Dataset {")
lines.append("dimensions:")
for name, size in self.dims.items():
lines.append(f"\t{name} = {size} ;")
lines.append("\nvariables:")
for name, da in self.variables.items():
dims = ", ".join(da.dims)
lines.append(f"\t{da.dtype} {name}({dims}) ;")
for k, v in da.attrs.items():
lines.append(f"\t\t{name}:{k} = {v} ;")
lines.append("\n// global attributes:")
for k, v in self.attrs.items():
lines.append(f"\t:{k} = {v} ;")
lines.append("}")
buf.write("\n".join(lines))
@property
def chunks(self) -> Mapping[Hashable, Tuple[int, ...]]:
chunks: Dict[Hashable, Tuple[int, ...]] = {}
for v in self.variables.values():
if v.chunks is not None:
for dim, c in zip(v.dims, v.chunks):
if dim in chunks and c != chunks[dim]:
raise ValueError(
f"Object has inconsistent chunks along dimension {dim}. "
"This can be fixed by calling unify_chunks()."
)
chunks[dim] = c
return Frozen(SortedKeysDict(chunks))
def chunk(
self,
chunks: Union[
Number,
str,
Mapping[Hashable, Union[None, Number, str, Tuple[Number, ...]]],
] = {},
name_prefix: str = "xarray-",
token: str = None,
lock: bool = False,
) -> "Dataset":
if chunks is None:
warnings.warn(
"None value for 'chunks' is deprecated. "
"It will raise an error in the future. Use instead '{}'",
category=FutureWarning,
)
chunks = {}
if isinstance(chunks, (Number, str)):
chunks = dict.fromkeys(self.dims, chunks)
bad_dims = chunks.keys() - self.dims.keys()
if bad_dims:
raise ValueError(
"some chunks keys are not dimensions on this " "object: %s" % bad_dims
)
variables = {
k: _maybe_chunk(k, v, chunks, token, lock, name_prefix)
for k, v in self.variables.items()
}
return self._replace(variables)
def _validate_indexers(
self, indexers: Mapping[Hashable, Any], missing_dims: str = "raise"
) -> Iterator[Tuple[Hashable, Union[int, slice, np.ndarray, Variable]]]:
from .dataarray import DataArray
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
# all indexers should be int, slice, np.ndarrays, or Variable
for k, v in indexers.items():
if isinstance(v, (int, slice, Variable)):
yield k, v
elif isinstance(v, DataArray):
yield k, v.variable
elif isinstance(v, tuple):
yield k, as_variable(v)
elif isinstance(v, Dataset):
raise TypeError("cannot use a Dataset as an indexer")
elif isinstance(v, Sequence) and len(v) == 0:
yield k, np.empty((0,), dtype="int64")
else:
v = np.asarray(v)
if v.dtype.kind in "US":
index = self.indexes[k]
if isinstance(index, pd.DatetimeIndex):
v = v.astype("datetime64[ns]")
elif isinstance(index, xr.CFTimeIndex):
v = _parse_array_of_cftime_strings(v, index.date_type)
if v.ndim > 1:
raise IndexError(
"Unlabeled multi-dimensional array cannot be "
"used for indexing: {}".format(k)
)
yield k, v
def _validate_interp_indexers(
self, indexers: Mapping[Hashable, Any]
) -> Iterator[Tuple[Hashable, Variable]]:
for k, v in self._validate_indexers(indexers):
if isinstance(v, Variable):
if v.ndim == 1:
yield k, v.to_index_variable()
else:
yield k, v
elif isinstance(v, int):
yield k, Variable((), v)
elif isinstance(v, np.ndarray):
if v.ndim == 0:
yield k, Variable((), v)
elif v.ndim == 1:
yield k, IndexVariable((k,), v)
else:
raise AssertionError() # Already tested by _validate_indexers
else:
raise TypeError(type(v))
def _get_indexers_coords_and_indexes(self, indexers):
from .dataarray import DataArray
coords_list = []
for k, v in indexers.items():
if isinstance(v, DataArray):
if v.dtype.kind == "b":
if v.ndim != 1: # we only support 1-d boolean array
raise ValueError(
"{:d}d-boolean array is used for indexing along "
"dimension {!r}, but only 1d boolean arrays are "
"supported.".format(v.ndim, k)
)
# Make sure in case of boolean DataArray, its
# coordinate also should be indexed.
v_coords = v[v.values.nonzero()[0]].coords
else:
v_coords = v.coords
coords_list.append(v_coords)
# we don't need to call align() explicitly or check indexes for
coords, indexes = merge_coordinates_without_align(coords_list)
assert_coordinate_consistent(self, coords)
attached_coords = {k: v for k, v in coords.items() if k not in self._variables}
attached_indexes = {
k: v for k, v in indexes.items() if k not in self._variables
}
return attached_coords, attached_indexes
def isel(
self,
indexers: Mapping[Hashable, Any] = None,
drop: bool = False,
missing_dims: str = "raise",
**indexers_kwargs: Any,
) -> "Dataset":
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "isel")
if any(is_fancy_indexer(idx) for idx in indexers.values()):
return self._isel_fancy(indexers, drop=drop, missing_dims=missing_dims)
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
variables = {}
dims: Dict[Hashable, Tuple[int, ...]] = {}
coord_names = self._coord_names.copy()
indexes = self._indexes.copy() if self._indexes is not None else None
for var_name, var_value in self._variables.items():
var_indexers = {k: v for k, v in indexers.items() if k in var_value.dims}
if var_indexers:
var_value = var_value.isel(var_indexers)
if drop and var_value.ndim == 0 and var_name in coord_names:
coord_names.remove(var_name)
if indexes:
indexes.pop(var_name, None)
continue
if indexes and var_name in indexes:
if var_value.ndim == 1:
indexes[var_name] = var_value.to_index()
else:
del indexes[var_name]
variables[var_name] = var_value
dims.update(zip(var_value.dims, var_value.shape))
return self._construct_direct(
variables=variables,
coord_names=coord_names,
dims=dims,
attrs=self._attrs,
indexes=indexes,
encoding=self._encoding,
close=self._close,
)
def _isel_fancy(
self,
indexers: Mapping[Hashable, Any],
*,
drop: bool,
missing_dims: str = "raise",
) -> "Dataset":
# Note: we need to preserve the original indexers variable in order to merge the
# coords below
indexers_list = list(self._validate_indexers(indexers, missing_dims))
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for name, var in self.variables.items():
var_indexers = {k: v for k, v in indexers_list if k in var.dims}
if drop and name in var_indexers:
continue # drop this variable
if name in self.indexes:
new_var, new_index = isel_variable_and_index(
name, var, self.indexes[name], var_indexers
)
if new_index is not None:
indexes[name] = new_index
elif var_indexers:
new_var = var.isel(indexers=var_indexers)
else:
new_var = var.copy(deep=False)
variables[name] = new_var
coord_names = self._coord_names & variables.keys()
selected = self._replace_with_new_dims(variables, coord_names, indexes)
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(indexers)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = self._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def sel(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
drop: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
pos_indexers, new_indexes = remap_label_indexers(
self, indexers=indexers, method=method, tolerance=tolerance
)
result = self.isel(indexers=pos_indexers, drop=drop)
return result._overwrite_indexes(new_indexes)
def head(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "head")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {k: slice(val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def tail(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if not indexers_kwargs:
if indexers is None:
indexers = 5
if not isinstance(indexers, int) and not is_dict_like(indexers):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "tail")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
indexers_slices = {
k: slice(-val, None) if val != 0 else slice(val)
for k, val in indexers.items()
}
return self.isel(indexers_slices)
def thin(
self,
indexers: Union[Mapping[Hashable, int], int] = None,
**indexers_kwargs: Any,
) -> "Dataset":
if (
not indexers_kwargs
and not isinstance(indexers, int)
and not is_dict_like(indexers)
):
raise TypeError("indexers must be either dict-like or a single integer")
if isinstance(indexers, int):
indexers = {dim: indexers for dim in self.dims}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "thin")
for k, v in indexers.items():
if not isinstance(v, int):
raise TypeError(
"expected integer type indexer for "
"dimension %r, found %r" % (k, type(v))
)
elif v < 0:
raise ValueError(
"expected positive integer as indexer "
"for dimension %r, found %s" % (k, v)
)
elif v == 0:
raise ValueError("step cannot be zero")
indexers_slices = {k: slice(None, None, val) for k, val in indexers.items()}
return self.isel(indexers_slices)
def broadcast_like(
self, other: Union["Dataset", "DataArray"], exclude: Iterable[Hashable] = None
) -> "Dataset":
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
args = align(other, self, join="outer", copy=False, exclude=exclude)
dims_map, common_coords = _get_broadcast_dims_map_common_coords(args, exclude)
return _broadcast_helper(args[1], exclude, dims_map, common_coords)
def reindex_like(
self,
other: Union["Dataset", "DataArray"],
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
) -> "Dataset":
indexers = alignment.reindex_like_indexers(self, other)
return self.reindex(
indexers=indexers,
method=method,
copy=copy,
fill_value=fill_value,
tolerance=tolerance,
)
def reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
**indexers_kwargs: Any,
) -> "Dataset":
return self._reindex(
indexers,
method,
tolerance,
copy,
fill_value,
sparse=False,
**indexers_kwargs,
)
def _reindex(
self,
indexers: Mapping[Hashable, Any] = None,
method: str = None,
tolerance: Number = None,
copy: bool = True,
fill_value: Any = dtypes.NA,
sparse: bool = False,
**indexers_kwargs: Any,
) -> "Dataset":
indexers = utils.either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
bad_dims = [d for d in indexers if d not in self.dims]
if bad_dims:
raise ValueError("invalid reindex dimensions: %s" % bad_dims)
variables, indexes = alignment.reindex_variables(
self.variables,
self.sizes,
self.indexes,
indexers,
method,
tolerance,
copy=copy,
fill_value=fill_value,
sparse=sparse,
)
coord_names = set(self._coord_names)
coord_names.update(indexers)
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp(
self,
coords: Mapping[Hashable, Any] = None,
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
**coords_kwargs: Any,
) -> "Dataset":
from . import missing
if kwargs is None:
kwargs = {}
coords = either_dict_or_kwargs(coords, coords_kwargs, "interp")
indexers = dict(self._validate_interp_indexers(coords))
if coords:
# This avoids broadcasting over coordinates that are both in
# the original array AND in the indexing array. It essentially
# forces interpolation along the shared coordinates.
sdims = (
set(self.dims)
.intersection(*[set(nx.dims) for nx in indexers.values()])
.difference(coords.keys())
)
indexers.update({d: self.variables[d] for d in sdims})
obj = self if assume_sorted else self.sortby([k for k in coords])
def maybe_variable(obj, k):
# workaround to get variable for dimension without coordinate.
try:
return obj._variables[k]
except KeyError:
return as_variable((k, range(obj.dims[k])))
def _validate_interp_indexer(x, new_x):
# In the case of datetimes, the restrictions placed on indexers
# used with interp are stronger than those which are placed on
# isel, so we need an additional check after _validate_indexers.
if _contains_datetime_like_objects(
x
) and not _contains_datetime_like_objects(new_x):
raise TypeError(
"When interpolating over a datetime-like "
"coordinate, the coordinates to "
"interpolate to must be either datetime "
"strings or datetimes. "
"Instead got\n{}".format(new_x)
)
return x, new_x
variables: Dict[Hashable, Variable] = {}
for name, var in obj._variables.items():
if name in indexers:
continue
if var.dtype.kind in "uifc":
var_indexers = {
k: _validate_interp_indexer(maybe_variable(obj, k), v)
for k, v in indexers.items()
if k in var.dims
}
variables[name] = missing.interp(var, var_indexers, method, **kwargs)
elif all(d not in indexers for d in var.dims):
# keep unrelated object array
variables[name] = var
coord_names = obj._coord_names & variables.keys()
indexes = {k: v for k, v in obj.indexes.items() if k not in indexers}
selected = self._replace_with_new_dims(
variables.copy(), coord_names, indexes=indexes
)
# attach indexer as coordinate
variables.update(indexers)
for k, v in indexers.items():
assert isinstance(v, Variable)
if v.dims == (k,):
indexes[k] = v.to_index()
# Extract coordinates from indexers
coord_vars, new_indexes = selected._get_indexers_coords_and_indexes(coords)
variables.update(coord_vars)
indexes.update(new_indexes)
coord_names = obj._coord_names & variables.keys() | coord_vars.keys()
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def interp_like(
self,
other: Union["Dataset", "DataArray"],
method: str = "linear",
assume_sorted: bool = False,
kwargs: Mapping[str, Any] = None,
) -> "Dataset":
if kwargs is None:
kwargs = {}
coords = alignment.reindex_like_indexers(self, other)
numeric_coords: Dict[Hashable, pd.Index] = {}
object_coords: Dict[Hashable, pd.Index] = {}
for k, v in coords.items():
if v.dtype.kind in "uifcMm":
numeric_coords[k] = v
else:
object_coords[k] = v
ds = self
if object_coords:
# We do not support interpolation along object coordinate.
# reindex instead.
ds = self.reindex(object_coords)
return ds.interp(numeric_coords, method, assume_sorted, kwargs)
# Helper methods for rename()
def _rename_vars(self, name_dict, dims_dict):
variables = {}
coord_names = set()
for k, v in self.variables.items():
var = v.copy(deep=False)
var.dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
name = name_dict.get(k, k)
if name in variables:
raise ValueError(f"the new name {name!r} conflicts")
variables[name] = var
if k in self._coord_names:
coord_names.add(name)
return variables, coord_names
def _rename_dims(self, name_dict):
return {name_dict.get(k, k): v for k, v in self.dims.items()}
def _rename_indexes(self, name_dict, dims_set):
if self._indexes is None:
return None
indexes = {}
for k, v in self.indexes.items():
new_name = name_dict.get(k, k)
if new_name not in dims_set:
continue
if isinstance(v, pd.MultiIndex):
new_names = [name_dict.get(k, k) for k in v.names]
index = v.rename(names=new_names)
else:
index = v.rename(new_name)
indexes[new_name] = index
return indexes
def _rename_all(self, name_dict, dims_dict):
variables, coord_names = self._rename_vars(name_dict, dims_dict)
dims = self._rename_dims(dims_dict)
indexes = self._rename_indexes(name_dict, dims.keys())
return variables, coord_names, dims, indexes
def rename(
self,
name_dict: Mapping[Hashable, Hashable] = None,
**names: Hashable,
) -> "Dataset":
name_dict = either_dict_or_kwargs(name_dict, names, "rename")
for k in name_dict.keys():
if k not in self and k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"variable or dimension in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict=name_dict
)
assert_unique_multiindex_level_names(variables)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def rename_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims: Hashable
) -> "Dataset":
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"dimension in this dataset" % k
)
if v in self.dims or v in self:
raise ValueError(
f"Cannot rename {k} to {v} because {v} already exists. "
"Try using swap_dims instead."
)
variables, coord_names, sizes, indexes = self._rename_all(
name_dict={}, dims_dict=dims_dict
)
return self._replace(variables, coord_names, dims=sizes, indexes=indexes)
def rename_vars(
self, name_dict: Mapping[Hashable, Hashable] = None, **names: Hashable
) -> "Dataset":
name_dict = either_dict_or_kwargs(name_dict, names, "rename_vars")
for k in name_dict:
if k not in self:
raise ValueError(
"cannot rename %r because it is not a "
"variable or coordinate in this dataset" % k
)
variables, coord_names, dims, indexes = self._rename_all(
name_dict=name_dict, dims_dict={}
)
return self._replace(variables, coord_names, dims=dims, indexes=indexes)
def swap_dims(
self, dims_dict: Mapping[Hashable, Hashable] = None, **dims_kwargs
) -> "Dataset":
# TODO: deprecate this method in favor of a (less confusing)
# rename_dims() method that only renames dimensions.
dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, "swap_dims")
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot swap from dimension %r because it is "
"not an existing dimension" % k
)
if v in self.variables and self.variables[v].dims != (k,):
raise ValueError(
"replacement dimension %r is not a 1D "
"variable along the old dimension %r" % (v, k)
)
result_dims = {dims_dict.get(dim, dim) for dim in self.dims}
coord_names = self._coord_names.copy()
coord_names.update({dim for dim in dims_dict.values() if dim in self.variables})
variables: Dict[Hashable, Variable] = {}
indexes: Dict[Hashable, pd.Index] = {}
for k, v in self.variables.items():
dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
if k in result_dims:
var = v.to_index_variable()
if k in self.indexes:
indexes[k] = self.indexes[k]
else:
new_index = var.to_index()
if new_index.nlevels == 1:
# make sure index name matches dimension name
new_index = new_index.rename(k)
indexes[k] = new_index
else:
var = v.to_base_variable()
var.dims = dims
variables[k] = var
return self._replace_with_new_dims(variables, coord_names, indexes=indexes)
def expand_dims(
self,
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
axis: Union[None, int, Sequence[int]] = None,
**dim_kwargs: Any,
) -> "Dataset":
if dim is None:
pass
elif isinstance(dim, Mapping):
# We're later going to modify dim in place; don't tamper with
# the input
dim = dict(dim)
elif isinstance(dim, int):
raise TypeError(
"dim should be hashable or sequence of hashables or mapping"
)
elif isinstance(dim, str) or not isinstance(dim, Sequence):
dim = {dim: 1}
elif isinstance(dim, Sequence):
if len(dim) != len(set(dim)):
raise ValueError("dims should not contain duplicate values.")
dim = {d: 1 for d in dim}
dim = either_dict_or_kwargs(dim, dim_kwargs, "expand_dims")
assert isinstance(dim, MutableMapping)
if axis is None:
axis = list(range(len(dim)))
elif not isinstance(axis, Sequence):
axis = [axis]
if len(dim) != len(axis):
raise ValueError("lengths of dim and axis should be identical.")
for d in dim:
if d in self.dims:
raise ValueError(f"Dimension {d} already exists.")
if d in self._variables and not utils.is_scalar(self._variables[d]):
raise ValueError(
"{dim} already exists as coordinate or"
" variable name.".format(dim=d)
)
variables: Dict[Hashable, Variable] = {}
coord_names = self._coord_names.copy()
# If dim is a dict, then ensure that the values are either integers
# or iterables.
for k, v in dim.items():
if hasattr(v, "__iter__"):
# If the value for the new dimension is an iterable, then
# save the coordinates to the variables dict, and set the
# value within the dim dict to the length of the iterable
# for later use.
variables[k] = xr.IndexVariable((k,), v)
coord_names.add(k)
dim[k] = variables[k].size
elif isinstance(v, int):
pass # Do nothing if the dimensions value is just an int
else:
raise TypeError(
"The value of new dimension {k} must be "
"an iterable or an int".format(k=k)
)
for k, v in self._variables.items():
if k not in dim:
if k in coord_names: # Do not change coordinates
variables[k] = v
else:
result_ndim = len(v.dims) + len(axis)
for a in axis:
if a < -result_ndim or result_ndim - 1 < a:
raise IndexError(
f"Axis {a} of variable {k} is out of bounds of the "
f"expanded dimension size {result_ndim}"
)
axis_pos = [a if a >= 0 else result_ndim + a for a in axis]
if len(axis_pos) != len(set(axis_pos)):
raise ValueError("axis should not contain duplicate values")
# We need to sort them to make sure `axis` equals to the
# axis positions of the result array.
zip_axis_dim = sorted(zip(axis_pos, dim.items()))
all_dims = list(zip(v.dims, v.shape))
for d, c in zip_axis_dim:
all_dims.insert(d, c)
variables[k] = v.set_dims(dict(all_dims))
else:
# If dims includes a label of a non-dimension coordinate,
# it will be promoted to a 1D coordinate with a single value.
variables[k] = v.set_dims(k).to_index_variable()
new_dims = self._dims.copy()
new_dims.update(dim)
return self._replace_vars_and_dims(
variables, dims=new_dims, coord_names=coord_names
)
def set_index(
self,
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
append: bool = False,
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
) -> "Dataset":
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, "set_index")
variables, coord_names = merge_indexes(
indexes, self._variables, self._coord_names, append=append
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reset_index(
self,
dims_or_levels: Union[Hashable, Sequence[Hashable]],
drop: bool = False,
) -> "Dataset":
variables, coord_names = split_indexes(
dims_or_levels,
self._variables,
self._coord_names,
cast(Mapping[Hashable, Hashable], self._level_coords),
drop=drop,
)
return self._replace_vars_and_dims(variables, coord_names=coord_names)
def reorder_levels(
self,
dim_order: Mapping[Hashable, Sequence[int]] = None,
**dim_order_kwargs: Sequence[int],
) -> "Dataset":
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs, "reorder_levels")
variables = self._variables.copy()
indexes = dict(self.indexes)
for dim, order in dim_order.items():
coord = self._variables[dim]
index = self.indexes[dim]
if not isinstance(index, pd.MultiIndex):
raise ValueError(f"coordinate {dim} has no MultiIndex")
new_index = index.reorder_levels(order)
variables[dim] = IndexVariable(coord.dims, new_index)
indexes[dim] = new_index
return self._replace(variables, indexes=indexes)
def _stack_once(self, dims, new_dim):
if ... in dims:
dims = list(infix_dims(dims, self.dims))
variables = {}
for name, var in self.variables.items():
if name not in dims:
if any(d in var.dims for d in dims):
add_dims = [d for d in dims if d not in var.dims]
vdims = list(var.dims) + add_dims
shape = [self.dims[d] for d in vdims]
exp_var = var.set_dims(vdims, shape)
stacked_var = exp_var.stack(**{new_dim: dims})
variables[name] = stacked_var
else:
variables[name] = var.copy(deep=False)
# consider dropping levels that are unused?
levels = [self.get_index(dim) for dim in dims]
idx = utils.multiindex_from_product_levels(levels, names=dims)
variables[new_dim] = IndexVariable(new_dim, idx)
coord_names = set(self._coord_names) - set(dims) | {new_dim}
indexes = {k: v for k, v in self.indexes.items() if k not in dims}
indexes[new_dim] = idx
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def stack(
self,
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
**dimensions_kwargs: Sequence[Hashable],
) -> "Dataset":
dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, "stack")
result = self
for new_dim, dims in dimensions.items():
result = result._stack_once(dims, new_dim)
return result
def to_stacked_array(
self,
new_dim: Hashable,
sample_dims: Sequence[Hashable],
variable_dim: str = "variable",
name: Hashable = None,
) -> "DataArray":
stacking_dims = tuple(dim for dim in self.dims if dim not in sample_dims)
for variable in self:
dims = self[variable].dims
dims_include_sample_dims = set(sample_dims) <= set(dims)
if not dims_include_sample_dims:
raise ValueError(
"All variables in the dataset must contain the "
"dimensions {}.".format(dims)
)
def ensure_stackable(val):
assign_coords = {variable_dim: val.name}
for dim in stacking_dims:
if dim not in val.dims:
assign_coords[dim] = None
expand_dims = set(stacking_dims).difference(set(val.dims))
expand_dims.add(variable_dim)
# must be list for .expand_dims
expand_dims = list(expand_dims)
return (
val.assign_coords(**assign_coords)
.expand_dims(expand_dims)
.stack({new_dim: (variable_dim,) + stacking_dims})
)
# concatenate the arrays
stackable_vars = [ensure_stackable(self[key]) for key in self.data_vars]
data_array = xr.concat(stackable_vars, dim=new_dim)
# coerce the levels of the MultiIndex to have the same type as the
# input dimensions. This code is messy, so it might be better to just
# input a dummy value for the singleton dimension.
idx = data_array.indexes[new_dim]
levels = [idx.levels[0]] + [
level.astype(self[level.name].dtype) for level in idx.levels[1:]
]
new_idx = idx.set_levels(levels)
data_array[new_dim] = IndexVariable(new_dim, new_idx)
if name is not None:
data_array.name = name
return data_array
def _unstack_once(self, dim: Hashable, fill_value) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in self.variables.items():
if name != dim:
if dim in var.dims:
if isinstance(fill_value, Mapping):
fill_value_ = fill_value[name]
else:
fill_value_ = fill_value
variables[name] = var._unstack_once(
index=index, dim=dim, fill_value=fill_value_
)
else:
variables[name] = var
for name, lev in zip(index.names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(index.names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def _unstack_full_reindex(
self, dim: Hashable, fill_value, sparse: bool
) -> "Dataset":
index = self.get_index(dim)
index = remove_unused_levels_categories(index)
full_idx = pd.MultiIndex.from_product(index.levels, names=index.names)
# take a shortcut in case the MultiIndex was not modified.
if index.equals(full_idx):
obj = self
else:
obj = self._reindex(
{dim: full_idx}, copy=False, fill_value=fill_value, sparse=sparse
)
new_dim_names = index.names
new_dim_sizes = [lev.size for lev in index.levels]
variables: Dict[Hashable, Variable] = {}
indexes = {k: v for k, v in self.indexes.items() if k != dim}
for name, var in obj.variables.items():
if name != dim:
if dim in var.dims:
new_dims = dict(zip(new_dim_names, new_dim_sizes))
variables[name] = var.unstack({dim: new_dims})
else:
variables[name] = var
for name, lev in zip(new_dim_names, index.levels):
variables[name] = IndexVariable(name, lev)
indexes[name] = lev
coord_names = set(self._coord_names) - {dim} | set(new_dim_names)
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def unstack(
self,
dim: Union[Hashable, Iterable[Hashable]] = None,
fill_value: Any = dtypes.NA,
sparse: bool = False,
) -> "Dataset":
if dim is None:
dims = [
d for d in self.dims if isinstance(self.get_index(d), pd.MultiIndex)
]
else:
if isinstance(dim, str) or not isinstance(dim, Iterable):
dims = [dim]
else:
dims = list(dim)
missing_dims = [d for d in dims if d not in self.dims]
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
non_multi_dims = [
d for d in dims if not isinstance(self.get_index(d), pd.MultiIndex)
]
if non_multi_dims:
raise ValueError(
"cannot unstack dimensions that do not "
"have a MultiIndex: %s" % non_multi_dims
)
result = self.copy(deep=False)
for dim in dims:
if (
# Dask arrays don't support assignment by index, which the fast unstack
_duck_dask_array(v.data) for v in self.variables.values())
# it)
# https://github.com/pydata/sparse/issues/422
or any(
isinstance(v.data, sparse_array_type)
for v in self.variables.values()
)
or sparse
# numpy full_like only added `shape` in 1.17
or LooseVersion(np.__version__) < LooseVersion("1.17")
# Until https://github.com/pydata/xarray/pull/4751 is resolved,
# we check explicitly whether it's a numpy array. Once that is
= result._unstack_full_reindex(dim, fill_value, sparse)
else:
result = result._unstack_once(dim, fill_value)
return result
def update(self, other: "CoercibleMapping") -> "Dataset":
merge_result = dataset_update_method(self, other)
return self._replace(inplace=True, **merge_result._asdict())
def merge(
self,
other: Union["CoercibleMapping", "DataArray"],
overwrite_vars: Union[Hashable, Iterable[Hashable]] = frozenset(),
compat: str = "no_conflicts",
join: str = "outer",
fill_value: Any = dtypes.NA,
combine_attrs: str = "override",
) -> "Dataset":
other = other.to_dataset() if isinstance(other, xr.DataArray) else other
merge_result = dataset_merge_method(
self,
other,
overwrite_vars=overwrite_vars,
compat=compat,
join=join,
fill_value=fill_value,
combine_attrs=combine_attrs,
)
return self._replace(**merge_result._asdict())
def _assert_all_in_dataset(
self, names: Iterable[Hashable], virtual_okay: bool = False
) -> None:
bad_names = set(names) - set(self._variables)
if virtual_okay:
bad_names -= self.virtual_variables
if bad_names:
raise ValueError(
"One or more of the specified variables "
"cannot be found in this dataset"
)
def drop_vars(
self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
if is_scalar(names) or not isinstance(names, Iterable):
names = {names}
else:
names = set(names)
if errors == "raise":
self._assert_all_in_dataset(names)
variables = {k: v for k, v in self._variables.items() if k not in names}
coord_names = {k for k in self._coord_names if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k not in names}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
def drop(self, labels=None, dim=None, *, errors="raise", **labels_kwargs):
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if is_dict_like(labels) and not isinstance(labels, dict):
warnings.warn(
"dropping coordinates using `drop` is be deprecated; use drop_vars.",
FutureWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if labels_kwargs or isinstance(labels, dict):
if dim is not None:
raise ValueError("cannot specify dim and dict-like arguments.")
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop")
if dim is None and (is_scalar(labels) or isinstance(labels, Iterable)):
warnings.warn(
"dropping variables using `drop` will be deprecated; using drop_vars is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_vars(labels, errors=errors)
if dim is not None:
warnings.warn(
"dropping labels using list-like labels is deprecated; using "
"dict-like arguments with `drop_sel`, e.g. `ds.drop_sel(dim=[labels]).",
DeprecationWarning,
stacklevel=2,
)
return self.drop_sel({dim: labels}, errors=errors, **labels_kwargs)
warnings.warn(
"dropping labels using `drop` will be deprecated; using drop_sel is encouraged.",
PendingDeprecationWarning,
stacklevel=2,
)
return self.drop_sel(labels, errors=errors)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
labels = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
ds = self
for dim, labels_for_dim in labels.items():
# is a large numpy array
if utils.is_scalar(labels_for_dim):
labels_for_dim = [labels_for_dim]
labels_for_dim = np.asarray(labels_for_dim)
try:
index = self.get_index(dim)
except KeyError:
raise ValueError("dimension %r does not have coordinate labels" % dim)
new_index = index.drop(labels_for_dim, errors=errors)
ds = ds.loc[{dim: new_index}]
return ds
def drop_isel(self, indexers=None, **indexers_kwargs):
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "drop_isel")
ds = self
dimension_index = {}
for dim, pos_for_dim in indexers.items():
# Don't cast to set, as it would harm performance when labels
if utils.is_scalar(pos_for_dim):
pos_for_dim = [pos_for_dim]
pos_for_dim = np.asarray(pos_for_dim)
index = self.get_index(dim)
new_index = index.delete(pos_for_dim)
dimension_index[dim] = new_index
ds = ds.loc[dimension_index]
return ds
def drop_dims(
self, drop_dims: Union[Hashable, Iterable[Hashable]], *, errors: str = "raise"
) -> "Dataset":
if errors not in ["raise", "ignore"]:
raise ValueError('errors must be either "raise" or "ignore"')
if isinstance(drop_dims, str) or not isinstance(drop_dims, Iterable):
drop_dims = {drop_dims}
else:
drop_dims = set(drop_dims)
if errors == "raise":
missing_dims = drop_dims - set(self.dims)
if missing_dims:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dims
)
drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}
return self.drop_vars(drop_vars)
def transpose(self, *dims: Hashable) -> "Dataset":
if dims:
if set(dims) ^ set(self.dims) and ... not in dims:
raise ValueError(
"arguments to transpose (%s) must be "
"permuted dataset dimensions (%s)" % (dims, tuple(self.dims))
)
ds = self.copy()
for name, var in self._variables.items():
var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))
ds._variables[name] = var.transpose(*var_dims)
return ds
def dropna(
self,
dim: Hashable,
how: str = "any",
thresh: int = None,
subset: Iterable[Hashable] = None,
):
# depending on the order of the supplied axes.
if dim not in self.dims:
raise ValueError("%s must be a single dataset dimension" % dim)
if subset is None:
subset = iter(self.data_vars)
count = np.zeros(self.dims[dim], dtype=np.int64)
size = np.int_(0) # for type checking
for k in subset:
array = self._variables[k]
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += np.asarray(array.count(dims)) # type: ignore[attr-defined]
size += np.prod([self.dims[d] for d in dims])
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == size
elif how == "all":
mask = count > 0
elif how is not None:
raise ValueError("invalid how option: %s" % how)
else:
raise TypeError("must specify how or thresh")
return self.isel({dim: mask})
def fillna(self, value: Any) -> "Dataset":
if utils.is_dict_like(value):
value_keys = getattr(value, "data_vars", value).keys()
if not set(value_keys) <= set(self.data_vars.keys()):
raise ValueError(
"all variables in the argument to `fillna` "
"must be contained in the original dataset"
)
out = ops.fillna(self, value)
return out
def interpolate_na(
self,
dim: Hashable = None,
method: str = "linear",
limit: int = None,
use_coordinate: Union[bool, Hashable] = True,
max_gap: Union[
int, float, str, pd.Timedelta, np.timedelta64, datetime.timedelta
] = None,
**kwargs: Any,
) -> "Dataset":
from .missing import _apply_over_vars_with_dim, interp_na
new = _apply_over_vars_with_dim(
interp_na,
self,
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
**kwargs,
)
return new
def ffill(self, dim: Hashable, limit: int = None) -> "Dataset":
from .missing import _apply_over_vars_with_dim, ffill
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
return new
def bfill(self, dim: Hashable, limit: int = None) -> "Dataset":
from .missing import _apply_over_vars_with_dim, bfill
new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit)
return new
def combine_first(self, other: "Dataset") -> "Dataset":
out = ops.fillna(self, other, join="outer", dataset_join="outer")
return out
def reduce(
self,
func: Callable,
dim: Union[Hashable, Iterable[Hashable]] = None,
keep_attrs: bool = None,
keepdims: bool = False,
numeric_only: bool = False,
**kwargs: Any,
) -> "Dataset":
if "axis" in kwargs:
raise ValueError(
"passing 'axis' to Dataset reduce methods is ambiguous."
" Please use 'dim' instead."
)
if dim is None or dim is ...:
dims = set(self.dims)
elif isinstance(dim, str) or not isinstance(dim, Iterable):
dims = {dim}
else:
dims = set(dim)
missing_dimensions = [d for d in dims if d not in self.dims]
if missing_dimensions:
raise ValueError(
"Dataset does not contain the dimensions: %s" % missing_dimensions
)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables: Dict[Hashable, Variable] = {}
for name, var in self._variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if name in self.coords:
if not reduce_dims:
variables[name] = var
else:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or (var.dtype == np.bool_)
):
if len(reduce_dims) == 1:
# unpack dimensions for the benefit of functions
# like np.argmin which can't handle tuple arguments
(reduce_dims,) = reduce_dims
elif len(reduce_dims) == var.ndim:
reduce_dims = None
variables[name] = var.reduce(
func,
dim=reduce_dims,
keep_attrs=keep_attrs,
keepdims=keepdims,
**kwargs,
)
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
attrs = self.attrs if keep_attrs else None
return self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
def map(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
variables = {
k: maybe_wrap_array(v, func(v, *args, **kwargs))
for k, v in self.data_vars.items()
}
if keep_attrs:
for k, v in variables.items():
v._copy_attrs_from(self.data_vars[k])
attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
def apply(
self,
func: Callable,
keep_attrs: bool = None,
args: Iterable[Any] = (),
**kwargs: Any,
) -> "Dataset":
warnings.warn(
"Dataset.apply may be deprecated in the future. Using Dataset.map is encouraged",
PendingDeprecationWarning,
stacklevel=2,
)
return self.map(func, keep_attrs, args, **kwargs)
def assign(
self, variables: Mapping[Hashable, Any] = None, **variables_kwargs: Hashable
) -> "Dataset":
variables = either_dict_or_kwargs(variables, variables_kwargs, "assign")
data = self.copy()
results = data._calc_assign_results(variables)
data.update(results)
return data
def to_array(self, dim="variable", name=None):
from .dataarray import DataArray
data_vars = [self.variables[k] for k in self.data_vars]
broadcast_vars = broadcast_variables(*data_vars)
data = duck_array_ops.stack([b.data for b in broadcast_vars], axis=0)
coords = dict(self.coords)
coords[dim] = list(self.data_vars)
indexes = propagate_indexes(self._indexes)
dims = (dim,) + broadcast_vars[0].dims
return DataArray(
data, coords, dims, attrs=self.attrs, name=name, indexes=indexes
)
def _normalize_dim_order(
self, dim_order: List[Hashable] = None
) -> Dict[Hashable, int]:
if dim_order is None:
dim_order = list(self.dims)
elif set(dim_order) != set(self.dims):
raise ValueError(
"dim_order {} does not match the set of dimensions of this "
"Dataset: {}".format(dim_order, list(self.dims))
)
ordered_dims = {k: self.dims[k] for k in dim_order}
return ordered_dims
def _to_dataframe(self, ordered_dims: Mapping[Hashable, int]):
columns = [k for k in self.variables if k not in self.dims]
data = [
self._variables[k].set_dims(ordered_dims).values.reshape(-1)
for k in columns
]
index = self.coords.to_index([*ordered_dims])
return pd.DataFrame(dict(zip(columns, data)), index=index)
def to_dataframe(self, dim_order: List[Hashable] = None) -> pd.DataFrame:
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
return self._to_dataframe(ordered_dims=ordered_dims)
def _set_sparse_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
from sparse import COO
if isinstance(idx, pd.MultiIndex):
coords = np.stack([np.asarray(code) for code in idx.codes], axis=0)
is_sorted = idx.is_lexsorted()
shape = tuple(lev.size for lev in idx.levels)
else:
coords = np.arange(idx.size).reshape(1, -1)
is_sorted = True
shape = (idx.size,)
for name, values in arrays:
# special case the rare exceptions (e.g., dtype=int without a
# MultiIndex).
dtype, fill_value = dtypes.maybe_promote(values.dtype)
values = np.asarray(values, dtype=dtype)
data = COO(
coords,
values,
shape,
has_duplicates=False,
sorted=is_sorted,
fill_value=fill_value,
)
self[name] = (dims, data)
def _set_numpy_data_from_dataframe(
self, idx: pd.Index, arrays: List[Tuple[Hashable, np.ndarray]], dims: tuple
) -> None:
if not isinstance(idx, pd.MultiIndex):
for name, values in arrays:
self[name] = (dims, values)
return
# NB: similar, more general logic, now exists in
# variable.unstack_once; we could consider combining them at some
# point.
shape = tuple(lev.size for lev in idx.levels)
indexer = tuple(idx.codes)
# We already verified that the MultiIndex has all unique values, so
# there are missing values if and only if the size of output arrays is
# larger that the index.
missing_values = np.prod(shape) > idx.shape[0]
for name, values in arrays:
# NumPy indexing is much faster than using DataFrame.reindex() to
# fill in missing values:
# https://stackoverflow.com/a/35049899/809705
if missing_values:
dtype, fill_value = dtypes.maybe_promote(values.dtype)
data = np.full(shape, fill_value, dtype)
else:
# If there are no missing values, keep the existing dtype
# instead of promoting to support NA, e.g., keep integer
# columns as integers.
# TODO: consider removing this special case, which doesn't
data = np.zeros(shape, values.dtype)
data[indexer] = values
self[name] = (dims, data)
@classmethod
def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> "Dataset":
if not dataframe.columns.is_unique:
raise ValueError("cannot convert DataFrame with non-unique columns")
idx = remove_unused_levels_categories(dataframe.index)
if isinstance(idx, pd.MultiIndex) and not idx.is_unique:
raise ValueError(
"cannot convert a DataFrame with a non-unique MultiIndex into xarray"
)
# TODO: allow users to control how this casting happens, e.g., by
# forwarding arguments to pandas.Series.to_numpy?
arrays = [(k, np.asarray(v)) for k, v in dataframe.items()]
obj = cls()
if isinstance(idx, pd.MultiIndex):
dims = tuple(
name if name is not None else "level_%i" % n
for n, name in enumerate(idx.names)
)
for dim, lev in zip(dims, idx.levels):
obj[dim] = (dim, lev)
else:
index_name = idx.name if idx.name is not None else "index"
dims = (index_name,)
obj[index_name] = (dims, idx)
if sparse:
obj._set_sparse_data_from_dataframe(idx, arrays, dims)
else:
obj._set_numpy_data_from_dataframe(idx, arrays, dims)
return obj
def to_dask_dataframe(self, dim_order=None, set_index=False):
import dask.array as da
import dask.dataframe as dd
ordered_dims = self._normalize_dim_order(dim_order=dim_order)
columns = list(ordered_dims)
columns.extend(k for k in self.coords if k not in self.dims)
columns.extend(self.data_vars)
series_list = []
for name in columns:
try:
var = self.variables[name]
except KeyError:
# dimension without a matching coordinate
size = self.dims[name]
data = da.arange(size, chunks=size, dtype=np.int64)
var = Variable((name,), data)
# IndexVariable objects have a dummy .chunk() method
if isinstance(var, IndexVariable):
var = var.to_base_variable()
dask_array = var.set_dims(ordered_dims).chunk(self.chunks).data
series = dd.from_array(dask_array.reshape(-1), columns=[name])
series_list.append(series)
df = dd.concat(series_list, axis=1)
if set_index:
dim_order = [*ordered_dims]
if len(dim_order) == 1:
(dim,) = dim_order
df = df.set_index(dim)
else:
# triggers an error about multi-indexes, even if only one
# dimension is passed
df = df.set_index(dim_order)
return df
def to_dict(self, data=True):
d = {
"coords": {},
"attrs": decode_numpy_dict_values(self.attrs),
"dims": dict(self.dims),
"data_vars": {},
}
for k in self.coords:
d["coords"].update({k: self[k].variable.to_dict(data=data)})
for k in self.data_vars:
d["data_vars"].update({k: self[k].variable.to_dict(data=data)})
return d
@classmethod
def from_dict(cls, d):
if not {"coords", "data_vars"}.issubset(set(d)):
variables = d.items()
else:
import itertools
variables = itertools.chain(
d.get("coords", {}).items(), d.get("data_vars", {}).items()
)
try:
variable_dict = {
k: (v["dims"], v["data"], v.get("attrs")) for k, v in variables
}
except KeyError as e:
raise ValueError(
"cannot convert dict without the key "
"'{dims_data}'".format(dims_data=str(e.args[0]))
)
obj = cls(variable_dict)
# what if coords aren't dims?
coords = set(d.get("coords", {})) - set(d.get("dims", {}))
obj = obj.set_coords(coords)
obj.attrs.update(d.get("attrs", {}))
return obj
@staticmethod
def _unary_op(f):
@functools.wraps(f)
def func(self, *args, **kwargs):
variables = {}
keep_attrs = kwargs.pop("keep_attrs", None)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
for k, v in self._variables.items():
if k in self._coord_names:
variables[k] = v
else:
variables[k] = f(v, *args, **kwargs)
if keep_attrs:
variables[k].attrs = v._attrs
attrs = self._attrs if keep_attrs else None
return self._replace_with_new_dims(variables, attrs=attrs)
return func
@staticmethod
def _binary_op(f, reflexive=False, join=None):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
return NotImplemented
align_type = OPTIONS["arithmetic_join"] if join is None else join
if isinstance(other, (DataArray, Dataset)):
self, other = align(self, other, join=align_type, copy=False)
g = f if not reflexive else lambda x, y: f(y, x)
ds = self._calculate_binary_op(g, other, join=align_type)
return ds
return func
@staticmethod
def _inplace_binary_op(f):
@functools.wraps(f)
def func(self, other):
from .dataarray import DataArray
if isinstance(other, groupby.GroupBy):
raise TypeError(
"in-place operations between a Dataset and "
"a grouped object are not permitted"
)
# arithmetic -- this lets us automatically align things
if isinstance(other, (DataArray, Dataset)):
other = other.reindex_like(self, copy=False)
g = ops.inplace_to_noninplace_op(f)
ds = self._calculate_binary_op(g, other, inplace=True)
self._replace_with_new_dims(
ds._variables,
ds._coord_names,
attrs=ds._attrs,
indexes=ds._indexes,
inplace=True,
)
return self
return func
def _calculate_binary_op(self, f, other, join="inner", inplace=False):
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
if inplace and set(lhs_data_vars) != set(rhs_data_vars):
raise ValueError(
"datasets must have the same data variables "
"for in-place arithmetic operations: %s, %s"
% (list(lhs_data_vars), list(rhs_data_vars))
)
dest_vars = {}
for k in lhs_data_vars:
if k in rhs_data_vars:
dest_vars[k] = f(lhs_vars[k], rhs_vars[k])
elif join in ["left", "outer"]:
dest_vars[k] = f(lhs_vars[k], np.nan)
for k in rhs_data_vars:
if k not in dest_vars and join in ["right", "outer"]:
dest_vars[k] = f(rhs_vars[k], np.nan)
return dest_vars
if utils.is_dict_like(other) and not isinstance(other, Dataset):
# can't use our shortcut of doing the binary operation with
new_data_vars = apply_over_both(
self.data_vars, other, self.data_vars, other
)
return Dataset(new_data_vars)
other_coords = getattr(other, "coords", None)
ds = self.coords.merge(other_coords)
if isinstance(other, Dataset):
new_vars = apply_over_both(
self.data_vars, other.data_vars, self.variables, other.variables
)
else:
other_variable = getattr(other, "variable", other)
new_vars = {k: f(self.variables[k], other_variable) for k in self.data_vars}
ds._variables.update(new_vars)
ds._dims = calculate_dimensions(ds._variables)
return ds
def _copy_attrs_from(self, other):
self.attrs = other.attrs
for v in other.variables:
if v in self.variables:
self.variables[v].attrs = other.variables[v].attrs
def diff(self, dim, n=1, label="upper"):
if n == 0:
return self
if n < 0:
raise ValueError(f"order `n` must be non-negative but got {n}")
kwargs_start = {dim: slice(None, -1)}
kwargs_end = {dim: slice(1, None)}
if label == "upper":
kwargs_new = kwargs_end
elif label == "lower":
kwargs_new = kwargs_start
else:
raise ValueError("The 'label' argument has to be either 'upper' or 'lower'")
variables = {}
for name, var in self.variables.items():
if dim in var.dims:
if name in self.data_vars:
variables[name] = var.isel(**kwargs_end) - var.isel(**kwargs_start)
else:
variables[name] = var.isel(**kwargs_new)
else:
variables[name] = var
indexes = dict(self.indexes)
if dim in indexes:
indexes[dim] = indexes[dim][kwargs_new[dim]]
difference = self._replace_with_new_dims(variables, indexes=indexes)
if n > 1:
return difference.diff(dim, n - 1)
else:
return difference
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "shift")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
fill_value_ = (
fill_value.get(name, dtypes.NA)
if isinstance(fill_value, dict)
else fill_value
)
var_shifts = {k: v for k, v in shifts.items() if k in var.dims}
variables[name] = var.shift(fill_value=fill_value_, shifts=var_shifts)
else:
variables[name] = var
return self._replace(variables)
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "roll")
invalid = [k for k in shifts if k not in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
if roll_coords is None:
warnings.warn(
"roll_coords will be set to False in the future."
" Explicitly set roll_coords to silence warning.",
FutureWarning,
stacklevel=2,
)
roll_coords = True
unrolled_vars = () if roll_coords else self.coords
variables = {}
for k, v in self.variables.items():
if k not in unrolled_vars:
variables[k] = v.roll(
**{k: s for k, s in shifts.items() if k in v.dims}
)
else:
variables[k] = v
if roll_coords:
indexes = {}
for k, v in self.indexes.items():
(dim,) = self.variables[k].dims
if dim in shifts:
indexes[k] = roll_index(v, shifts[dim])
else:
indexes[k] = v
else:
indexes = dict(self.indexes)
return self._replace(variables, indexes=indexes)
def sortby(self, variables, ascending=True):
from .dataarray import DataArray
if not isinstance(variables, list):
variables = [variables]
else:
variables = variables
variables = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *variables, join="left")
aligned_self = aligned_vars[0]
aligned_other_vars = aligned_vars[1:]
vars_by_dim = defaultdict(list)
for data_array in aligned_other_vars:
if data_array.ndim != 1:
raise ValueError("Input DataArray is not 1-D.")
(key,) = data_array.dims
vars_by_dim[key].append(data_array)
indices = {}
for key, arrays in vars_by_dim.items():
order = np.lexsort(tuple(reversed(arrays)))
indices[key] = order if ascending else order[::-1]
return aligned_self.isel(**indices)
def quantile(
self,
q,
dim=None,
interpolation="linear",
numeric_only=False,
keep_attrs=None,
skipna=True,
):
if isinstance(dim, str):
dims = {dim}
elif dim in [None, ...]:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty(
[d for d in dims if d not in self.dims],
"Dataset does not contain the dimensions: %s",
)
q = np.asarray(q, dtype=np.float64)
variables = {}
for name, var in self.variables.items():
reduce_dims = [d for d in var.dims if d in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (
not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_
):
if len(reduce_dims) == var.ndim:
reduce_dims = None
variables[name] = var.quantile(
q,
dim=reduce_dims,
interpolation=interpolation,
keep_attrs=keep_attrs,
skipna=skipna,
)
else:
variables[name] = var
coord_names = {k for k in self.coords if k in variables}
indexes = {k: v for k, v in self.indexes.items() if k in variables}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
new = self._replace_with_new_dims(
variables, coord_names=coord_names, attrs=attrs, indexes=indexes
)
return new.assign_coords(quantile=q)
def rank(self, dim, pct=False, keep_attrs=None):
if dim not in self.dims:
raise ValueError("Dataset does not contain the dimension: %s" % dim)
variables = {}
for name, var in self.variables.items():
if name in self.data_vars:
if dim in var.dims:
variables[name] = var.rank(dim, pct=pct)
else:
variables[name] = var
coord_names = set(self.coords)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=False)
attrs = self.attrs if keep_attrs else None
return self._replace(variables, coord_names, attrs=attrs)
def differentiate(self, coord, edge_order=1, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s"
coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)
variables = {}
for k, v in self.variables.items():
if k in self.data_vars and dim in v.dims and k not in self.coords:
if _contains_datetime_like_objects(v):
v = v._to_numeric(datetime_unit=datetime_unit)
grad = duck_array_ops.gradient(
v.data, coord_var, edge_order=edge_order, axis=v.get_axis_num(dim)
)
variables[k] = Variable(v.dims, grad)
else:
variables[k] = v
return self._replace(variables)
def integrate(
self, coord: Union[Hashable, Sequence[Hashable]], datetime_unit: str = None
) -> "Dataset":
if not isinstance(coord, (list, tuple)):
coord = (coord,)
result = self
for c in coord:
result = result._integrate_one(c, datetime_unit=datetime_unit)
return result
def _integrate_one(self, coord, datetime_unit=None):
from .variable import Variable
if coord not in self.variables and coord not in self.dims:
raise ValueError(f"Coordinate {coord} does not exist.")
coord_var = self[coord].variable
if coord_var.ndim != 1:
raise ValueError(
"Coordinate {} must be 1 dimensional but is {}"
" dimensional".format(coord, coord_var.ndim)
)
dim = coord_var.dims[0]
if _contains_datetime_like_objects(coord_var):
if coord_var.dtype.kind in "mM" and datetime_unit is None:
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = "s"
coord_var = coord_var._replace(
data=datetime_to_numeric(coord_var.data, datetime_unit=datetime_unit)
)
variables = {}
coord_names = set()
for k, v in self.variables.items():
if k in self.coords:
if dim not in v.dims:
variables[k] = v
coord_names.add(k)
else:
if k in self.data_vars and dim in v.dims:
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
integ = duck_array_ops.trapz(
v.data, coord_var.data, axis=v.get_axis_num(dim)
)
v_dims = list(v.dims)
v_dims.remove(dim)
variables[k] = Variable(v_dims, integ)
else:
variables[k] = v
indexes = {k: v for k, v in self.indexes.items() if k in variables}
return self._replace_with_new_dims(
variables, coord_names=coord_names, indexes=indexes
)
@property
def real(self):
return self.map(lambda x: x.real, keep_attrs=True)
@property
def imag(self):
return self.map(lambda x: x.imag, keep_attrs=True)
plot = utils.UncachedAccessor(_Dataset_PlotMethods)
def filter_by_attrs(self, **kwargs):
selection = []
for var_name, variable in self.variables.items():
has_value_flag = False
for attr_name, pattern in kwargs.items():
attr_value = variable.attrs.get(attr_name)
if (callable(pattern) and pattern(attr_value)) or attr_value == pattern:
has_value_flag = True
else:
has_value_flag = False
break
if has_value_flag is True:
selection.append(var_name)
return self[selection]
def unify_chunks(self) -> "Dataset":
try:
self.chunks
except ValueError:
pass
else:
return self.copy()
import dask.array
ds = self.copy()
dims_pos_map = {dim: index for index, dim in enumerate(ds.dims)}
dask_array_names = []
dask_unify_args = []
for name, variable in ds.variables.items():
if isinstance(variable.data, dask.array.Array):
dims_tuple = [dims_pos_map[dim] for dim in variable.dims]
dask_array_names.append(name)
dask_unify_args.append(variable.data)
dask_unify_args.append(dims_tuple)
_, rechunked_arrays = dask.array.core.unify_chunks(*dask_unify_args)
for name, new_array in zip(dask_array_names, rechunked_arrays):
ds.variables[name]._data = new_array
return ds
def map_blocks(
self,
func: "Callable[..., T_DSorDA]",
args: Sequence[Any] = (),
kwargs: Mapping[str, Any] = None,
template: Union["DataArray", "Dataset"] = None,
) -> "T_DSorDA":
from .parallel import map_blocks
return map_blocks(func, self, args, kwargs, template)
def polyfit(
self,
dim: Hashable,
deg: int,
skipna: bool = None,
rcond: float = None,
w: Union[Hashable, Any] = None,
full: bool = False,
cov: Union[bool, str] = False,
):
variables = {}
skipna_da = skipna
x = get_clean_interp_index(self, dim, strict=False)
xname = "{}_".format(self[dim].name)
order = int(deg) + 1
lhs = np.vander(x, order)
if rcond is None:
rcond = (
x.shape[0] * np.core.finfo(x.dtype).eps # type: ignore[attr-defined]
)
# Weights:
if w is not None:
if isinstance(w, Hashable):
w = self.coords[w]
w = np.asarray(w)
if w.ndim != 1:
raise TypeError("Expected a 1-d array for weights.")
if w.shape[0] != lhs.shape[0]:
raise TypeError("Expected w and {} to have the same length".format(dim))
lhs *= w[:, np.newaxis]
# Scaling
scale = np.sqrt((lhs * lhs).sum(axis=0))
lhs /= scale
degree_dim = utils.get_temp_dimname(self.dims, "degree")
rank = np.linalg.matrix_rank(lhs)
if full:
rank = xr.DataArray(rank, name=xname + "matrix_rank")
variables[rank.name] = rank
sing = np.linalg.svd(lhs, compute_uv=False)
sing = xr.DataArray(
sing,
dims=(degree_dim,),
coords={degree_dim: np.arange(rank - 1, -1, -1)},
name=xname + "singular_values",
)
variables[sing.name] = sing
for name, da in self.data_vars.items():
if dim not in da.dims:
continue
if is_duck_dask_array(da.data) and (
rank != order or full or skipna is None
):
# Current algorithm with dask and skipna=False neither supports
# deficient ranks nor does it output the "full" info (issue dask/dask#6516)
skipna_da = True
elif skipna is None:
skipna_da = bool(np.any(da.isnull()))
dims_to_stack = [dimname for dimname in da.dims if dimname != dim]
stacked_coords: Dict[Hashable, DataArray] = {}
if dims_to_stack:
stacked_dim = utils.get_temp_dimname(dims_to_stack, "stacked")
rhs = da.transpose(dim, *dims_to_stack).stack(
{stacked_dim: dims_to_stack}
)
stacked_coords = {stacked_dim: rhs[stacked_dim]}
scale_da = scale[:, np.newaxis]
else:
rhs = da
scale_da = scale
if w is not None:
rhs *= w[:, np.newaxis]
with warnings.catch_warnings():
if full: # Copy np.polyfit behavior
warnings.simplefilter("ignore", np.RankWarning)
else: # Raise only once per variable
warnings.simplefilter("once", np.RankWarning)
coeffs, residuals = duck_array_ops.least_squares(
lhs, rhs.data, rcond=rcond, skipna=skipna_da
)
if isinstance(name, str):
name = "{}_".format(name)
else:
# Thus a ReprObject => polyfit was called on a DataArray
name = ""
coeffs = xr.DataArray(
coeffs / scale_da,
dims=[degree_dim] + list(stacked_coords.keys()),
coords={degree_dim: np.arange(order)[::-1], **stacked_coords},
name=name + "polyfit_coefficients",
)
if dims_to_stack:
coeffs = coeffs.unstack(stacked_dim)
variables[coeffs.name] = coeffs
if full or (cov is True):
residuals = xr.DataArray(
residuals if dims_to_stack else residuals.squeeze(),
dims=list(stacked_coords.keys()),
coords=stacked_coords,
name=name + "polyfit_residuals",
)
if dims_to_stack:
residuals = residuals.unstack(stacked_dim)
variables[residuals.name] = residuals
if cov:
Vbase = np.linalg.inv(np.dot(lhs.T, lhs))
Vbase /= np.outer(scale, scale)
if cov == "unscaled":
fac = 1
else:
if x.shape[0] <= order:
raise ValueError(
"The number of data points must exceed order to scale the covariance matrix."
)
fac = residuals / (x.shape[0] - order)
covariance = xr.DataArray(Vbase, dims=("cov_i", "cov_j")) * fac
variables[name + "polyfit_covariance"] = covariance
return Dataset(data_vars=variables, attrs=self.attrs.copy())
def pad(
self,
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
mode: str = "constant",
stat_length: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
constant_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
end_values: Union[
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
] = None,
reflect_type: str = None,
**pad_width_kwargs: Any,
) -> "Dataset":
pad_width = either_dict_or_kwargs(pad_width, pad_width_kwargs, "pad")
if mode in ("edge", "reflect", "symmetric", "wrap"):
coord_pad_mode = mode
coord_pad_options = {
"stat_length": stat_length,
"constant_values": constant_values,
"end_values": end_values,
"reflect_type": reflect_type,
}
else:
coord_pad_mode = "constant"
coord_pad_options = {}
variables = {}
for name, var in self.variables.items():
var_pad_width = {k: v for k, v in pad_width.items() if k in var.dims}
if not var_pad_width:
variables[name] = var
elif name in self.data_vars:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=mode,
stat_length=stat_length,
constant_values=constant_values,
end_values=end_values,
reflect_type=reflect_type,
)
else:
variables[name] = var.pad(
pad_width=var_pad_width,
mode=coord_pad_mode,
**coord_pad_options, # type: ignore[arg-type]
)
return self._replace_vars_and_dims(variables)
def idxmin(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
return self.map(
methodcaller(
"idxmin",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def idxmax(
self,
dim: Hashable = None,
skipna: bool = None,
fill_value: Any = dtypes.NA,
keep_attrs: bool = None,
) -> "Dataset":
return self.map(
methodcaller(
"idxmax",
dim=dim,
skipna=skipna,
fill_value=fill_value,
keep_attrs=keep_attrs,
)
)
def argmin(self, dim=None, **kwargs):
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
argmin_func = getattr(duck_array_ops, "argmin")
return self.reduce(argmin_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def argmax(self, dim=None, **kwargs):
if dim is None:
warnings.warn(
"Once the behaviour of DataArray.argmin() and Variable.argmin() without "
"dim changes to return a dict of indices of each dimension, for "
"consistency it will be an error to call Dataset.argmin() with no argument,"
"since we don't return a dict of Datasets.",
DeprecationWarning,
stacklevel=2,
)
if (
dim is None
or (not isinstance(dim, Sequence) and dim is not ...)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
argmax_func = getattr(duck_array_ops, "argmax")
return self.reduce(argmax_func, dim=dim, **kwargs)
else:
raise ValueError(
"When dim is a sequence or ..., DataArray.argmin() returns a dict. "
"dicts cannot be contained in a Dataset, so cannot call "
"Dataset.argmin() with a sequence or ... for dim"
)
def query(
self,
queries: Mapping[Hashable, Any] = None,
parser: str = "pandas",
engine: str = None,
missing_dims: str = "raise",
**queries_kwargs: Any,
) -> "Dataset":
# allow queries to be given either as a dict or as kwargs
queries = either_dict_or_kwargs(queries, queries_kwargs, "query")
# check queries
for dim, expr in queries.items():
if not isinstance(expr, str):
msg = f"expr for dim {dim} must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
# evaluate the queries to create the indexers
indexers = {
dim: pd.eval(expr, resolvers=[self], parser=parser, engine=engine)
for dim, expr in queries.items()
}
# apply the selection
return self.isel(indexers, missing_dims=missing_dims)
def curvefit(
self,
coords: Union[Union[str, "DataArray"], Iterable[Union[str, "DataArray"]]],
func: Callable[..., Any],
reduce_dims: Union[Hashable, Iterable[Hashable]] = None,
skipna: bool = True,
p0: Dict[str, Any] = None,
bounds: Dict[str, Any] = None,
param_names: Sequence[str] = None,
kwargs: Dict[str, Any] = None,
):
from scipy.optimize import curve_fit
if p0 is None:
p0 = {}
if bounds is None:
bounds = {}
if kwargs is None:
kwargs = {}
if not reduce_dims:
reduce_dims_ = []
elif isinstance(reduce_dims, str) or not isinstance(reduce_dims, Iterable):
reduce_dims_ = [reduce_dims]
else:
reduce_dims_ = list(reduce_dims)
if (
isinstance(coords, str)
or isinstance(coords, xr.DataArray)
or not isinstance(coords, Iterable)
):
coords = [coords]
coords_ = [self[coord] if isinstance(coord, str) else coord for coord in coords]
# Determine whether any coords are dims on self
for coord in coords_:
reduce_dims_ += [c for c in self.dims if coord.equals(self[c])]
reduce_dims_ = list(set(reduce_dims_))
preserved_dims = list(set(self.dims) - set(reduce_dims_))
if not reduce_dims_:
raise ValueError(
"No arguments to `coords` were identified as a dimension on the calling "
"object, and no dims were supplied to `reduce_dims`. This would result "
"in fitting on scalar data."
)
# Broadcast all coords with each other
coords_ = xr.broadcast(*coords_)
coords_ = [
coord.broadcast_like(self, exclude=preserved_dims) for coord in coords_
]
params, func_args = _get_func_args(func, param_names)
param_defaults, bounds_defaults = _initialize_curvefit_params(
params, p0, bounds, func_args
)
n_params = len(params)
kwargs.setdefault("p0", [param_defaults[p] for p in params])
kwargs.setdefault(
"bounds",
[
[bounds_defaults[p][0] for p in params],
[bounds_defaults[p][1] for p in params],
],
)
def _wrapper(Y, *coords_, **kwargs):
# Wrap curve_fit with raveled coordinates and pointwise NaN handling
x = np.vstack([c.ravel() for c in coords_])
y = Y.ravel()
if skipna:
mask = np.all([np.any(~np.isnan(x), axis=0), ~np.isnan(y)], axis=0)
x = x[:, mask]
y = y[mask]
if not len(y):
popt = np.full([n_params], np.nan)
pcov = np.full([n_params, n_params], np.nan)
return popt, pcov
x = np.squeeze(x)
popt, pcov = curve_fit(func, x, y, **kwargs)
return popt, pcov
result = xr.Dataset()
for name, da in self.data_vars.items():
if name is xr.core.dataarray._THIS_ARRAY:
name = ""
else:
name = f"{str(name)}_"
popt, pcov = xr.apply_ufunc(
_wrapper,
da,
*coords_,
vectorize=True,
dask="parallelized",
input_core_dims=[reduce_dims_ for d in range(len(coords_) + 1)],
output_core_dims=[["param"], ["cov_i", "cov_j"]],
dask_gufunc_kwargs={
"output_sizes": {
"param": n_params,
"cov_i": n_params,
"cov_j": n_params,
},
},
output_dtypes=(np.float64, np.float64),
exclude_dims=set(reduce_dims_),
kwargs=kwargs,
)
result[name + "curvefit_coefficients"] = popt
result[name + "curvefit_covariance"] = pcov
result = result.assign_coords(
{"param": params, "cov_i": params, "cov_j": params}
)
result.attrs = self.attrs.copy()
return result
ops.inject_all_ops_and_reduce_methods(Dataset, array_only=False)
| true | true |
f72c3934b0697c32c252b1d2e817e435900da1e3 | 441 | py | Python | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 48 | 2018-10-24T14:52:06.000Z | 2022-03-25T21:14:50.000Z | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 2,034 | 2018-10-31T20:59:16.000Z | 2022-03-22T21:38:03.000Z | metaci/plan/migrations/0018_planrepository_active.py | sfdc-qbranch/MetaCI | 78ac0d2bccd2db381998321ebd71029dd5d9ab39 | [
"BSD-3-Clause"
] | 27 | 2018-12-24T18:16:23.000Z | 2021-12-15T17:57:27.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-09-13 23:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("plan", "0016_auto_20180904_1457")]
operations = [
migrations.AddField(
model_name="planrepository",
name="active",
field=models.BooleanField(default=True),
)
]
| 23.210526 | 56 | 0.643991 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("plan", "0016_auto_20180904_1457")]
operations = [
migrations.AddField(
model_name="planrepository",
name="active",
field=models.BooleanField(default=True),
)
]
| true | true |
f72c39bc796a19aeb0f55dc3bee1129236c8a00e | 111,695 | py | Python | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 2 | 2016-11-14T15:08:53.000Z | 2016-11-20T09:25:30.000Z | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 3 | 2021-03-31T19:53:24.000Z | 2021-12-13T20:46:19.000Z | salt/grains/core.py | MeAndTheFirefly/salt | 77fc3ec3ee25c1b769cc66ddee09067d18080844 | [
"Apache-2.0"
] | 2 | 2020-11-04T06:32:02.000Z | 2020-11-06T11:01:18.000Z | # -*- coding: utf-8 -*-
"""
The static grains, these are the core, or built in grains.
When grains are loaded they are not loaded in the same way that modules are
loaded, grain functions are detected and executed, the functions MUST
return a dict which will be applied to the main grains dict. This module
will always be executed first, so that any grains loaded here in the core
module can be overwritten just by returning dict keys with the same value
as those returned here
"""
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import hashlib
import locale
import logging
import os
import platform
import re
import socket
import sys
import time
import uuid
from errno import EACCES, EPERM
import distro
import salt.exceptions
import salt.log
# Solve the Chicken and egg problem where grains need to run before any
# of the modules are loaded and are generally available for any usage.
import salt.modules.cmdmod
import salt.modules.network
import salt.modules.smbios
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
from salt.utils.network import _get_interfaces
# rewrite distro.linux_distribution to allow best=True kwarg in version(), needed to get the minor version numbers in CentOS
def _linux_distribution():
return (
distro.id(),
distro.version(best=True),
distro.codename(),
)
try:
import dateutil.tz # pylint: disable=import-error
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
# attempt to import the python wmi module
# the Windows minion uses WMI for some of its grains
try:
import wmi # pylint: disable=import-error
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
"Unable to import Python wmi module, some core grains " "will be missing"
)
__proxyenabled__ = ["*"]
__FQDN__ = None
__salt__ = {
"cmd.run": salt.modules.cmdmod._run_quiet,
"cmd.retcode": salt.modules.cmdmod._retcode_quiet,
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"smbios.records": salt.modules.smbios.records,
"smbios.get": salt.modules.smbios.get,
"network.fqdns": salt.modules.network.fqdns,
}
HAS_UNAME = hasattr(os, "uname")
# Possible value for h_errno defined in netdb.h
HOST_NOT_FOUND = 1
NO_DATA = 4
def _windows_cpudata():
"""
Return some CPU information on Windows minions
"""
# Provides:
# num_cpus
# cpu_model
grains = {}
if "NUMBER_OF_PROCESSORS" in os.environ:
# Cast to int so that the logic isn't broken when used as a
# conditional in templating. Also follows _linux_cpudata()
try:
grains["num_cpus"] = int(os.environ["NUMBER_OF_PROCESSORS"])
except ValueError:
grains["num_cpus"] = 1
grains["cpu_model"] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString",
).get("vdata")
return grains
def _linux_cpudata():
"""
Return some CPU information for Linux minions
"""
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = "/proc/cpuinfo"
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, "r") as _fp:
for line in _fp:
comps = line.split(":")
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == "processor":
grains["num_cpus"] = int(val) + 1
# head -2 /proc/cpuinfo
# vendor_id : IBM/S390
# # processors : 2
elif key == "# processors":
grains["num_cpus"] = int(val)
elif key == "vendor_id":
grains["cpu_model"] = val
elif key == "model name":
grains["cpu_model"] = val
elif key == "flags":
grains["cpu_flags"] = val.split()
elif key == "Features":
grains["cpu_flags"] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == "Processor":
grains["cpu_model"] = val.split("-")[0]
grains["num_cpus"] = 1
if "num_cpus" not in grains:
grains["num_cpus"] = 0
if "cpu_model" not in grains:
grains["cpu_model"] = "Unknown"
if "cpu_flags" not in grains:
grains["cpu_flags"] = []
return grains
def _linux_gpu_data():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
if __opts__.get("enable_lspci", True) is False:
return {}
if __opts__.get("enable_gpu_grains", True) is False:
return {}
lspci = salt.utils.path.which("lspci")
if not lspci:
log.debug(
"The `lspci` binary is not available on the system. GPU grains "
"will not be available."
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpu_classes = ("vga compatible controller", "3d controller", "display controller")
devs = []
try:
lspci_out = __salt__["cmd.run"]("{0} -vmm".format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append("")
for line in lspci_list:
# check for record-separating empty lines
if line == "":
if cur_dev.get("Class", "").lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r"^\w+:\s+.*", line):
key, val = line.split(":", 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug("Unexpected lspci output: '%s'", line)
if error:
log.warning(
"Error loading grains, unexpected linux_gpu_data output, "
"check that you have a valid shell configured and "
"permissions to run lspci command"
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split("[^A-Za-z0-9]", gpu["Vendor"].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = "unknown"
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({"vendor": vendor, "model": gpu["Device"]})
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _netbsd_gpu_data():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("pcictl pci0 list")
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r"[0-9:]+ ({0}) (.+) \(VGA .+\)".format(vendor), line, re.IGNORECASE
)
if vendor_match:
gpus.append(
{
"vendor": vendor_match.group(1),
"model": vendor_match.group(2),
}
)
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _osx_gpudata():
"""
num_gpus: int
gpus:
- vendor: nvidia|amd|ati|...
model: string
"""
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("system_profiler SPDisplaysDataType")
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(": ")
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(" ")
vendor = vendor.lower()
gpus.append({"vendor": vendor, "model": model})
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _bsd_cpudata(osdata):
"""
Return CPU information for BSD-like systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which("sysctl")
arch = salt.utils.path.which("arch")
cmds = {}
if sysctl:
cmds.update(
{
"num_cpus": "{0} -n hw.ncpu".format(sysctl),
"cpuarch": "{0} -n hw.machine".format(sysctl),
"cpu_model": "{0} -n hw.model".format(sysctl),
}
)
if arch and osdata["kernel"] == "OpenBSD":
cmds["cpuarch"] = "{0} -s".format(arch)
if osdata["kernel"] == "Darwin":
cmds["cpu_model"] = "{0} -n machdep.cpu.brand_string".format(sysctl)
cmds["cpu_flags"] = "{0} -n machdep.cpu.features".format(sysctl)
grains = dict([(k, __salt__["cmd.run"](v)) for k, v in six.iteritems(cmds)])
if "cpu_flags" in grains and isinstance(grains["cpu_flags"], six.string_types):
grains["cpu_flags"] = grains["cpu_flags"].split(" ")
if osdata["kernel"] == "NetBSD":
grains["cpu_flags"] = []
for line in __salt__["cmd.run"]("cpuctl identify 0").splitlines():
cpu_match = re.match(r"cpu[0-9]:\ features[0-9]?\ .+<(.+)>", line)
if cpu_match:
flag = cpu_match.group(1).split(",")
grains["cpu_flags"].extend(flag)
if osdata["kernel"] == "FreeBSD" and os.path.isfile("/var/run/dmesg.boot"):
grains["cpu_flags"] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen("/var/run/dmesg.boot", "r") as _fp:
cpu_here = False
for line in _fp:
if line.startswith("CPU: "):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(" "):
break # game over
if "Features" in line:
start = line.find("<")
end = line.find(">")
if start > 0 and end > 0:
flag = line[start + 1 : end].split(",")
grains["cpu_flags"].extend(flag)
try:
grains["num_cpus"] = int(grains["num_cpus"])
except ValueError:
grains["num_cpus"] = 1
return grains
def _sunos_cpudata():
"""
Return the CPU information for Solaris-like systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains["cpu_flags"] = []
grains["cpuarch"] = __salt__["cmd.run"]("isainfo -k")
psrinfo = "/usr/sbin/psrinfo 2>/dev/null"
grains["num_cpus"] = len(
__salt__["cmd.run"](psrinfo, python_shell=True).splitlines()
)
kstat_info = "kstat -p cpu_info:*:*:brand"
for line in __salt__["cmd.run"](kstat_info).splitlines():
match = re.match(r"(\w+:\d+:\w+\d+:\w+)\s+(.+)", line)
if match:
grains["cpu_model"] = match.group(2)
isainfo = "isainfo -n -v"
for line in __salt__["cmd.run"](isainfo).splitlines():
match = re.match(r"^\s+(.+)", line)
if match:
cpu_flags = match.group(1).split()
grains["cpu_flags"].extend(cpu_flags)
return grains
def _aix_cpudata():
"""
Return CPU information for AIX systems
"""
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("cpuarch", r"(?im)^\s*Processor\s+Type:\s+(\S+)"),
("cpu_flags", r"(?im)^\s*Processor\s+Version:\s+(\S+)"),
("cpu_model", r"(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)"),
("num_cpus", r"(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def _linux_memdata():
"""
Return the memory information for Linux-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
meminfo = "/proc/meminfo"
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, "r") as ifile:
for line in ifile:
comps = line.rstrip("\n").split(":")
if not len(comps) > 1:
continue
if comps[0].strip() == "MemTotal":
# Use floor division to force output to be an integer
grains["mem_total"] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == "SwapTotal":
# Use floor division to force output to be an integer
grains["swap_total"] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
"""
Return the memory information for BSD-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.memsize".format(sysctl))
swap_total = (
__salt__["cmd.run"]("{0} -n vm.swapusage".format(sysctl))
.split()[2]
.replace(",", ".")
)
if swap_total.endswith("K"):
_power = 2 ** 10
elif swap_total.endswith("M"):
_power = 2 ** 20
elif swap_total.endswith("G"):
_power = 2 ** 30
swap_total = float(swap_total[:-1]) * _power
grains["mem_total"] = int(mem) // 1024 // 1024
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
"""
Return the memory information for BSD-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.physmem".format(sysctl))
if osdata["kernel"] == "NetBSD" and mem.startswith("-"):
mem = __salt__["cmd.run"]("{0} -n hw.physmem64".format(sysctl))
grains["mem_total"] = int(mem) // 1024 // 1024
if osdata["kernel"] in ["OpenBSD", "NetBSD"]:
swapctl = salt.utils.path.which("swapctl")
swap_data = __salt__["cmd.run"]("{0} -sk".format(swapctl))
if swap_data == "no swap devices configured":
swap_total = 0
else:
swap_total = swap_data.split(" ")[1]
else:
swap_total = __salt__["cmd.run"]("{0} -n vm.swap_total".format(sysctl))
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
"""
Return the memory information for SunOS-like systems
"""
grains = {"mem_total": 0, "swap_total": 0}
prtconf = "/usr/sbin/prtconf 2>/dev/null"
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = line.split(" ")
if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
grains["mem_total"] = int(comps[2].strip())
swap_cmd = salt.utils.path.which("swap")
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
return grains
def _aix_memdata():
"""
Return the memory information for AIX systems
"""
grains = {"mem_total": 0, "swap_total": 0}
prtconf = salt.utils.path.which("prtconf")
if prtconf:
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(" ") if x]
if len(comps) > 2 and "Memory" in comps[0] and "Size" in comps[1]:
grains["mem_total"] = int(comps[2])
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
swap_cmd = salt.utils.path.which("swap")
if swap_cmd:
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
else:
log.error("The 'swap' binary was not found in $PATH.")
return grains
def _windows_memdata():
"""
Return the memory information for Windows systems
"""
grains = {"mem_total": 0}
# get the Total Physical memory as reported by msinfo32
tot_bytes = win32api.GlobalMemoryStatusEx()["TotalPhys"]
# return memory info in gigabytes
grains["mem_total"] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
"""
Gather information about the system memory
"""
# Provides:
# mem_total
# swap_total, for supported systems.
grains = {"mem_total": 0}
if osdata["kernel"] == "Linux":
grains.update(_linux_memdata())
elif osdata["kernel"] in ("FreeBSD", "OpenBSD", "NetBSD"):
grains.update(_bsd_memdata(osdata))
elif osdata["kernel"] == "Darwin":
grains.update(_osx_memdata())
elif osdata["kernel"] == "SunOS":
grains.update(_sunos_memdata())
elif osdata["kernel"] == "AIX":
grains.update(_aix_memdata())
elif osdata["kernel"] == "Windows" and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
"""
Parse the output of lsattr -El sys0 for os_uuid
"""
grains = {}
cmd = salt.utils.path.which("lsattr")
if cmd:
data = __salt__["cmd.run"]("{0} -El sys0".format(cmd)) + os.linesep
uuid_regexes = [re.compile(r"(?im)^\s*os_uuid\s+(\S+)\s+(.*)")]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["machine_id"] = res.group(1).strip()
break
else:
log.error("The 'lsattr' binary was not found in $PATH.")
return grains
def _windows_virtual(osdata):
"""
Returns what type of virtual hardware is under the hood, kvm or physical
"""
# Provides:
# virtual
# virtual_subtype
grains = dict()
if osdata["kernel"] != "Windows":
return grains
grains["virtual"] = osdata.get("virtual", "physical")
# It is possible that the 'manufacturer' and/or 'productname' grains
# exist but have a value of None.
manufacturer = osdata.get("manufacturer", "")
if manufacturer is None:
manufacturer = ""
productname = osdata.get("productname", "")
if productname is None:
productname = ""
if "QEMU" in manufacturer:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Bochs" in manufacturer:
grains["virtual"] = "kvm"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "oVirt" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "oVirt"
# Red Hat Enterprise Virtualization
elif "RHEV Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
# Product Name: VirtualBox
elif "VirtualBox" in productname:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware Virtual Platform" in productname:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif "Microsoft" in manufacturer and "Virtual Machine" in productname:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in manufacturer:
grains["virtual"] = "Parallels"
# Apache CloudStack
elif "CloudStack KVM Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "cloudstack"
return grains
def _virtual(osdata):
"""
Returns what type of virtual hardware is under the hood, kvm or physical
"""
# This is going to be a monster, if you are running a vm you can test this
# grain with please submit patches!
# Provides:
# virtual
# virtual_subtype
grains = {"virtual": osdata.get("virtual", "physical")}
# Skip the below loop on platforms which have none of the desired cmds
# This is a temporary measure until we can write proper virtual hardware
# detection.
skip_cmds = ("AIX",)
# list of commands to be executed to determine the 'virtual' grain
_cmds = ["systemd-detect-virt", "virt-what", "dmidecode"]
# test first for virt-what, which covers most of the desired functionality
# on most platforms
if not salt.utils.platform.is_windows() and osdata["kernel"] not in skip_cmds:
if salt.utils.path.which("virt-what"):
_cmds = ["virt-what"]
# Check if enable_lspci is True or False
if __opts__.get("enable_lspci", True) is True:
# /proc/bus/pci does not exists, lspci will fail
if os.path.exists("/proc/bus/pci"):
_cmds += ["lspci"]
# Add additional last resort commands
if osdata["kernel"] in skip_cmds:
_cmds = ()
# Quick backout for BrandZ (Solaris LX Branded zones)
# Don't waste time trying other commands to detect the virtual grain
if (
HAS_UNAME
and osdata["kernel"] == "Linux"
and "BrandZ virtual linux" in os.uname()
):
grains["virtual"] = "zone"
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata["kernel"] == "Darwin":
command = "system_profiler"
args = ["SPDisplaysDataType"]
elif osdata["kernel"] == "SunOS":
virtinfo = salt.utils.path.which("virtinfo")
if virtinfo:
try:
ret = __salt__["cmd.run_all"](virtinfo)
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret["stdout"].endswith("not supported"):
command = "prtdiag"
else:
command = "virtinfo"
args.append("-c current list -H -o name")
else:
command = "prtdiag"
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = "{0} {1}".format(cmd, " ".join(args))
try:
ret = __salt__["cmd.run_all"](cmd)
if ret["retcode"] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if (
salt.utils.platform.is_windows()
or "systemd-detect-virt" in cmd
or "prtdiag" in cmd
):
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret["stdout"]
if command == "system_profiler":
macoutput = output.lower()
if "0x1ab8" in macoutput:
grains["virtual"] = "Parallels"
if "parallels" in macoutput:
grains["virtual"] = "Parallels"
if "vmware" in macoutput:
grains["virtual"] = "VMware"
if "0x15ad" in macoutput:
grains["virtual"] = "VMware"
if "virtualbox" in macoutput:
grains["virtual"] = "VirtualBox"
# Break out of the loop so the next log message is not issued
break
elif command == "systemd-detect-virt":
if output in (
"qemu",
"kvm",
"oracle",
"xen",
"bochs",
"chroot",
"uml",
"systemd-nspawn",
):
grains["virtual"] = output
break
elif "vmware" in output:
grains["virtual"] = "VMware"
break
elif "microsoft" in output:
grains["virtual"] = "VirtualPC"
break
elif "lxc" in output:
grains["virtual"] = "LXC"
break
elif "systemd-nspawn" in output:
grains["virtual"] = "LXC"
break
elif command == "virt-what":
for line in output.splitlines():
if line in ("kvm", "qemu", "uml", "xen", "lxc"):
grains["virtual"] = line
break
elif "vmware" in line:
grains["virtual"] = "VMware"
break
elif "parallels" in line:
grains["virtual"] = "Parallels"
break
elif "hyperv" in line:
grains["virtual"] = "HyperV"
break
elif command == "dmidecode":
# Product Name: VirtualBox
if "Vendor: QEMU" in output:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Manufacturer: QEMU" in output:
grains["virtual"] = "kvm"
if "Vendor: Bochs" in output:
grains["virtual"] = "kvm"
if "Manufacturer: Bochs" in output:
grains["virtual"] = "kvm"
if "BHYVE" in output:
grains["virtual"] = "bhyve"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "Manufacturer: oVirt" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
# Red Hat Enterprise Virtualization
elif "Product Name: RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware" in output:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ": Microsoft" in output and "Virtual Machine" in output:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in output:
grains["virtual"] = "Parallels"
elif "Manufacturer: Google" in output:
grains["virtual"] = "kvm"
# Proxmox KVM
elif "Vendor: SeaBIOS" in output:
grains["virtual"] = "kvm"
# Break out of the loop, lspci parsing is not necessary
break
elif command == "lspci":
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if "vmware" in model:
grains["virtual"] = "VMware"
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "virtio" in model:
grains["virtual"] = "kvm"
# Break out of the loop so the next log message is not issued
break
elif command == "prtdiag":
model = output.lower().split("\n")[0]
if "vmware" in model:
grains["virtual"] = "VMware"
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "joyent smartdc hvm" in model:
grains["virtual"] = "kvm"
break
elif command == "virtinfo":
if output == "logical-domain":
grains["virtual"] = "LDOM"
roles = []
for role in ("control", "io", "root", "service"):
subtype_cmd = "{0} -c current get -H -o value {1}-role".format(
command, role
)
ret = __salt__["cmd.run"]("{0}".format(subtype_cmd))
if ret == "true":
roles.append(role)
if roles:
grains["virtual_subtype"] = roles
elif output == "non-global-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "non-global"
elif output == "kernel-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "kernel"
elif output == "vmware":
grains["virtual"] = "VMware"
break
choices = ("Linux", "HP-UX")
isdir = os.path.isdir
sysctl = salt.utils.path.which("sysctl")
if osdata["kernel"] in choices:
if os.path.isdir("/proc"):
try:
self_root = os.stat("/")
init_root = os.stat("/proc/1/root/.")
if self_root != init_root:
grains["virtual_subtype"] = "chroot"
except (IOError, OSError):
pass
if isdir("/proc/vz"):
if os.path.isfile("/proc/vz/version"):
grains["virtual"] = "openvzhn"
elif os.path.isfile("/proc/vz/veinfo"):
grains["virtual"] = "openvzve"
# a posteriori, it's expected for these to have failed:
failed_commands.discard("lspci")
failed_commands.discard("dmidecode")
# Provide additional detection for OpenVZ
if os.path.isfile("/proc/self/status"):
with salt.utils.files.fopen("/proc/self/status") as status_file:
vz_re = re.compile(r"^envID:\s+(\d+)$")
for line in status_file:
vz_match = vz_re.match(line.rstrip("\n"))
if vz_match and int(vz_match.groups()[0]) != 0:
grains["virtual"] = "openvzve"
elif vz_match and int(vz_match.groups()[0]) == 0:
grains["virtual"] = "openvzhn"
if isdir("/proc/sys/xen") or isdir("/sys/bus/xen") or isdir("/proc/xen"):
if os.path.isfile("/proc/xen/xsd_kva"):
# Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
# Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
grains["virtual_subtype"] = "Xen Dom0"
else:
if osdata.get("productname", "") == "HVM domU":
# Requires dmidecode!
grains["virtual_subtype"] = "Xen HVM DomU"
elif os.path.isfile("/proc/xen/capabilities") and os.access(
"/proc/xen/capabilities", os.R_OK
):
with salt.utils.files.fopen("/proc/xen/capabilities") as fhr:
if "control_d" not in fhr.read():
# Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
grains["virtual_subtype"] = "Xen PV DomU"
else:
# Shouldn't get to this, but just in case
grains["virtual_subtype"] = "Xen Dom0"
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir("/sys/bus/xen"):
if "xen:" in __salt__["cmd.run"]("dmesg").lower():
grains["virtual_subtype"] = "Xen PV DomU"
elif os.path.isfile("/sys/bus/xen/drivers/xenconsole"):
# An actual DomU will have the xenconsole driver
grains["virtual_subtype"] = "Xen PV DomU"
# If a Dom0 or DomU was detected, obviously this is xen
if "dom" in grains.get("virtual_subtype", "").lower():
grains["virtual"] = "xen"
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile("/proc/1/cgroup"):
try:
with salt.utils.files.fopen("/proc/1/cgroup", "r") as fhr:
fhr_contents = fhr.read()
if ":/lxc/" in fhr_contents:
grains["virtual"] = "container"
grains["virtual_subtype"] = "LXC"
elif ":/kubepods/" in fhr_contents:
grains["virtual_subtype"] = "kubernetes"
elif ":/libpod_parent/" in fhr_contents:
grains["virtual_subtype"] = "libpod"
else:
if any(
x in fhr_contents
for x in (":/system.slice/docker", ":/docker/", ":/docker-ce/")
):
grains["virtual"] = "container"
grains["virtual_subtype"] = "Docker"
except IOError:
pass
if os.path.isfile("/proc/cpuinfo"):
with salt.utils.files.fopen("/proc/cpuinfo", "r") as fhr:
if "QEMU Virtual CPU" in fhr.read():
grains["virtual"] = "kvm"
if os.path.isfile("/sys/devices/virtual/dmi/id/product_name"):
try:
with salt.utils.files.fopen(
"/sys/devices/virtual/dmi/id/product_name", "r"
) as fhr:
output = salt.utils.stringutils.to_unicode(
fhr.read(), errors="replace"
)
if "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
elif "RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "oVirt Node" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
elif "Google" in output:
grains["virtual"] = "gce"
elif "BHYVE" in output:
grains["virtual"] = "bhyve"
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except IOError:
pass
elif osdata["kernel"] == "FreeBSD":
kenv = salt.utils.path.which("kenv")
if kenv:
product = __salt__["cmd.run"]("{0} smbios.system.product".format(kenv))
maker = __salt__["cmd.run"]("{0} smbios.system.maker".format(kenv))
if product.startswith("VMware"):
grains["virtual"] = "VMware"
if product.startswith("VirtualBox"):
grains["virtual"] = "VirtualBox"
if maker.startswith("Xen"):
grains["virtual_subtype"] = "{0} {1}".format(maker, product)
grains["virtual"] = "xen"
if maker.startswith("Microsoft") and product.startswith("Virtual"):
grains["virtual"] = "VirtualPC"
if maker.startswith("OpenStack"):
grains["virtual"] = "OpenStack"
if maker.startswith("Bochs"):
grains["virtual"] = "kvm"
if sysctl:
hv_vendor = __salt__["cmd.run"]("{0} -n hw.hv_vendor".format(sysctl))
model = __salt__["cmd.run"]("{0} -n hw.model".format(sysctl))
jail = __salt__["cmd.run"]("{0} -n security.jail.jailed".format(sysctl))
if "bhyve" in hv_vendor:
grains["virtual"] = "bhyve"
elif "QEMU Virtual CPU" in model:
grains["virtual"] = "kvm"
if jail == "1":
grains["virtual_subtype"] = "jail"
elif osdata["kernel"] == "OpenBSD":
if "manufacturer" in osdata:
if osdata["manufacturer"] in ["QEMU", "Red Hat", "Joyent"]:
grains["virtual"] = "kvm"
if osdata["manufacturer"] == "OpenBSD":
grains["virtual"] = "vmm"
elif osdata["kernel"] == "NetBSD":
if sysctl:
if "QEMU Virtual CPU" in __salt__["cmd.run"](
"{0} -n machdep.cpu_brand".format(sysctl)
):
grains["virtual"] = "kvm"
elif "invalid" not in __salt__["cmd.run"](
"{0} -n machdep.xen.suspend".format(sysctl)
):
grains["virtual"] = "Xen PV DomU"
elif "VMware" in __salt__["cmd.run"](
"{0} -n machdep.dmi.system-vendor".format(sysctl)
):
grains["virtual"] = "VMware"
# NetBSD has Xen dom0 support
elif (
__salt__["cmd.run"]("{0} -n machdep.idle-mechanism".format(sysctl))
== "xen"
):
if os.path.isfile("/var/run/xenconsoled.pid"):
grains["virtual_subtype"] = "Xen Dom0"
elif osdata["kernel"] == "SunOS":
# we did not get any data from virtinfo or prtdiag
# check the zonename here as fallback
zonename = salt.utils.path.which("zonename")
if zonename:
zone = __salt__["cmd.run"]("{0}".format(zonename))
if zone != "global":
grains["virtual"] = "zone"
# last ditch efford to check the brand identifier
elif os.path.isdir("/.SUNWnative"):
grains["virtual"] = "zone"
# If we have a virtual_subtype, we're virtual, but maybe we couldn't
# figure out what specific virtual type we were?
if grains.get("virtual_subtype") and grains["virtual"] == "physical":
grains["virtual"] = "virtual"
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
"cannot execute it. Grains output might not be "
"accurate.",
command,
)
return grains
def _virtual_hv(osdata):
"""
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
"""
grains = {}
# Bail early if we're not running on Xen
try:
if "xen" not in osdata["virtual"]:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ("major", "minor", "extra"):
with salt.utils.files.fopen(
"/sys/hypervisor/version/{}".format(fn), "r"
) as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains["virtual_hv_version"] = "{}.{}{}".format(
version["major"], version["minor"], version["extra"]
)
grains["virtual_hv_version_info"] = [
version["major"],
version["minor"],
version["extra"],
]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {
0: "writable_page_tables",
1: "writable_descriptor_tables",
2: "auto_translated_physmap",
3: "supervisor_mode_kernel",
4: "pae_pgdir_above_4gb",
5: "mmu_pt_update_preserve_ad",
7: "gnttab_map_avail_bits",
8: "hvm_callback_vector",
9: "hvm_safe_pvclock",
10: "hvm_pirqs",
11: "dom0",
12: "grant_map_identity",
13: "memory_op_vnode_supported",
14: "ARM_SMCCC_supported",
}
try:
with salt.utils.files.fopen("/sys/hypervisor/properties/features", "r") as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains["virtual_hv_features"] = features
grains["virtual_hv_features_list"] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
"""
Return the ps grain
"""
grains = {}
bsd_choices = ("FreeBSD", "NetBSD", "OpenBSD", "MacOS")
if osdata["os"] in bsd_choices:
grains["ps"] = "ps auxwww"
elif osdata["os_family"] == "Solaris":
grains["ps"] = "/usr/ucb/ps auxwww"
elif osdata["os"] == "Windows":
grains["ps"] = "tasklist.exe"
elif osdata.get("virtual", "") == "openvzhn":
grains["ps"] = (
'ps -fH -p $(grep -l "^envID:[[:space:]]*0\\$" '
'/proc/[0-9]*/status | sed -e "s=/proc/\\([0-9]*\\)/.*=\\1=") '
"| awk '{ $7=\"\"; print }'"
)
elif osdata["os_family"] == "AIX":
grains["ps"] = "/usr/bin/ps auxww"
elif osdata["os_family"] == "NILinuxRT":
grains["ps"] = "ps -o user,pid,ppid,tty,time,comm"
else:
grains["ps"] = "ps -efHww"
return grains
def _clean_value(key, val):
"""
Clean out well-known bogus values.
If it isn't clean (for example has value 'None'), return None.
Otherwise, return the original value.
NOTE: This logic also exists in the smbios module. This function is
for use when not using smbios to retrieve the value.
"""
if val is None or not val or re.match("none", val, flags=re.IGNORECASE):
return None
elif "uuid" in key:
# Try each version (1-5) of RFC4122 to check if it's actually a UUID
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace("HW %s value %s is an invalid UUID", key, val.replace("\n", " "))
return None
elif re.search("serial|part|version", key):
# 'To be filled by O.E.M.
# 'Not applicable' etc.
# 'Not specified' etc.
# 0000000, 1234567 etc.
# begone!
if (
re.match(r"^[0]+$", val)
or re.match(r"[0]?1234567[8]?[9]?[0]?", val)
or re.search(
r"sernum|part[_-]?number|specified|filled|applicable",
val,
flags=re.IGNORECASE,
)
):
return None
elif re.search("asset|manufacturer", key):
# AssetTag0. Manufacturer04. Begone.
if re.search(
r"manufacturer|to be filled|available|asset|^no(ne|t)",
val,
flags=re.IGNORECASE,
):
return None
else:
# map unspecified, undefined, unknown & whatever to None
if re.search(r"to be filled", val, flags=re.IGNORECASE) or re.search(
r"un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)",
val,
flags=re.IGNORECASE,
):
return None
return val
def _windows_os_release_grain(caption, product_type):
"""
helper function for getting the osrelease grain
:return:
"""
# This creates the osrelease grain based on the Windows Operating
# System Product Name. As long as Microsoft maintains a similar format
# this should be future proof
version = "Unknown"
release = ""
if "Server" in caption:
# Edge case here to handle MS Product that doesn't contain a year
if re.match(r"^Microsoft Hyper-V Server$", caption):
version = "2019"
else:
for item in caption.split(" "):
# If it's all digits, then it's version
if re.match(r"\d+", item):
version = item
# If it starts with R and then numbers, it's the release
# ie: R2
if re.match(r"^R\d+$", item):
release = item
os_release = "{0}Server{1}".format(version, release)
else:
for item in caption.split(" "):
# If it's a number, decimal number, Thin or Vista, then it's the
# version
if re.match(r"^(\d+(\.\d+)?)|Thin|Vista|XP$", item):
version = item
os_release = version
# If the version is still Unknown, revert back to the old way of getting
# the os_release
# https://github.com/saltstack/salt/issues/52339
if os_release in ["Unknown"]:
os_release = platform.release()
server = {
"Vista": "2008Server",
"7": "2008ServerR2",
"8": "2012Server",
"8.1": "2012ServerR2",
"10": "2016Server",
}
# Starting with Python 2.7.12 and 3.5.2 the `platform.uname()`
# function started reporting the Desktop version instead of the
# Server version on # Server versions of Windows, so we need to look
# those up. So, if you find a Server Platform that's a key in the
# server dictionary, then lookup the actual Server Release.
# (Product Type 1 is Desktop, Everything else is Server)
if product_type > 1 and os_release in server:
os_release = server[os_release]
return os_release
def _windows_platform_data():
"""
Use the platform module for as much as we can.
"""
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {"product": None, "serial": None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard["product"] = motherboardinfo.Product
motherboard["serial"] = motherboardinfo.SerialNumber
except IndexError:
log.debug("Motherboard info not available on this system")
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info["ServicePackMajor"] > 0:
service_pack = "".join(["SP", six.text_type(info["ServicePackMajor"])])
os_release = _windows_os_release_grain(
caption=osinfo.Caption, product_type=osinfo.ProductType
)
grains = {
"kernelrelease": _clean_value("kernelrelease", osinfo.Version),
"kernelversion": _clean_value("kernelversion", kernel_version),
"osversion": _clean_value("osversion", osinfo.Version),
"osrelease": _clean_value("osrelease", os_release),
"osservicepack": _clean_value("osservicepack", service_pack),
"osmanufacturer": _clean_value("osmanufacturer", osinfo.Manufacturer),
"manufacturer": _clean_value("manufacturer", systeminfo.Manufacturer),
"productname": _clean_value("productname", systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
"biosversion": _clean_value("biosversion", biosinfo.Name.strip()),
"serialnumber": _clean_value("serialnumber", biosinfo.SerialNumber),
"osfullname": _clean_value("osfullname", osinfo.Caption),
"timezone": _clean_value("timezone", timeinfo.Description),
"windowsdomain": _clean_value("windowsdomain", net_info["Domain"]),
"windowsdomaintype": _clean_value(
"windowsdomaintype", net_info["DomainType"]
),
"motherboard": {
"productname": _clean_value(
"motherboard.productname", motherboard["product"]
),
"serialnumber": _clean_value(
"motherboard.serialnumber", motherboard["serial"]
),
},
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if "VRTUAL" in biosinfo.Version: # (not a typo)
grains["virtual"] = "HyperV"
elif "A M I" in biosinfo.Version:
grains["virtual"] = "VirtualPC"
elif "VMware" in systeminfo.Model:
grains["virtual"] = "VMware"
elif "VirtualBox" in systeminfo.Model:
grains["virtual"] = "VirtualBox"
elif "Xen" in biosinfo.Version:
grains["virtual"] = "Xen"
if "HVM domU" in systeminfo.Model:
grains["virtual_subtype"] = "HVM domU"
elif "OpenStack" in systeminfo.Model:
grains["virtual"] = "OpenStack"
elif "AMAZON" in biosinfo.Version:
grains["virtual"] = "EC2"
return grains
def _osx_platform_data():
"""
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
"""
cmd = "system_profiler SPHardwareDataType"
hardware = __salt__["cmd.run"](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(": ")
if field_name.strip() == "Model Name":
key = "model_name"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = "boot_rom_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = "smc_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = "system_serialnumber"
grains[key] = _clean_value(key, field_val)
return grains
def id_():
"""
Return the id
"""
return {"id": __opts__.get("id", "")}
_REPLACE_LINUX_RE = re.compile(r"\W(?:gnu/)?linux", re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
"redhatente": "RedHat",
"gentoobase": "Gentoo",
"archarm": "Arch ARM",
"arch": "Arch",
"debian": "Debian",
"raspbian": "Raspbian",
"fedoraremi": "Fedora",
"chapeau": "Chapeau",
"korora": "Korora",
"amazonami": "Amazon",
"alt": "ALT",
"enterprise": "OEL",
"oracleserv": "OEL",
"cloudserve": "CloudLinux",
"cloudlinux": "CloudLinux",
"pidora": "Fedora",
"scientific": "ScientificLinux",
"synology": "Synology",
"nilrt": "NILinuxRT",
"poky": "Poky",
"manjaro": "Manjaro",
"manjarolin": "Manjaro",
"univention": "Univention",
"antergos": "Antergos",
"sles": "SUSE",
"void": "Void",
"slesexpand": "RES",
"linuxmint": "Mint",
"neon": "KDE neon",
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
"Ubuntu": "Debian",
"Fedora": "RedHat",
"Chapeau": "RedHat",
"Korora": "RedHat",
"FedBerry": "RedHat",
"CentOS": "RedHat",
"GoOSe": "RedHat",
"Scientific": "RedHat",
"Amazon": "RedHat",
"CloudLinux": "RedHat",
"OVS": "RedHat",
"OEL": "RedHat",
"XCP": "RedHat",
"XCP-ng": "RedHat",
"XenServer": "RedHat",
"RES": "RedHat",
"Sangoma": "RedHat",
"Mandrake": "Mandriva",
"ESXi": "VMware",
"Mint": "Debian",
"VMwareESX": "VMware",
"Bluewhite64": "Bluewhite",
"Slamd64": "Slackware",
"SLES": "Suse",
"SUSE Enterprise Server": "Suse",
"SUSE Enterprise Server": "Suse",
"SLED": "Suse",
"openSUSE": "Suse",
"SUSE": "Suse",
"openSUSE Leap": "Suse",
"openSUSE Tumbleweed": "Suse",
"SLES_SAP": "Suse",
"Solaris": "Solaris",
"SmartOS": "Solaris",
"OmniOS": "Solaris",
"OpenIndiana Development": "Solaris",
"OpenIndiana": "Solaris",
"OpenSolaris Development": "Solaris",
"OpenSolaris": "Solaris",
"Oracle Solaris": "Solaris",
"Arch ARM": "Arch",
"Manjaro": "Arch",
"Antergos": "Arch",
"ALT": "RedHat",
"Trisquel": "Debian",
"GCEL": "Debian",
"Linaro": "Debian",
"elementary OS": "Debian",
"elementary": "Debian",
"Univention": "Debian",
"ScientificLinux": "RedHat",
"Raspbian": "Debian",
"Devuan": "Debian",
"antiX": "Debian",
"Kali": "Debian",
"neon": "Debian",
"Cumulus": "Debian",
"Deepin": "Debian",
"NILinuxRT": "NILinuxRT",
"KDE neon": "Debian",
"Void": "Void",
"IDMS": "Debian",
"Funtoo": "Gentoo",
"AIX": "AIX",
"TurnKey": "Debian",
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile(
(
"^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:'|\")?"
"([\\w\\s\\.\\-_]+)(?:'|\")?"
)
)
def _linux_bin_exists(binary):
"""
Does a binary exist in linux (depends on which, type, or whereis)
"""
for search_cmd in ("which", "type -ap"):
try:
return __salt__["cmd.retcode"]("{0} {1}".format(search_cmd, binary)) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return (
len(
__salt__["cmd.run_all"]("whereis -b {0}".format(binary))[
"stdout"
].split()
)
> 1
)
except salt.exceptions.CommandExecutionError:
return False
def _parse_lsb_release():
ret = {}
try:
log.trace("Attempting to parse /etc/lsb-release")
with salt.utils.files.fopen("/etc/lsb-release") as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip("\n")).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret["lsb_{0}".format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace("Failed to parse /etc/lsb-release: %s", exc)
return ret
def _parse_os_release(*os_release_files):
"""
Parse os-release and return a parameter dictionary
See http://www.freedesktop.org/software/systemd/man/os-release.html
for specification of the file format.
"""
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile("^([\\w]+)=(?:'|\")?(.*?)(?:'|\")?$")
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r"\1", match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
"""
Parse CPE_NAME data from the os-release
Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe
Note: cpe:2.3:part:vendor:product:version:update:edition:lang:sw_edition:target_sw:target_hw:other
however some OS's do not have the full 13 elements, for example:
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
:param cpe:
:return:
"""
part = {
"o": "operating system",
"h": "hardware",
"a": "application",
}
ret = {}
cpe = (cpe or "").split(":")
if len(cpe) > 4 and cpe[0] == "cpe":
if cpe[1].startswith("/"): # WFN to URI
ret["vendor"], ret["product"], ret["version"] = cpe[2:5]
ret["phase"] = cpe[5] if len(cpe) > 5 else None
ret["part"] = part.get(cpe[1][1:])
elif len(cpe) == 6 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"] = [
x if x != "*" else None for x in cpe[3:6]
]
ret["phase"] = None
ret["part"] = part.get(cpe[2])
elif len(cpe) > 7 and len(cpe) <= 13 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"], ret["phase"] = [
x if x != "*" else None for x in cpe[3:7]
]
ret["part"] = part.get(cpe[2])
return ret
def os_data():
"""
Return grains pertaining to the operating system
"""
grains = {
"num_gpus": 0,
"gpus": [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(
grains["kernel"],
grains["nodename"],
grains["kernelrelease"],
grains["kernelversion"],
grains["cpuarch"],
_,
) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains["kernel"] = "proxy"
grains["kernelrelease"] = "proxy"
grains["kernelversion"] = "proxy"
grains["osrelease"] = "proxy"
grains["os"] = "proxy"
grains["os_family"] = "proxy"
grains["osfullname"] = "proxy"
elif salt.utils.platform.is_windows():
grains["os"] = "Windows"
grains["os_family"] = "Windows"
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if "Server" in grains["osrelease"]:
osrelease_info = grains["osrelease"].split("Server", 1)
osrelease_info[1] = osrelease_info[1].lstrip("R")
else:
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
grains["osfinger"] = "{os}-{ver}".format(
os=grains["os"], ver=grains["osrelease"]
)
grains["init"] = "Windows"
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists("selinuxenabled"):
log.trace("Adding selinux grains")
grains["selinux"] = {}
grains["selinux"]["enabled"] = (
__salt__["cmd.retcode"]("selinuxenabled") == 0
)
if _linux_bin_exists("getenforce"):
grains["selinux"]["enforced"] = __salt__["cmd.run"](
"getenforce"
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists("systemctl") and _linux_bin_exists("localectl"):
log.trace("Adding systemd grains")
grains["systemd"] = {}
systemd_info = __salt__["cmd.run"]("systemctl --version").splitlines()
grains["systemd"]["version"] = systemd_info[0].split()[1]
grains["systemd"]["features"] = systemd_info[1]
# Add init grain
grains["init"] = "unknown"
log.trace("Adding init grain")
try:
os.stat("/run/systemd/system")
grains["init"] = "systemd"
except (OSError, IOError):
try:
with salt.utils.files.fopen("/proc/1/cmdline") as fhr:
init_cmdline = fhr.read().replace("\x00", " ").split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning("Unable to fetch data from /proc/1/cmdline")
if init_bin is not None and init_bin.endswith("bin/init"):
supported_inits = (b"upstart", b"sysvinit", b"systemd")
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__["file_buffer_size"]
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, "rb") as fp_:
edge = b""
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode("utf-8")
grains["init"] = item
buf = b""
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
"Unable to read from init_bin (%s): %s", init_bin, exc
)
elif salt.utils.path.which("supervisord") in init_cmdline:
grains["init"] = "supervisord"
elif salt.utils.path.which("dumb-init") in init_cmdline:
# https://github.com/Yelp/dumb-init
grains["init"] = "dumb-init"
elif salt.utils.path.which("tini") in init_cmdline:
# https://github.com/krallin/tini
grains["init"] = "tini"
elif init_cmdline == ["runit"]:
grains["init"] = "runit"
elif "/sbin/my_init" in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains["init"] = "runit"
else:
log.debug(
"Could not determine init system from command line: (%s)",
" ".join(init_cmdline),
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace("Getting lsb_release distro information")
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = "lsb_{0}{1}".format(
"" if key.startswith("distrib_") else "distrib_", key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace("lsb_release python bindings not available")
grains.update(_parse_lsb_release())
if grains.get("lsb_distrib_description", "").lower().startswith("antergos"):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains["osfullname"] = "Antergos Linux"
elif "lsb_distrib_id" not in grains:
log.trace("Failed to get lsb_distrib_id, trying to parse os-release")
os_release = _parse_os_release("/etc/os-release", "/usr/lib/os-release")
if os_release:
if "NAME" in os_release:
grains["lsb_distrib_id"] = os_release["NAME"].strip()
if "VERSION_ID" in os_release:
grains["lsb_distrib_release"] = os_release["VERSION_ID"]
if "VERSION_CODENAME" in os_release:
grains["lsb_distrib_codename"] = os_release["VERSION_CODENAME"]
elif "PRETTY_NAME" in os_release:
codename = os_release["PRETTY_NAME"]
# https://github.com/saltstack/salt/issues/44108
if os_release["ID"] == "debian":
codename_match = re.search(r"\((\w+)\)$", codename)
if codename_match:
codename = codename_match.group(1)
grains["lsb_distrib_codename"] = codename
if "CPE_NAME" in os_release:
cpe = _parse_cpe_name(os_release["CPE_NAME"])
if not cpe:
log.error("Broken CPE_NAME format in /etc/os-release!")
elif cpe.get("vendor", "").lower() in ["suse", "opensuse"]:
grains["os"] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains["osfullname"] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains["osfullname"] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if (
cpe.get("version") and cpe.get("vendor") == "opensuse"
): # Keep VERSION_ID for SLES
grains["lsb_distrib_release"] = cpe["version"]
elif os.path.isfile("/etc/SuSE-release"):
log.trace("Parsing distrib info from /etc/SuSE-release")
grains["lsb_distrib_id"] = "SUSE"
version = ""
patch = ""
with salt.utils.files.fopen("/etc/SuSE-release") as fhr:
for line in fhr:
if "enterprise" in line.lower():
grains["lsb_distrib_id"] = "SLES"
grains["lsb_distrib_codename"] = re.sub(
r"\(.+\)", "", line
).strip()
elif "version" in line.lower():
version = re.sub(r"[^0-9]", "", line)
elif "patchlevel" in line.lower():
patch = re.sub(r"[^0-9]", "", line)
grains["lsb_distrib_release"] = version
if patch:
grains["lsb_distrib_release"] += "." + patch
patchstr = "SP" + patch
if (
grains["lsb_distrib_codename"]
and patchstr not in grains["lsb_distrib_codename"]
):
grains["lsb_distrib_codename"] += " " + patchstr
if not grains.get("lsb_distrib_codename"):
grains["lsb_distrib_codename"] = "n.a"
elif os.path.isfile("/etc/altlinux-release"):
log.trace("Parsing distrib info from /etc/altlinux-release")
# ALT Linux
grains["lsb_distrib_id"] = "altlinux"
with salt.utils.files.fopen("/etc/altlinux-release") as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == "ALT":
grains["lsb_distrib_release"] = comps[2]
grains["lsb_distrib_codename"] = (
comps[3].replace("(", "").replace(")", "")
)
elif os.path.isfile("/etc/centos-release"):
log.trace("Parsing distrib info from /etc/centos-release")
# CentOS Linux
grains["lsb_distrib_id"] = "CentOS"
with salt.utils.files.fopen("/etc/centos-release") as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r"\d+\.\d+")
find_codename = re.compile(r"(?<=\()(.*?)(?=\))")
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains["lsb_distrib_release"] = release.group()
if codename is not None:
grains["lsb_distrib_codename"] = codename.group()
elif os.path.isfile("/etc.defaults/VERSION") and os.path.isfile(
"/etc.defaults/synoinfo.conf"
):
grains["osfullname"] = "Synology"
log.trace(
"Parsing Synology distrib info from /etc/.defaults/VERSION"
)
with salt.utils.files.fopen("/etc.defaults/VERSION", "r") as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip("\n").split("=")
except ValueError:
continue
if key in ("majorversion", "minorversion", "buildnumber"):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
"Unable to determine Synology version info. "
"Please report this, as it is likely a bug."
)
else:
grains[
"osrelease"
] = "{majorversion}.{minorversion}-{buildnumber}".format(
**synoinfo
)
log.trace(
"Getting OS name, release, and codename from distro id, version, codename"
)
(osname, osrelease, oscodename) = [
x.strip('"').strip("'") for x in _linux_distribution()
]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if "osfullname" not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get("lsb_distrib_id", "").lower().startswith("nilrt"):
grains["osfullname"] = "nilrt"
else:
grains["osfullname"] = grains.get("lsb_distrib_id", osname).strip()
if "osrelease" not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
# This also affects Centos 8
if any(
os in grains.get("lsb_distrib_codename", "")
for os in ["CentOS Linux 7", "CentOS Linux 8"]
):
grains.pop("lsb_distrib_release", None)
grains["osrelease"] = grains.get("lsb_distrib_release", osrelease).strip()
grains["oscodename"] = (
grains.get("lsb_distrib_codename", "").strip() or oscodename
)
if "Red Hat" in grains["oscodename"]:
grains["oscodename"] = oscodename
distroname = _REPLACE_LINUX_RE.sub("", grains["osfullname"]).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(" ", "").lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if "os" not in grains:
grains["os"] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains["kernel"] == "SunOS":
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index("_") + 1 :]
grains["os"] = grains["osfullname"] = "SmartOS"
# store a parsed version of YYYY.MM.DD as osrelease
grains["osrelease"] = ".".join(
[
uname_v.split("T")[0][0:4],
uname_v.split("T")[0][4:6],
uname_v.split("T")[0][6:8],
]
)
# store a untouched copy of the timestamp in osrelease_stamp
grains["osrelease_stamp"] = uname_v
elif os.path.isfile("/etc/release"):
with salt.utils.files.fopen("/etc/release", "r") as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r"((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?"
r"\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?"
)
(
osname,
development,
osmajorrelease,
osminorrelease,
) = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains["os"] = grains["osfullname"] = "Solaris"
grains["osrelease"] = ""
else:
if development is not None:
osname = " ".join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains["os"] = grains["osfullname"] = osname
if osname in ["Oracle Solaris"] and uname_v.startswith(
osmajorrelease
):
# Oracla Solars 11 and up have minor version in uname
grains["osrelease"] = uname_v
elif osname in ["OmniOS"]:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
grains.update(_sunos_cpudata())
elif grains["kernel"] == "VMkernel":
grains["os"] = "ESXi"
elif grains["kernel"] == "Darwin":
osrelease = __salt__["cmd.run"]("sw_vers -productVersion")
osname = __salt__["cmd.run"]("sw_vers -productName")
osbuild = __salt__["cmd.run"]("sw_vers -buildVersion")
grains["os"] = "MacOS"
grains["os_family"] = "MacOS"
grains["osfullname"] = "{0} {1}".format(osname, osrelease)
grains["osrelease"] = osrelease
grains["osbuild"] = osbuild
grains["init"] = "launchd"
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains["kernel"] == "AIX":
osrelease = __salt__["cmd.run"]("oslevel")
osrelease_techlevel = __salt__["cmd.run"]("oslevel -r")
osname = __salt__["cmd.run"]("uname")
grains["os"] = "AIX"
grains["osfullname"] = osname
grains["osrelease"] = osrelease
grains["osrelease_techlevel"] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains["os"] = grains["kernel"]
if grains["kernel"] == "FreeBSD":
grains["osfullname"] = grains["os"]
try:
grains["osrelease"] = __salt__["cmd.run"]("freebsd-version -u").split("-")[
0
]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
grains.update(_bsd_cpudata(grains))
if grains["kernel"] in ("OpenBSD", "NetBSD"):
grains.update(_bsd_cpudata(grains))
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
if grains["kernel"] == "NetBSD":
grains.update(_netbsd_gpu_data())
if not grains["os"]:
grains["os"] = "Unknown {0}".format(grains["kernel"])
grains["os_family"] = "Unknown"
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains["os_family"] = _OS_FAMILY_MAP.get(grains["os"], grains["os"])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get("os_family") == "Debian":
osarch = __salt__["cmd.run"]("dpkg --print-architecture").strip()
elif grains.get("os_family") in ["RedHat", "Suse"]:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get("os_family") in ("NILinuxRT", "Poky"):
archinfo = {}
for line in __salt__["cmd.run"]("opkg print-architecture").splitlines():
if line.startswith("arch"):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains["cpuarch"]
grains["osarch"] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get("osrelease", ""):
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
try:
grains["osmajorrelease"] = int(grains["osrelease_info"][0])
except (IndexError, TypeError, ValueError):
log.debug(
"Unable to derive osmajorrelease from osrelease_info '%s'. "
"The osmajorrelease grain will not be set.",
grains["osrelease_info"],
)
os_name = grains[
"os"
if grains.get("os")
in ("Debian", "FreeBSD", "OpenBSD", "NetBSD", "Mac", "Raspbian")
else "osfullname"
]
grains["osfinger"] = "{0}-{1}".format(
os_name,
grains["osrelease"]
if os_name in ("Ubuntu",)
else grains["osrelease_info"][0],
)
return grains
def locale_info():
"""
Provides
defaultlanguage
defaultencoding
"""
grains = {}
grains["locale_info"] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains["locale_info"]["defaultlanguage"],
grains["locale_info"]["defaultencoding"],
) = locale.getdefaultlocale()
except Exception: # pylint: disable=broad-except
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains["locale_info"]["defaultlanguage"] = "unknown"
grains["locale_info"]["defaultencoding"] = "unknown"
grains["locale_info"]["detectedencoding"] = __salt_system_encoding__
grains["locale_info"]["timezone"] = "unknown"
if _DATEUTIL_TZ:
try:
grains["locale_info"]["timezone"] = datetime.datetime.now(
dateutil.tz.tzlocal()
).tzname()
except UnicodeDecodeError:
# Because the method 'tzname' is not a part of salt the decoding error cant be fixed.
# The error is in datetime in the python2 lib
if salt.utils.platform.is_windows():
grains["locale_info"]["timezone"] = time.tzname[0].decode("mbcs")
return grains
def hostname():
"""
Return fqdn, hostname, domainname
.. note::
On Windows the ``domain`` grain may refer to the dns entry for the host
instead of the Windows domain to which the host is joined. It may also
be empty if not a part of any domain. Refer to the ``windowsdomain``
grain instead
"""
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains["localhost"] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error(
"Having trouble getting a hostname. Does this machine have its hostname and domain set properly?"
)
__FQDN__ = "localhost.localdomain"
grains["fqdn"] = __FQDN__
(grains["host"], grains["domain"]) = grains["fqdn"].partition(".")[::2]
return grains
def append_domain():
"""
Return append_domain if set
"""
grain = {}
if salt.utils.platform.is_proxy():
return grain
if "append_domain" in __opts__:
grain["append_domain"] = __opts__["append_domain"]
return grain
def fqdns():
"""
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
To disable the fqdns grain, set enable_fqdns_grains: False in the minion configuration file.
"""
# Provides:
# fqdns
opt = {"fqdns": []}
if __opts__.get(
"enable_fqdns_grains",
False
if salt.utils.platform.is_windows() or salt.utils.platform.is_proxy()
else True,
):
opt = __salt__["network.fqdns"]()
return opt
def ip_fqdn():
"""
Return ip address and FQDN grains
"""
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret["ipv4"] = salt.utils.network.ip_addrs(include_loopback=True)
ret["ipv6"] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()["fqdn"]
for socket_type, ipv_num in ((socket.AF_INET, "4"), (socket.AF_INET6, "6")):
key = "fqdn_ip" + ipv_num
if not ret["ipv" + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except (socket.error, UnicodeError):
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__["__role"] == "master":
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
"second timeout when rendering grains. Set the dns or "
"/etc/hosts for IPv%s to clear this.",
ipv_num,
_fqdn,
timediff,
ipv_num,
)
ret[key] = []
return ret
def ip_interfaces():
"""
Provide a dict of the connected interfaces and their ip addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip_interfaces": ret}
def ip4_interfaces():
"""
Provide a dict of the connected interfaces and their ip4 addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip4_interfaces": ret}
def ip6_interfaces():
"""
Provide a dict of the connected interfaces and their ip6 addresses
The addresses will be passed as a list for each interface
"""
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip6_interfaces": ret}
def hwaddr_interfaces():
"""
Provide a dict of the connected interfaces and their
hw addresses (Mac Address)
"""
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if "hwaddr" in ifaces[face]:
ret[face] = ifaces[face]["hwaddr"]
return {"hwaddr_interfaces": ret}
def dns():
"""
Parse the resolver configuration file
.. versionadded:: 2016.3.0
"""
# Provides:
# dns
if salt.utils.platform.is_windows() or "proxyminion" in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ("nameservers", "ip4_nameservers", "ip6_nameservers", "sortlist"):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {"dns": resolv} if resolv else {}
def get_machine_id():
"""
Provide the machine-id for machine/virtualization combination
"""
# Provides:
# machine-id
if platform.system() == "AIX":
return _aix_get_machine_id()
locations = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {"machine_id": machineid.read().strip()}
def cwd():
"""
Current working directory
"""
return {"cwd": os.getcwd()}
def path():
"""
Return the path
"""
# Provides:
# path
# systempath
_path = salt.utils.stringutils.to_unicode(os.environ.get("PATH", "").strip())
return {
"path": _path,
"systempath": _path.split(os.path.pathsep),
}
def pythonversion():
"""
Return the Python version
"""
# Provides:
# pythonversion
return {"pythonversion": list(sys.version_info)}
def pythonpath():
"""
Return the Python path
"""
# Provides:
# pythonpath
return {"pythonpath": sys.path}
def pythonexecutable():
"""
Return the python executable in use
"""
# Provides:
# pythonexecutable
return {"pythonexecutable": sys.executable}
def saltpath():
"""
Return the path of the salt module
"""
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {"saltpath": os.path.dirname(salt_path)}
def saltversion():
"""
Return the version of salt
"""
# Provides:
# saltversion
from salt.version import __version__
return {"saltversion": __version__}
def zmqversion():
"""
Return the zeromq version
"""
# Provides:
# zmqversion
try:
import zmq
return {"zmqversion": zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
"""
Return the version_info of salt
.. versionadded:: 0.17.0
"""
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {"saltversioninfo": list(__version_info__)}
def _hw_data(osdata):
"""
Get system specific hardware data from dmidecode
Provides
biosversion
productname
manufacturer
serialnumber
biosreleasedate
uuid
.. versionadded:: 0.9.5
"""
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata["kernel"] == "Linux" and os.path.exists("/sys/class/dmi/id"):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
"biosversion": "bios_version",
"productname": "product_name",
"manufacturer": "sys_vendor",
"biosreleasedate": "bios_date",
"uuid": "product_uuid",
"serialnumber": "product_serial",
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join("/sys/class/dmi/id", fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, "r") as ifile:
grains[key] = salt.utils.stringutils.to_unicode(
ifile.read().strip(), errors="replace"
)
if key == "uuid":
grains["uuid"] = grains["uuid"].lower()
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(["dmidecode", "smbios"]) is not None and not (
salt.utils.platform.is_smartos()
or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc")
)
):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
"biosversion": __salt__["smbios.get"]("bios-version"),
"productname": __salt__["smbios.get"]("system-product-name"),
"manufacturer": __salt__["smbios.get"]("system-manufacturer"),
"biosreleasedate": __salt__["smbios.get"]("bios-release-date"),
"uuid": __salt__["smbios.get"]("system-uuid"),
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__["smbios.get"]("system-uuid")
if uuid is not None:
grains["uuid"] = uuid.lower()
for serial in (
"system-serial-number",
"chassis-serial-number",
"baseboard-serial-number",
):
serial = __salt__["smbios.get"](serial)
if serial is not None:
grains["serialnumber"] = serial
break
elif salt.utils.path.which_bin(["fw_printenv"]) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
"manufacturer": "manufacturer",
"serialnumber": "serial#",
"productname": "DeviceDesc",
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__["cmd.run_all"]("fw_printenv {0}".format(cmd_key))
if result["retcode"] == 0:
uboot_keyval = result["stdout"].split("=")
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata["kernel"] == "FreeBSD":
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which("kenv")
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
"biosversion": "smbios.bios.version",
"manufacturer": "smbios.system.maker",
"serialnumber": "smbios.system.serial",
"productname": "smbios.system.product",
"biosreleasedate": "smbios.bios.reldate",
"uuid": "smbios.system.uuid",
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__["cmd.run"]("{0} {1}".format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "OpenBSD":
sysctl = salt.utils.path.which("sysctl")
hwdata = {
"biosversion": "hw.version",
"manufacturer": "hw.vendor",
"productname": "hw.product",
"serialnumber": "hw.serialno",
"uuid": "hw.uuid",
}
for key, oid in six.iteritems(hwdata):
value = __salt__["cmd.run"]("{0} -n {1}".format(sysctl, oid))
if not value.endswith(" value is not available"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "NetBSD":
sysctl = salt.utils.path.which("sysctl")
nbsd_hwdata = {
"biosversion": "machdep.dmi.board-version",
"manufacturer": "machdep.dmi.system-vendor",
"serialnumber": "machdep.dmi.system-serial",
"productname": "machdep.dmi.system-product",
"biosreleasedate": "machdep.dmi.bios-date",
"uuid": "machdep.dmi.system-uuid",
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__["cmd.run_all"]("{0} -n {1}".format(sysctl, oid))
if result["retcode"] == 0:
grains[key] = _clean_value(key, result["stdout"])
elif osdata["kernel"] == "Darwin":
grains["manufacturer"] = "Apple Inc."
sysctl = salt.utils.path.which("sysctl")
hwdata = {"productname": "hw.model"}
for key, oid in hwdata.items():
value = __salt__["cmd.run"]("{0} -b {1}".format(sysctl, oid))
if not value.endswith(" is invalid"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc"):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (
("/usr/sbin/prtdiag", "-v"),
("/usr/sbin/prtconf", "-vp"),
("/usr/sbin/virtinfo", "-a"),
):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__["cmd.run"]("{0} {1}".format(cmd, args))
data += "\n"
sn_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?im)^\s*chassis-sn:\s*(\S+)", # prtconf
r"(?im)^\s*Chassis\s+Serial#:\s*(\S+)", # virtinfo
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?im)^\s*Domain\s+UUID:\s*(\S+)"] # virtinfo
]
manufacture_regexes = [
re.compile(r)
for r in [r"(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)"] # prtdiag
]
product_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)", # prtdiag
r"(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)", # prtconf
r"(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)", # prtconf
]
]
sn_regexes = [
re.compile(r)
for r in [
r"(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?i)Chassis\s+Serial#:\s*(\S+)", # virtinfo
r"(?i)chassis-sn:\s*(\S+)", # prtconf
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?i)Domain\s+UUID:\s+(\S+)"] # virtinfo
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["serialnumber"] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[
0:2
] # Limit the number in case we found the data in multiple places
grains["biosversion"] = obp_rev.strip().replace("'", "")
grains["biosreleasedate"] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains["systemfirmware"] = fw_rev.strip().replace("'", "")
grains["systemfirmwaredate"] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["uuid"] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacture"] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains["product"] = t_productname
grains["productname"] = t_productname
break
elif osdata["kernel"] == "AIX":
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("serialnumber", r"(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)"),
("systemfirmware", r"(?im)^\s*Firmware\s+Version:\s+(.*)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
product_regexes = [re.compile(r"(?im)^\s*System\s+Model:\s+(\S+)")]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacturer"], grains["productname"] = (
res.group(1).strip().replace("'", "").split(",")
)
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def get_server_id():
"""
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
"""
# Provides:
# server_id
if salt.utils.platform.is_proxy():
return {}
id_ = __opts__.get("id", "")
hash_ = int(hashlib.sha256(id_.encode()).hexdigest(), 16)
return {"server_id": abs(hash_ % (2 ** 31))}
def get_master():
"""
Provides the minion with the name of its master.
This is useful in states to target other services running on the master.
"""
# Provides:
# master
return {"master": __opts__.get("master", "")}
def default_gateway():
"""
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will also parse out the
ip address of the default gateway, and put it in ip4_gw or ip6_gw.
If the `ip` command is unavailable, no grains will be populated.
Currently does not support multiple default gateways. The grains will be
set to the first default gateway found.
List of grains:
ip4_gw: True # ip/True/False if default ipv4 gateway
ip6_gw: True # ip/True/False if default ipv6 gateway
ip_gw: True # True if either of the above is True, False otherwise
"""
grains = {}
ip_bin = salt.utils.path.which("ip")
if not ip_bin:
return {}
grains["ip_gw"] = False
grains["ip4_gw"] = False
grains["ip6_gw"] = False
for ip_version in ("4", "6"):
try:
out = __salt__["cmd.run"]([ip_bin, "-" + ip_version, "route", "show"])
for line in out.splitlines():
if line.startswith("default"):
grains["ip_gw"] = True
grains["ip{0}_gw".format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == "via":
grains["ip{0}_gw".format(ip_version)] = gw_ip
break
except Exception: # pylint: disable=broad-except
continue
return grains
def kernelparams():
"""
Return the kernel boot parameters
"""
try:
with salt.utils.files.fopen("/proc/cmdline", "r") as fhr:
cmdline = fhr.read()
grains = {"kernelparams": []}
for data in [
item.split("=") for item in salt.utils.args.shlex_split(cmdline)
]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains["kernelparams"] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug("Failed to read /proc/cmdline: %s", exc)
return grains
| 36.911765 | 124 | 0.528985 |
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import hashlib
import locale
import logging
import os
import platform
import re
import socket
import sys
import time
import uuid
from errno import EACCES, EPERM
import distro
import salt.exceptions
import salt.log
import salt.modules.cmdmod
import salt.modules.network
import salt.modules.smbios
import salt.utils.args
import salt.utils.dns
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.pkg.rpm
import salt.utils.platform
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
from salt.utils.network import _get_interfaces
def _linux_distribution():
return (
distro.id(),
distro.version(best=True),
distro.codename(),
)
try:
import dateutil.tz
_DATEUTIL_TZ = True
except ImportError:
_DATEUTIL_TZ = False
log = logging.getLogger(__name__)
HAS_WMI = False
if salt.utils.platform.is_windows():
import salt.utils.win_osinfo
try:
import wmi
import salt.utils.winapi
import win32api
import salt.utils.win_reg
HAS_WMI = True
except ImportError:
log.exception(
"Unable to import Python wmi module, some core grains " "will be missing"
)
__proxyenabled__ = ["*"]
__FQDN__ = None
__salt__ = {
"cmd.run": salt.modules.cmdmod._run_quiet,
"cmd.retcode": salt.modules.cmdmod._retcode_quiet,
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"smbios.records": salt.modules.smbios.records,
"smbios.get": salt.modules.smbios.get,
"network.fqdns": salt.modules.network.fqdns,
}
HAS_UNAME = hasattr(os, "uname")
HOST_NOT_FOUND = 1
NO_DATA = 4
def _windows_cpudata():
grains = {}
if "NUMBER_OF_PROCESSORS" in os.environ:
# conditional in templating. Also follows _linux_cpudata()
try:
grains["num_cpus"] = int(os.environ["NUMBER_OF_PROCESSORS"])
except ValueError:
grains["num_cpus"] = 1
grains["cpu_model"] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString",
).get("vdata")
return grains
def _linux_cpudata():
# Provides:
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cpuinfo = "/proc/cpuinfo"
# Parse over the cpuinfo file
if os.path.isfile(cpuinfo):
with salt.utils.files.fopen(cpuinfo, "r") as _fp:
for line in _fp:
comps = line.split(":")
if not len(comps) > 1:
continue
key = comps[0].strip()
val = comps[1].strip()
if key == "processor":
grains["num_cpus"] = int(val) + 1
# head -2 /proc/cpuinfo
# vendor_id : IBM/S390
# # processors : 2
elif key == "# processors":
grains["num_cpus"] = int(val)
elif key == "vendor_id":
grains["cpu_model"] = val
elif key == "model name":
grains["cpu_model"] = val
elif key == "flags":
grains["cpu_flags"] = val.split()
elif key == "Features":
grains["cpu_flags"] = val.split()
# ARM support - /proc/cpuinfo
#
# Processor : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Features : swp half thumb fastmult vfp edsp java tls
# CPU implementer : 0x41
# CPU architecture: 7
# CPU variant : 0x0
# CPU part : 0xb76
# CPU revision : 7
#
# Hardware : BCM2708
# Revision : 0002
# Serial : 00000000
elif key == "Processor":
grains["cpu_model"] = val.split("-")[0]
grains["num_cpus"] = 1
if "num_cpus" not in grains:
grains["num_cpus"] = 0
if "cpu_model" not in grains:
grains["cpu_model"] = "Unknown"
if "cpu_flags" not in grains:
grains["cpu_flags"] = []
return grains
def _linux_gpu_data():
if __opts__.get("enable_lspci", True) is False:
return {}
if __opts__.get("enable_gpu_grains", True) is False:
return {}
lspci = salt.utils.path.which("lspci")
if not lspci:
log.debug(
"The `lspci` binary is not available on the system. GPU grains "
"will not be available."
)
return {}
# dominant gpu vendors to search for (MUST be lowercase for matching below)
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpu_classes = ("vga compatible controller", "3d controller", "display controller")
devs = []
try:
lspci_out = __salt__["cmd.run"]("{0} -vmm".format(lspci))
cur_dev = {}
error = False
# Add a blank element to the lspci_out.splitlines() list,
# otherwise the last device is not evaluated as a cur_dev and ignored.
lspci_list = lspci_out.splitlines()
lspci_list.append("")
for line in lspci_list:
# check for record-separating empty lines
if line == "":
if cur_dev.get("Class", "").lower() in gpu_classes:
devs.append(cur_dev)
cur_dev = {}
continue
if re.match(r"^\w+:\s+.*", line):
key, val = line.split(":", 1)
cur_dev[key.strip()] = val.strip()
else:
error = True
log.debug("Unexpected lspci output: '%s'", line)
if error:
log.warning(
"Error loading grains, unexpected linux_gpu_data output, "
"check that you have a valid shell configured and "
"permissions to run lspci command"
)
except OSError:
pass
gpus = []
for gpu in devs:
vendor_strings = re.split("[^A-Za-z0-9]", gpu["Vendor"].lower())
# default vendor to 'unknown', overwrite if we match a known one
vendor = "unknown"
for name in known_vendors:
# search for an 'expected' vendor name in the list of strings
if name in vendor_strings:
vendor = name
break
gpus.append({"vendor": vendor, "model": gpu["Device"]})
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _netbsd_gpu_data():
known_vendors = [
"nvidia",
"amd",
"ati",
"intel",
"cirrus logic",
"vmware",
"matrox",
"aspeed",
]
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("pcictl pci0 list")
for line in pcictl_out.splitlines():
for vendor in known_vendors:
vendor_match = re.match(
r"[0-9:]+ ({0}) (.+) \(VGA .+\)".format(vendor), line, re.IGNORECASE
)
if vendor_match:
gpus.append(
{
"vendor": vendor_match.group(1),
"model": vendor_match.group(2),
}
)
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _osx_gpudata():
gpus = []
try:
pcictl_out = __salt__["cmd.run"]("system_profiler SPDisplaysDataType")
for line in pcictl_out.splitlines():
fieldname, _, fieldval = line.partition(": ")
if fieldname.strip() == "Chipset Model":
vendor, _, model = fieldval.partition(" ")
vendor = vendor.lower()
gpus.append({"vendor": vendor, "model": model})
except OSError:
pass
grains = {}
grains["num_gpus"] = len(gpus)
grains["gpus"] = gpus
return grains
def _bsd_cpudata(osdata):
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
sysctl = salt.utils.path.which("sysctl")
arch = salt.utils.path.which("arch")
cmds = {}
if sysctl:
cmds.update(
{
"num_cpus": "{0} -n hw.ncpu".format(sysctl),
"cpuarch": "{0} -n hw.machine".format(sysctl),
"cpu_model": "{0} -n hw.model".format(sysctl),
}
)
if arch and osdata["kernel"] == "OpenBSD":
cmds["cpuarch"] = "{0} -s".format(arch)
if osdata["kernel"] == "Darwin":
cmds["cpu_model"] = "{0} -n machdep.cpu.brand_string".format(sysctl)
cmds["cpu_flags"] = "{0} -n machdep.cpu.features".format(sysctl)
grains = dict([(k, __salt__["cmd.run"](v)) for k, v in six.iteritems(cmds)])
if "cpu_flags" in grains and isinstance(grains["cpu_flags"], six.string_types):
grains["cpu_flags"] = grains["cpu_flags"].split(" ")
if osdata["kernel"] == "NetBSD":
grains["cpu_flags"] = []
for line in __salt__["cmd.run"]("cpuctl identify 0").splitlines():
cpu_match = re.match(r"cpu[0-9]:\ features[0-9]?\ .+<(.+)>", line)
if cpu_match:
flag = cpu_match.group(1).split(",")
grains["cpu_flags"].extend(flag)
if osdata["kernel"] == "FreeBSD" and os.path.isfile("/var/run/dmesg.boot"):
grains["cpu_flags"] = []
# TODO: at least it needs to be tested for BSD other then FreeBSD
with salt.utils.files.fopen("/var/run/dmesg.boot", "r") as _fp:
cpu_here = False
for line in _fp:
if line.startswith("CPU: "):
cpu_here = True # starts CPU descr
continue
if cpu_here:
if not line.startswith(" "):
break # game over
if "Features" in line:
start = line.find("<")
end = line.find(">")
if start > 0 and end > 0:
flag = line[start + 1 : end].split(",")
grains["cpu_flags"].extend(flag)
try:
grains["num_cpus"] = int(grains["num_cpus"])
except ValueError:
grains["num_cpus"] = 1
return grains
def _sunos_cpudata():
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
grains["cpu_flags"] = []
grains["cpuarch"] = __salt__["cmd.run"]("isainfo -k")
psrinfo = "/usr/sbin/psrinfo 2>/dev/null"
grains["num_cpus"] = len(
__salt__["cmd.run"](psrinfo, python_shell=True).splitlines()
)
kstat_info = "kstat -p cpu_info:*:*:brand"
for line in __salt__["cmd.run"](kstat_info).splitlines():
match = re.match(r"(\w+:\d+:\w+\d+:\w+)\s+(.+)", line)
if match:
grains["cpu_model"] = match.group(2)
isainfo = "isainfo -n -v"
for line in __salt__["cmd.run"](isainfo).splitlines():
match = re.match(r"^\s+(.+)", line)
if match:
cpu_flags = match.group(1).split()
grains["cpu_flags"].extend(cpu_flags)
return grains
def _aix_cpudata():
# Provides:
# cpuarch
# num_cpus
# cpu_model
# cpu_flags
grains = {}
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("cpuarch", r"(?im)^\s*Processor\s+Type:\s+(\S+)"),
("cpu_flags", r"(?im)^\s*Processor\s+Version:\s+(\S+)"),
("cpu_model", r"(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)"),
("num_cpus", r"(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def _linux_memdata():
grains = {"mem_total": 0, "swap_total": 0}
meminfo = "/proc/meminfo"
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, "r") as ifile:
for line in ifile:
comps = line.rstrip("\n").split(":")
if not len(comps) > 1:
continue
if comps[0].strip() == "MemTotal":
grains["mem_total"] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == "SwapTotal":
grains["swap_total"] = int(comps[1].split()[0]) // 1024
return grains
def _osx_memdata():
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.memsize".format(sysctl))
swap_total = (
__salt__["cmd.run"]("{0} -n vm.swapusage".format(sysctl))
.split()[2]
.replace(",", ".")
)
if swap_total.endswith("K"):
_power = 2 ** 10
elif swap_total.endswith("M"):
_power = 2 ** 20
elif swap_total.endswith("G"):
_power = 2 ** 30
swap_total = float(swap_total[:-1]) * _power
grains["mem_total"] = int(mem) // 1024 // 1024
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _bsd_memdata(osdata):
grains = {"mem_total": 0, "swap_total": 0}
sysctl = salt.utils.path.which("sysctl")
if sysctl:
mem = __salt__["cmd.run"]("{0} -n hw.physmem".format(sysctl))
if osdata["kernel"] == "NetBSD" and mem.startswith("-"):
mem = __salt__["cmd.run"]("{0} -n hw.physmem64".format(sysctl))
grains["mem_total"] = int(mem) // 1024 // 1024
if osdata["kernel"] in ["OpenBSD", "NetBSD"]:
swapctl = salt.utils.path.which("swapctl")
swap_data = __salt__["cmd.run"]("{0} -sk".format(swapctl))
if swap_data == "no swap devices configured":
swap_total = 0
else:
swap_total = swap_data.split(" ")[1]
else:
swap_total = __salt__["cmd.run"]("{0} -n vm.swap_total".format(sysctl))
grains["swap_total"] = int(swap_total) // 1024 // 1024
return grains
def _sunos_memdata():
grains = {"mem_total": 0, "swap_total": 0}
prtconf = "/usr/sbin/prtconf 2>/dev/null"
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = line.split(" ")
if comps[0].strip() == "Memory" and comps[1].strip() == "size:":
grains["mem_total"] = int(comps[2].strip())
swap_cmd = salt.utils.path.which("swap")
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_avail = int(swap_data[-2][:-1])
swap_used = int(swap_data[-4][:-1])
swap_total = (swap_avail + swap_used) // 1024
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
return grains
def _aix_memdata():
grains = {"mem_total": 0, "swap_total": 0}
prtconf = salt.utils.path.which("prtconf")
if prtconf:
for line in __salt__["cmd.run"](prtconf, python_shell=True).splitlines():
comps = [x for x in line.strip().split(" ") if x]
if len(comps) > 2 and "Memory" in comps[0] and "Size" in comps[1]:
grains["mem_total"] = int(comps[2])
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
swap_cmd = salt.utils.path.which("swap")
if swap_cmd:
swap_data = __salt__["cmd.run"]("{0} -s".format(swap_cmd)).split()
try:
swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4
except ValueError:
swap_total = None
grains["swap_total"] = swap_total
else:
log.error("The 'swap' binary was not found in $PATH.")
return grains
def _windows_memdata():
grains = {"mem_total": 0}
tot_bytes = win32api.GlobalMemoryStatusEx()["TotalPhys"]
grains["mem_total"] = int(tot_bytes / (1024 ** 2))
return grains
def _memdata(osdata):
grains = {"mem_total": 0}
if osdata["kernel"] == "Linux":
grains.update(_linux_memdata())
elif osdata["kernel"] in ("FreeBSD", "OpenBSD", "NetBSD"):
grains.update(_bsd_memdata(osdata))
elif osdata["kernel"] == "Darwin":
grains.update(_osx_memdata())
elif osdata["kernel"] == "SunOS":
grains.update(_sunos_memdata())
elif osdata["kernel"] == "AIX":
grains.update(_aix_memdata())
elif osdata["kernel"] == "Windows" and HAS_WMI:
grains.update(_windows_memdata())
return grains
def _aix_get_machine_id():
grains = {}
cmd = salt.utils.path.which("lsattr")
if cmd:
data = __salt__["cmd.run"]("{0} -El sys0".format(cmd)) + os.linesep
uuid_regexes = [re.compile(r"(?im)^\s*os_uuid\s+(\S+)\s+(.*)")]
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["machine_id"] = res.group(1).strip()
break
else:
log.error("The 'lsattr' binary was not found in $PATH.")
return grains
def _windows_virtual(osdata):
grains = dict()
if osdata["kernel"] != "Windows":
return grains
grains["virtual"] = osdata.get("virtual", "physical")
manufacturer = osdata.get("manufacturer", "")
if manufacturer is None:
manufacturer = ""
productname = osdata.get("productname", "")
if productname is None:
productname = ""
if "QEMU" in manufacturer:
grains["virtual"] = "kvm"
if "Bochs" in manufacturer:
grains["virtual"] = "kvm"
elif "oVirt" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "oVirt"
elif "RHEV Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in productname:
grains["virtual"] = "VirtualBox"
elif "VMware Virtual Platform" in productname:
grains["virtual"] = "VMware"
elif "Microsoft" in manufacturer and "Virtual Machine" in productname:
grains["virtual"] = "VirtualPC"
elif "Parallels Software" in manufacturer:
grains["virtual"] = "Parallels"
elif "CloudStack KVM Hypervisor" in productname:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "cloudstack"
return grains
def _virtual(osdata):
grains = {"virtual": osdata.get("virtual", "physical")}
skip_cmds = ("AIX",)
_cmds = ["systemd-detect-virt", "virt-what", "dmidecode"]
if not salt.utils.platform.is_windows() and osdata["kernel"] not in skip_cmds:
if salt.utils.path.which("virt-what"):
_cmds = ["virt-what"]
if __opts__.get("enable_lspci", True) is True:
if os.path.exists("/proc/bus/pci"):
_cmds += ["lspci"]
if osdata["kernel"] in skip_cmds:
_cmds = ()
if (
HAS_UNAME
and osdata["kernel"] == "Linux"
and "BrandZ virtual linux" in os.uname()
):
grains["virtual"] = "zone"
return grains
failed_commands = set()
for command in _cmds:
args = []
if osdata["kernel"] == "Darwin":
command = "system_profiler"
args = ["SPDisplaysDataType"]
elif osdata["kernel"] == "SunOS":
virtinfo = salt.utils.path.which("virtinfo")
if virtinfo:
try:
ret = __salt__["cmd.run_all"](virtinfo)
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
failed_commands.add(virtinfo)
else:
if ret["stdout"].endswith("not supported"):
command = "prtdiag"
else:
command = "virtinfo"
args.append("-c current list -H -o name")
else:
command = "prtdiag"
cmd = salt.utils.path.which(command)
if not cmd:
continue
cmd = "{0} {1}".format(cmd, " ".join(args))
try:
ret = __salt__["cmd.run_all"](cmd)
if ret["retcode"] > 0:
if salt.log.is_logging_configured():
# systemd-detect-virt always returns > 0 on non-virtualized
# systems
# prtdiag only works in the global zone, skip if it fails
if (
salt.utils.platform.is_windows()
or "systemd-detect-virt" in cmd
or "prtdiag" in cmd
):
continue
failed_commands.add(command)
continue
except salt.exceptions.CommandExecutionError:
if salt.log.is_logging_configured():
if salt.utils.platform.is_windows():
continue
failed_commands.add(command)
continue
output = ret["stdout"]
if command == "system_profiler":
macoutput = output.lower()
if "0x1ab8" in macoutput:
grains["virtual"] = "Parallels"
if "parallels" in macoutput:
grains["virtual"] = "Parallels"
if "vmware" in macoutput:
grains["virtual"] = "VMware"
if "0x15ad" in macoutput:
grains["virtual"] = "VMware"
if "virtualbox" in macoutput:
grains["virtual"] = "VirtualBox"
# Break out of the loop so the next log message is not issued
break
elif command == "systemd-detect-virt":
if output in (
"qemu",
"kvm",
"oracle",
"xen",
"bochs",
"chroot",
"uml",
"systemd-nspawn",
):
grains["virtual"] = output
break
elif "vmware" in output:
grains["virtual"] = "VMware"
break
elif "microsoft" in output:
grains["virtual"] = "VirtualPC"
break
elif "lxc" in output:
grains["virtual"] = "LXC"
break
elif "systemd-nspawn" in output:
grains["virtual"] = "LXC"
break
elif command == "virt-what":
for line in output.splitlines():
if line in ("kvm", "qemu", "uml", "xen", "lxc"):
grains["virtual"] = line
break
elif "vmware" in line:
grains["virtual"] = "VMware"
break
elif "parallels" in line:
grains["virtual"] = "Parallels"
break
elif "hyperv" in line:
grains["virtual"] = "HyperV"
break
elif command == "dmidecode":
# Product Name: VirtualBox
if "Vendor: QEMU" in output:
# FIXME: Make this detect between kvm or qemu
grains["virtual"] = "kvm"
if "Manufacturer: QEMU" in output:
grains["virtual"] = "kvm"
if "Vendor: Bochs" in output:
grains["virtual"] = "kvm"
if "Manufacturer: Bochs" in output:
grains["virtual"] = "kvm"
if "BHYVE" in output:
grains["virtual"] = "bhyve"
# Product Name: (oVirt) www.ovirt.org
# Red Hat Community virtualization Project based on kvm
elif "Manufacturer: oVirt" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
# Red Hat Enterprise Virtualization
elif "Product Name: RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
# Product Name: VMware Virtual Platform
elif "VMware" in output:
grains["virtual"] = "VMware"
# Manufacturer: Microsoft Corporation
# Product Name: Virtual Machine
elif ": Microsoft" in output and "Virtual Machine" in output:
grains["virtual"] = "VirtualPC"
# Manufacturer: Parallels Software International Inc.
elif "Parallels Software" in output:
grains["virtual"] = "Parallels"
elif "Manufacturer: Google" in output:
grains["virtual"] = "kvm"
# Proxmox KVM
elif "Vendor: SeaBIOS" in output:
grains["virtual"] = "kvm"
# Break out of the loop, lspci parsing is not necessary
break
elif command == "lspci":
# dmidecode not available or the user does not have the necessary
# permissions
model = output.lower()
if "vmware" in model:
grains["virtual"] = "VMware"
# 00:04.0 System peripheral: InnoTek Systemberatung GmbH
# VirtualBox Guest Service
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "virtio" in model:
grains["virtual"] = "kvm"
# Break out of the loop so the next log message is not issued
break
elif command == "prtdiag":
model = output.lower().split("\n")[0]
if "vmware" in model:
grains["virtual"] = "VMware"
elif "virtualbox" in model:
grains["virtual"] = "VirtualBox"
elif "qemu" in model:
grains["virtual"] = "kvm"
elif "joyent smartdc hvm" in model:
grains["virtual"] = "kvm"
break
elif command == "virtinfo":
if output == "logical-domain":
grains["virtual"] = "LDOM"
roles = []
for role in ("control", "io", "root", "service"):
subtype_cmd = "{0} -c current get -H -o value {1}-role".format(
command, role
)
ret = __salt__["cmd.run"]("{0}".format(subtype_cmd))
if ret == "true":
roles.append(role)
if roles:
grains["virtual_subtype"] = roles
elif output == "non-global-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "non-global"
elif output == "kernel-zone":
grains["virtual"] = "zone"
grains["virtual_subtype"] = "kernel"
elif output == "vmware":
grains["virtual"] = "VMware"
break
choices = ("Linux", "HP-UX")
isdir = os.path.isdir
sysctl = salt.utils.path.which("sysctl")
if osdata["kernel"] in choices:
if os.path.isdir("/proc"):
try:
self_root = os.stat("/")
init_root = os.stat("/proc/1/root/.")
if self_root != init_root:
grains["virtual_subtype"] = "chroot"
except (IOError, OSError):
pass
if isdir("/proc/vz"):
if os.path.isfile("/proc/vz/version"):
grains["virtual"] = "openvzhn"
elif os.path.isfile("/proc/vz/veinfo"):
grains["virtual"] = "openvzve"
# a posteriori, it's expected for these to have failed:
failed_commands.discard("lspci")
failed_commands.discard("dmidecode")
if os.path.isfile("/proc/self/status"):
with salt.utils.files.fopen("/proc/self/status") as status_file:
vz_re = re.compile(r"^envID:\s+(\d+)$")
for line in status_file:
vz_match = vz_re.match(line.rstrip("\n"))
if vz_match and int(vz_match.groups()[0]) != 0:
grains["virtual"] = "openvzve"
elif vz_match and int(vz_match.groups()[0]) == 0:
grains["virtual"] = "openvzhn"
if isdir("/proc/sys/xen") or isdir("/sys/bus/xen") or isdir("/proc/xen"):
if os.path.isfile("/proc/xen/xsd_kva"):
grains["virtual_subtype"] = "Xen Dom0"
else:
if osdata.get("productname", "") == "HVM domU":
grains["virtual_subtype"] = "Xen HVM DomU"
elif os.path.isfile("/proc/xen/capabilities") and os.access(
"/proc/xen/capabilities", os.R_OK
):
with salt.utils.files.fopen("/proc/xen/capabilities") as fhr:
if "control_d" not in fhr.read():
grains["virtual_subtype"] = "Xen PV DomU"
else:
grains["virtual_subtype"] = "Xen Dom0"
# Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
# Tested on Fedora 15 / 2.6.41.4-1 without running xen
elif isdir("/sys/bus/xen"):
if "xen:" in __salt__["cmd.run"]("dmesg").lower():
grains["virtual_subtype"] = "Xen PV DomU"
elif os.path.isfile("/sys/bus/xen/drivers/xenconsole"):
# An actual DomU will have the xenconsole driver
grains["virtual_subtype"] = "Xen PV DomU"
# If a Dom0 or DomU was detected, obviously this is xen
if "dom" in grains.get("virtual_subtype", "").lower():
grains["virtual"] = "xen"
# Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
if os.path.isfile("/proc/1/cgroup"):
try:
with salt.utils.files.fopen("/proc/1/cgroup", "r") as fhr:
fhr_contents = fhr.read()
if ":/lxc/" in fhr_contents:
grains["virtual"] = "container"
grains["virtual_subtype"] = "LXC"
elif ":/kubepods/" in fhr_contents:
grains["virtual_subtype"] = "kubernetes"
elif ":/libpod_parent/" in fhr_contents:
grains["virtual_subtype"] = "libpod"
else:
if any(
x in fhr_contents
for x in (":/system.slice/docker", ":/docker/", ":/docker-ce/")
):
grains["virtual"] = "container"
grains["virtual_subtype"] = "Docker"
except IOError:
pass
if os.path.isfile("/proc/cpuinfo"):
with salt.utils.files.fopen("/proc/cpuinfo", "r") as fhr:
if "QEMU Virtual CPU" in fhr.read():
grains["virtual"] = "kvm"
if os.path.isfile("/sys/devices/virtual/dmi/id/product_name"):
try:
with salt.utils.files.fopen(
"/sys/devices/virtual/dmi/id/product_name", "r"
) as fhr:
output = salt.utils.stringutils.to_unicode(
fhr.read(), errors="replace"
)
if "VirtualBox" in output:
grains["virtual"] = "VirtualBox"
elif "RHEV Hypervisor" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "rhev"
elif "oVirt Node" in output:
grains["virtual"] = "kvm"
grains["virtual_subtype"] = "ovirt"
elif "Google" in output:
grains["virtual"] = "gce"
elif "BHYVE" in output:
grains["virtual"] = "bhyve"
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except IOError:
pass
elif osdata["kernel"] == "FreeBSD":
kenv = salt.utils.path.which("kenv")
if kenv:
product = __salt__["cmd.run"]("{0} smbios.system.product".format(kenv))
maker = __salt__["cmd.run"]("{0} smbios.system.maker".format(kenv))
if product.startswith("VMware"):
grains["virtual"] = "VMware"
if product.startswith("VirtualBox"):
grains["virtual"] = "VirtualBox"
if maker.startswith("Xen"):
grains["virtual_subtype"] = "{0} {1}".format(maker, product)
grains["virtual"] = "xen"
if maker.startswith("Microsoft") and product.startswith("Virtual"):
grains["virtual"] = "VirtualPC"
if maker.startswith("OpenStack"):
grains["virtual"] = "OpenStack"
if maker.startswith("Bochs"):
grains["virtual"] = "kvm"
if sysctl:
hv_vendor = __salt__["cmd.run"]("{0} -n hw.hv_vendor".format(sysctl))
model = __salt__["cmd.run"]("{0} -n hw.model".format(sysctl))
jail = __salt__["cmd.run"]("{0} -n security.jail.jailed".format(sysctl))
if "bhyve" in hv_vendor:
grains["virtual"] = "bhyve"
elif "QEMU Virtual CPU" in model:
grains["virtual"] = "kvm"
if jail == "1":
grains["virtual_subtype"] = "jail"
elif osdata["kernel"] == "OpenBSD":
if "manufacturer" in osdata:
if osdata["manufacturer"] in ["QEMU", "Red Hat", "Joyent"]:
grains["virtual"] = "kvm"
if osdata["manufacturer"] == "OpenBSD":
grains["virtual"] = "vmm"
elif osdata["kernel"] == "NetBSD":
if sysctl:
if "QEMU Virtual CPU" in __salt__["cmd.run"](
"{0} -n machdep.cpu_brand".format(sysctl)
):
grains["virtual"] = "kvm"
elif "invalid" not in __salt__["cmd.run"](
"{0} -n machdep.xen.suspend".format(sysctl)
):
grains["virtual"] = "Xen PV DomU"
elif "VMware" in __salt__["cmd.run"](
"{0} -n machdep.dmi.system-vendor".format(sysctl)
):
grains["virtual"] = "VMware"
# NetBSD has Xen dom0 support
elif (
__salt__["cmd.run"]("{0} -n machdep.idle-mechanism".format(sysctl))
== "xen"
):
if os.path.isfile("/var/run/xenconsoled.pid"):
grains["virtual_subtype"] = "Xen Dom0"
elif osdata["kernel"] == "SunOS":
# we did not get any data from virtinfo or prtdiag
# check the zonename here as fallback
zonename = salt.utils.path.which("zonename")
if zonename:
zone = __salt__["cmd.run"]("{0}".format(zonename))
if zone != "global":
grains["virtual"] = "zone"
# last ditch efford to check the brand identifier
elif os.path.isdir("/.SUNWnative"):
grains["virtual"] = "zone"
# If we have a virtual_subtype, we're virtual, but maybe we couldn't
# figure out what specific virtual type we were?
if grains.get("virtual_subtype") and grains["virtual"] == "physical":
grains["virtual"] = "virtual"
for command in failed_commands:
log.info(
"Although '%s' was found in path, the current user "
"cannot execute it. Grains output might not be "
"accurate.",
command,
)
return grains
def _virtual_hv(osdata):
grains = {}
# Bail early if we're not running on Xen
try:
if "xen" not in osdata["virtual"]:
return grains
except KeyError:
return grains
try:
version = {}
for fn in ("major", "minor", "extra"):
with salt.utils.files.fopen(
"/sys/hypervisor/version/{}".format(fn), "r"
) as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains["virtual_hv_version"] = "{}.{}{}".format(
version["major"], version["minor"], version["extra"]
)
grains["virtual_hv_version_info"] = [
version["major"],
version["minor"],
version["extra"],
]
except (IOError, OSError, KeyError):
pass
xen_feature_table = {
0: "writable_page_tables",
1: "writable_descriptor_tables",
2: "auto_translated_physmap",
3: "supervisor_mode_kernel",
4: "pae_pgdir_above_4gb",
5: "mmu_pt_update_preserve_ad",
7: "gnttab_map_avail_bits",
8: "hvm_callback_vector",
9: "hvm_safe_pvclock",
10: "hvm_pirqs",
11: "dom0",
12: "grant_map_identity",
13: "memory_op_vnode_supported",
14: "ARM_SMCCC_supported",
}
try:
with salt.utils.files.fopen("/sys/hypervisor/properties/features", "r") as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains["virtual_hv_features"] = features
grains["virtual_hv_features_list"] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains
def _ps(osdata):
grains = {}
bsd_choices = ("FreeBSD", "NetBSD", "OpenBSD", "MacOS")
if osdata["os"] in bsd_choices:
grains["ps"] = "ps auxwww"
elif osdata["os_family"] == "Solaris":
grains["ps"] = "/usr/ucb/ps auxwww"
elif osdata["os"] == "Windows":
grains["ps"] = "tasklist.exe"
elif osdata.get("virtual", "") == "openvzhn":
grains["ps"] = (
'ps -fH -p $(grep -l "^envID:[[:space:]]*0\\$" '
'/proc/[0-9]*/status | sed -e "s=/proc/\\([0-9]*\\)/.*=\\1=") '
"| awk '{ $7=\"\"; print }'"
)
elif osdata["os_family"] == "AIX":
grains["ps"] = "/usr/bin/ps auxww"
elif osdata["os_family"] == "NILinuxRT":
grains["ps"] = "ps -o user,pid,ppid,tty,time,comm"
else:
grains["ps"] = "ps -efHww"
return grains
def _clean_value(key, val):
if val is None or not val or re.match("none", val, flags=re.IGNORECASE):
return None
elif "uuid" in key:
for uuidver in range(1, 5):
try:
uuid.UUID(val, version=uuidver)
return val
except ValueError:
continue
log.trace("HW %s value %s is an invalid UUID", key, val.replace("\n", " "))
return None
elif re.search("serial|part|version", key):
# 'To be filled by O.E.M.
if (
re.match(r"^[0]+$", val)
or re.match(r"[0]?1234567[8]?[9]?[0]?", val)
or re.search(
r"sernum|part[_-]?number|specified|filled|applicable",
val,
flags=re.IGNORECASE,
)
):
return None
elif re.search("asset|manufacturer", key):
if re.search(
r"manufacturer|to be filled|available|asset|^no(ne|t)",
val,
flags=re.IGNORECASE,
):
return None
else:
if re.search(r"to be filled", val, flags=re.IGNORECASE) or re.search(
r"un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)",
val,
flags=re.IGNORECASE,
):
return None
return val
def _windows_os_release_grain(caption, product_type):
version = "Unknown"
release = ""
if "Server" in caption:
if re.match(r"^Microsoft Hyper-V Server$", caption):
version = "2019"
else:
for item in caption.split(" "):
# If it's all digits, then it's version
if re.match(r"\d+", item):
version = item
# If it starts with R and then numbers, it's the release
if re.match(r"^R\d+$", item):
release = item
os_release = "{0}Server{1}".format(version, release)
else:
for item in caption.split(" "):
if re.match(r"^(\d+(\.\d+)?)|Thin|Vista|XP$", item):
version = item
os_release = version
if os_release in ["Unknown"]:
os_release = platform.release()
server = {
"Vista": "2008Server",
"7": "2008ServerR2",
"8": "2012Server",
"8.1": "2012ServerR2",
"10": "2016Server",
}
up the actual Server Release.
# (Product Type 1 is Desktop, Everything else is Server)
if product_type > 1 and os_release in server:
os_release = server[os_release]
return os_release
def _windows_platform_data():
# Provides:
# kernelrelease
# kernelversion
# osversion
# osrelease
# osservicepack
# osmanufacturer
# manufacturer
# productname
# biosversion
# serialnumber
# osfullname
# timezone
# windowsdomain
# windowsdomaintype
# motherboard.productname
# motherboard.serialnumber
# virtual
if not HAS_WMI:
return {}
with salt.utils.winapi.Com():
wmi_c = wmi.WMI()
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx
systeminfo = wmi_c.Win32_ComputerSystem()[0]
# https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx
osinfo = wmi_c.Win32_OperatingSystem()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx
biosinfo = wmi_c.Win32_BIOS()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx
timeinfo = wmi_c.Win32_TimeZone()[0]
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx
motherboard = {"product": None, "serial": None}
try:
motherboardinfo = wmi_c.Win32_BaseBoard()[0]
motherboard["product"] = motherboardinfo.Product
motherboard["serial"] = motherboardinfo.SerialNumber
except IndexError:
log.debug("Motherboard info not available on this system")
kernel_version = platform.version()
info = salt.utils.win_osinfo.get_os_version_info()
net_info = salt.utils.win_osinfo.get_join_info()
service_pack = None
if info["ServicePackMajor"] > 0:
service_pack = "".join(["SP", six.text_type(info["ServicePackMajor"])])
os_release = _windows_os_release_grain(
caption=osinfo.Caption, product_type=osinfo.ProductType
)
grains = {
"kernelrelease": _clean_value("kernelrelease", osinfo.Version),
"kernelversion": _clean_value("kernelversion", kernel_version),
"osversion": _clean_value("osversion", osinfo.Version),
"osrelease": _clean_value("osrelease", os_release),
"osservicepack": _clean_value("osservicepack", service_pack),
"osmanufacturer": _clean_value("osmanufacturer", osinfo.Manufacturer),
"manufacturer": _clean_value("manufacturer", systeminfo.Manufacturer),
"productname": _clean_value("productname", systeminfo.Model),
# bios name had a bunch of whitespace appended to it in my testing
# 'PhoenixBIOS 4.0 Release 6.0 '
"biosversion": _clean_value("biosversion", biosinfo.Name.strip()),
"serialnumber": _clean_value("serialnumber", biosinfo.SerialNumber),
"osfullname": _clean_value("osfullname", osinfo.Caption),
"timezone": _clean_value("timezone", timeinfo.Description),
"windowsdomain": _clean_value("windowsdomain", net_info["Domain"]),
"windowsdomaintype": _clean_value(
"windowsdomaintype", net_info["DomainType"]
),
"motherboard": {
"productname": _clean_value(
"motherboard.productname", motherboard["product"]
),
"serialnumber": _clean_value(
"motherboard.serialnumber", motherboard["serial"]
),
},
}
# test for virtualized environments
# I only had VMware available so the rest are unvalidated
if "VRTUAL" in biosinfo.Version: # (not a typo)
grains["virtual"] = "HyperV"
elif "A M I" in biosinfo.Version:
grains["virtual"] = "VirtualPC"
elif "VMware" in systeminfo.Model:
grains["virtual"] = "VMware"
elif "VirtualBox" in systeminfo.Model:
grains["virtual"] = "VirtualBox"
elif "Xen" in biosinfo.Version:
grains["virtual"] = "Xen"
if "HVM domU" in systeminfo.Model:
grains["virtual_subtype"] = "HVM domU"
elif "OpenStack" in systeminfo.Model:
grains["virtual"] = "OpenStack"
elif "AMAZON" in biosinfo.Version:
grains["virtual"] = "EC2"
return grains
def _osx_platform_data():
cmd = "system_profiler SPHardwareDataType"
hardware = __salt__["cmd.run"](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(": ")
if field_name.strip() == "Model Name":
key = "model_name"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = "boot_rom_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = "smc_version"
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = "system_serialnumber"
grains[key] = _clean_value(key, field_val)
return grains
def id_():
return {"id": __opts__.get("id", "")}
_REPLACE_LINUX_RE = re.compile(r"\W(?:gnu/)?linux", re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
# Please see os_data() and _supported_dists.
# If your system is not detecting properly it likely needs an entry here.
_OS_NAME_MAP = {
"redhatente": "RedHat",
"gentoobase": "Gentoo",
"archarm": "Arch ARM",
"arch": "Arch",
"debian": "Debian",
"raspbian": "Raspbian",
"fedoraremi": "Fedora",
"chapeau": "Chapeau",
"korora": "Korora",
"amazonami": "Amazon",
"alt": "ALT",
"enterprise": "OEL",
"oracleserv": "OEL",
"cloudserve": "CloudLinux",
"cloudlinux": "CloudLinux",
"pidora": "Fedora",
"scientific": "ScientificLinux",
"synology": "Synology",
"nilrt": "NILinuxRT",
"poky": "Poky",
"manjaro": "Manjaro",
"manjarolin": "Manjaro",
"univention": "Univention",
"antergos": "Antergos",
"sles": "SUSE",
"void": "Void",
"slesexpand": "RES",
"linuxmint": "Mint",
"neon": "KDE neon",
}
# Map the 'os' grain to the 'os_family' grain
# These should always be capitalized entries as the lookup comes
# post-_OS_NAME_MAP. If your system is having trouble with detection, please
# make sure that the 'os' grain is capitalized and working correctly first.
_OS_FAMILY_MAP = {
"Ubuntu": "Debian",
"Fedora": "RedHat",
"Chapeau": "RedHat",
"Korora": "RedHat",
"FedBerry": "RedHat",
"CentOS": "RedHat",
"GoOSe": "RedHat",
"Scientific": "RedHat",
"Amazon": "RedHat",
"CloudLinux": "RedHat",
"OVS": "RedHat",
"OEL": "RedHat",
"XCP": "RedHat",
"XCP-ng": "RedHat",
"XenServer": "RedHat",
"RES": "RedHat",
"Sangoma": "RedHat",
"Mandrake": "Mandriva",
"ESXi": "VMware",
"Mint": "Debian",
"VMwareESX": "VMware",
"Bluewhite64": "Bluewhite",
"Slamd64": "Slackware",
"SLES": "Suse",
"SUSE Enterprise Server": "Suse",
"SUSE Enterprise Server": "Suse",
"SLED": "Suse",
"openSUSE": "Suse",
"SUSE": "Suse",
"openSUSE Leap": "Suse",
"openSUSE Tumbleweed": "Suse",
"SLES_SAP": "Suse",
"Solaris": "Solaris",
"SmartOS": "Solaris",
"OmniOS": "Solaris",
"OpenIndiana Development": "Solaris",
"OpenIndiana": "Solaris",
"OpenSolaris Development": "Solaris",
"OpenSolaris": "Solaris",
"Oracle Solaris": "Solaris",
"Arch ARM": "Arch",
"Manjaro": "Arch",
"Antergos": "Arch",
"ALT": "RedHat",
"Trisquel": "Debian",
"GCEL": "Debian",
"Linaro": "Debian",
"elementary OS": "Debian",
"elementary": "Debian",
"Univention": "Debian",
"ScientificLinux": "RedHat",
"Raspbian": "Debian",
"Devuan": "Debian",
"antiX": "Debian",
"Kali": "Debian",
"neon": "Debian",
"Cumulus": "Debian",
"Deepin": "Debian",
"NILinuxRT": "NILinuxRT",
"KDE neon": "Debian",
"Void": "Void",
"IDMS": "Debian",
"Funtoo": "Gentoo",
"AIX": "AIX",
"TurnKey": "Debian",
}
# Matches any possible format:
# DISTRIB_ID="Ubuntu"
# DISTRIB_ID='Mageia'
# DISTRIB_ID=Fedora
# DISTRIB_RELEASE='10.10'
# DISTRIB_CODENAME='squeeze'
# DISTRIB_DESCRIPTION='Ubuntu 10.10'
_LSB_REGEX = re.compile(
(
"^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:'|\")?"
"([\\w\\s\\.\\-_]+)(?:'|\")?"
)
)
def _linux_bin_exists(binary):
for search_cmd in ("which", "type -ap"):
try:
return __salt__["cmd.retcode"]("{0} {1}".format(search_cmd, binary)) == 0
except salt.exceptions.CommandExecutionError:
pass
try:
return (
len(
__salt__["cmd.run_all"]("whereis -b {0}".format(binary))[
"stdout"
].split()
)
> 1
)
except salt.exceptions.CommandExecutionError:
return False
def _parse_lsb_release():
ret = {}
try:
log.trace("Attempting to parse /etc/lsb-release")
with salt.utils.files.fopen("/etc/lsb-release") as ifile:
for line in ifile:
try:
key, value = _LSB_REGEX.match(line.rstrip("\n")).groups()[:2]
except AttributeError:
pass
else:
# Adds lsb_distrib_{id,release,codename,description}
ret["lsb_{0}".format(key.lower())] = value.rstrip()
except (IOError, OSError) as exc:
log.trace("Failed to parse /etc/lsb-release: %s", exc)
return ret
def _parse_os_release(*os_release_files):
ret = {}
for filename in os_release_files:
try:
with salt.utils.files.fopen(filename) as ifile:
regex = re.compile("^([\\w]+)=(?:'|\")?(.*?)(?:'|\")?$")
for line in ifile:
match = regex.match(line.strip())
if match:
# Shell special characters ("$", quotes, backslash,
# backtick) are escaped with backslashes
ret[match.group(1)] = re.sub(
r'\\([$"\'\\`])', r"\1", match.group(2)
)
break
except (IOError, OSError):
pass
return ret
def _parse_cpe_name(cpe):
part = {
"o": "operating system",
"h": "hardware",
"a": "application",
}
ret = {}
cpe = (cpe or "").split(":")
if len(cpe) > 4 and cpe[0] == "cpe":
if cpe[1].startswith("/"): # WFN to URI
ret["vendor"], ret["product"], ret["version"] = cpe[2:5]
ret["phase"] = cpe[5] if len(cpe) > 5 else None
ret["part"] = part.get(cpe[1][1:])
elif len(cpe) == 6 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"] = [
x if x != "*" else None for x in cpe[3:6]
]
ret["phase"] = None
ret["part"] = part.get(cpe[2])
elif len(cpe) > 7 and len(cpe) <= 13 and cpe[1] == "2.3": # WFN to a string
ret["vendor"], ret["product"], ret["version"], ret["phase"] = [
x if x != "*" else None for x in cpe[3:7]
]
ret["part"] = part.get(cpe[2])
return ret
def os_data():
grains = {
"num_gpus": 0,
"gpus": [],
}
# Windows Server 2008 64-bit
# ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64',
# 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel')
# Ubuntu 10.04
# ('Linux', 'MINIONNAME', '2.6.32-38-server',
# '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '')
# pylint: disable=unpacking-non-sequence
(
grains["kernel"],
grains["nodename"],
grains["kernelrelease"],
grains["kernelversion"],
grains["cpuarch"],
_,
) = platform.uname()
# pylint: enable=unpacking-non-sequence
if salt.utils.platform.is_proxy():
grains["kernel"] = "proxy"
grains["kernelrelease"] = "proxy"
grains["kernelversion"] = "proxy"
grains["osrelease"] = "proxy"
grains["os"] = "proxy"
grains["os_family"] = "proxy"
grains["osfullname"] = "proxy"
elif salt.utils.platform.is_windows():
grains["os"] = "Windows"
grains["os_family"] = "Windows"
grains.update(_memdata(grains))
grains.update(_windows_platform_data())
grains.update(_windows_cpudata())
grains.update(_windows_virtual(grains))
grains.update(_ps(grains))
if "Server" in grains["osrelease"]:
osrelease_info = grains["osrelease"].split("Server", 1)
osrelease_info[1] = osrelease_info[1].lstrip("R")
else:
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
grains["osfinger"] = "{os}-{ver}".format(
os=grains["os"], ver=grains["osrelease"]
)
grains["init"] = "Windows"
return grains
elif salt.utils.platform.is_linux():
# Add SELinux grain, if you have it
if _linux_bin_exists("selinuxenabled"):
log.trace("Adding selinux grains")
grains["selinux"] = {}
grains["selinux"]["enabled"] = (
__salt__["cmd.retcode"]("selinuxenabled") == 0
)
if _linux_bin_exists("getenforce"):
grains["selinux"]["enforced"] = __salt__["cmd.run"](
"getenforce"
).strip()
# Add systemd grain, if you have it
if _linux_bin_exists("systemctl") and _linux_bin_exists("localectl"):
log.trace("Adding systemd grains")
grains["systemd"] = {}
systemd_info = __salt__["cmd.run"]("systemctl --version").splitlines()
grains["systemd"]["version"] = systemd_info[0].split()[1]
grains["systemd"]["features"] = systemd_info[1]
# Add init grain
grains["init"] = "unknown"
log.trace("Adding init grain")
try:
os.stat("/run/systemd/system")
grains["init"] = "systemd"
except (OSError, IOError):
try:
with salt.utils.files.fopen("/proc/1/cmdline") as fhr:
init_cmdline = fhr.read().replace("\x00", " ").split()
except (IOError, OSError):
pass
else:
try:
init_bin = salt.utils.path.which(init_cmdline[0])
except IndexError:
# Emtpy init_cmdline
init_bin = None
log.warning("Unable to fetch data from /proc/1/cmdline")
if init_bin is not None and init_bin.endswith("bin/init"):
supported_inits = (b"upstart", b"sysvinit", b"systemd")
edge_len = max(len(x) for x in supported_inits) - 1
try:
buf_size = __opts__["file_buffer_size"]
except KeyError:
# Default to the value of file_buffer_size for the minion
buf_size = 262144
try:
with salt.utils.files.fopen(init_bin, "rb") as fp_:
edge = b""
buf = fp_.read(buf_size).lower()
while buf:
buf = edge + buf
for item in supported_inits:
if item in buf:
if six.PY3:
item = item.decode("utf-8")
grains["init"] = item
buf = b""
break
edge = buf[-edge_len:]
buf = fp_.read(buf_size).lower()
except (IOError, OSError) as exc:
log.error(
"Unable to read from init_bin (%s): %s", init_bin, exc
)
elif salt.utils.path.which("supervisord") in init_cmdline:
grains["init"] = "supervisord"
elif salt.utils.path.which("dumb-init") in init_cmdline:
# https://github.com/Yelp/dumb-init
grains["init"] = "dumb-init"
elif salt.utils.path.which("tini") in init_cmdline:
# https://github.com/krallin/tini
grains["init"] = "tini"
elif init_cmdline == ["runit"]:
grains["init"] = "runit"
elif "/sbin/my_init" in init_cmdline:
# Phusion Base docker container use runit for srv mgmt, but
# my_init as pid1
grains["init"] = "runit"
else:
log.debug(
"Could not determine init system from command line: (%s)",
" ".join(init_cmdline),
)
# Add lsb grains on any distro with lsb-release. Note that this import
# can fail on systems with lsb-release installed if the system package
# does not install the python package for the python interpreter used by
# Salt (i.e. python2 or python3)
try:
log.trace("Getting lsb_release distro information")
import lsb_release # pylint: disable=import-error
release = lsb_release.get_distro_information()
for key, value in six.iteritems(release):
key = key.lower()
lsb_param = "lsb_{0}{1}".format(
"" if key.startswith("distrib_") else "distrib_", key
)
grains[lsb_param] = value
# Catch a NameError to workaround possible breakage in lsb_release
# See https://github.com/saltstack/salt/issues/37867
except (ImportError, NameError):
# if the python library isn't available, try to parse
# /etc/lsb-release using regex
log.trace("lsb_release python bindings not available")
grains.update(_parse_lsb_release())
if grains.get("lsb_distrib_description", "").lower().startswith("antergos"):
# Antergos incorrectly configures their /etc/lsb-release,
# setting the DISTRIB_ID to "Arch". This causes the "os" grain
# to be incorrectly set to "Arch".
grains["osfullname"] = "Antergos Linux"
elif "lsb_distrib_id" not in grains:
log.trace("Failed to get lsb_distrib_id, trying to parse os-release")
os_release = _parse_os_release("/etc/os-release", "/usr/lib/os-release")
if os_release:
if "NAME" in os_release:
grains["lsb_distrib_id"] = os_release["NAME"].strip()
if "VERSION_ID" in os_release:
grains["lsb_distrib_release"] = os_release["VERSION_ID"]
if "VERSION_CODENAME" in os_release:
grains["lsb_distrib_codename"] = os_release["VERSION_CODENAME"]
elif "PRETTY_NAME" in os_release:
codename = os_release["PRETTY_NAME"]
# https://github.com/saltstack/salt/issues/44108
if os_release["ID"] == "debian":
codename_match = re.search(r"\((\w+)\)$", codename)
if codename_match:
codename = codename_match.group(1)
grains["lsb_distrib_codename"] = codename
if "CPE_NAME" in os_release:
cpe = _parse_cpe_name(os_release["CPE_NAME"])
if not cpe:
log.error("Broken CPE_NAME format in /etc/os-release!")
elif cpe.get("vendor", "").lower() in ["suse", "opensuse"]:
grains["os"] = "SUSE"
# openSUSE `osfullname` grain normalization
if os_release.get("NAME") == "openSUSE Leap":
grains["osfullname"] = "Leap"
elif os_release.get("VERSION") == "Tumbleweed":
grains["osfullname"] = os_release["VERSION"]
# Override VERSION_ID, if CPE_NAME around
if (
cpe.get("version") and cpe.get("vendor") == "opensuse"
): # Keep VERSION_ID for SLES
grains["lsb_distrib_release"] = cpe["version"]
elif os.path.isfile("/etc/SuSE-release"):
log.trace("Parsing distrib info from /etc/SuSE-release")
grains["lsb_distrib_id"] = "SUSE"
version = ""
patch = ""
with salt.utils.files.fopen("/etc/SuSE-release") as fhr:
for line in fhr:
if "enterprise" in line.lower():
grains["lsb_distrib_id"] = "SLES"
grains["lsb_distrib_codename"] = re.sub(
r"\(.+\)", "", line
).strip()
elif "version" in line.lower():
version = re.sub(r"[^0-9]", "", line)
elif "patchlevel" in line.lower():
patch = re.sub(r"[^0-9]", "", line)
grains["lsb_distrib_release"] = version
if patch:
grains["lsb_distrib_release"] += "." + patch
patchstr = "SP" + patch
if (
grains["lsb_distrib_codename"]
and patchstr not in grains["lsb_distrib_codename"]
):
grains["lsb_distrib_codename"] += " " + patchstr
if not grains.get("lsb_distrib_codename"):
grains["lsb_distrib_codename"] = "n.a"
elif os.path.isfile("/etc/altlinux-release"):
log.trace("Parsing distrib info from /etc/altlinux-release")
# ALT Linux
grains["lsb_distrib_id"] = "altlinux"
with salt.utils.files.fopen("/etc/altlinux-release") as ifile:
# This file is symlinked to from:
# /etc/fedora-release
# /etc/redhat-release
# /etc/system-release
for line in ifile:
# ALT Linux Sisyphus (unstable)
comps = line.split()
if comps[0] == "ALT":
grains["lsb_distrib_release"] = comps[2]
grains["lsb_distrib_codename"] = (
comps[3].replace("(", "").replace(")", "")
)
elif os.path.isfile("/etc/centos-release"):
log.trace("Parsing distrib info from /etc/centos-release")
# CentOS Linux
grains["lsb_distrib_id"] = "CentOS"
with salt.utils.files.fopen("/etc/centos-release") as ifile:
for line in ifile:
# Need to pull out the version and codename
# in the case of custom content in /etc/centos-release
find_release = re.compile(r"\d+\.\d+")
find_codename = re.compile(r"(?<=\()(.*?)(?=\))")
release = find_release.search(line)
codename = find_codename.search(line)
if release is not None:
grains["lsb_distrib_release"] = release.group()
if codename is not None:
grains["lsb_distrib_codename"] = codename.group()
elif os.path.isfile("/etc.defaults/VERSION") and os.path.isfile(
"/etc.defaults/synoinfo.conf"
):
grains["osfullname"] = "Synology"
log.trace(
"Parsing Synology distrib info from /etc/.defaults/VERSION"
)
with salt.utils.files.fopen("/etc.defaults/VERSION", "r") as fp_:
synoinfo = {}
for line in fp_:
try:
key, val = line.rstrip("\n").split("=")
except ValueError:
continue
if key in ("majorversion", "minorversion", "buildnumber"):
synoinfo[key] = val.strip('"')
if len(synoinfo) != 3:
log.warning(
"Unable to determine Synology version info. "
"Please report this, as it is likely a bug."
)
else:
grains[
"osrelease"
] = "{majorversion}.{minorversion}-{buildnumber}".format(
**synoinfo
)
log.trace(
"Getting OS name, release, and codename from distro id, version, codename"
)
(osname, osrelease, oscodename) = [
x.strip('"').strip("'") for x in _linux_distribution()
]
# Try to assign these three names based on the lsb info, they tend to
# be more accurate than what python gets from /etc/DISTRO-release.
# It's worth noting that Ubuntu has patched their Python distribution
# so that linux_distribution() does the /etc/lsb-release parsing, but
# we do it anyway here for the sake for full portability.
if "osfullname" not in grains:
# If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt'
if grains.get("lsb_distrib_id", "").lower().startswith("nilrt"):
grains["osfullname"] = "nilrt"
else:
grains["osfullname"] = grains.get("lsb_distrib_id", osname).strip()
if "osrelease" not in grains:
# NOTE: This is a workaround for CentOS 7 os-release bug
# https://bugs.centos.org/view.php?id=8359
# /etc/os-release contains no minor distro release number so we fall back to parse
# /etc/centos-release file instead.
# Commit introducing this comment should be reverted after the upstream bug is released.
# This also affects Centos 8
if any(
os in grains.get("lsb_distrib_codename", "")
for os in ["CentOS Linux 7", "CentOS Linux 8"]
):
grains.pop("lsb_distrib_release", None)
grains["osrelease"] = grains.get("lsb_distrib_release", osrelease).strip()
grains["oscodename"] = (
grains.get("lsb_distrib_codename", "").strip() or oscodename
)
if "Red Hat" in grains["oscodename"]:
grains["oscodename"] = oscodename
distroname = _REPLACE_LINUX_RE.sub("", grains["osfullname"]).strip()
# return the first ten characters with no spaces, lowercased
shortname = distroname.replace(" ", "").lower()[:10]
# this maps the long names from the /etc/DISTRO-release files to the
# traditional short names that Salt has used.
if "os" not in grains:
grains["os"] = _OS_NAME_MAP.get(shortname, distroname)
grains.update(_linux_cpudata())
grains.update(_linux_gpu_data())
elif grains["kernel"] == "SunOS":
if salt.utils.platform.is_smartos():
# See https://github.com/joyent/smartos-live/issues/224
if HAS_UNAME:
uname_v = os.uname()[3] # format: joyent_20161101T004406Z
else:
uname_v = os.name
uname_v = uname_v[uname_v.index("_") + 1 :]
grains["os"] = grains["osfullname"] = "SmartOS"
# store a parsed version of YYYY.MM.DD as osrelease
grains["osrelease"] = ".".join(
[
uname_v.split("T")[0][0:4],
uname_v.split("T")[0][4:6],
uname_v.split("T")[0][6:8],
]
)
# store a untouched copy of the timestamp in osrelease_stamp
grains["osrelease_stamp"] = uname_v
elif os.path.isfile("/etc/release"):
with salt.utils.files.fopen("/etc/release", "r") as fp_:
rel_data = fp_.read()
try:
release_re = re.compile(
r"((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?"
r"\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?"
)
(
osname,
development,
osmajorrelease,
osminorrelease,
) = release_re.search(rel_data).groups()
except AttributeError:
# Set a blank osrelease grain and fallback to 'Solaris'
# as the 'os' grain.
grains["os"] = grains["osfullname"] = "Solaris"
grains["osrelease"] = ""
else:
if development is not None:
osname = " ".join((osname, development))
if HAS_UNAME:
uname_v = os.uname()[3]
else:
uname_v = os.name
grains["os"] = grains["osfullname"] = osname
if osname in ["Oracle Solaris"] and uname_v.startswith(
osmajorrelease
):
# Oracla Solars 11 and up have minor version in uname
grains["osrelease"] = uname_v
elif osname in ["OmniOS"]:
# OmniOS
osrelease = []
osrelease.append(osmajorrelease[1:])
osrelease.append(osminorrelease[1:])
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
else:
# Sun Solaris 10 and earlier/comparable
osrelease = []
osrelease.append(osmajorrelease)
if osminorrelease:
osrelease.append(osminorrelease)
grains["osrelease"] = ".".join(osrelease)
grains["osrelease_stamp"] = uname_v
grains.update(_sunos_cpudata())
elif grains["kernel"] == "VMkernel":
grains["os"] = "ESXi"
elif grains["kernel"] == "Darwin":
osrelease = __salt__["cmd.run"]("sw_vers -productVersion")
osname = __salt__["cmd.run"]("sw_vers -productName")
osbuild = __salt__["cmd.run"]("sw_vers -buildVersion")
grains["os"] = "MacOS"
grains["os_family"] = "MacOS"
grains["osfullname"] = "{0} {1}".format(osname, osrelease)
grains["osrelease"] = osrelease
grains["osbuild"] = osbuild
grains["init"] = "launchd"
grains.update(_bsd_cpudata(grains))
grains.update(_osx_gpudata())
grains.update(_osx_platform_data())
elif grains["kernel"] == "AIX":
osrelease = __salt__["cmd.run"]("oslevel")
osrelease_techlevel = __salt__["cmd.run"]("oslevel -r")
osname = __salt__["cmd.run"]("uname")
grains["os"] = "AIX"
grains["osfullname"] = osname
grains["osrelease"] = osrelease
grains["osrelease_techlevel"] = osrelease_techlevel
grains.update(_aix_cpudata())
else:
grains["os"] = grains["kernel"]
if grains["kernel"] == "FreeBSD":
grains["osfullname"] = grains["os"]
try:
grains["osrelease"] = __salt__["cmd.run"]("freebsd-version -u").split("-")[
0
]
except salt.exceptions.CommandExecutionError:
# freebsd-version was introduced in 10.0.
# derive osrelease from kernelversion prior to that
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
grains.update(_bsd_cpudata(grains))
if grains["kernel"] in ("OpenBSD", "NetBSD"):
grains.update(_bsd_cpudata(grains))
grains["osrelease"] = grains["kernelrelease"].split("-")[0]
if grains["kernel"] == "NetBSD":
grains.update(_netbsd_gpu_data())
if not grains["os"]:
grains["os"] = "Unknown {0}".format(grains["kernel"])
grains["os_family"] = "Unknown"
else:
# this assigns family names based on the os name
# family defaults to the os name if not found
grains["os_family"] = _OS_FAMILY_MAP.get(grains["os"], grains["os"])
# Build the osarch grain. This grain will be used for platform-specific
# considerations such as package management. Fall back to the CPU
# architecture.
if grains.get("os_family") == "Debian":
osarch = __salt__["cmd.run"]("dpkg --print-architecture").strip()
elif grains.get("os_family") in ["RedHat", "Suse"]:
osarch = salt.utils.pkg.rpm.get_osarch()
elif grains.get("os_family") in ("NILinuxRT", "Poky"):
archinfo = {}
for line in __salt__["cmd.run"]("opkg print-architecture").splitlines():
if line.startswith("arch"):
_, arch, priority = line.split()
archinfo[arch.strip()] = int(priority.strip())
# Return osarch in priority order (higher to lower)
osarch = sorted(archinfo, key=archinfo.get, reverse=True)
else:
osarch = grains["cpuarch"]
grains["osarch"] = osarch
grains.update(_memdata(grains))
# Get the hardware and bios data
grains.update(_hw_data(grains))
# Load the virtual machine info
grains.update(_virtual(grains))
grains.update(_virtual_hv(grains))
grains.update(_ps(grains))
if grains.get("osrelease", ""):
osrelease_info = grains["osrelease"].split(".")
for idx, value in enumerate(osrelease_info):
if not value.isdigit():
continue
osrelease_info[idx] = int(value)
grains["osrelease_info"] = tuple(osrelease_info)
try:
grains["osmajorrelease"] = int(grains["osrelease_info"][0])
except (IndexError, TypeError, ValueError):
log.debug(
"Unable to derive osmajorrelease from osrelease_info '%s'. "
"The osmajorrelease grain will not be set.",
grains["osrelease_info"],
)
os_name = grains[
"os"
if grains.get("os")
in ("Debian", "FreeBSD", "OpenBSD", "NetBSD", "Mac", "Raspbian")
else "osfullname"
]
grains["osfinger"] = "{0}-{1}".format(
os_name,
grains["osrelease"]
if os_name in ("Ubuntu",)
else grains["osrelease_info"][0],
)
return grains
def locale_info():
grains = {}
grains["locale_info"] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains["locale_info"]["defaultlanguage"],
grains["locale_info"]["defaultencoding"],
) = locale.getdefaultlocale()
except Exception: # pylint: disable=broad-except
# locale.getdefaultlocale can ValueError!! Catch anything else it
# might do, per #2205
grains["locale_info"]["defaultlanguage"] = "unknown"
grains["locale_info"]["defaultencoding"] = "unknown"
grains["locale_info"]["detectedencoding"] = __salt_system_encoding__
grains["locale_info"]["timezone"] = "unknown"
if _DATEUTIL_TZ:
try:
grains["locale_info"]["timezone"] = datetime.datetime.now(
dateutil.tz.tzlocal()
).tzname()
except UnicodeDecodeError:
# Because the method 'tzname' is not a part of salt the decoding error cant be fixed.
# The error is in datetime in the python2 lib
if salt.utils.platform.is_windows():
grains["locale_info"]["timezone"] = time.tzname[0].decode("mbcs")
return grains
def hostname():
# This is going to need some work
# Provides:
# fqdn
# host
# localhost
# domain
global __FQDN__
grains = {}
if salt.utils.platform.is_proxy():
return grains
grains["localhost"] = socket.gethostname()
if __FQDN__ is None:
__FQDN__ = salt.utils.network.get_fqhostname()
# On some distros (notably FreeBSD) if there is no hostname set
# salt.utils.network.get_fqhostname() will return None.
# In this case we punt and log a message at error level, but force the
# hostname and domain to be localhost.localdomain
# Otherwise we would stacktrace below
if __FQDN__ is None: # still!
log.error(
"Having trouble getting a hostname. Does this machine have its hostname and domain set properly?"
)
__FQDN__ = "localhost.localdomain"
grains["fqdn"] = __FQDN__
(grains["host"], grains["domain"]) = grains["fqdn"].partition(".")[::2]
return grains
def append_domain():
grain = {}
if salt.utils.platform.is_proxy():
return grain
if "append_domain" in __opts__:
grain["append_domain"] = __opts__["append_domain"]
return grain
def fqdns():
# Provides:
# fqdns
opt = {"fqdns": []}
if __opts__.get(
"enable_fqdns_grains",
False
if salt.utils.platform.is_windows() or salt.utils.platform.is_proxy()
else True,
):
opt = __salt__["network.fqdns"]()
return opt
def ip_fqdn():
if salt.utils.platform.is_proxy():
return {}
ret = {}
ret["ipv4"] = salt.utils.network.ip_addrs(include_loopback=True)
ret["ipv6"] = salt.utils.network.ip_addrs6(include_loopback=True)
_fqdn = hostname()["fqdn"]
for socket_type, ipv_num in ((socket.AF_INET, "4"), (socket.AF_INET6, "6")):
key = "fqdn_ip" + ipv_num
if not ret["ipv" + ipv_num]:
ret[key] = []
else:
try:
start_time = datetime.datetime.utcnow()
info = socket.getaddrinfo(_fqdn, None, socket_type)
ret[key] = list(set(item[4][0] for item in info))
except (socket.error, UnicodeError):
timediff = datetime.datetime.utcnow() - start_time
if timediff.seconds > 5 and __opts__["__role"] == "master":
log.warning(
'Unable to find IPv%s record for "%s" causing a %s '
"second timeout when rendering grains. Set the dns or "
"/etc/hosts for IPv%s to clear this.",
ipv_num,
_fqdn,
timediff,
ipv_num,
)
ret[key] = []
return ret
def ip_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip_interfaces": ret}
def ip4_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip4_interfaces": ret}
def ip6_interfaces():
# Provides:
# ip_interfaces
if salt.utils.platform.is_proxy():
return {}
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
iface_ips = []
for inet in ifaces[face].get("inet6", []):
if "address" in inet:
iface_ips.append(inet["address"])
for secondary in ifaces[face].get("secondary", []):
if "address" in secondary:
iface_ips.append(secondary["address"])
ret[face] = iface_ips
return {"ip6_interfaces": ret}
def hwaddr_interfaces():
# Provides:
# hwaddr_interfaces
ret = {}
ifaces = _get_interfaces()
for face in ifaces:
if "hwaddr" in ifaces[face]:
ret[face] = ifaces[face]["hwaddr"]
return {"hwaddr_interfaces": ret}
def dns():
# Provides:
# dns
if salt.utils.platform.is_windows() or "proxyminion" in __opts__:
return {}
resolv = salt.utils.dns.parse_resolv()
for key in ("nameservers", "ip4_nameservers", "ip6_nameservers", "sortlist"):
if key in resolv:
resolv[key] = [six.text_type(i) for i in resolv[key]]
return {"dns": resolv} if resolv else {}
def get_machine_id():
# Provides:
# machine-id
if platform.system() == "AIX":
return _aix_get_machine_id()
locations = ["/etc/machine-id", "/var/lib/dbus/machine-id"]
existing_locations = [loc for loc in locations if os.path.exists(loc)]
if not existing_locations:
return {}
else:
with salt.utils.files.fopen(existing_locations[0]) as machineid:
return {"machine_id": machineid.read().strip()}
def cwd():
return {"cwd": os.getcwd()}
def path():
# Provides:
# path
# systempath
_path = salt.utils.stringutils.to_unicode(os.environ.get("PATH", "").strip())
return {
"path": _path,
"systempath": _path.split(os.path.pathsep),
}
def pythonversion():
# Provides:
# pythonversion
return {"pythonversion": list(sys.version_info)}
def pythonpath():
# Provides:
# pythonpath
return {"pythonpath": sys.path}
def pythonexecutable():
# Provides:
# pythonexecutable
return {"pythonexecutable": sys.executable}
def saltpath():
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {"saltpath": os.path.dirname(salt_path)}
def saltversion():
# Provides:
# saltversion
from salt.version import __version__
return {"saltversion": __version__}
def zmqversion():
# Provides:
# zmqversion
try:
import zmq
return {"zmqversion": zmq.zmq_version()} # pylint: disable=no-member
except ImportError:
return {}
def saltversioninfo():
# Provides:
# saltversioninfo
from salt.version import __version_info__
return {"saltversioninfo": list(__version_info__)}
def _hw_data(osdata):
if salt.utils.platform.is_proxy():
return {}
grains = {}
if osdata["kernel"] == "Linux" and os.path.exists("/sys/class/dmi/id"):
# On many Linux distributions basic firmware information is available via sysfs
# requires CONFIG_DMIID to be enabled in the Linux kernel configuration
sysfs_firmware_info = {
"biosversion": "bios_version",
"productname": "product_name",
"manufacturer": "sys_vendor",
"biosreleasedate": "bios_date",
"uuid": "product_uuid",
"serialnumber": "product_serial",
}
for key, fw_file in sysfs_firmware_info.items():
contents_file = os.path.join("/sys/class/dmi/id", fw_file)
if os.path.exists(contents_file):
try:
with salt.utils.files.fopen(contents_file, "r") as ifile:
grains[key] = salt.utils.stringutils.to_unicode(
ifile.read().strip(), errors="replace"
)
if key == "uuid":
grains["uuid"] = grains["uuid"].lower()
except UnicodeDecodeError:
# Some firmwares provide non-valid 'product_name'
# files, ignore them
log.debug(
"The content in /sys/devices/virtual/dmi/id/product_name is not valid"
)
except (IOError, OSError) as err:
# PermissionError is new to Python 3, but corresponds to the EACESS and
# EPERM error numbers. Use those instead here for PY2 compatibility.
if err.errno == EACCES or err.errno == EPERM:
# Skip the grain if non-root user has no access to the file.
pass
elif salt.utils.path.which_bin(["dmidecode", "smbios"]) is not None and not (
salt.utils.platform.is_smartos()
or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc")
)
):
# On SmartOS (possibly SunOS also) smbios only works in the global zone
# smbios is also not compatible with linux's smbios (smbios -s = print summarized)
grains = {
"biosversion": __salt__["smbios.get"]("bios-version"),
"productname": __salt__["smbios.get"]("system-product-name"),
"manufacturer": __salt__["smbios.get"]("system-manufacturer"),
"biosreleasedate": __salt__["smbios.get"]("bios-release-date"),
"uuid": __salt__["smbios.get"]("system-uuid"),
}
grains = dict([(key, val) for key, val in grains.items() if val is not None])
uuid = __salt__["smbios.get"]("system-uuid")
if uuid is not None:
grains["uuid"] = uuid.lower()
for serial in (
"system-serial-number",
"chassis-serial-number",
"baseboard-serial-number",
):
serial = __salt__["smbios.get"](serial)
if serial is not None:
grains["serialnumber"] = serial
break
elif salt.utils.path.which_bin(["fw_printenv"]) is not None:
# ARM Linux devices expose UBOOT env variables via fw_printenv
hwdata = {
"manufacturer": "manufacturer",
"serialnumber": "serial
"productname": "DeviceDesc",
}
for grain_name, cmd_key in six.iteritems(hwdata):
result = __salt__["cmd.run_all"]("fw_printenv {0}".format(cmd_key))
if result["retcode"] == 0:
uboot_keyval = result["stdout"].split("=")
grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
elif osdata["kernel"] == "FreeBSD":
# On FreeBSD /bin/kenv (already in base system)
# can be used instead of dmidecode
kenv = salt.utils.path.which("kenv")
if kenv:
# In theory, it will be easier to add new fields to this later
fbsd_hwdata = {
"biosversion": "smbios.bios.version",
"manufacturer": "smbios.system.maker",
"serialnumber": "smbios.system.serial",
"productname": "smbios.system.product",
"biosreleasedate": "smbios.bios.reldate",
"uuid": "smbios.system.uuid",
}
for key, val in six.iteritems(fbsd_hwdata):
value = __salt__["cmd.run"]("{0} {1}".format(kenv, val))
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "OpenBSD":
sysctl = salt.utils.path.which("sysctl")
hwdata = {
"biosversion": "hw.version",
"manufacturer": "hw.vendor",
"productname": "hw.product",
"serialnumber": "hw.serialno",
"uuid": "hw.uuid",
}
for key, oid in six.iteritems(hwdata):
value = __salt__["cmd.run"]("{0} -n {1}".format(sysctl, oid))
if not value.endswith(" value is not available"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "NetBSD":
sysctl = salt.utils.path.which("sysctl")
nbsd_hwdata = {
"biosversion": "machdep.dmi.board-version",
"manufacturer": "machdep.dmi.system-vendor",
"serialnumber": "machdep.dmi.system-serial",
"productname": "machdep.dmi.system-product",
"biosreleasedate": "machdep.dmi.bios-date",
"uuid": "machdep.dmi.system-uuid",
}
for key, oid in six.iteritems(nbsd_hwdata):
result = __salt__["cmd.run_all"]("{0} -n {1}".format(sysctl, oid))
if result["retcode"] == 0:
grains[key] = _clean_value(key, result["stdout"])
elif osdata["kernel"] == "Darwin":
grains["manufacturer"] = "Apple Inc."
sysctl = salt.utils.path.which("sysctl")
hwdata = {"productname": "hw.model"}
for key, oid in hwdata.items():
value = __salt__["cmd.run"]("{0} -b {1}".format(sysctl, oid))
if not value.endswith(" is invalid"):
grains[key] = _clean_value(key, value)
elif osdata["kernel"] == "SunOS" and osdata["cpuarch"].startswith("sparc"):
# Depending on the hardware model, commands can report different bits
# of information. With that said, consolidate the output from various
# commands and attempt various lookups.
data = ""
for (cmd, args) in (
("/usr/sbin/prtdiag", "-v"),
("/usr/sbin/prtconf", "-vp"),
("/usr/sbin/virtinfo", "-a"),
):
if salt.utils.path.which(cmd): # Also verifies that cmd is executable
data += __salt__["cmd.run"]("{0} {1}".format(cmd, args))
data += "\n"
sn_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?im)^\s*chassis-sn:\s*(\S+)", # prtconf
r"(?im)^\s*Chassis\s+Serial
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?im)^\s*Domain\s+UUID:\s*(\S+)"] # virtinfo
]
manufacture_regexes = [
re.compile(r)
for r in [r"(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)"] # prtdiag
]
product_regexes = [
re.compile(r)
for r in [
r"(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)", # prtdiag
r"(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)", # prtconf
r"(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)", # prtconf
]
]
sn_regexes = [
re.compile(r)
for r in [
r"(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)", # prtdiag
r"(?i)Chassis\s+Serial#:\s*(\S+)", # virtinfo
r"(?i)chassis-sn:\s*(\S+)", # prtconf
]
]
obp_regexes = [
re.compile(r)
for r in [
r"(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)", # prtdiag
r"(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)", # prtconf
]
]
fw_regexes = [
re.compile(r)
for r in [r"(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)"] # prtdiag
]
uuid_regexes = [
re.compile(r) for r in [r"(?i)Domain\s+UUID:\s+(\S+)"] # virtinfo
]
for regex in sn_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["serialnumber"] = res.group(1).strip().replace("'", "")
break
for regex in obp_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
obp_rev, obp_date = res.groups()[
0:2
] # Limit the number in case we found the data in multiple places
grains["biosversion"] = obp_rev.strip().replace("'", "")
grains["biosreleasedate"] = obp_date.strip().replace("'", "")
for regex in fw_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
fw_rev, fw_date = res.groups()[0:2]
grains["systemfirmware"] = fw_rev.strip().replace("'", "")
grains["systemfirmwaredate"] = fw_date.strip().replace("'", "")
break
for regex in uuid_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["uuid"] = res.group(1).strip().replace("'", "")
break
for regex in manufacture_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacture"] = res.group(1).strip().replace("'", "")
break
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
t_productname = res.group(1).strip().replace("'", "")
if t_productname:
grains["product"] = t_productname
grains["productname"] = t_productname
break
elif osdata["kernel"] == "AIX":
cmd = salt.utils.path.which("prtconf")
if cmd:
data = __salt__["cmd.run"]("{0}".format(cmd)) + os.linesep
for dest, regstring in (
("serialnumber", r"(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)"),
("systemfirmware", r"(?im)^\s*Firmware\s+Version:\s+(.*)"),
):
for regex in [re.compile(r) for r in [regstring]]:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains[dest] = res.group(1).strip().replace("'", "")
product_regexes = [re.compile(r"(?im)^\s*System\s+Model:\s+(\S+)")]
for regex in product_regexes:
res = regex.search(data)
if res and len(res.groups()) >= 1:
grains["manufacturer"], grains["productname"] = (
res.group(1).strip().replace("'", "").split(",")
)
break
else:
log.error("The 'prtconf' binary was not found in $PATH.")
return grains
def get_server_id():
# Provides:
# server_id
if salt.utils.platform.is_proxy():
return {}
id_ = __opts__.get("id", "")
hash_ = int(hashlib.sha256(id_.encode()).hexdigest(), 16)
return {"server_id": abs(hash_ % (2 ** 31))}
def get_master():
# Provides:
# master
return {"master": __opts__.get("master", "")}
def default_gateway():
grains = {}
ip_bin = salt.utils.path.which("ip")
if not ip_bin:
return {}
grains["ip_gw"] = False
grains["ip4_gw"] = False
grains["ip6_gw"] = False
for ip_version in ("4", "6"):
try:
out = __salt__["cmd.run"]([ip_bin, "-" + ip_version, "route", "show"])
for line in out.splitlines():
if line.startswith("default"):
grains["ip_gw"] = True
grains["ip{0}_gw".format(ip_version)] = True
try:
via, gw_ip = line.split()[1:3]
except ValueError:
pass
else:
if via == "via":
grains["ip{0}_gw".format(ip_version)] = gw_ip
break
except Exception: # pylint: disable=broad-except
continue
return grains
def kernelparams():
try:
with salt.utils.files.fopen("/proc/cmdline", "r") as fhr:
cmdline = fhr.read()
grains = {"kernelparams": []}
for data in [
item.split("=") for item in salt.utils.args.shlex_split(cmdline)
]:
value = None
if len(data) == 2:
value = data[1].strip('"')
grains["kernelparams"] += [(data[0], value)]
except IOError as exc:
grains = {}
log.debug("Failed to read /proc/cmdline: %s", exc)
return grains
| true | true |
f72c39d04f46b4659fec28e1537a34671c4a461f | 439 | py | Python | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | 1 | 2020-02-07T17:38:14.000Z | 2020-02-07T17:38:14.000Z | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | null | null | null | people/templatetags/people_extras.py | hayatbayramolsa/website | 22a00a1de8b5902c559e4b48df27fa5c1329f16a | [
"WTFPL"
] | null | null | null | from django import template
register = template.Library()
def fontawesome(icon_name, size=""):
"""
Generate fontawesome syntax for HTML.
Usage:
{% fontawesome "iconname" %}
{% fontawesome "iconname" "size" %}
Size values are: lg, 2x, 3x, 4x, 5x
"""
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i>' % (icon_name, size)
register.simple_tag(fontawesome)
| 19.086957 | 60 | 0.587699 | from django import template
register = template.Library()
def fontawesome(icon_name, size=""):
if len(size) > 0:
size = "fa-%s" % size
return '<i class="fa fa-%s %s"></i>' % (icon_name, size)
register.simple_tag(fontawesome)
| true | true |
f72c3a32e58db3f2d9a4b04faa87382ae4209bcf | 314 | py | Python | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null | symarray/symarray/calculus/tests/test_arrays.py | tonyfast/uarray | 72fe4a0b86b26208747c95c828c66b8284d435d4 | [
"BSD-3-Clause"
] | null | null | null |
from symarray.calculus.integers import Integer
from symarray.calculus.arrays import Array
from symarray.shape import NDShape
def test_basic():
a = Array('a')
b = Array('b', shape=NDShape((Integer('n1'), Integer('n2'))))
n = Integer('n')
expr = a+n*a+2+b
print(expr.shape)
print(expr[1])
| 22.428571 | 65 | 0.659236 |
from symarray.calculus.integers import Integer
from symarray.calculus.arrays import Array
from symarray.shape import NDShape
def test_basic():
a = Array('a')
b = Array('b', shape=NDShape((Integer('n1'), Integer('n2'))))
n = Integer('n')
expr = a+n*a+2+b
print(expr.shape)
print(expr[1])
| true | true |
f72c3ac1f20334925f3e4c702afd2d9868b7b904 | 3,221 | py | Python | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | u-tokyo/2018-summer/dataset.py | PandaDrunkard/proex | c303f051721d9f271d8187957a4458dc5f4558b1 | [
"MIT"
] | null | null | null | import math
def load_image(filename, append_index=False):
content = [line.strip().split(' ') for line in open(filename)][0]
r = list(map(int, content[0::3]))
g = list(map(int, content[1::3]))
b = list(map(int, content[2::3]))
if append_index:
return list(zip(r,g,b,range(len(r))))
else:
return list(zip(r,g,b,))
WHITE=tuple([255,255,255])
def format_image(raw):
formated = [[]]
for i, element in enumerate(raw):
if element[:3] == WHITE:
subset = raw[i::i+1]
is_white_line = (len(subset) > 2)
for sub in raw[i::i+1]:
if sub[:3] != WHITE:
is_white_line = False
break
if is_white_line:
formated.append([])
else:
formated[-1].append(element)
else:
formated[-1].append(element)
formated = formated[:-1]
return formated
def format_square(raw):
size = len(raw)
w = int(math.sqrt(size))
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def width(raw):
size = len(raw)
for i in range(1, size//2):
rgb = raw[i][:3]
if rgb == WHITE:
subset = raw[i::i+1]
# print(f'{(i+1)}: {subset[:5]}')
is_white = map(lambda subelm: subelm[:3]==WHITE, subset)
if all(is_white):
return i+1
return -1
def format_image2(raw):
w = width(raw)
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def test(append_index=False):
return load_image('./test.txt', append_index=append_index)
def image1(append_index=False):
return load_image('./image1.txt', append_index=append_index)
def image2(append_index=False):
return load_image('./image2.txt', append_index=append_index)
def image3(append_index=False):
return load_image('./image3.txt', append_index=append_index)
TIF_HEADER_ARRAY=[
77,77, 0,42, 0, 0, 0, 8, 0, 7, 1, 0, 0, 4, 0, 0,
0, 1, 0, 0, 0, 0, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0,
0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0,98, 1, 6,
0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1,17, 0, 4, 0, 0,
0, 1, 0, 0, 0,104, 1,21, 0, 3, 0, 0, 0, 1, 0, 3,
0, 0, 1,23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8, 0, 8, 0, 8
]
def save_image(filename, image):
hight = len(image)
width = len(image[0])
b_hight = (hight).to_bytes(4, byteorder='big')
b_width = (width).to_bytes(4, byteorder='big')
b_s = (hight*width*3).to_bytes(4, byteorder='big')
# set hight/width/s
header = TIF_HEADER_ARRAY[:]
for i in range(4):
header[18 + i] = b_width[i]
header[30 + i] = b_hight[i]
header[90 + i] = b_s[i]
b_header = bytes(header)
content = []
for r in range(hight):
for c in range(width):
content += list(image[r][c][:3])
b_content = bytes(content)
with open(filename, 'wb') as out:
out.write(b_header)
out.write(b_content) | 30.386792 | 69 | 0.535548 | import math
def load_image(filename, append_index=False):
content = [line.strip().split(' ') for line in open(filename)][0]
r = list(map(int, content[0::3]))
g = list(map(int, content[1::3]))
b = list(map(int, content[2::3]))
if append_index:
return list(zip(r,g,b,range(len(r))))
else:
return list(zip(r,g,b,))
WHITE=tuple([255,255,255])
def format_image(raw):
formated = [[]]
for i, element in enumerate(raw):
if element[:3] == WHITE:
subset = raw[i::i+1]
is_white_line = (len(subset) > 2)
for sub in raw[i::i+1]:
if sub[:3] != WHITE:
is_white_line = False
break
if is_white_line:
formated.append([])
else:
formated[-1].append(element)
else:
formated[-1].append(element)
formated = formated[:-1]
return formated
def format_square(raw):
size = len(raw)
w = int(math.sqrt(size))
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def width(raw):
size = len(raw)
for i in range(1, size//2):
rgb = raw[i][:3]
if rgb == WHITE:
subset = raw[i::i+1]
is_white = map(lambda subelm: subelm[:3]==WHITE, subset)
if all(is_white):
return i+1
return -1
def format_image2(raw):
w = width(raw)
formatted = []
for i in range(len(raw) // w):
formatted.append([])
for j in range(w):
formatted[-1].append(raw[i*w + j])
return formatted
def test(append_index=False):
return load_image('./test.txt', append_index=append_index)
def image1(append_index=False):
return load_image('./image1.txt', append_index=append_index)
def image2(append_index=False):
return load_image('./image2.txt', append_index=append_index)
def image3(append_index=False):
return load_image('./image3.txt', append_index=append_index)
TIF_HEADER_ARRAY=[
77,77, 0,42, 0, 0, 0, 8, 0, 7, 1, 0, 0, 4, 0, 0,
0, 1, 0, 0, 0, 0, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0,
0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0,98, 1, 6,
0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1,17, 0, 4, 0, 0,
0, 1, 0, 0, 0,104, 1,21, 0, 3, 0, 0, 0, 1, 0, 3,
0, 0, 1,23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8, 0, 8, 0, 8
]
def save_image(filename, image):
hight = len(image)
width = len(image[0])
b_hight = (hight).to_bytes(4, byteorder='big')
b_width = (width).to_bytes(4, byteorder='big')
b_s = (hight*width*3).to_bytes(4, byteorder='big')
header = TIF_HEADER_ARRAY[:]
for i in range(4):
header[18 + i] = b_width[i]
header[30 + i] = b_hight[i]
header[90 + i] = b_s[i]
b_header = bytes(header)
content = []
for r in range(hight):
for c in range(width):
content += list(image[r][c][:3])
b_content = bytes(content)
with open(filename, 'wb') as out:
out.write(b_header)
out.write(b_content) | true | true |
f72c3b061208c98f8b6103c531da45e38011c75c | 92,091 | py | Python | pandas/util/testing.py | mimikaTU/pandas | 573d4e7e1b354e7ee0cb12280ec58835207106ea | [
"BSD-3-Clause"
] | 1 | 2020-01-18T09:57:03.000Z | 2020-01-18T09:57:03.000Z | pandas/util/testing.py | Kaya176/pandas | 4fb963b6a3261940de5891323a8d217087a2a9a1 | [
"BSD-3-Clause"
] | 1 | 2018-03-22T16:06:03.000Z | 2018-03-22T16:06:03.000Z | pandas/util/testing.py | Kaya176/pandas | 4fb963b6a3261940de5891323a8d217087a2a9a1 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import division
# pylint: disable-msg=W0402
import re
import string
import sys
import tempfile
import warnings
import inspect
import os
import subprocess
import locale
import traceback
from datetime import datetime
from functools import wraps
from contextlib import contextmanager
from numpy.random import randn, rand
import numpy as np
import pandas as pd
from pandas.core.arrays import ExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas.core.dtypes.common import (
is_datetimelike_v_numeric,
is_datetimelike_v_object,
is_number, is_bool,
needs_i8_conversion,
is_categorical_dtype,
is_interval_dtype,
is_sequence,
is_list_like)
from pandas.io.formats.printing import pprint_thing
from pandas.core.algorithms import take_1d
import pandas.core.common as com
import pandas.compat as compat
from pandas.compat import (
filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
raise_with_traceback, httplib, StringIO, PY3)
from pandas import (bdate_range, CategoricalIndex, Categorical, IntervalIndex,
DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex,
Index, MultiIndex,
Series, DataFrame, Panel)
from pandas._libs import testing as _testing
from pandas.io.common import urlopen
N = 30
K = 4
_RAISE_NETWORK_ERROR_DEFAULT = False
# set testing_mode
_testing_mode_warnings = (DeprecationWarning, compat.ResourceWarning)
def set_testing_mode():
# set the testing mode filters
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('always', _testing_mode_warnings)
def reset_testing_mode():
# reset the testing mode filters
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('ignore', _testing_mode_warnings)
set_testing_mode()
def reset_display_options():
"""
Reset the display options for printing and representing objects.
"""
pd.reset_option('^display.', silent=True)
def round_trip_pickle(obj, path=None):
"""
Pickle an object and then read it again.
Parameters
----------
obj : pandas object
The object to pickle and then re-read.
path : str, default None
The path where the pickled object is written and then read.
Returns
-------
round_trip_pickled_object : pandas object
The original object that was pickled and then re-read.
"""
if path is None:
path = u('__{random_bytes}__.pickle'.format(random_bytes=rands(10)))
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.read_pickle(path)
def round_trip_pathlib(writer, reader, path=None):
"""
Write an object to file specified by a pathlib.Path and read it back
Parameters
----------
writer : callable bound to pandas object
IO writing function (e.g. DataFrame.to_csv )
reader : callable
IO reading function (e.g. pd.read_csv )
path : str, default None
The path where the object is written and then read.
Returns
-------
round_trip_object : pandas object
The original object that was serialized and then re-read.
"""
import pytest
Path = pytest.importorskip('pathlib').Path
if path is None:
path = '___pathlib___'
with ensure_clean(path) as path:
writer(Path(path))
obj = reader(Path(path))
return obj
def round_trip_localpath(writer, reader, path=None):
"""
Write an object to file specified by a py.path LocalPath and read it back
Parameters
----------
writer : callable bound to pandas object
IO writing function (e.g. DataFrame.to_csv )
reader : callable
IO reading function (e.g. pd.read_csv )
path : str, default None
The path where the object is written and then read.
Returns
-------
round_trip_object : pandas object
The original object that was serialized and then re-read.
"""
import pytest
LocalPath = pytest.importorskip('py.path').local
if path is None:
path = '___localpath___'
with ensure_clean(path) as path:
writer(LocalPath(path))
obj = reader(LocalPath(path))
return obj
@contextmanager
def decompress_file(path, compression):
"""
Open a compressed file and return a file object
Parameters
----------
path : str
The path where the file is read from
compression : {'gzip', 'bz2', 'zip', 'xz', None}
Name of the decompression to use
Returns
-------
f : file object
"""
if compression is None:
f = open(path, 'rb')
elif compression == 'gzip':
import gzip
f = gzip.open(path, 'rb')
elif compression == 'bz2':
import bz2
f = bz2.BZ2File(path, 'rb')
elif compression == 'xz':
lzma = compat.import_lzma()
f = lzma.LZMAFile(path, 'rb')
elif compression == 'zip':
import zipfile
zip_file = zipfile.ZipFile(path)
zip_names = zip_file.namelist()
if len(zip_names) == 1:
f = zip_file.open(zip_names.pop())
else:
raise ValueError('ZIP file {} error. Only one file per ZIP.'
.format(path))
else:
msg = 'Unrecognized compression type: {}'.format(compression)
raise ValueError(msg)
yield f
f.close()
def assert_almost_equal(left, right, check_exact=False,
check_dtype='equiv', check_less_precise=False,
**kwargs):
"""
Check that the left and right objects are approximately equal.
Parameters
----------
left : object
right : object
check_exact : bool, default False
Whether to compare number exactly.
check_dtype: bool, default True
check dtype if both a and b are the same type
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
"""
if isinstance(left, pd.Index):
return assert_index_equal(left, right, check_exact=check_exact,
exact=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.Series):
return assert_series_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.DataFrame):
return assert_frame_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
else:
# other sequences
if check_dtype:
if is_number(left) and is_number(right):
# do not compare numeric classes, like np.float64 and float
pass
elif is_bool(left) and is_bool(right):
# do not compare bool classes, like np.bool_ and bool
pass
else:
if (isinstance(left, np.ndarray) or
isinstance(right, np.ndarray)):
obj = 'numpy array'
else:
obj = 'Input'
assert_class_equal(left, right, obj=obj)
return _testing.assert_almost_equal(
left, right,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
def _check_isinstance(left, right, cls):
"""
Helper method for our assert_* methods that ensures that
the two objects being compared have the right type before
proceeding with the comparison.
Parameters
----------
left : The first object being compared.
right : The second object being compared.
cls : The class type to check against.
Raises
------
AssertionError : Either `left` or `right` is not an instance of `cls`.
"""
err_msg = "{name} Expected type {exp_type}, found {act_type} instead"
cls_name = cls.__name__
if not isinstance(left, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(left)))
if not isinstance(right, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(right)))
def assert_dict_equal(left, right, compare_keys=True):
_check_isinstance(left, right, dict)
return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
def randbool(size=(), p=0.5):
return rand(*size) <= p
RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),
dtype=(np.str_, 1))
RANDU_CHARS = np.array(list(u("").join(map(unichr, lrange(1488, 1488 + 26))) +
string.digits), dtype=(np.unicode_, 1))
def rands_array(nchars, size, dtype='O'):
"""Generate an array of byte strings."""
retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
.view((np.str_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def randu_array(nchars, size, dtype='O'):
"""Generate an array of unicode strings."""
retval = (np.random.choice(RANDU_CHARS, size=nchars * np.prod(size))
.view((np.unicode_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def rands(nchars):
"""
Generate one random byte string.
See `rands_array` if you want to create an array of random strings.
"""
return ''.join(np.random.choice(RANDS_CHARS, nchars))
def randu(nchars):
"""
Generate one random unicode string.
See `randu_array` if you want to create an array of random unicode strings.
"""
return ''.join(np.random.choice(RANDU_CHARS, nchars))
def close(fignum=None):
from matplotlib.pyplot import get_fignums, close as _close
if fignum is None:
for fignum in get_fignums():
_close(fignum)
else:
_close(fignum)
# -----------------------------------------------------------------------------
# locale utilities
def check_output(*popenargs, **kwargs):
# shamelessly taken from Python 2.7 source
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
def _default_locale_getter():
try:
raw_locales = check_output(['locale -a'], shell=True)
except subprocess.CalledProcessError as e:
raise type(e)("{exception}, the 'locale -a' command cannot be found "
"on your system".format(exception=e))
return raw_locales
def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
"""Get all the locales that are available on the system.
Parameters
----------
prefix : str
If not ``None`` then return only those locales with the prefix
provided. For example to get all English language locales (those that
start with ``"en"``), pass ``prefix="en"``.
normalize : bool
Call ``locale.normalize`` on the resulting list of available locales.
If ``True``, only locales that can be set without throwing an
``Exception`` are returned.
locale_getter : callable
The function to use to retrieve the current locales. This should return
a string with each locale separated by a newline character.
Returns
-------
locales : list of strings
A list of locale strings that can be set with ``locale.setlocale()``.
For example::
locale.setlocale(locale.LC_ALL, locale_string)
On error will return None (no locale available, e.g. Windows)
"""
try:
raw_locales = locale_getter()
except Exception:
return None
try:
# raw_locales is "\n" separated list of locales
# it may contain non-decodable parts, so split
# extract what we can and then rejoin.
raw_locales = raw_locales.split(b'\n')
out_locales = []
for x in raw_locales:
if PY3:
out_locales.append(str(
x, encoding=pd.options.display.encoding))
else:
out_locales.append(str(x))
except TypeError:
pass
if prefix is None:
return _valid_locales(out_locales, normalize)
found = re.compile('{prefix}.*'.format(prefix=prefix)) \
.findall('\n'.join(out_locales))
return _valid_locales(found, normalize)
@contextmanager
def set_locale(new_locale, lc_var=locale.LC_ALL):
"""Context manager for temporarily setting a locale.
Parameters
----------
new_locale : str or tuple
A string of the form <language_country>.<encoding>. For example to set
the current locale to US English with a UTF8 encoding, you would pass
"en_US.UTF-8".
Notes
-----
This is useful when you want to run a particular block of code under a
particular locale, without globally setting the locale. This probably isn't
thread-safe.
"""
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
try:
normalized_locale = locale.getlocale()
except ValueError:
yield new_locale
else:
if com._all_not_none(*normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.setlocale(lc_var, current_locale)
def _can_set_locale(lc):
"""Check to see if we can set a locale without throwing an exception.
Parameters
----------
lc : str
The locale to attempt to set.
Returns
-------
isvalid : bool
Whether the passed locale can be set
"""
try:
with set_locale(lc):
pass
except locale.Error: # horrible name for a Exception subclass
return False
else:
return True
def _valid_locales(locales, normalize):
"""Return a list of normalized locales that do not throw an ``Exception``
when set.
Parameters
----------
locales : str
A string where each locale is separated by a newline.
normalize : bool
Whether to call ``locale.normalize`` on each locale.
Returns
-------
valid_locales : list
A list of valid locales.
"""
if normalize:
normalizer = lambda x: locale.normalize(x.strip())
else:
normalizer = lambda x: x.strip()
return list(filter(_can_set_locale, map(normalizer, locales)))
# -----------------------------------------------------------------------------
# Stdout / stderr decorators
def capture_stdout(f):
"""
Decorator to capture stdout in a buffer so that it can be checked
(or suppressed) during testing.
Parameters
----------
f : callable
The test that is capturing stdout.
Returns
-------
f : callable
The decorated test ``f``, which captures stdout.
Examples
--------
>>> from pandas.util.testing import capture_stdout
>>>
>>> import sys
>>>
>>> @capture_stdout
... def test_print_pass():
... print("foo")
... out = sys.stdout.getvalue()
... assert out == "foo\n"
>>>
>>> @capture_stdout
... def test_print_fail():
... print("foo")
... out = sys.stdout.getvalue()
... assert out == "bar\n"
...
AssertionError: assert 'foo\n' == 'bar\n'
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stdout = StringIO()
f(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
return wrapper
def capture_stderr(f):
"""
Decorator to capture stderr in a buffer so that it can be checked
(or suppressed) during testing.
Parameters
----------
f : callable
The test that is capturing stderr.
Returns
-------
f : callable
The decorated test ``f``, which captures stderr.
Examples
--------
>>> from pandas.util.testing import capture_stderr
>>>
>>> import sys
>>>
>>> @capture_stderr
... def test_stderr_pass():
... sys.stderr.write("foo")
... out = sys.stderr.getvalue()
... assert out == "foo\n"
>>>
>>> @capture_stderr
... def test_stderr_fail():
... sys.stderr.write("foo")
... out = sys.stderr.getvalue()
... assert out == "bar\n"
...
AssertionError: assert 'foo\n' == 'bar\n'
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stderr = StringIO()
f(*args, **kwargs)
finally:
sys.stderr = sys.__stderr__
return wrapper
# -----------------------------------------------------------------------------
# Console debugging tools
def debug(f, *args, **kwargs):
from pdb import Pdb as OldPdb
try:
from IPython.core.debugger import Pdb
kw = dict(color_scheme='Linux')
except ImportError:
Pdb = OldPdb
kw = {}
pdb = Pdb(**kw)
return pdb.runcall(f, *args, **kwargs)
def pudebug(f, *args, **kwargs):
import pudb
return pudb.runcall(f, *args, **kwargs)
def set_trace():
from IPython.core.debugger import Pdb
try:
Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)
except Exception:
from pdb import Pdb as OldPdb
OldPdb().set_trace(sys._getframe().f_back)
# -----------------------------------------------------------------------------
# contextmanager to ensure the file cleanup
@contextmanager
def ensure_clean(filename=None, return_filelike=False):
"""Gets a temporary path and agrees to remove on close.
Parameters
----------
filename : str (optional)
if None, creates a temporary file which is then removed when out of
scope. if passed, creates temporary file with filename as ending.
return_filelike : bool (default False)
if True, returns a file-like which is *always* cleaned. Necessary for
savefig and other functions which want to append extensions.
"""
filename = filename or ''
fd = None
if return_filelike:
f = tempfile.TemporaryFile(suffix=filename)
try:
yield f
finally:
f.close()
else:
# don't generate tempfile if using a path with directory specified
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")
try:
fd, filename = tempfile.mkstemp(suffix=filename)
except UnicodeEncodeError:
import pytest
pytest.skip('no unicode file names on this system')
try:
yield filename
finally:
try:
os.close(fd)
except Exception as e:
print("Couldn't close file descriptor: {fdesc} (file: {fname})"
.format(fdesc=fd, fname=filename))
try:
if os.path.exists(filename):
os.remove(filename)
except Exception as e:
print("Exception on removing file: {error}".format(error=e))
def get_data_path(f=''):
"""Return the path of a data file, these are relative to the current test
directory.
"""
# get our callers file
_, filename, _, _, _, _ = inspect.getouterframes(inspect.currentframe())[1]
base_dir = os.path.abspath(os.path.dirname(filename))
return os.path.join(base_dir, 'data', f)
# -----------------------------------------------------------------------------
# Comparators
def equalContents(arr1, arr2):
"""Checks if the set of unique elements of arr1 and arr2 are equivalent.
"""
return frozenset(arr1) == frozenset(arr2)
def assert_index_equal(left, right, exact='equiv', check_names=True,
check_less_precise=False, check_exact=True,
check_categorical=True, obj='Index'):
"""Check that left and right Index are equal.
Parameters
----------
left : Index
right : Index
exact : bool / string {'equiv'}, default False
Whether to check the Index class, dtype and inferred_type
are identical. If 'equiv', then RangeIndex can be substituted for
Int64Index as well.
check_names : bool, default True
Whether to check the names attribute.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_exact : bool, default True
Whether to compare number exactly.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
obj : str, default 'Index'
Specify object name being compared, internally used to show appropriate
assertion message
"""
def _check_types(l, r, obj='Index'):
if exact:
assert_class_equal(left, right, exact=exact, obj=obj)
assert_attr_equal('dtype', l, r, obj=obj)
# allow string-like to have different inferred_types
if l.inferred_type in ('string', 'unicode'):
assert r.inferred_type in ('string', 'unicode')
else:
assert_attr_equal('inferred_type', l, r, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
unique = index.levels[level]
labels = index.labels[level]
filled = take_1d(unique.values, labels, fill_value=unique._na_value)
values = unique._shallow_copy(filled, name=index.names[level])
return values
# instance validation
_check_isinstance(left, right, Index)
# class / dtype comparison
_check_types(left, right, obj=obj)
# level comparison
if left.nlevels != right.nlevels:
msg1 = '{obj} levels are different'.format(obj=obj)
msg2 = '{nlevels}, {left}'.format(nlevels=left.nlevels, left=left)
msg3 = '{nlevels}, {right}'.format(nlevels=right.nlevels, right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# length comparison
if len(left) != len(right):
msg1 = '{obj} length are different'.format(obj=obj)
msg2 = '{length}, {left}'.format(length=len(left), left=left)
msg3 = '{length}, {right}'.format(length=len(right), right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
for level in range(left.nlevels):
# cannot use get_level_values here because it can change dtype
llevel = _get_ilevel_values(left, level)
rlevel = _get_ilevel_values(right, level)
lobj = 'MultiIndex level [{level}]'.format(level=level)
assert_index_equal(llevel, rlevel,
exact=exact, check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact, obj=lobj)
# get_level_values may change dtype
_check_types(left.levels[level], right.levels[level], obj=obj)
if check_exact:
if not left.equals(right):
diff = np.sum((left.values != right.values)
.astype(int)) * 100.0 / len(left)
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
else:
_testing.assert_almost_equal(left.values, right.values,
check_less_precise=check_less_precise,
check_dtype=exact,
obj=obj, lobj=left, robj=right)
# metadata comparison
if check_names:
assert_attr_equal('names', left, right, obj=obj)
if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex):
assert_attr_equal('freq', left, right, obj=obj)
if (isinstance(left, pd.IntervalIndex) or
isinstance(right, pd.IntervalIndex)):
assert_attr_equal('closed', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_class_equal(left, right, exact=True, obj='Input'):
"""checks classes are equal."""
def repr_class(x):
if isinstance(x, Index):
# return Index as it is to include values in the error message
return x
try:
return x.__class__.__name__
except AttributeError:
return repr(type(x))
if exact == 'equiv':
if type(left) != type(right):
# allow equivalence of Int64Index/RangeIndex
types = set([type(left).__name__, type(right).__name__])
if len(types - set(['Int64Index', 'RangeIndex'])):
msg = '{obj} classes are not equivalent'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
elif exact:
if type(left) != type(right):
msg = '{obj} classes are different'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
def assert_attr_equal(attr, left, right, obj='Attributes'):
"""checks attributes are equal. Both objects must have attribute.
Parameters
----------
attr : str
Attribute name being compared.
left : object
right : object
obj : str, default 'Attributes'
Specify object name being compared, internally used to show appropriate
assertion message
"""
left_attr = getattr(left, attr)
right_attr = getattr(right, attr)
if left_attr is right_attr:
return True
elif (is_number(left_attr) and np.isnan(left_attr) and
is_number(right_attr) and np.isnan(right_attr)):
# np.nan
return True
try:
result = left_attr == right_attr
except TypeError:
# datetimetz on rhs may raise TypeError
result = False
if not isinstance(result, bool):
result = result.all()
if result:
return True
else:
msg = 'Attribute "{attr}" are different'.format(attr=attr)
raise_assert_detail(obj, msg, left_attr, right_attr)
def assert_is_valid_plot_return_object(objs):
import matplotlib.pyplot as plt
if isinstance(objs, (pd.Series, np.ndarray)):
for el in objs.ravel():
msg = ('one of \'objs\' is not a matplotlib Axes instance, type '
'encountered {name!r}').format(name=el.__class__.__name__)
assert isinstance(el, (plt.Axes, dict)), msg
else:
assert isinstance(objs, (plt.Artist, tuple, dict)), \
('objs is neither an ndarray of Artist instances nor a '
'single Artist instance, tuple, or dict, "objs" is a {name!r}'
).format(name=objs.__class__.__name__)
def isiterable(obj):
return hasattr(obj, '__iter__')
def is_sorted(seq):
if isinstance(seq, (Index, Series)):
seq = seq.values
# sorting does not change precisions
return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
def assert_categorical_equal(left, right, check_dtype=True,
obj='Categorical', check_category_order=True):
"""Test that Categoricals are equivalent.
Parameters
----------
left, right : Categorical
Categoricals to compare
check_dtype : bool, default True
Check that integer dtype of the codes are the same
obj : str, default 'Categorical'
Specify object name being compared, internally used to show appropriate
assertion message
check_category_order : bool, default True
Whether the order of the categories should be compared, which
implies identical integer codes. If False, only the resulting
values are compared. The ordered attribute is
checked regardless.
"""
_check_isinstance(left, right, Categorical)
if check_category_order:
assert_index_equal(left.categories, right.categories,
obj='{obj}.categories'.format(obj=obj))
assert_numpy_array_equal(left.codes, right.codes,
check_dtype=check_dtype,
obj='{obj}.codes'.format(obj=obj))
else:
assert_index_equal(left.categories.sort_values(),
right.categories.sort_values(),
obj='{obj}.categories'.format(obj=obj))
assert_index_equal(left.categories.take(left.codes),
right.categories.take(right.codes),
obj='{obj}.values'.format(obj=obj))
assert_attr_equal('ordered', left, right, obj=obj)
def raise_assert_detail(obj, message, left, right, diff=None):
if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif is_categorical_dtype(left):
left = repr(left)
if isinstance(right, np.ndarray):
right = pprint_thing(right)
elif is_categorical_dtype(right):
right = repr(right)
msg = """{obj} are different
{message}
[left]: {left}
[right]: {right}""".format(obj=obj, message=message, left=left, right=right)
if diff is not None:
msg += "\n[diff]: {diff}".format(diff=diff)
raise AssertionError(msg)
def assert_numpy_array_equal(left, right, strict_nan=False,
check_dtype=True, err_msg=None,
obj='numpy array', check_same=None):
""" Checks that 'np.ndarray' is equivalent
Parameters
----------
left : np.ndarray or iterable
right : np.ndarray or iterable
strict_nan : bool, default False
If True, consider NaN and None to be different.
check_dtype: bool, default True
check dtype if both a and b are np.ndarray
err_msg : str, default None
If provided, used as assertion message
obj : str, default 'numpy array'
Specify object name being compared, internally used to show appropriate
assertion message
check_same : None|'copy'|'same', default None
Ensure left and right refer/do not refer to the same memory area
"""
# instance validation
# Show a detailed error message when classes are different
assert_class_equal(left, right, obj=obj)
# both classes must be an np.ndarray
_check_isinstance(left, right, np.ndarray)
def _get_base(obj):
return obj.base if getattr(obj, 'base', None) is not None else obj
left_base = _get_base(left)
right_base = _get_base(right)
if check_same == 'same':
if left_base is not right_base:
msg = "{left!r} is not {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
elif check_same == 'copy':
if left_base is right_base:
msg = "{left!r} is {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
def _raise(left, right, err_msg):
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(obj, '{obj} shapes are different'
.format(obj=obj), left.shape, right.shape)
diff = 0
for l, r in zip(left, right):
# count up differences
if not array_equivalent(l, r, strict_nan=strict_nan):
diff += 1
diff = diff * 100.0 / left.size
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
raise AssertionError(err_msg)
# compare shape and values
if not array_equivalent(left, right, strict_nan=strict_nan):
_raise(left, right, err_msg)
if check_dtype:
if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
assert_attr_equal('dtype', left, right, obj=obj)
return True
def assert_extension_array_equal(left, right):
"""Check that left and right ExtensionArrays are equal.
Parameters
----------
left, right : ExtensionArray
The two arrays to compare
Notes
-----
Missing values are checked separately from valid values.
A mask of missing values is computed for each and checked to match.
The remaining all-valid values are cast to object dtype and checked.
"""
assert isinstance(left, ExtensionArray)
assert left.dtype == right.dtype
left_na = left.isna()
right_na = right.isna()
assert_numpy_array_equal(left_na, right_na)
left_valid = left[~left_na].astype(object)
right_valid = right[~right_na].astype(object)
assert_numpy_array_equal(left_valid, right_valid)
# This could be refactored to use the NDFrame.equals method
def assert_series_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_series_type=True,
check_less_precise=False,
check_names=True,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
obj='Series'):
"""Check that left and right Series are equal.
Parameters
----------
left : Series
right : Series
check_dtype : bool, default True
Whether to check the Series dtype is identical.
check_index_type : bool / string {'equiv'}, default 'equiv'
Whether to check the Index class, dtype and inferred_type
are identical.
check_series_type : bool, default True
Whether to check the Series class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_exact : bool, default False
Whether to compare number exactly.
check_names : bool, default True
Whether to check the Series and Index names attribute.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
obj : str, default 'Series'
Specify object name being compared, internally used to show appropriate
assertion message
"""
# instance validation
_check_isinstance(left, right, Series)
if check_series_type:
# ToDo: There are some tests using rhs is sparse
# lhs is dense. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# length comparison
if len(left) != len(right):
msg1 = '{len}, {left}'.format(len=len(left), left=left.index)
msg2 = '{len}, {right}'.format(len=len(right), right=right.index)
raise_assert_detail(obj, 'Series length are different', msg1, msg2)
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
if check_dtype:
# We want to skip exact dtype checking when `check_categorical`
# is False. We'll still raise if only one is a `Categorical`,
# regardless of `check_categorical`
if (is_categorical_dtype(left) and is_categorical_dtype(right) and
not check_categorical):
pass
else:
assert_attr_equal('dtype', left, right)
if check_exact:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj),)
elif check_datetimelike_compat:
# we want to check only if we have compat dtypes
# e.g. integer and M|m are NOT compat, but we can simply check
# the values in that case
if (is_datetimelike_v_numeric(left, right) or
is_datetimelike_v_object(left, right) or
needs_i8_conversion(left) or
needs_i8_conversion(right)):
# datetimelike may have different objects (e.g. datetime.datetime
# vs Timestamp) but will compare equal
if not Index(left.values).equals(Index(right.values)):
msg = ('[datetimelike_compat=True] {left} is not equal to '
'{right}.').format(left=left.values, right=right.values)
raise AssertionError(msg)
else:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype)
elif is_interval_dtype(left) or is_interval_dtype(right):
# TODO: big hack here
left = pd.IntervalIndex(left)
right = pd.IntervalIndex(right)
assert_index_equal(left, right, obj='{obj}.index'.format(obj=obj))
else:
_testing.assert_almost_equal(left.get_values(), right.get_values(),
check_less_precise=check_less_precise,
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj))
# metadata comparison
if check_names:
assert_attr_equal('name', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
# This could be refactored to use the NDFrame.equals method
def assert_frame_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_column_type='equiv',
check_frame_type=True,
check_less_precise=False,
check_names=True,
by_blocks=False,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
check_like=False,
obj='DataFrame'):
"""Check that left and right DataFrame are equal.
Parameters
----------
left : DataFrame
right : DataFrame
check_dtype : bool, default True
Whether to check the DataFrame dtype is identical.
check_index_type : bool / string {'equiv'}, default False
Whether to check the Index class, dtype and inferred_type
are identical.
check_column_type : bool / string {'equiv'}, default False
Whether to check the columns class, dtype and inferred_type
are identical.
check_frame_type : bool, default False
Whether to check the DataFrame class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_names : bool, default True
Whether to check the Index names attribute.
by_blocks : bool, default False
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
check_exact : bool, default False
Whether to compare number exactly.
check_datetimelike_compat : bool, default False
Compare datetime-like which is comparable ignoring dtype.
check_categorical : bool, default True
Whether to compare internal Categorical exactly.
check_like : bool, default False
If true, ignore the order of rows & columns
obj : str, default 'DataFrame'
Specify object name being compared, internally used to show appropriate
assertion message
"""
# instance validation
_check_isinstance(left, right, DataFrame)
if check_frame_type:
# ToDo: There are some tests using rhs is SparseDataFrame
# lhs is DataFrame. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# shape comparison
if left.shape != right.shape:
raise_assert_detail(obj,
'DataFrame shape mismatch',
'{shape!r}'.format(shape=left.shape),
'{shape!r}'.format(shape=right.shape))
if check_like:
left, right = left.reindex_like(right), right
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
# column comparison
assert_index_equal(left.columns, right.columns, exact=check_column_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.columns'.format(obj=obj))
# compare by blocks
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
assert_frame_equal(lblocks[dtype], rblocks[dtype],
check_dtype=check_dtype, obj='DataFrame.blocks')
# compare by columns
else:
for i, col in enumerate(left.columns):
assert col in right
lcol = left.iloc[:, i]
rcol = right.iloc[:, i]
assert_series_equal(
lcol, rcol, check_dtype=check_dtype,
check_index_type=check_index_type,
check_less_precise=check_less_precise,
check_exact=check_exact, check_names=check_names,
check_datetimelike_compat=check_datetimelike_compat,
check_categorical=check_categorical,
obj='DataFrame.iloc[:, {idx}]'.format(idx=i))
def assert_panel_equal(left, right,
check_dtype=True,
check_panel_type=False,
check_less_precise=False,
check_names=False,
by_blocks=False,
obj='Panel'):
"""Check that left and right Panels are equal.
Parameters
----------
left : Panel (or nd)
right : Panel (or nd)
check_dtype : bool, default True
Whether to check the Panel dtype is identical.
check_panel_type : bool, default False
Whether to check the Panel class is identical.
check_less_precise : bool or int, default False
Specify comparison precision. Only used when check_exact is False.
5 digits (False) or 3 digits (True) after decimal points are compared.
If int, then specify the digits to compare
check_names : bool, default True
Whether to check the Index names attribute.
by_blocks : bool, default False
Specify how to compare internal data. If False, compare by columns.
If True, compare by blocks.
obj : str, default 'Panel'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
if check_panel_type:
assert_class_equal(left, right, obj=obj)
for axis in left._AXIS_ORDERS:
left_ind = getattr(left, axis)
right_ind = getattr(right, axis)
assert_index_equal(left_ind, right_ind, check_names=check_names)
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
array_equivalent(lblocks[dtype].values, rblocks[dtype].values)
else:
# can potentially be slow
for i, item in enumerate(left._get_axis(0)):
msg = "non-matching item (right) '{item}'".format(item=item)
assert item in right, msg
litem = left.iloc[i]
ritem = right.iloc[i]
assert_frame_equal(litem, ritem,
check_less_precise=check_less_precise,
check_names=check_names)
for i, item in enumerate(right._get_axis(0)):
msg = "non-matching item (left) '{item}'".format(item=item)
assert item in left, msg
# -----------------------------------------------------------------------------
# Sparse
def assert_sp_array_equal(left, right, check_dtype=True):
"""Check that the left and right SparseArray are equal.
Parameters
----------
left : SparseArray
right : SparseArray
check_dtype : bool, default True
Whether to check the data dtype is identical.
"""
_check_isinstance(left, right, pd.SparseArray)
assert_numpy_array_equal(left.sp_values, right.sp_values,
check_dtype=check_dtype)
# SparseIndex comparison
assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)
if not left.sp_index.equals(right.sp_index):
raise_assert_detail('SparseArray.index', 'index are not equal',
left.sp_index, right.sp_index)
assert_attr_equal('fill_value', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values,
check_dtype=check_dtype)
def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True,
check_series_type=True, check_names=True,
obj='SparseSeries'):
"""Check that the left and right SparseSeries are equal.
Parameters
----------
left : SparseSeries
right : SparseSeries
check_dtype : bool, default True
Whether to check the Series dtype is identical.
exact_indices : bool, default True
check_series_type : bool, default True
Whether to check the SparseSeries class is identical.
check_names : bool, default True
Whether to check the SparseSeries name attribute.
obj : str, default 'SparseSeries'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
_check_isinstance(left, right, pd.SparseSeries)
if check_series_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_sp_array_equal(left.block.values, right.block.values)
if check_names:
assert_attr_equal('name', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values)
def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True,
check_frame_type=True, obj='SparseDataFrame'):
"""Check that the left and right SparseDataFrame are equal.
Parameters
----------
left : SparseDataFrame
right : SparseDataFrame
check_dtype : bool, default True
Whether to check the Series dtype is identical.
exact_indices : bool, default True
SparseSeries SparseIndex objects must be exactly the same,
otherwise just compare dense representations.
check_frame_type : bool, default True
Whether to check the SparseDataFrame class is identical.
obj : str, default 'SparseDataFrame'
Specify the object name being compared, internally used to show
the appropriate assertion message.
"""
_check_isinstance(left, right, pd.SparseDataFrame)
if check_frame_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns,
obj='{obj}.columns'.format(obj=obj))
for col, series in compat.iteritems(left):
assert (col in right)
# trade-off?
if exact_indices:
assert_sp_series_equal(series, right[col],
check_dtype=check_dtype)
else:
assert_series_equal(series.to_dense(), right[col].to_dense(),
check_dtype=check_dtype)
assert_attr_equal('default_fill_value', left, right, obj=obj)
# do I care?
# assert(left.default_kind == right.default_kind)
for col in right:
assert (col in left)
# -----------------------------------------------------------------------------
# Others
def assert_contains_all(iterable, dic):
for k in iterable:
assert k in dic, "Did not contain item: '{key!r}'".format(key=k)
def assert_copy(iter1, iter2, **eql_kwargs):
"""
iter1, iter2: iterables that produce elements
comparable with assert_almost_equal
Checks that the elements are equal, but not
the same object. (Does not check that items
in sequences are also not the same object)
"""
for elem1, elem2 in zip(iter1, iter2):
assert_almost_equal(elem1, elem2, **eql_kwargs)
msg = ("Expected object {obj1!r} and object {obj2!r} to be "
"different objects, but they were the same object."
).format(obj1=type(elem1), obj2=type(elem2))
assert elem1 is not elem2, msg
def getCols(k):
return string.ascii_uppercase[:k]
def getArangeMat():
return np.arange(N * K).reshape((N, K))
# make index
def makeStringIndex(k=10, name=None):
return Index(rands_array(nchars=10, size=k), name=name)
def makeUnicodeIndex(k=10, name=None):
return Index(randu_array(nchars=10, size=k), name=name)
def makeCategoricalIndex(k=10, n=3, name=None, **kwargs):
""" make a length k index or n categories """
x = rands_array(nchars=4, size=n)
return CategoricalIndex(np.random.choice(x, k), name=name, **kwargs)
def makeIntervalIndex(k=10, name=None, **kwargs):
""" make a length k IntervalIndex """
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs)
def makeBoolIndex(k=10, name=None):
if k == 1:
return Index([True], name=name)
elif k == 2:
return Index([False, True], name=name)
return Index([False, True] + [False] * (k - 2), name=name)
def makeIntIndex(k=10, name=None):
return Index(lrange(k), name=name)
def makeUIntIndex(k=10, name=None):
return Index([2**63 + i for i in lrange(k)], name=name)
def makeRangeIndex(k=10, name=None, **kwargs):
return RangeIndex(0, k, 1, name=name, **kwargs)
def makeFloatIndex(k=10, name=None):
values = sorted(np.random.random_sample(k)) - np.random.random_sample(1)
return Index(values * (10 ** np.random.randint(0, 9)), name=name)
def makeDateIndex(k=10, freq='B', name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = bdate_range(dt, periods=k, freq=freq, name=name)
return DatetimeIndex(dr, name=name, **kwargs)
def makeTimedeltaIndex(k=10, freq='D', name=None, **kwargs):
return TimedeltaIndex(start='1 day', periods=k, freq=freq,
name=name, **kwargs)
def makePeriodIndex(k=10, name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = PeriodIndex(start=dt, periods=k, freq='B', name=name, **kwargs)
return dr
def makeMultiIndex(k=10, names=None, **kwargs):
return MultiIndex.from_product(
(('foo', 'bar'), (1, 2)), names=names, **kwargs)
def all_index_generator(k=10):
"""Generator which can be iterated over to get instances of all the various
index classes.
Parameters
----------
k: length of each of the index instances
"""
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex,
makeUnicodeIndex, makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeBoolIndex, makeRangeIndex,
makeIntervalIndex,
makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
yield make_index_func(k=k)
def index_subclass_makers_generator():
make_index_funcs = [
makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeRangeIndex,
makeIntervalIndex, makeCategoricalIndex,
makeMultiIndex
]
for make_index_func in make_index_funcs:
yield make_index_func
def all_timeseries_index_generator(k=10):
"""Generator which can be iterated over to get instances of all the classes
which represent time-seires.
Parameters
----------
k: length of each of the index instances
"""
make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
for make_index_func in make_index_funcs:
yield make_index_func(k=k)
# make series
def makeFloatSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeStringSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeObjectSeries(name=None):
dateIndex = makeDateIndex(N)
dateIndex = Index(dateIndex, dtype=object)
index = makeStringIndex(N)
return Series(dateIndex, index=index, name=name)
def getSeriesData():
index = makeStringIndex(N)
return {c: Series(randn(N), index=index) for c in getCols(K)}
def makeTimeSeries(nper=None, freq='B', name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name)
def makePeriodSeries(nper=None, name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makePeriodIndex(nper), name=name)
def getTimeSeriesData(nper=None, freq='B'):
return {c: makeTimeSeries(nper, freq) for c in getCols(K)}
def getPeriodData(nper=None):
return {c: makePeriodSeries(nper) for c in getCols(K)}
# make frame
def makeTimeDataFrame(nper=None, freq='B'):
data = getTimeSeriesData(nper, freq)
return DataFrame(data)
def makeDataFrame():
data = getSeriesData()
return DataFrame(data)
def getMixedTypeDict():
index = Index(['a', 'b', 'c', 'd', 'e'])
data = {
'A': [0., 1., 2., 3., 4.],
'B': [0., 1., 0., 1., 0.],
'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'],
'D': bdate_range('1/1/2009', periods=5)
}
return index, data
def makeMixedDataFrame():
return DataFrame(getMixedTypeDict()[1])
def makePeriodFrame(nper=None):
data = getPeriodData(nper)
return DataFrame(data)
def makePanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makeTimeDataFrame(nper) for c in cols}
return Panel.fromDict(data)
def makePeriodPanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makePeriodFrame(nper) for c in cols}
return Panel.fromDict(data)
def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
idx_type=None):
"""Create an index/multindex with given dimensions, levels, names, etc'
nentries - number of entries in index
nlevels - number of levels (> 1 produces multindex)
prefix - a string prefix for labels
names - (Optional), bool or list of strings. if True will use default
names, if false will use no names, if a list is given, the name of
each level in the index will be taken from the list.
ndupe_l - (Optional), list of ints, the number of rows for which the
label will repeated at the corresponding level, you can specify just
the first few, the rest will use the default ndupe_l of 1.
len(ndupe_l) <= nlevels.
idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td".
If idx_type is not None, `idx_nlevels` must be 1.
"i"/"f" creates an integer/float index,
"s"/"u" creates a string/unicode index
"dt" create a datetime index.
"td" create a datetime index.
if unspecified, string labels will be generated.
"""
if ndupe_l is None:
ndupe_l = [1] * nlevels
assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels)
assert (names is None or names is False or
names is True or len(names) is nlevels)
assert idx_type is None or \
(idx_type in ('i', 'f', 's', 'u', 'dt', 'p', 'td') and nlevels == 1)
if names is True:
# build default names
names = [prefix + str(i) for i in range(nlevels)]
if names is False:
# pass None to index constructor for no name
names = None
# make singelton case uniform
if isinstance(names, compat.string_types) and nlevels == 1:
names = [names]
# specific 1D index type requested?
idx_func = dict(i=makeIntIndex, f=makeFloatIndex,
s=makeStringIndex, u=makeUnicodeIndex,
dt=makeDateIndex, td=makeTimedeltaIndex,
p=makePeriodIndex).get(idx_type)
if idx_func:
idx = idx_func(nentries)
# but we need to fill in the name
if names:
idx.name = names[0]
return idx
elif idx_type is not None:
raise ValueError('"{idx_type}" is not a legal value for `idx_type`, '
'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'
.format(idx_type=idx_type))
if len(ndupe_l) < nlevels:
ndupe_l.extend([1] * (nlevels - len(ndupe_l)))
assert len(ndupe_l) == nlevels
assert all(x > 0 for x in ndupe_l)
tuples = []
for i in range(nlevels):
def keyfunc(x):
import re
numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_")
return lmap(int, numeric_tuple)
# build a list of lists to create the index from
div_factor = nentries // ndupe_l[i] + 1
cnt = Counter()
for j in range(div_factor):
label = '{prefix}_l{i}_g{j}'.format(prefix=prefix, i=i, j=j)
cnt[label] = ndupe_l[i]
# cute Counter trick
result = list(sorted(cnt.elements(), key=keyfunc))[:nentries]
tuples.append(result)
tuples = lzip(*tuples)
# convert tuples to index
if nentries == 1:
# we have a single level of tuples, i.e. a regular Index
index = Index(tuples[0], name=names[0])
elif nlevels == 1:
name = None if names is None else names[0]
index = Index((x[0] for x in tuples), name=name)
else:
index = MultiIndex.from_tuples(tuples, names=names)
return index
def makeCustomDataframe(nrows, ncols, c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
"""
nrows, ncols - number of data rows/cols
c_idx_names, idx_names - False/True/list of strings, yields No names ,
default names or uses the provided names for the levels of the
corresponding index. You can provide a single string when
c_idx_nlevels ==1.
c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex
r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex
data_gen_f - a function f(row,col) which return the data value
at that position, the default generator used yields values of the form
"RxCy" based on position.
c_ndupe_l, r_ndupe_l - list of integers, determines the number
of duplicates for each label at a given level of the corresponding
index. The default `None` value produces a multiplicity of 1 across
all levels, i.e. a unique index. Will accept a partial list of length
N < idx_nlevels, for just the first N levels. If ndupe doesn't divide
nrows/ncol, the last label might have lower multiplicity.
dtype - passed to the DataFrame constructor as is, in case you wish to
have more control in conjuncion with a custom `data_gen_f`
r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td".
If idx_type is not None, `idx_nlevels` must be 1.
"i"/"f" creates an integer/float index,
"s"/"u" creates a string/unicode index
"dt" create a datetime index.
"td" create a timedelta index.
if unspecified, string labels will be generated.
Examples:
# 5 row, 3 columns, default names on both, single index on both axis
>> makeCustomDataframe(5,3)
# make the data a random int between 1 and 100
>> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100))
# 2-level multiindex on rows with each label duplicated
# twice on first level, default names on both axis, single
# index on both axis
>> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2])
# DatetimeIndex on row, index with unicode labels on columns
# no names on either axis
>> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False,
r_idx_type="dt",c_idx_type="u")
# 4-level multindex on rows with names provided, 2-level multindex
# on columns with default labels and default names.
>> a=makeCustomDataframe(5,3,r_idx_nlevels=4,
r_idx_names=["FEE","FI","FO","FAM"],
c_idx_nlevels=2)
>> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4)
"""
assert c_idx_nlevels > 0
assert r_idx_nlevels > 0
assert r_idx_type is None or \
(r_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and r_idx_nlevels == 1)
assert c_idx_type is None or \
(c_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and c_idx_nlevels == 1)
columns = makeCustomIndex(ncols, nlevels=c_idx_nlevels, prefix='C',
names=c_idx_names, ndupe_l=c_ndupe_l,
idx_type=c_idx_type)
index = makeCustomIndex(nrows, nlevels=r_idx_nlevels, prefix='R',
names=r_idx_names, ndupe_l=r_ndupe_l,
idx_type=r_idx_type)
# by default, generate data based on location
if data_gen_f is None:
data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c)
data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)]
return DataFrame(data, index, columns, dtype=dtype)
def _create_missing_idx(nrows, ncols, density, random_state=None):
if random_state is None:
random_state = np.random
else:
random_state = np.random.RandomState(random_state)
# below is cribbed from scipy.sparse
size = int(np.round((1 - density) * nrows * ncols))
# generate a few more to ensure unique values
min_rows = 5
fac = 1.02
extra_size = min(size + min_rows, fac * size)
def _gen_unique_rand(rng, _extra_size):
ind = rng.rand(int(_extra_size))
return np.unique(np.floor(ind * nrows * ncols))[:size]
ind = _gen_unique_rand(random_state, extra_size)
while ind.size < size:
extra_size *= 1.05
ind = _gen_unique_rand(random_state, extra_size)
j = np.floor(ind * 1. / nrows).astype(int)
i = (ind - j * nrows).astype(int)
return i.tolist(), j.tolist()
def makeMissingCustomDataframe(nrows, ncols, density=.9, random_state=None,
c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1,
data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
"""
Parameters
----------
Density : float, optional
Float in (0, 1) that gives the percentage of non-missing numbers in
the DataFrame.
random_state : {np.random.RandomState, int}, optional
Random number generator or random seed.
See makeCustomDataframe for descriptions of the rest of the parameters.
"""
df = makeCustomDataframe(nrows, ncols, c_idx_names=c_idx_names,
r_idx_names=r_idx_names,
c_idx_nlevels=c_idx_nlevels,
r_idx_nlevels=r_idx_nlevels,
data_gen_f=data_gen_f,
c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l,
dtype=dtype, c_idx_type=c_idx_type,
r_idx_type=r_idx_type)
i, j = _create_missing_idx(nrows, ncols, density, random_state)
df.values[i, j] = np.nan
return df
def makeMissingDataframe(density=.9, random_state=None):
df = makeDataFrame()
i, j = _create_missing_idx(*df.shape, density=density,
random_state=random_state)
df.values[i, j] = np.nan
return df
def add_nans(panel):
I, J, N = panel.shape
for i, item in enumerate(panel.items):
dm = panel[item]
for j, col in enumerate(dm.columns):
dm[col][:i + j] = np.NaN
return panel
def add_nans_panel4d(panel4d):
for l, label in enumerate(panel4d.labels):
panel = panel4d[label]
add_nans(panel)
return panel4d
class TestSubDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def optional_args(decorator):
"""allows a decorator to take optional positional and keyword arguments.
Assumes that taking a single, callable, positional argument means that
it is decorating a function, i.e. something like this::
@my_decorator
def function(): pass
Calls decorator with decorator(f, *args, **kwargs)"""
@wraps(decorator)
def wrapper(*args, **kwargs):
def dec(f):
return decorator(f, *args, **kwargs)
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
args = []
return dec(f)
else:
return dec
return wrapper
# skip tests on exceptions with this message
_network_error_messages = (
# 'urlopen error timed out',
# 'timeout: timed out',
# 'socket.timeout: timed out',
'timed out',
'Server Hangup',
'HTTP Error 503: Service Unavailable',
'502: Proxy Error',
'HTTP Error 502: internal error',
'HTTP Error 502',
'HTTP Error 503',
'HTTP Error 403',
'HTTP Error 400',
'Temporary failure in name resolution',
'Name or service not known',
'Connection refused',
'certificate verify',
)
# or this e.errno/e.reason.errno
_network_errno_vals = (
101, # Network is unreachable
111, # Connection refused
110, # Connection timed out
104, # Connection reset Error
54, # Connection reset by peer
60, # urllib.error.URLError: [Errno 60] Connection timed out
)
# Both of the above shouldn't mask real issues such as 404's
# or refused connections (changed DNS).
# But some tests (test_data yahoo) contact incredibly flakey
# servers.
# and conditionally raise on these exception types
_network_error_classes = (IOError, httplib.HTTPException)
if sys.version_info >= (3, 3):
_network_error_classes += (TimeoutError,) # noqa
def can_connect(url, error_classes=_network_error_classes):
"""Try to connect to the given url. True if succeeds, False if IOError
raised
Parameters
----------
url : basestring
The URL to try to connect to
Returns
-------
connectable : bool
Return True if no IOError (unable to connect) or URLError (bad url) was
raised
"""
try:
with urlopen(url):
pass
except error_classes:
return False
else:
return True
@optional_args
def network(t, url="http://www.google.com",
raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
check_before_test=False,
error_classes=_network_error_classes,
skip_errnos=_network_errno_vals,
_skip_on_messages=_network_error_messages,
):
"""
Label a test as requiring network connection and, if an error is
encountered, only raise if it does not find a network connection.
In comparison to ``network``, this assumes an added contract to your test:
you must assert that, under normal conditions, your test will ONLY fail if
it does not have network connectivity.
You can call this in 3 ways: as a standard decorator, with keyword
arguments, or with a positional argument that is the url to check.
Parameters
----------
t : callable
The test requiring network connectivity.
url : path
The url to test via ``pandas.io.common.urlopen`` to check
for connectivity. Defaults to 'http://www.google.com'.
raise_on_error : bool
If True, never catches errors.
check_before_test : bool
If True, checks connectivity before running the test case.
error_classes : tuple or Exception
error classes to ignore. If not in ``error_classes``, raises the error.
defaults to IOError. Be careful about changing the error classes here.
skip_errnos : iterable of int
Any exception that has .errno or .reason.erno set to one
of these values will be skipped with an appropriate
message.
_skip_on_messages: iterable of string
any exception e for which one of the strings is
a substring of str(e) will be skipped with an appropriate
message. Intended to suppress errors where an errno isn't available.
Notes
-----
* ``raise_on_error`` supercedes ``check_before_test``
Returns
-------
t : callable
The decorated test ``t``, with checks for connectivity errors.
Example
-------
Tests decorated with @network will fail if it's possible to make a network
connection to another URL (defaults to google.com)::
>>> from pandas.util.testing import network
>>> from pandas.io.common import urlopen
>>> @network
... def test_network():
... with urlopen("rabbit://bonanza.com"):
... pass
Traceback
...
URLError: <urlopen error unknown url type: rabit>
You can specify alternative URLs::
>>> @network("http://www.yahoo.com")
... def test_something_with_yahoo():
... raise IOError("Failure Message")
>>> test_something_with_yahoo()
Traceback (most recent call last):
...
IOError: Failure Message
If you set check_before_test, it will check the url first and not run the
test on failure::
>>> @network("failing://url.blaher", check_before_test=True)
... def test_something():
... print("I ran!")
... raise ValueError("Failure")
>>> test_something()
Traceback (most recent call last):
...
Errors not related to networking will always be raised.
"""
from pytest import skip
t.network = True
@compat.wraps(t)
def wrapper(*args, **kwargs):
if check_before_test and not raise_on_error:
if not can_connect(url, error_classes):
skip()
try:
return t(*args, **kwargs)
except Exception as e:
errno = getattr(e, 'errno', None)
if not errno and hasattr(errno, "reason"):
errno = getattr(e.reason, 'errno', None)
if errno in skip_errnos:
skip("Skipping test due to known errno"
" and error {error}".format(error=e))
try:
e_str = traceback.format_exc(e)
except Exception:
e_str = str(e)
if any(m.lower() in e_str.lower() for m in _skip_on_messages):
skip("Skipping test because exception "
"message is known and error {error}".format(error=e))
if not isinstance(e, error_classes):
raise
if raise_on_error or can_connect(url, error_classes):
raise
else:
skip("Skipping test due to lack of connectivity"
" and error {error}".format(e))
return wrapper
with_connectivity_check = network
class SimpleMock(object):
"""
Poor man's mocking object
Note: only works for new-style classes, assumes __getattribute__ exists.
>>> a = type("Duck",(),{})
>>> a.attr1,a.attr2 ="fizz","buzz"
>>> b = SimpleMock(a,"attr1","bar")
>>> b.attr1 == "bar" and b.attr2 == "buzz"
True
>>> a.attr1 == "fizz" and a.attr2 == "buzz"
True
"""
def __init__(self, obj, *args, **kwds):
assert(len(args) % 2 == 0)
attrs = kwds.get("attrs", {})
for k, v in zip(args[::2], args[1::2]):
# dict comprehensions break 2.6
attrs[k] = v
self.attrs = attrs
self.obj = obj
def __getattribute__(self, name):
attrs = object.__getattribute__(self, "attrs")
obj = object.__getattribute__(self, "obj")
return attrs.get(name, type(obj).__getattribute__(obj, name))
@contextmanager
def stdin_encoding(encoding=None):
"""
Context manager for running bits of code while emulating an arbitrary
stdin encoding.
>>> import sys
>>> _encoding = sys.stdin.encoding
>>> with stdin_encoding('AES'): sys.stdin.encoding
'AES'
>>> sys.stdin.encoding==_encoding
True
"""
import sys
_stdin = sys.stdin
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
yield
sys.stdin = _stdin
def assert_raises_regex(_exception, _regexp, _callable=None,
*args, **kwargs):
r"""
Check that the specified Exception is raised and that the error message
matches a given regular expression pattern. This may be a regular
expression object or a string containing a regular expression suitable
for use by `re.search()`. This is a port of the `assertRaisesRegexp`
function from unittest in Python 2.7.
Examples
--------
>>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ')
>>> import re
>>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ')
If an exception of a different type is raised, it bubbles up.
>>> assert_raises_regex(TypeError, 'literal', int, 'XYZ')
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'XYZ'
>>> dct = dict()
>>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple')
Traceback (most recent call last):
...
AssertionError: "pear" does not match "'apple'"
You can also use this in a with statement.
>>> with assert_raises_regex(TypeError, 'unsupported operand type\(s\)'):
... 1 + {}
>>> with assert_raises_regex(TypeError, 'banana'):
... 'apple'[0] = 'b'
Traceback (most recent call last):
...
AssertionError: "banana" does not match "'str' object does not support \
item assignment"
"""
manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
if _callable is not None:
with manager:
_callable(*args, **kwargs)
else:
return manager
class _AssertRaisesContextmanager(object):
"""
Context manager behind `assert_raises_regex`.
"""
def __init__(self, exception, regexp=None):
"""
Initialize an _AssertRaisesContextManager instance.
Parameters
----------
exception : class
The expected Exception class.
regexp : str, default None
The regex to compare against the Exception message.
"""
self.exception = exception
if regexp is not None and not hasattr(regexp, "search"):
regexp = re.compile(regexp, re.DOTALL)
self.regexp = regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, trace_back):
expected = self.exception
if not exc_type:
exp_name = getattr(expected, "__name__", str(expected))
raise AssertionError("{name} not raised.".format(name=exp_name))
return self.exception_matches(exc_type, exc_value, trace_back)
def exception_matches(self, exc_type, exc_value, trace_back):
"""
Check that the Exception raised matches the expected Exception
and expected error message regular expression.
Parameters
----------
exc_type : class
The type of Exception raised.
exc_value : Exception
The instance of `exc_type` raised.
trace_back : stack trace object
The traceback object associated with `exc_value`.
Returns
-------
is_matched : bool
Whether or not the Exception raised matches the expected
Exception class and expected error message regular expression.
Raises
------
AssertionError : The error message provided does not match
the expected error message regular expression.
"""
if issubclass(exc_type, self.exception):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
msg = '"{pat}" does not match "{val}"'.format(
pat=self.regexp.pattern, val=val)
e = AssertionError(msg)
raise_with_traceback(e, trace_back)
return True
else:
# Failed, so allow Exception to bubble up.
return False
@contextmanager
def assert_produces_warning(expected_warning=Warning, filter_level="always",
clear=None, check_stacklevel=True):
"""
Context manager for running code expected to either raise a specific
warning, or not raise any warnings. Verifies that the code raises the
expected warning, and that it does not raise any other unexpected
warnings. It is basically a wrapper around ``warnings.catch_warnings``.
Parameters
----------
expected_warning : {Warning, False, None}, default Warning
The type of Exception raised. ``exception.Warning`` is the base
class for all warnings. To check that no warning is returned,
specify ``False`` or ``None``.
filter_level : str, default "always"
Specifies whether warnings are ignored, displayed, or turned
into errors.
Valid values are:
* "error" - turns matching warnings into exceptions
* "ignore" - discard the warning
* "always" - always emit a warning
* "default" - print the warning the first time it is generated
from each location
* "module" - print the warning the first time it is generated
from each module
* "once" - print the warning the first time it is generated
clear : str, default None
If not ``None`` then remove any previously raised warnings from
the ``__warningsregistry__`` to ensure that no warning messages are
suppressed by this context manager. If ``None`` is specified,
the ``__warningsregistry__`` keeps track of which warnings have been
shown, and does not show them again.
check_stacklevel : bool, default True
If True, displays the line that called the function containing
the warning to show were the function is called. Otherwise, the
line that implements the function is displayed.
Examples
--------
>>> import warnings
>>> with assert_produces_warning():
... warnings.warn(UserWarning())
...
>>> with assert_produces_warning(False):
... warnings.warn(RuntimeWarning())
...
Traceback (most recent call last):
...
AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
>>> with assert_produces_warning(UserWarning):
... warnings.warn(RuntimeWarning())
Traceback (most recent call last):
...
AssertionError: Did not see expected warning of class 'UserWarning'.
..warn:: This is *not* thread-safe.
"""
with warnings.catch_warnings(record=True) as w:
if clear is not None:
# make sure that we are clearning these warnings
# if they have happened before
# to guarantee that we will catch them
if not is_list_like(clear):
clear = [clear]
for m in clear:
try:
m.__warningregistry__.clear()
except Exception:
pass
saw_warning = False
warnings.simplefilter(filter_level)
yield w
extra_warnings = []
for actual_warning in w:
if (expected_warning and issubclass(actual_warning.category,
expected_warning)):
saw_warning = True
if check_stacklevel and issubclass(actual_warning.category,
(FutureWarning,
DeprecationWarning)):
from inspect import getframeinfo, stack
caller = getframeinfo(stack()[2][0])
msg = ("Warning not set with correct stacklevel. "
"File where warning is raised: {actual} != "
"{caller}. Warning message: {message}"
).format(actual=actual_warning.filename,
caller=caller.filename,
message=actual_warning.message)
assert actual_warning.filename == caller.filename, msg
else:
extra_warnings.append(actual_warning.category.__name__)
if expected_warning:
msg = "Did not see expected warning of class {name!r}.".format(
name=expected_warning.__name__)
assert saw_warning, msg
assert not extra_warnings, ("Caused unexpected warning(s): {extra!r}."
).format(extra=extra_warnings)
class RNGContext(object):
"""
Context manager to set the numpy random number generator speed. Returns
to the original value upon exiting the context manager.
Parameters
----------
seed : int
Seed for numpy.random.seed
Examples
--------
with RNGContext(42):
np.random.randn()
"""
def __init__(self, seed):
self.seed = seed
def __enter__(self):
self.start_state = np.random.get_state()
np.random.seed(self.seed)
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.start_state)
@contextmanager
def use_numexpr(use, min_elements=None):
from pandas.core.computation import expressions as expr
if min_elements is None:
min_elements = expr._MIN_ELEMENTS
olduse = expr._USE_NUMEXPR
oldmin = expr._MIN_ELEMENTS
expr.set_use_numexpr(use)
expr._MIN_ELEMENTS = min_elements
yield
expr._MIN_ELEMENTS = oldmin
expr.set_use_numexpr(olduse)
def test_parallel(num_threads=2, kwargs_list=None):
"""Decorator to run the same function multiple times in parallel.
Parameters
----------
num_threads : int, optional
The number of times the function is run in parallel.
kwargs_list : list of dicts, optional
The list of kwargs to update original
function kwargs on different threads.
Notes
-----
This decorator does not pass the return value of the decorated function.
Original from scikit-image:
https://github.com/scikit-image/scikit-image/pull/1519
"""
assert num_threads > 0
has_kwargs_list = kwargs_list is not None
if has_kwargs_list:
assert len(kwargs_list) == num_threads
import threading
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if has_kwargs_list:
update_kwargs = lambda i: dict(kwargs, **kwargs_list[i])
else:
update_kwargs = lambda i: kwargs
threads = []
for i in range(num_threads):
updated_kwargs = update_kwargs(i)
thread = threading.Thread(target=func, args=args,
kwargs=updated_kwargs)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return inner
return wrapper
class SubclassedSeries(Series):
_metadata = ['testattr', 'name']
@property
def _constructor(self):
return SubclassedSeries
@property
def _constructor_expanddim(self):
return SubclassedDataFrame
class SubclassedDataFrame(DataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedDataFrame
@property
def _constructor_sliced(self):
return SubclassedSeries
class SubclassedSparseSeries(pd.SparseSeries):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseSeries
@property
def _constructor_expanddim(self):
return SubclassedSparseDataFrame
class SubclassedSparseDataFrame(pd.SparseDataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseDataFrame
@property
def _constructor_sliced(self):
return SubclassedSparseSeries
class SubclassedCategorical(Categorical):
@property
def _constructor(self):
return SubclassedCategorical
@contextmanager
def patch(ob, attr, value):
"""Temporarily patch an attribute of an object.
Parameters
----------
ob : any
The object to patch. This must support attribute assignment for `attr`.
attr : str
The name of the attribute to patch.
value : any
The temporary attribute to assign.
Examples
--------
>>> class C(object):
... attribute = 'original'
...
>>> C.attribute
'original'
>>> with patch(C, 'attribute', 'patched'):
... in_context = C.attribute
...
>>> in_context
'patched'
>>> C.attribute # the value is reset when the context manager exists
'original'
Correctly replaces attribute when the manager exits with an exception.
>>> with patch(C, 'attribute', 'patched'):
... in_context = C.attribute
... raise ValueError()
Traceback (most recent call last):
...
ValueError
>>> in_context
'patched'
>>> C.attribute
'original'
"""
noattr = object() # mark that the attribute never existed
old = getattr(ob, attr, noattr)
setattr(ob, attr, value)
try:
yield
finally:
if old is noattr:
delattr(ob, attr)
else:
setattr(ob, attr, old)
@contextmanager
def set_timezone(tz):
"""Context manager for temporarily setting a timezone.
Parameters
----------
tz : str
A string representing a valid timezone.
Examples
--------
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> tzlocal().tzname(datetime.now())
'IST'
>>> with set_timezone('US/Eastern'):
... tzlocal().tzname(datetime.now())
...
'EDT'
"""
import os
import time
def setTZ(tz):
if tz is None:
try:
del os.environ['TZ']
except KeyError:
pass
else:
os.environ['TZ'] = tz
time.tzset()
orig_tz = os.environ.get('TZ')
setTZ(tz)
try:
yield
finally:
setTZ(orig_tz)
def _make_skipna_wrapper(alternative, skipna_alternative=None):
"""Create a function for calling on an array.
Parameters
----------
alternative : function
The function to be called on the array with no NaNs.
Only used when 'skipna_alternative' is None.
skipna_alternative : function
The function to be called on the original array
Returns
-------
skipna_wrapper : function
"""
if skipna_alternative:
def skipna_wrapper(x):
return skipna_alternative(x.values)
else:
def skipna_wrapper(x):
nona = x.dropna()
if len(nona) == 0:
return np.nan
return alternative(nona)
return skipna_wrapper
| 32.854442 | 79 | 0.611059 | from __future__ import division
import re
import string
import sys
import tempfile
import warnings
import inspect
import os
import subprocess
import locale
import traceback
from datetime import datetime
from functools import wraps
from contextlib import contextmanager
from numpy.random import randn, rand
import numpy as np
import pandas as pd
from pandas.core.arrays import ExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas.core.dtypes.common import (
is_datetimelike_v_numeric,
is_datetimelike_v_object,
is_number, is_bool,
needs_i8_conversion,
is_categorical_dtype,
is_interval_dtype,
is_sequence,
is_list_like)
from pandas.io.formats.printing import pprint_thing
from pandas.core.algorithms import take_1d
import pandas.core.common as com
import pandas.compat as compat
from pandas.compat import (
filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter,
raise_with_traceback, httplib, StringIO, PY3)
from pandas import (bdate_range, CategoricalIndex, Categorical, IntervalIndex,
DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex,
Index, MultiIndex,
Series, DataFrame, Panel)
from pandas._libs import testing as _testing
from pandas.io.common import urlopen
N = 30
K = 4
_RAISE_NETWORK_ERROR_DEFAULT = False
_testing_mode_warnings = (DeprecationWarning, compat.ResourceWarning)
def set_testing_mode():
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('always', _testing_mode_warnings)
def reset_testing_mode():
testing_mode = os.environ.get('PANDAS_TESTING_MODE', 'None')
if 'deprecate' in testing_mode:
warnings.simplefilter('ignore', _testing_mode_warnings)
set_testing_mode()
def reset_display_options():
pd.reset_option('^display.', silent=True)
def round_trip_pickle(obj, path=None):
if path is None:
path = u('__{random_bytes}__.pickle'.format(random_bytes=rands(10)))
with ensure_clean(path) as path:
pd.to_pickle(obj, path)
return pd.read_pickle(path)
def round_trip_pathlib(writer, reader, path=None):
import pytest
Path = pytest.importorskip('pathlib').Path
if path is None:
path = '___pathlib___'
with ensure_clean(path) as path:
writer(Path(path))
obj = reader(Path(path))
return obj
def round_trip_localpath(writer, reader, path=None):
import pytest
LocalPath = pytest.importorskip('py.path').local
if path is None:
path = '___localpath___'
with ensure_clean(path) as path:
writer(LocalPath(path))
obj = reader(LocalPath(path))
return obj
@contextmanager
def decompress_file(path, compression):
if compression is None:
f = open(path, 'rb')
elif compression == 'gzip':
import gzip
f = gzip.open(path, 'rb')
elif compression == 'bz2':
import bz2
f = bz2.BZ2File(path, 'rb')
elif compression == 'xz':
lzma = compat.import_lzma()
f = lzma.LZMAFile(path, 'rb')
elif compression == 'zip':
import zipfile
zip_file = zipfile.ZipFile(path)
zip_names = zip_file.namelist()
if len(zip_names) == 1:
f = zip_file.open(zip_names.pop())
else:
raise ValueError('ZIP file {} error. Only one file per ZIP.'
.format(path))
else:
msg = 'Unrecognized compression type: {}'.format(compression)
raise ValueError(msg)
yield f
f.close()
def assert_almost_equal(left, right, check_exact=False,
check_dtype='equiv', check_less_precise=False,
**kwargs):
if isinstance(left, pd.Index):
return assert_index_equal(left, right, check_exact=check_exact,
exact=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.Series):
return assert_series_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
elif isinstance(left, pd.DataFrame):
return assert_frame_equal(left, right, check_exact=check_exact,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
else:
if check_dtype:
if is_number(left) and is_number(right):
pass
elif is_bool(left) and is_bool(right):
pass
else:
if (isinstance(left, np.ndarray) or
isinstance(right, np.ndarray)):
obj = 'numpy array'
else:
obj = 'Input'
assert_class_equal(left, right, obj=obj)
return _testing.assert_almost_equal(
left, right,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
**kwargs)
def _check_isinstance(left, right, cls):
err_msg = "{name} Expected type {exp_type}, found {act_type} instead"
cls_name = cls.__name__
if not isinstance(left, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(left)))
if not isinstance(right, cls):
raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
act_type=type(right)))
def assert_dict_equal(left, right, compare_keys=True):
_check_isinstance(left, right, dict)
return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
def randbool(size=(), p=0.5):
return rand(*size) <= p
RANDS_CHARS = np.array(list(string.ascii_letters + string.digits),
dtype=(np.str_, 1))
RANDU_CHARS = np.array(list(u("").join(map(unichr, lrange(1488, 1488 + 26))) +
string.digits), dtype=(np.unicode_, 1))
def rands_array(nchars, size, dtype='O'):
retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
.view((np.str_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def randu_array(nchars, size, dtype='O'):
retval = (np.random.choice(RANDU_CHARS, size=nchars * np.prod(size))
.view((np.unicode_, nchars)).reshape(size))
if dtype is None:
return retval
else:
return retval.astype(dtype)
def rands(nchars):
return ''.join(np.random.choice(RANDS_CHARS, nchars))
def randu(nchars):
return ''.join(np.random.choice(RANDU_CHARS, nchars))
def close(fignum=None):
from matplotlib.pyplot import get_fignums, close as _close
if fignum is None:
for fignum in get_fignums():
_close(fignum)
else:
_close(fignum)
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
def _default_locale_getter():
try:
raw_locales = check_output(['locale -a'], shell=True)
except subprocess.CalledProcessError as e:
raise type(e)("{exception}, the 'locale -a' command cannot be found "
"on your system".format(exception=e))
return raw_locales
def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
try:
raw_locales = locale_getter()
except Exception:
return None
try:
raw_locales = raw_locales.split(b'\n')
out_locales = []
for x in raw_locales:
if PY3:
out_locales.append(str(
x, encoding=pd.options.display.encoding))
else:
out_locales.append(str(x))
except TypeError:
pass
if prefix is None:
return _valid_locales(out_locales, normalize)
found = re.compile('{prefix}.*'.format(prefix=prefix)) \
.findall('\n'.join(out_locales))
return _valid_locales(found, normalize)
@contextmanager
def set_locale(new_locale, lc_var=locale.LC_ALL):
current_locale = locale.getlocale()
try:
locale.setlocale(lc_var, new_locale)
try:
normalized_locale = locale.getlocale()
except ValueError:
yield new_locale
else:
if com._all_not_none(*normalized_locale):
yield '.'.join(normalized_locale)
else:
yield new_locale
finally:
locale.setlocale(lc_var, current_locale)
def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
def _valid_locales(locales, normalize):
if normalize:
normalizer = lambda x: locale.normalize(x.strip())
else:
normalizer = lambda x: x.strip()
return list(filter(_can_set_locale, map(normalizer, locales)))
def capture_stdout(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stdout = StringIO()
f(*args, **kwargs)
finally:
sys.stdout = sys.__stdout__
return wrapper
def capture_stderr(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
sys.stderr = StringIO()
f(*args, **kwargs)
finally:
sys.stderr = sys.__stderr__
return wrapper
def debug(f, *args, **kwargs):
from pdb import Pdb as OldPdb
try:
from IPython.core.debugger import Pdb
kw = dict(color_scheme='Linux')
except ImportError:
Pdb = OldPdb
kw = {}
pdb = Pdb(**kw)
return pdb.runcall(f, *args, **kwargs)
def pudebug(f, *args, **kwargs):
import pudb
return pudb.runcall(f, *args, **kwargs)
def set_trace():
from IPython.core.debugger import Pdb
try:
Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)
except Exception:
from pdb import Pdb as OldPdb
OldPdb().set_trace(sys._getframe().f_back)
@contextmanager
def ensure_clean(filename=None, return_filelike=False):
filename = filename or ''
fd = None
if return_filelike:
f = tempfile.TemporaryFile(suffix=filename)
try:
yield f
finally:
f.close()
else:
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")
try:
fd, filename = tempfile.mkstemp(suffix=filename)
except UnicodeEncodeError:
import pytest
pytest.skip('no unicode file names on this system')
try:
yield filename
finally:
try:
os.close(fd)
except Exception as e:
print("Couldn't close file descriptor: {fdesc} (file: {fname})"
.format(fdesc=fd, fname=filename))
try:
if os.path.exists(filename):
os.remove(filename)
except Exception as e:
print("Exception on removing file: {error}".format(error=e))
def get_data_path(f=''):
# get our callers file
_, filename, _, _, _, _ = inspect.getouterframes(inspect.currentframe())[1]
base_dir = os.path.abspath(os.path.dirname(filename))
return os.path.join(base_dir, 'data', f)
# -----------------------------------------------------------------------------
# Comparators
def equalContents(arr1, arr2):
return frozenset(arr1) == frozenset(arr2)
def assert_index_equal(left, right, exact='equiv', check_names=True,
check_less_precise=False, check_exact=True,
check_categorical=True, obj='Index'):
def _check_types(l, r, obj='Index'):
if exact:
assert_class_equal(left, right, exact=exact, obj=obj)
assert_attr_equal('dtype', l, r, obj=obj)
# allow string-like to have different inferred_types
if l.inferred_type in ('string', 'unicode'):
assert r.inferred_type in ('string', 'unicode')
else:
assert_attr_equal('inferred_type', l, r, obj=obj)
def _get_ilevel_values(index, level):
# accept level number only
unique = index.levels[level]
labels = index.labels[level]
filled = take_1d(unique.values, labels, fill_value=unique._na_value)
values = unique._shallow_copy(filled, name=index.names[level])
return values
# instance validation
_check_isinstance(left, right, Index)
# class / dtype comparison
_check_types(left, right, obj=obj)
# level comparison
if left.nlevels != right.nlevels:
msg1 = '{obj} levels are different'.format(obj=obj)
msg2 = '{nlevels}, {left}'.format(nlevels=left.nlevels, left=left)
msg3 = '{nlevels}, {right}'.format(nlevels=right.nlevels, right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# length comparison
if len(left) != len(right):
msg1 = '{obj} length are different'.format(obj=obj)
msg2 = '{length}, {left}'.format(length=len(left), left=left)
msg3 = '{length}, {right}'.format(length=len(right), right=right)
raise_assert_detail(obj, msg1, msg2, msg3)
# MultiIndex special comparison for little-friendly error messages
if left.nlevels > 1:
for level in range(left.nlevels):
# cannot use get_level_values here because it can change dtype
llevel = _get_ilevel_values(left, level)
rlevel = _get_ilevel_values(right, level)
lobj = 'MultiIndex level [{level}]'.format(level=level)
assert_index_equal(llevel, rlevel,
exact=exact, check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact, obj=lobj)
# get_level_values may change dtype
_check_types(left.levels[level], right.levels[level], obj=obj)
if check_exact:
if not left.equals(right):
diff = np.sum((left.values != right.values)
.astype(int)) * 100.0 / len(left)
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
else:
_testing.assert_almost_equal(left.values, right.values,
check_less_precise=check_less_precise,
check_dtype=exact,
obj=obj, lobj=left, robj=right)
# metadata comparison
if check_names:
assert_attr_equal('names', left, right, obj=obj)
if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex):
assert_attr_equal('freq', left, right, obj=obj)
if (isinstance(left, pd.IntervalIndex) or
isinstance(right, pd.IntervalIndex)):
assert_attr_equal('closed', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_class_equal(left, right, exact=True, obj='Input'):
def repr_class(x):
if isinstance(x, Index):
# return Index as it is to include values in the error message
return x
try:
return x.__class__.__name__
except AttributeError:
return repr(type(x))
if exact == 'equiv':
if type(left) != type(right):
# allow equivalence of Int64Index/RangeIndex
types = set([type(left).__name__, type(right).__name__])
if len(types - set(['Int64Index', 'RangeIndex'])):
msg = '{obj} classes are not equivalent'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
elif exact:
if type(left) != type(right):
msg = '{obj} classes are different'.format(obj=obj)
raise_assert_detail(obj, msg, repr_class(left),
repr_class(right))
def assert_attr_equal(attr, left, right, obj='Attributes'):
left_attr = getattr(left, attr)
right_attr = getattr(right, attr)
if left_attr is right_attr:
return True
elif (is_number(left_attr) and np.isnan(left_attr) and
is_number(right_attr) and np.isnan(right_attr)):
# np.nan
return True
try:
result = left_attr == right_attr
except TypeError:
# datetimetz on rhs may raise TypeError
result = False
if not isinstance(result, bool):
result = result.all()
if result:
return True
else:
msg = 'Attribute "{attr}" are different'.format(attr=attr)
raise_assert_detail(obj, msg, left_attr, right_attr)
def assert_is_valid_plot_return_object(objs):
import matplotlib.pyplot as plt
if isinstance(objs, (pd.Series, np.ndarray)):
for el in objs.ravel():
msg = ('one of \'objs\' is not a matplotlib Axes instance, type '
'encountered {name!r}').format(name=el.__class__.__name__)
assert isinstance(el, (plt.Axes, dict)), msg
else:
assert isinstance(objs, (plt.Artist, tuple, dict)), \
('objs is neither an ndarray of Artist instances nor a '
'single Artist instance, tuple, or dict, "objs" is a {name!r}'
).format(name=objs.__class__.__name__)
def isiterable(obj):
return hasattr(obj, '__iter__')
def is_sorted(seq):
if isinstance(seq, (Index, Series)):
seq = seq.values
# sorting does not change precisions
return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
def assert_categorical_equal(left, right, check_dtype=True,
obj='Categorical', check_category_order=True):
_check_isinstance(left, right, Categorical)
if check_category_order:
assert_index_equal(left.categories, right.categories,
obj='{obj}.categories'.format(obj=obj))
assert_numpy_array_equal(left.codes, right.codes,
check_dtype=check_dtype,
obj='{obj}.codes'.format(obj=obj))
else:
assert_index_equal(left.categories.sort_values(),
right.categories.sort_values(),
obj='{obj}.categories'.format(obj=obj))
assert_index_equal(left.categories.take(left.codes),
right.categories.take(right.codes),
obj='{obj}.values'.format(obj=obj))
assert_attr_equal('ordered', left, right, obj=obj)
def raise_assert_detail(obj, message, left, right, diff=None):
if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif is_categorical_dtype(left):
left = repr(left)
if isinstance(right, np.ndarray):
right = pprint_thing(right)
elif is_categorical_dtype(right):
right = repr(right)
msg = """{obj} are different
{message}
[left]: {left}
[right]: {right}""".format(obj=obj, message=message, left=left, right=right)
if diff is not None:
msg += "\n[diff]: {diff}".format(diff=diff)
raise AssertionError(msg)
def assert_numpy_array_equal(left, right, strict_nan=False,
check_dtype=True, err_msg=None,
obj='numpy array', check_same=None):
# instance validation
# Show a detailed error message when classes are different
assert_class_equal(left, right, obj=obj)
# both classes must be an np.ndarray
_check_isinstance(left, right, np.ndarray)
def _get_base(obj):
return obj.base if getattr(obj, 'base', None) is not None else obj
left_base = _get_base(left)
right_base = _get_base(right)
if check_same == 'same':
if left_base is not right_base:
msg = "{left!r} is not {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
elif check_same == 'copy':
if left_base is right_base:
msg = "{left!r} is {right!r}".format(
left=left_base, right=right_base)
raise AssertionError(msg)
def _raise(left, right, err_msg):
if err_msg is None:
if left.shape != right.shape:
raise_assert_detail(obj, '{obj} shapes are different'
.format(obj=obj), left.shape, right.shape)
diff = 0
for l, r in zip(left, right):
# count up differences
if not array_equivalent(l, r, strict_nan=strict_nan):
diff += 1
diff = diff * 100.0 / left.size
msg = '{obj} values are different ({pct} %)'.format(
obj=obj, pct=np.round(diff, 5))
raise_assert_detail(obj, msg, left, right)
raise AssertionError(err_msg)
# compare shape and values
if not array_equivalent(left, right, strict_nan=strict_nan):
_raise(left, right, err_msg)
if check_dtype:
if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
assert_attr_equal('dtype', left, right, obj=obj)
return True
def assert_extension_array_equal(left, right):
assert isinstance(left, ExtensionArray)
assert left.dtype == right.dtype
left_na = left.isna()
right_na = right.isna()
assert_numpy_array_equal(left_na, right_na)
left_valid = left[~left_na].astype(object)
right_valid = right[~right_na].astype(object)
assert_numpy_array_equal(left_valid, right_valid)
# This could be refactored to use the NDFrame.equals method
def assert_series_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_series_type=True,
check_less_precise=False,
check_names=True,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
obj='Series'):
# instance validation
_check_isinstance(left, right, Series)
if check_series_type:
# ToDo: There are some tests using rhs is sparse
# lhs is dense. Should use assert_class_equal in future
assert isinstance(left, type(right))
# assert_class_equal(left, right, obj=obj)
# length comparison
if len(left) != len(right):
msg1 = '{len}, {left}'.format(len=len(left), left=left.index)
msg2 = '{len}, {right}'.format(len=len(right), right=right.index)
raise_assert_detail(obj, 'Series length are different', msg1, msg2)
# index comparison
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
if check_dtype:
# We want to skip exact dtype checking when `check_categorical`
# is False. We'll still raise if only one is a `Categorical`,
if (is_categorical_dtype(left) and is_categorical_dtype(right) and
not check_categorical):
pass
else:
assert_attr_equal('dtype', left, right)
if check_exact:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj),)
elif check_datetimelike_compat:
if (is_datetimelike_v_numeric(left, right) or
is_datetimelike_v_object(left, right) or
needs_i8_conversion(left) or
needs_i8_conversion(right)):
if not Index(left.values).equals(Index(right.values)):
msg = ('[datetimelike_compat=True] {left} is not equal to '
'{right}.').format(left=left.values, right=right.values)
raise AssertionError(msg)
else:
assert_numpy_array_equal(left.get_values(), right.get_values(),
check_dtype=check_dtype)
elif is_interval_dtype(left) or is_interval_dtype(right):
left = pd.IntervalIndex(left)
right = pd.IntervalIndex(right)
assert_index_equal(left, right, obj='{obj}.index'.format(obj=obj))
else:
_testing.assert_almost_equal(left.get_values(), right.get_values(),
check_less_precise=check_less_precise,
check_dtype=check_dtype,
obj='{obj}'.format(obj=obj))
if check_names:
assert_attr_equal('name', left, right, obj=obj)
if check_categorical:
if is_categorical_dtype(left) or is_categorical_dtype(right):
assert_categorical_equal(left.values, right.values,
obj='{obj} category'.format(obj=obj))
def assert_frame_equal(left, right, check_dtype=True,
check_index_type='equiv',
check_column_type='equiv',
check_frame_type=True,
check_less_precise=False,
check_names=True,
by_blocks=False,
check_exact=False,
check_datetimelike_compat=False,
check_categorical=True,
check_like=False,
obj='DataFrame'):
_check_isinstance(left, right, DataFrame)
if check_frame_type:
assert isinstance(left, type(right))
if left.shape != right.shape:
raise_assert_detail(obj,
'DataFrame shape mismatch',
'{shape!r}'.format(shape=left.shape),
'{shape!r}'.format(shape=right.shape))
if check_like:
left, right = left.reindex_like(right), right
assert_index_equal(left.index, right.index, exact=check_index_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns, exact=check_column_type,
check_names=check_names,
check_less_precise=check_less_precise,
check_exact=check_exact,
check_categorical=check_categorical,
obj='{obj}.columns'.format(obj=obj))
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
assert_frame_equal(lblocks[dtype], rblocks[dtype],
check_dtype=check_dtype, obj='DataFrame.blocks')
else:
for i, col in enumerate(left.columns):
assert col in right
lcol = left.iloc[:, i]
rcol = right.iloc[:, i]
assert_series_equal(
lcol, rcol, check_dtype=check_dtype,
check_index_type=check_index_type,
check_less_precise=check_less_precise,
check_exact=check_exact, check_names=check_names,
check_datetimelike_compat=check_datetimelike_compat,
check_categorical=check_categorical,
obj='DataFrame.iloc[:, {idx}]'.format(idx=i))
def assert_panel_equal(left, right,
check_dtype=True,
check_panel_type=False,
check_less_precise=False,
check_names=False,
by_blocks=False,
obj='Panel'):
if check_panel_type:
assert_class_equal(left, right, obj=obj)
for axis in left._AXIS_ORDERS:
left_ind = getattr(left, axis)
right_ind = getattr(right, axis)
assert_index_equal(left_ind, right_ind, check_names=check_names)
if by_blocks:
rblocks = right._to_dict_of_blocks()
lblocks = left._to_dict_of_blocks()
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
assert dtype in lblocks
assert dtype in rblocks
array_equivalent(lblocks[dtype].values, rblocks[dtype].values)
else:
for i, item in enumerate(left._get_axis(0)):
msg = "non-matching item (right) '{item}'".format(item=item)
assert item in right, msg
litem = left.iloc[i]
ritem = right.iloc[i]
assert_frame_equal(litem, ritem,
check_less_precise=check_less_precise,
check_names=check_names)
for i, item in enumerate(right._get_axis(0)):
msg = "non-matching item (left) '{item}'".format(item=item)
assert item in left, msg
def assert_sp_array_equal(left, right, check_dtype=True):
_check_isinstance(left, right, pd.SparseArray)
assert_numpy_array_equal(left.sp_values, right.sp_values,
check_dtype=check_dtype)
assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)
if not left.sp_index.equals(right.sp_index):
raise_assert_detail('SparseArray.index', 'index are not equal',
left.sp_index, right.sp_index)
assert_attr_equal('fill_value', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values,
check_dtype=check_dtype)
def assert_sp_series_equal(left, right, check_dtype=True, exact_indices=True,
check_series_type=True, check_names=True,
obj='SparseSeries'):
_check_isinstance(left, right, pd.SparseSeries)
if check_series_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_sp_array_equal(left.block.values, right.block.values)
if check_names:
assert_attr_equal('name', left, right)
if check_dtype:
assert_attr_equal('dtype', left, right)
assert_numpy_array_equal(left.values, right.values)
def assert_sp_frame_equal(left, right, check_dtype=True, exact_indices=True,
check_frame_type=True, obj='SparseDataFrame'):
_check_isinstance(left, right, pd.SparseDataFrame)
if check_frame_type:
assert_class_equal(left, right, obj=obj)
assert_index_equal(left.index, right.index,
obj='{obj}.index'.format(obj=obj))
assert_index_equal(left.columns, right.columns,
obj='{obj}.columns'.format(obj=obj))
for col, series in compat.iteritems(left):
assert (col in right)
if exact_indices:
assert_sp_series_equal(series, right[col],
check_dtype=check_dtype)
else:
assert_series_equal(series.to_dense(), right[col].to_dense(),
check_dtype=check_dtype)
assert_attr_equal('default_fill_value', left, right, obj=obj)
for col in right:
assert (col in left)
def assert_contains_all(iterable, dic):
for k in iterable:
assert k in dic, "Did not contain item: '{key!r}'".format(key=k)
def assert_copy(iter1, iter2, **eql_kwargs):
for elem1, elem2 in zip(iter1, iter2):
assert_almost_equal(elem1, elem2, **eql_kwargs)
msg = ("Expected object {obj1!r} and object {obj2!r} to be "
"different objects, but they were the same object."
).format(obj1=type(elem1), obj2=type(elem2))
assert elem1 is not elem2, msg
def getCols(k):
return string.ascii_uppercase[:k]
def getArangeMat():
return np.arange(N * K).reshape((N, K))
def makeStringIndex(k=10, name=None):
return Index(rands_array(nchars=10, size=k), name=name)
def makeUnicodeIndex(k=10, name=None):
return Index(randu_array(nchars=10, size=k), name=name)
def makeCategoricalIndex(k=10, n=3, name=None, **kwargs):
x = rands_array(nchars=4, size=n)
return CategoricalIndex(np.random.choice(x, k), name=name, **kwargs)
def makeIntervalIndex(k=10, name=None, **kwargs):
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs)
def makeBoolIndex(k=10, name=None):
if k == 1:
return Index([True], name=name)
elif k == 2:
return Index([False, True], name=name)
return Index([False, True] + [False] * (k - 2), name=name)
def makeIntIndex(k=10, name=None):
return Index(lrange(k), name=name)
def makeUIntIndex(k=10, name=None):
return Index([2**63 + i for i in lrange(k)], name=name)
def makeRangeIndex(k=10, name=None, **kwargs):
return RangeIndex(0, k, 1, name=name, **kwargs)
def makeFloatIndex(k=10, name=None):
values = sorted(np.random.random_sample(k)) - np.random.random_sample(1)
return Index(values * (10 ** np.random.randint(0, 9)), name=name)
def makeDateIndex(k=10, freq='B', name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = bdate_range(dt, periods=k, freq=freq, name=name)
return DatetimeIndex(dr, name=name, **kwargs)
def makeTimedeltaIndex(k=10, freq='D', name=None, **kwargs):
return TimedeltaIndex(start='1 day', periods=k, freq=freq,
name=name, **kwargs)
def makePeriodIndex(k=10, name=None, **kwargs):
dt = datetime(2000, 1, 1)
dr = PeriodIndex(start=dt, periods=k, freq='B', name=name, **kwargs)
return dr
def makeMultiIndex(k=10, names=None, **kwargs):
return MultiIndex.from_product(
(('foo', 'bar'), (1, 2)), names=names, **kwargs)
def all_index_generator(k=10):
all_make_index_funcs = [makeIntIndex, makeFloatIndex, makeStringIndex,
makeUnicodeIndex, makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeBoolIndex, makeRangeIndex,
makeIntervalIndex,
makeCategoricalIndex]
for make_index_func in all_make_index_funcs:
yield make_index_func(k=k)
def index_subclass_makers_generator():
make_index_funcs = [
makeDateIndex, makePeriodIndex,
makeTimedeltaIndex, makeRangeIndex,
makeIntervalIndex, makeCategoricalIndex,
makeMultiIndex
]
for make_index_func in make_index_funcs:
yield make_index_func
def all_timeseries_index_generator(k=10):
make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
for make_index_func in make_index_funcs:
yield make_index_func(k=k)
def makeFloatSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeStringSeries(name=None):
index = makeStringIndex(N)
return Series(randn(N), index=index, name=name)
def makeObjectSeries(name=None):
dateIndex = makeDateIndex(N)
dateIndex = Index(dateIndex, dtype=object)
index = makeStringIndex(N)
return Series(dateIndex, index=index, name=name)
def getSeriesData():
index = makeStringIndex(N)
return {c: Series(randn(N), index=index) for c in getCols(K)}
def makeTimeSeries(nper=None, freq='B', name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name)
def makePeriodSeries(nper=None, name=None):
if nper is None:
nper = N
return Series(randn(nper), index=makePeriodIndex(nper), name=name)
def getTimeSeriesData(nper=None, freq='B'):
return {c: makeTimeSeries(nper, freq) for c in getCols(K)}
def getPeriodData(nper=None):
return {c: makePeriodSeries(nper) for c in getCols(K)}
def makeTimeDataFrame(nper=None, freq='B'):
data = getTimeSeriesData(nper, freq)
return DataFrame(data)
def makeDataFrame():
data = getSeriesData()
return DataFrame(data)
def getMixedTypeDict():
index = Index(['a', 'b', 'c', 'd', 'e'])
data = {
'A': [0., 1., 2., 3., 4.],
'B': [0., 1., 0., 1., 0.],
'C': ['foo1', 'foo2', 'foo3', 'foo4', 'foo5'],
'D': bdate_range('1/1/2009', periods=5)
}
return index, data
def makeMixedDataFrame():
return DataFrame(getMixedTypeDict()[1])
def makePeriodFrame(nper=None):
data = getPeriodData(nper)
return DataFrame(data)
def makePanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makeTimeDataFrame(nper) for c in cols}
return Panel.fromDict(data)
def makePeriodPanel(nper=None):
with warnings.catch_warnings(record=True):
cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]]
data = {c: makePeriodFrame(nper) for c in cols}
return Panel.fromDict(data)
def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None,
idx_type=None):
if ndupe_l is None:
ndupe_l = [1] * nlevels
assert (is_sequence(ndupe_l) and len(ndupe_l) <= nlevels)
assert (names is None or names is False or
names is True or len(names) is nlevels)
assert idx_type is None or \
(idx_type in ('i', 'f', 's', 'u', 'dt', 'p', 'td') and nlevels == 1)
if names is True:
names = [prefix + str(i) for i in range(nlevels)]
if names is False:
names = None
if isinstance(names, compat.string_types) and nlevels == 1:
names = [names]
idx_func = dict(i=makeIntIndex, f=makeFloatIndex,
s=makeStringIndex, u=makeUnicodeIndex,
dt=makeDateIndex, td=makeTimedeltaIndex,
p=makePeriodIndex).get(idx_type)
if idx_func:
idx = idx_func(nentries)
if names:
idx.name = names[0]
return idx
elif idx_type is not None:
raise ValueError('"{idx_type}" is not a legal value for `idx_type`, '
'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'
.format(idx_type=idx_type))
if len(ndupe_l) < nlevels:
ndupe_l.extend([1] * (nlevels - len(ndupe_l)))
assert len(ndupe_l) == nlevels
assert all(x > 0 for x in ndupe_l)
tuples = []
for i in range(nlevels):
def keyfunc(x):
import re
numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_")
return lmap(int, numeric_tuple)
# build a list of lists to create the index from
div_factor = nentries // ndupe_l[i] + 1
cnt = Counter()
for j in range(div_factor):
label = '{prefix}_l{i}_g{j}'.format(prefix=prefix, i=i, j=j)
cnt[label] = ndupe_l[i]
# cute Counter trick
result = list(sorted(cnt.elements(), key=keyfunc))[:nentries]
tuples.append(result)
tuples = lzip(*tuples)
# convert tuples to index
if nentries == 1:
# we have a single level of tuples, i.e. a regular Index
index = Index(tuples[0], name=names[0])
elif nlevels == 1:
name = None if names is None else names[0]
index = Index((x[0] for x in tuples), name=name)
else:
index = MultiIndex.from_tuples(tuples, names=names)
return index
def makeCustomDataframe(nrows, ncols, c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
assert c_idx_nlevels > 0
assert r_idx_nlevels > 0
assert r_idx_type is None or \
(r_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and r_idx_nlevels == 1)
assert c_idx_type is None or \
(c_idx_type in ('i', 'f', 's',
'u', 'dt', 'p', 'td') and c_idx_nlevels == 1)
columns = makeCustomIndex(ncols, nlevels=c_idx_nlevels, prefix='C',
names=c_idx_names, ndupe_l=c_ndupe_l,
idx_type=c_idx_type)
index = makeCustomIndex(nrows, nlevels=r_idx_nlevels, prefix='R',
names=r_idx_names, ndupe_l=r_ndupe_l,
idx_type=r_idx_type)
# by default, generate data based on location
if data_gen_f is None:
data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c)
data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)]
return DataFrame(data, index, columns, dtype=dtype)
def _create_missing_idx(nrows, ncols, density, random_state=None):
if random_state is None:
random_state = np.random
else:
random_state = np.random.RandomState(random_state)
# below is cribbed from scipy.sparse
size = int(np.round((1 - density) * nrows * ncols))
# generate a few more to ensure unique values
min_rows = 5
fac = 1.02
extra_size = min(size + min_rows, fac * size)
def _gen_unique_rand(rng, _extra_size):
ind = rng.rand(int(_extra_size))
return np.unique(np.floor(ind * nrows * ncols))[:size]
ind = _gen_unique_rand(random_state, extra_size)
while ind.size < size:
extra_size *= 1.05
ind = _gen_unique_rand(random_state, extra_size)
j = np.floor(ind * 1. / nrows).astype(int)
i = (ind - j * nrows).astype(int)
return i.tolist(), j.tolist()
def makeMissingCustomDataframe(nrows, ncols, density=.9, random_state=None,
c_idx_names=True, r_idx_names=True,
c_idx_nlevels=1, r_idx_nlevels=1,
data_gen_f=None,
c_ndupe_l=None, r_ndupe_l=None, dtype=None,
c_idx_type=None, r_idx_type=None):
df = makeCustomDataframe(nrows, ncols, c_idx_names=c_idx_names,
r_idx_names=r_idx_names,
c_idx_nlevels=c_idx_nlevels,
r_idx_nlevels=r_idx_nlevels,
data_gen_f=data_gen_f,
c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l,
dtype=dtype, c_idx_type=c_idx_type,
r_idx_type=r_idx_type)
i, j = _create_missing_idx(nrows, ncols, density, random_state)
df.values[i, j] = np.nan
return df
def makeMissingDataframe(density=.9, random_state=None):
df = makeDataFrame()
i, j = _create_missing_idx(*df.shape, density=density,
random_state=random_state)
df.values[i, j] = np.nan
return df
def add_nans(panel):
I, J, N = panel.shape
for i, item in enumerate(panel.items):
dm = panel[item]
for j, col in enumerate(dm.columns):
dm[col][:i + j] = np.NaN
return panel
def add_nans_panel4d(panel4d):
for l, label in enumerate(panel4d.labels):
panel = panel4d[label]
add_nans(panel)
return panel4d
class TestSubDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def optional_args(decorator):
@wraps(decorator)
def wrapper(*args, **kwargs):
def dec(f):
return decorator(f, *args, **kwargs)
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
args = []
return dec(f)
else:
return dec
return wrapper
# skip tests on exceptions with this message
_network_error_messages = (
# 'urlopen error timed out',
# 'timeout: timed out',
# 'socket.timeout: timed out',
'timed out',
'Server Hangup',
'HTTP Error 503: Service Unavailable',
'502: Proxy Error',
'HTTP Error 502: internal error',
'HTTP Error 502',
'HTTP Error 503',
'HTTP Error 403',
'HTTP Error 400',
'Temporary failure in name resolution',
'Name or service not known',
'Connection refused',
'certificate verify',
)
# or this e.errno/e.reason.errno
_network_errno_vals = (
101, # Network is unreachable
111, # Connection refused
110, # Connection timed out
104, # Connection reset Error
54, # Connection reset by peer
60, # urllib.error.URLError: [Errno 60] Connection timed out
)
# Both of the above shouldn't mask real issues such as 404's
# or refused connections (changed DNS).
# But some tests (test_data yahoo) contact incredibly flakey
# servers.
# and conditionally raise on these exception types
_network_error_classes = (IOError, httplib.HTTPException)
if sys.version_info >= (3, 3):
_network_error_classes += (TimeoutError,) # noqa
def can_connect(url, error_classes=_network_error_classes):
try:
with urlopen(url):
pass
except error_classes:
return False
else:
return True
@optional_args
def network(t, url="http://www.google.com",
raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT,
check_before_test=False,
error_classes=_network_error_classes,
skip_errnos=_network_errno_vals,
_skip_on_messages=_network_error_messages,
):
from pytest import skip
t.network = True
@compat.wraps(t)
def wrapper(*args, **kwargs):
if check_before_test and not raise_on_error:
if not can_connect(url, error_classes):
skip()
try:
return t(*args, **kwargs)
except Exception as e:
errno = getattr(e, 'errno', None)
if not errno and hasattr(errno, "reason"):
errno = getattr(e.reason, 'errno', None)
if errno in skip_errnos:
skip("Skipping test due to known errno"
" and error {error}".format(error=e))
try:
e_str = traceback.format_exc(e)
except Exception:
e_str = str(e)
if any(m.lower() in e_str.lower() for m in _skip_on_messages):
skip("Skipping test because exception "
"message is known and error {error}".format(error=e))
if not isinstance(e, error_classes):
raise
if raise_on_error or can_connect(url, error_classes):
raise
else:
skip("Skipping test due to lack of connectivity"
" and error {error}".format(e))
return wrapper
with_connectivity_check = network
class SimpleMock(object):
def __init__(self, obj, *args, **kwds):
assert(len(args) % 2 == 0)
attrs = kwds.get("attrs", {})
for k, v in zip(args[::2], args[1::2]):
# dict comprehensions break 2.6
attrs[k] = v
self.attrs = attrs
self.obj = obj
def __getattribute__(self, name):
attrs = object.__getattribute__(self, "attrs")
obj = object.__getattribute__(self, "obj")
return attrs.get(name, type(obj).__getattribute__(obj, name))
@contextmanager
def stdin_encoding(encoding=None):
import sys
_stdin = sys.stdin
sys.stdin = SimpleMock(sys.stdin, "encoding", encoding)
yield
sys.stdin = _stdin
def assert_raises_regex(_exception, _regexp, _callable=None,
*args, **kwargs):
manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
if _callable is not None:
with manager:
_callable(*args, **kwargs)
else:
return manager
class _AssertRaisesContextmanager(object):
def __init__(self, exception, regexp=None):
self.exception = exception
if regexp is not None and not hasattr(regexp, "search"):
regexp = re.compile(regexp, re.DOTALL)
self.regexp = regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, trace_back):
expected = self.exception
if not exc_type:
exp_name = getattr(expected, "__name__", str(expected))
raise AssertionError("{name} not raised.".format(name=exp_name))
return self.exception_matches(exc_type, exc_value, trace_back)
def exception_matches(self, exc_type, exc_value, trace_back):
if issubclass(exc_type, self.exception):
if self.regexp is not None:
val = str(exc_value)
if not self.regexp.search(val):
msg = '"{pat}" does not match "{val}"'.format(
pat=self.regexp.pattern, val=val)
e = AssertionError(msg)
raise_with_traceback(e, trace_back)
return True
else:
# Failed, so allow Exception to bubble up.
return False
@contextmanager
def assert_produces_warning(expected_warning=Warning, filter_level="always",
clear=None, check_stacklevel=True):
with warnings.catch_warnings(record=True) as w:
if clear is not None:
# make sure that we are clearning these warnings
# if they have happened before
# to guarantee that we will catch them
if not is_list_like(clear):
clear = [clear]
for m in clear:
try:
m.__warningregistry__.clear()
except Exception:
pass
saw_warning = False
warnings.simplefilter(filter_level)
yield w
extra_warnings = []
for actual_warning in w:
if (expected_warning and issubclass(actual_warning.category,
expected_warning)):
saw_warning = True
if check_stacklevel and issubclass(actual_warning.category,
(FutureWarning,
DeprecationWarning)):
from inspect import getframeinfo, stack
caller = getframeinfo(stack()[2][0])
msg = ("Warning not set with correct stacklevel. "
"File where warning is raised: {actual} != "
"{caller}. Warning message: {message}"
).format(actual=actual_warning.filename,
caller=caller.filename,
message=actual_warning.message)
assert actual_warning.filename == caller.filename, msg
else:
extra_warnings.append(actual_warning.category.__name__)
if expected_warning:
msg = "Did not see expected warning of class {name!r}.".format(
name=expected_warning.__name__)
assert saw_warning, msg
assert not extra_warnings, ("Caused unexpected warning(s): {extra!r}."
).format(extra=extra_warnings)
class RNGContext(object):
def __init__(self, seed):
self.seed = seed
def __enter__(self):
self.start_state = np.random.get_state()
np.random.seed(self.seed)
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.start_state)
@contextmanager
def use_numexpr(use, min_elements=None):
from pandas.core.computation import expressions as expr
if min_elements is None:
min_elements = expr._MIN_ELEMENTS
olduse = expr._USE_NUMEXPR
oldmin = expr._MIN_ELEMENTS
expr.set_use_numexpr(use)
expr._MIN_ELEMENTS = min_elements
yield
expr._MIN_ELEMENTS = oldmin
expr.set_use_numexpr(olduse)
def test_parallel(num_threads=2, kwargs_list=None):
assert num_threads > 0
has_kwargs_list = kwargs_list is not None
if has_kwargs_list:
assert len(kwargs_list) == num_threads
import threading
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if has_kwargs_list:
update_kwargs = lambda i: dict(kwargs, **kwargs_list[i])
else:
update_kwargs = lambda i: kwargs
threads = []
for i in range(num_threads):
updated_kwargs = update_kwargs(i)
thread = threading.Thread(target=func, args=args,
kwargs=updated_kwargs)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return inner
return wrapper
class SubclassedSeries(Series):
_metadata = ['testattr', 'name']
@property
def _constructor(self):
return SubclassedSeries
@property
def _constructor_expanddim(self):
return SubclassedDataFrame
class SubclassedDataFrame(DataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedDataFrame
@property
def _constructor_sliced(self):
return SubclassedSeries
class SubclassedSparseSeries(pd.SparseSeries):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseSeries
@property
def _constructor_expanddim(self):
return SubclassedSparseDataFrame
class SubclassedSparseDataFrame(pd.SparseDataFrame):
_metadata = ['testattr']
@property
def _constructor(self):
return SubclassedSparseDataFrame
@property
def _constructor_sliced(self):
return SubclassedSparseSeries
class SubclassedCategorical(Categorical):
@property
def _constructor(self):
return SubclassedCategorical
@contextmanager
def patch(ob, attr, value):
noattr = object() # mark that the attribute never existed
old = getattr(ob, attr, noattr)
setattr(ob, attr, value)
try:
yield
finally:
if old is noattr:
delattr(ob, attr)
else:
setattr(ob, attr, old)
@contextmanager
def set_timezone(tz):
import os
import time
def setTZ(tz):
if tz is None:
try:
del os.environ['TZ']
except KeyError:
pass
else:
os.environ['TZ'] = tz
time.tzset()
orig_tz = os.environ.get('TZ')
setTZ(tz)
try:
yield
finally:
setTZ(orig_tz)
def _make_skipna_wrapper(alternative, skipna_alternative=None):
if skipna_alternative:
def skipna_wrapper(x):
return skipna_alternative(x.values)
else:
def skipna_wrapper(x):
nona = x.dropna()
if len(nona) == 0:
return np.nan
return alternative(nona)
return skipna_wrapper
| true | true |
f72c3bbbbfb56f466b8bb7c5ad7d122e79a30a61 | 22,903 | py | Python | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 652 | 2015-07-26T00:00:17.000Z | 2022-02-24T18:30:04.000Z | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 8 | 2015-09-07T03:38:19.000Z | 2021-05-23T03:18:51.000Z | app/venv/lib/python2.7/site-packages/numpy/distutils/mingw32ccompiler.py | anaheino/Ufo-sightings-map | 64af02093f97737cbbdfd8af9e1aeb4d8aa8fcdc | [
"MIT"
] | 40 | 2015-07-24T19:45:08.000Z | 2021-11-01T14:54:56.000Z | """
Support code for building Python extensions on Windows.
# NT stuff
# 1. Make sure libpython<version>.a exists for gcc. If not, build it.
# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)
# 3. Force windows to use g77
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import subprocess
import re
# Overwrite certain distutils.ccompiler functions:
import numpy.distutils.ccompiler
if sys.version_info[0] < 3:
from . import log
else:
from numpy.distutils import log
# NT stuff
# 1. Make sure libpython<version>.a exists for gcc. If not, build it.
# 2. Force windows to use gcc (we're struggling with MSVC and g77 support)
# --> this is done in numpy/distutils/ccompiler.py
# 3. Force windows to use g77
import distutils.cygwinccompiler
from distutils.version import StrictVersion
from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import (DistutilsExecError, CompileError,
UnknownFileError)
from numpy.distutils.misc_util import (msvc_runtime_library,
get_build_architecture)
# Useful to generate table of symbols from a dll
_START = re.compile(r'\[Ordinal/Name Pointer\] Table')
_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')
# the same as cygwin plus some additional parameters
class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):
""" A modified MingW32 compiler compatible with an MSVC built Python.
"""
compiler_type = 'mingw32'
def __init__ (self,
verbose=0,
dry_run=0,
force=0):
distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,
dry_run, force)
# we need to support 3.2 which doesn't match the standard
# get_versions methods regex
if self.gcc_version is None:
import re
p = subprocess.Popen(['gcc', '-dumpversion'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
result = re.search('(\d+\.\d+)', out_string)
if result:
self.gcc_version = StrictVersion(result.group(1))
# A real mingw32 doesn't need to specify a different entry point,
# but cygwin 2.91.57 in no-cygwin-mode needs it.
if self.gcc_version <= "2.91.57":
entry_point = '--entry _DllMain@12'
else:
entry_point = ''
if self.linker_dll == 'dllwrap':
# Commented out '--driver-name g++' part that fixes weird
# g++.exe: g++: No such file or directory
# error (mingw 1.0 in Enthon24 tree, gcc-3.4.5).
# If the --driver-name part is required for some environment
# then make the inclusion of this part specific to that
# environment.
self.linker = 'dllwrap' # --driver-name g++'
elif self.linker_dll == 'gcc':
self.linker = 'g++'
p = subprocess.Popen(['gcc', '--version'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
# Before build with MinGW-W64 generate the python import library
# with gendef and dlltool according to the MingW-W64 FAQ.
# Use the MinGW-W64 provided msvc runtime import libraries.
# Don't call build_import_library() and build_msvcr_library.
if 'MinGW-W64' not in str(out_string):
# **changes: eric jones 4/11/01
# 1. Check for import library on Windows. Build if it doesn't
# exist.
build_import_library()
# Check for custom msvc runtime library on Windows. Build if it
# doesn't exist.
msvcr_success = build_msvcr_library()
msvcr_dbg_success = build_msvcr_library(debug=True)
if msvcr_success or msvcr_dbg_success:
# add preprocessor statement for using customized msvcr lib
self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')
# Define the MSVC version as hint for MinGW
msvcr_version = '0x%03i0' % int(msvc_runtime_library().lstrip('msvcr'))
self.define_macro('__MSVCRT_VERSION__', msvcr_version)
# MS_WIN64 should be defined when building for amd64 on windows,
# but python headers define it only for MS compilers, which has all
# kind of bad consequences, like using Py_ModuleInit4 instead of
# Py_ModuleInit4_64, etc... So we add it here
if get_build_architecture() == 'AMD64':
if self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall',
compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0'
' -Wall -Wstrict-prototypes',
linker_exe='gcc -g -mno-cygwin',
linker_so='gcc -g -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option
self.set_executables(
compiler='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall',
compiler_so='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall -Wstrict-prototypes',
linker_exe='gcc',
linker_so='gcc -shared -Wl,-gc-sections -Wl,-s')
else:
if self.gcc_version <= "3.0.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -w',
compiler_so='gcc -mno-cygwin -mdll -O2 -w'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='%s -mno-cygwin -mdll -static %s' %
(self.linker, entry_point))
elif self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -Wall',
compiler_so='gcc -mno-cygwin -O2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='g++ -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option i686
# build needs '-mincoming-stack-boundary=2' due to ABI
# incompatibility to Win32 ABI
self.set_executables(
compiler='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall',
compiler_so='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ ',
linker_so='g++ -shared -Wl,-gc-sections -Wl,-s')
# added for python2.3 support we can't pass it through set_executables
# because pre 2.2 would fail
self.compiler_cxx = ['g++']
# Maybe we should also append -mthreads, but then the finished dlls
# need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support
# thread-safe exception handling on `Mingw32')
# no additional libraries needed
#self.dll_libraries=[]
return
# __init__ ()
def link(self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols = None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
# Include the appropiate MSVC runtime library if Python was built
# with MSVC >= 7.0 (MinGW standard is msvcrt)
runtime_library = msvc_runtime_library()
if runtime_library:
if not libraries:
libraries = []
libraries.append(runtime_library)
args = (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
None, #export_symbols, we do this in our def-file
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
if self.gcc_version < "3.0.0":
func = distutils.cygwinccompiler.CygwinCCompiler.link
else:
func = UnixCCompiler.link
func(*args[:func.__code__.co_argcount])
return
def object_filenames (self,
source_filenames,
strip_dir=0,
output_dir=''):
if output_dir is None: output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext (os.path.normcase(src_name))
# added these lines to strip off windows drive letters
# without it, .o files are placed next to .c files
# instead of the build directory
drv, base = os.path.splitdrive(base)
if drv:
base = base[1:]
if ext not in (self.src_extensions + ['.rc', '.res']):
raise UnknownFileError(
"unknown file type '%s' (from '%s')" % \
(ext, src_name))
if strip_dir:
base = os.path.basename (base)
if ext == '.res' or ext == '.rc':
# these need to be compiled to object files
obj_names.append (os.path.join (output_dir,
base + ext + self.obj_extension))
else:
obj_names.append (os.path.join (output_dir,
base + self.obj_extension))
return obj_names
# object_filenames ()
def find_python_dll():
maj, min, micro = [int(i) for i in sys.version_info[:3]]
dllname = 'python%d%d.dll' % (maj, min)
print("Looking for %s" % dllname)
# We can't do much here:
# - find it in python main dir
# - in system32,
# - ortherwise (Sxs), I don't know how to get it.
lib_dirs = []
lib_dirs.append(sys.prefix)
lib_dirs.append(os.path.join(sys.prefix, 'lib'))
try:
lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32'))
except KeyError:
pass
for d in lib_dirs:
dll = os.path.join(d, dllname)
if os.path.exists(dll):
return dll
raise ValueError("%s not found in %s" % (dllname, lib_dirs))
def dump_table(dll):
st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE)
return st.stdout.readlines()
def generate_def(dll, dfile):
"""Given a dll file location, get all its exported symbols and dump them
into the given def file.
The .def file will be overwritten"""
dump = dump_table(dll)
for i in range(len(dump)):
if _START.match(dump[i].decode()):
break
else:
raise ValueError("Symbol table not found")
syms = []
for j in range(i+1, len(dump)):
m = _TABLE.match(dump[j].decode())
if m:
syms.append((int(m.group(1).strip()), m.group(2)))
else:
break
if len(syms) == 0:
log.warn('No symbols found in %s' % dll)
d = open(dfile, 'w')
d.write('LIBRARY %s\n' % os.path.basename(dll))
d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
d.write(';DATA PRELOAD SINGLE\n')
d.write('\nEXPORTS\n')
for s in syms:
#d.write('@%d %s\n' % (s[0], s[1]))
d.write('%s\n' % s[1])
d.close()
def find_dll(dll_name):
arch = {'AMD64' : 'amd64',
'Intel' : 'x86'}[get_build_architecture()]
def _find_dll_in_winsxs(dll_name):
# Walk through the WinSxS directory to find the dll.
winsxs_path = os.path.join(os.environ['WINDIR'], 'winsxs')
if not os.path.exists(winsxs_path):
return None
for root, dirs, files in os.walk(winsxs_path):
if dll_name in files and arch in root:
return os.path.join(root, dll_name)
return None
def _find_dll_in_path(dll_name):
# First, look in the Python directory, then scan PATH for
# the given dll name.
for path in [sys.prefix] + os.environ['PATH'].split(';'):
filepath = os.path.join(path, dll_name)
if os.path.exists(filepath):
return os.path.abspath(filepath)
return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)
def build_msvcr_library(debug=False):
if os.name != 'nt':
return False
msvcr_name = msvc_runtime_library()
# Skip using a custom library for versions < MSVC 8.0
if int(msvcr_name.lstrip('msvcr')) < 80:
log.debug('Skip building msvcr library:'
' custom functionality not present')
return False
if debug:
msvcr_name += 'd'
# Skip if custom library already exists
out_name = "lib%s.a" % msvcr_name
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building msvcr library: "%s" exists' %
(out_file,))
return True
# Find the msvcr dll
msvcr_dll_name = msvcr_name + '.dll'
dll_file = find_dll(msvcr_dll_name)
if not dll_file:
log.warn('Cannot build msvcr library: "%s" not found' %
msvcr_dll_name)
return False
def_name = "lib%s.def" % msvcr_name
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building msvcr library: "%s" (from %s)' \
% (out_file, dll_file))
# Generate a symbol definition file from the msvcr dll
generate_def(dll_file, def_file)
# Create a custom mingw library for the given symbol definitions
cmd = ['dlltool', '-d', def_file, '-l', out_file]
retcode = subprocess.call(cmd)
# Clean up symbol definitions
os.remove(def_file)
return (not retcode)
def build_import_library():
if os.name != 'nt':
return
arch = get_build_architecture()
if arch == 'AMD64':
return _build_import_library_amd64()
elif arch == 'Intel':
return _build_import_library_x86()
else:
raise ValueError("Unhandled arch %s" % arch)
def _build_import_library_amd64():
dll_file = find_python_dll()
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' %
(out_file))
return
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building import library (arch=AMD64): "%s" (from %s)' %
(out_file, dll_file))
generate_def(dll_file, def_file)
cmd = ['dlltool', '-d', def_file, '-l', out_file]
subprocess.Popen(cmd)
def _build_import_library_x86():
""" Build the import libraries for Mingw32-gcc on Windows
"""
lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if not os.path.isfile(lib_file):
log.warn('Cannot build import library: "%s" not found' % (lib_file))
return
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' % (out_file))
return
log.info('Building import library (ARCH=x86): "%s"' % (out_file))
from numpy.distutils import lib2def
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)
nm_output = lib2def.getnm(nm_cmd)
dlist, flist = lib2def.parse_nm(nm_output)
lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))
dll_name = "python%d%d.dll" % tuple(sys.version_info[:2])
args = (dll_name, def_file, out_file)
cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args
status = os.system(cmd)
# for now, fail silently
if status:
log.warn('Failed to build import library for gcc. Linking will fail.')
return
#=====================================
# Dealing with Visual Studio MANIFESTS
#=====================================
# Functions to deal with visual studio manifests. Manifest are a mechanism to
# enforce strong DLL versioning on windows, and has nothing to do with
# distutils MANIFEST. manifests are XML files with version info, and used by
# the OS loader; they are necessary when linking against a DLL not in the
# system path; in particular, official python 2.6 binary is built against the
# MS runtime 9 (the one from VS 2008), which is not available on most windows
# systems; python 2.6 installer does install it in the Win SxS (Side by side)
# directory, but this requires the manifest for this to work. This is a big
# mess, thanks MS for a wonderful system.
# XXX: ideally, we should use exactly the same version as used by python. I
# submitted a patch to get this version, but it was only included for python
# 2.6.1 and above. So for versions below, we use a "best guess".
_MSVCRVER_TO_FULLVER = {}
if sys.platform == 'win32':
try:
import msvcrt
# I took one version in my SxS directory: no idea if it is the good
# one, and we can't retrieve it from python
_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
# Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0
# on Windows XP:
_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"):
major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2)
_MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION
del major, minor, rest
except ImportError:
# If we are here, means python was not built with MSVC. Not sure what
# to do in that case: manifest building will fail, but it should not be
# used in that case anyway
log.warn('Cannot import msvcrt: using manifest will not be possible')
def msvc_manifest_xml(maj, min):
"""Given a major and minor version of the MSVCR, returns the
corresponding XML file."""
try:
fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
except KeyError:
raise ValueError("Version %d,%d of MSVCRT not supported yet" %
(maj, min))
# Don't be fooled, it looks like an XML, but it is not. In particular, it
# should not have any space before starting, and its size should be
# divisible by 4, most likely for alignement constraints when the xml is
# embedded in the binary...
# This template was copied directly from the python 2.6 binary (using
# strings.exe from mingw on python.exe).
template = """\
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
return template % {'fullver': fullver, 'maj': maj, 'min': min}
def manifest_rc(name, type='dll'):
"""Return the rc file used to generate the res file which will be embedded
as manifest for given manifest file name, of given type ('dll' or
'exe').
Parameters
----------
name : str
name of the manifest file to embed
type : str {'dll', 'exe'}
type of the binary which will embed the manifest
"""
if type == 'dll':
rctype = 2
elif type == 'exe':
rctype = 1
else:
raise ValueError("Type %s not supported" % type)
return """\
#include "winuser.h"
%d RT_MANIFEST %s""" % (rctype, name)
def check_embedded_msvcr_match_linked(msver):
"""msver is the ms runtime version used for the MANIFEST."""
# check msvcr major version are the same for linking and
# embedding
msvcv = msvc_runtime_library()
if msvcv:
assert msvcv.startswith("msvcr"), msvcv
# Dealing with something like "mscvr90" or "mscvr100", the last
# last digit is the minor release, want int("9") or int("10"):
maj = int(msvcv[5:-1])
if not maj == int(msver):
raise ValueError(
"Discrepancy between linked msvcr " \
"(%d) and the one about to be embedded " \
"(%d)" % (int(msver), maj))
def configtest_name(config):
base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
return os.path.splitext(base)[0]
def manifest_name(config):
# Get configest name (including suffix)
root = configtest_name(config)
exext = config.compiler.exe_extension
return root + exext + ".manifest"
def rc_name(config):
# Get configtest name (including suffix)
root = configtest_name(config)
return root + ".rc"
def generate_manifest(config):
msver = get_build_msvc_version()
if msver is not None:
if msver >= 8:
check_embedded_msvcr_match_linked(msver)
ma = int(msver)
mi = int((msver - ma) * 10)
# Write the manifest file
manxml = msvc_manifest_xml(ma, mi)
man = open(manifest_name(config), "w")
config.temp_files.append(manifest_name(config))
man.write(manxml)
man.close()
| 38.171667 | 176 | 0.590752 | from __future__ import division, absolute_import, print_function
import os
import sys
import subprocess
import re
import numpy.distutils.ccompiler
if sys.version_info[0] < 3:
from . import log
else:
from numpy.distutils import log
# --> this is done in numpy/distutils/ccompiler.py
# 3. Force windows to use g77
import distutils.cygwinccompiler
from distutils.version import StrictVersion
from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import (DistutilsExecError, CompileError,
UnknownFileError)
from numpy.distutils.misc_util import (msvc_runtime_library,
get_build_architecture)
# Useful to generate table of symbols from a dll
_START = re.compile(r'\[Ordinal/Name Pointer\] Table')
_TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)')
# the same as cygwin plus some additional parameters
class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler):
compiler_type = 'mingw32'
def __init__ (self,
verbose=0,
dry_run=0,
force=0):
distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose,
dry_run, force)
# we need to support 3.2 which doesn't match the standard
if self.gcc_version is None:
import re
p = subprocess.Popen(['gcc', '-dumpversion'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
result = re.search('(\d+\.\d+)', out_string)
if result:
self.gcc_version = StrictVersion(result.group(1))
# but cygwin 2.91.57 in no-cygwin-mode needs it.
if self.gcc_version <= "2.91.57":
entry_point = '--entry _DllMain@12'
else:
entry_point = ''
if self.linker_dll == 'dllwrap':
# Commented out '--driver-name g++' part that fixes weird
# g++.exe: g++: No such file or directory
# error (mingw 1.0 in Enthon24 tree, gcc-3.4.5).
# If the --driver-name part is required for some environment
# then make the inclusion of this part specific to that
# environment.
self.linker = 'dllwrap' # --driver-name g++'
elif self.linker_dll == 'gcc':
self.linker = 'g++'
p = subprocess.Popen(['gcc', '--version'], shell=True,
stdout=subprocess.PIPE)
out_string = p.stdout.read()
p.stdout.close()
if 'MinGW-W64' not in str(out_string):
# **changes: eric jones 4/11/01
# 1. Check for import library on Windows. Build if it doesn't
build_import_library()
msvcr_success = build_msvcr_library()
msvcr_dbg_success = build_msvcr_library(debug=True)
if msvcr_success or msvcr_dbg_success:
# add preprocessor statement for using customized msvcr lib
self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR')
# Define the MSVC version as hint for MinGW
msvcr_version = '0x%03i0' % int(msvc_runtime_library().lstrip('msvcr'))
self.define_macro('__MSVCRT_VERSION__', msvcr_version)
# MS_WIN64 should be defined when building for amd64 on windows,
# but python headers define it only for MS compilers, which has all
# kind of bad consequences, like using Py_ModuleInit4 instead of
# Py_ModuleInit4_64, etc... So we add it here
if get_build_architecture() == 'AMD64':
if self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall',
compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0'
' -Wall -Wstrict-prototypes',
linker_exe='gcc -g -mno-cygwin',
linker_so='gcc -g -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option
self.set_executables(
compiler='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall',
compiler_so='gcc -march=x86-64 -mtune=generic -DMS_WIN64'
' -O2 -msse2 -Wall -Wstrict-prototypes',
linker_exe='gcc',
linker_so='gcc -shared -Wl,-gc-sections -Wl,-s')
else:
if self.gcc_version <= "3.0.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -w',
compiler_so='gcc -mno-cygwin -mdll -O2 -w'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='%s -mno-cygwin -mdll -static %s' %
(self.linker, entry_point))
elif self.gcc_version < "4.0":
self.set_executables(
compiler='gcc -mno-cygwin -O2 -Wall',
compiler_so='gcc -mno-cygwin -O2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ -mno-cygwin',
linker_so='g++ -mno-cygwin -shared')
else:
# gcc-4 series releases do not support -mno-cygwin option i686
# build needs '-mincoming-stack-boundary=2' due to ABI
# incompatibility to Win32 ABI
self.set_executables(
compiler='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall',
compiler_so='gcc -O2 -march=core2 -mtune=generic'
' -mfpmath=sse -msse2'
' -mincoming-stack-boundary=2 -Wall'
' -Wstrict-prototypes',
linker_exe='g++ ',
linker_so='g++ -shared -Wl,-gc-sections -Wl,-s')
# added for python2.3 support we can't pass it through set_executables
self.compiler_cxx = ['g++']
# no additional libraries needed
#self.dll_libraries=[]
return
# __init__ ()
def link(self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols = None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
# Include the appropiate MSVC runtime library if Python was built
# with MSVC >= 7.0 (MinGW standard is msvcrt)
runtime_library = msvc_runtime_library()
if runtime_library:
if not libraries:
libraries = []
libraries.append(runtime_library)
args = (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
None, #export_symbols, we do this in our def-file
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
if self.gcc_version < "3.0.0":
func = distutils.cygwinccompiler.CygwinCCompiler.link
else:
func = UnixCCompiler.link
func(*args[:func.__code__.co_argcount])
return
def object_filenames (self,
source_filenames,
strip_dir=0,
output_dir=''):
if output_dir is None: output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext (os.path.normcase(src_name))
# added these lines to strip off windows drive letters
# without it, .o files are placed next to .c files
# instead of the build directory
drv, base = os.path.splitdrive(base)
if drv:
base = base[1:]
if ext not in (self.src_extensions + ['.rc', '.res']):
raise UnknownFileError(
"unknown file type '%s' (from '%s')" % \
(ext, src_name))
if strip_dir:
base = os.path.basename (base)
if ext == '.res' or ext == '.rc':
# these need to be compiled to object files
obj_names.append (os.path.join (output_dir,
base + ext + self.obj_extension))
else:
obj_names.append (os.path.join (output_dir,
base + self.obj_extension))
return obj_names
# object_filenames ()
def find_python_dll():
maj, min, micro = [int(i) for i in sys.version_info[:3]]
dllname = 'python%d%d.dll' % (maj, min)
print("Looking for %s" % dllname)
# We can't do much here:
lib_dirs = []
lib_dirs.append(sys.prefix)
lib_dirs.append(os.path.join(sys.prefix, 'lib'))
try:
lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32'))
except KeyError:
pass
for d in lib_dirs:
dll = os.path.join(d, dllname)
if os.path.exists(dll):
return dll
raise ValueError("%s not found in %s" % (dllname, lib_dirs))
def dump_table(dll):
st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE)
return st.stdout.readlines()
def generate_def(dll, dfile):
dump = dump_table(dll)
for i in range(len(dump)):
if _START.match(dump[i].decode()):
break
else:
raise ValueError("Symbol table not found")
syms = []
for j in range(i+1, len(dump)):
m = _TABLE.match(dump[j].decode())
if m:
syms.append((int(m.group(1).strip()), m.group(2)))
else:
break
if len(syms) == 0:
log.warn('No symbols found in %s' % dll)
d = open(dfile, 'w')
d.write('LIBRARY %s\n' % os.path.basename(dll))
d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
d.write(';DATA PRELOAD SINGLE\n')
d.write('\nEXPORTS\n')
for s in syms:
#d.write('@%d %s\n' % (s[0], s[1]))
d.write('%s\n' % s[1])
d.close()
def find_dll(dll_name):
arch = {'AMD64' : 'amd64',
'Intel' : 'x86'}[get_build_architecture()]
def _find_dll_in_winsxs(dll_name):
# Walk through the WinSxS directory to find the dll.
winsxs_path = os.path.join(os.environ['WINDIR'], 'winsxs')
if not os.path.exists(winsxs_path):
return None
for root, dirs, files in os.walk(winsxs_path):
if dll_name in files and arch in root:
return os.path.join(root, dll_name)
return None
def _find_dll_in_path(dll_name):
# First, look in the Python directory, then scan PATH for
# the given dll name.
for path in [sys.prefix] + os.environ['PATH'].split(';'):
filepath = os.path.join(path, dll_name)
if os.path.exists(filepath):
return os.path.abspath(filepath)
return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name)
def build_msvcr_library(debug=False):
if os.name != 'nt':
return False
msvcr_name = msvc_runtime_library()
# Skip using a custom library for versions < MSVC 8.0
if int(msvcr_name.lstrip('msvcr')) < 80:
log.debug('Skip building msvcr library:'
' custom functionality not present')
return False
if debug:
msvcr_name += 'd'
# Skip if custom library already exists
out_name = "lib%s.a" % msvcr_name
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building msvcr library: "%s" exists' %
(out_file,))
return True
# Find the msvcr dll
msvcr_dll_name = msvcr_name + '.dll'
dll_file = find_dll(msvcr_dll_name)
if not dll_file:
log.warn('Cannot build msvcr library: "%s" not found' %
msvcr_dll_name)
return False
def_name = "lib%s.def" % msvcr_name
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building msvcr library: "%s" (from %s)' \
% (out_file, dll_file))
# Generate a symbol definition file from the msvcr dll
generate_def(dll_file, def_file)
# Create a custom mingw library for the given symbol definitions
cmd = ['dlltool', '-d', def_file, '-l', out_file]
retcode = subprocess.call(cmd)
# Clean up symbol definitions
os.remove(def_file)
return (not retcode)
def build_import_library():
if os.name != 'nt':
return
arch = get_build_architecture()
if arch == 'AMD64':
return _build_import_library_amd64()
elif arch == 'Intel':
return _build_import_library_x86()
else:
raise ValueError("Unhandled arch %s" % arch)
def _build_import_library_amd64():
dll_file = find_python_dll()
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' %
(out_file))
return
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building import library (arch=AMD64): "%s" (from %s)' %
(out_file, dll_file))
generate_def(dll_file, def_file)
cmd = ['dlltool', '-d', def_file, '-l', out_file]
subprocess.Popen(cmd)
def _build_import_library_x86():
lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
out_name = "libpython%d%d.a" % tuple(sys.version_info[:2])
out_file = os.path.join(sys.prefix, 'libs', out_name)
if not os.path.isfile(lib_file):
log.warn('Cannot build import library: "%s" not found' % (lib_file))
return
if os.path.isfile(out_file):
log.debug('Skip building import library: "%s" exists' % (out_file))
return
log.info('Building import library (ARCH=x86): "%s"' % (out_file))
from numpy.distutils import lib2def
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)
nm_output = lib2def.getnm(nm_cmd)
dlist, flist = lib2def.parse_nm(nm_output)
lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))
dll_name = "python%d%d.dll" % tuple(sys.version_info[:2])
args = (dll_name, def_file, out_file)
cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args
status = os.system(cmd)
# for now, fail silently
if status:
log.warn('Failed to build import library for gcc. Linking will fail.')
return
#=====================================
# Dealing with Visual Studio MANIFESTS
#=====================================
# Functions to deal with visual studio manifests. Manifest are a mechanism to
# enforce strong DLL versioning on windows, and has nothing to do with
# distutils MANIFEST. manifests are XML files with version info, and used by
# the OS loader; they are necessary when linking against a DLL not in the
# system path; in particular, official python 2.6 binary is built against the
# MS runtime 9 (the one from VS 2008), which is not available on most windows
# systems; python 2.6 installer does install it in the Win SxS (Side by side)
# directory, but this requires the manifest for this to work. This is a big
# mess, thanks MS for a wonderful system.
# XXX: ideally, we should use exactly the same version as used by python. I
# submitted a patch to get this version, but it was only included for python
# 2.6.1 and above. So for versions below, we use a "best guess".
_MSVCRVER_TO_FULLVER = {}
if sys.platform == 'win32':
try:
import msvcrt
# I took one version in my SxS directory: no idea if it is the good
# one, and we can't retrieve it from python
_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"):
major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2)
_MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION
del major, minor, rest
except ImportError:
log.warn('Cannot import msvcrt: using manifest will not be possible')
def msvc_manifest_xml(maj, min):
try:
fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
except KeyError:
raise ValueError("Version %d,%d of MSVCRT not supported yet" %
(maj, min))
# should not have any space before starting, and its size should be
# divisible by 4, most likely for alignement constraints when the xml is
# embedded in the binary...
# This template was copied directly from the python 2.6 binary (using
# strings.exe from mingw on python.exe).
template = """\
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>"""
return template % {'fullver': fullver, 'maj': maj, 'min': min}
def manifest_rc(name, type='dll'):
if type == 'dll':
rctype = 2
elif type == 'exe':
rctype = 1
else:
raise ValueError("Type %s not supported" % type)
return """\
#include "winuser.h"
%d RT_MANIFEST %s""" % (rctype, name)
def check_embedded_msvcr_match_linked(msver):
# check msvcr major version are the same for linking and
# embedding
msvcv = msvc_runtime_library()
if msvcv:
assert msvcv.startswith("msvcr"), msvcv
# Dealing with something like "mscvr90" or "mscvr100", the last
# last digit is the minor release, want int("9") or int("10"):
maj = int(msvcv[5:-1])
if not maj == int(msver):
raise ValueError(
"Discrepancy between linked msvcr " \
"(%d) and the one about to be embedded " \
"(%d)" % (int(msver), maj))
def configtest_name(config):
base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
return os.path.splitext(base)[0]
def manifest_name(config):
# Get configest name (including suffix)
root = configtest_name(config)
exext = config.compiler.exe_extension
return root + exext + ".manifest"
def rc_name(config):
# Get configtest name (including suffix)
root = configtest_name(config)
return root + ".rc"
def generate_manifest(config):
msver = get_build_msvc_version()
if msver is not None:
if msver >= 8:
check_embedded_msvcr_match_linked(msver)
ma = int(msver)
mi = int((msver - ma) * 10)
# Write the manifest file
manxml = msvc_manifest_xml(ma, mi)
man = open(manifest_name(config), "w")
config.temp_files.append(manifest_name(config))
man.write(manxml)
man.close()
| true | true |
f72c3c1f7ed42aa55a23fb88c63f41612e677e8b | 203 | py | Python | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 11 | 2018-05-02T21:31:57.000Z | 2021-11-09T11:40:47.000Z | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 20 | 2018-05-01T14:32:59.000Z | 2022-02-14T21:53:58.000Z | pyBrematic/utils/__init__.py | d-Rickyy-b/Brematic-Controller | 878ace569ff7df0617a35f595cb74244c21ebb9c | [
"MIT"
] | 5 | 2018-11-08T15:35:48.000Z | 2020-12-27T18:28:44.000Z | # -*- coding: utf-8 -*-
from .encoding import DataEncoder
from .rand import Rand
from .singleton import singleton
from .storage import Storage
__all__ = ["singleton", "Storage", "DataEncoder", "Rand"]
| 22.555556 | 57 | 0.724138 |
from .encoding import DataEncoder
from .rand import Rand
from .singleton import singleton
from .storage import Storage
__all__ = ["singleton", "Storage", "DataEncoder", "Rand"]
| true | true |
f72c3cb0514457777ed5fb9a0b71f43e86fde81c | 4,523 | py | Python | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | null | null | null | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | 11 | 2021-04-23T21:25:29.000Z | 2022-03-14T02:40:26.000Z | caw/tests/test_e2e.py | FNNDSC/caw | a41761c4502481f6ccb60ef6e9956464c9b30eb9 | [
"MIT"
] | 1 | 2021-10-17T16:18:30.000Z | 2021-10-17T16:18:30.000Z | """
An end-to-end test which performs the following:
1. creates a ChRIS user account.
2. caw login
3. caw search
4. caw upload --pipeline ...
5. caw download
6. caw logout
"""
import os
import unittest
import random
import string
import requests
import subprocess as sp
from tempfile import NamedTemporaryFile, TemporaryDirectory
from time import sleep
from glob import iglob
def random_string(length=12) -> str:
return ''.join(random.choice(string.ascii_letters) for x in range(length))
address = 'http://localhost:8000/api/v1/'
username = 'caw_test_' + random_string(6)
password = random_string(12)
def create_account():
res = requests.post(
f'{address}users/',
headers={
'Content-Type': 'application/vnd.collection+json',
'Accept': 'application/json'
},
json={
'template': {
'data': [
{
'name': 'email',
'value': f'{username}@babyMRI.org'
},
{
'name': 'username',
'value': username
},
{
'name': 'password',
'value': password
}
]
}
}
)
res.raise_for_status()
data = res.json()
assert 'username' in data
assert data['username'] == username
def poll_feed(feed_url: str, jobs_count: int, poll_interval=10, timeout=300) -> dict:
timer = 0
headers = {
'Accept': 'application/json'
}
data = {}
while timer <= timeout:
print(f'calling get with {feed_url}')
import logging
logging.getLogger().setLevel(logging.DEBUG)
res = requests.get(feed_url, headers=headers, auth=(username, password))
res.raise_for_status()
data = res.json()
if data['finished_jobs'] == jobs_count:
return data
sleep(poll_interval)
timer += poll_interval
return data
class TestEndToEnd(unittest.TestCase):
@unittest.skipUnless('CAW_TEST_FULL' in os.environ, 'Set CAW_TEST_FULL=y to run the end-to-end test.')
def test_endtoend(self):
create_account()
sp.run(['caw', '--address', address, '--username', username, 'login', '--password-stdin'],
input=(password + '\n'), text=True, check=True)
with NamedTemporaryFile('w', suffix='.txt', delete=False) as f:
f.write("If you steal from one author it's plagiarism; if you steal from"
"\nmany it's research."
'\n -- Wilson Mizner\n')
search = sp.check_output(['caw', 'search'], text=True)
self.assertIn('Example branching pipeline', search,
msg='"Example branching pipeline" not found in `caw search`')
feed_url = sp.check_output(['caw', 'upload', '--pipeline', 'Example branching pipeline', '--', f.name],
text=True).rstrip('\n')
self.assertTrue(feed_url.startswith(address),
msg='Feed URL was not correctly printed after `caw upload`')
self.assertTrue(feed_url.endswith('/'),
msg='Feed URL was not correctly printed after `caw upload`')
feed_data = poll_feed(feed_url, jobs_count=9)
with TemporaryDirectory() as tmpdir:
sp.run(['caw', 'download', feed_data['files'], tmpdir])
# the pipeline runs pl-dircopy --prefix L where L is a letter.
# if the DAG is constructed properly, it should produce the following prefixes
prefixes = {'', 'a', 'ba', 'ca', 'dba', 'eca', 'fca', 'gca', 'hgca'}
suffix = os.path.basename(f.name)
results = [
# example:
# '/tmp/folder/caw_test_SzvEhj/feed_10/pl-dircopy_81/pl-simpledsapp_82/pl-simpledsapp_83/pl-simpledsapp_85/data/fcatmpl_hy4m5o.txt'
# --> 'fca'
os.path.basename(fname[:-len(suffix)])
for fname in iglob(os.path.join(tmpdir, '**', '*' + suffix), recursive=True)
]
self.assertEqual(len(results), 9, msg='Incorrect number of files produced by feed.')
self.assertSetEqual(prefixes, set(results),
msg='DAG not reconstructed in the correct order.')
sp.run(['caw', 'logout'])
if __name__ == '__main__':
unittest.main()
| 34.007519 | 147 | 0.554941 |
import os
import unittest
import random
import string
import requests
import subprocess as sp
from tempfile import NamedTemporaryFile, TemporaryDirectory
from time import sleep
from glob import iglob
def random_string(length=12) -> str:
return ''.join(random.choice(string.ascii_letters) for x in range(length))
address = 'http://localhost:8000/api/v1/'
username = 'caw_test_' + random_string(6)
password = random_string(12)
def create_account():
res = requests.post(
f'{address}users/',
headers={
'Content-Type': 'application/vnd.collection+json',
'Accept': 'application/json'
},
json={
'template': {
'data': [
{
'name': 'email',
'value': f'{username}@babyMRI.org'
},
{
'name': 'username',
'value': username
},
{
'name': 'password',
'value': password
}
]
}
}
)
res.raise_for_status()
data = res.json()
assert 'username' in data
assert data['username'] == username
def poll_feed(feed_url: str, jobs_count: int, poll_interval=10, timeout=300) -> dict:
timer = 0
headers = {
'Accept': 'application/json'
}
data = {}
while timer <= timeout:
print(f'calling get with {feed_url}')
import logging
logging.getLogger().setLevel(logging.DEBUG)
res = requests.get(feed_url, headers=headers, auth=(username, password))
res.raise_for_status()
data = res.json()
if data['finished_jobs'] == jobs_count:
return data
sleep(poll_interval)
timer += poll_interval
return data
class TestEndToEnd(unittest.TestCase):
@unittest.skipUnless('CAW_TEST_FULL' in os.environ, 'Set CAW_TEST_FULL=y to run the end-to-end test.')
def test_endtoend(self):
create_account()
sp.run(['caw', '--address', address, '--username', username, 'login', '--password-stdin'],
input=(password + '\n'), text=True, check=True)
with NamedTemporaryFile('w', suffix='.txt', delete=False) as f:
f.write("If you steal from one author it's plagiarism; if you steal from"
"\nmany it's research."
'\n -- Wilson Mizner\n')
search = sp.check_output(['caw', 'search'], text=True)
self.assertIn('Example branching pipeline', search,
msg='"Example branching pipeline" not found in `caw search`')
feed_url = sp.check_output(['caw', 'upload', '--pipeline', 'Example branching pipeline', '--', f.name],
text=True).rstrip('\n')
self.assertTrue(feed_url.startswith(address),
msg='Feed URL was not correctly printed after `caw upload`')
self.assertTrue(feed_url.endswith('/'),
msg='Feed URL was not correctly printed after `caw upload`')
feed_data = poll_feed(feed_url, jobs_count=9)
with TemporaryDirectory() as tmpdir:
sp.run(['caw', 'download', feed_data['files'], tmpdir])
prefixes = {'', 'a', 'ba', 'ca', 'dba', 'eca', 'fca', 'gca', 'hgca'}
suffix = os.path.basename(f.name)
results = [
os.path.basename(fname[:-len(suffix)])
for fname in iglob(os.path.join(tmpdir, '**', '*' + suffix), recursive=True)
]
self.assertEqual(len(results), 9, msg='Incorrect number of files produced by feed.')
self.assertSetEqual(prefixes, set(results),
msg='DAG not reconstructed in the correct order.')
sp.run(['caw', 'logout'])
if __name__ == '__main__':
unittest.main()
| true | true |
f72c3ce1384bcf313ac21687415c8302c74d8838 | 5,540 | py | Python | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | null | null | null | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | 3 | 2021-03-31T19:37:57.000Z | 2021-12-13T20:32:40.000Z | clothingBot.py | MohamedBengezi/clothingBot | da48eec8548579be70e6990b991af8d0d9aa9c77 | [
"MIT"
] | null | null | null | import sys
import json
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
site_000 = 'https://apolina-kids.com/collections/all'
def findItem(prodName):
elem = driver.find_element_by_xpath('//img[contains(@alt,"'+prodName+'")]')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, 5, 5)
action.click()
action.perform()
def selectSize():
try:
select = driver.find_element_by_xpath(
"//select[@id=\"product-select-4540644753485-option-0\"]")
all_options = select.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "5-7Y":
print("Value is: %s" % value)
option.click()
except:
print('No select found')
def addToCart():
try:
addToCart = driver.find_element_by_xpath(
"//input[@value='Add to Cart']")
except:
print('Add To Cart button not found')
try:
addToCart.send_keys(webdriver.common.keys.Keys.RETURN)
except:
try:
addToCart.click()
except:
print("Could not click 'Add to cart'")
sleep(2)
checkout = driver.find_element_by_xpath(
"//input[@value='Check Out']")
checkout.send_keys(webdriver.common.keys.Keys.RETURN)
def clickButton(id):
if (id is None):
cont = driver.find_element_by_name("button")
else:
cont = driver.find_element_by_id(id)
cont.send_keys(webdriver.common.keys.Keys.RETURN)
def shippingDetails():
with open('info.json') as f:
data = json.load(f)
email = driver.find_element_by_id("checkout_email")
email.send_keys(data['email'])
firstName = driver.find_element_by_id(
"checkout_shipping_address_first_name")
firstName.send_keys(data['firstName'])
lastName = driver.find_element_by_id("checkout_shipping_address_last_name")
lastName.send_keys(data['lastName'])
address = driver.find_element_by_id(
"checkout_shipping_address_address1")
address.send_keys(data['address'])
try:
aprtment = driver.find_element_by_id(
"checkout_shipping_address_address2")
aprtment.send_keys(data['apartment'])
except:
print('Not an apartment')
city = driver.find_element_by_id(
"checkout_shipping_address_city")
city.send_keys(data['city'])
country = driver.find_element_by_id(
"checkout_shipping_address_country")
all_options = country.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "United States":
option.click()
break
state = driver.find_element_by_id(
"checkout_shipping_address_province")
state_options = state.find_elements_by_tag_name("option")
for states in state_options:
value1 = states.get_attribute("value")
print("Value1 is: %s" % value1)
if value1 == data['state']:
print("Value is: %s" % value1)
states.click()
break
zipcode = driver.find_element_by_id(
"checkout_shipping_address_zip")
zipcode.send_keys(data['zipcode'])
phone = driver.find_element_by_id("checkout_shipping_address_phone")
phone.send_keys(data['phone'])
# def inputPayment():
# driver.switch_to.frame(driver.find_element_by_xpath(
# "//*[contains(@id,'card-fields-number')]"))
# wait = WebDriverWait(driver, 10)
# wait.until(EC.frame_to_be_available_and_switch_to_it(
# (By.CLASS_NAME, "card-fields-iframe")))
# cardNumber = driver.find_element_by_id("number")
# cardNumber.send_keys('4930 0000 0000 0000')
# name = WebDriverWait(driver, 20).until(EC.element_to_be_clickable(
# (By.XPATH, "//input[@id='name']")))
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# name,
# "value",
# "NNAAAAMME")
# name.send_keys('NAME')
# name.send_keys(webdriver.common.keys.Keys.RETURN)
# js = "arguments[0].setAttribute('value','\"+NAME+\"')"
# expiry = driver.find_element_by_id("expiry")
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# expiry,
# "value",
# "04 / 34")
# verification_value = driver.find_element_by_id("verification_value")
# driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
# verification_value,
# "value",
# "123")
# sleep(10)
# driver.switch_to.default_content()
if __name__ == '__main__':
# setting the site and driver
driver = webdriver.Firefox()
# load the site
URL = site_000
driver.get(URL)
sleep(1)
findItem('POL DRESS - FARM CHECK / HAY')
sleep(1)
selectSize()
addToCart()
sleep(3)
shippingDetails()
clickButton(None)
sleep(2.5)
clickButton(None)
sleep(3)
| 31.657143 | 85 | 0.638809 | import sys
import json
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
site_000 = 'https://apolina-kids.com/collections/all'
def findItem(prodName):
elem = driver.find_element_by_xpath('//img[contains(@alt,"'+prodName+'")]')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, 5, 5)
action.click()
action.perform()
def selectSize():
try:
select = driver.find_element_by_xpath(
"//select[@id=\"product-select-4540644753485-option-0\"]")
all_options = select.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "5-7Y":
print("Value is: %s" % value)
option.click()
except:
print('No select found')
def addToCart():
try:
addToCart = driver.find_element_by_xpath(
"//input[@value='Add to Cart']")
except:
print('Add To Cart button not found')
try:
addToCart.send_keys(webdriver.common.keys.Keys.RETURN)
except:
try:
addToCart.click()
except:
print("Could not click 'Add to cart'")
sleep(2)
checkout = driver.find_element_by_xpath(
"//input[@value='Check Out']")
checkout.send_keys(webdriver.common.keys.Keys.RETURN)
def clickButton(id):
if (id is None):
cont = driver.find_element_by_name("button")
else:
cont = driver.find_element_by_id(id)
cont.send_keys(webdriver.common.keys.Keys.RETURN)
def shippingDetails():
with open('info.json') as f:
data = json.load(f)
email = driver.find_element_by_id("checkout_email")
email.send_keys(data['email'])
firstName = driver.find_element_by_id(
"checkout_shipping_address_first_name")
firstName.send_keys(data['firstName'])
lastName = driver.find_element_by_id("checkout_shipping_address_last_name")
lastName.send_keys(data['lastName'])
address = driver.find_element_by_id(
"checkout_shipping_address_address1")
address.send_keys(data['address'])
try:
aprtment = driver.find_element_by_id(
"checkout_shipping_address_address2")
aprtment.send_keys(data['apartment'])
except:
print('Not an apartment')
city = driver.find_element_by_id(
"checkout_shipping_address_city")
city.send_keys(data['city'])
country = driver.find_element_by_id(
"checkout_shipping_address_country")
all_options = country.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
if value == "United States":
option.click()
break
state = driver.find_element_by_id(
"checkout_shipping_address_province")
state_options = state.find_elements_by_tag_name("option")
for states in state_options:
value1 = states.get_attribute("value")
print("Value1 is: %s" % value1)
if value1 == data['state']:
print("Value is: %s" % value1)
states.click()
break
zipcode = driver.find_element_by_id(
"checkout_shipping_address_zip")
zipcode.send_keys(data['zipcode'])
phone = driver.find_element_by_id("checkout_shipping_address_phone")
phone.send_keys(data['phone'])
if __name__ == '__main__':
driver = webdriver.Firefox()
URL = site_000
driver.get(URL)
sleep(1)
findItem('POL DRESS - FARM CHECK / HAY')
sleep(1)
selectSize()
addToCart()
sleep(3)
shippingDetails()
clickButton(None)
sleep(2.5)
clickButton(None)
sleep(3)
| true | true |
f72c3d058896a02a0504926742ddd9e972b29447 | 15,106 | py | Python | twilio/rest/conversations/v1/service/configuration/notification.py | timgates42/twilio-python | ef29d03a4857b62b616df4a8f4f2b7c294afbb99 | [
"MIT"
] | 2 | 2022-01-13T10:58:03.000Z | 2022-03-16T07:12:17.000Z | venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py | syt1209/PythonProjects | 0409dbd3c0b0ddf00debc38875059c828eb31dec | [
"MIT"
] | 9 | 2018-05-07T21:59:44.000Z | 2022-01-29T22:49:29.000Z | venv/Lib/site-packages/twilio/rest/conversations/v1/service/configuration/notification.py | syt1209/PythonProjects | 0409dbd3c0b0ddf00debc38875059c828eb31dec | [
"MIT"
] | 4 | 2021-03-25T09:00:08.000Z | 2021-08-05T06:54:23.000Z | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NotificationList(ListResource):
def __init__(self, version, chat_service_sid):
"""
Initialize the NotificationList
:param Version version: Version that contains the resource
:param chat_service_sid: The unique string that identifies the resource
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationList
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationList
"""
super(NotificationList, self).__init__(version)
# Path Solution
self._solution = {'chat_service_sid': chat_service_sid, }
def get(self):
"""
Constructs a NotificationContext
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __call__(self):
"""
Constructs a NotificationContext
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.NotificationList>'
class NotificationPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the NotificationPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param chat_service_sid: The unique string that identifies the resource
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationPage
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationPage
"""
super(NotificationPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of NotificationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Conversations.V1.NotificationPage>'
class NotificationContext(InstanceContext):
def __init__(self, version, chat_service_sid):
"""
Initialize the NotificationContext
:param Version version: Version that contains the resource
:param chat_service_sid: The SID of the Conversation Service that the Configuration applies to.
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
super(NotificationContext, self).__init__(version)
# Path Solution
self._solution = {'chat_service_sid': chat_service_sid, }
self._uri = '/Services/{chat_service_sid}/Configuration/Notifications'.format(**self._solution)
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
"""
Update the NotificationInstance
:param bool log_enabled: Weather the notification logging is enabled.
:param bool new_message_enabled: Whether to send a notification when a new message is added to a conversation.
:param unicode new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation.
:param unicode new_message_sound: The name of the sound to play when a new message is added to a conversation.
:param bool new_message_badge_count_enabled: Whether the new message badge is enabled.
:param bool added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation.
:param unicode added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation.
:param unicode added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation.
:param bool removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation.
:param unicode removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed.
:param unicode removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation.
:returns: The updated NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
data = values.of({
'LogEnabled': log_enabled,
'NewMessage.Enabled': new_message_enabled,
'NewMessage.Template': new_message_template,
'NewMessage.Sound': new_message_sound,
'NewMessage.BadgeCountEnabled': new_message_badge_count_enabled,
'AddedToConversation.Enabled': added_to_conversation_enabled,
'AddedToConversation.Template': added_to_conversation_template,
'AddedToConversation.Sound': added_to_conversation_sound,
'RemovedFromConversation.Enabled': removed_from_conversation_enabled,
'RemovedFromConversation.Template': removed_from_conversation_template,
'RemovedFromConversation.Sound': removed_from_conversation_sound,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def fetch(self):
"""
Fetch the NotificationInstance
:returns: The fetched NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationContext {}>'.format(context)
class NotificationInstance(InstanceResource):
def __init__(self, version, payload, chat_service_sid):
"""
Initialize the NotificationInstance
:returns: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
super(NotificationInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'new_message': payload.get('new_message'),
'added_to_conversation': payload.get('added_to_conversation'),
'removed_from_conversation': payload.get('removed_from_conversation'),
'log_enabled': payload.get('log_enabled'),
'url': payload.get('url'),
}
# Context
self._context = None
self._solution = {'chat_service_sid': chat_service_sid, }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: NotificationContext for this NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationContext
"""
if self._context is None:
self._context = NotificationContext(
self._version,
chat_service_sid=self._solution['chat_service_sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The unique ID of the Account responsible for this configuration.
:rtype: unicode
"""
return self._properties['account_sid']
@property
def chat_service_sid(self):
"""
:returns: The SID of the Conversation Service that the Configuration applies to.
:rtype: unicode
"""
return self._properties['chat_service_sid']
@property
def new_message(self):
"""
:returns: The Push Notification configuration for New Messages.
:rtype: dict
"""
return self._properties['new_message']
@property
def added_to_conversation(self):
"""
:returns: The Push Notification configuration for being added to a Conversation.
:rtype: dict
"""
return self._properties['added_to_conversation']
@property
def removed_from_conversation(self):
"""
:returns: The Push Notification configuration for being removed from a Conversation.
:rtype: dict
"""
return self._properties['removed_from_conversation']
@property
def log_enabled(self):
"""
:returns: Weather the notification logging is enabled.
:rtype: bool
"""
return self._properties['log_enabled']
@property
def url(self):
"""
:returns: An absolute URL for this configuration.
:rtype: unicode
"""
return self._properties['url']
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
"""
Update the NotificationInstance
:param bool log_enabled: Weather the notification logging is enabled.
:param bool new_message_enabled: Whether to send a notification when a new message is added to a conversation.
:param unicode new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation.
:param unicode new_message_sound: The name of the sound to play when a new message is added to a conversation.
:param bool new_message_badge_count_enabled: Whether the new message badge is enabled.
:param bool added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation.
:param unicode added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation.
:param unicode added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation.
:param bool removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation.
:param unicode removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed.
:param unicode removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation.
:returns: The updated NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return self._proxy.update(
log_enabled=log_enabled,
new_message_enabled=new_message_enabled,
new_message_template=new_message_template,
new_message_sound=new_message_sound,
new_message_badge_count_enabled=new_message_badge_count_enabled,
added_to_conversation_enabled=added_to_conversation_enabled,
added_to_conversation_template=added_to_conversation_template,
added_to_conversation_sound=added_to_conversation_sound,
removed_from_conversation_enabled=removed_from_conversation_enabled,
removed_from_conversation_template=removed_from_conversation_template,
removed_from_conversation_sound=removed_from_conversation_sound,
)
def fetch(self):
"""
Fetch the NotificationInstance
:returns: The fetched NotificationInstance
:rtype: twilio.rest.conversations.v1.service.configuration.notification.NotificationInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationInstance {}>'.format(context)
| 42.672316 | 163 | 0.693632 |
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class NotificationList(ListResource):
def __init__(self, version, chat_service_sid):
super(NotificationList, self).__init__(version)
self._solution = {'chat_service_sid': chat_service_sid, }
def get(self):
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __call__(self):
return NotificationContext(self._version, chat_service_sid=self._solution['chat_service_sid'], )
def __repr__(self):
return '<Twilio.Conversations.V1.NotificationList>'
class NotificationPage(Page):
def __init__(self, version, response, solution):
super(NotificationPage, self).__init__(version, response)
self._solution = solution
def get_instance(self, payload):
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
return '<Twilio.Conversations.V1.NotificationPage>'
class NotificationContext(InstanceContext):
def __init__(self, version, chat_service_sid):
super(NotificationContext, self).__init__(version)
self._solution = {'chat_service_sid': chat_service_sid, }
self._uri = '/Services/{chat_service_sid}/Configuration/Notifications'.format(**self._solution)
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
data = values.of({
'LogEnabled': log_enabled,
'NewMessage.Enabled': new_message_enabled,
'NewMessage.Template': new_message_template,
'NewMessage.Sound': new_message_sound,
'NewMessage.BadgeCountEnabled': new_message_badge_count_enabled,
'AddedToConversation.Enabled': added_to_conversation_enabled,
'AddedToConversation.Template': added_to_conversation_template,
'AddedToConversation.Sound': added_to_conversation_sound,
'RemovedFromConversation.Enabled': removed_from_conversation_enabled,
'RemovedFromConversation.Template': removed_from_conversation_template,
'RemovedFromConversation.Sound': removed_from_conversation_sound,
})
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def fetch(self):
payload = self._version.fetch(method='GET', uri=self._uri, )
return NotificationInstance(
self._version,
payload,
chat_service_sid=self._solution['chat_service_sid'],
)
def __repr__(self):
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationContext {}>'.format(context)
class NotificationInstance(InstanceResource):
def __init__(self, version, payload, chat_service_sid):
super(NotificationInstance, self).__init__(version)
self._properties = {
'account_sid': payload.get('account_sid'),
'chat_service_sid': payload.get('chat_service_sid'),
'new_message': payload.get('new_message'),
'added_to_conversation': payload.get('added_to_conversation'),
'removed_from_conversation': payload.get('removed_from_conversation'),
'log_enabled': payload.get('log_enabled'),
'url': payload.get('url'),
}
self._context = None
self._solution = {'chat_service_sid': chat_service_sid, }
@property
def _proxy(self):
if self._context is None:
self._context = NotificationContext(
self._version,
chat_service_sid=self._solution['chat_service_sid'],
)
return self._context
@property
def account_sid(self):
return self._properties['account_sid']
@property
def chat_service_sid(self):
return self._properties['chat_service_sid']
@property
def new_message(self):
return self._properties['new_message']
@property
def added_to_conversation(self):
return self._properties['added_to_conversation']
@property
def removed_from_conversation(self):
return self._properties['removed_from_conversation']
@property
def log_enabled(self):
return self._properties['log_enabled']
@property
def url(self):
return self._properties['url']
def update(self, log_enabled=values.unset, new_message_enabled=values.unset,
new_message_template=values.unset, new_message_sound=values.unset,
new_message_badge_count_enabled=values.unset,
added_to_conversation_enabled=values.unset,
added_to_conversation_template=values.unset,
added_to_conversation_sound=values.unset,
removed_from_conversation_enabled=values.unset,
removed_from_conversation_template=values.unset,
removed_from_conversation_sound=values.unset):
return self._proxy.update(
log_enabled=log_enabled,
new_message_enabled=new_message_enabled,
new_message_template=new_message_template,
new_message_sound=new_message_sound,
new_message_badge_count_enabled=new_message_badge_count_enabled,
added_to_conversation_enabled=added_to_conversation_enabled,
added_to_conversation_template=added_to_conversation_template,
added_to_conversation_sound=added_to_conversation_sound,
removed_from_conversation_enabled=removed_from_conversation_enabled,
removed_from_conversation_template=removed_from_conversation_template,
removed_from_conversation_sound=removed_from_conversation_sound,
)
def fetch(self):
return self._proxy.fetch()
def __repr__(self):
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Conversations.V1.NotificationInstance {}>'.format(context)
| true | true |
f72c3d8a0d20aa867b3ae48210aa041fe0e1ebf3 | 516 | py | Python | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 11,750 | 2015-10-12T07:03:39.000Z | 2022-03-31T20:43:15.000Z | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,951 | 2015-10-12T00:41:25.000Z | 2022-03-31T22:19:26.000Z | env/Lib/site-packages/plotly/validators/violin/_points.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,623 | 2015-10-15T14:40:27.000Z | 2022-03-28T16:05:50.000Z | import _plotly_utils.basevalidators
class PointsValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="points", parent_name="violin", **kwargs):
super(PointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop(
"values", ["all", "outliers", "suspectedoutliers", False]
),
**kwargs
)
| 34.4 | 77 | 0.622093 | import _plotly_utils.basevalidators
class PointsValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="points", parent_name="violin", **kwargs):
super(PointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop(
"values", ["all", "outliers", "suspectedoutliers", False]
),
**kwargs
)
| true | true |
f72c3deb6a646c951f899749fe2ceefc65d3ed16 | 5,534 | py | Python | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | null | null | null | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | null | null | null | plotly/graph_objs/layout/scene/_domain.py | omridanan/plotly.py | a8d26670cba49ce15ce9b7639ae0f55a6088a825 | [
"MIT"
] | 1 | 2019-02-18T04:12:56.000Z | 2019-02-18T04:12:56.000Z | from plotly.basedatatypes import BaseLayoutHierarchyType
import copy
class Domain(BaseLayoutHierarchyType):
# column
# ------
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this scene subplot .
The 'column' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self['column']
@column.setter
def column(self, val):
self['column'] = val
# row
# ---
@property
def row(self):
"""
If there is a layout grid, use the domain for this row in the
grid for this scene subplot .
The 'row' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self['row']
@row.setter
def row(self, val):
self['row'] = val
# x
# -
@property
def x(self):
"""
Sets the horizontal domain of this scene subplot (in plot
fraction).
The 'x' property is an info array that may be specified as a
list or tuple of 2 elements where:
(0) The 'x[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'x[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self['x']
@x.setter
def x(self, val):
self['x'] = val
# y
# -
@property
def y(self):
"""
Sets the vertical domain of this scene subplot (in plot
fraction).
The 'y' property is an info array that may be specified as a
list or tuple of 2 elements where:
(0) The 'y[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'y[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self['y']
@y.setter
def y(self, val):
self['y'] = val
# property parent name
# --------------------
@property
def _parent_path_str(self):
return 'layout.scene'
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
"""
def __init__(
self, arg=None, column=None, row=None, x=None, y=None, **kwargs
):
"""
Construct a new Domain object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of plotly.graph_objs.layout.scene.Domain
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
Returns
-------
Domain
"""
super(Domain, self).__init__('domain')
# Validate arg
# ------------
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.Domain
constructor must be a dict or
an instance of plotly.graph_objs.layout.scene.Domain"""
)
# Import validators
# -----------------
from plotly.validators.layout.scene import (domain as v_domain)
# Initialize validators
# ---------------------
self._validators['column'] = v_domain.ColumnValidator()
self._validators['row'] = v_domain.RowValidator()
self._validators['x'] = v_domain.XValidator()
self._validators['y'] = v_domain.YValidator()
# Populate data dict with properties
# ----------------------------------
_v = arg.pop('column', None)
self.column = column if column is not None else _v
_v = arg.pop('row', None)
self.row = row if row is not None else _v
_v = arg.pop('x', None)
self.x = x if x is not None else _v
_v = arg.pop('y', None)
self.y = y if y is not None else _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
| 27.809045 | 71 | 0.527647 | from plotly.basedatatypes import BaseLayoutHierarchyType
import copy
class Domain(BaseLayoutHierarchyType):
@property
def column(self):
return self['column']
@column.setter
def column(self, val):
self['column'] = val
@property
def row(self):
return self['row']
@row.setter
def row(self, val):
self['row'] = val
@property
def x(self):
return self['x']
@x.setter
def x(self, val):
self['x'] = val
@property
def y(self):
return self['y']
@y.setter
def y(self, val):
self['y'] = val
@property
def _parent_path_str(self):
return 'layout.scene'
@property
def _prop_descriptions(self):
return """\
column
If there is a layout grid, use the domain for this
column in the grid for this scene subplot .
row
If there is a layout grid, use the domain for this row
in the grid for this scene subplot .
x
Sets the horizontal domain of this scene subplot (in
plot fraction).
y
Sets the vertical domain of this scene subplot (in plot
fraction).
"""
def __init__(
self, arg=None, column=None, row=None, x=None, y=None, **kwargs
):
super(Domain, self).__init__('domain')
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.Domain
constructor must be a dict or
an instance of plotly.graph_objs.layout.scene.Domain"""
)
from plotly.validators.layout.scene import (domain as v_domain)
self._validators['column'] = v_domain.ColumnValidator()
self._validators['row'] = v_domain.RowValidator()
self._validators['x'] = v_domain.XValidator()
self._validators['y'] = v_domain.YValidator()
_v = arg.pop('column', None)
self.column = column if column is not None else _v
_v = arg.pop('row', None)
self.row = row if row is not None else _v
_v = arg.pop('x', None)
self.x = x if x is not None else _v
_v = arg.pop('y', None)
self.y = y if y is not None else _v
self._process_kwargs(**dict(arg, **kwargs))
| true | true |
f72c3e5bb5282a9d3bfbafdfee816454ab692053 | 64,538 | py | Python | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | tests/test_scottbrian_algo1/test_algo_api.py | ScottBrian/scottbrian_algo1 | 57cd8fc5674507db51b1c887d5f9a68462b0ca9d | [
"MIT"
] | null | null | null | """test_algo_api.py module."""
# from datetime import datetime, timedelta
import pytest
# import sys
# from pathlib import Path
import numpy as np
import pandas as pd # type: ignore
import string
import math
from typing import Any, List, NamedTuple
# from typing_extensions import Final
from ibapi.tag_value import TagValue # type: ignore
from ibapi.contract import ComboLeg # type: ignore
from ibapi.contract import DeltaNeutralContract
from ibapi.contract import Contract, ContractDetails
from scottbrian_algo1.algo_api import AlgoApp, AlreadyConnected, \
DisconnectLockHeld, ConnectTimeout, RequestTimeout, DisconnectDuringRequest
from scottbrian_algo1.algo_maps import get_contract_dict, get_contract_obj
from scottbrian_algo1.algo_maps import get_contract_details_obj
# from scottbrian_utils.diag_msg import diag_msg
# from scottbrian_utils.file_catalog import FileCatalog
import logging
logger = logging.getLogger(__name__)
###############################################################################
# TestAlgoAppConnect class
###############################################################################
class TestAlgoAppConnect:
"""TestAlgoAppConnect class."""
def test_mock_connect_to_ib(self,
algo_app: "AlgoApp"
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
"""
verify_algo_app_initialized(algo_app)
# we are testing connect_to_ib and the subsequent code that gets
# control as a result, such as getting the first requestID and then
# starting a separate thread for the run loop.
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_mock_connect_to_ib_with_timeout(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# we are testing connect_to_ib with a simulated timeout
logger.debug("about to connect")
with pytest.raises(ConnectTimeout):
algo_app.connect_to_ib("127.0.0.1",
mock_ib.PORT_FOR_REQID_TIMEOUT,
client_id=0)
# verify that algo_app is not connected
verify_algo_app_disconnected(algo_app)
assert algo_app.request_id == 0
def test_connect_to_ib_already_connected(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# first, connect normally to mock_ib
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_PAPER_TRADING,
client_id=0)
# verify that algo_app is connected
verify_algo_app_connected(algo_app)
# try to connect again - should get error
with pytest.raises(AlreadyConnected):
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_PAPER_TRADING,
client_id=0)
# verify that algo_app is still connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_connect_to_ib_with_lock_held(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test connecting to IB with disconnect lock held.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
# obtain the disconnect lock
logger.debug("about to obtain disconnect lock")
algo_app.disconnect_lock.acquire()
# try to connect - should get error
with pytest.raises(DisconnectLockHeld):
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is still simply initialized
verify_algo_app_initialized(algo_app)
# def test_real_connect_to_IB(self) -> None:
# """Test connecting to IB.
#
# Args:
# algo_app: instance of AlgoApp from conftest pytest fixture
# monkeypatch: pytest fixture
#
# """
# proj_dir = Path.cwd().resolve().parents[1] # back two directories
# test_cat = \
# FileCatalog({'symbols': Path(proj_dir / 't_datasets/symbols.csv')
# })
# algo_app = AlgoApp(test_cat)
# verify_algo_app_initialized(algo_app)
#
# # we are testing connect_to_ib and the subsequent code that gets
# # control as a result, such as getting the first requestID and then
# # starting a separate thread for the run loop.
# logger.debug("about to connect")
# connect_ans = algo_app.connect_to_ib("127.0.0.1", 7496, client_id=0)
#
# # verify that algo_app is connected and alive with a valid reqId
# assert connect_ans
# assert algo_app.run_thread.is_alive()
# assert algo_app.isConnected()
# assert algo_app.request_id == 1
#
# algo_app.disconnect_from_ib()
# assert not algo_app.run_thread.is_alive()
# assert not algo_app.isConnected()
###############################################################################
# connect disconnect verification
###############################################################################
def verify_algo_app_initialized(algo_app: "AlgoApp") -> None:
"""Helper function to verify the also_app instance is initialized.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert len(algo_app.ds_catalog) > 0
assert algo_app.request_id == 0
assert algo_app.symbols.empty
assert algo_app.stock_symbols.empty
assert algo_app.response_complete_event.is_set() is False
assert algo_app.nextValidId_event.is_set() is False
assert algo_app.__repr__() == 'AlgoApp(ds_catalog)'
# assert algo_app.run_thread is None
def verify_algo_app_connected(algo_app: "AlgoApp") -> None:
"""Helper function to verify we are connected to ib.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert algo_app.run_thread.is_alive()
assert algo_app.isConnected()
assert algo_app.request_id == 1
def verify_algo_app_disconnected(algo_app: "AlgoApp") -> None:
"""Helper function to verify we are disconnected from ib.
Args:
algo_app: instance of AlgoApp that is to be checked
"""
assert not algo_app.run_thread.is_alive()
assert not algo_app.isConnected()
###############################################################################
###############################################################################
# matching symbols
###############################################################################
###############################################################################
class ExpCounts(NamedTuple):
"""NamedTuple for the expected counts."""
sym_non_recursive: int
sym_recursive: int
stock_sym_non_recursive: int
stock_sym_recursive: int
class SymDfs:
"""Saved sym dfs."""
def __init__(self,
mock_sym_df: Any,
sym_df: Any,
mock_stock_sym_df: Any,
stock_sym_df: Any) -> None:
"""Initialize the SymDfs.
Args:
mock_sym_df: mock sym DataFrame
sym_df: symbol DataFrame
mock_stock_sym_df: mock stock symbol DataFrame
stock_sym_df: stock symbols dataFrame
"""
self.mock_sym_df = mock_sym_df
self.sym_df = sym_df
self.mock_stock_sym_df = mock_stock_sym_df
self.stock_sym_df = stock_sym_df
class TestAlgoAppMatchingSymbols:
"""TestAlgoAppMatchingSymbols class."""
def test_request_symbols_all_combos(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test request_symbols with all patterns.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
try:
for idx, search_pattern in enumerate(
mock_ib.search_patterns()):
exp_counts = get_exp_number(search_pattern, mock_ib)
# verify symbol table has zero entries for the symbol
logger.info("calling verify_match_symbols req_type 1 "
"sym %s num %d", search_pattern, idx)
algo_app.symbols = pd.DataFrame()
algo_app.stock_symbols = pd.DataFrame()
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=1)
logger.info("calling verify_match_symbols req_type 2 "
"sym %s num %d", search_pattern, idx)
algo_app.symbols = pd.DataFrame()
algo_app.stock_symbols = pd.DataFrame()
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=2)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_request_symbols_zero_result(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test request_symbols with pattern that finds exactly 1 symbol.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
try:
exp_counts = ExpCounts(0, 0, 0, 0)
# verify symbol table has zero entries for the symbols
for idx, search_pattern in enumerate(
mock_ib.no_find_search_patterns()):
logger.info("calling verify_match_symbols req_type 1 "
"sym %s num %d", search_pattern, idx)
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=1)
logger.info("calling verify_match_symbols req_type 2 "
"sym %s num %d", search_pattern, idx)
verify_match_symbols(algo_app,
mock_ib,
search_pattern,
exp_counts=exp_counts,
req_type=2)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_timeout(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols gets timeout.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
mock_ib.PORT_FOR_SIMULATE_REQUEST_TIMEOUT,
client_id=0)
verify_algo_app_connected(algo_app)
with pytest.raises(RequestTimeout):
algo_app.request_symbols('A')
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_disconnect(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols gets disconnected while waiting.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
mock_ib.
PORT_FOR_SIMULATE_REQUEST_DISCONNECT,
client_id=0)
verify_algo_app_connected(algo_app)
with pytest.raises(DisconnectDuringRequest):
algo_app.request_symbols('A')
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols with pattern that finds no symbols.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
sym_dfs = SymDfs(pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame())
# full_stock_sym_match_descs = pd.DataFrame()
# stock_symbols_ds = pd.DataFrame()
# full_sym_match_descs = pd.DataFrame()
# symbols_ds = pd.DataFrame()
# we need to loop from A to Z
for letter in string.ascii_uppercase:
logger.debug("about to verify_get_symbols for letter %s",
letter)
# full_stock_sym_match_descs, stock_symbols_ds,\
# full_sym_match_descs, symbols_ds = \
sym_dfs = verify_get_symbols(letter,
algo_app,
mock_ib,
sym_dfs)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug('disconnected - test case returning')
def test_get_symbols_with_connect_disconnect(self,
algo_app: "AlgoApp",
mock_ib: Any) -> None:
"""Test get_symbols with pattern that finds no symbols.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
sym_dfs = SymDfs(pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame(),
pd.DataFrame())
# full_stock_sym_match_descs = pd.DataFrame()
# full_sym_match_descs = pd.DataFrame()
# stock_symbols_ds = pd.DataFrame()
# symbols_ds = pd.DataFrame()
# we need to loop from A to Z
for letter in string.ascii_uppercase:
try:
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
verify_algo_app_connected(algo_app)
algo_app.request_throttle_secs = 0.01
logger.debug("about to verify_get_symbols for letter %s",
letter)
# full_stock_sym_match_descs, stock_symbols_ds, \
# full_sym_match_descs, symbols_ds = \
sym_dfs = verify_get_symbols(letter,
algo_app,
mock_ib,
sym_dfs)
finally:
logger.debug('disconnecting')
algo_app.disconnect_from_ib()
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
###############################################################################
# matching symbols verification
###############################################################################
def verify_match_symbols(algo_app: "AlgoApp",
mock_ib: Any,
pattern: str,
exp_counts: ExpCounts,
req_type: int = 1) -> None:
"""Verify that we find symbols correctly.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
pattern: symbols to use for searching
exp_counts: recursive and non-recursive matches expected
req_type: indicates which request to do
"""
assert req_type == 1 or req_type == 2
if req_type == 1:
logger.debug("about to request_symbols for %s", pattern)
algo_app.request_symbols(pattern)
# assert algo_app.request_id == 2
else: # req_type == 2:
logger.debug("about to get_symbols_recursive for %s", pattern)
algo_app.get_symbols_recursive(pattern)
assert algo_app.request_id >= 2
# algo_app.stock_symbols.drop_duplicates(inplace=True)
logger.debug("getting stock_sym_match_descs")
symbol_starts_with_pattern = \
mock_ib.contract_descriptions['symbol'].map(
lambda symbol: symbol.startswith(pattern))
stock_sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& (mock_ib.contract_descriptions['secType'] == 'STK')
& (mock_ib.contract_descriptions['currency'] == 'USD')
& (if_opt_in_derivativeSecTypes(mock_ib.contract_descriptions)),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& ((mock_ib.contract_descriptions['secType'] != 'STK')
| (mock_ib.contract_descriptions['currency'] != 'USD')
| if_opt_not_in_derivativeSecTypes(mock_ib.contract_descriptions)
),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
logger.debug("verifying results counts")
if req_type == 1:
assert len(algo_app.stock_symbols) \
== exp_counts.stock_sym_non_recursive
assert len(algo_app.symbols) == exp_counts.sym_non_recursive
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(sym_match_descs) == exp_counts.sym_recursive
else:
assert len(algo_app.stock_symbols) == exp_counts.stock_sym_recursive
assert len(algo_app.symbols) == exp_counts.sym_recursive
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(sym_match_descs) == exp_counts.sym_recursive
logger.debug("verifying results match DataFrame")
if exp_counts.stock_sym_recursive > 0:
if req_type == 1:
stock_sym_match_descs = stock_sym_match_descs.iloc[
0:exp_counts.stock_sym_non_recursive]
stock_sym_match_descs = stock_sym_match_descs.set_index(
['conId']).sort_index()
algo_app.stock_symbols.sort_index(inplace=True)
comp_df = algo_app.stock_symbols.compare(stock_sym_match_descs)
assert comp_df.empty
if exp_counts.sym_recursive > 0:
if req_type == 1:
sym_match_descs = sym_match_descs.iloc[
0:exp_counts.sym_non_recursive]
sym_match_descs = sym_match_descs.set_index(
['conId']).sort_index()
algo_app.symbols.sort_index(inplace=True)
comp_df = algo_app.symbols.compare(sym_match_descs)
assert comp_df.empty
logger.debug("all results verified for req_type %d", req_type)
def if_opt_in_derivativeSecTypes(df: Any) -> Any:
"""Find the symbols that have options.
Args:
df: pandas DataFrame of symbols
Returns:
array of boolean values used in pandas loc function
"""
ret_array = np.full(len(df), False)
for i in range(len(df)):
if 'OPT' in df.iloc[i].derivativeSecTypes:
ret_array[i] = True
return ret_array
def if_opt_not_in_derivativeSecTypes(df: Any) -> Any:
"""Find the symbols that do not have options.
Args:
df: pandas DataFrame of symbols
Returns:
array of boolean values used in pandas loc function
"""
ret_array = np.full(len(df), True)
for i in range(len(df)):
if 'OPT' in df.iloc[i].derivativeSecTypes:
ret_array[i] = False
return ret_array
def get_exp_number(search_pattern: str, mock_ib: Any) -> ExpCounts:
"""Helper function to get number of expected symbols.
Args:
search_pattern: search arg as string of one or more chars
mock_ib: mock of ib
Returns:
number of expected matches for recursive and non-recursive requests
"""
combo_factor = (1 + 3 + 3**2 + 3**3)
if len(search_pattern) > 4:
# 5 or more chars will never match (for our mock setup)
return ExpCounts(0, 0, 0, 0)
if search_pattern[0] not in string.ascii_uppercase[0:17]:
return ExpCounts(0, 0, 0, 0) # not in A-Q, inclusive
if len(search_pattern) >= 2:
if search_pattern[1] not in string.ascii_uppercase[1:3] + '.':
return ExpCounts(0, 0, 0, 0) # not in 'BC.'
combo_factor = (1 + 3 + 3**2)
if len(search_pattern) >= 3:
if search_pattern[2] not in string.ascii_uppercase[2:5]:
return ExpCounts(0, 0, 0, 0) # not in 'CDE'
combo_factor = (1 + 3)
if len(search_pattern) == 4:
if search_pattern[3] not in string.ascii_uppercase[3:5] + '.':
return ExpCounts(0, 0, 0, 0) # not in 'DE.'
combo_factor = 1
num_stock_sym_combos = 0
num_sym_combos = 0
combo = mock_ib.get_combos(search_pattern[0])
for item in combo:
if item[0] == 'STK' and item[2] == 'USD' and 'OPT' in item[3]:
num_stock_sym_combos += 1
else:
num_sym_combos += 1
exp_stock_sym_recursive = num_stock_sym_combos * combo_factor
exp_sym_recursive = num_sym_combos * combo_factor
exp_stock_sym_non_recursive = \
math.ceil(min(16, len(combo) * combo_factor)
* (num_stock_sym_combos / len(combo)))
exp_sym_non_recursive = \
math.floor(min(16, len(combo) * combo_factor)
* (num_sym_combos / len(combo)))
return ExpCounts(exp_sym_non_recursive,
exp_sym_recursive,
exp_stock_sym_non_recursive,
exp_stock_sym_recursive
)
def verify_get_symbols(letter: str,
algo_app: "AlgoApp",
mock_ib: Any,
sym_dfs: SymDfs) -> SymDfs:
"""Verify get_symbols.
Args:
letter: the single letter we are collecting symbols for
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
sym_dfs: saved DataFrames between calls
Returns:
updated sym_dfs
"""
if letter != 'A':
# verify the symbol_status ds
symbols_status_path = \
algo_app.ds_catalog.get_path('symbols_status')
logger.info('symbols_status_path: %s', symbols_status_path)
assert symbols_status_path.exists()
symbols_status = pd.read_csv(symbols_status_path,
header=0,
index_col=0)
test_letter = symbols_status.iloc[0, 0]
assert test_letter == letter
exp_counts = get_exp_number(letter, mock_ib)
logger.debug("about to get_symbols for %s", letter)
algo_app.get_symbols()
assert algo_app.request_id >= 2
logger.debug("getting stock_sym_match_descs for %s", letter)
symbol_starts_with_pattern = \
mock_ib.contract_descriptions['symbol'].map(
lambda symbol: symbol.startswith(letter))
stock_sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& (mock_ib.contract_descriptions['secType'] == 'STK')
& (mock_ib.contract_descriptions['currency'] == 'USD')
& (if_opt_in_derivativeSecTypes(
mock_ib.contract_descriptions)),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
sym_match_descs = mock_ib.contract_descriptions.loc[
symbol_starts_with_pattern
& ((mock_ib.contract_descriptions['secType'] != 'STK')
| (mock_ib.contract_descriptions['currency'] != 'USD')
| if_opt_not_in_derivativeSecTypes(mock_ib.contract_descriptions)
),
['conId', 'symbol', 'secType', 'primaryExchange', 'currency',
'derivativeSecTypes']
]
# we expect the stock_symbols to accumulate and grow, so the
# number should now be what was there from the previous
# iteration of this loop plus what we just now added
assert len(stock_sym_match_descs) == exp_counts.stock_sym_recursive
assert len(algo_app.stock_symbols) == (
exp_counts.stock_sym_recursive + len(sym_dfs.stock_sym_df))
assert len(sym_match_descs) == exp_counts.sym_recursive
assert len(algo_app.symbols) == (
exp_counts.sym_recursive + len(sym_dfs.sym_df))
if exp_counts.stock_sym_recursive > 0:
stock_sym_match_descs = stock_sym_match_descs.set_index(
['conId']).sort_index()
sym_dfs.mock_stock_sym_df \
= sym_dfs.mock_stock_sym_df.append(stock_sym_match_descs)
sym_dfs.mock_stock_sym_df.sort_index(inplace=True)
# check the data set
stock_symbols_path = algo_app.ds_catalog.get_path('stock_symbols')
logger.info('stock_symbols_path: %s', stock_symbols_path)
sym_dfs.stock_sym_df = pd.read_csv(stock_symbols_path,
header=0,
index_col=0,
converters={
'derivativeSecTypes':
lambda x: eval(x)})
comp_df = algo_app.stock_symbols.compare(sym_dfs.stock_sym_df)
assert comp_df.empty
comp_df = algo_app.stock_symbols.compare(sym_dfs.mock_stock_sym_df)
assert comp_df.empty
if exp_counts.sym_recursive > 0:
sym_match_descs = sym_match_descs.set_index(
['conId']).sort_index()
sym_dfs.mock_sym_df = \
sym_dfs.mock_sym_df.append(sym_match_descs)
sym_dfs.mock_sym_df.sort_index(inplace=True)
# check the data set
symbols_path = \
algo_app.ds_catalog.get_path('symbols')
logger.info('symbols_path: %s', symbols_path)
sym_dfs.sym_df = pd.read_csv(symbols_path,
header=0,
index_col=0,
converters={
'derivativeSecTypes':
lambda x: eval(x)})
comp_df = algo_app.symbols.compare(sym_dfs.sym_df)
assert comp_df.empty
comp_df = algo_app.symbols.compare(sym_dfs.mock_sym_df)
assert comp_df.empty
return sym_dfs
###############################################################################
###############################################################################
# error path
###############################################################################
###############################################################################
class TestErrorPath:
"""Class to test error path."""
def test_error_path_by_request_when_not_connected(self,
algo_app: "AlgoApp",
capsys: Any) -> None:
"""Test the error callback by any request while not connected.
Args:
algo_app: instance of AlgoApp from conftest pytest fixture
capsys: pytest fixture to capture print output
"""
verify_algo_app_initialized(algo_app)
logger.debug('verifying disconnected')
verify_algo_app_disconnected(algo_app)
logger.debug("about to request time")
algo_app.reqCurrentTime()
captured = capsys.readouterr().out
assert captured == 'Error: -1 504 Not connected' + '\n'
###############################################################################
###############################################################################
# contract details
###############################################################################
###############################################################################
class TestAlgoAppContractDetails:
"""TestAlgoAppContractDetails class."""
def test_get_contract_details_0_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for non-existent conId.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_1_entry(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 1 entry.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_2_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 2 entries.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
contract.conId = 7002
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_duplicates(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for 3 entries plus a duplicate.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
contract = Contract() # create an empty contract with conId of 0
contract.conId = 7001
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001])
contract.conId = 7002
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
contract.conId = 7001 # try to add 7001 again
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib, [7001, 7002])
contract.conId = 7003
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib,
[7001, 7002, 7003])
contract.conId = 7002 # another duplicate
algo_app.get_contract_details(contract)
verify_contract_details(contract, algo_app, mock_ib,
[7001, 7002, 7003])
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
def test_get_contract_details_many_entries(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test contract details for many entries.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
verify_algo_app_initialized(algo_app)
logger.debug("about to connect")
algo_app.connect_to_ib("127.0.0.1",
algo_app.PORT_FOR_LIVE_TRADING,
client_id=0)
# verify that algo_app is connected and alive with a valid reqId
verify_algo_app_connected(algo_app)
try:
conId_list = []
for conId in range(7001, 7033):
contract = Contract() # create an empty contract
contract.conId = conId
conId_list.append(conId)
algo_app.get_contract_details(contract)
verify_contract_details(contract,
algo_app,
mock_ib,
conId_list)
finally:
algo_app.disconnect_from_ib()
verify_algo_app_disconnected(algo_app)
###############################################################################
# contract details verification
###############################################################################
def verify_contract_details(contract: "Contract",
algo_app: "AlgoApp",
mock_ib: Any,
conId_list: List[int]) -> None:
"""Verify contract details.
Args:
contract: the contract used to get details
algo_app: instance of AlgoApp from conftest pytest fixture
mock_ib: pytest fixture of contract_descriptions
conId_list: list of con ids
"""
assert len(algo_app.contract_details) == len(conId_list)
if len(conId_list) > 0:
# first, save the algo_app contracts and contract_details
contracts_ds = algo_app.contracts
contract_details_ds = algo_app.contract_details
# next, reload algo_app contracts and contract_details from csv
# so we can test that they were saved and restored
# correctly (i.e., we will compare them against
# what we just loaded)
contracts_path = algo_app.ds_catalog.get_path('contracts')
logger.info('contracts_path: %s', contracts_path)
algo_app.contracts = algo_app.load_contracts(contracts_path)
algo_app.load_contract_details()
# print('contract_details_ds:\n', contract_details_ds)
# print('contract_details_ds.__dict__:\n',
# contract_details_ds.__dict__)
for conId in conId_list:
# match_desc = mock_ib.contract_descriptions.loc[
# mock_ib.contract_descriptions['conId'] == conId]
# match_desc = match_desc.iloc[0]
contract1 = get_contract_obj(
algo_app.contracts.loc[conId].to_dict())
contract2 = get_contract_obj(contracts_ds.loc[conId].to_dict())
compare_contracts(contract1,
contract2)
contract3 = get_contract_from_mock_desc(conId, mock_ib)
compare_contracts(contract1,
contract3)
contract_details1 = get_contract_details_obj(
algo_app.contract_details.loc[conId].to_dict())
contract_details2 = get_contract_details_obj(
contract_details_ds.loc[conId].to_dict())
compare_contract_details(contract_details1,
contract_details2)
contract_details3 = \
get_contract_details_from_mock_desc(conId, mock_ib)
compare_contract_details(contract_details1,
contract_details3)
###############################################################################
###############################################################################
# TestExtraContractFields
###############################################################################
###############################################################################
class TestExtraContractFields:
"""TestExtraContractFields class."""
###########################################################################
# test_contract_combo_legs
###########################################################################
def test_contract_extra_fields(self,
algo_app: "AlgoApp",
mock_ib: Any
) -> None:
"""Test combo legs in contract.
Args:
algo_app: pytest fixture instance of AlgoApp (see conftest.py)
mock_ib: pytest fixture of contract_descriptions
"""
num_contracts = 50
contract_list = []
contract_df = pd.DataFrame()
# get the path for saving/loading the combo legs contract df
extra_contract_path = \
algo_app.ds_catalog.get_path('extra_contract')
logger.info('extra_contract_path: %s', extra_contract_path)
for i in range(num_contracts):
conId = 7001 + i
contract = get_contract_from_mock_desc(conId,
mock_ib,
include_extra_details=True)
# add combo legs
combo_leg_list = build_combo_legs(i, mock_ib)
if combo_leg_list:
contract.comboLegs = combo_leg_list
elif i % 2 == 1: # empty list
# empty list for odd, None for even
contract.comboLegs = []
contract_list.append(contract)
contract_dict = get_contract_dict(contract)
contract_df = \
contract_df.append(pd.DataFrame(contract_dict,
index=[contract.conId]))
# Save dataframe to csv
contract_df.to_csv(extra_contract_path)
# read dataframe from csv
contract_df2 = algo_app.load_contracts(extra_contract_path)
for i in range(num_contracts):
contract1 = contract_list[i]
contract_dict2 = contract_df2.iloc[i].to_dict()
contract2 = get_contract_obj(contract_dict2)
compare_contracts(contract1, contract2)
###############################################################################
# build_combo_legs
###############################################################################
def build_combo_legs(idx: int,
mock_ib: Any) -> List[ComboLeg]:
"""Build the combo leg list for a contract.
Args:
idx: the index of the entry being built
mock_ib: pytest fixture of contract_descriptions
Returns:
list with zero or more ComboLeg items
"""
num_combo_legs = idx % 4 # vary the number built from 0 to 3
combo_leg_list = []
for j in range(num_combo_legs):
combo_leg = ComboLeg()
combo_leg.conId = \
mock_ib.combo_legs.cl_conId.iloc[idx + j]
combo_leg.ratio = \
mock_ib.combo_legs.cl_ratio.iloc[idx + j]
combo_leg.action = \
mock_ib.combo_legs.cl_action.iloc[idx + j]
combo_leg.exchange = \
mock_ib.combo_legs.cl_exchange.iloc[idx + j]
combo_leg.openClose = \
mock_ib.combo_legs.cl_openClose.iloc[idx + j]
combo_leg.shortSaleSlot = \
mock_ib.combo_legs.cl_shortSaleSlot.iloc[idx + j]
combo_leg.designatedLocation = \
mock_ib.combo_legs.cl_designatedLocation.iloc[idx + j]
combo_leg.exemptCode = \
mock_ib.combo_legs.cl_exemptCode.iloc[idx + j]
combo_leg_list.append(combo_leg)
return combo_leg_list
###############################################################################
# get_contract_from_mock_desc
###############################################################################
def get_contract_from_mock_desc(conId: int,
mock_ib: Any,
include_extra_details: bool = False
) -> Contract:
"""Build and return a contract from the mock description.
Args:
conId: index of mock_desc and mock_dnc to use
mock_ib: contains contract data frames
include_extra_details: include more details beyond what is
returned for reqContractDetails
Returns:
Contract with fields from input mock_desc and mock_dnc
"""
ret_con = Contract()
ret_con.conId = mock_ib.contract_descriptions.at[conId, 'conId'] # cd
ret_con.symbol = mock_ib.contract_descriptions.at[conId, 'symbol'] # cd
ret_con.secType = mock_ib.contract_descriptions.at[conId, 'secType'] # cd
if mock_ib.contract_descriptions.at[conId, 'lastTradeDateOrContractMonth']:
split_date = \
mock_ib.contract_descriptions.at[
conId, 'lastTradeDateOrContractMonth'].split()
if len(split_date) > 0: # very well better be!
ret_con.lastTradeDateOrContractMonth = split_date[0]
ret_con.strike = mock_ib.contract_descriptions.at[conId, 'strike'] # cd
ret_con.right = mock_ib.contract_descriptions.at[conId, 'right'] # cd
ret_con.multiplier = \
mock_ib.contract_descriptions.at[conId, 'multiplier'] # cd
ret_con.exchange = \
mock_ib.contract_descriptions.at[conId, 'exchange'] # cd
ret_con.primaryExchange = \
mock_ib.contract_descriptions.at[conId, 'primaryExchange'] # cd
ret_con.currency = \
mock_ib.contract_descriptions.at[conId, 'currency'] # cd
ret_con.localSymbol = \
mock_ib.contract_descriptions.at[conId, 'localSymbol'] # cd
ret_con.tradingClass = \
mock_ib.contract_descriptions.at[conId, 'tradingClass'] # cd
###########################################################################
# following fields are not included with reqContractDetails
###########################################################################
if include_extra_details:
ret_con.includeExpired = \
mock_ib.contract_descriptions.at[conId, 'includeExpired']
ret_con.secIdType = mock_ib.contract_descriptions.at[conId,
'secIdType']
ret_con.secId = mock_ib.contract_descriptions.at[conId, 'secId']
# combos
ret_con.comboLegsDescrip = \
mock_ib.contract_descriptions.at[conId, 'comboLegsDescrip']
# ret_con.comboLegs = mock_ib.contract_descriptions.comboLegs
# build a delta_neutral_contract every third time
if (conId % 3) == 0:
delta_neutral_contract = DeltaNeutralContract()
# item() is used to convert numpy.int64 to python int
delta_neutral_contract.conId = \
mock_ib.delta_neutral_contract.at[conId, 'conId']
delta_neutral_contract.delta = \
mock_ib.delta_neutral_contract.at[conId, 'delta']
delta_neutral_contract.price = \
mock_ib.delta_neutral_contract.at[conId, 'price']
ret_con.deltaNeutralContract = delta_neutral_contract
return ret_con
###############################################################################
# get_contract_details_from_mock_desc
###############################################################################
def get_contract_details_from_mock_desc(conId: int,
mock_ib: Any
) -> ContractDetails:
"""Build and return a contract_details from the mock description.
Args:
conId: index of entry to use
mock_ib: DataFrame with values for contract_details
Returns:
ContractDetails with fields from input mock_desc
"""
ret_con = ContractDetails()
ret_con.contract = get_contract_from_mock_desc(conId, mock_ib)
ret_con.marketName = \
mock_ib.contract_descriptions.at[conId, 'marketName'] # cd
ret_con.minTick = mock_ib.contract_descriptions.at[conId, 'minTick'] # cd
ret_con.orderTypes = \
mock_ib.contract_descriptions.at[conId, 'orderTypes'] # cd
ret_con.validExchanges = \
mock_ib.contract_descriptions.at[conId, 'validExchanges'] # cd
ret_con.priceMagnifier = \
mock_ib.contract_descriptions.at[conId, 'priceMagnifier'] # cd
ret_con.underConId = \
mock_ib.contract_descriptions.at[conId, 'underConId'] # cd
ret_con.longName = mock_ib.contract_descriptions.at[conId,
'longName'] # cd
ret_con.contractMonth = \
mock_ib.contract_descriptions.at[conId, 'contractMonth'] # cd
ret_con.industry = mock_ib.contract_descriptions.at[conId,
'industry'] # cd
ret_con.category = mock_ib.contract_descriptions.at[conId,
'category'] # cd
ret_con.subcategory = \
mock_ib.contract_descriptions.at[conId, 'subcategory'] # cd
ret_con.timeZoneId = \
mock_ib.contract_descriptions.at[conId, 'timeZoneId'] # cd
ret_con.tradingHours = \
mock_ib.contract_descriptions.at[conId, 'tradingHours'] # cd
ret_con.liquidHours = \
mock_ib.contract_descriptions.at[conId, 'liquidHours'] # cd
ret_con.evRule = mock_ib.contract_descriptions.at[conId, 'evRule'] # cd
ret_con.evMultiplier = \
mock_ib.contract_descriptions.at[conId, 'evMultiplier'] # cd
ret_con.mdSizeMultiplier = \
mock_ib.contract_descriptions.at[conId, 'mdSizeMultiplier'] # cd
ret_con.aggGroup = mock_ib.contract_descriptions.at[conId,
'aggGroup'] # cd
ret_con.underSymbol = \
mock_ib.contract_descriptions.at[conId, 'underSymbol'] # cd
ret_con.underSecType = \
mock_ib.contract_descriptions.at[conId, 'underSecType'] # cd
ret_con.marketRuleIds = \
mock_ib.contract_descriptions.at[conId, 'marketRuleIds'] # cd
secIdList = mock_ib.contract_descriptions.at[conId, 'secIdList']
new_secIdList = []
for j in range(0,
2 * mock_ib.contract_descriptions.at[conId,
'secIdListCount'],
2):
tag = secIdList[j]
value = secIdList[j+1]
tag_value = TagValue(tag, value)
new_secIdList.append(tag_value)
ret_con.secIdList = new_secIdList # cd
ret_con.realExpirationDate = \
mock_ib.contract_descriptions.at[conId, 'realExpirationDate'] # cd
# last trade time come from lastTradeDate as 'date time' (i.e., 2 items)
if mock_ib.contract_descriptions.at[conId, 'lastTradeDateOrContractMonth']:
split_date = \
mock_ib.contract_descriptions.at[
conId, 'lastTradeDateOrContractMonth'].split()
if len(split_date) > 1:
ret_con.lastTradeTime = split_date[1]
ret_con.stockType = mock_ib.contract_descriptions.at[conId,
'stockType'] # cd
return ret_con
###############################################################################
# compare_tag_value
###############################################################################
def compare_tag_value(tag_value1: TagValue,
tag_value2: TagValue
) -> None:
"""Compare two tag_value objects for equality.
Args:
tag_value1: tag_value 1
tag_value2: tag_value 2
"""
assert tag_value1.tag == tag_value2.tag
assert isinstance(tag_value1.tag, str)
assert isinstance(tag_value2.tag, str)
assert tag_value1.value == tag_value2.value
assert isinstance(tag_value1.value, str)
assert isinstance(tag_value2.value, str)
###############################################################################
# compare_combo_legs
###############################################################################
def compare_combo_legs(cl1: ComboLeg,
cl2: ComboLeg
) -> None:
"""Compare two combo leg objects for equality.
Args:
cl1: combo leg 1
cl2: combo leg 2
"""
assert cl1.conId == cl2.conId
assert cl1.ratio == cl2.ratio
assert cl1.action == cl2.action
assert cl1.exchange == cl2.exchange
assert cl1.openClose == cl2.openClose
assert cl1.shortSaleSlot == cl2.shortSaleSlot
assert cl1.designatedLocation == cl2.designatedLocation
assert cl1.exemptCode == cl2.exemptCode
verify_combo_leg_types(cl1)
verify_combo_leg_types(cl1)
###############################################################################
# verify_combo_leg_types
###############################################################################
def verify_combo_leg_types(combo_leg: ComboLeg) -> None:
"""Verify that combo_leg fields are correct type.
Args:
combo_leg: combo_leg to verify
"""
assert isinstance(combo_leg.conId, (int, np.int64))
assert isinstance(combo_leg.ratio, (int, np.int64))
assert isinstance(combo_leg.action, str)
assert isinstance(combo_leg.exchange, str)
assert isinstance(combo_leg.openClose, (int, np.int64))
assert isinstance(combo_leg.shortSaleSlot, (int, np.int64))
assert isinstance(combo_leg.designatedLocation, str)
assert isinstance(combo_leg.exemptCode, (int, np.int64))
###############################################################################
# compare_delta_neutral_contracts
###############################################################################
def compare_delta_neutral_contracts(con1: DeltaNeutralContract,
con2: DeltaNeutralContract
) -> None:
"""Compare two delta neutral contracts for equality.
Args:
con1: contract 1
con2: contract 2
"""
assert con1.conId == con2.conId
assert isinstance(con1.conId, (int, np.int64))
assert isinstance(con2.conId, int)
assert con1.delta == con2.delta
assert isinstance(con1.delta, float)
assert isinstance(con2.delta, float)
assert con1.price == con2.price
assert isinstance(con1.price, float)
assert isinstance(con2.price, float)
###############################################################################
# compare_contracts
###############################################################################
def compare_contracts(con1: Contract, con2: Contract) -> None:
"""Compare two contracts for equality.
Args:
con1: contract 1
con2: contract 2
"""
assert con1.conId == con2.conId
assert con1.symbol == con2.symbol
assert con1.secType == con2.secType
assert (con1.lastTradeDateOrContractMonth
== con2.lastTradeDateOrContractMonth)
assert con1.strike == con2.strike
assert con1.right == con2.right
assert con1.multiplier == con2.multiplier
assert con1.exchange == con2.exchange
assert con1.primaryExchange == con2.primaryExchange
assert con1.currency == con2.currency
assert con1.localSymbol == con2.localSymbol
assert con1.tradingClass == con2.tradingClass
assert con1.includeExpired == con2.includeExpired
assert con1.secIdType == con2.secIdType
assert con1.secId == con2.secId
# combos
assert con1.comboLegsDescrip == con2.comboLegsDescrip
if con1.comboLegs and con2.comboLegs:
assert len(con1.comboLegs) == len(con2.comboLegs)
for i in range(len(con1.comboLegs)):
compare_combo_legs(con1.comboLegs[i],
con2.comboLegs[i])
else: # check whether one contract has it and the other does not
assert not (con1.comboLegs or con2.comboLegs)
if con1.deltaNeutralContract and con2.deltaNeutralContract:
compare_delta_neutral_contracts(con1.deltaNeutralContract,
con2.deltaNeutralContract)
else: # check whether one contract has it and one does not
assert not (con1.deltaNeutralContract or con2.deltaNeutralContract)
verify_contract_types(con1)
verify_contract_types(con2)
###############################################################################
# verify_contract_types
###############################################################################
def verify_contract_types(contract: Contract) -> None:
"""Verify that contract fields are correct type.
Args:
contract: contract to verify
"""
assert isinstance(contract.conId, (int, np.int64))
assert isinstance(contract.symbol, str)
assert isinstance(contract.secType, str)
assert isinstance(contract.lastTradeDateOrContractMonth, str)
assert isinstance(contract.strike, float)
assert isinstance(contract.right, str)
assert isinstance(contract.multiplier, str)
assert isinstance(contract.exchange, str)
assert isinstance(contract.primaryExchange, str)
assert isinstance(contract.currency, str)
assert isinstance(contract.localSymbol, str)
assert isinstance(contract.tradingClass, str)
assert isinstance(contract.includeExpired, (bool, np.bool_))
assert isinstance(contract.secIdType, str)
assert isinstance(contract.secId, str)
# combos
assert isinstance(contract.comboLegsDescrip, str)
assert isinstance(contract.comboLegs, (list, type(None)))
if contract.comboLegs:
for combo_leg in contract.comboLegs:
assert isinstance(combo_leg, ComboLeg)
assert isinstance(contract.deltaNeutralContract,
(DeltaNeutralContract, type(None)))
###############################################################################
# compare_contract_details
###############################################################################
def compare_contract_details(con1: ContractDetails,
con2: ContractDetails
) -> None:
"""Compare two contract_details for equality.
Args:
con1: contract_details 1
con2: contract_details 2
"""
if con1.contract and con2.contract:
compare_contracts(con1.contract, con2.contract)
else: # check whether one contract_details has it, one does not
assert not (con1.contract or con2.contract)
assert con1.marketName == con2.marketName
assert con1.minTick == con2.minTick
assert con1.orderTypes == con2.orderTypes
assert con1.validExchanges == con2.validExchanges
assert con1.priceMagnifier == con2.priceMagnifier
assert con1.underConId == con2.underConId
assert con1.longName == con2.longName
assert con1.contractMonth == con2.contractMonth
assert con1.industry == con2.industry
assert con1.category == con2.category
assert con1.subcategory == con2.subcategory
assert con1.timeZoneId == con2.timeZoneId
assert con1.tradingHours == con2.tradingHours
assert con1.liquidHours == con2.liquidHours
assert con1.evRule == con2.evRule
assert con1.evMultiplier == con2.evMultiplier
assert con1.mdSizeMultiplier == con2.mdSizeMultiplier
assert con1.aggGroup == con2.aggGroup
assert con1.underSymbol == con2.underSymbol
assert con1.underSecType == con2.underSecType
assert con1.marketRuleIds == con2.marketRuleIds
if con1.secIdList and con2.secIdList:
assert len(con1.secIdList) == len(con2.secIdList)
for i in range(len(con1.secIdList)):
compare_tag_value(con1.secIdList[i], con2.secIdList[i])
else: # check whether one contract_details has it, one does not
assert not (con1.secIdList or con2.secIdList)
assert con1.realExpirationDate == con2.realExpirationDate
assert con1.lastTradeTime == con2.lastTradeTime
assert con1.stockType == con2.stockType
# BOND values
assert con1.cusip == con2.cusip
assert con1.ratings == con2.ratings
assert con1.descAppend == con2.descAppend
assert con1.bondType == con2.bondType
assert con1.couponType == con2.couponType
assert con1.callable == con2.callable
assert con1.putable == con2.putable
assert con1.coupon == con2.coupon
assert con1.convertible == con2.convertible
assert con1.maturity == con2.maturity
assert con1.issueDate == con2.issueDate
assert con1.nextOptionDate == con2.nextOptionDate
assert con1.nextOptionType == con2.nextOptionType
assert con1.nextOptionPartial == con2.nextOptionPartial
assert con1.notes == con2.notes
###############################################################################
# fundamental data
###############################################################################
# class TestAlgoAppFundamentalData:
# """TestAlgoAppContractDetails class."""
#
# def test_get_contract_details_0_entries(self,
# algo_app: "AlgoApp",
# mock_ib: Any
# ) -> None:
# """Test contract details for non-existent conId.
#
# Args:
# algo_app: pytest fixture instance of AlgoApp (see conftest.py)
# mock_ib: pytest fixture of contract_descriptions
#
# """
# verify_algo_app_initialized(algo_app)
#
# logger.debug("about to connect")
# algo_app.connect_to_ib("127.0.0.1",
# algo_app.PORT_FOR_LIVE_TRADING,
# client_id=0)
#
# # verify that algo_app is connected and alive with a valid reqId
# verify_algo_app_connected(algo_app)
#
# contract = Contract() # create an empty contract with conId of 0
# algo_app.get_contract_details(contract)
#
# verify_contract_details(contract, algo_app, mock_ib, [0])
#
# algo_app.disconnect_from_ib()
# verify_algo_app_disconnected(algo_app)
| 37.133487 | 79 | 0.562754 |
import pytest
import numpy as np
import pandas as pd
import string
import math
from typing import Any, List, NamedTuple
from ibapi.tag_value import TagValue
from ibapi.contract import ComboLeg
from ibapi.contract import DeltaNeutralContract
from ibapi.contract import Contract, ContractDetails
from scottbrian_algo1.algo_api import AlgoApp, AlreadyConnected, \
DisconnectLockHeld, ConnectTimeout, RequestTimeout, DisconnectDuringRequest
from scottbrian_algo1.algo_maps import get_contract_dict, get_contract_obj
from scottbrian_algo1.algo_maps import get_contract_details_obj
import logging
logger = logging.getLogger(__name__)
| true | true |
f72c3eaefc009d0112c0c6fa0eb8a060a2d74f83 | 13,353 | py | Python | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | 5 | 2021-05-17T04:45:03.000Z | 2022-03-23T12:51:46.000Z | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | null | null | null | cryptoapis/model/inline_response40084.py | Crypto-APIs/Crypto_APIs_2.0_SDK_Python | c59ebd914850622b2c6500c4c30af31fb9cecf0e | [
"MIT"
] | 2 | 2021-06-02T07:32:26.000Z | 2022-02-12T02:36:23.000Z | """
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: developers@cryptoapis.io
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from cryptoapis.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from cryptoapis.exceptions import ApiAttributeError
def lazy_import():
from cryptoapis.model.get_eip1559_fee_recommendations_e400 import GetEIP1559FeeRecommendationsE400
globals()['GetEIP1559FeeRecommendationsE400'] = GetEIP1559FeeRecommendationsE400
class InlineResponse40084(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'api_version': (str,), # noqa: E501
'request_id': (str,), # noqa: E501
'error': (GetEIP1559FeeRecommendationsE400,), # noqa: E501
'context': (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'api_version': 'apiVersion', # noqa: E501
'request_id': 'requestId', # noqa: E501
'error': 'error', # noqa: E501
'context': 'context', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, api_version, request_id, error, *args, **kwargs): # noqa: E501
"""InlineResponse40084 - a model defined in OpenAPI
Args:
api_version (str): Specifies the version of the API that incorporates this endpoint.
request_id (str): Defines the ID of the request. The `requestId` is generated by Crypto APIs and it's unique for every request.
error (GetEIP1559FeeRecommendationsE400):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
context (str): In batch situations the user can use the context to correlate responses with requests. This property is present regardless of whether the response was successful or returned as an error. `context` is specified by the user.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, api_version, request_id, error, *args, **kwargs): # noqa: E501
"""InlineResponse40084 - a model defined in OpenAPI
Args:
api_version (str): Specifies the version of the API that incorporates this endpoint.
request_id (str): Defines the ID of the request. The `requestId` is generated by Crypto APIs and it's unique for every request.
error (GetEIP1559FeeRecommendationsE400):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
context (str): In batch situations the user can use the context to correlate responses with requests. This property is present regardless of whether the response was successful or returned as an error. `context` is specified by the user.. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| 46.852632 | 484 | 0.59642 |
import re
import sys
from cryptoapis.model_utils import (
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from cryptoapis.exceptions import ApiAttributeError
def lazy_import():
from cryptoapis.model.get_eip1559_fee_recommendations_e400 import GetEIP1559FeeRecommendationsE400
globals()['GetEIP1559FeeRecommendationsE400'] = GetEIP1559FeeRecommendationsE400
class InlineResponse40084(ModelNormal):
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
'api_version': (str,),
'request_id': (str,),
'error': (GetEIP1559FeeRecommendationsE400,),
'context': (str,),
}
@cached_property
def discriminator():
return None
attribute_map = {
'api_version': 'apiVersion',
'request_id': 'requestId',
'error': 'error',
'context': 'context',
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, api_version, request_id, error, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, api_version, request_id, error, *args, **kwargs):
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.api_version = api_version
self.request_id = request_id
self.error = error
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| true | true |
f72c3f4ba1a384299dbf753da7d0c4ce5d5a213d | 117 | py | Python | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | App/pogress.py | MarioTiara/MarioTiara-RD-Detection-Ensemble-CNN | 95101b942a7e51078bfe643021e745e51e82516f | [
"MIT"
] | null | null | null | from tqdm import tqdm,trange
from time import sleep
for i in trange(20):
sleep(0.1)
pass
raise SystemExit
| 11.7 | 28 | 0.709402 | from tqdm import tqdm,trange
from time import sleep
for i in trange(20):
sleep(0.1)
pass
raise SystemExit
| true | true |
f72c409dd9d8c1ef88d4e1e5c1f5d52fa3e3b565 | 546 | py | Python | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | manage.py | C-PRONCE/django-project | 573402850462a73bd8750118f74e2b36aa650ded | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "second_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| 34.125 | 78 | 0.690476 |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "second_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| true | true |
f72c41aed18c0d9acc5d31e93cff1a2cecca0807 | 2,225 | py | Python | test/ux/components/model/test_repository.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 172 | 2021-09-14T18:34:17.000Z | 2022-03-30T06:49:53.000Z | test/ux/components/model/test_repository.py | intel/lp-opt-tool | 130eefa3586b38df6c0ff78cc8807ae273f6a63f | [
"Apache-2.0"
] | 40 | 2021-09-14T02:26:12.000Z | 2022-03-29T08:34:04.000Z | test/ux/components/model/test_repository.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 33 | 2021-09-15T07:27:25.000Z | 2022-03-25T08:30:57.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test ModelRepository."""
import unittest
from neural_compressor.ux.components.model.repository import ModelRepository
from neural_compressor.ux.utils.consts import Frameworks
from neural_compressor.ux.utils.exceptions import NotFoundException
class TestModelRepository(unittest.TestCase):
"""Test ModelRepository class."""
def test_onnx_is_model_path(self) -> None:
"""Test if onnx file is recognized correctly."""
path = "/home/user/model.onnx"
result = ModelRepository.is_model_path(path)
self.assertTrue(result)
def test_mp3_is_model_path(self) -> None:
"""Test if mp3 file is recognized correctly."""
path = "/home/user/favourite_song.mp3"
result = ModelRepository.is_model_path(path)
self.assertFalse(result)
def test_get_frameworks(self) -> None:
"""Test getting frameworks."""
expected = [Frameworks.ONNX.value, Frameworks.TF.value]
repository = ModelRepository()
actual = repository.get_frameworks()
self.assertEqual(expected, actual)
def test_framework_from_path_for_known_model(self) -> None:
"""Test get_framework_from_path."""
actual = ModelRepository.get_framework_from_path("/home/user/model.onnx")
self.assertEqual(Frameworks.ONNX.value, actual)
def test_framework_from_path_for_unknown_model(self) -> None:
"""Test get_framework_from_path."""
with self.assertRaises(NotFoundException):
ModelRepository.get_framework_from_path("/home/user/favourite_song.mp3")
if __name__ == "__main__":
unittest.main()
| 36.47541 | 84 | 0.720899 |
import unittest
from neural_compressor.ux.components.model.repository import ModelRepository
from neural_compressor.ux.utils.consts import Frameworks
from neural_compressor.ux.utils.exceptions import NotFoundException
class TestModelRepository(unittest.TestCase):
def test_onnx_is_model_path(self) -> None:
path = "/home/user/model.onnx"
result = ModelRepository.is_model_path(path)
self.assertTrue(result)
def test_mp3_is_model_path(self) -> None:
path = "/home/user/favourite_song.mp3"
result = ModelRepository.is_model_path(path)
self.assertFalse(result)
def test_get_frameworks(self) -> None:
expected = [Frameworks.ONNX.value, Frameworks.TF.value]
repository = ModelRepository()
actual = repository.get_frameworks()
self.assertEqual(expected, actual)
def test_framework_from_path_for_known_model(self) -> None:
actual = ModelRepository.get_framework_from_path("/home/user/model.onnx")
self.assertEqual(Frameworks.ONNX.value, actual)
def test_framework_from_path_for_unknown_model(self) -> None:
with self.assertRaises(NotFoundException):
ModelRepository.get_framework_from_path("/home/user/favourite_song.mp3")
if __name__ == "__main__":
unittest.main()
| true | true |
f72c41f790310bb3e579547708ef92adbef03768 | 4,008 | py | Python | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | 1 | 2019-12-10T14:59:12.000Z | 2019-12-10T14:59:12.000Z | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | null | null | null | unit_test/test_interface.py | riven314/capstone_dash_interface | 5eab25f4c15ad09aa889554820231175b0a3ed28 | [
"CC0-1.0"
] | 1 | 2020-01-01T12:24:51.000Z | 2020-01-01T12:24:51.000Z | """
test the following:
model + scene understanding + interface
"""
import os
import sys
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH)
import cv2
from PyQt5.QtGui import QImage, QColor, QPixmap
from PyQt5.QtWidgets import QApplication
import qtmodern.styles
import qtmodern.windows
from layout import Layout
from pyqt_utils import convert_qimg
from scene_summary import get_names, create_grid, scene_summarize
from simplify_thread_utils import FrameStore, FrameThread
from obj_avoidance import run_avoidance
class SimplifyInteface(Layout):
def __init__(self):
super().__init__()
# setup for scene understanding
self.load_lightbulb()
self.mat = create_grid(h = 240, w = 427)
self.names = get_names()
self.init_thread()
def load_lightbulb(self):
RED_PATH = os.path.join('..', 'images', 'red.jpg')
GREEN_PATH = os.path.join('..', 'images', 'green.jpg')
assert os.path.isfile(RED_PATH), '[ERROR] Path not exist: {}'.format(RED_PATH)
assert os.path.isfile(GREEN_PATH), '[ERROR] Path not exist: {}'.format(GREEN_PATH)
red = cv2.imread(RED_PATH)
green = cv2.imread(GREEN_PATH)
self.red_qimg = convert_qimg(red, win_width = 50, win_height = 50)
self.green_qimg = convert_qimg(green, win_width = 50, win_height = 50)
def init_thread(self):
self.f_thread = FrameThread()
self.seg_names = self.f_thread.model_config.names
self.seg_colors = self.f_thread.model_config.colors
self.f_thread.frame_signal.connect(lambda frame_store: self.update_first_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_second_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_third_layer(frame_store))
self.f_thread.start()
def update_first_layer(self, frame_store):
"""
update different runtime and FPS
"""
self.model_time.setText('{0:.1f} ms'.format(frame_store.model_time * 1000))
self.fps_time.setText('{0:.1f}'.format(frame_store.fps_time))
def update_second_layer(self, frame_store):
"""
update segmentation result and scene summary
"""
# update segmentation result
qimg = convert_qimg(frame_store.pred_rgb, win_width = 620, win_height = 360)
self.seg_frame.setPixmap(QPixmap.fromImage(qimg))
# update scene summary
grid_dict = scene_summarize(frame_store.pred_idx,
self.mat, self.names,
threshold = 900)
self.update_scene_summary(grid_dict)
def update_scene_summary(self, grid_dict):
for i, obj_ls in grid_dict.items():
txt = ', '.join(obj_ls)
q_label = getattr(self, 'grid_{}'.format(i + 1))
q_label.setText(txt)
def update_third_layer(self, frame_store):
obj_tup, obj_img = run_avoidance(frame_store.d1_img, frame_store.pred_idx)
qimg = convert_qimg(obj_img, win_width = 620, win_height = 360, is_gray = True)
# update frame on left
self.obj_frame.setPixmap(QPixmap.fromImage(qimg))
# update summary on right
if obj_tup[1] is None:
self.obj_name.setText('NA')
self.obj_dist.setText('NA')
self.lightbulb.setPixmap(QPixmap.fromImage(self.green_qimg))
else:
obj_name = self.names[obj_tup[1] + 1]
self.obj_name.setText(obj_name)
self.obj_dist.setText('{} m'.format(obj_tup[2]))
self.lightbulb.setPixmap(QPixmap.fromImage(self.red_qimg))
if __name__ == '__main__':
app = QApplication(sys.argv)
win = SimplifyInteface()
qtmodern.styles.dark(app)
win_modern = qtmodern.windows.ModernWindow(win)
win_modern.show()
sys.exit(app.exec_())
| 38.538462 | 102 | 0.643214 | import os
import sys
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH)
import cv2
from PyQt5.QtGui import QImage, QColor, QPixmap
from PyQt5.QtWidgets import QApplication
import qtmodern.styles
import qtmodern.windows
from layout import Layout
from pyqt_utils import convert_qimg
from scene_summary import get_names, create_grid, scene_summarize
from simplify_thread_utils import FrameStore, FrameThread
from obj_avoidance import run_avoidance
class SimplifyInteface(Layout):
def __init__(self):
super().__init__()
self.load_lightbulb()
self.mat = create_grid(h = 240, w = 427)
self.names = get_names()
self.init_thread()
def load_lightbulb(self):
RED_PATH = os.path.join('..', 'images', 'red.jpg')
GREEN_PATH = os.path.join('..', 'images', 'green.jpg')
assert os.path.isfile(RED_PATH), '[ERROR] Path not exist: {}'.format(RED_PATH)
assert os.path.isfile(GREEN_PATH), '[ERROR] Path not exist: {}'.format(GREEN_PATH)
red = cv2.imread(RED_PATH)
green = cv2.imread(GREEN_PATH)
self.red_qimg = convert_qimg(red, win_width = 50, win_height = 50)
self.green_qimg = convert_qimg(green, win_width = 50, win_height = 50)
def init_thread(self):
self.f_thread = FrameThread()
self.seg_names = self.f_thread.model_config.names
self.seg_colors = self.f_thread.model_config.colors
self.f_thread.frame_signal.connect(lambda frame_store: self.update_first_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_second_layer(frame_store))
self.f_thread.frame_signal.connect(lambda frame_store: self.update_third_layer(frame_store))
self.f_thread.start()
def update_first_layer(self, frame_store):
self.model_time.setText('{0:.1f} ms'.format(frame_store.model_time * 1000))
self.fps_time.setText('{0:.1f}'.format(frame_store.fps_time))
def update_second_layer(self, frame_store):
qimg = convert_qimg(frame_store.pred_rgb, win_width = 620, win_height = 360)
self.seg_frame.setPixmap(QPixmap.fromImage(qimg))
grid_dict = scene_summarize(frame_store.pred_idx,
self.mat, self.names,
threshold = 900)
self.update_scene_summary(grid_dict)
def update_scene_summary(self, grid_dict):
for i, obj_ls in grid_dict.items():
txt = ', '.join(obj_ls)
q_label = getattr(self, 'grid_{}'.format(i + 1))
q_label.setText(txt)
def update_third_layer(self, frame_store):
obj_tup, obj_img = run_avoidance(frame_store.d1_img, frame_store.pred_idx)
qimg = convert_qimg(obj_img, win_width = 620, win_height = 360, is_gray = True)
self.obj_frame.setPixmap(QPixmap.fromImage(qimg))
if obj_tup[1] is None:
self.obj_name.setText('NA')
self.obj_dist.setText('NA')
self.lightbulb.setPixmap(QPixmap.fromImage(self.green_qimg))
else:
obj_name = self.names[obj_tup[1] + 1]
self.obj_name.setText(obj_name)
self.obj_dist.setText('{} m'.format(obj_tup[2]))
self.lightbulb.setPixmap(QPixmap.fromImage(self.red_qimg))
if __name__ == '__main__':
app = QApplication(sys.argv)
win = SimplifyInteface()
qtmodern.styles.dark(app)
win_modern = qtmodern.windows.ModernWindow(win)
win_modern.show()
sys.exit(app.exec_())
| true | true |
f72c4215bb8a7b8efd6c3aee4ac1b1fb3af3b383 | 6,434 | py | Python | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/__init__.py | PRUDHVI-BOT/apple | daae0ca57f42c6a924a59bfd800b92e2a6c6115e | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot initialization. """
import os
from sys import version_info
from logging import basicConfig, getLogger, INFO, DEBUG
from distutils.util import strtobool as sb
from pylast import LastFMNetwork, md5
from pySmartDL import SmartDL
from dotenv import load_dotenv
from requests import get
from telethon import TelegramClient
from telethon.sessions import StringSession
load_dotenv("config.env")
# Bot Logs setup:
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
if CONSOLE_LOGGER_VERBOSE:
basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=DEBUG,
)
else:
basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=INFO)
LOGS = getLogger(__name__)
if version_info[0] < 3 or version_info[1] < 6:
LOGS.info("You MUST have a python version of at least 3.6."
"Multiple features depend on this. Bot quitting.")
quit(1)
# Check if the config was edited by using the already used variable.
# Basically, its the 'virginity check' for the config file ;)
CONFIG_CHECK = os.environ.get(
"___________PLOX_______REMOVE_____THIS_____LINE__________", None)
if CONFIG_CHECK:
LOGS.info(
"Please remove the line mentioned in the first hashtag from the config.env file"
)
quit(1)
# Telegram App KEY and HASH
API_KEY = os.environ.get("API_KEY", None)
API_HASH = os.environ.get("API_HASH", None)
# Userbot Session String
STRING_SESSION = os.environ.get("STRING_SESSION", None)
# Logging channel/group ID configuration.
BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None))
# Userbot logging feature switch.
BOTLOG = sb(os.environ.get("BOTLOG", "False"))
LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False"))
# Bleep Blop, this is a bot ;)
PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False"))
# Console verbose logging
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
# SQL Database URI
DB_URI = os.environ.get("DATABASE_URL", None)
# OCR API key
OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None)
# remove.bg API key
REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None)
# Chrome Driver and Headless Google Chrome Binaries
CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None)
GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None)
# OpenWeatherMap API Key
OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)
WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None)
# Anti Spambot Config
ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False"))
ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False"))
# Youtube API key
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None)
# Default .alive name
ALIVE_NAME = os.environ.get("ALIVE_NAME", None)
# Time & Date - Country and Time Zone
COUNTRY = str(os.environ.get("COUNTRY", ""))
TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1))
# Clean Welcome
CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True"))
# Last.fm Module
BIO_PREFIX = os.environ.get("BIO_PREFIX", None)
DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None)
LASTFM_API = os.environ.get("LASTFM_API", None)
LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None)
LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None)
LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None)
if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASSWORD_PLAIN:
LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)
lastfm = LastFMNetwork(api_key=LASTFM_API,
api_secret=LASTFM_SECRET,
username=LASTFM_USERNAME,
password_hash=LASTFM_PASS)
else:
lastfm = None
# Google Drive Module configuration.
G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None)
G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None)
G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None)
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", None)
# Directory to save downloaded stuff, for many modules.
TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY",
"./downloads")
# Setting Up CloudMail.ru and MEGA.nz extractor binaries,
# and giving them correct perms to work properly.
if not os.path.exists('bin'):
os.mkdir('bin')
binaries = {
"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
"bin/megadown",
"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
"bin/cmrudl"
}
for binary, path in binaries.items():
downloader = SmartDL(binary, path, progress_bar=False)
downloader.start()
os.chmod(path, 0o755)
# 'bot' variable
if STRING_SESSION:
# pylint: disable=invalid-name
bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, timeout=5, retry_delay=5)
else:
# pylint: disable=invalid-name
bot = TelegramClient("userbot", API_KEY, API_HASH, timeout=5, retry_delay=5)
async def check_botlog_chatid():
if not BOTLOG_CHATID and LOGSPAMMER:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
)
quit(1)
elif not BOTLOG_CHATID and BOTLOG:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
)
quit(1)
elif not BOTLOG or not LOGSPAMMER:
return
entity = await bot.get_entity(BOTLOG_CHATID)
if entity.default_banned_rights.send_messages:
LOGS.info(
"Your account doesn't have rights to send messages to BOTLOG_CHATID "
"group. Check if you typed the Chat ID correctly.")
quit(1)
with bot:
try:
bot.loop.run_until_complete(check_botlog_chatid())
except:
LOGS.info(
"BOTLOG_CHATID environment variable isn't a "
"valid entity. Check your environment variables/config.env file.")
quit(1)
# Global Variables
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
CMD_HELP = {}
ISAFK = False
AFKREASON = None
| 32.17 | 143 | 0.713864 |
import os
from sys import version_info
from logging import basicConfig, getLogger, INFO, DEBUG
from distutils.util import strtobool as sb
from pylast import LastFMNetwork, md5
from pySmartDL import SmartDL
from dotenv import load_dotenv
from requests import get
from telethon import TelegramClient
from telethon.sessions import StringSession
load_dotenv("config.env")
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
if CONSOLE_LOGGER_VERBOSE:
basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=DEBUG,
)
else:
basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=INFO)
LOGS = getLogger(__name__)
if version_info[0] < 3 or version_info[1] < 6:
LOGS.info("You MUST have a python version of at least 3.6."
"Multiple features depend on this. Bot quitting.")
quit(1)
CONFIG_CHECK = os.environ.get(
"___________PLOX_______REMOVE_____THIS_____LINE__________", None)
if CONFIG_CHECK:
LOGS.info(
"Please remove the line mentioned in the first hashtag from the config.env file"
)
quit(1)
API_KEY = os.environ.get("API_KEY", None)
API_HASH = os.environ.get("API_HASH", None)
STRING_SESSION = os.environ.get("STRING_SESSION", None)
BOTLOG_CHATID = int(os.environ.get("BOTLOG_CHATID", None))
BOTLOG = sb(os.environ.get("BOTLOG", "False"))
LOGSPAMMER = sb(os.environ.get("LOGSPAMMER", "False"))
PM_AUTO_BAN = sb(os.environ.get("PM_AUTO_BAN", "False"))
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))
DB_URI = os.environ.get("DATABASE_URL", None)
OCR_SPACE_API_KEY = os.environ.get("OCR_SPACE_API_KEY", None)
REM_BG_API_KEY = os.environ.get("REM_BG_API_KEY", None)
CHROME_DRIVER = os.environ.get("CHROME_DRIVER", None)
GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None)
OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)
WEATHER_DEFCITY = os.environ.get("WEATHER_DEFCITY", None)
ANTI_SPAMBOT = sb(os.environ.get("ANTI_SPAMBOT", "False"))
ANTI_SPAMBOT_SHOUT = sb(os.environ.get("ANTI_SPAMBOT_SHOUT", "False"))
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY", None)
ALIVE_NAME = os.environ.get("ALIVE_NAME", None)
COUNTRY = str(os.environ.get("COUNTRY", ""))
TZ_NUMBER = int(os.environ.get("TZ_NUMBER", 1))
CLEAN_WELCOME = sb(os.environ.get("CLEAN_WELCOME", "True"))
BIO_PREFIX = os.environ.get("BIO_PREFIX", None)
DEFAULT_BIO = os.environ.get("DEFAULT_BIO", None)
LASTFM_API = os.environ.get("LASTFM_API", None)
LASTFM_SECRET = os.environ.get("LASTFM_SECRET", None)
LASTFM_USERNAME = os.environ.get("LASTFM_USERNAME", None)
LASTFM_PASSWORD_PLAIN = os.environ.get("LASTFM_PASSWORD", None)
if LASTFM_API and LASTFM_SECRET and LASTFM_USERNAME and LASTFM_PASSWORD_PLAIN:
LASTFM_PASS = md5(LASTFM_PASSWORD_PLAIN)
lastfm = LastFMNetwork(api_key=LASTFM_API,
api_secret=LASTFM_SECRET,
username=LASTFM_USERNAME,
password_hash=LASTFM_PASS)
else:
lastfm = None
G_DRIVE_CLIENT_ID = os.environ.get("G_DRIVE_CLIENT_ID", None)
G_DRIVE_CLIENT_SECRET = os.environ.get("G_DRIVE_CLIENT_SECRET", None)
G_DRIVE_AUTH_TOKEN_DATA = os.environ.get("G_DRIVE_AUTH_TOKEN_DATA", None)
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", None)
TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TMP_DOWNLOAD_DIRECTORY",
"./downloads")
if not os.path.exists('bin'):
os.mkdir('bin')
binaries = {
"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
"bin/megadown",
"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
"bin/cmrudl"
}
for binary, path in binaries.items():
downloader = SmartDL(binary, path, progress_bar=False)
downloader.start()
os.chmod(path, 0o755)
if STRING_SESSION:
bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH, timeout=5, retry_delay=5)
else:
bot = TelegramClient("userbot", API_KEY, API_HASH, timeout=5, retry_delay=5)
async def check_botlog_chatid():
if not BOTLOG_CHATID and LOGSPAMMER:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
)
quit(1)
elif not BOTLOG_CHATID and BOTLOG:
LOGS.info(
"You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
)
quit(1)
elif not BOTLOG or not LOGSPAMMER:
return
entity = await bot.get_entity(BOTLOG_CHATID)
if entity.default_banned_rights.send_messages:
LOGS.info(
"Your account doesn't have rights to send messages to BOTLOG_CHATID "
"group. Check if you typed the Chat ID correctly.")
quit(1)
with bot:
try:
bot.loop.run_until_complete(check_botlog_chatid())
except:
LOGS.info(
"BOTLOG_CHATID environment variable isn't a "
"valid entity. Check your environment variables/config.env file.")
quit(1)
COUNT_MSG = 0
USERS = {}
COUNT_PM = {}
LASTMSG = {}
CMD_HELP = {}
ISAFK = False
AFKREASON = None
| true | true |
f72c4479ad5d2532a05900a83c5526eec00f800e | 13,381 | py | Python | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 14 | 2019-04-12T11:24:54.000Z | 2022-03-21T01:13:27.000Z | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 37 | 2019-06-29T05:54:10.000Z | 2021-08-03T05:54:52.000Z | src/rkd_harbor/tasks/deployment/base.py | attawayinc/riotkit-harbor | baea9f6e856f18835d316e3adc01ced2b9aaebda | [
"Apache-2.0"
] | 2 | 2021-09-29T04:22:52.000Z | 2021-09-29T06:43:59.000Z | import os
import subprocess
from abc import ABC
from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import StrictUndefined
from jinja2.exceptions import UndefinedError
from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from rkd.yaml_parser import YamlFileLoader
from rkd.exception import MissingInputException
from rkd.api.inputoutput import Wizard
from ..base import HarborBaseTask
from ...exception import MissingDeploymentConfigurationError
HARBOR_ROOT = os.path.dirname(os.path.realpath(__file__)) + '/../../deployment/files'
class BaseDeploymentTask(HarborBaseTask, ABC):
ansible_dir: str = '.rkd/deployment'
_config: dict
vault_args: list = []
def get_config(self) -> dict:
"""Loads and parses deployment.yml file.
Supports:
- Ansible Vault encryption of deployment.yml
- SSH private key storage inside deployment.yml
"""
deployment_filenames = ['deployment.yml', 'deployment.yaml']
try:
self._config
except AttributeError:
# try multiple files
for filename in deployment_filenames:
if os.path.isfile(filename):
#
# Check file contents before
#
with open(filename, 'rb') as f:
content = f.read().decode('utf-8')
#
# When file is encrypted, then decrypt it
#
if content.startswith('$ANSIBLE_VAULT;'):
tmp_vault_path, tmp_vault_filename = self.temp.create_tmp_file_path()
self.io().info('Decrypting deployment file')
self.sh('cp %s %s' % (filename, tmp_vault_path))
self.io().info_msg('Need a vault passphrase to decrypt "%s"' % filename)
self.rkd([':harbor:vault:encrypt', '-d', tmp_vault_path] + self.vault_args)
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
tmp_vault_filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
raise MissingDeploymentConfigurationError()
return self._config
def _process_config_private_keys(self):
"""Allow private keys to be pasted directly to the deployment.yml
On-the-fly those keys will be written into the temporary directory
"""
for group_name, nodes in self._config['nodes'].items():
for node_num in range(0, len(nodes)):
if 'private_key' not in self._config['nodes'][group_name][node_num]:
continue
if '-----BEGIN' not in self._config['nodes'][group_name][node_num]['private_key']:
continue
tmp_path = self.temp.assign_temporary_file(mode=0o700)
self.io().info('Storing inline private key as "%s"' % tmp_path)
with open(tmp_path, 'w') as key_file:
key_file.write(self._config['nodes'][group_name][node_num]['private_key'].strip())
key_file.write("\n")
self._config['nodes'][group_name][node_num]['private_key'] = tmp_path
def _verify_synced_version(self, abs_ansible_dir: str):
"""Verifies last synchronization - displays warning if Harbor version was changed after last
files synchronization"""
if not os.path.isfile(abs_ansible_dir + '/.synced'):
return
with open(abs_ansible_dir + '/.synced', 'rb') as f:
synced_version = f.read().decode('utf-8').strip()
actual_version = self.get_harbor_version()
if synced_version != actual_version:
self.io().warn('Ansible deployment in .rkd/deployment is not up-to-date. We recommend to update' +
' from %s to %s' % (synced_version, actual_version))
def _write_synced_version(self, abs_ansible_dir: str):
"""Writes information about, in which Harbor version the files were synced last time"""
with open(abs_ansible_dir + '/.synced', 'wb') as f:
f.write(self.get_harbor_version().encode('utf-8'))
def role_is_installed_and_configured(self) -> bool:
return os.path.isfile(self.ansible_dir + '/.synced')
def _ask_and_set_var(self, ctx: ExecutionContext, arg_name: str, title: str, attribute: str, secret: bool):
"""Ask user an interactive question, then add answer to the deployment.yml loaded in memory
The variable will be appended to any node, where the variable is empty.
Example: We have 5 servers, 3 without a password. So the password will be applied to 3 servers.
"""
self.get_config()
if not ctx.get_arg(arg_name):
return
wizard = Wizard(self).ask(title, attribute=attribute, secret=secret)
for group_name, nodes in self._config['nodes'].items():
node_num = 0
for node in nodes:
node_num += 1
if attribute in self._config['nodes'][group_name][node_num - 1]:
continue
self._config['nodes'][group_name][node_num - 1][attribute] = wizard.answers[attribute]
def install_and_configure_role(self, ctx: ExecutionContext, force_update: bool = False) -> bool:
"""Install an Ansible role from galaxy, and configure playbook, inventory, all the needed things"""
abs_ansible_dir = os.path.realpath(self.ansible_dir)
should_update = force_update or not os.path.isfile(abs_ansible_dir + '/.synced')
self.io().info('Checking role installation...')
self._silent_mkdir(abs_ansible_dir)
self._verify_synced_version(abs_ansible_dir)
# optionally ask user and set facts such as passwords, key paths, sudo passwords
# ansible-vault password prompt is handed by ansible-vault itself
self._ask_and_set_var(ctx, '--ask-ssh-login', 'SSH username', 'user', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-pass', 'SSH password', 'password', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-key-path', 'SSH private key path', 'private_key', secret=False)
self._ask_and_set_var(ctx, '--ask-sudo-pass', 'Sudo password for remote machines', 'sudo_pass', secret=True)
if not self._synchronize_structure_from_template(abs_ansible_dir, only_jinja_templates=True):
self.io().error_msg('Cannot synchronize templates')
return False
if should_update:
self.io().info('Role will be updated')
if not self._synchronize_structure_from_template(abs_ansible_dir):
self.io().error_msg('Cannot synchronize structure')
return False
self.io().debug('Downloading fresh role...')
self.download_roles()
self._write_synced_version(abs_ansible_dir)
return True
def download_roles(self):
self.sh(' '.join([
'ansible-galaxy',
'install', '-r', self.ansible_dir + '/requirements.yml',
'-p', self.ansible_dir + '/roles/',
'--force'
]), capture=False)
def _synchronize_structure_from_template(self, abs_ansible_dir: str, only_jinja_templates: bool = False) -> bool:
"""Synchronizes template structure into .rkd/deployment"""
self.io().debug(
'Synchronizing structure from template (only_jinja_templates=' + str(only_jinja_templates) + ')')
# synchronize directory structure
for root, subdirs, files in os.walk(HARBOR_ROOT):
relative_root = root[len(HARBOR_ROOT) + 1:]
self._silent_mkdir(abs_ansible_dir + '/' + relative_root)
for file in files:
if only_jinja_templates and not file.endswith('.j2'):
continue
abs_src_file_path = root + '/' + file
abs_dest_file_path = abs_ansible_dir + '/' + relative_root + '/' + file
if not self._copy_file(abs_src_file_path, abs_dest_file_path):
self.io().error('Cannot process file %s' % abs_dest_file_path)
return False
return True
def _copy_file(self, abs_src_file_path: str, abs_dest_file_path: str):
"""Copies a file from template directory - supports jinja2 files rendering on-the-fly"""
if abs_dest_file_path.endswith('.j2'):
abs_dest_file_path = abs_dest_file_path[:-3]
with open(abs_src_file_path, 'rb') as f:
tpl = Environment(loader=FileSystemLoader(['./', './rkd/deployment']), undefined=StrictUndefined)\
.from_string(f.read().decode('utf-8'))
try:
variables = self._prepare_variables()
with open(abs_dest_file_path, 'wb') as f:
f.write(tpl.render(**variables).encode('utf-8'))
except UndefinedError as e:
self.io().error(str(e) + " - required in " + abs_src_file_path + ", please define it in deployment.yml")
return False
return True
subprocess.check_call(['cp', '-p', abs_src_file_path, abs_dest_file_path])
self.io().debug('Created ' + abs_dest_file_path)
return True
def _prepare_variables(self):
"""Glues together variables from environment and from deployment.yaml for exposing in JINJA2 templates"""
variables = {}
variables.update(os.environ)
variables.update(self.get_config())
if 'git_url' not in variables:
variables['git_url'] = subprocess\
.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8')\
.replace('\n', '')\
.strip()
if 'git_secret_url' not in variables:
variables['git_secret_url'] = variables['git_url'].replace('\n', '')
return variables
def _preserve_vault_parameters_for_usage_in_inner_tasks(self, ctx: ExecutionContext):
"""Preserve original parameters related to Vault, so those parameters can be propagated to inner tasks"""
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords')
except MissingInputException:
vault_passwords = ''
# keep the vault arguments for decryption of deployment.yml
self.vault_args = ['--vault-passwords=' + vault_passwords]
if ctx.get_arg('--ask-vault-pass'):
self.vault_args.append('--ask-vault-pass')
def _get_vault_opts(self, ctx: ExecutionContext, chdir: str = '') -> str:
"""Creates options to pass in Ansible Vault commandline
The output will be a temporary vault file with password entered inline or a --ask-vault-pass switch
"""
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords').split('||')
except MissingInputException:
vault_passwords = []
num = 0
opts = ''
enforce_ask_pass = ctx.get_arg('--ask-vault-pass')
for passwd in vault_passwords:
num = num + 1
if not passwd:
continue
if passwd.startswith('./') or passwd.startswith('/'):
if os.path.isfile(passwd):
opts += ' --vault-password-file="%s" ' % (chdir + passwd)
else:
self.io().error('Vault password file "%s" does not exist, calling --ask-vault-pass' % passwd)
enforce_ask_pass = True
else:
tmp_vault_file = self.temp.assign_temporary_file(mode=0o644)
with open(tmp_vault_file, 'w') as f:
f.write(passwd)
opts += ' --vault-password-file="%s" ' % (chdir + tmp_vault_file)
if enforce_ask_pass:
opts += ' --ask-vault-pass '
return opts
@classmethod
def _add_vault_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-vault-pass', '-v', help='Ask for vault password interactively', action='store_true')
parser.add_argument('--vault-passwords', '-V', help='Vault passwords separated by "||" eg. 123||456')
@classmethod
def _add_ask_pass_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-ssh-login', help='Ask for SSH username', action='store_true')
parser.add_argument('--ask-ssh-pass', help='Ask for a SSH password', action='store_true')
parser.add_argument('--ask-ssh-key-path', help='Ask for a SSH private key path', action='store_true')
parser.add_argument('--ask-sudo-pass', help='Ask for sudo password', action='store_true')
| 41.172308 | 120 | 0.603318 | import os
import subprocess
from abc import ABC
from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import StrictUndefined
from jinja2.exceptions import UndefinedError
from argparse import ArgumentParser
from rkd.api.contract import ExecutionContext
from rkd.yaml_parser import YamlFileLoader
from rkd.exception import MissingInputException
from rkd.api.inputoutput import Wizard
from ..base import HarborBaseTask
from ...exception import MissingDeploymentConfigurationError
HARBOR_ROOT = os.path.dirname(os.path.realpath(__file__)) + '/../../deployment/files'
class BaseDeploymentTask(HarborBaseTask, ABC):
ansible_dir: str = '.rkd/deployment'
_config: dict
vault_args: list = []
def get_config(self) -> dict:
deployment_filenames = ['deployment.yml', 'deployment.yaml']
try:
self._config
except AttributeError:
for filename in deployment_filenames:
if os.path.isfile(filename):
with open(filename, 'rb') as f:
content = f.read().decode('utf-8')
if content.startswith('$ANSIBLE_VAULT;'):
tmp_vault_path, tmp_vault_filename = self.temp.create_tmp_file_path()
self.io().info('Decrypting deployment file')
self.sh('cp %s %s' % (filename, tmp_vault_path))
self.io().info_msg('Need a vault passphrase to decrypt "%s"' % filename)
self.rkd([':harbor:vault:encrypt', '-d', tmp_vault_path] + self.vault_args)
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
tmp_vault_filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
self._config = YamlFileLoader(self._ctx.directories).load_from_file(
filename,
'org.riotkit.harbor/deployment/v1'
)
self._process_config_private_keys()
return self._config
raise MissingDeploymentConfigurationError()
return self._config
def _process_config_private_keys(self):
for group_name, nodes in self._config['nodes'].items():
for node_num in range(0, len(nodes)):
if 'private_key' not in self._config['nodes'][group_name][node_num]:
continue
if '-----BEGIN' not in self._config['nodes'][group_name][node_num]['private_key']:
continue
tmp_path = self.temp.assign_temporary_file(mode=0o700)
self.io().info('Storing inline private key as "%s"' % tmp_path)
with open(tmp_path, 'w') as key_file:
key_file.write(self._config['nodes'][group_name][node_num]['private_key'].strip())
key_file.write("\n")
self._config['nodes'][group_name][node_num]['private_key'] = tmp_path
def _verify_synced_version(self, abs_ansible_dir: str):
if not os.path.isfile(abs_ansible_dir + '/.synced'):
return
with open(abs_ansible_dir + '/.synced', 'rb') as f:
synced_version = f.read().decode('utf-8').strip()
actual_version = self.get_harbor_version()
if synced_version != actual_version:
self.io().warn('Ansible deployment in .rkd/deployment is not up-to-date. We recommend to update' +
' from %s to %s' % (synced_version, actual_version))
def _write_synced_version(self, abs_ansible_dir: str):
with open(abs_ansible_dir + '/.synced', 'wb') as f:
f.write(self.get_harbor_version().encode('utf-8'))
def role_is_installed_and_configured(self) -> bool:
return os.path.isfile(self.ansible_dir + '/.synced')
def _ask_and_set_var(self, ctx: ExecutionContext, arg_name: str, title: str, attribute: str, secret: bool):
self.get_config()
if not ctx.get_arg(arg_name):
return
wizard = Wizard(self).ask(title, attribute=attribute, secret=secret)
for group_name, nodes in self._config['nodes'].items():
node_num = 0
for node in nodes:
node_num += 1
if attribute in self._config['nodes'][group_name][node_num - 1]:
continue
self._config['nodes'][group_name][node_num - 1][attribute] = wizard.answers[attribute]
def install_and_configure_role(self, ctx: ExecutionContext, force_update: bool = False) -> bool:
abs_ansible_dir = os.path.realpath(self.ansible_dir)
should_update = force_update or not os.path.isfile(abs_ansible_dir + '/.synced')
self.io().info('Checking role installation...')
self._silent_mkdir(abs_ansible_dir)
self._verify_synced_version(abs_ansible_dir)
self._ask_and_set_var(ctx, '--ask-ssh-login', 'SSH username', 'user', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-pass', 'SSH password', 'password', secret=True)
self._ask_and_set_var(ctx, '--ask-ssh-key-path', 'SSH private key path', 'private_key', secret=False)
self._ask_and_set_var(ctx, '--ask-sudo-pass', 'Sudo password for remote machines', 'sudo_pass', secret=True)
if not self._synchronize_structure_from_template(abs_ansible_dir, only_jinja_templates=True):
self.io().error_msg('Cannot synchronize templates')
return False
if should_update:
self.io().info('Role will be updated')
if not self._synchronize_structure_from_template(abs_ansible_dir):
self.io().error_msg('Cannot synchronize structure')
return False
self.io().debug('Downloading fresh role...')
self.download_roles()
self._write_synced_version(abs_ansible_dir)
return True
def download_roles(self):
self.sh(' '.join([
'ansible-galaxy',
'install', '-r', self.ansible_dir + '/requirements.yml',
'-p', self.ansible_dir + '/roles/',
'--force'
]), capture=False)
def _synchronize_structure_from_template(self, abs_ansible_dir: str, only_jinja_templates: bool = False) -> bool:
self.io().debug(
'Synchronizing structure from template (only_jinja_templates=' + str(only_jinja_templates) + ')')
for root, subdirs, files in os.walk(HARBOR_ROOT):
relative_root = root[len(HARBOR_ROOT) + 1:]
self._silent_mkdir(abs_ansible_dir + '/' + relative_root)
for file in files:
if only_jinja_templates and not file.endswith('.j2'):
continue
abs_src_file_path = root + '/' + file
abs_dest_file_path = abs_ansible_dir + '/' + relative_root + '/' + file
if not self._copy_file(abs_src_file_path, abs_dest_file_path):
self.io().error('Cannot process file %s' % abs_dest_file_path)
return False
return True
def _copy_file(self, abs_src_file_path: str, abs_dest_file_path: str):
if abs_dest_file_path.endswith('.j2'):
abs_dest_file_path = abs_dest_file_path[:-3]
with open(abs_src_file_path, 'rb') as f:
tpl = Environment(loader=FileSystemLoader(['./', './rkd/deployment']), undefined=StrictUndefined)\
.from_string(f.read().decode('utf-8'))
try:
variables = self._prepare_variables()
with open(abs_dest_file_path, 'wb') as f:
f.write(tpl.render(**variables).encode('utf-8'))
except UndefinedError as e:
self.io().error(str(e) + " - required in " + abs_src_file_path + ", please define it in deployment.yml")
return False
return True
subprocess.check_call(['cp', '-p', abs_src_file_path, abs_dest_file_path])
self.io().debug('Created ' + abs_dest_file_path)
return True
def _prepare_variables(self):
variables = {}
variables.update(os.environ)
variables.update(self.get_config())
if 'git_url' not in variables:
variables['git_url'] = subprocess\
.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8')\
.replace('\n', '')\
.strip()
if 'git_secret_url' not in variables:
variables['git_secret_url'] = variables['git_url'].replace('\n', '')
return variables
def _preserve_vault_parameters_for_usage_in_inner_tasks(self, ctx: ExecutionContext):
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords')
except MissingInputException:
vault_passwords = ''
self.vault_args = ['--vault-passwords=' + vault_passwords]
if ctx.get_arg('--ask-vault-pass'):
self.vault_args.append('--ask-vault-pass')
def _get_vault_opts(self, ctx: ExecutionContext, chdir: str = '') -> str:
try:
vault_passwords = ctx.get_arg_or_env('--vault-passwords').split('||')
except MissingInputException:
vault_passwords = []
num = 0
opts = ''
enforce_ask_pass = ctx.get_arg('--ask-vault-pass')
for passwd in vault_passwords:
num = num + 1
if not passwd:
continue
if passwd.startswith('./') or passwd.startswith('/'):
if os.path.isfile(passwd):
opts += ' --vault-password-file="%s" ' % (chdir + passwd)
else:
self.io().error('Vault password file "%s" does not exist, calling --ask-vault-pass' % passwd)
enforce_ask_pass = True
else:
tmp_vault_file = self.temp.assign_temporary_file(mode=0o644)
with open(tmp_vault_file, 'w') as f:
f.write(passwd)
opts += ' --vault-password-file="%s" ' % (chdir + tmp_vault_file)
if enforce_ask_pass:
opts += ' --ask-vault-pass '
return opts
@classmethod
def _add_vault_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-vault-pass', '-v', help='Ask for vault password interactively', action='store_true')
parser.add_argument('--vault-passwords', '-V', help='Vault passwords separated by "||" eg. 123||456')
@classmethod
def _add_ask_pass_arguments_to_argparse(cls, parser: ArgumentParser):
parser.add_argument('--ask-ssh-login', help='Ask for SSH username', action='store_true')
parser.add_argument('--ask-ssh-pass', help='Ask for a SSH password', action='store_true')
parser.add_argument('--ask-ssh-key-path', help='Ask for a SSH private key path', action='store_true')
parser.add_argument('--ask-sudo-pass', help='Ask for sudo password', action='store_true')
| true | true |
f72c4540917b51bca7ea46963d819966d9f4ad33 | 103 | py | Python | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | 1 | 2020-05-16T14:03:09.000Z | 2020-05-16T14:03:09.000Z | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | null | null | null | code/test/__init__.py | fgitmichael/TestModeDisentangling | 022fbe5b49e847aeb110d89be1e0b1c28bcff01d | [
"MIT"
] | null | null | null | from .mode_actions_sampler import ModeActionSampler
from .disentangling_test import DisentanglingTester | 51.5 | 51 | 0.912621 | from .mode_actions_sampler import ModeActionSampler
from .disentangling_test import DisentanglingTester | true | true |
f72c464b80241ef5e87521b090940d0e329fe244 | 2,462 | py | Python | algotrader/trading/context.py | alexcwyu/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 17 | 2016-03-30T21:52:30.000Z | 2021-05-01T18:21:48.000Z | algotrader/trading/context.py | ajmal017/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 2 | 2016-10-04T19:29:05.000Z | 2017-02-01T19:24:39.000Z | algotrader/trading/context.py | ajmal017/python-trading | a494f602411a3ebfdecae002a16a5ea93fc7a046 | [
"Apache-2.0"
] | 9 | 2016-04-24T05:05:26.000Z | 2020-05-03T13:01:34.000Z | from algotrader import Context
from algotrader.model.model_factory import ModelFactory
from algotrader.provider import ProviderManager
from algotrader.provider.broker import Broker
from algotrader.provider.datastore import DataStore
from algotrader.provider.feed import Feed
from algotrader.strategy import StrategyManager
from algotrader.trading.account import AccountManager
from algotrader.trading.clock import Clock, RealTimeClock, SimulationClock
from algotrader.trading.config import Config
from algotrader.trading.event import EventBus
from algotrader.trading.instrument_data import InstrumentDataManager
from algotrader.trading.order import OrderManager
from algotrader.trading.portfolio import Portfolio, PortfolioManager
from algotrader.trading.ref_data import RefDataManager
from algotrader.trading.sequence import SequenceManager
class ApplicationContext(Context):
def __init__(self, config: Config = None):
super(ApplicationContext, self).__init__()
self.config = config if config else Config()
self.clock = self.add_startable(self.__get_clock())
self.provider_mgr = self.add_startable(ProviderManager())
self.seq_mgr = self.add_startable(SequenceManager())
self.inst_data_mgr = self.add_startable(InstrumentDataManager())
self.ref_data_mgr = self.add_startable(RefDataManager())
self.order_mgr = self.add_startable(OrderManager())
self.acct_mgr = self.add_startable(AccountManager())
self.portf_mgr = self.add_startable(PortfolioManager())
self.stg_mgr = self.add_startable(StrategyManager())
self.event_bus = EventBus()
self.model_factory = ModelFactory
def __get_clock(self) -> Clock:
if self.config.get_app_config("clockId", Clock.Simulation) == Clock.RealTime:
return RealTimeClock()
return SimulationClock()
def get_data_store(self) -> DataStore:
return self.provider_mgr.get(self.config.get_app_config("dataStoreId"))
def get_broker(self) -> Broker:
return self.provider_mgr.get(self.config.get_app_config("brokerId"))
def get_feed(self) -> Feed:
return self.provider_mgr.get(self.config.get_app_config("feedId"))
def get_portfolio(self) -> Portfolio:
return self.portf_mgr.get_or_new_portfolio(self.config.get_app_config("dataStoreId"),
self.config.get_app_config("portfolioInitialcash"))
| 42.448276 | 102 | 0.750203 | from algotrader import Context
from algotrader.model.model_factory import ModelFactory
from algotrader.provider import ProviderManager
from algotrader.provider.broker import Broker
from algotrader.provider.datastore import DataStore
from algotrader.provider.feed import Feed
from algotrader.strategy import StrategyManager
from algotrader.trading.account import AccountManager
from algotrader.trading.clock import Clock, RealTimeClock, SimulationClock
from algotrader.trading.config import Config
from algotrader.trading.event import EventBus
from algotrader.trading.instrument_data import InstrumentDataManager
from algotrader.trading.order import OrderManager
from algotrader.trading.portfolio import Portfolio, PortfolioManager
from algotrader.trading.ref_data import RefDataManager
from algotrader.trading.sequence import SequenceManager
class ApplicationContext(Context):
def __init__(self, config: Config = None):
super(ApplicationContext, self).__init__()
self.config = config if config else Config()
self.clock = self.add_startable(self.__get_clock())
self.provider_mgr = self.add_startable(ProviderManager())
self.seq_mgr = self.add_startable(SequenceManager())
self.inst_data_mgr = self.add_startable(InstrumentDataManager())
self.ref_data_mgr = self.add_startable(RefDataManager())
self.order_mgr = self.add_startable(OrderManager())
self.acct_mgr = self.add_startable(AccountManager())
self.portf_mgr = self.add_startable(PortfolioManager())
self.stg_mgr = self.add_startable(StrategyManager())
self.event_bus = EventBus()
self.model_factory = ModelFactory
def __get_clock(self) -> Clock:
if self.config.get_app_config("clockId", Clock.Simulation) == Clock.RealTime:
return RealTimeClock()
return SimulationClock()
def get_data_store(self) -> DataStore:
return self.provider_mgr.get(self.config.get_app_config("dataStoreId"))
def get_broker(self) -> Broker:
return self.provider_mgr.get(self.config.get_app_config("brokerId"))
def get_feed(self) -> Feed:
return self.provider_mgr.get(self.config.get_app_config("feedId"))
def get_portfolio(self) -> Portfolio:
return self.portf_mgr.get_or_new_portfolio(self.config.get_app_config("dataStoreId"),
self.config.get_app_config("portfolioInitialcash"))
| true | true |
f72c464dc5c8ee869e61bd1a0fbcf6cc63feb838 | 3,082 | py | Python | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | 3 | 2019-01-04T12:54:16.000Z | 2019-01-13T07:08:10.000Z | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | null | null | null | lispy/lisp.py | fucangyu/myself-impls | 9fd2730f9e0e12f95559d2f4e41c34b670441428 | [
"MIT"
] | 1 | 2019-08-27T18:29:53.000Z | 2019-08-27T18:29:53.000Z | import math
import operator as op
from collections import ChainMap as Environment
Symbol = str
List = list
Number = (int, float)
def parse(program: str):
return read_from_tokens(tokenize(program))
def tokenize(raw):
return raw.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list):
if not len(tokens):
raise SyntaxError('unexpected EOF')
head = tokens.pop(0)
if head == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0)
return L
elif head == ')':
raise SyntaxError('unexpected )')
else:
return atom(head)
def atom(token: str) -> 'Atom':
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
def gen_env() -> dict:
env = {}
env.update(vars(math))
env.update({
'+': op.add,
'-': op.sub,
'*': op.mul,
'/': op.truediv,
'>': op.gt,
'<': op.lt,
'>=': op.ge,
'<=': op.le,
'=': op.eq,
'abs': abs,
'append': op.add,
'apply': lambda proc, args: proc(*args),
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x, y: [x] + y,
'eq?': op.is_,
'equal?': op.eq,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x, list),
'map': lambda *args: list(map(*args)),
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x: isinstance(x, Number),
'procedure?': callable,
'round': round,
'symbol?': lambda x: isinstance(x, Symbol),
})
return env
global_env = gen_env()
def eval(x, env=global_env):
if isinstance(x, Symbol):
return env[x]
elif isinstance(x, Number):
return x
elif x[0] == 'quote':
_, exp = x
return exp
elif x[0] == 'if':
_, test, conseq, alt = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define':
_, symbol, exp = x
env[symbol] = eval(exp, env)
elif x[0] == 'lambda':
_, parms, body = x
return Procedure(parms, body, env)
else:
proc = eval(x[0], env)
args = [eval(arg, env) for arg in x[1:]]
return proc(*args)
def repl(prompt='lispy>> '):
while True:
val = eval(parse(input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
class Procedure(object):
def __init__(self, parms, body, env):
self.parms, self.body, self.env = parms, body, env
def __call__(self, *args):
env = Environment(dict(zip(self.parms, args)), self.env)
return eval(self.body, env)
repl()
| 23.172932 | 64 | 0.508436 | import math
import operator as op
from collections import ChainMap as Environment
Symbol = str
List = list
Number = (int, float)
def parse(program: str):
return read_from_tokens(tokenize(program))
def tokenize(raw):
return raw.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list):
if not len(tokens):
raise SyntaxError('unexpected EOF')
head = tokens.pop(0)
if head == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0)
return L
elif head == ')':
raise SyntaxError('unexpected )')
else:
return atom(head)
def atom(token: str) -> 'Atom':
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
def gen_env() -> dict:
env = {}
env.update(vars(math))
env.update({
'+': op.add,
'-': op.sub,
'*': op.mul,
'/': op.truediv,
'>': op.gt,
'<': op.lt,
'>=': op.ge,
'<=': op.le,
'=': op.eq,
'abs': abs,
'append': op.add,
'apply': lambda proc, args: proc(*args),
'begin': lambda *x: x[-1],
'car': lambda x: x[0],
'cdr': lambda x: x[1:],
'cons': lambda x, y: [x] + y,
'eq?': op.is_,
'equal?': op.eq,
'length': len,
'list': lambda *x: list(x),
'list?': lambda x: isinstance(x, list),
'map': lambda *args: list(map(*args)),
'max': max,
'min': min,
'not': op.not_,
'null?': lambda x: x == [],
'number?': lambda x: isinstance(x, Number),
'procedure?': callable,
'round': round,
'symbol?': lambda x: isinstance(x, Symbol),
})
return env
global_env = gen_env()
def eval(x, env=global_env):
if isinstance(x, Symbol):
return env[x]
elif isinstance(x, Number):
return x
elif x[0] == 'quote':
_, exp = x
return exp
elif x[0] == 'if':
_, test, conseq, alt = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define':
_, symbol, exp = x
env[symbol] = eval(exp, env)
elif x[0] == 'lambda':
_, parms, body = x
return Procedure(parms, body, env)
else:
proc = eval(x[0], env)
args = [eval(arg, env) for arg in x[1:]]
return proc(*args)
def repl(prompt='lispy>> '):
while True:
val = eval(parse(input(prompt)))
if val is not None:
print(schemestr(val))
def schemestr(exp):
if isinstance(exp, List):
return '(' + ' '.join(map(schemestr, exp)) + ')'
else:
return str(exp)
class Procedure(object):
def __init__(self, parms, body, env):
self.parms, self.body, self.env = parms, body, env
def __call__(self, *args):
env = Environment(dict(zip(self.parms, args)), self.env)
return eval(self.body, env)
repl()
| true | true |
f72c46adb32a8a5bb98d87da7bfcaf092e3eb79b | 19,109 | py | Python | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | logs/management/commands/import_log.py | ahemery/ezreports | 9ff0f472ff0f0efd06c8315b99084bd723b0e2f9 | [
"Apache-2.0"
] | null | null | null | import csv
import glob
import os
import pycurl
import re
import ldap3
from datetime import date, timedelta, datetime
from dateutil.parser import parse
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.db.models import Max
from django.utils.text import slugify
from front.models import *
config = {
"ldap": {
"server": "ldap.univ-pau.fr",
"user": "cn=consultplus,ou=admin,dc=univ-pau,dc=fr",
"pwd": "uppaplus",
"base": "ou=people,dc=univ-pau,dc=fr"
},
"ezpaarse": {
"server": "http://ezpaarse.univ-pau.fr",
"options": [
"geoip: none",
"Output-Fields: +datetime",
"Crypted-Fields: none"
],
"debug": "false"
},
"logpath": "/mnt/data/dev/scd/ezreports/proxy_logs/*.log",
"csvpath": "/mnt/data/dev/scd/ezreports/csv/",
}
def querylaboratoire(ldap, name):
name = name.replace("\\", "\\5C")
name = name.replace("*", "\2A")
name = name.replace("(", "\\28")
name = name.replace(")", "\\29")
name = name.replace("\0", "\\00")
if not ldap.search(
'ou=structures,dc=univ-pau,dc=fr',
"(ou=" + name + ")",
attributes=['supannCodeEntite']):
return None
return ldap.entries[0].supannCodeEntite.value
def connexions2sql(filename, sql):
"""
Récupère les connexions à partir du fichier de log d'ezproxy
et les stocke en base
:param filename Nom du fichier à traiter
:param sql Cursor sql
:return:
"""
# Expression régulière pour les log d'ezproxy
regex = "^(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}) - " \
"(?P<login>[0-9a-zA-Z]*) .*" \
"\[(?P<datetime>.*)\].*connect\?session=.*&url=" \
"https?://w*\.?(?P<url>.[^/]*)/(?P<path>.*) HTTP/1.1.*"
login = re.compile(regex)
# Ouvre le fichier
with open(filename) as file:
# Pour chaque lignes
for line in file:
# Ca match ?
match = login.match(line)
if not match:
continue
url = match.group("url")
date = datetime.strptime(match.group("datetime"), '%d/%b/%Y:%H:%M:%S %z')
# Insertion du lien si inconnu
sql.execute(
"INSERT INTO liens (url, slug, disabled) "
"SELECT %(url)s, %(slug)s, 0 "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM liens WHERE url = %(url)s or slug=%(slug)s) LIMIT 1 ",
params={'url': url, 'slug': slugify(url)})
# Insertion de l'utilisateur si inconnu
sql.execute(
"INSERT INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s)) LIMIT 1 ",
params={'login': match.group("login")})
# Insertion de la connexion
sql.execute(
"INSERT INTO connexions "
"SELECT NULL as id, %(date)s as date, %(time)s as time, md5(%(ip)s) as ip, "
"l.id as lien_id, u.id as utilisateur_id "
"FROM utilisateurs u "
"LEFT JOIN liens l on l.url = %(url)s "
"WHERE u.hash = md5(%(login)s) "
"AND NOT EXISTS (SELECT utilisateur_id FROM connexions WHERE "
"utilisateur_id = u.id AND lien_id = l.id AND date = %(date)s "
"AND time = %(time)s AND ip = md5(%(ip)s))",
params={'login': match.group("login"), 'url': url,
'date': date.strftime("%Y-%m-%d"), 'time': date.strftime("%H:%M:%S"),
'ip': match.group("ip")})
connection.commit()
def log2csv(filename):
"""
Converti un fichier log en csv en l'envoyant à ezPAARSE
:param filename: Nom du fichier de log brut
:param outputpath: chemin de sortie du fichier
:return: Nom complet (chemin + nom_du_fichier) du fichier produit
"""
ez = config['ezpaarse']
now = datetime.now()
print(str(now) + " Log 2 CSV : \"" + filename + "\"...")
# Extrait le nom du fichier et son chemin d'accès
path, file = os.path.split(filename)
# Nom du fichier de sortie
outfile = config['csvpath'] + os.path.splitext(file)[0] + '.csv'
return outfile
# On envoie le fichier de log à ezPAARSE
with open(outfile, "wb") as handle:
c = pycurl.Curl()
if ez['debug'] == "true":
c.setopt(c.VERBOSE, 1)
if ez['options'] is not None:
c.setopt(c.HTTPHEADER, ez['options'])
c.setopt(c.URL, ez["server"])
c.setopt(c.HTTPPOST, [(filename, (c.FORM_FILE, filename))])
c.setopt(c.WRITEDATA, handle)
c.perform()
c.close()
return outfile
def csv2sql(filename, sql):
"""
Importe les fichiers CSV produits par ezPAARSE dans une base SQL
:param filename: Nom du fichier CSV à importer
:param sql Connexion sql
:return: Rien
"""
# now = datetime.now()
print(str(datetime.now()) + " CSV 2 SQL : \"" + filename + "\"")
# Ouvre le fichier csv en lecture
with open(filename, 'r') as csvfile:
#
# Connexion à l'annuaire LDAP
server = ldap3.Server(config['ldap']['server'])
ldap = ldap3.Connection(server,
user=config['ldap']['user'],
password=config['ldap']['pwd'],
auto_bind=True)
# Converti le fichier en format CSV
for row in csv.DictReader(csvfile, delimiter=';'):
#print(row)
csvhash = ""
for k, v in sorted(row.items()):
csvhash += v
# Variables
dt = parse(row["datetime"])
login = row["login"]
# Insertion des clefs étrangères
sql.execute("INSERT IGNORE INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s))",
params={'login': login})
if row['publisher_name']:
sql.execute("INSERT INTO editeurs (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM editeurs WHERE slug = %(slug)s) LIMIT 1 ",
params={'libelle': row["publisher_name"], 'slug': slugify(row['publisher_name'])})
# todo: Faire le lien entre la ressource et l'éditeur lors de la création d'une nouvelle ressource
if row['platform_name']:
sql.execute("INSERT INTO ressources (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM ressources WHERE slug = %(slug)s) LIMIT 1 ",
params={'slug': slugify(row["platform_name"]), 'libelle': row["platform_name"]})
if row['rtype']:
sql.execute("INSERT INTO types (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM types WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["rtype"]})
if row['mime']:
sql.execute("INSERT INTO formats (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM formats WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["mime"]})
# Insertions des consultations
sql.execute("INSERT INTO consultations "
"(JOUR, HEURE, UTILISATEUR_ID, RESSOURCE_ID, EDITEUR_ID, TYPE_ID, FORMAT_ID, HOST, HASH) "
"SELECT %(jour)s, %(heure)s, u.id, r.id, e.id, t.id, f.id, %(host)s, sha1(%(hash)s) "
"FROM (SELECT 1) as tmp "
"LEFT JOIN utilisateurs u on u.hash = md5(%(login)s) "
"LEFT JOIN ressources r on r.slug = %(ressource)s "
"LEFT JOIN formats f on f.code = %(format)s "
"LEFT JOIN types t on t.code = %(type)s "
"LEFT JOIN editeurs e on e.slug = %(editeur)s "
"WHERE NOT EXISTS(SELECT id FROM consultations WHERE hash = sha1(%(hash)s)) "
"LIMIT 1 ",
{
'jour': dt.date(),
'heure': dt.time(),
'login': login,
'ressource': slugify(row["platform_name"]),
'editeur': slugify(row["publisher_name"]),
'type': row["rtype"],
'format': row["mime"],
'host': row["host"],
'hash': csvhash,
})
ec_id = sql.lastrowid
# On a déjà inséré cette ligne, donc on passe à la suivante
if ec_id == 0:
continue
#
# On récupère les informations LDAP du compte utilisateur
if not ldap.search(
'ou=people,dc=univ-pau,dc=fr',
"(uid=" + login + ")",
attributes=['supannEtuInscription', 'supannEntiteAffectationPrincipale', 'uppaCodeComp',
'uppaDrhComposante', 'uppaProfil', 'uppaDrhLaboratoire']):
print("No ldap informations for \"" + login + "\"")
continue
# todo: Vilain hack, bouuh !
infos = ldap.entries[0]._attributes
if not infos:
continue
#
# Converti le profil en tableau si ce n'est pas le cas
profils = infos["uppaProfil"].values if "uppaProfil" in infos else ["VIDE"]
for profil in profils:
composante_libelle = None
composante_code = None
laboratoire = None
laboratoire_code = None
diplome_libelle = None
diplome_code = None
cursus_annee = None
if profil == "VIDE":
composante_code = infos["uppaCodeComp"]
composante_libelle = infos["uppaDrhComposante"]
#
# Profil étudiant
elif profil in ("ETU", "AE0", "AE1", "AE2", "AET", "AEP"):
if "supannEtuInscription" in infos:
# Eclate le champ supannEtuInscription
inscriptions = infos["supannEtuInscription"].values
for insc in inscriptions:
insc = insc.replace("[", "").split("]")
for d in insc:
d = d.split("=")
if d[0] == "cursusann":
cursus_annee = d[1].replace("{SUPANN}", "")
if d[0] == "libDiplome":
diplome_libelle = d[1]
if d[0] == "diplome":
diplome_code = d[1].replace("{SISE}", "")
else:
cursus_annee = ""
diplome_libelle = infos["uppaDrhComposante"] if "uppaDrhComposante" in infos else None
if isinstance(diplome_libelle, list):
diplome_libelle = diplome_libelle[0]
diplome_code = infos["uppaCodeComp"] if "uppaCodeComp" in infos else None
if isinstance(diplome_code, list):
diplome_code = diplome_code[0]
#
# Profil personnel
elif profil in ("PER", "DOC", "VAC", "INV", "APE", "HEB", "ANC", "APH", "CET", "EME", "LEC",
"PVA", "PAD", "PEC", "STA", "ADM", "AP0", "PAR", "PPE", "ADC", "RSS", "AD0"):
#
# Composante
if "supannEntiteAffectationPrincipale" in infos:
composante_code = infos["supannEntiteAffectationPrincipale"].value
if len(infos["uppaCodeComp"]) > 1:
for id, code in enumerate(infos["uppaCodeComp"]):
if code == composante_code:
composante_libelle = infos["uppaDrhComposante"][id]
break
else:
composante_libelle = infos["uppaDrhComposante"].value
else:
composante_code = infos["uppaCodeComp"].value if "uppaCodeComp" in infos else ""
composante_libelle = infos["uppaDrhComposante"].value if "uppaDrhComposante" in infos else ""
#
# Laboratoire
if "uppaDrhLaboratoire" in infos:
laboratoire = infos["uppaDrhLaboratoire"][0].value \
if isinstance(infos["uppaDrhLaboratoire"], list) else infos["uppaDrhLaboratoire"].value
# todo: Par défaut, prend le premier enregistrement
if isinstance(laboratoire, list):
laboratoire = laboratoire[0]
laboratoire_code = querylaboratoire(ldap, laboratoire)
else:
#print("Profil non géré : " + profil)
continue
#
# Insère les données manquants
sql.execute("INSERT INTO profils (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM profils WHERE code = %(code)s) LIMIT 1 ",
params={'code': profil})
if composante_code is not None and composante_code != 0 \
and composante_libelle is not None and composante_libelle != "":
sql.execute("INSERT INTO composantes (code, libelle) "
"SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT code FROM composantes WHERE code = %(code)s) LIMIT 1 ",
{'code': composante_code, 'libelle': composante_libelle})
# todo: Gérer le cas il y a plusieurs diplomes
if diplome_code is not None and diplome_libelle is not None:
sql.execute("REPLACE INTO diplomes (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM diplomes WHERE code = %(code)s) LIMIT 1 ",
{'code': diplome_code, 'libelle': diplome_libelle})
if cursus_annee != "" and cursus_annee is not None:
sql.execute("INSERT INTO cursus (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM cursus WHERE code = %(code)s) LIMIT 1 ",
params={'code': cursus_annee})
if laboratoire != "" and laboratoire is not None:
sql.execute("INSERT INTO laboratoires (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM laboratoires WHERE code = %(code)s "
"or libelle = %(libelle)s) LIMIT 1 ",
params={'code': laboratoire_code, 'libelle': laboratoire})
sql.execute("INSERT IGNORE INTO meta "
"(consultation_id, profil_id, composante_id, laboratoire_id, diplome_id, cursus_id) "
"SELECT %(consultation)s, p.id, co.id, l.id, d.id, c.id "
"FROM profils p "
"LEFT JOIN laboratoires l on l.libelle = %(laboratoire)s "
"LEFT JOIN diplomes d on d.code = %(diplome)s "
"LEFT JOIN cursus c on c.code = %(cursus)s "
"LEFT JOIN composantes co on co.id = %(composante)s "
"WHERE p.code = %(profil)s",
{
'consultation': ec_id,
'profil': profil,
'composante': composante_code,
'laboratoire': laboratoire,
'diplome': diplome_code,
'cursus': cursus_annee
})
connection.commit()
class Command(BaseCommand):
args = '<team_id>'
help = 'Process raw logs from the reverse proxy and import them in database'
def add_arguments(self, parser):
parser.add_argument('--min-date',
help="Everything before this date is ignored (dd/mm/yyyy)",
#default=date.today() - timedelta(1),
required=False)
def handle(self, *args, **options):
# Si aucun argument, on prend depuis la dernière date en base
if not options['min_date']:
#
# Date du dernier fichier traité
query = Connexion.objects.all().aggregate(Max('date'))
mindate = datetime(query['date__max'].year, query['date__max'].month, query['date__max'].day - 1)
else:
try:
mindate = datetime.strptime(options['min_date'], '%d/%m/%Y',)
except ValueError:
raise CommandError('Invalide min-date format !')
# Connexion SQL
sql = connection.cursor()
# Pour chaque fichier de log à traiter
for logfile in sorted(glob.glob(config['logpath'])):
# format du fichier 'ezproxy-YYYY.MM.DD.log'
filename = os.path.split(logfile)[1]
filedate = datetime.strptime(filename, 'ezproxy-%Y.%m.%d.log')
if filedate < mindate:
continue
self.stdout.write("Processing '{}'".format(os.path.basename(logfile)))
#
# Importe les connexions
#
connexions2sql(logfile, sql)
#
# Envoie les données au serveur EZPaarse
#
csvfile = log2csv(logfile)
#
# Envoie les données d'EZPaarse en base sql
#
csv2sql(csvfile, sql)
| 41.905702 | 117 | 0.487676 | import csv
import glob
import os
import pycurl
import re
import ldap3
from datetime import date, timedelta, datetime
from dateutil.parser import parse
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.db.models import Max
from django.utils.text import slugify
from front.models import *
config = {
"ldap": {
"server": "ldap.univ-pau.fr",
"user": "cn=consultplus,ou=admin,dc=univ-pau,dc=fr",
"pwd": "uppaplus",
"base": "ou=people,dc=univ-pau,dc=fr"
},
"ezpaarse": {
"server": "http://ezpaarse.univ-pau.fr",
"options": [
"geoip: none",
"Output-Fields: +datetime",
"Crypted-Fields: none"
],
"debug": "false"
},
"logpath": "/mnt/data/dev/scd/ezreports/proxy_logs/*.log",
"csvpath": "/mnt/data/dev/scd/ezreports/csv/",
}
def querylaboratoire(ldap, name):
name = name.replace("\\", "\\5C")
name = name.replace("*", "\2A")
name = name.replace("(", "\\28")
name = name.replace(")", "\\29")
name = name.replace("\0", "\\00")
if not ldap.search(
'ou=structures,dc=univ-pau,dc=fr',
"(ou=" + name + ")",
attributes=['supannCodeEntite']):
return None
return ldap.entries[0].supannCodeEntite.value
def connexions2sql(filename, sql):
regex = "^(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3}) - " \
"(?P<login>[0-9a-zA-Z]*) .*" \
"\[(?P<datetime>.*)\].*connect\?session=.*&url=" \
"https?://w*\.?(?P<url>.[^/]*)/(?P<path>.*) HTTP/1.1.*"
login = re.compile(regex)
# Ouvre le fichier
with open(filename) as file:
# Pour chaque lignes
for line in file:
# Ca match ?
match = login.match(line)
if not match:
continue
url = match.group("url")
date = datetime.strptime(match.group("datetime"), '%d/%b/%Y:%H:%M:%S %z')
# Insertion du lien si inconnu
sql.execute(
"INSERT INTO liens (url, slug, disabled) "
"SELECT %(url)s, %(slug)s, 0 "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM liens WHERE url = %(url)s or slug=%(slug)s) LIMIT 1 ",
params={'url': url, 'slug': slugify(url)})
# Insertion de l'utilisateur si inconnu
sql.execute(
"INSERT INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s)) LIMIT 1 ",
params={'login': match.group("login")})
sql.execute(
"INSERT INTO connexions "
"SELECT NULL as id, %(date)s as date, %(time)s as time, md5(%(ip)s) as ip, "
"l.id as lien_id, u.id as utilisateur_id "
"FROM utilisateurs u "
"LEFT JOIN liens l on l.url = %(url)s "
"WHERE u.hash = md5(%(login)s) "
"AND NOT EXISTS (SELECT utilisateur_id FROM connexions WHERE "
"utilisateur_id = u.id AND lien_id = l.id AND date = %(date)s "
"AND time = %(time)s AND ip = md5(%(ip)s))",
params={'login': match.group("login"), 'url': url,
'date': date.strftime("%Y-%m-%d"), 'time': date.strftime("%H:%M:%S"),
'ip': match.group("ip")})
connection.commit()
def log2csv(filename):
ez = config['ezpaarse']
now = datetime.now()
print(str(now) + " Log 2 CSV : \"" + filename + "\"...")
path, file = os.path.split(filename)
# Nom du fichier de sortie
outfile = config['csvpath'] + os.path.splitext(file)[0] + '.csv'
return outfile
# On envoie le fichier de log à ezPAARSE
with open(outfile, "wb") as handle:
c = pycurl.Curl()
if ez['debug'] == "true":
c.setopt(c.VERBOSE, 1)
if ez['options'] is not None:
c.setopt(c.HTTPHEADER, ez['options'])
c.setopt(c.URL, ez["server"])
c.setopt(c.HTTPPOST, [(filename, (c.FORM_FILE, filename))])
c.setopt(c.WRITEDATA, handle)
c.perform()
c.close()
return outfile
def csv2sql(filename, sql):
# now = datetime.now()
print(str(datetime.now()) + " CSV 2 SQL : \"" + filename + "\"")
# Ouvre le fichier csv en lecture
with open(filename, 'r') as csvfile:
#
# Connexion à l'annuaire LDAP
server = ldap3.Server(config['ldap']['server'])
ldap = ldap3.Connection(server,
user=config['ldap']['user'],
password=config['ldap']['pwd'],
auto_bind=True)
for row in csv.DictReader(csvfile, delimiter=';'):
csvhash = ""
for k, v in sorted(row.items()):
csvhash += v
dt = parse(row["datetime"])
login = row["login"]
sql.execute("INSERT IGNORE INTO utilisateurs (hash) SELECT md5(%(login)s) "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM utilisateurs WHERE hash = md5(%(login)s))",
params={'login': login})
if row['publisher_name']:
sql.execute("INSERT INTO editeurs (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM editeurs WHERE slug = %(slug)s) LIMIT 1 ",
params={'libelle': row["publisher_name"], 'slug': slugify(row['publisher_name'])})
if row['platform_name']:
sql.execute("INSERT INTO ressources (libelle, slug) SELECT %(libelle)s, %(slug)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM ressources WHERE slug = %(slug)s) LIMIT 1 ",
params={'slug': slugify(row["platform_name"]), 'libelle': row["platform_name"]})
if row['rtype']:
sql.execute("INSERT INTO types (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM types WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["rtype"]})
if row['mime']:
sql.execute("INSERT INTO formats (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM formats WHERE code = %(code)s) LIMIT 1 ",
params={'code': row["mime"]})
sql.execute("INSERT INTO consultations "
"(JOUR, HEURE, UTILISATEUR_ID, RESSOURCE_ID, EDITEUR_ID, TYPE_ID, FORMAT_ID, HOST, HASH) "
"SELECT %(jour)s, %(heure)s, u.id, r.id, e.id, t.id, f.id, %(host)s, sha1(%(hash)s) "
"FROM (SELECT 1) as tmp "
"LEFT JOIN utilisateurs u on u.hash = md5(%(login)s) "
"LEFT JOIN ressources r on r.slug = %(ressource)s "
"LEFT JOIN formats f on f.code = %(format)s "
"LEFT JOIN types t on t.code = %(type)s "
"LEFT JOIN editeurs e on e.slug = %(editeur)s "
"WHERE NOT EXISTS(SELECT id FROM consultations WHERE hash = sha1(%(hash)s)) "
"LIMIT 1 ",
{
'jour': dt.date(),
'heure': dt.time(),
'login': login,
'ressource': slugify(row["platform_name"]),
'editeur': slugify(row["publisher_name"]),
'type': row["rtype"],
'format': row["mime"],
'host': row["host"],
'hash': csvhash,
})
ec_id = sql.lastrowid
if ec_id == 0:
continue
if not ldap.search(
'ou=people,dc=univ-pau,dc=fr',
"(uid=" + login + ")",
attributes=['supannEtuInscription', 'supannEntiteAffectationPrincipale', 'uppaCodeComp',
'uppaDrhComposante', 'uppaProfil', 'uppaDrhLaboratoire']):
print("No ldap informations for \"" + login + "\"")
continue
infos = ldap.entries[0]._attributes
if not infos:
continue
profils = infos["uppaProfil"].values if "uppaProfil" in infos else ["VIDE"]
for profil in profils:
composante_libelle = None
composante_code = None
laboratoire = None
laboratoire_code = None
diplome_libelle = None
diplome_code = None
cursus_annee = None
if profil == "VIDE":
composante_code = infos["uppaCodeComp"]
composante_libelle = infos["uppaDrhComposante"]
#
# Profil étudiant
elif profil in ("ETU", "AE0", "AE1", "AE2", "AET", "AEP"):
if "supannEtuInscription" in infos:
# Eclate le champ supannEtuInscription
inscriptions = infos["supannEtuInscription"].values
for insc in inscriptions:
insc = insc.replace("[", "").split("]")
for d in insc:
d = d.split("=")
if d[0] == "cursusann":
cursus_annee = d[1].replace("{SUPANN}", "")
if d[0] == "libDiplome":
diplome_libelle = d[1]
if d[0] == "diplome":
diplome_code = d[1].replace("{SISE}", "")
else:
cursus_annee = ""
diplome_libelle = infos["uppaDrhComposante"] if "uppaDrhComposante" in infos else None
if isinstance(diplome_libelle, list):
diplome_libelle = diplome_libelle[0]
diplome_code = infos["uppaCodeComp"] if "uppaCodeComp" in infos else None
if isinstance(diplome_code, list):
diplome_code = diplome_code[0]
#
# Profil personnel
elif profil in ("PER", "DOC", "VAC", "INV", "APE", "HEB", "ANC", "APH", "CET", "EME", "LEC",
"PVA", "PAD", "PEC", "STA", "ADM", "AP0", "PAR", "PPE", "ADC", "RSS", "AD0"):
#
# Composante
if "supannEntiteAffectationPrincipale" in infos:
composante_code = infos["supannEntiteAffectationPrincipale"].value
if len(infos["uppaCodeComp"]) > 1:
for id, code in enumerate(infos["uppaCodeComp"]):
if code == composante_code:
composante_libelle = infos["uppaDrhComposante"][id]
break
else:
composante_libelle = infos["uppaDrhComposante"].value
else:
composante_code = infos["uppaCodeComp"].value if "uppaCodeComp" in infos else ""
composante_libelle = infos["uppaDrhComposante"].value if "uppaDrhComposante" in infos else ""
#
# Laboratoire
if "uppaDrhLaboratoire" in infos:
laboratoire = infos["uppaDrhLaboratoire"][0].value \
if isinstance(infos["uppaDrhLaboratoire"], list) else infos["uppaDrhLaboratoire"].value
# todo: Par défaut, prend le premier enregistrement
if isinstance(laboratoire, list):
laboratoire = laboratoire[0]
laboratoire_code = querylaboratoire(ldap, laboratoire)
else:
#print("Profil non géré : " + profil)
continue
#
# Insère les données manquants
sql.execute("INSERT INTO profils (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM profils WHERE code = %(code)s) LIMIT 1 ",
params={'code': profil})
if composante_code is not None and composante_code != 0 \
and composante_libelle is not None and composante_libelle != "":
sql.execute("INSERT INTO composantes (code, libelle) "
"SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT code FROM composantes WHERE code = %(code)s) LIMIT 1 ",
{'code': composante_code, 'libelle': composante_libelle})
# todo: Gérer le cas il y a plusieurs diplomes
if diplome_code is not None and diplome_libelle is not None:
sql.execute("REPLACE INTO diplomes (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM diplomes WHERE code = %(code)s) LIMIT 1 ",
{'code': diplome_code, 'libelle': diplome_libelle})
if cursus_annee != "" and cursus_annee is not None:
sql.execute("INSERT INTO cursus (code) SELECT %(code)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM cursus WHERE code = %(code)s) LIMIT 1 ",
params={'code': cursus_annee})
if laboratoire != "" and laboratoire is not None:
sql.execute("INSERT INTO laboratoires (code, libelle) SELECT %(code)s, %(libelle)s "
"FROM (SELECT 1) as tmp "
"WHERE NOT EXISTS(SELECT id FROM laboratoires WHERE code = %(code)s "
"or libelle = %(libelle)s) LIMIT 1 ",
params={'code': laboratoire_code, 'libelle': laboratoire})
sql.execute("INSERT IGNORE INTO meta "
"(consultation_id, profil_id, composante_id, laboratoire_id, diplome_id, cursus_id) "
"SELECT %(consultation)s, p.id, co.id, l.id, d.id, c.id "
"FROM profils p "
"LEFT JOIN laboratoires l on l.libelle = %(laboratoire)s "
"LEFT JOIN diplomes d on d.code = %(diplome)s "
"LEFT JOIN cursus c on c.code = %(cursus)s "
"LEFT JOIN composantes co on co.id = %(composante)s "
"WHERE p.code = %(profil)s",
{
'consultation': ec_id,
'profil': profil,
'composante': composante_code,
'laboratoire': laboratoire,
'diplome': diplome_code,
'cursus': cursus_annee
})
connection.commit()
class Command(BaseCommand):
args = '<team_id>'
help = 'Process raw logs from the reverse proxy and import them in database'
def add_arguments(self, parser):
parser.add_argument('--min-date',
help="Everything before this date is ignored (dd/mm/yyyy)",
#default=date.today() - timedelta(1),
required=False)
def handle(self, *args, **options):
# Si aucun argument, on prend depuis la dernière date en base
if not options['min_date']:
#
# Date du dernier fichier traité
query = Connexion.objects.all().aggregate(Max('date'))
mindate = datetime(query['date__max'].year, query['date__max'].month, query['date__max'].day - 1)
else:
try:
mindate = datetime.strptime(options['min_date'], '%d/%m/%Y',)
except ValueError:
raise CommandError('Invalide min-date format !')
# Connexion SQL
sql = connection.cursor()
# Pour chaque fichier de log à traiter
for logfile in sorted(glob.glob(config['logpath'])):
# format du fichier 'ezproxy-YYYY.MM.DD.log'
filename = os.path.split(logfile)[1]
filedate = datetime.strptime(filename, 'ezproxy-%Y.%m.%d.log')
if filedate < mindate:
continue
self.stdout.write("Processing '{}'".format(os.path.basename(logfile)))
#
# Importe les connexions
#
connexions2sql(logfile, sql)
#
# Envoie les données au serveur EZPaarse
#
csvfile = log2csv(logfile)
#
# Envoie les données d'EZPaarse en base sql
csv2sql(csvfile, sql)
| true | true |
f72c46cc6e6046ea77fc6de5d29eb113534e9e14 | 9,731 | py | Python | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | tools/rosunit/test/test_junitxml.py | dodsonmg/ros | f1ce3d9d36e8df9dcdca6b37086aabb7f3e202d3 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id: $
import os
import io
import sys
import unittest
import tempfile
import shutil
junitxml = None
## Basic test of xmlresult functionality of reading gtest xml files and
## summarizing their results into a new file.
class MockResult():
def __init__(self, directory, filename, suites = [], noSuitesRoot = False):
self.filename = os.path.join(directory, filename)
self.suites = suites
# whether to suppress <testsuites> root node
self.noSuitesRoot = noSuitesRoot
class MockSuite():
def __init__(self, cases, name, tests = 0, errors = 0, fail = 0, time = 1):
self.cases = cases
self.tests = tests
self.time = time
self.fail = fail
self.errors = errors
self.name = name
class MockCase():
def __init__(self, name, errorList = [], classname="", time = 1):
self.classname = classname
self.name = name
self.time = time
self.errorList = errorList
class MockErrorType(Exception):
def __init__(self, value, etype = ''):
self.value = value
self.__name__ = value
self.type = etype
def _writeMockResultFile(result):
"writes a test result as a gtest compatible test runner would do"
with open(result.filename, 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('<testsuites>\n')
for suite in result.suites:
f.write('<testsuite tests="'+str(suite.tests)+'" failures="'+str(suite.fail)+'" time="'+str(suite.time)+'" errors="'+str(suite.errors)+'" name="'+suite.name+'">\n')
for case in suite.cases:
f.write('<testcase name="'+case.name+'" status="run" time="'+str(case.time)+'" classname="'+case.classname+'">\n')
for error in case.errorList:
f.write('<failure message="'+error.value+'" type="'+error.value+'"/>\n')
f.write('</testcase>\n')
f.write('</testsuite>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('</testsuites>\n')
class XmlResultTestGeneration(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
def tearDown(self):
pass
def testGenerateError(self):
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
self.assertEquals(b'''<error type="error_type"><![CDATA[
error_text
]]></error>''', error_str)
def testGenerateFailure(self):
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
self.assertEquals(b'''<failure type="failure_type"><![CDATA[
failure_text
]]></failure>''', failure_str)
def testGenerateTestCaseResult(self):
testcase = junitxml.TestCaseResult('test_case')
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
testcase.add_error(error)
testcase.add_failure(failure)
testcase_str = testcase.xml()
self.assertEquals(b'''<testcase classname="" name="test_case" time="0.0"><failure type="failure_type"><![CDATA[
failure_text
]]></failure><error type="error_type"><![CDATA[
error_text
]]></error></testcase>''', testcase_str)
class XmlResultTestRead(unittest.TestCase):
def setUp(self):
# lazy-import to get coverage
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
self.directory = tempfile.mkdtemp()
# setting up mock results as dict so results can be checked individually
self.mockresults={
"empty": MockResult(self.directory, "empty.xml", []),
"emptysuite": MockResult(self.directory, "emptysuite.xml", [MockSuite([], "emptySuite", 0, 0, 0, 0)]),
"succ1": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)]),
"err1": MockResult(self.directory, "err1.xml", [MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1)]),
"fail1": MockResult(self.directory, "fail1.xml", [MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]),
"noroot": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)], noSuitesRoot = True),
"multicase": MockResult(self.directory,
"multicase.xml",
[MockSuite([MockCase("succCase"),
MockCase("errCase"),
MockCase("failCase")],
"succ1suite", 3, 1, 1, time = 3)]),
"multisuite": MockResult(self.directory,
"multisuite.xml",
[MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1),
MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1),
MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)])
}
for name, result in self.mockresults.items():
_writeMockResultFile(result)
def tearDown(self):
shutil.rmtree(self.directory)
#pass
def testReadNoSuites(self):
result = junitxml.read(self.mockresults["empty"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadEmptySuite(self):
result = junitxml.read(self.mockresults["emptysuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadSuccess(self):
result = junitxml.read(self.mockresults["succ1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadError(self):
result = junitxml.read(self.mockresults["err1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadFail(self):
result = junitxml.read(self.mockresults["fail1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMulticase(self):
result = junitxml.read(self.mockresults["multicase"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMultisuite(self):
result = junitxml.read(self.mockresults["multisuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
| 42.679825 | 176 | 0.631795 |
import os
import io
import sys
import unittest
import tempfile
import shutil
junitxml = None
.filename = os.path.join(directory, filename)
self.suites = suites
self.noSuitesRoot = noSuitesRoot
class MockSuite():
def __init__(self, cases, name, tests = 0, errors = 0, fail = 0, time = 1):
self.cases = cases
self.tests = tests
self.time = time
self.fail = fail
self.errors = errors
self.name = name
class MockCase():
def __init__(self, name, errorList = [], classname="", time = 1):
self.classname = classname
self.name = name
self.time = time
self.errorList = errorList
class MockErrorType(Exception):
def __init__(self, value, etype = ''):
self.value = value
self.__name__ = value
self.type = etype
def _writeMockResultFile(result):
with open(result.filename, 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('<testsuites>\n')
for suite in result.suites:
f.write('<testsuite tests="'+str(suite.tests)+'" failures="'+str(suite.fail)+'" time="'+str(suite.time)+'" errors="'+str(suite.errors)+'" name="'+suite.name+'">\n')
for case in suite.cases:
f.write('<testcase name="'+case.name+'" status="run" time="'+str(case.time)+'" classname="'+case.classname+'">\n')
for error in case.errorList:
f.write('<failure message="'+error.value+'" type="'+error.value+'"/>\n')
f.write('</testcase>\n')
f.write('</testsuite>\n')
if len(result.suites) > 1 or result.noSuitesRoot == False:
f.write('</testsuites>\n')
class XmlResultTestGeneration(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
def tearDown(self):
pass
def testGenerateError(self):
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
self.assertEquals(b'''<error type="error_type"><![CDATA[
error_text
]]></error>''', error_str)
def testGenerateFailure(self):
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
self.assertEquals(b'''<failure type="failure_type"><![CDATA[
failure_text
]]></failure>''', failure_str)
def testGenerateTestCaseResult(self):
testcase = junitxml.TestCaseResult('test_case')
error = junitxml.TestError('error_type', 'error_text')
error_str = error.xml()
failure = junitxml.TestFailure('failure_type', 'failure_text')
failure_str = failure.xml()
testcase.add_error(error)
testcase.add_failure(failure)
testcase_str = testcase.xml()
self.assertEquals(b'''<testcase classname="" name="test_case" time="0.0"><failure type="failure_type"><![CDATA[
failure_text
]]></failure><error type="error_type"><![CDATA[
error_text
]]></error></testcase>''', testcase_str)
class XmlResultTestRead(unittest.TestCase):
def setUp(self):
global junitxml
if junitxml is None:
import rosunit.junitxml
junitxml = rosunit.junitxml
self.directory = tempfile.mkdtemp()
self.mockresults={
"empty": MockResult(self.directory, "empty.xml", []),
"emptysuite": MockResult(self.directory, "emptysuite.xml", [MockSuite([], "emptySuite", 0, 0, 0, 0)]),
"succ1": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)]),
"err1": MockResult(self.directory, "err1.xml", [MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1)]),
"fail1": MockResult(self.directory, "fail1.xml", [MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]),
"noroot": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)], noSuitesRoot = True),
"multicase": MockResult(self.directory,
"multicase.xml",
[MockSuite([MockCase("succCase"),
MockCase("errCase"),
MockCase("failCase")],
"succ1suite", 3, 1, 1, time = 3)]),
"multisuite": MockResult(self.directory,
"multisuite.xml",
[MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1),
MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1),
MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)])
}
for name, result in self.mockresults.items():
_writeMockResultFile(result)
def tearDown(self):
shutil.rmtree(self.directory)
def testReadNoSuites(self):
result = junitxml.read(self.mockresults["empty"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadEmptySuite(self):
result = junitxml.read(self.mockresults["emptysuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(0.0, result.time)
self.assertEquals(0, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadSuccess(self):
result = junitxml.read(self.mockresults["succ1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadError(self):
result = junitxml.read(self.mockresults["err1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(0, result.num_failures)
def testReadFail(self):
result = junitxml.read(self.mockresults["fail1"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(1.0, result.time)
self.assertEquals(1, result.num_tests)
self.assertEquals(0, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMulticase(self):
result = junitxml.read(self.mockresults["multicase"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
def testReadMultisuite(self):
result = junitxml.read(self.mockresults["multisuite"].filename, "fooname")
self.assert_(result is not None)
self.assertEquals(3.0, result.time)
self.assertEquals(3, result.num_tests)
self.assertEquals(1, result.num_errors)
self.assertEquals(1, result.num_failures)
| true | true |
f72c48af45b656ece0447e4d40290a0102816591 | 20,906 | py | Python | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | odoo/base-addons/sale/tests/test_sale_product_attribute_value_config.py | LucasBorges-Santos/docker-odoo | 53987bbd61f6119669b5f801ee2ad54695084a21 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields
from odoo.addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged
class TestSaleProductAttributeValueSetup(TestProductAttributeValueSetup):
def _setup_currency(self, currency_ratio=2):
"""Get or create a currency. This makes the test non-reliant on demo.
With an easy currency rate, for a simple 2 ratio in the following tests.
"""
from_currency = self.computer.currency_id
self._set_or_create_rate_today(from_currency, rate=1)
to_currency = self._get_or_create_currency("my currency", "C")
self._set_or_create_rate_today(to_currency, currency_ratio)
return to_currency
def _set_or_create_rate_today(self, currency, rate):
"""Get or create a currency rate for today. This makes the test
non-reliant on demo data."""
name = fields.Date.today()
currency_id = currency.id
company_id = self.env.company.id
CurrencyRate = self.env['res.currency.rate']
currency_rate = CurrencyRate.search([
('company_id', '=', company_id),
('currency_id', '=', currency_id),
('name', '=', name),
])
if currency_rate:
currency_rate.rate = rate
else:
CurrencyRate.create({
'company_id': company_id,
'currency_id': currency_id,
'name': name,
'rate': rate,
})
def _get_or_create_currency(self, name, symbol):
"""Get or create a currency based on name. This makes the test
non-reliant on demo data."""
currency = self.env['res.currency'].search([('name', '=', name)])
return currency or currency.create({
'name': name,
'symbol': symbol,
})
@tagged('post_install', '-at_install')
class TestSaleProductAttributeValueConfig(TestSaleProductAttributeValueSetup):
def _setup_pricelist(self, currency_ratio=2):
to_currency = self._setup_currency(currency_ratio)
discount = 10
pricelist = self.env['product.pricelist'].create({
'name': 'test pl',
'currency_id': to_currency.id,
'company_id': self.computer.company_id.id,
})
pricelist_item = self.env['product.pricelist.item'].create({
'min_quantity': 2,
'compute_price': 'percentage',
'percent_price': discount,
'pricelist_id': pricelist.id,
})
return (pricelist, pricelist_item, currency_ratio, 1 - discount / 100)
def test_01_is_combination_possible_archived(self):
"""The goal is to test the possibility of archived combinations.
This test could not be put into product module because there was no
model which had product_id as required and without cascade on delete.
Here we have the sales order line in this situation.
This is a necessary condition for `_create_variant_ids` to archive
instead of delete the variants.
"""
def do_test(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant2 = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertTrue(variant)
self.assertTrue(variant2)
# Create a dummy SO to prevent the variant from being deleted by
# _create_variant_ids() because the variant is a related field that
# is required on the SO line
so = self.env['sale.order'].create({'partner_id': 1})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant.id
})
# additional variant to test correct ignoring when mismatch values
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant2.id
})
variant2.active = False
# CASE: 1 not archived, 2 archived
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
# CASE: both archived combination (without no_variant)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: OK after attribute line removed
self.computer_hdd_attribute_lines.unlink()
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8))
# CASE: not archived (with no_variant)
self.hdd_attribute.create_variant = 'no_variant'
self._add_hdd_attribute_line()
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination found (with no_variant)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (including no_variant)
self.computer_ssd_attribute_lines.unlink()
variant4 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant4.id
})
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
# CASE: archived combination has different attributes (without no_variant)
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'always'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant5 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant5.id
})
self.assertTrue(variant4 != variant5)
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
computer_ssd_256_before = self._get_product_template_attribute_value(self.ssd_256)
do_test(self)
# CASE: add back the removed attribute and try everything again
self.computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.ssd_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id, self.ssd_512.id])],
})
computer_ssd_256_after = self._get_product_template_attribute_value(self.ssd_256)
self.assertEqual(computer_ssd_256_after, computer_ssd_256_before)
self.assertEqual(computer_ssd_256_after.attribute_line_id, computer_ssd_256_before.attribute_line_id)
do_test(self)
def test_02_get_combination_info(self):
# If using multi-company, company_id will be False, and this code should
# still work.
# The case with a company_id will be implicitly tested on website_sale.
self.computer.company_id = False
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
# CASE: no pricelist, no currency, with existing combination, with price_extra on attributes
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant = self.computer._get_variant_for_combination(combination)
res = self.computer._get_combination_info(combination)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: no combination, product given
res = self.computer._get_combination_info(self.env['product.template.attribute.value'], computer_variant.id)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
# CASE: using pricelist, quantity rule
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: no_variant combination, it's another variant now
self.computer_ssd_attribute_lines.unlink()
self.ssd_attribute.create_variant = 'no_variant'
self._add_ssd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._get_variant_for_combination(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, but the variant already exists
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._create_product_variant(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, no variant existing
# Test invalidate_cache on product.template _create_variant_ids
self._add_keyboard_attribute()
combination += self._get_product_template_attribute_value(self.keyboard_excluded)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], (2222 - 5) * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
# CASE: pricelist set value to 0, no variant
# Test invalidate_cache on product.pricelist write
pricelist_item.percent_price = 100
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], 0)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
def test_03_get_combination_info_discount_policy(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
pricelist.discount_policy = 'with_discount'
# CASE: no discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: no discount, setting without_discount
pricelist.discount_policy = 'without_discount'
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting without_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], True)
def test_04_create_product_variant_non_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
not create variant if the type is not dynamic. It can however return a
variant if it already exists."""
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant is already created, it should return it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant1 = self.computer._get_variant_for_combination(combination)
self.assertEqual(self.computer._create_product_variant(combination), variant1)
# CASE: variant does not exist, but template is non-dynamic, so it
# should not create it
Product = self.env['product.product']
variant1.unlink()
self.assertEqual(self.computer._create_product_variant(combination), Product)
def test_05_create_product_variant_dynamic(self):
"""The goal of this test is to make sure the create_product_variant does
work with dynamic. If the combination is possible, it should create it.
If it's not possible, it should not create it."""
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant does not exist, but combination is not possible
# so it should not create it
impossible_combination = computer_ssd_256 + computer_ram_16 + computer_hdd_1
Product = self.env['product.product']
self.assertEqual(self.computer._create_product_variant(impossible_combination), Product)
# CASE: the variant does not exist, and the combination is possible, so
# it should create it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant = self.computer._create_product_variant(combination)
self.assertTrue(variant)
# CASE: the variant already exists, so it should return it
self.assertEqual(variant, self.computer._create_product_variant(combination))
def _add_keyboard_attribute(self):
self.keyboard_attribute = self.env['product.attribute'].create({
'name': 'Keyboard',
'sequence': 6,
'create_variant': 'dynamic',
})
self.keyboard_included = self.env['product.attribute.value'].create({
'name': 'Included',
'attribute_id': self.keyboard_attribute.id,
'sequence': 1,
})
self.keyboard_excluded = self.env['product.attribute.value'].create({
'name': 'Excluded',
'attribute_id': self.keyboard_attribute.id,
'sequence': 2,
})
self.computer_keyboard_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.keyboard_attribute.id,
'value_ids': [(6, 0, [self.keyboard_included.id, self.keyboard_excluded.id])],
})
self.computer_keyboard_attribute_lines.product_template_value_ids[0].price_extra = 5
self.computer_keyboard_attribute_lines.product_template_value_ids[1].price_extra = -5
| 51.114914 | 120 | 0.69162 |
from odoo import fields
from odoo.addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged
class TestSaleProductAttributeValueSetup(TestProductAttributeValueSetup):
def _setup_currency(self, currency_ratio=2):
from_currency = self.computer.currency_id
self._set_or_create_rate_today(from_currency, rate=1)
to_currency = self._get_or_create_currency("my currency", "C")
self._set_or_create_rate_today(to_currency, currency_ratio)
return to_currency
def _set_or_create_rate_today(self, currency, rate):
name = fields.Date.today()
currency_id = currency.id
company_id = self.env.company.id
CurrencyRate = self.env['res.currency.rate']
currency_rate = CurrencyRate.search([
('company_id', '=', company_id),
('currency_id', '=', currency_id),
('name', '=', name),
])
if currency_rate:
currency_rate.rate = rate
else:
CurrencyRate.create({
'company_id': company_id,
'currency_id': currency_id,
'name': name,
'rate': rate,
})
def _get_or_create_currency(self, name, symbol):
currency = self.env['res.currency'].search([('name', '=', name)])
return currency or currency.create({
'name': name,
'symbol': symbol,
})
@tagged('post_install', '-at_install')
class TestSaleProductAttributeValueConfig(TestSaleProductAttributeValueSetup):
def _setup_pricelist(self, currency_ratio=2):
to_currency = self._setup_currency(currency_ratio)
discount = 10
pricelist = self.env['product.pricelist'].create({
'name': 'test pl',
'currency_id': to_currency.id,
'company_id': self.computer.company_id.id,
})
pricelist_item = self.env['product.pricelist.item'].create({
'min_quantity': 2,
'compute_price': 'percentage',
'percent_price': discount,
'pricelist_id': pricelist.id,
})
return (pricelist, pricelist_item, currency_ratio, 1 - discount / 100)
def test_01_is_combination_possible_archived(self):
def do_test(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant2 = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_2)
self.assertTrue(variant)
self.assertTrue(variant2)
so = self.env['sale.order'].create({'partner_id': 1})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant.id
})
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant2.id
})
variant2.active = False
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_2))
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.computer_hdd_attribute_lines.unlink()
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8))
self.hdd_attribute.create_variant = 'no_variant'
self._add_hdd_attribute_line()
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
self.assertTrue(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
variant = self.computer._get_variant_for_combination(computer_ssd_256 + computer_ram_8 + computer_hdd_1)
variant.active = False
self.assertFalse(self.computer._is_combination_possible(computer_ssd_256 + computer_ram_8 + computer_hdd_1))
self.computer_ssd_attribute_lines.unlink()
variant4 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant4.id
})
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'always'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
computer_hdd_2 = self._get_product_template_attribute_value(self.hdd_2)
variant5 = self.computer._get_variant_for_combination(computer_ram_8 + computer_hdd_1)
self.env['sale.order.line'].create({
'order_id': so.id,
'name': "test",
'product_id': variant5.id
})
self.assertTrue(variant4 != variant5)
self.assertTrue(self.computer._is_combination_possible(computer_ram_8 + computer_hdd_1))
computer_ssd_256_before = self._get_product_template_attribute_value(self.ssd_256)
do_test(self)
self.computer_ssd_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.ssd_attribute.id,
'value_ids': [(6, 0, [self.ssd_256.id, self.ssd_512.id])],
})
computer_ssd_256_after = self._get_product_template_attribute_value(self.ssd_256)
self.assertEqual(computer_ssd_256_after, computer_ssd_256_before)
self.assertEqual(computer_ssd_256_after.attribute_line_id, computer_ssd_256_before.attribute_line_id)
do_test(self)
def test_02_get_combination_info(self):
self.computer.company_id = False
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant = self.computer._get_variant_for_combination(combination)
res = self.computer._get_combination_info(combination)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
res = self.computer._get_combination_info(self.env['product.template.attribute.value'], computer_variant.id)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222)
self.assertEqual(res['list_price'], 2222)
self.assertEqual(res['price_extra'], 222)
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant.id)
self.assertEqual(res['display_name'], "Super Computer (256 GB, 8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.computer_ssd_attribute_lines.unlink()
self.ssd_attribute.create_variant = 'no_variant'
self._add_ssd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._get_variant_for_combination(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, but the variant already exists
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
computer_variant_new = self.computer._create_product_variant(combination)
self.assertTrue(computer_variant_new)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], computer_variant_new.id)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To)")
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
# CASE: dynamic combination, no variant existing
# Test invalidate_cache on product.template _create_variant_ids
self._add_keyboard_attribute()
combination += self._get_product_template_attribute_value(self.keyboard_excluded)
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], (2222 - 5) * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
# CASE: pricelist set value to 0, no variant
# Test invalidate_cache on product.pricelist write
pricelist_item.percent_price = 100
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['product_template_id'], self.computer.id)
self.assertEqual(res['product_id'], False)
self.assertEqual(res['display_name'], "Super Computer (8 GB, 1 To, Excluded)")
self.assertEqual(res['price'], 0)
self.assertEqual(res['list_price'], (2222 - 5) * currency_ratio)
self.assertEqual(res['price_extra'], (222 - 5) * currency_ratio)
def test_03_get_combination_info_discount_policy(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
pricelist, pricelist_item, currency_ratio, discount_ratio = self._setup_pricelist()
pricelist.discount_policy = 'with_discount'
# CASE: no discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting with_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: no discount, setting without_discount
pricelist.discount_policy = 'without_discount'
res = self.computer._get_combination_info(combination, add_qty=1, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], False)
# CASE: discount, setting without_discount
res = self.computer._get_combination_info(combination, add_qty=2, pricelist=pricelist)
self.assertEqual(res['price'], 2222 * currency_ratio * discount_ratio)
self.assertEqual(res['list_price'], 2222 * currency_ratio)
self.assertEqual(res['price_extra'], 222 * currency_ratio)
self.assertEqual(res['has_discounted_price'], True)
def test_04_create_product_variant_non_dynamic(self):
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant is already created, it should return it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant1 = self.computer._get_variant_for_combination(combination)
self.assertEqual(self.computer._create_product_variant(combination), variant1)
# CASE: variant does not exist, but template is non-dynamic, so it
# should not create it
Product = self.env['product.product']
variant1.unlink()
self.assertEqual(self.computer._create_product_variant(combination), Product)
def test_05_create_product_variant_dynamic(self):
self.computer_hdd_attribute_lines.unlink()
self.hdd_attribute.create_variant = 'dynamic'
self._add_hdd_attribute_line()
computer_ssd_256 = self._get_product_template_attribute_value(self.ssd_256)
computer_ram_8 = self._get_product_template_attribute_value(self.ram_8)
computer_ram_16 = self._get_product_template_attribute_value(self.ram_16)
computer_hdd_1 = self._get_product_template_attribute_value(self.hdd_1)
self._add_exclude(computer_ram_16, computer_hdd_1)
# CASE: variant does not exist, but combination is not possible
# so it should not create it
impossible_combination = computer_ssd_256 + computer_ram_16 + computer_hdd_1
Product = self.env['product.product']
self.assertEqual(self.computer._create_product_variant(impossible_combination), Product)
# CASE: the variant does not exist, and the combination is possible, so
# it should create it
combination = computer_ssd_256 + computer_ram_8 + computer_hdd_1
variant = self.computer._create_product_variant(combination)
self.assertTrue(variant)
# CASE: the variant already exists, so it should return it
self.assertEqual(variant, self.computer._create_product_variant(combination))
def _add_keyboard_attribute(self):
self.keyboard_attribute = self.env['product.attribute'].create({
'name': 'Keyboard',
'sequence': 6,
'create_variant': 'dynamic',
})
self.keyboard_included = self.env['product.attribute.value'].create({
'name': 'Included',
'attribute_id': self.keyboard_attribute.id,
'sequence': 1,
})
self.keyboard_excluded = self.env['product.attribute.value'].create({
'name': 'Excluded',
'attribute_id': self.keyboard_attribute.id,
'sequence': 2,
})
self.computer_keyboard_attribute_lines = self.env['product.template.attribute.line'].create({
'product_tmpl_id': self.computer.id,
'attribute_id': self.keyboard_attribute.id,
'value_ids': [(6, 0, [self.keyboard_included.id, self.keyboard_excluded.id])],
})
self.computer_keyboard_attribute_lines.product_template_value_ids[0].price_extra = 5
self.computer_keyboard_attribute_lines.product_template_value_ids[1].price_extra = -5
| true | true |
f72c490d26e31fc870e558ebe85f5de8ccd13aa9 | 4,921 | py | Python | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 2 | 2021-03-01T10:27:41.000Z | 2021-11-04T21:27:12.000Z | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 1 | 2022-03-07T09:09:21.000Z | 2022-03-07T09:09:21.000Z | src/btfs/firebase_dc.py | mikespub-org/mar10-clouddav | dabfe2832438667ca5ff960e9273fceae9280f15 | [
"MIT"
] | 1 | 2020-10-17T07:35:37.000Z | 2020-10-17T07:35:37.000Z | # (c) 2009-2019 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Implementation of a domain controller that allows users to authenticate via the
Google Identity Platform - based on Firebase Authentication.
Used by HTTPAuthenticator. Only for web-based access or behind an identity-aware proxy.
See https://wsgidav.readthedocs.io/en/latest/user_guide_configure.html
"""
from wsgidav import util
from wsgidav.dc.base_dc import BaseDomainController
from .sessions import get_current_session
__docformat__ = "reStructuredText"
_logger = util.get_module_logger(__name__)
class FirebaseDomainController(BaseDomainController):
known_roles = ("admin", "editor", "reader", "browser", "none")
def __init__(self, wsgidav_app, config):
super().__init__(wsgidav_app, config)
# auth_conf = config["http_authenticator"]
dc_conf = config.get("firebase_dc", {})
self.project_id = dc_conf.get("project_id", None)
self.api_key = dc_conf.get("api_key", None)
self.id_token = dc_conf.get("id_token", "id_token")
self.user_role = dc_conf.get("user_role", "reader")
self.anon_role = dc_conf.get("anon_role", "browser")
def __str__(self):
return f"{self.__class__.__name__}('{self.project_id}')"
def get_domain_realm(self, path_info, environ):
return f"Firebase({self.project_id})"
def require_authentication(self, realm, environ):
# TODO: check id_token or trusted_auth_header
# environ["wsgidav.auth.user_name"] = ""
# The domain controller MAY set those values depending on user's
# authorization:
# environ["wsgidav.auth.roles"] = None
# environ["wsgidav.auth.permissions"] = None
# "wsgidav.auth.realm": "Firebase(...)"
if not environ:
return True
_logger.debug("Realm: %s" % realm)
# "wsgidav.auth.user_name": "",
if environ.get("wsgidav.auth.user_name"):
_logger.debug("User: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "wsgidav.config": {...}
config = environ.get("wsgidav.config", {})
auth_conf = config.get("http_authenticator", {})
trusted_auth_header = auth_conf.get("trusted_auth_header", None)
if trusted_auth_header and environ.get(trusted_auth_header):
environ["wsgidav.auth.user_name"] = environ.get(trusted_auth_header)
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.user_role]
_logger.debug("Trusted: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "HTTP_COOKIE": "..."
session = get_current_session(environ)
if session.is_user():
environ["wsgidav.auth.user_name"] = session.user_id
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = []
for role in session.get_roles():
if (
role in self.known_roles
and role not in environ["wsgidav.auth.roles"]
):
environ["wsgidav.auth.roles"].append(role)
if len(environ["wsgidav.auth.roles"]) < 1:
environ["wsgidav.auth.roles"].append(self.user_role)
return False
# "wsgidav.auth.roles": null
# "wsgidav.auth.permissions": null
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.anon_role]
if self.anon_role in ("browser", "reader", "editor"):
return False
# "HTTP_USER_AGENT": "Microsoft-WebDAV-MiniRedir/10.0.17134"
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: tell users to login via browser at /auth/token first, and then use persistent cookie
# or basic auth with e-mail & access token here?
return True
return True
def basic_auth_user(self, realm, user_name, password, environ):
if environ and environ.get("wsgidav.auth.user_name"):
return True
# We don't have access to a plaintext password (or stored hash)
_logger.debug("Realm: %s" % realm)
_logger.debug("User: %s" % user_name)
# _logger.debug("Pass: %s" % password)
# import json
# _logger.debug("Environ: %s" % json.dumps(environ, indent=2, default=lambda o: repr(o)))
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: verify persistent cookie or use basic auth with e-mail & access token?
return True
return False
def supports_http_digest_auth(self):
# We don't have access to a plaintext password (or stored hash)
return False
| 44.333333 | 104 | 0.633611 |
from wsgidav import util
from wsgidav.dc.base_dc import BaseDomainController
from .sessions import get_current_session
__docformat__ = "reStructuredText"
_logger = util.get_module_logger(__name__)
class FirebaseDomainController(BaseDomainController):
known_roles = ("admin", "editor", "reader", "browser", "none")
def __init__(self, wsgidav_app, config):
super().__init__(wsgidav_app, config)
dc_conf = config.get("firebase_dc", {})
self.project_id = dc_conf.get("project_id", None)
self.api_key = dc_conf.get("api_key", None)
self.id_token = dc_conf.get("id_token", "id_token")
self.user_role = dc_conf.get("user_role", "reader")
self.anon_role = dc_conf.get("anon_role", "browser")
def __str__(self):
return f"{self.__class__.__name__}('{self.project_id}')"
def get_domain_realm(self, path_info, environ):
return f"Firebase({self.project_id})"
def require_authentication(self, realm, environ):
# authorization:
# environ["wsgidav.auth.roles"] = None
# environ["wsgidav.auth.permissions"] = None
# "wsgidav.auth.realm": "Firebase(...)"
if not environ:
return True
_logger.debug("Realm: %s" % realm)
# "wsgidav.auth.user_name": "",
if environ.get("wsgidav.auth.user_name"):
_logger.debug("User: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "wsgidav.config": {...}
config = environ.get("wsgidav.config", {})
auth_conf = config.get("http_authenticator", {})
trusted_auth_header = auth_conf.get("trusted_auth_header", None)
if trusted_auth_header and environ.get(trusted_auth_header):
environ["wsgidav.auth.user_name"] = environ.get(trusted_auth_header)
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.user_role]
_logger.debug("Trusted: %s" % environ.get("wsgidav.auth.user_name"))
return False
# "HTTP_COOKIE": "..."
session = get_current_session(environ)
if session.is_user():
environ["wsgidav.auth.user_name"] = session.user_id
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = []
for role in session.get_roles():
if (
role in self.known_roles
and role not in environ["wsgidav.auth.roles"]
):
environ["wsgidav.auth.roles"].append(role)
if len(environ["wsgidav.auth.roles"]) < 1:
environ["wsgidav.auth.roles"].append(self.user_role)
return False
# "wsgidav.auth.roles": null
# "wsgidav.auth.permissions": null
if not environ.get("wsgidav.auth.roles"):
environ["wsgidav.auth.roles"] = [self.anon_role]
if self.anon_role in ("browser", "reader", "editor"):
return False
# "HTTP_USER_AGENT": "Microsoft-WebDAV-MiniRedir/10.0.17134"
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
# TODO: tell users to login via browser at /auth/token first, and then use persistent cookie
# or basic auth with e-mail & access token here?
return True
return True
def basic_auth_user(self, realm, user_name, password, environ):
if environ and environ.get("wsgidav.auth.user_name"):
return True
# We don't have access to a plaintext password (or stored hash)
_logger.debug("Realm: %s" % realm)
_logger.debug("User: %s" % user_name)
if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""):
return True
return False
def supports_http_digest_auth(self):
return False
| true | true |
f72c4c832d99aaf2b05ca354a98a00fc55c755f2 | 1,232 | py | Python | paper_simulation_scripts/run_one_job.py | bsierieb1/SCDCdm_public | 4cd3460a598fad01cb556dc1fb86f63d805ee052 | [
"BSD-3-Clause"
] | 1 | 2021-03-31T10:44:48.000Z | 2021-03-31T10:44:48.000Z | paper_simulation_scripts/run_one_job.py | neurogenomics/scCODA | db610c1bda904f79a8142da767cf8e62d1cd8d32 | [
"BSD-3-Clause"
] | null | null | null | paper_simulation_scripts/run_one_job.py | neurogenomics/scCODA | db610c1bda904f79a8142da767cf8e62d1cd8d32 | [
"BSD-3-Clause"
] | null | null | null | """
This script is executed in each job on the server to run simulation studies on all the parameters that are passed to it
"""
import sys
import ast
import numpy as np
from scdcdm.util import multi_parameter_sampling as mult
# Convert string parameters to lists
cases = ast.literal_eval(sys.argv[1])
print("cases:", cases)
K = ast.literal_eval(sys.argv[2])
print("K:", K)
n_total = ast.literal_eval(sys.argv[3])
print("n_total:", n_total)
n_samples = ast.literal_eval(sys.argv[4])
print("n_samples:", n_samples)
print(sys.argv[5])
b_true = ast.literal_eval(sys.argv[5])
print("b_true:", b_true)
w_true = ast.literal_eval(sys.argv[6])
print("w_true:", w_true)
num_results = ast.literal_eval(sys.argv[7])
print("num_results:", num_results)
n = ast.literal_eval(sys.argv[8])
print("n:", n)
# Run simulation study
p = mult.MultiParamSimulation(cases, K, n_total, n_samples, b_true, w_true, num_results,
baseline_index=4, formula="x_0")
p.simulate()
p.save(path="/home/icb/johannes.ostner/compositional_diff/compositionalDiff-johannes_tests_2/benchmark_results/overall_benchmark/",
filename="result_b_" + str(np.round(b_true, 3)).replace(" ", " ") + "_w_" + str(w_true) + "_round_" + str(n))
| 32.421053 | 131 | 0.719156 | import sys
import ast
import numpy as np
from scdcdm.util import multi_parameter_sampling as mult
cases = ast.literal_eval(sys.argv[1])
print("cases:", cases)
K = ast.literal_eval(sys.argv[2])
print("K:", K)
n_total = ast.literal_eval(sys.argv[3])
print("n_total:", n_total)
n_samples = ast.literal_eval(sys.argv[4])
print("n_samples:", n_samples)
print(sys.argv[5])
b_true = ast.literal_eval(sys.argv[5])
print("b_true:", b_true)
w_true = ast.literal_eval(sys.argv[6])
print("w_true:", w_true)
num_results = ast.literal_eval(sys.argv[7])
print("num_results:", num_results)
n = ast.literal_eval(sys.argv[8])
print("n:", n)
p = mult.MultiParamSimulation(cases, K, n_total, n_samples, b_true, w_true, num_results,
baseline_index=4, formula="x_0")
p.simulate()
p.save(path="/home/icb/johannes.ostner/compositional_diff/compositionalDiff-johannes_tests_2/benchmark_results/overall_benchmark/",
filename="result_b_" + str(np.round(b_true, 3)).replace(" ", " ") + "_w_" + str(w_true) + "_round_" + str(n))
| true | true |
f72c4d210b5eea32e3d333a149d7cfd14424c8d5 | 14,927 | py | Python | uf/application/uda.py | yupeijei1997/unif | 16685a89446e6ce14080439162a9bfd0c75f0521 | [
"Apache-2.0"
] | 1 | 2021-05-15T12:07:40.000Z | 2021-05-15T12:07:40.000Z | uf/application/uda.py | yupeijei1997/unif | 16685a89446e6ce14080439162a9bfd0c75f0521 | [
"Apache-2.0"
] | null | null | null | uf/application/uda.py | yupeijei1997/unif | 16685a89446e6ce14080439162a9bfd0c75f0521 | [
"Apache-2.0"
] | null | null | null | # coding:=utf-8
# Copyright 2021 Tencent. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
''' Applications based on UDA. '''
import numpy as np
from uf.tools import tf
from .base import ClassifierModule
from .bert import BERTClassifier, get_bert_config, get_key_to_depths
from uf.modeling.bert import BERTEncoder
from uf.modeling.uda import UDADecoder
from uf.tokenization.word_piece import get_word_piece_tokenizer
import uf.utils as utils
import uf.modeling.util as util
class UDAClassifier(BERTClassifier, ClassifierModule):
''' Single-label classifier on UDA. '''
_INFER_ATTRIBUTES = BERTClassifier._INFER_ATTRIBUTES
def __init__(self,
config_file,
vocab_file,
max_seq_length=128,
label_size=None,
init_checkpoint=None,
output_dir=None,
gpu_ids=None,
drop_pooler=False,
uda_softmax_temp=-1,
uda_confidence_thresh=-1,
tsa_schedule='linear',
do_lower_case=True,
truncate_method='LIFO'):
super(ClassifierModule, self).__init__(
init_checkpoint, output_dir, gpu_ids)
self.batch_size = 0
self.max_seq_length = max_seq_length
self.label_size = label_size
self.truncate_method = truncate_method
self._drop_pooler = drop_pooler
self._uda_softmax_temp = uda_softmax_temp
self._uda_confidence_thresh = uda_confidence_thresh
self._tsa_schedule = tsa_schedule
self._id_to_label = None
self.__init_args__ = locals()
self.bert_config = get_bert_config(config_file)
self.tokenizer = get_word_piece_tokenizer(vocab_file, do_lower_case)
self._key_to_depths = get_key_to_depths(
self.bert_config.num_hidden_layers)
if '[CLS]' not in self.tokenizer.vocab:
self.tokenizer.add('[CLS]')
self.bert_config.vocab_size += 1
tf.logging.info('Add necessary token `[CLS]` into vocabulary.')
if '[SEP]' not in self.tokenizer.vocab:
self.tokenizer.add('[SEP]')
self.bert_config.vocab_size += 1
tf.logging.info('Add necessary token `[SEP]` into vocabulary.')
def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None,
is_training=False):
self._assert_legal(X, y, sample_weight, X_tokenized)
# simplified when not training
if not is_training:
return super().convert(
X, y, sample_weight, X_tokenized, is_training)
if is_training:
assert y is not None, '`y` can\'t be None.'
n_inputs = None
data = {}
# convert X
if X or X_tokenized:
tokenized = False if X else X_tokenized
(input_ids, input_mask, segment_ids,
aug_input_ids, aug_input_mask, aug_segment_ids,
is_supervised) = self._convert_X_reimp(
X_tokenized if tokenized else X, y, tokenized=tokenized)
data['input_ids'] = np.array(input_ids, dtype=np.int32)
data['input_mask'] = np.array(input_mask, dtype=np.int32)
data['segment_ids'] = np.array(segment_ids, dtype=np.int32)
data['aug_input_ids'] = np.array(aug_input_ids, dtype=np.int32)
data['aug_input_mask'] = np.array(aug_input_mask, dtype=np.int32)
data['aug_segment_ids'] = np.array(aug_segment_ids, dtype=np.int32)
data['is_supervised'] = np.array(is_supervised, dtype=np.int32)
n_inputs = len(input_ids)
if n_inputs < self.batch_size:
self.batch_size = max(n_inputs, len(self._gpu_ids))
# convert y
if y:
label_ids = self._convert_y(y)
data['label_ids'] = np.array(label_ids, dtype=np.int32)
# convert sample_weight
if is_training or y:
sample_weight = self._convert_sample_weight(
sample_weight, n_inputs)
data['sample_weight'] = np.array(sample_weight, dtype=np.float32)
return data
def _convert_X_reimp(self, X_target, y, tokenized):
# tokenize input texts
sup_ori_input_tokens = []
aug_input_tokens = []
is_supervised = []
for ex_id, example in enumerate(X_target):
try:
label = y[ex_id]
if label is None:
assert len(example) == 2
sup_ori_input_tokens.append(
self._convert_x(example[0], tokenized))
aug_input_tokens.append(
self._convert_x(example[1], tokenized))
is_supervised.append(0)
else:
sup_ori_input_tokens.append(
self._convert_x(example, tokenized))
aug_input_tokens.append([])
is_supervised.append(1)
except AssertionError:
raise AssertionError (
'Must have exactly two inputs for an '
'unsupervised example, respectively original '
'and augmented.')
except Exception:
raise ValueError(
'Wrong input format (line %d): \'%s\'. '
% (ex_id, example))
input_ids = []
input_mask = []
segment_ids = []
for ex_id, segments in enumerate(sup_ori_input_tokens):
_input_tokens = ['[CLS]']
_input_ids = []
_input_mask = [1]
_segment_ids = [0]
utils.truncate_segments(
segments, self.max_seq_length - len(segments) - 1,
truncate_method=self.truncate_method)
for s_id, segment in enumerate(segments):
_segment_id = min(s_id, 1)
_input_tokens.extend(segment + ['[SEP]'])
_input_mask.extend([1] * (len(segment) + 1))
_segment_ids.extend([_segment_id] * (len(segment) + 1))
_input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)
# padding
for _ in range(self.max_seq_length - len(_input_ids)):
_input_ids.append(0)
_input_mask.append(0)
_segment_ids.append(0)
input_ids.append(_input_ids)
input_mask.append(_input_mask)
segment_ids.append(_segment_ids)
aug_input_ids = []
aug_input_mask = []
aug_segment_ids = []
for ex_id, segments in enumerate(aug_input_tokens):
_input_tokens = ['[CLS]']
_input_ids = []
_input_mask = [1]
_segment_ids = [0]
utils.truncate_segments(
segments, self.max_seq_length - len(segments) - 1,
truncate_method=self.truncate_method)
for s_id, segment in enumerate(segments):
_segment_id = min(s_id, 1)
_input_tokens.extend(segment + ['[SEP]'])
_input_mask.extend([1] * (len(segment) + 1))
_segment_ids.extend([_segment_id] * (len(segment) + 1))
_input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)
# padding
for _ in range(self.max_seq_length - len(_input_ids)):
_input_ids.append(0)
_input_mask.append(0)
_segment_ids.append(0)
aug_input_ids.append(_input_ids)
aug_input_mask.append(_input_mask)
aug_segment_ids.append(_segment_ids)
return (input_ids, input_mask, segment_ids,
aug_input_ids, aug_input_mask, aug_segment_ids,
is_supervised)
def _convert_y(self, y):
label_set = set(y)
if None in label_set:
label_set -= {None}
# automatically set `label_size`
if self.label_size:
assert len(label_set) <= self.label_size, (
'Number of unique `y`s exceeds `label_size`.')
else:
self.label_size = len(label_set)
# automatically set `id_to_label`
if not self._id_to_label:
self._id_to_label = list(label_set)
try:
# Allign if user inputs continual integers.
# e.g. [2, 0, 1]
self._id_to_label = list(sorted(self._id_to_label))
except Exception:
pass
if len(self._id_to_label) < self.label_size:
for i in range(len(self._id_to_label), self.label_size):
self._id_to_label.append(i)
# automatically set `label_to_id` for prediction
self._label_to_id = {
label: index for index, label in enumerate(self._id_to_label)}
label_ids = [self._label_to_id[label]
if label is not None else -1 for label in y]
return label_ids
def _set_placeholders(self, target, on_export=False, **kwargs):
self.placeholders = {
'input_ids': utils.get_placeholder(
target, 'input_ids',
[None, self.max_seq_length], tf.int32),
'input_mask': utils.get_placeholder(
target, 'input_mask',
[None, self.max_seq_length], tf.int32),
'segment_ids': utils.get_placeholder(
target, 'segment_ids',
[None, self.max_seq_length], tf.int32),
'label_ids': utils.get_placeholder(
target, 'label_ids', [None], tf.int32),
}
if kwargs.get('is_training'):
self.placeholders['aug_input_ids'] = utils.get_placeholder(
target, 'aug_input_ids',
[None, self.max_seq_length], tf.int32)
self.placeholders['aug_input_mask'] = utils.get_placeholder(
target, 'aug_input_mask',
[None, self.max_seq_length], tf.int32)
self.placeholders['aug_segment_ids'] = utils.get_placeholder(
target, 'aug_segment_ids',
[None, self.max_seq_length], tf.int32)
self.placeholders['is_supervised'] = utils.get_placeholder(
target, 'is_supervised',
[None], tf.float32)
if not on_export:
self.placeholders['sample_weight'] = \
utils.get_placeholder(
target, 'sample_weight',
[None], tf.float32)
def _forward(self, is_training, split_placeholders, **kwargs):
if not is_training:
return super()._forward(is_training, split_placeholders, **kwargs)
aug_input_ids = tf.boolean_mask(
split_placeholders['aug_input_ids'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
aug_input_mask = tf.boolean_mask(
split_placeholders['aug_input_mask'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
aug_segment_ids = tf.boolean_mask(
split_placeholders['aug_segment_ids'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
input_ids = tf.concat(
[split_placeholders['input_ids'],
aug_input_ids], axis=0)
input_mask = tf.concat(
[split_placeholders['input_mask'],
aug_input_mask], axis=0)
segment_ids = tf.concat(
[split_placeholders['segment_ids'],
aug_segment_ids], axis=0)
encoder = BERTEncoder(
bert_config=self.bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
scope='bert',
drop_pooler=self._drop_pooler,
**kwargs)
encoder_output = encoder.get_pooled_output()
label_ids = split_placeholders['label_ids']
is_expanded = tf.zeros_like(label_ids, dtype=tf.float32)
batch_size = util.get_shape_list(aug_input_ids)[0]
aug_is_expanded = tf.ones((batch_size), dtype=tf.float32)
is_expanded = tf.concat([is_expanded, aug_is_expanded], axis=0)
decoder = UDADecoder(
is_training=is_training,
input_tensor=encoder_output,
is_supervised=split_placeholders['is_supervised'],
is_expanded=is_expanded,
label_ids=label_ids,
label_size=self.label_size,
sample_weight=split_placeholders.get('sample_weight'),
scope='cls/seq_relationship',
global_step=self._global_step,
num_train_steps=self.total_steps,
uda_softmax_temp=self._uda_softmax_temp,
uda_confidence_thresh=self._uda_confidence_thresh,
tsa_schedule=self._tsa_schedule,
**kwargs)
(total_loss, losses, probs, preds) = decoder.get_forward_outputs()
return (total_loss, losses, probs, preds)
def _get_fit_ops(self, as_feature=False):
ops = [self._train_op,
self._preds['preds'],
self._losses['supervised'],
self._losses['unsupervised'],
]
if as_feature:
ops.extend([self.placeholders['is_supervised'],
self.placeholders['label_ids']])
return ops
def _get_fit_info(self, output_arrays, feed_dict, as_feature=False):
if as_feature:
batch_is_sup = output_arrays[-2]
batch_labels = output_arrays[-1]
else:
batch_is_sup = feed_dict[self.placeholders['is_supervised']]
batch_labels = feed_dict[self.placeholders['label_ids']]
# accuracy
batch_preds = output_arrays[1]
accuracy = np.sum((batch_preds == batch_labels) * batch_is_sup) / \
np.sum(batch_is_sup)
# supervised loss
batch_sup_losses = output_arrays[2]
sup_loss = np.mean(batch_sup_losses)
# supervised loss
batch_unsup_losses = output_arrays[3]
unsup_loss = np.mean(batch_unsup_losses)
info = ''
info += ', accuracy %.4f' % accuracy
info += ', supervised loss %.6f' % sup_loss
info += ', unsupervised loss %.6f' % unsup_loss
return info
| 38.872396 | 79 | 0.586923 |
import numpy as np
from uf.tools import tf
from .base import ClassifierModule
from .bert import BERTClassifier, get_bert_config, get_key_to_depths
from uf.modeling.bert import BERTEncoder
from uf.modeling.uda import UDADecoder
from uf.tokenization.word_piece import get_word_piece_tokenizer
import uf.utils as utils
import uf.modeling.util as util
class UDAClassifier(BERTClassifier, ClassifierModule):
_INFER_ATTRIBUTES = BERTClassifier._INFER_ATTRIBUTES
def __init__(self,
config_file,
vocab_file,
max_seq_length=128,
label_size=None,
init_checkpoint=None,
output_dir=None,
gpu_ids=None,
drop_pooler=False,
uda_softmax_temp=-1,
uda_confidence_thresh=-1,
tsa_schedule='linear',
do_lower_case=True,
truncate_method='LIFO'):
super(ClassifierModule, self).__init__(
init_checkpoint, output_dir, gpu_ids)
self.batch_size = 0
self.max_seq_length = max_seq_length
self.label_size = label_size
self.truncate_method = truncate_method
self._drop_pooler = drop_pooler
self._uda_softmax_temp = uda_softmax_temp
self._uda_confidence_thresh = uda_confidence_thresh
self._tsa_schedule = tsa_schedule
self._id_to_label = None
self.__init_args__ = locals()
self.bert_config = get_bert_config(config_file)
self.tokenizer = get_word_piece_tokenizer(vocab_file, do_lower_case)
self._key_to_depths = get_key_to_depths(
self.bert_config.num_hidden_layers)
if '[CLS]' not in self.tokenizer.vocab:
self.tokenizer.add('[CLS]')
self.bert_config.vocab_size += 1
tf.logging.info('Add necessary token `[CLS]` into vocabulary.')
if '[SEP]' not in self.tokenizer.vocab:
self.tokenizer.add('[SEP]')
self.bert_config.vocab_size += 1
tf.logging.info('Add necessary token `[SEP]` into vocabulary.')
def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None,
is_training=False):
self._assert_legal(X, y, sample_weight, X_tokenized)
if not is_training:
return super().convert(
X, y, sample_weight, X_tokenized, is_training)
if is_training:
assert y is not None, '`y` can\'t be None.'
n_inputs = None
data = {}
# convert X
if X or X_tokenized:
tokenized = False if X else X_tokenized
(input_ids, input_mask, segment_ids,
aug_input_ids, aug_input_mask, aug_segment_ids,
is_supervised) = self._convert_X_reimp(
X_tokenized if tokenized else X, y, tokenized=tokenized)
data['input_ids'] = np.array(input_ids, dtype=np.int32)
data['input_mask'] = np.array(input_mask, dtype=np.int32)
data['segment_ids'] = np.array(segment_ids, dtype=np.int32)
data['aug_input_ids'] = np.array(aug_input_ids, dtype=np.int32)
data['aug_input_mask'] = np.array(aug_input_mask, dtype=np.int32)
data['aug_segment_ids'] = np.array(aug_segment_ids, dtype=np.int32)
data['is_supervised'] = np.array(is_supervised, dtype=np.int32)
n_inputs = len(input_ids)
if n_inputs < self.batch_size:
self.batch_size = max(n_inputs, len(self._gpu_ids))
# convert y
if y:
label_ids = self._convert_y(y)
data['label_ids'] = np.array(label_ids, dtype=np.int32)
# convert sample_weight
if is_training or y:
sample_weight = self._convert_sample_weight(
sample_weight, n_inputs)
data['sample_weight'] = np.array(sample_weight, dtype=np.float32)
return data
def _convert_X_reimp(self, X_target, y, tokenized):
# tokenize input texts
sup_ori_input_tokens = []
aug_input_tokens = []
is_supervised = []
for ex_id, example in enumerate(X_target):
try:
label = y[ex_id]
if label is None:
assert len(example) == 2
sup_ori_input_tokens.append(
self._convert_x(example[0], tokenized))
aug_input_tokens.append(
self._convert_x(example[1], tokenized))
is_supervised.append(0)
else:
sup_ori_input_tokens.append(
self._convert_x(example, tokenized))
aug_input_tokens.append([])
is_supervised.append(1)
except AssertionError:
raise AssertionError (
'Must have exactly two inputs for an '
'unsupervised example, respectively original '
'and augmented.')
except Exception:
raise ValueError(
'Wrong input format (line %d): \'%s\'. '
% (ex_id, example))
input_ids = []
input_mask = []
segment_ids = []
for ex_id, segments in enumerate(sup_ori_input_tokens):
_input_tokens = ['[CLS]']
_input_ids = []
_input_mask = [1]
_segment_ids = [0]
utils.truncate_segments(
segments, self.max_seq_length - len(segments) - 1,
truncate_method=self.truncate_method)
for s_id, segment in enumerate(segments):
_segment_id = min(s_id, 1)
_input_tokens.extend(segment + ['[SEP]'])
_input_mask.extend([1] * (len(segment) + 1))
_segment_ids.extend([_segment_id] * (len(segment) + 1))
_input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)
# padding
for _ in range(self.max_seq_length - len(_input_ids)):
_input_ids.append(0)
_input_mask.append(0)
_segment_ids.append(0)
input_ids.append(_input_ids)
input_mask.append(_input_mask)
segment_ids.append(_segment_ids)
aug_input_ids = []
aug_input_mask = []
aug_segment_ids = []
for ex_id, segments in enumerate(aug_input_tokens):
_input_tokens = ['[CLS]']
_input_ids = []
_input_mask = [1]
_segment_ids = [0]
utils.truncate_segments(
segments, self.max_seq_length - len(segments) - 1,
truncate_method=self.truncate_method)
for s_id, segment in enumerate(segments):
_segment_id = min(s_id, 1)
_input_tokens.extend(segment + ['[SEP]'])
_input_mask.extend([1] * (len(segment) + 1))
_segment_ids.extend([_segment_id] * (len(segment) + 1))
_input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)
# padding
for _ in range(self.max_seq_length - len(_input_ids)):
_input_ids.append(0)
_input_mask.append(0)
_segment_ids.append(0)
aug_input_ids.append(_input_ids)
aug_input_mask.append(_input_mask)
aug_segment_ids.append(_segment_ids)
return (input_ids, input_mask, segment_ids,
aug_input_ids, aug_input_mask, aug_segment_ids,
is_supervised)
def _convert_y(self, y):
label_set = set(y)
if None in label_set:
label_set -= {None}
# automatically set `label_size`
if self.label_size:
assert len(label_set) <= self.label_size, (
'Number of unique `y`s exceeds `label_size`.')
else:
self.label_size = len(label_set)
# automatically set `id_to_label`
if not self._id_to_label:
self._id_to_label = list(label_set)
try:
# Allign if user inputs continual integers.
# e.g. [2, 0, 1]
self._id_to_label = list(sorted(self._id_to_label))
except Exception:
pass
if len(self._id_to_label) < self.label_size:
for i in range(len(self._id_to_label), self.label_size):
self._id_to_label.append(i)
# automatically set `label_to_id` for prediction
self._label_to_id = {
label: index for index, label in enumerate(self._id_to_label)}
label_ids = [self._label_to_id[label]
if label is not None else -1 for label in y]
return label_ids
def _set_placeholders(self, target, on_export=False, **kwargs):
self.placeholders = {
'input_ids': utils.get_placeholder(
target, 'input_ids',
[None, self.max_seq_length], tf.int32),
'input_mask': utils.get_placeholder(
target, 'input_mask',
[None, self.max_seq_length], tf.int32),
'segment_ids': utils.get_placeholder(
target, 'segment_ids',
[None, self.max_seq_length], tf.int32),
'label_ids': utils.get_placeholder(
target, 'label_ids', [None], tf.int32),
}
if kwargs.get('is_training'):
self.placeholders['aug_input_ids'] = utils.get_placeholder(
target, 'aug_input_ids',
[None, self.max_seq_length], tf.int32)
self.placeholders['aug_input_mask'] = utils.get_placeholder(
target, 'aug_input_mask',
[None, self.max_seq_length], tf.int32)
self.placeholders['aug_segment_ids'] = utils.get_placeholder(
target, 'aug_segment_ids',
[None, self.max_seq_length], tf.int32)
self.placeholders['is_supervised'] = utils.get_placeholder(
target, 'is_supervised',
[None], tf.float32)
if not on_export:
self.placeholders['sample_weight'] = \
utils.get_placeholder(
target, 'sample_weight',
[None], tf.float32)
def _forward(self, is_training, split_placeholders, **kwargs):
if not is_training:
return super()._forward(is_training, split_placeholders, **kwargs)
aug_input_ids = tf.boolean_mask(
split_placeholders['aug_input_ids'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
aug_input_mask = tf.boolean_mask(
split_placeholders['aug_input_mask'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
aug_segment_ids = tf.boolean_mask(
split_placeholders['aug_segment_ids'],
mask=(1.0 - split_placeholders['is_supervised']),
axis=0)
input_ids = tf.concat(
[split_placeholders['input_ids'],
aug_input_ids], axis=0)
input_mask = tf.concat(
[split_placeholders['input_mask'],
aug_input_mask], axis=0)
segment_ids = tf.concat(
[split_placeholders['segment_ids'],
aug_segment_ids], axis=0)
encoder = BERTEncoder(
bert_config=self.bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
scope='bert',
drop_pooler=self._drop_pooler,
**kwargs)
encoder_output = encoder.get_pooled_output()
label_ids = split_placeholders['label_ids']
is_expanded = tf.zeros_like(label_ids, dtype=tf.float32)
batch_size = util.get_shape_list(aug_input_ids)[0]
aug_is_expanded = tf.ones((batch_size), dtype=tf.float32)
is_expanded = tf.concat([is_expanded, aug_is_expanded], axis=0)
decoder = UDADecoder(
is_training=is_training,
input_tensor=encoder_output,
is_supervised=split_placeholders['is_supervised'],
is_expanded=is_expanded,
label_ids=label_ids,
label_size=self.label_size,
sample_weight=split_placeholders.get('sample_weight'),
scope='cls/seq_relationship',
global_step=self._global_step,
num_train_steps=self.total_steps,
uda_softmax_temp=self._uda_softmax_temp,
uda_confidence_thresh=self._uda_confidence_thresh,
tsa_schedule=self._tsa_schedule,
**kwargs)
(total_loss, losses, probs, preds) = decoder.get_forward_outputs()
return (total_loss, losses, probs, preds)
def _get_fit_ops(self, as_feature=False):
ops = [self._train_op,
self._preds['preds'],
self._losses['supervised'],
self._losses['unsupervised'],
]
if as_feature:
ops.extend([self.placeholders['is_supervised'],
self.placeholders['label_ids']])
return ops
def _get_fit_info(self, output_arrays, feed_dict, as_feature=False):
if as_feature:
batch_is_sup = output_arrays[-2]
batch_labels = output_arrays[-1]
else:
batch_is_sup = feed_dict[self.placeholders['is_supervised']]
batch_labels = feed_dict[self.placeholders['label_ids']]
# accuracy
batch_preds = output_arrays[1]
accuracy = np.sum((batch_preds == batch_labels) * batch_is_sup) / \
np.sum(batch_is_sup)
# supervised loss
batch_sup_losses = output_arrays[2]
sup_loss = np.mean(batch_sup_losses)
# supervised loss
batch_unsup_losses = output_arrays[3]
unsup_loss = np.mean(batch_unsup_losses)
info = ''
info += ', accuracy %.4f' % accuracy
info += ', supervised loss %.6f' % sup_loss
info += ', unsupervised loss %.6f' % unsup_loss
return info
| true | true |
f72c4da207cd6d82929af064fa9ceebeef08defa | 283 | py | Python | iterators_and_generators/demo_generators.py | Minkov/python-oop-2020-02 | d2acb1504c1a135cded2ae6ff42acccb303d9ab1 | [
"MIT"
] | 2 | 2020-02-27T18:34:45.000Z | 2020-10-25T17:34:15.000Z | iterators_and_generators/demo_generators.py | Minkov/python-oop-2020-02 | d2acb1504c1a135cded2ae6ff42acccb303d9ab1 | [
"MIT"
] | null | null | null | iterators_and_generators/demo_generators.py | Minkov/python-oop-2020-02 | d2acb1504c1a135cded2ae6ff42acccb303d9ab1 | [
"MIT"
] | null | null | null | def custom_range(min, max):
index = min
while index <= max:
yield index
index += 1
it = custom_range(1, 2)
print(next(it))
print(next(it))
print((x for x in range(3)))
even = filter(lambda x: x % 2 == 0, range(10))
for x in even:
print(x) | 18.866667 | 47 | 0.55477 | def custom_range(min, max):
index = min
while index <= max:
yield index
index += 1
it = custom_range(1, 2)
print(next(it))
print(next(it))
print((x for x in range(3)))
even = filter(lambda x: x % 2 == 0, range(10))
for x in even:
print(x) | true | true |
f72c4f1fb0a457648028cbec2b488d34d23bde73 | 5,745 | py | Python | logistic_fit.py | ege-erdil/logistic-fit | 7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb | [
"MIT"
] | null | null | null | logistic_fit.py | ege-erdil/logistic-fit | 7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb | [
"MIT"
] | null | null | null | logistic_fit.py | ege-erdil/logistic-fit | 7c6cc9ed35877ed8d142dd75b7b98658e19cf7cb | [
"MIT"
] | null | null | null | from autograd import grad
import autograd.numpy as np
from scipy.stats import logistic, norm
from scipy.optimize import minimize
def logistic_pdf(x, loc, scale):
y = (x - loc)/scale
return np.exp(-y)/(scale * (1 + np.exp(-y))**2)
def logistic_cdf(x, loc, scale):
y = (x-loc)/scale
if y < -100:
return 0
elif y > 100:
return 1
else:
return 1/(1 + np.exp(-y))
def logistic_logpdf(x, loc, scale):
y = (x - loc)/scale
if y < -250:
return y - np.log(scale)
elif y > 250:
return -y - np.log(scale)
else:
return -y - np.log(scale) - 2 * np.log(1 + np.exp(-y))
def square_dist(a1, a2):
s = 0
for k in range(len(a1)):
s += (a1[k] - a2[k])**2
return s
def log_likelihood_logistic(data, params):
n = len(data)
c = (len(params) + 1)//3
r = 0
if (len(params) + 1) % 3 != 0:
print("Parameters specified incorrectly!")
return None
else:
weights = [1]
for k in range(c-1):
weights.append(np.exp(params[2*c + k]))
s = np.sum(weights)
for x in data:
pdf_list = [logistic_logpdf(x, params[2*j], np.exp(params[2*j+1])) for j in range(c)]
pdf_list_avg = np.sum(pdf_list)/c
pdf_list_n = [weights[j] * np.exp(pdf_list[j] - pdf_list_avg) for j in range(c)]
r += (pdf_list_avg + np.log(np.sum(pdf_list_n)/s))/n
return r
def cdf_loss(percentiles, params):
n = len(percentiles)
c = (len(params) + 1)//3
r = 0
if (len(params) + 1) % 3 != 0:
print("Parameters specified incorrectly!")
return None
else:
weights = [1]
for k in range(c-1):
weights.append(np.exp(params[2*c + k]))
s = np.sum(weights)
for q in range(1, n):
cdf_list = [logistic_cdf(percentiles[q-1], params[2*j], np.exp(params[2*j+1])) for j in range(c)]
cdf_list_n = [weights[j] * cdf_list[j] for j in range(c)]
r += (np.sum(cdf_list_n)/s - q/n)**2/n
return r
def estimate(data, bins=20, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
percentiles = [np.percentile(data, k) for k in range(100//bins, 100, 100//bins)]
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_loss(params):
return cdf_loss(percentiles, params) + 0.0001 * np.dot(params[2*num:], params[2*num:])
training_loss_jac = grad(training_loss)
res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
def estimate_log(data, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_likelihood(params):
return log_likelihood_logistic(data, params)
def training_loss(params):
return -log_likelihood_logistic(data, params)
training_likelihood_jac = grad(training_likelihood)
training_loss_jac = grad(training_loss)
res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
def estimate_powell(data, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_likelihood(params):
return log_likelihood_logistic(data, params)
def training_loss(params):
return -log_likelihood_logistic(data, params)
training_likelihood_jac = grad(training_likelihood)
training_loss_jac = grad(training_loss)
res = minimize(training_loss, x0=fit_params, method="Powell", tol=tol, options = {"maxiter": maxiter})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
| 33.794118 | 132 | 0.582594 | from autograd import grad
import autograd.numpy as np
from scipy.stats import logistic, norm
from scipy.optimize import minimize
def logistic_pdf(x, loc, scale):
y = (x - loc)/scale
return np.exp(-y)/(scale * (1 + np.exp(-y))**2)
def logistic_cdf(x, loc, scale):
y = (x-loc)/scale
if y < -100:
return 0
elif y > 100:
return 1
else:
return 1/(1 + np.exp(-y))
def logistic_logpdf(x, loc, scale):
y = (x - loc)/scale
if y < -250:
return y - np.log(scale)
elif y > 250:
return -y - np.log(scale)
else:
return -y - np.log(scale) - 2 * np.log(1 + np.exp(-y))
def square_dist(a1, a2):
s = 0
for k in range(len(a1)):
s += (a1[k] - a2[k])**2
return s
def log_likelihood_logistic(data, params):
n = len(data)
c = (len(params) + 1)//3
r = 0
if (len(params) + 1) % 3 != 0:
print("Parameters specified incorrectly!")
return None
else:
weights = [1]
for k in range(c-1):
weights.append(np.exp(params[2*c + k]))
s = np.sum(weights)
for x in data:
pdf_list = [logistic_logpdf(x, params[2*j], np.exp(params[2*j+1])) for j in range(c)]
pdf_list_avg = np.sum(pdf_list)/c
pdf_list_n = [weights[j] * np.exp(pdf_list[j] - pdf_list_avg) for j in range(c)]
r += (pdf_list_avg + np.log(np.sum(pdf_list_n)/s))/n
return r
def cdf_loss(percentiles, params):
n = len(percentiles)
c = (len(params) + 1)//3
r = 0
if (len(params) + 1) % 3 != 0:
print("Parameters specified incorrectly!")
return None
else:
weights = [1]
for k in range(c-1):
weights.append(np.exp(params[2*c + k]))
s = np.sum(weights)
for q in range(1, n):
cdf_list = [logistic_cdf(percentiles[q-1], params[2*j], np.exp(params[2*j+1])) for j in range(c)]
cdf_list_n = [weights[j] * cdf_list[j] for j in range(c)]
r += (np.sum(cdf_list_n)/s - q/n)**2/n
return r
def estimate(data, bins=20, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
percentiles = [np.percentile(data, k) for k in range(100//bins, 100, 100//bins)]
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_loss(params):
return cdf_loss(percentiles, params) + 0.0001 * np.dot(params[2*num:], params[2*num:])
training_loss_jac = grad(training_loss)
res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
def estimate_log(data, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_likelihood(params):
return log_likelihood_logistic(data, params)
def training_loss(params):
return -log_likelihood_logistic(data, params)
training_likelihood_jac = grad(training_likelihood)
training_loss_jac = grad(training_loss)
res = minimize(training_loss, jac=training_loss_jac, x0=fit_params, method="BFGS", options = {"maxiter": maxiter, "gtol": tol})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
def estimate_powell(data, num = 1, tol = 0.01, maxiter = 100):
fit_params = np.zeros(3*num - 1)
a = np.average(data)
s = np.log(np.std(data))
for i in range(num):
fit_params[2*i] = np.random.normal(loc=a, scale=np.exp(s), size=1)
fit_params[2*i+1] = np.random.normal(loc=s - np.log(num), scale=1, size=1)
def training_likelihood(params):
return log_likelihood_logistic(data, params)
def training_loss(params):
return -log_likelihood_logistic(data, params)
training_likelihood_jac = grad(training_likelihood)
training_loss_jac = grad(training_loss)
res = minimize(training_loss, x0=fit_params, method="Powell", tol=tol, options = {"maxiter": maxiter})
print(res)
final_params = res.x
for i in range(num):
final_params[2*i+1] = np.exp(final_params[2*i+1])
results = []
for i in range(num):
results.append(final_params[2*i])
results.append(logistic.isf(0.25, loc=final_params[2*i], scale=final_params[2*i+1]) - final_params[2*i])
for i in range(num-1):
results.append(final_params[2*num + i])
return results
| true | true |
f72c4f3b403c785cc891e829c3dd7d88ad7ca116 | 308 | py | Python | tests/parser_test.py | krilifon/proxy-parse | 79d1c1655024a03e7a8c1b653dfdf6d68f89e511 | [
"MIT"
] | 4 | 2021-11-29T18:56:54.000Z | 2021-12-23T10:59:58.000Z | tests/parser_test.py | krilifon/proxy-parse | 79d1c1655024a03e7a8c1b653dfdf6d68f89e511 | [
"MIT"
] | null | null | null | tests/parser_test.py | krilifon/proxy-parse | 79d1c1655024a03e7a8c1b653dfdf6d68f89e511 | [
"MIT"
] | null | null | null | from proxy_parse import ProxyParser
from proxy_parse.spiders import HideMySpider
def test_proxy_parser():
proxy_parser = ProxyParser(scrapy_spiders=[HideMySpider])
result = proxy_parser.parse()
assert type(result) is list
assert all(type(proxy) is str and ":" in proxy for proxy in result)
| 30.8 | 71 | 0.762987 | from proxy_parse import ProxyParser
from proxy_parse.spiders import HideMySpider
def test_proxy_parser():
proxy_parser = ProxyParser(scrapy_spiders=[HideMySpider])
result = proxy_parser.parse()
assert type(result) is list
assert all(type(proxy) is str and ":" in proxy for proxy in result)
| true | true |
f72c50b550d0cb981526fc944b9967a3ca63e4c6 | 237 | py | Python | polyaxon/api/code_reference/serializers.py | elyase/polyaxon | 1c19f059a010a6889e2b7ea340715b2bcfa382a0 | [
"MIT"
] | null | null | null | polyaxon/api/code_reference/serializers.py | elyase/polyaxon | 1c19f059a010a6889e2b7ea340715b2bcfa382a0 | [
"MIT"
] | null | null | null | polyaxon/api/code_reference/serializers.py | elyase/polyaxon | 1c19f059a010a6889e2b7ea340715b2bcfa382a0 | [
"MIT"
] | null | null | null | from rest_framework import serializers
from db.models.repos import CodeReference
class CodeReferenceSerializer(serializers.ModelSerializer):
class Meta:
model = CodeReference
exclude = ['created_at', 'updated_at']
| 23.7 | 59 | 0.755274 | from rest_framework import serializers
from db.models.repos import CodeReference
class CodeReferenceSerializer(serializers.ModelSerializer):
class Meta:
model = CodeReference
exclude = ['created_at', 'updated_at']
| true | true |
f72c516d329c6cda5c8629429947754fd975930b | 458 | py | Python | .venv/lib/python3.7/site-packages/jupyter_client/__init__.py | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | 4acdbc423428fb2e0068720add69e7870c87929a | [
"Apache-2.0"
] | 76 | 2020-07-06T14:44:05.000Z | 2022-02-14T15:30:21.000Z | .venv/lib/python3.7/site-packages/jupyter_client/__init__.py | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | 4acdbc423428fb2e0068720add69e7870c87929a | [
"Apache-2.0"
] | 24 | 2020-03-25T19:35:43.000Z | 2022-02-10T11:46:50.000Z | .venv/lib/python3.7/site-packages/jupyter_client/__init__.py | ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos | 4acdbc423428fb2e0068720add69e7870c87929a | [
"Apache-2.0"
] | 11 | 2019-01-21T17:51:48.000Z | 2021-08-10T07:04:33.000Z | """Client-side implementations of the Jupyter protocol"""
from ._version import version_info, __version__, protocol_version_info, protocol_version
from .connect import *
from .launcher import *
from .client import KernelClient
from .manager import KernelManager, AsyncKernelManager, run_kernel
from .blocking import BlockingKernelClient
from .asynchronous import AsyncKernelClient
from .multikernelmanager import MultiKernelManager, AsyncMultiKernelManager
| 41.636364 | 88 | 0.851528 |
from ._version import version_info, __version__, protocol_version_info, protocol_version
from .connect import *
from .launcher import *
from .client import KernelClient
from .manager import KernelManager, AsyncKernelManager, run_kernel
from .blocking import BlockingKernelClient
from .asynchronous import AsyncKernelClient
from .multikernelmanager import MultiKernelManager, AsyncMultiKernelManager
| true | true |
f72c517b8635ba9e8ee1d7ac3aac00b5ef74b266 | 475 | py | Python | src/som/primitives/invokable_primitives.py | smarr/RPySOM | 941e1fe08753d6e97dac24c3ba4d1e99a9c40160 | [
"MIT"
] | 12 | 2016-01-07T14:20:57.000Z | 2019-10-13T06:56:20.000Z | src/som/primitives/invokable_primitives.py | smarr/RPySOM | 941e1fe08753d6e97dac24c3ba4d1e99a9c40160 | [
"MIT"
] | 2 | 2016-05-26T06:53:33.000Z | 2020-09-02T15:58:28.000Z | src/som/primitives/invokable_primitives.py | SOM-st/RPySOM | 2dcfc71786a3bd5be5a842c649645f71d6c35f89 | [
"MIT"
] | 2 | 2016-05-25T06:07:52.000Z | 2019-10-02T16:52:25.000Z | from som.primitives.primitives import Primitives
from som.vmobjects.primitive import UnaryPrimitive
def _holder(rcvr):
return rcvr.get_holder()
def _signature(rcvr):
return rcvr.get_signature()
class InvokablePrimitivesBase(Primitives):
def install_primitives(self):
self._install_instance_primitive(UnaryPrimitive("holder", self._universe, _holder))
self._install_instance_primitive(UnaryPrimitive("signature", self._universe, _signature))
| 27.941176 | 97 | 0.785263 | from som.primitives.primitives import Primitives
from som.vmobjects.primitive import UnaryPrimitive
def _holder(rcvr):
return rcvr.get_holder()
def _signature(rcvr):
return rcvr.get_signature()
class InvokablePrimitivesBase(Primitives):
def install_primitives(self):
self._install_instance_primitive(UnaryPrimitive("holder", self._universe, _holder))
self._install_instance_primitive(UnaryPrimitive("signature", self._universe, _signature))
| true | true |
f72c517f1ba15c39ff29e590665a48a098bdbe9a | 868 | py | Python | Aula_extrator_url/main.py | laurourbano/Projetos_Python | 50e7f4a7ff34158385ea7b635bac95ec8a0363a1 | [
"MIT"
] | 1 | 2021-12-28T02:51:34.000Z | 2021-12-28T02:51:34.000Z | Aula_extrator_url/main.py | laurourbano/Projetos_Python | 50e7f4a7ff34158385ea7b635bac95ec8a0363a1 | [
"MIT"
] | null | null | null | Aula_extrator_url/main.py | laurourbano/Projetos_Python | 50e7f4a7ff34158385ea7b635bac95ec8a0363a1 | [
"MIT"
] | null | null | null | # Arquivo utilizado até a aula 3, quando então passamos a utilizar a classe
# ExtratorURL no arquivo extrator_url.py
url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar"
# Sanitização da URL
url = url.strip()
# Validação da URL
if url == "":
raise ValueError("A URL está vazia")
# Separa base e parâmetros
indice_interrogacao = url.find('?')
url_base = url[:indice_interrogacao]
url_parametros = url[indice_interrogacao+1:]
print(url_parametros)
# Busca o valor de um parâmetro
parametro_busca = 'quantidade'
indice_parametro = url_parametros.find(parametro_busca)
indice_valor = indice_parametro + len(parametro_busca) + 1
indice_e_comercial = url_parametros.find('&', indice_valor)
if indice_e_comercial == -1:
valor = url_parametros[indice_valor:]
else:
valor = url_parametros[indice_valor:indice_e_comercial]
print(valor) | 31 | 78 | 0.776498 |
url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar"
url = url.strip()
if url == "":
raise ValueError("A URL está vazia")
indice_interrogacao = url.find('?')
url_base = url[:indice_interrogacao]
url_parametros = url[indice_interrogacao+1:]
print(url_parametros)
parametro_busca = 'quantidade'
indice_parametro = url_parametros.find(parametro_busca)
indice_valor = indice_parametro + len(parametro_busca) + 1
indice_e_comercial = url_parametros.find('&', indice_valor)
if indice_e_comercial == -1:
valor = url_parametros[indice_valor:]
else:
valor = url_parametros[indice_valor:indice_e_comercial]
print(valor) | true | true |
f72c51acdba5f7032ff01e97210db5d3fb75c607 | 8,224 | py | Python | conda/cli/main.py | jacoblsmith/conda | f50b919a4c923820c1bb2b449603534084faa28b | [
"BSD-3-Clause"
] | null | null | null | conda/cli/main.py | jacoblsmith/conda | f50b919a4c923820c1bb2b449603534084faa28b | [
"BSD-3-Clause"
] | null | null | null | conda/cli/main.py | jacoblsmith/conda | f50b919a4c923820c1bb2b449603534084faa28b | [
"BSD-3-Clause"
] | null | null | null | # (c) Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
'''conda is a tool for managing environments and packages.
conda provides the following commands:
Information
===========
info : display information about the current install
list : list packages linked into a specified environment
search : print information about a specified package
help : display a list of available conda commands and their help
strings
Package Management
==================
create : create a new conda environment from a list of specified
packages
install : install new packages into an existing conda environment
update : update packages in a specified conda environment
Packaging
=========
build : build a package from recipe
package : create a conda package in an environment
index : updates repodata.json in channel directories
Additional help for each command can be accessed by using:
conda <command> -h
'''
from __future__ import print_function, division, absolute_import
import sys
def main():
if len(sys.argv) > 1:
argv1 = sys.argv[1]
if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'):
import conda.cli.activate as activate
activate.main()
return
if argv1 in ('..changeps1'):
import conda.cli.misc as misc
misc.main()
return
if argv1 == 'pip':
sys.exit("""ERROR:
The "conda pip" command has been removed from conda (as of version 1.8) for
the following reasons:
* users get the wrong impression that you *must* use conda pip (instead
of simply pip) when using Anaconda
* there should only be one preferred way to build packages, and that is
the conda build command
* the command did too many things at once, i.e. build a package and
then also install it
* the command is Python centric, whereas conda (from a package management
perspective) is Python agnostic
* packages created with conda pip are not robust, i.e. they will maybe
not work on other people's systems
In short:
* use "conda build" if you want to build a conda package
* use "conda install" if you want to install something
* use "pip" if you want to install something that is on PyPI for which there
isn't a conda package.
""")
if argv1 in ('activate', 'deactivate'):
sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1)
if sys.platform != 'win32':
sys.stderr.write('Did you mean "source %s" ?\n' %
' '.join(sys.argv[1:]))
sys.exit(1)
# for backwards compatibility of conda-api
if sys.argv[1:4] == ['share', '--json', '--prefix']:
import json
from os.path import abspath
from conda.share import old_create_bundle
prefix = sys.argv[4]
path, warnings = old_create_bundle(abspath(prefix))
json.dump(dict(path=path, warnings=warnings),
sys.stdout, indent=2, sort_keys=True)
return
if sys.argv[1:4] == ['clone', '--json', '--prefix']:
import json
from os.path import abspath
from conda.share import old_clone_bundle
prefix, path = sys.argv[4:6]
old_clone_bundle(path, abspath(prefix))
json.dump(dict(warnings=[]), sys.stdout, indent=2)
return
if len(sys.argv) == 1:
sys.argv.append('-h')
import logging
from conda.cli import conda_argparse
import argparse
import conda
p = conda_argparse.ArgumentParser(
description='conda is a tool for managing and deploying applications, environments and packages.'
)
p.add_argument(
'-V', '--version',
action='version',
version='conda %s' % conda.__version__,
help="Show the conda version number and exit."
)
p.add_argument(
"--debug",
action = "store_true",
help = "Show debug output."
)
p.add_argument(
"--json",
action = "store_true",
help = argparse.SUPPRESS,
)
sub_parsers = p.add_subparsers(
metavar = 'command',
dest = 'cmd',
)
from conda.cli import main_info
main_info.configure_parser(sub_parsers)
from conda.cli import main_help
main_help.configure_parser(sub_parsers)
from conda.cli import main_list
main_list.configure_parser(sub_parsers)
from conda.cli import main_search
main_search.configure_parser(sub_parsers)
from conda.cli import main_create
main_create.configure_parser(sub_parsers)
from conda.cli import main_install
main_install.configure_parser(sub_parsers)
from conda.cli import main_update
main_update.configure_parser(sub_parsers)
from conda.cli import main_remove
main_remove.configure_parser(sub_parsers)
main_remove.configure_parser(sub_parsers, name='uninstall')
from conda.cli import main_run
main_run.configure_parser(sub_parsers)
from conda.cli import main_config
main_config.configure_parser(sub_parsers)
from conda.cli import main_init
main_init.configure_parser(sub_parsers)
from conda.cli import main_clean
main_clean.configure_parser(sub_parsers)
from conda.cli import main_package
main_package.configure_parser(sub_parsers)
from conda.cli import main_bundle
main_bundle.configure_parser(sub_parsers)
from conda.cli.find_commands import find_commands
sub_parsers.completer = lambda prefix, **kwargs: [i for i in
list(sub_parsers.choices) + find_commands() if i.startswith(prefix)]
args = p.parse_args()
if getattr(args, 'json', False):
# Silence logging info to avoid interfering with JSON output
for logger in logging.Logger.manager.loggerDict:
if logger not in ('fetch', 'progress'):
logging.getLogger(logger).setLevel(logging.CRITICAL + 1)
if args.debug:
logging.disable(logging.NOTSET)
logging.basicConfig(level=logging.DEBUG)
if (not main_init.is_initialized() and
'init' not in sys.argv and 'info' not in sys.argv):
if hasattr(args, 'name') and hasattr(args, 'prefix'):
import conda.config as config
from conda.cli import common
if common.get_prefix(args) == config.root_dir:
sys.exit("""\
Error: This installation of conda is not initialized. Use 'conda create -n
envname' to create a conda environment and 'source activate envname' to
activate it.
# Note that pip installing conda is not the recommended way for setting up your
# system. The recommended way for setting up a conda system is by installing
# Miniconda, see: http://repo.continuum.io/miniconda/index.html""")
args_func(args, p)
def args_func(args, p):
from conda.cli import common
use_json = getattr(args, 'json', False)
try:
args.func(args, p)
except RuntimeError as e:
if 'maximum recursion depth exceeded' in str(e):
print_issue_message(e, use_json=use_json)
raise
common.error_and_exit(str(e), json=use_json)
except Exception as e:
print_issue_message(e, use_json=use_json)
raise # as if we did not catch it
def print_issue_message(e, use_json=False):
from conda.cli import common
if e.__class__.__name__ not in ('ScannerError', 'ParserError'):
message = """\
An unexpected error has occurred, please consider sending the
following traceback to the conda GitHub issue tracker at:
https://github.com/conda/conda/issues
Include the output of the command 'conda info' in your report.
"""
if use_json:
import traceback
common.error_and_exit(message + traceback.format_exc(),
error_type="UnexpectedError", json=True)
print(message)
if __name__ == '__main__':
main()
| 35.601732 | 105 | 0.655399 |
from __future__ import print_function, division, absolute_import
import sys
def main():
if len(sys.argv) > 1:
argv1 = sys.argv[1]
if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'):
import conda.cli.activate as activate
activate.main()
return
if argv1 in ('..changeps1'):
import conda.cli.misc as misc
misc.main()
return
if argv1 == 'pip':
sys.exit("""ERROR:
The "conda pip" command has been removed from conda (as of version 1.8) for
the following reasons:
* users get the wrong impression that you *must* use conda pip (instead
of simply pip) when using Anaconda
* there should only be one preferred way to build packages, and that is
the conda build command
* the command did too many things at once, i.e. build a package and
then also install it
* the command is Python centric, whereas conda (from a package management
perspective) is Python agnostic
* packages created with conda pip are not robust, i.e. they will maybe
not work on other people's systems
In short:
* use "conda build" if you want to build a conda package
* use "conda install" if you want to install something
* use "pip" if you want to install something that is on PyPI for which there
isn't a conda package.
""")
if argv1 in ('activate', 'deactivate'):
sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1)
if sys.platform != 'win32':
sys.stderr.write('Did you mean "source %s" ?\n' %
' '.join(sys.argv[1:]))
sys.exit(1)
if sys.argv[1:4] == ['share', '--json', '--prefix']:
import json
from os.path import abspath
from conda.share import old_create_bundle
prefix = sys.argv[4]
path, warnings = old_create_bundle(abspath(prefix))
json.dump(dict(path=path, warnings=warnings),
sys.stdout, indent=2, sort_keys=True)
return
if sys.argv[1:4] == ['clone', '--json', '--prefix']:
import json
from os.path import abspath
from conda.share import old_clone_bundle
prefix, path = sys.argv[4:6]
old_clone_bundle(path, abspath(prefix))
json.dump(dict(warnings=[]), sys.stdout, indent=2)
return
if len(sys.argv) == 1:
sys.argv.append('-h')
import logging
from conda.cli import conda_argparse
import argparse
import conda
p = conda_argparse.ArgumentParser(
description='conda is a tool for managing and deploying applications, environments and packages.'
)
p.add_argument(
'-V', '--version',
action='version',
version='conda %s' % conda.__version__,
help="Show the conda version number and exit."
)
p.add_argument(
"--debug",
action = "store_true",
help = "Show debug output."
)
p.add_argument(
"--json",
action = "store_true",
help = argparse.SUPPRESS,
)
sub_parsers = p.add_subparsers(
metavar = 'command',
dest = 'cmd',
)
from conda.cli import main_info
main_info.configure_parser(sub_parsers)
from conda.cli import main_help
main_help.configure_parser(sub_parsers)
from conda.cli import main_list
main_list.configure_parser(sub_parsers)
from conda.cli import main_search
main_search.configure_parser(sub_parsers)
from conda.cli import main_create
main_create.configure_parser(sub_parsers)
from conda.cli import main_install
main_install.configure_parser(sub_parsers)
from conda.cli import main_update
main_update.configure_parser(sub_parsers)
from conda.cli import main_remove
main_remove.configure_parser(sub_parsers)
main_remove.configure_parser(sub_parsers, name='uninstall')
from conda.cli import main_run
main_run.configure_parser(sub_parsers)
from conda.cli import main_config
main_config.configure_parser(sub_parsers)
from conda.cli import main_init
main_init.configure_parser(sub_parsers)
from conda.cli import main_clean
main_clean.configure_parser(sub_parsers)
from conda.cli import main_package
main_package.configure_parser(sub_parsers)
from conda.cli import main_bundle
main_bundle.configure_parser(sub_parsers)
from conda.cli.find_commands import find_commands
sub_parsers.completer = lambda prefix, **kwargs: [i for i in
list(sub_parsers.choices) + find_commands() if i.startswith(prefix)]
args = p.parse_args()
if getattr(args, 'json', False):
for logger in logging.Logger.manager.loggerDict:
if logger not in ('fetch', 'progress'):
logging.getLogger(logger).setLevel(logging.CRITICAL + 1)
if args.debug:
logging.disable(logging.NOTSET)
logging.basicConfig(level=logging.DEBUG)
if (not main_init.is_initialized() and
'init' not in sys.argv and 'info' not in sys.argv):
if hasattr(args, 'name') and hasattr(args, 'prefix'):
import conda.config as config
from conda.cli import common
if common.get_prefix(args) == config.root_dir:
sys.exit("""\
Error: This installation of conda is not initialized. Use 'conda create -n
envname' to create a conda environment and 'source activate envname' to
activate it.
# Note that pip installing conda is not the recommended way for setting up your
# system. The recommended way for setting up a conda system is by installing
# Miniconda, see: http://repo.continuum.io/miniconda/index.html""")
args_func(args, p)
def args_func(args, p):
from conda.cli import common
use_json = getattr(args, 'json', False)
try:
args.func(args, p)
except RuntimeError as e:
if 'maximum recursion depth exceeded' in str(e):
print_issue_message(e, use_json=use_json)
raise
common.error_and_exit(str(e), json=use_json)
except Exception as e:
print_issue_message(e, use_json=use_json)
raise
def print_issue_message(e, use_json=False):
from conda.cli import common
if e.__class__.__name__ not in ('ScannerError', 'ParserError'):
message = """\
An unexpected error has occurred, please consider sending the
following traceback to the conda GitHub issue tracker at:
https://github.com/conda/conda/issues
Include the output of the command 'conda info' in your report.
"""
if use_json:
import traceback
common.error_and_exit(message + traceback.format_exc(),
error_type="UnexpectedError", json=True)
print(message)
if __name__ == '__main__':
main()
| true | true |
f72c52094e0d1fefbdc0188332f4f3efdc92129b | 4,055 | py | Python | semantic-conventions/src/opentelemetry/semconv/model/constraints.py | bogdandrutu/build-tools | 08bec45f36f112751a2ea0785368a4fa8e2add6a | [
"Apache-2.0"
] | null | null | null | semantic-conventions/src/opentelemetry/semconv/model/constraints.py | bogdandrutu/build-tools | 08bec45f36f112751a2ea0785368a4fa8e2add6a | [
"Apache-2.0"
] | null | null | null | semantic-conventions/src/opentelemetry/semconv/model/constraints.py | bogdandrutu/build-tools | 08bec45f36f112751a2ea0785368a4fa8e2add6a | [
"Apache-2.0"
] | null | null | null | # Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dataclasses import dataclass, field, replace
from typing import List, Tuple, Set
from opentelemetry.semconv.model.exceptions import ValidationError
from opentelemetry.semconv.model.semantic_attribute import SemanticAttribute
from opentelemetry.semconv.model.utils import validate_values
from ruamel.yaml.comments import CommentedSeq
# We cannot frozen due to later evaluation of the attributes
@dataclass
class AnyOf:
"""Defines a constraint where at least one of the list of attributes must be set.
The implementation of this class is evaluated in two times. At parsing time, the choice_list_ids field is
populated. After all yaml files are parsed, the choice_list_attributes field is populated with the object
representation of the attribute ids of choice_list_ids.
Attributes:
choice_list_ids Contains the lists of attributes ids that must be set.
inherited True if it is inherited by another semantic convention, i.e. by include or extends.
choice_list_attributes Contains the list of attributes objects. This list contains the same lists of
attributes of choice_list_ids but instead of the ids, it contains the respective
objects representations.
_yaml_src_position Contains the position in the YAML file of the AnyOf attribute
"""
choice_list_ids: Tuple[Tuple[str, ...]]
inherited: bool = False
choice_list_attributes: Tuple[Tuple[SemanticAttribute, ...]] = ()
_yaml_src_position: int = 0
def __eq__(self, other):
if not isinstance(other, AnyOf):
return False
return self.choice_list_ids == other.choice_list_ids
def __hash__(self):
return hash(self.choice_list_ids)
def add_attributes(self, attr: List[SemanticAttribute]):
self.choice_list_attributes += (attr,)
def inherit_anyof(self):
return replace(self, inherited=True)
@dataclass(frozen=True)
class Include:
semconv_id: str
def parse_constraints(yaml_constraints):
""" This method parses the yaml representation for semantic convention attributes
creating a list of Constraint objects.
"""
constraints = ()
allowed_keys = ("include", "any_of")
for constraint in yaml_constraints:
validate_values(constraint, allowed_keys)
if len(constraint.keys()) > 1:
position = constraint.lc.data[list(constraint)[1]]
msg = (
"Invalid entry in constraint array - multiple top-level keys in entry."
)
raise ValidationError.from_yaml_pos(position, msg)
if "include" in constraint:
constraints += (Include(constraint.get("include")),)
elif "any_of" in constraint:
choice_sets = ()
for constraint_list in constraint.get("any_of"):
inner_id_list = ()
if isinstance(constraint_list, CommentedSeq):
inner_id_list = tuple(
attr_constraint for attr_constraint in constraint_list
)
else:
inner_id_list += (constraint_list,)
choice_sets += (inner_id_list,)
any_of = AnyOf(choice_sets)
any_of._yaml_src_position = constraint.get("any_of").lc.data
constraints += (any_of,)
return constraints
| 41.377551 | 119 | 0.67349 |
from dataclasses import dataclass, field, replace
from typing import List, Tuple, Set
from opentelemetry.semconv.model.exceptions import ValidationError
from opentelemetry.semconv.model.semantic_attribute import SemanticAttribute
from opentelemetry.semconv.model.utils import validate_values
from ruamel.yaml.comments import CommentedSeq
@dataclass
class AnyOf:
choice_list_ids: Tuple[Tuple[str, ...]]
inherited: bool = False
choice_list_attributes: Tuple[Tuple[SemanticAttribute, ...]] = ()
_yaml_src_position: int = 0
def __eq__(self, other):
if not isinstance(other, AnyOf):
return False
return self.choice_list_ids == other.choice_list_ids
def __hash__(self):
return hash(self.choice_list_ids)
def add_attributes(self, attr: List[SemanticAttribute]):
self.choice_list_attributes += (attr,)
def inherit_anyof(self):
return replace(self, inherited=True)
@dataclass(frozen=True)
class Include:
semconv_id: str
def parse_constraints(yaml_constraints):
constraints = ()
allowed_keys = ("include", "any_of")
for constraint in yaml_constraints:
validate_values(constraint, allowed_keys)
if len(constraint.keys()) > 1:
position = constraint.lc.data[list(constraint)[1]]
msg = (
"Invalid entry in constraint array - multiple top-level keys in entry."
)
raise ValidationError.from_yaml_pos(position, msg)
if "include" in constraint:
constraints += (Include(constraint.get("include")),)
elif "any_of" in constraint:
choice_sets = ()
for constraint_list in constraint.get("any_of"):
inner_id_list = ()
if isinstance(constraint_list, CommentedSeq):
inner_id_list = tuple(
attr_constraint for attr_constraint in constraint_list
)
else:
inner_id_list += (constraint_list,)
choice_sets += (inner_id_list,)
any_of = AnyOf(choice_sets)
any_of._yaml_src_position = constraint.get("any_of").lc.data
constraints += (any_of,)
return constraints
| true | true |
f72c526d85a4169c9d8e5811a9e733fff90c8df8 | 3,136 | py | Python | gitea_api/models/issue_labels_option.py | r7l/python-gitea-api | 31d3dba27ea7e551e2048a1230c4ab4d73365006 | [
"MIT"
] | 1 | 2022-02-09T23:43:26.000Z | 2022-02-09T23:43:26.000Z | gitea_api/models/issue_labels_option.py | r7l/python-gitea-api | 31d3dba27ea7e551e2048a1230c4ab4d73365006 | [
"MIT"
] | null | null | null | gitea_api/models/issue_labels_option.py | r7l/python-gitea-api | 31d3dba27ea7e551e2048a1230c4ab4d73365006 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Gitea API.
This documentation describes the Gitea API. # noqa: E501
OpenAPI spec version: 1.16.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class IssueLabelsOption(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'labels': 'list[int]'
}
attribute_map = {
'labels': 'labels'
}
def __init__(self, labels=None): # noqa: E501
"""IssueLabelsOption - a model defined in Swagger""" # noqa: E501
self._labels = None
self.discriminator = None
if labels is not None:
self.labels = labels
@property
def labels(self):
"""Gets the labels of this IssueLabelsOption. # noqa: E501
list of label IDs # noqa: E501
:return: The labels of this IssueLabelsOption. # noqa: E501
:rtype: list[int]
"""
return self._labels
@labels.setter
def labels(self, labels):
"""Sets the labels of this IssueLabelsOption.
list of label IDs # noqa: E501
:param labels: The labels of this IssueLabelsOption. # noqa: E501
:type: list[int]
"""
self._labels = labels
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(IssueLabelsOption, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, IssueLabelsOption):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 27.752212 | 80 | 0.552934 |
import pprint
import re
import six
class IssueLabelsOption(object):
swagger_types = {
'labels': 'list[int]'
}
attribute_map = {
'labels': 'labels'
}
def __init__(self, labels=None):
self._labels = None
self.discriminator = None
if labels is not None:
self.labels = labels
@property
def labels(self):
return self._labels
@labels.setter
def labels(self, labels):
self._labels = labels
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(IssueLabelsOption, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, IssueLabelsOption):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c52cdd198823444e5eba59c73f88ccbadef74 | 3,334 | py | Python | benchmark/startCirq3299.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startCirq3299.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startCirq3299.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=45
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=9
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.Y.on(input_qubit[3])) # number=12
c.append(cirq.H.on(input_qubit[3])) # number=36
c.append(cirq.CZ.on(input_qubit[2],input_qubit[3])) # number=37
c.append(cirq.H.on(input_qubit[3])) # number=38
c.append(cirq.H.on(input_qubit[0])) # number=5
c.append(cirq.H.on(input_qubit[1])) # number=6
c.append(cirq.H.on(input_qubit[2])) # number=24
c.append(cirq.CZ.on(input_qubit[3],input_qubit[2])) # number=25
c.append(cirq.H.on(input_qubit[2])) # number=26
c.append(cirq.H.on(input_qubit[2])) # number=7
c.append(cirq.H.on(input_qubit[3])) # number=8
c.append(cirq.H.on(input_qubit[2])) # number=42
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=43
c.append(cirq.H.on(input_qubit[2])) # number=44
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=39
c.append(cirq.X.on(input_qubit[2])) # number=40
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=41
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=31
c.append(cirq.H.on(input_qubit[3])) # number=16
c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=17
c.append(cirq.H.on(input_qubit[3])) # number=18
c.append(cirq.X.on(input_qubit[3])) # number=14
c.append(cirq.H.on(input_qubit[3])) # number=32
c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=33
c.append(cirq.H.on(input_qubit[3])) # number=34
c.append(cirq.rx(-1.928937889304133).on(input_qubit[1])) # number=35
c.append(cirq.Y.on(input_qubit[2])) # number=10
c.append(cirq.Y.on(input_qubit[2])) # number=11
c.append(cirq.X.on(input_qubit[1])) # number=20
c.append(cirq.X.on(input_qubit[1])) # number=21
c.append(cirq.X.on(input_qubit[3])) # number=27
c.append(cirq.X.on(input_qubit[3])) # number=28
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq3299.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | 37.044444 | 77 | 0.678164 |
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
from cirq.contrib.svg import SVGCircuit
def make_circuit(n: int, input_qubit):
c = cirq.Circuit()
c.append(cirq.H.on(input_qubit[0]))
c.append(cirq.H.on(input_qubit[1]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.Y.on(input_qubit[3]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.CZ.on(input_qubit[2],input_qubit[3]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.H.on(input_qubit[0]))
c.append(cirq.H.on(input_qubit[1]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.CZ.on(input_qubit[3],input_qubit[2]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2]))
c.append(cirq.H.on(input_qubit[2]))
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2]))
c.append(cirq.X.on(input_qubit[2]))
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2]))
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.CZ.on(input_qubit[0],input_qubit[3]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.X.on(input_qubit[3]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.CZ.on(input_qubit[0],input_qubit[3]))
c.append(cirq.H.on(input_qubit[3]))
c.append(cirq.rx(-1.928937889304133).on(input_qubit[1]))
c.append(cirq.Y.on(input_qubit[2]))
c.append(cirq.Y.on(input_qubit[2]))
c.append(cirq.X.on(input_qubit[1]))
c.append(cirq.X.on(input_qubit[1]))
c.append(cirq.X.on(input_qubit[3]))
c.append(cirq.X.on(input_qubit[3]))
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq3299.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | true | true |
f72c52e95f901b6fd8527d85d0d774d80df5f455 | 842 | py | Python | zeeguu/api/api/teacher_dashboard/student_words.py | mircealungu/Zeeguu-API-2 | 1e8ea7f5dd0b883ed2d714b9324162b1a8edd170 | [
"MIT"
] | 8 | 2018-02-06T15:47:55.000Z | 2021-05-26T15:24:49.000Z | zeeguu/api/api/teacher_dashboard/student_words.py | mircealungu/Zeeguu-API-2 | 1e8ea7f5dd0b883ed2d714b9324162b1a8edd170 | [
"MIT"
] | 57 | 2018-02-02T19:54:38.000Z | 2021-07-15T15:45:15.000Z | zeeguu/api/api/teacher_dashboard/student_words.py | mircealungu/Zeeguu-API-2 | 1e8ea7f5dd0b883ed2d714b9324162b1a8edd170 | [
"MIT"
] | 13 | 2017-10-12T09:05:19.000Z | 2020-02-19T09:38:01.000Z | import zeeguu.core
from zeeguu.core.sql.learner.words import words_not_studied, learned_words
from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params
from .. import api, json_result, with_session
db = zeeguu.core.db
@api.route("/student_words_not_studied", methods=["POST"])
@with_session
def student_words_not_studied():
user, cohort, from_str, to_str = _get_student_cohort_and_period_from_POST_params()
stats = words_not_studied(user.id, cohort.language_id, from_str, to_str)
return json_result(stats)
@api.route("/student_learned_words", methods=["POST"])
@with_session
def student_learned_words():
user, cohort, from_date, to_date = _get_student_cohort_and_period_from_POST_params()
stats = learned_words(user.id, cohort.language_id, from_date, to_date)
return json_result(stats)
| 35.083333 | 88 | 0.800475 | import zeeguu.core
from zeeguu.core.sql.learner.words import words_not_studied, learned_words
from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params
from .. import api, json_result, with_session
db = zeeguu.core.db
@api.route("/student_words_not_studied", methods=["POST"])
@with_session
def student_words_not_studied():
user, cohort, from_str, to_str = _get_student_cohort_and_period_from_POST_params()
stats = words_not_studied(user.id, cohort.language_id, from_str, to_str)
return json_result(stats)
@api.route("/student_learned_words", methods=["POST"])
@with_session
def student_learned_words():
user, cohort, from_date, to_date = _get_student_cohort_and_period_from_POST_params()
stats = learned_words(user.id, cohort.language_id, from_date, to_date)
return json_result(stats)
| true | true |
f72c53192b9962222a935bcba714f77187770d13 | 186 | py | Python | Reliability_Tests/ex78.py | dieterch/dReliaCalc | 1e0a06e904f3a60527c3a6ae0f45c666a9b48128 | [
"MIT"
] | null | null | null | Reliability_Tests/ex78.py | dieterch/dReliaCalc | 1e0a06e904f3a60527c3a6ae0f45c666a9b48128 | [
"MIT"
] | null | null | null | Reliability_Tests/ex78.py | dieterch/dReliaCalc | 1e0a06e904f3a60527c3a6ae0f45c666a9b48128 | [
"MIT"
] | null | null | null | from reliability.Reliability_testing import one_sample_proportion
result = one_sample_proportion(trials=30, successes=29)
print(result)
'''
(0.8278305443665873, 0.9991564290733695)
'''
| 23.25 | 65 | 0.817204 | from reliability.Reliability_testing import one_sample_proportion
result = one_sample_proportion(trials=30, successes=29)
print(result)
| true | true |
f72c533b9f24bb347b96c3082d58404f5c3dff10 | 592 | py | Python | examples/display_feed_example.py | UniquePassive/randcam | 7c8dc977cfaf5eddb9b06f6280ab268526114d40 | [
"Apache-2.0"
] | 1 | 2018-06-04T04:10:06.000Z | 2018-06-04T04:10:06.000Z | examples/display_feed_example.py | UniquePassive/randcam | 7c8dc977cfaf5eddb9b06f6280ab268526114d40 | [
"Apache-2.0"
] | null | null | null | examples/display_feed_example.py | UniquePassive/randcam | 7c8dc977cfaf5eddb9b06f6280ab268526114d40 | [
"Apache-2.0"
] | 1 | 2018-06-04T04:10:07.000Z | 2018-06-04T04:10:07.000Z | import cv2
import binascii
from randcam import RandCam
with RandCam(0, True) as rc:
result, random = rc.seed()
while True:
result, image = rc.feed.read()
cv2.imshow('Captured Image', image)
key = cv2.waitKey(1)
# 'S' key - reseed
if key == ord('s'):
result, random = rc.seed()
# 'R' key - print random string
elif key == ord('r'):
byte_array = bytearray(random.getrandbits(8) for i in range(32))
print("random string: %s" % binascii.hexlify(byte_array).decode("utf-8"))
| 29.6 | 86 | 0.554054 | import cv2
import binascii
from randcam import RandCam
with RandCam(0, True) as rc:
result, random = rc.seed()
while True:
result, image = rc.feed.read()
cv2.imshow('Captured Image', image)
key = cv2.waitKey(1)
if key == ord('s'):
result, random = rc.seed()
elif key == ord('r'):
byte_array = bytearray(random.getrandbits(8) for i in range(32))
print("random string: %s" % binascii.hexlify(byte_array).decode("utf-8"))
| true | true |
f72c534e1699dc5a2e1677045e0d3915c236a50b | 12,873 | py | Python | info_summary/get_summary_pdf.py | Dangaran/home_station_project | 890b342e79e3dd493a8f418ed9283f0d444e5073 | [
"CC0-1.0"
] | null | null | null | info_summary/get_summary_pdf.py | Dangaran/home_station_project | 890b342e79e3dd493a8f418ed9283f0d444e5073 | [
"CC0-1.0"
] | null | null | null | info_summary/get_summary_pdf.py | Dangaran/home_station_project | 890b342e79e3dd493a8f418ed9283f0d444e5073 | [
"CC0-1.0"
] | null | null | null | import requests
import pandas as pd
from plotnine import *
import json
import time
from fpdf import FPDF
from datetime import datetime
# change pandas display options
pd.options.display.max_columns = 101
pd.options.display.max_rows = 200
pd.options.display.precision = 7
# get aemet and home information
last_day = {
'date_start': int(time.time()) - 86400,
'date_end': int(time.time())
}
response_aemet = requests.post('url_to_aws_lambda/get-aemet-data', json=last_day)
aemet_info = json.loads(response_aemet.text)
response_home = requests.post('url_to_aws_lambda/get-home-data', json=last_day)
home_info = json.loads(response_home.text)
# merge dataframes
aemet_info_df = pd.DataFrame(aemet_info)
aemet_info_df.sort_values(by="timestamp", inplace=True)
home_info_df = pd.DataFrame(home_info)
home_info_df.sort_values(by="timestamp", inplace=True)
last_day_info = pd.merge(aemet_info_df, home_info_df, on='timestamp', suffixes=("_aemet", "_home"))
last_day_info = last_day_info.iloc[100:124, :]
# -----------------------------------------------------------
#
# TEMPERATURE ANALYSIS
#
# -----------------------------------------------------------
# prepare data for plotting
home_temp_threshold = 20
# transform hour column to string and sort them
last_day_info['hour'] = last_day_info['hour'].astype(str)
last_day_info['hour'] = pd.Categorical(last_day_info['hour'], categories=last_day_info['hour'])
# melt data to plot temperatures
temp_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['thermal_sensation', 'temperature_aemet', 'temperature_home'], var_name='temp_loc', value_name='temp_value')
# change temp_loc to more readable strings for plotting
temp_data_to_plot['temp_loc'].replace({'thermal_sensation': 'Thermal sensation (outside)',
'temperature_aemet': 'Temperature (outside)',
'temperature_home': 'Temperature (home)',}, inplace=True)
# get home data
home_temp_plot = temp_data_to_plot.loc[temp_data_to_plot.temp_loc == 'Temperature (home)', :]
# make the plot
temp_plot = ggplot(temp_data_to_plot, aes(x = 'hour', y = 'temp_value', color = 'temp_loc', group = 'temp_loc')) +\
geom_line() +\
geom_point(size = .5) +\
geom_point(aes(x='hour', y='temp_value'), size = .5, color = ['#FF6633' if value <= home_temp_threshold else '#64f564' for value in list(home_temp_plot['temp_value'])], data = home_temp_plot) +\
geom_hline(aes(yintercept= home_temp_threshold), size = 1, linetype = 'dotted', alpha = .2) +\
labs(title = 'Differences in temperature between outside and inside your house', x = 'Hour', y = 'Temperature (ºC)', color='') +\
scale_color_manual(values = ['#64f564', '#e6454a', '#6bb8ff']) +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 10))
ggsave(plot=temp_plot, filename='./today_plots/temp_plot.png', dpi=100)
# -----------------------------------------------------------
#
# HUMIDITY ANALYSIS
#
# -----------------------------------------------------------
# prepare plot
hum_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['humidity_home', 'humidity_aemet'], var_name='hum_loc', value_name='hum_value')
hum_data_to_plot.hum_value = pd.to_numeric(hum_data_to_plot.hum_value, errors = 'raise')
hum_data_to_plot['hum_loc'].replace({'humidity_aemet': 'Humidity (outside)',
'humidity_home': 'Humidity (home)',}, inplace=True)
# create the plot
hum_plot = ggplot(hum_data_to_plot, aes(x = 'hour', y = 'hum_value', fill = 'hum_loc')) +\
geom_bar(stat = 'identity', position='dodge', color = 'grey') +\
labs(title = 'Differences in humidity between outside and inside your house', x = 'Hour', y = 'Relative humidity (%)', fill='') +\
scale_fill_manual(values = ['#9da6d4', '#4f66e0']) +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 10))
ggsave(plot=hum_plot, filename='./today_plots/hum_plot.png', dpi=100)
# -----------------------------------------------------------
#
# WIND ANALYSIS
#
# -----------------------------------------------------------
# Wind information
# avg and max speed
avg_wind_speed = round(last_day_info.avg_wind_speed.apply(lambda x: int(x)).mean(), 2)
max_wind_speed = round(last_day_info.max_wind_speed.apply(lambda x: int(x)).max(), 2)
# prepare plot
# count number of cardinal directions
cardinal_dir_list = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO']
wind_dir_df = last_day_info.wind_direction.value_counts().to_frame()
wind_dir_df.reset_index(inplace =True)
wind_dir_df.rename(columns = {'index': 'cardinal_direction'}, inplace = True)
wind_dir_df
# complete cardinal column
missing_dir = list(set(cardinal_dir_list) - set(wind_dir_df.cardinal_direction.to_list()))
for direction in missing_dir:
wind_dir_df = wind_dir_df.append({'cardinal_direction': direction,
'wind_direction': 0}, ignore_index=True)
wind_dir_df
# create column with correct order to plot
wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_direction').reset_index(drop = True)
wind_dir_df['cardinal_order'] = [2, 0, 1, 7, 6, 4, 3, 5]
wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_order')
wind_dir_df.index = wind_dir_df.cardinal_order
# create x and y axis
wind_dir_df['x_axis'] = [0,
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'E', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']),
0,
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'O', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])]
wind_dir_df['y_axis'] = [int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'N', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']),
0,
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'S', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']),
0,
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])]
# remove 0 columns to plot
wind_dir_df = wind_dir_df.loc[wind_dir_df.wind_direction != 0, :]
# create the plot
wind_plot = ggplot(aes(x = 'x_axis', y = 'y_axis'), wind_dir_df) +\
geom_point(size = .3, color = 'darkgreen') +\
geom_polygon(alpha = .2) +\
xlim(-24, 24) +\
ylim(-24, 24) +\
geom_segment(aes(x=0, xend=22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=-22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=0, y=0, yend=22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=0, y=0, yend=-22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
annotate('text', x=23, y= 0, label = 'E', color = 'darkgreen') +\
annotate('text', x=-23.3, y= 0, label = 'O', color = 'darkgreen') +\
annotate('text', x=0, y= 24, label = 'N', color = 'darkgreen') +\
annotate('text', x=0, y= -24, label = 'S', color = 'darkgreen') +\
labs(title = 'Wind direction over the last 24 hours', x = '', y = '') +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 15),
panel_grid_major = element_blank(),
panel_grid_minor = element_blank(),
panel_background = element_blank(),
axis_line = element_blank(),
axis_ticks_major = element_blank(),
axis_text = element_blank())
ggsave(plot=wind_plot, filename='./today_plots/wind_plot.png', dpi=100)
# -----------------------------------------------------------
#
# SKY ANALYSIS
#
# -----------------------------------------------------------
most_common_sky = last_day_info.sky_condition.value_counts().idxmax()
snow_probability = round(last_day_info.snow_probability.apply(lambda x: int(x)).mean(), 2)
precipitation_probability = round(last_day_info.precipitation_probability.apply(lambda x: int(x)).mean(), 2)
most_common_warning_lvl = last_day_info.warning_level.value_counts().idxmax()
total_precipitation = round(last_day_info.precipitation.apply(lambda x: int(x)).sum(), 2)
# -----------------------------------------------------------
#
# PEOPLE ANALYSIS
#
# -----------------------------------------------------------
# Check number of people
people_df = last_day_info.loc[:, ['hour', 'pic_name']]
people_df.pic_name = people_df.pic_name.fillna('No_0_data')
people_df['people_count'] = people_df.pic_name.apply(lambda x: int(x.split('_')[1]))
hours_with_people_at_home = people_df.loc[people_df.people_count > 0].shape[0]
most_people_in_room = people_df.people_count.value_counts(ascending = True).index[0]
rows_with_most_people = people_df.loc[people_df.people_count == most_people_in_room]
hours_with_most_people = rows_with_most_people.hour.to_list()
pics_names = rows_with_most_people.pic_name.to_list()
# -----------------------------------------------------------
#
# PDF CREATION
#
# -----------------------------------------------------------
# export information in pdf
# extract date
today_timestamp = int(last_day_info.timestamp.reset_index(drop =True)[5])
today_date = datetime.utcfromtimestamp(today_timestamp).strftime('%d/%m/%Y')
# create pdf to export
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 5)
pdf.set_font('arial', 'B', 12)
pdf.cell(0, 10, 'Home report from {}'.format(today_date), 0, 2, 'C') # title
pdf.cell(5)
# subtitle
pdf.set_font('arial', '', 10)
pdf.cell(0, 10, 'This report was extracted from the information gathered by the sensors from your Raspberry and Aemet.', 0, 2, 'C')
pdf.set_font('arial', 'B', 12)
# First analysis - Temperature and Humidity
pdf.cell(60, 10, 'Temperature Analysis:', 0, 0, 'R')
pdf.cell(85, 10, 'Humidity Analysis:', 0, 2, 'R')
pdf.image('./today_plots/temp_plot.png', x = 3, y = 35, w = 110, h = 70, type = '', link = '')
pdf.image('./today_plots/hum_plot.png', x = 110, y = 35, w = 100, h = 70, type = '', link = '')
# second analysis - Sky and wind
pdf.set_x(60)
pdf.set_y(110)
pdf.cell(0, 10, 'Sky Analysis:', 0, 2, 'L')
pdf.set_font('arial', '', 10)
pdf.cell(0, 7, 'Most common sky in 24 hours: {}'.format(most_common_sky), 0, 2, 'L')
pdf.cell(0, 7, 'Most common warning level in 24 hours: {}'.format(most_common_warning_lvl), 0, 2, 'L')
pdf.cell(0, 7, 'Probability of Precipitation in 24 hours: {} %'.format(precipitation_probability), 0, 2, 'L')
pdf.cell(0, 7, 'Probability of Snow in 24 hours: {} %'.format(snow_probability), 0, 2, 'L')
pdf.cell(0, 7, 'Total Precipitation in 24 hours: {} mm'.format(total_precipitation), 0, 2, 'L')
pdf.image('./today_plots/wind_plot.png', x = 110, y = 112, w = 70, h = 60, type = '', link = '')
# third analysis - Pictures from people
pdf.set_y(170)
pdf.set_font('arial', 'B', 12)
pdf.cell(0, 10, 'Camera Analysis:', 0, 2, 'L')
pdf.set_font('arial', '', 10)
pdf.cell(0, 7, 'Number of hours with people at home: {}'.format(hours_with_people_at_home), 0, 2, 'L')
pdf.cell(0, 7, 'How many people were in the room at the time of maximum capacity?: {}'.format(most_people_in_room), 0, 2, 'L')
pdf.cell(0, 7, 'How many hours was the house with the maximum number of people?: {}'.format(rows_with_most_people.shape[0]), 0, 2, 'L')
pdf.cell(0, 7, 'What were the hours when the house had the maximum number of people?: {}'.format(', '.join(hours_with_most_people)), 0, 2, 'L')
pdf.cell(0, 7, 'What are the pictura names that correspond to those hours?: {}'.format(', '.join(pics_names)), 0, 2, 'L')
pdf.image('../rapsberry/camera/images/{}'.format(pics_names[0]), x = 15, y = 200, w = 70, h = 60, type = '', link = '')
# save output
pdf.output('test.pdf', 'F')
| 45.487633 | 210 | 0.607395 | import requests
import pandas as pd
from plotnine import *
import json
import time
from fpdf import FPDF
from datetime import datetime
pd.options.display.max_columns = 101
pd.options.display.max_rows = 200
pd.options.display.precision = 7
last_day = {
'date_start': int(time.time()) - 86400,
'date_end': int(time.time())
}
response_aemet = requests.post('url_to_aws_lambda/get-aemet-data', json=last_day)
aemet_info = json.loads(response_aemet.text)
response_home = requests.post('url_to_aws_lambda/get-home-data', json=last_day)
home_info = json.loads(response_home.text)
aemet_info_df = pd.DataFrame(aemet_info)
aemet_info_df.sort_values(by="timestamp", inplace=True)
home_info_df = pd.DataFrame(home_info)
home_info_df.sort_values(by="timestamp", inplace=True)
last_day_info = pd.merge(aemet_info_df, home_info_df, on='timestamp', suffixes=("_aemet", "_home"))
last_day_info = last_day_info.iloc[100:124, :]
home_temp_threshold = 20
last_day_info['hour'] = last_day_info['hour'].astype(str)
last_day_info['hour'] = pd.Categorical(last_day_info['hour'], categories=last_day_info['hour'])
temp_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['thermal_sensation', 'temperature_aemet', 'temperature_home'], var_name='temp_loc', value_name='temp_value')
temp_data_to_plot['temp_loc'].replace({'thermal_sensation': 'Thermal sensation (outside)',
'temperature_aemet': 'Temperature (outside)',
'temperature_home': 'Temperature (home)',}, inplace=True)
home_temp_plot = temp_data_to_plot.loc[temp_data_to_plot.temp_loc == 'Temperature (home)', :]
temp_plot = ggplot(temp_data_to_plot, aes(x = 'hour', y = 'temp_value', color = 'temp_loc', group = 'temp_loc')) +\
geom_line() +\
geom_point(size = .5) +\
geom_point(aes(x='hour', y='temp_value'), size = .5, color = ['#FF6633' if value <= home_temp_threshold else '#64f564' for value in list(home_temp_plot['temp_value'])], data = home_temp_plot) +\
geom_hline(aes(yintercept= home_temp_threshold), size = 1, linetype = 'dotted', alpha = .2) +\
labs(title = 'Differences in temperature between outside and inside your house', x = 'Hour', y = 'Temperature (ºC)', color='') +\
scale_color_manual(values = ['#64f564', '#e6454a', '#6bb8ff']) +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 10))
ggsave(plot=temp_plot, filename='./today_plots/temp_plot.png', dpi=100)
hum_data_to_plot = last_day_info.melt(id_vars=['hour'], value_vars=['humidity_home', 'humidity_aemet'], var_name='hum_loc', value_name='hum_value')
hum_data_to_plot.hum_value = pd.to_numeric(hum_data_to_plot.hum_value, errors = 'raise')
hum_data_to_plot['hum_loc'].replace({'humidity_aemet': 'Humidity (outside)',
'humidity_home': 'Humidity (home)',}, inplace=True)
hum_plot = ggplot(hum_data_to_plot, aes(x = 'hour', y = 'hum_value', fill = 'hum_loc')) +\
geom_bar(stat = 'identity', position='dodge', color = 'grey') +\
labs(title = 'Differences in humidity between outside and inside your house', x = 'Hour', y = 'Relative humidity (%)', fill='') +\
scale_fill_manual(values = ['#9da6d4', '#4f66e0']) +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 10))
ggsave(plot=hum_plot, filename='./today_plots/hum_plot.png', dpi=100)
avg_wind_speed = round(last_day_info.avg_wind_speed.apply(lambda x: int(x)).mean(), 2)
max_wind_speed = round(last_day_info.max_wind_speed.apply(lambda x: int(x)).max(), 2)
cardinal_dir_list = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO']
wind_dir_df = last_day_info.wind_direction.value_counts().to_frame()
wind_dir_df.reset_index(inplace =True)
wind_dir_df.rename(columns = {'index': 'cardinal_direction'}, inplace = True)
wind_dir_df
missing_dir = list(set(cardinal_dir_list) - set(wind_dir_df.cardinal_direction.to_list()))
for direction in missing_dir:
wind_dir_df = wind_dir_df.append({'cardinal_direction': direction,
'wind_direction': 0}, ignore_index=True)
wind_dir_df
wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_direction').reset_index(drop = True)
wind_dir_df['cardinal_order'] = [2, 0, 1, 7, 6, 4, 3, 5]
wind_dir_df = wind_dir_df.sort_values(by = 'cardinal_order')
wind_dir_df.index = wind_dir_df.cardinal_order
wind_dir_df['x_axis'] = [0,
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'E', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']),
0,
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'O', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])]
wind_dir_df['y_axis'] = [int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'N', 'wind_direction']),
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NE', 'wind_direction']),
0,
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SE', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'S', 'wind_direction']),
int(-wind_dir_df.loc[wind_dir_df.cardinal_direction == 'SO', 'wind_direction']),
0,
int(wind_dir_df.loc[wind_dir_df.cardinal_direction == 'NO', 'wind_direction'])]
wind_dir_df = wind_dir_df.loc[wind_dir_df.wind_direction != 0, :]
wind_plot = ggplot(aes(x = 'x_axis', y = 'y_axis'), wind_dir_df) +\
geom_point(size = .3, color = 'darkgreen') +\
geom_polygon(alpha = .2) +\
xlim(-24, 24) +\
ylim(-24, 24) +\
geom_segment(aes(x=0, xend=22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=-22, y=0, yend=0), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=0, y=0, yend=22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
geom_segment(aes(x=0, xend=0, y=0, yend=-22), alpha = 0.1, linetype = 'dotted', arrow = arrow()) +\
annotate('text', x=23, y= 0, label = 'E', color = 'darkgreen') +\
annotate('text', x=-23.3, y= 0, label = 'O', color = 'darkgreen') +\
annotate('text', x=0, y= 24, label = 'N', color = 'darkgreen') +\
annotate('text', x=0, y= -24, label = 'S', color = 'darkgreen') +\
labs(title = 'Wind direction over the last 24 hours', x = '', y = '') +\
theme_classic() +\
theme(plot_title=element_text(face='bold', ha= 'center', size = 15),
panel_grid_major = element_blank(),
panel_grid_minor = element_blank(),
panel_background = element_blank(),
axis_line = element_blank(),
axis_ticks_major = element_blank(),
axis_text = element_blank())
ggsave(plot=wind_plot, filename='./today_plots/wind_plot.png', dpi=100)
most_common_sky = last_day_info.sky_condition.value_counts().idxmax()
snow_probability = round(last_day_info.snow_probability.apply(lambda x: int(x)).mean(), 2)
precipitation_probability = round(last_day_info.precipitation_probability.apply(lambda x: int(x)).mean(), 2)
most_common_warning_lvl = last_day_info.warning_level.value_counts().idxmax()
total_precipitation = round(last_day_info.precipitation.apply(lambda x: int(x)).sum(), 2)
people_df = last_day_info.loc[:, ['hour', 'pic_name']]
people_df.pic_name = people_df.pic_name.fillna('No_0_data')
people_df['people_count'] = people_df.pic_name.apply(lambda x: int(x.split('_')[1]))
hours_with_people_at_home = people_df.loc[people_df.people_count > 0].shape[0]
most_people_in_room = people_df.people_count.value_counts(ascending = True).index[0]
rows_with_most_people = people_df.loc[people_df.people_count == most_people_in_room]
hours_with_most_people = rows_with_most_people.hour.to_list()
pics_names = rows_with_most_people.pic_name.to_list()
today_timestamp = int(last_day_info.timestamp.reset_index(drop =True)[5])
today_date = datetime.utcfromtimestamp(today_timestamp).strftime('%d/%m/%Y')
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 5)
pdf.set_font('arial', 'B', 12)
pdf.cell(0, 10, 'Home report from {}'.format(today_date), 0, 2, 'C')
pdf.cell(5)
pdf.set_font('arial', '', 10)
pdf.cell(0, 10, 'This report was extracted from the information gathered by the sensors from your Raspberry and Aemet.', 0, 2, 'C')
pdf.set_font('arial', 'B', 12)
pdf.cell(60, 10, 'Temperature Analysis:', 0, 0, 'R')
pdf.cell(85, 10, 'Humidity Analysis:', 0, 2, 'R')
pdf.image('./today_plots/temp_plot.png', x = 3, y = 35, w = 110, h = 70, type = '', link = '')
pdf.image('./today_plots/hum_plot.png', x = 110, y = 35, w = 100, h = 70, type = '', link = '')
pdf.set_x(60)
pdf.set_y(110)
pdf.cell(0, 10, 'Sky Analysis:', 0, 2, 'L')
pdf.set_font('arial', '', 10)
pdf.cell(0, 7, 'Most common sky in 24 hours: {}'.format(most_common_sky), 0, 2, 'L')
pdf.cell(0, 7, 'Most common warning level in 24 hours: {}'.format(most_common_warning_lvl), 0, 2, 'L')
pdf.cell(0, 7, 'Probability of Precipitation in 24 hours: {} %'.format(precipitation_probability), 0, 2, 'L')
pdf.cell(0, 7, 'Probability of Snow in 24 hours: {} %'.format(snow_probability), 0, 2, 'L')
pdf.cell(0, 7, 'Total Precipitation in 24 hours: {} mm'.format(total_precipitation), 0, 2, 'L')
pdf.image('./today_plots/wind_plot.png', x = 110, y = 112, w = 70, h = 60, type = '', link = '')
pdf.set_y(170)
pdf.set_font('arial', 'B', 12)
pdf.cell(0, 10, 'Camera Analysis:', 0, 2, 'L')
pdf.set_font('arial', '', 10)
pdf.cell(0, 7, 'Number of hours with people at home: {}'.format(hours_with_people_at_home), 0, 2, 'L')
pdf.cell(0, 7, 'How many people were in the room at the time of maximum capacity?: {}'.format(most_people_in_room), 0, 2, 'L')
pdf.cell(0, 7, 'How many hours was the house with the maximum number of people?: {}'.format(rows_with_most_people.shape[0]), 0, 2, 'L')
pdf.cell(0, 7, 'What were the hours when the house had the maximum number of people?: {}'.format(', '.join(hours_with_most_people)), 0, 2, 'L')
pdf.cell(0, 7, 'What are the pictura names that correspond to those hours?: {}'.format(', '.join(pics_names)), 0, 2, 'L')
pdf.image('../rapsberry/camera/images/{}'.format(pics_names[0]), x = 15, y = 200, w = 70, h = 60, type = '', link = '')
pdf.output('test.pdf', 'F')
| true | true |
f72c5491decdb5fc627448e653e80715d6890df3 | 473 | py | Python | duck/FlyBehavior.py | rinman24/headfirst-python | 1c6a12dc04475fae06e333a9abcdefee0bdda5d6 | [
"MIT"
] | null | null | null | duck/FlyBehavior.py | rinman24/headfirst-python | 1c6a12dc04475fae06e333a9abcdefee0bdda5d6 | [
"MIT"
] | null | null | null | duck/FlyBehavior.py | rinman24/headfirst-python | 1c6a12dc04475fae06e333a9abcdefee0bdda5d6 | [
"MIT"
] | null | null | null | from abc import ABC, abstractmethod
# abstract class
class FlyBehavior(ABC):
@staticmethod
@abstractmethod
def fly():
pass
# Concrete implementations
class FlyWithWings(FlyBehavior):
@staticmethod
def fly():
print("I'm flying!!")
class FlyNoWay(FlyBehavior):
@staticmethod
def fly():
print("I can't fly.")
class FlyWithRockets(FlyBehavior):
@staticmethod
def fly():
print("I'm flying with rockets!!")
| 18.92 | 42 | 0.649049 | from abc import ABC, abstractmethod
class FlyBehavior(ABC):
@staticmethod
@abstractmethod
def fly():
pass
class FlyWithWings(FlyBehavior):
@staticmethod
def fly():
print("I'm flying!!")
class FlyNoWay(FlyBehavior):
@staticmethod
def fly():
print("I can't fly.")
class FlyWithRockets(FlyBehavior):
@staticmethod
def fly():
print("I'm flying with rockets!!")
| true | true |
f72c564b609e2ec63105a6116e9ade4a3f942eae | 1,684 | py | Python | api/chat_api/migrations/0001_create_message_model.py | gda2048/ChatAPI | 6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189 | [
"MIT"
] | null | null | null | api/chat_api/migrations/0001_create_message_model.py | gda2048/ChatAPI | 6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189 | [
"MIT"
] | 5 | 2020-06-06T01:18:14.000Z | 2021-06-10T19:45:08.000Z | api/chat_api/migrations/0001_create_message_model.py | gda2048/ChatAPI | 6efab6fb5b9d1ff74b44075cd2d13cbb6cd06189 | [
"MIT"
] | null | null | null | # Generated by Django 2.2.5 on 2020-02-04 21:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.CharField(help_text='Содержание письма может быть максимум в 4095 символов', max_length=4095, verbose_name='Содержание сообщения')),
('subject', models.CharField(help_text='Тема сообщения может быть максимум в 255 символов', max_length=255, verbose_name='Тема сообщения')),
('is_read', models.BooleanField(default=False, verbose_name='Прочитано ли?')),
('creation_date', models.DateTimeField(auto_now=True, verbose_name='Дата создания')),
('receiver', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='got_messages', to=settings.AUTH_USER_MODEL, verbose_name='Получатель')),
('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='sent_messages', to=settings.AUTH_USER_MODEL, verbose_name='Создатель')),
],
options={
'verbose_name': 'Сообщение',
'verbose_name_plural': 'Сообщения',
'db_table': 'messages',
'ordering': ['-creation_date'],
},
),
]
| 46.777778 | 190 | 0.64905 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.CharField(help_text='Содержание письма может быть максимум в 4095 символов', max_length=4095, verbose_name='Содержание сообщения')),
('subject', models.CharField(help_text='Тема сообщения может быть максимум в 255 символов', max_length=255, verbose_name='Тема сообщения')),
('is_read', models.BooleanField(default=False, verbose_name='Прочитано ли?')),
('creation_date', models.DateTimeField(auto_now=True, verbose_name='Дата создания')),
('receiver', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='got_messages', to=settings.AUTH_USER_MODEL, verbose_name='Получатель')),
('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='sent_messages', to=settings.AUTH_USER_MODEL, verbose_name='Создатель')),
],
options={
'verbose_name': 'Сообщение',
'verbose_name_plural': 'Сообщения',
'db_table': 'messages',
'ordering': ['-creation_date'],
},
),
]
| true | true |
f72c5744bbab84a804af1d39c17f0245e4c8220a | 19,980 | py | Python | Tools/python37/Lib/textwrap.py | xxroot/android_universal | af2d8627182f936383d792c1f775d87da50f2f6d | [
"MIT"
] | 207 | 2018-10-01T08:53:01.000Z | 2022-03-14T12:15:54.000Z | Tools/python37/Lib/textwrap.py | xxroot/android_universal | af2d8627182f936383d792c1f775d87da50f2f6d | [
"MIT"
] | 8 | 2019-06-29T14:18:51.000Z | 2022-02-19T07:30:27.000Z | Tools/python37/Lib/textwrap.py | xxroot/android_universal | af2d8627182f936383d792c1f775d87da50f2f6d | [
"MIT"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | """Text wrapping and filling.
"""
# Copyright (C) 1999-2001 Gregory P. Ward.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Written by Greg Ward <gward@python.net>
import re
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
# Hardcode the recognized whitespace characters to the US-ASCII
# whitespace characters. The main reason for doing this is that
# some Unicode spaces (like \u00a0) are non-breaking whitespaces.
_whitespace = '\t\n\x0b\x0c\r '
class TextWrapper:
"""
Object for wrapping/filling text. The public interface consists of
the wrap() and fill() methods; the other methods are just there for
subclasses to override in order to tweak the default behaviour.
If you want to completely replace the main wrapping algorithm,
you'll probably have to override _wrap_chunks().
Several instance attributes control various aspects of wrapping:
width (default: 70)
the maximum width of wrapped lines (unless break_long_words
is false)
initial_indent (default: "")
string that will be prepended to the first line of wrapped
output. Counts towards the line's width.
subsequent_indent (default: "")
string that will be prepended to all lines save the first
of wrapped output; also counts towards each line's width.
expand_tabs (default: true)
Expand tabs in input text to spaces before further processing.
Each tab will become 0 .. 'tabsize' spaces, depending on its position
in its line. If false, each tab is treated as a single character.
tabsize (default: 8)
Expand tabs in input text to 0 .. 'tabsize' spaces, unless
'expand_tabs' is false.
replace_whitespace (default: true)
Replace all whitespace characters in the input text by spaces
after tab expansion. Note that if expand_tabs is false and
replace_whitespace is true, every tab will be converted to a
single space!
fix_sentence_endings (default: false)
Ensure that sentence-ending punctuation is always followed
by two spaces. Off by default because the algorithm is
(unavoidably) imperfect.
break_long_words (default: true)
Break words longer than 'width'. If false, those words will not
be broken, and some lines might be longer than 'width'.
break_on_hyphens (default: true)
Allow breaking hyphenated words. If true, wrapping will occur
preferably on whitespaces and right after hyphens part of
compound words.
drop_whitespace (default: true)
Drop leading and trailing whitespace from lines.
max_lines (default: None)
Truncate wrapped lines.
placeholder (default: ' [...]')
Append to the last line of truncated text.
"""
unicode_whitespace_trans = {}
uspace = ord(' ')
for x in _whitespace:
unicode_whitespace_trans[ord(x)] = uspace
# This funky little regex is just the trick for splitting
# text up into word-wrappable chunks. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
# (after stripping out empty strings).
word_punct = r'[\w!"\'&.,?]'
letter = r'[^\d\W]'
whitespace = r'[%s]' % re.escape(_whitespace)
nowhitespace = '[^' + whitespace[1:]
wordsep_re = re.compile(r'''
( # any whitespace
%(ws)s+
| # em-dash between words
(?<=%(wp)s) -{2,} (?=\w)
| # word, possibly hyphenated
%(nws)s+? (?:
# hyphenated word
-(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
(?= %(lt)s -? %(lt)s)
| # end of word
(?=%(ws)s|\Z)
| # em-dash
(?<=%(wp)s) (?=-{2,}\w)
)
)''' % {'wp': word_punct, 'lt': letter,
'ws': whitespace, 'nws': nowhitespace},
re.VERBOSE)
del word_punct, letter, nowhitespace
# This less funky little regex just split on recognized spaces. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
del whitespace
# XXX this is not locale- or charset-aware -- string.lowercase
# is US-ASCII only (and therefore English-only)
sentence_end_re = re.compile(r'[a-z]' # lowercase letter
r'[\.\!\?]' # sentence-ending punct.
r'[\"\']?' # optional end-of-quote
r'\Z') # end of chunk
def __init__(self,
width=70,
initial_indent="",
subsequent_indent="",
expand_tabs=True,
replace_whitespace=True,
fix_sentence_endings=False,
break_long_words=True,
drop_whitespace=True,
break_on_hyphens=True,
tabsize=8,
*,
max_lines=None,
placeholder=' [...]'):
self.width = width
self.initial_indent = initial_indent
self.subsequent_indent = subsequent_indent
self.expand_tabs = expand_tabs
self.replace_whitespace = replace_whitespace
self.fix_sentence_endings = fix_sentence_endings
self.break_long_words = break_long_words
self.drop_whitespace = drop_whitespace
self.break_on_hyphens = break_on_hyphens
self.tabsize = tabsize
self.max_lines = max_lines
self.placeholder = placeholder
# -- Private methods -----------------------------------------------
# (possibly useful for subclasses to override)
def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
becomes " foo bar baz".
"""
if self.expand_tabs:
text = text.expandtabs(self.tabsize)
if self.replace_whitespace:
text = text.translate(self.unicode_whitespace_trans)
return text
def _split(self, text):
"""_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
if break_on_hyphens is True, or in:
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', option!'
otherwise.
"""
if self.break_on_hyphens is True:
chunks = self.wordsep_re.split(text)
else:
chunks = self.wordsep_simple_re.split(text)
chunks = [c for c in chunks if c]
return chunks
def _fix_sentence_endings(self, chunks):
"""_fix_sentence_endings(chunks : [string])
Correct for sentence endings buried in 'chunks'. Eg. when the
original text contains "... foo.\\nBar ...", munge_whitespace()
and split() will convert that to [..., "foo.", " ", "Bar", ...]
which has one too few spaces; this method simply changes the one
space to two.
"""
i = 0
patsearch = self.sentence_end_re.search
while i < len(chunks)-1:
if chunks[i+1] == " " and patsearch(chunks[i]):
chunks[i+1] = " "
i += 2
else:
i += 1
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any line.
"""
# Figure out when indent is larger than the specified width, and make
# sure at least one character is stripped off on every pass
if width < 1:
space_left = 1
else:
space_left = width - cur_len
# If we're allowed to break long words, then do so: put as much
# of the next chunk onto the current line as will fit.
if self.break_long_words:
cur_line.append(reversed_chunks[-1][:space_left])
reversed_chunks[-1] = reversed_chunks[-1][space_left:]
# Otherwise, we have to preserve the long word intact. Only add
# it to the current line if there's nothing already there --
# that minimizes how much we violate the width constraint.
elif not cur_line:
cur_line.append(reversed_chunks.pop())
# If we're not allowed to break long words, and there's already
# text on the current line, do nothing. Next time through the
# main loop of _wrap_chunks(), we'll wind up here again, but
# cur_len will be zero, so the next line will be entirely
# devoted to the long word that we can't handle right now.
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is
indivisible (modulo 'break_long_words'), but a line break can
come between any two chunks. Chunks should not have internal
whitespace; ie. a chunk is either all whitespace or a "word".
Whitespace chunks will be removed from the beginning and end of
lines, but apart from that whitespace is preserved.
"""
lines = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
if self.max_lines is not None:
if self.max_lines > 1:
indent = self.subsequent_indent
else:
indent = self.initial_indent
if len(indent) + len(self.placeholder.lstrip()) > self.width:
raise ValueError("placeholder too large for max width")
# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks.
chunks.reverse()
while chunks:
# Start the list of chunks that will make up the current line.
# cur_len is just the length of all the chunks in cur_line.
cur_line = []
cur_len = 0
# Figure out which static string will prefix this line.
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
# Maximum width for this line.
width = self.width - len(indent)
# First chunk on line is whitespace -- drop it, unless this
# is the very beginning of the text (ie. no lines started yet).
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1]
while chunks:
l = len(chunks[-1])
# Can at least squeeze this chunk onto the current line.
if cur_len + l <= width:
cur_line.append(chunks.pop())
cur_len += l
# Nope, this line is full.
else:
break
# The current line is full, and the next chunk is too big to
# fit on *any* line (not just this one).
if chunks and len(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
cur_len = sum(map(len, cur_line))
# If the last chunk on this line is all whitespace, drop it.
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
cur_len -= len(cur_line[-1])
del cur_line[-1]
if cur_line:
if (self.max_lines is None or
len(lines) + 1 < self.max_lines or
(not chunks or
self.drop_whitespace and
len(chunks) == 1 and
not chunks[0].strip()) and cur_len <= width):
# Convert current line back to a string and store it in
# list of all lines (return value).
lines.append(indent + ''.join(cur_line))
else:
while cur_line:
if (cur_line[-1].strip() and
cur_len + len(self.placeholder) <= width):
cur_line.append(self.placeholder)
lines.append(indent + ''.join(cur_line))
break
cur_len -= len(cur_line[-1])
del cur_line[-1]
else:
if lines:
prev_line = lines[-1].rstrip()
if (len(prev_line) + len(self.placeholder) <=
self.width):
lines[-1] = prev_line + self.placeholder
break
lines.append(indent + self.placeholder.lstrip())
break
return lines
def _split_chunks(self, text):
text = self._munge_whitespace(text)
return self._split(text)
# -- Public interface ----------------------------------------------
def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space.
"""
chunks = self._split_chunks(text)
if self.fix_sentence_endings:
self._fix_sentence_endings(chunks)
return self._wrap_chunks(chunks)
def fill(self, text):
"""fill(text : string) -> string
Reformat the single paragraph in 'text' to fit in lines of no
more than 'self.width' columns, and return a new string
containing the entire wrapped paragraph.
"""
return "\n".join(self.wrap(text))
# -- Convenience interface ---------------------------------------------
def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
def fill(text, width=70, **kwargs):
"""Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.fill(text)
def shorten(text, width, **kwargs):
"""Collapse and truncate the given text to fit in the given width.
The text first has its whitespace collapsed. If it then fits in
the *width*, it is returned as is. Otherwise, as many words
as possible are joined and then the placeholder is appended::
>>> textwrap.shorten("Hello world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello world!", width=11)
'Hello [...]'
"""
w = TextWrapper(width=width, max_lines=1, **kwargs)
return w.fill(' '.join(text.strip().split()))
# -- Loosely related functionality -------------------------------------
_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
def dedent(text):
"""Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\\thello" are
considered to have no common leading whitespace. (This behaviour is
new in Python 2.5; older versions of this module incorrectly
expanded tabs before searching for common leading whitespace.)
"""
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
# Current line more deeply indented than previous winner:
# no change (previous winner is still on top).
elif indent.startswith(margin):
pass
# Current line consistent with and no deeper than previous winner:
# it's the new winner.
elif margin.startswith(indent):
margin = indent
# Find the largest common whitespace between current line and previous
# winner.
else:
for i, (x, y) in enumerate(zip(margin, indent)):
if x != y:
margin = margin[:i]
break
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split("\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(r'(?m)^' + margin, '', text)
return text
def indent(text, prefix, predicate=None):
"""Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
"""
if predicate is None:
def predicate(line):
return line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
if __name__ == "__main__":
#print dedent("\tfoo\n\tbar")
#print dedent(" \thello there\n \t how are you?")
print(dedent("Hello there.\n This is indented."))
| 41.026694 | 81 | 0.565716 |
import re
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
_whitespace = '\t\n\x0b\x0c\r '
class TextWrapper:
unicode_whitespace_trans = {}
uspace = ord(' ')
for x in _whitespace:
unicode_whitespace_trans[ord(x)] = uspace
word_punct = r'[\w!"\'&.,?]'
letter = r'[^\d\W]'
whitespace = r'[%s]' % re.escape(_whitespace)
nowhitespace = '[^' + whitespace[1:]
wordsep_re = re.compile(r'''
( # any whitespace
%(ws)s+
| # em-dash between words
(?<=%(wp)s) -{2,} (?=\w)
| # word, possibly hyphenated
%(nws)s+? (?:
# hyphenated word
-(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
(?= %(lt)s -? %(lt)s)
| # end of word
(?=%(ws)s|\Z)
| # em-dash
(?<=%(wp)s) (?=-{2,}\w)
)
)''' % {'wp': word_punct, 'lt': letter,
'ws': whitespace, 'nws': nowhitespace},
re.VERBOSE)
del word_punct, letter, nowhitespace
# This less funky little regex just split on recognized spaces. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
del whitespace
# XXX this is not locale- or charset-aware -- string.lowercase
# is US-ASCII only (and therefore English-only)
sentence_end_re = re.compile(r'[a-z]' # lowercase letter
r'[\.\!\?]' # sentence-ending punct.
r'[\"\']?'
r'\Z')
def __init__(self,
width=70,
initial_indent="",
subsequent_indent="",
expand_tabs=True,
replace_whitespace=True,
fix_sentence_endings=False,
break_long_words=True,
drop_whitespace=True,
break_on_hyphens=True,
tabsize=8,
*,
max_lines=None,
placeholder=' [...]'):
self.width = width
self.initial_indent = initial_indent
self.subsequent_indent = subsequent_indent
self.expand_tabs = expand_tabs
self.replace_whitespace = replace_whitespace
self.fix_sentence_endings = fix_sentence_endings
self.break_long_words = break_long_words
self.drop_whitespace = drop_whitespace
self.break_on_hyphens = break_on_hyphens
self.tabsize = tabsize
self.max_lines = max_lines
self.placeholder = placeholder
def _munge_whitespace(self, text):
if self.expand_tabs:
text = text.expandtabs(self.tabsize)
if self.replace_whitespace:
text = text.translate(self.unicode_whitespace_trans)
return text
def _split(self, text):
if self.break_on_hyphens is True:
chunks = self.wordsep_re.split(text)
else:
chunks = self.wordsep_simple_re.split(text)
chunks = [c for c in chunks if c]
return chunks
def _fix_sentence_endings(self, chunks):
i = 0
patsearch = self.sentence_end_re.search
while i < len(chunks)-1:
if chunks[i+1] == " " and patsearch(chunks[i]):
chunks[i+1] = " "
i += 2
else:
i += 1
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
if width < 1:
space_left = 1
else:
space_left = width - cur_len
# of the next chunk onto the current line as will fit.
if self.break_long_words:
cur_line.append(reversed_chunks[-1][:space_left])
reversed_chunks[-1] = reversed_chunks[-1][space_left:]
# Otherwise, we have to preserve the long word intact. Only add
# it to the current line if there's nothing already there --
elif not cur_line:
cur_line.append(reversed_chunks.pop())
# cur_len will be zero, so the next line will be entirely
# devoted to the long word that we can't handle right now.
def _wrap_chunks(self, chunks):
lines = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
if self.max_lines is not None:
if self.max_lines > 1:
indent = self.subsequent_indent
else:
indent = self.initial_indent
if len(indent) + len(self.placeholder.lstrip()) > self.width:
raise ValueError("placeholder too large for max width")
chunks.reverse()
while chunks:
cur_line = []
cur_len = 0
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
width = self.width - len(indent)
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1]
while chunks:
l = len(chunks[-1])
if cur_len + l <= width:
cur_line.append(chunks.pop())
cur_len += l
else:
break
if chunks and len(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
cur_len = sum(map(len, cur_line))
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
cur_len -= len(cur_line[-1])
del cur_line[-1]
if cur_line:
if (self.max_lines is None or
len(lines) + 1 < self.max_lines or
(not chunks or
self.drop_whitespace and
len(chunks) == 1 and
not chunks[0].strip()) and cur_len <= width):
lines.append(indent + ''.join(cur_line))
else:
while cur_line:
if (cur_line[-1].strip() and
cur_len + len(self.placeholder) <= width):
cur_line.append(self.placeholder)
lines.append(indent + ''.join(cur_line))
break
cur_len -= len(cur_line[-1])
del cur_line[-1]
else:
if lines:
prev_line = lines[-1].rstrip()
if (len(prev_line) + len(self.placeholder) <=
self.width):
lines[-1] = prev_line + self.placeholder
break
lines.append(indent + self.placeholder.lstrip())
break
return lines
def _split_chunks(self, text):
text = self._munge_whitespace(text)
return self._split(text)
def wrap(self, text):
chunks = self._split_chunks(text)
if self.fix_sentence_endings:
self._fix_sentence_endings(chunks)
return self._wrap_chunks(chunks)
def fill(self, text):
return "\n".join(self.wrap(text))
def wrap(text, width=70, **kwargs):
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
def fill(text, width=70, **kwargs):
w = TextWrapper(width=width, **kwargs)
return w.fill(text)
def shorten(text, width, **kwargs):
w = TextWrapper(width=width, max_lines=1, **kwargs)
return w.fill(' '.join(text.strip().split()))
_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
def dedent(text):
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
elif indent.startswith(margin):
pass
elif margin.startswith(indent):
margin = indent
# Find the largest common whitespace between current line and previous
# winner.
else:
for i, (x, y) in enumerate(zip(margin, indent)):
if x != y:
margin = margin[:i]
break
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split("\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(r'(?m)^' + margin, '', text)
return text
def indent(text, prefix, predicate=None):
if predicate is None:
def predicate(line):
return line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
if __name__ == "__main__":
#print dedent("\tfoo\n\tbar")
#print dedent(" \thello there\n \t how are you?")
print(dedent("Hello there.\n This is indented."))
| true | true |
f72c596ca53720016e67120b1a4e92b4a9a60f51 | 2,775 | py | Python | training/utils/utils.py | Tbarkin121/Tensegrity_IsaacGym | 0b6b5227e76b18396862c242a4e8e743248844b3 | [
"MIT"
] | 317 | 2021-09-08T01:28:49.000Z | 2022-03-31T07:52:36.000Z | training/utils/utils.py | Tbarkin121/Tensegrity_IsaacGym | 0b6b5227e76b18396862c242a4e8e743248844b3 | [
"MIT"
] | 24 | 2021-11-05T14:15:47.000Z | 2022-03-31T11:58:18.000Z | training/utils/utils.py | Tbarkin121/Tensegrity_IsaacGym | 0b6b5227e76b18396862c242a4e8e743248844b3 | [
"MIT"
] | 58 | 2021-10-31T07:15:43.000Z | 2022-03-29T14:51:02.000Z | # Copyright (c) 2018-2021, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# python
import numpy as np
import torch
import random
import os
def set_np_formatting():
""" formats numpy print """
np.set_printoptions(edgeitems=30, infstr='inf',
linewidth=4000, nanstr='nan', precision=2,
suppress=False, threshold=10000, formatter=None)
def set_seed(seed, torch_deterministic=False):
""" set seed across modules """
if seed == -1 and torch_deterministic:
seed = 42
elif seed == -1:
seed = np.random.randint(0, 10000)
print("Setting seed: {}".format(seed))
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if torch_deterministic:
# refer to https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.use_deterministic_algorithms(True)
else:
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
return seed
# EOF
| 39.084507 | 91 | 0.728649 |
import numpy as np
import torch
import random
import os
def set_np_formatting():
np.set_printoptions(edgeitems=30, infstr='inf',
linewidth=4000, nanstr='nan', precision=2,
suppress=False, threshold=10000, formatter=None)
def set_seed(seed, torch_deterministic=False):
if seed == -1 and torch_deterministic:
seed = 42
elif seed == -1:
seed = np.random.randint(0, 10000)
print("Setting seed: {}".format(seed))
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if torch_deterministic:
S_WORKSPACE_CONFIG'] = ':4096:8'
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.use_deterministic_algorithms(True)
else:
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
return seed
| true | true |
f72c59b6c86d8d1a0d95172b56d5bdce1315051e | 32,056 | py | Python | scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py | klement/trex-core | b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e | [
"Apache-2.0"
] | 1 | 2020-09-06T00:58:34.000Z | 2020-09-06T00:58:34.000Z | scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py | klement/trex-core | b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e | [
"Apache-2.0"
] | null | null | null | scripts/automation/trex_control_plane/interactive/trex/console/trex_console.py | klement/trex-core | b98e2e6d2b8c6caeb233ce36fcbc131ffc45e35e | [
"Apache-2.0"
] | 1 | 2021-09-13T13:43:10.000Z | 2021-09-13T13:43:10.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Dan Klein, Itay Marom
Cisco Systems, Inc.
Copyright (c) 2015-2015 Cisco Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import print_function
import collections
import subprocess
import inspect
import cmd
import json
import argparse
import random
import readline
import string
import os
import sys
import tty, termios
from threading import Lock
from functools import wraps, partial
import threading
import atexit
import tempfile
if __package__ == None:
print("TRex console must be launched as a module")
sys.exit(1)
from ..stl.api import *
from ..astf.api import *
from ..common.trex_client import TRexClient
from ..utils.text_opts import *
from ..utils.common import user_input, get_current_user, set_window_always_on_top
from ..utils import parsing_opts
from .trex_capture import CaptureManager
from .plugins_mngr import PluginsManager
from . import trex_tui
__version__ = "3.0"
# readline.write_history_file can fail with IOError in Python2
def write_history_file(hist_file):
hist_end = readline.get_current_history_length()
hist_start = max(0, hist_end - readline.get_history_length())
with open(hist_file, 'w') as f:
for i in range(hist_start, hist_end):
f.write('%s\n' % readline.get_history_item(i + 1))
# console custom logger
class ConsoleLogger(Logger):
def __init__ (self):
Logger.__init__(self)
self.prompt_redraw = lambda: None
self.tid = threading.current_thread().ident
def _write (self, msg, newline = True):
# if printed from another thread - handle it specifcially
if threading.current_thread().ident != self.tid:
self._write_async(msg, newline)
else:
self._write_sync(msg, newline)
def _write_sync (self, msg, newline):
if newline:
print(msg)
else:
print(msg, end=' ')
def _write_async (self, msg, newline):
print('\n')
self._write_sync(msg, newline)
self.prompt_redraw()
self._flush()
def _flush (self):
sys.stdout.flush()
class TRexGeneralCmd(cmd.Cmd):
def __init__(self, client_mode):
cmd.Cmd.__init__(self)
# configure history behaviour
self._history_file_dir = "/tmp/trex/console/"
self._history_file = self.get_history_file_full_path(client_mode)
readline.set_history_length(100)
# load history, if any
self.load_console_history()
atexit.register(self.save_console_history)
def get_history_file_full_path(self, client_mode):
return "{dir}{filename}_{mode}.hist".format(dir=self._history_file_dir,
filename=self.get_console_identifier(),
mode=client_mode)
def load_console_history(self):
if os.path.exists(self._history_file):
readline.read_history_file(self._history_file)
return
def save_console_history(self):
if not os.path.exists(self._history_file_dir):
# make the directory available for every user
try:
original_umask = os.umask(0)
os.makedirs(self._history_file_dir, mode = 0o777)
finally:
os.umask(original_umask)
# os.mknod(self._history_file)
try:
write_history_file(self._history_file)
except BaseException as e:
print(bold('\nCould not save history file: %s\nError: %s\n' % (self._history_file, e)))
def print_history (self):
length = readline.get_current_history_length()
for i in range(1, length + 1):
cmd = readline.get_history_item(i)
print("{:<5} {:}".format(i, cmd))
def get_history_item (self, index):
length = readline.get_current_history_length()
if index > length:
print(format_text("please select an index between {0} and {1}".format(0, length)))
return None
return readline.get_history_item(index)
def emptyline(self):
"""Called when an empty line is entered in response to the prompt.
This overriding is such that when empty line is passed, **nothing happens**.
"""
return
def completenames(self, text, *ignored):
"""
This overriding is such that a space is added to name completion.
"""
dotext = 'do_'+text
return [a[3:]+' ' for a in self.get_names() if a.startswith(dotext)]
# main console object
class TRexConsole(TRexGeneralCmd):
"""Trex Console"""
def __init__(self, client, verbose = False):
# cmd lock is used to make sure background job
# of the console is not done while the user excutes commands
self.cmd_lock = Lock()
self.client = client
self.verbose = verbose
TRexGeneralCmd.__init__(self, client.get_mode())
self.plugins_mngr = PluginsManager(self)
self.intro = "\n-=TRex Console v{ver}=-\n".format(ver=__version__)
self.intro += "\nType 'help' or '?' for supported actions\n"
self.terminal = None
self.tui = trex_tui.TrexTUI(self)
self.cap_mngr = CaptureManager(client, self.cmd_lock)
self.load_client_console_functions()
self.postcmd(False, "")
################### internal section ########################
def verify_connected(f):
@wraps(f)
def wrap(*args):
inst = args[0]
func_name = f.__name__
if func_name.startswith("do_"):
func_name = func_name[3:]
if not inst.client.is_connected():
print(format_text("\n'{0}' cannot be executed on offline mode\n".format(func_name), 'bold'))
return
ret = f(*args)
return ret
return wrap
def history_preserver(self, func, line):
filename = self._push_history()
try:
func(line)
finally:
self._pop_history(filename)
def load_client_console_functions (self):
for cmd_name, cmd_func in self.client.get_console_methods().items():
# register the function and its help
if cmd_func.preserve_history:
f = partial(self.history_preserver, cmd_func)
f.__doc__ = cmd_func.__doc__
f.name = cmd_func.name
f.group = cmd_func.group
setattr(self.__class__, 'do_' + cmd_name, f)
else:
setattr(self.__class__, 'do_' + cmd_name, cmd_func)
setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h'))
def load_client_plugin_functions (self, client, func_prefix):
for cmd_name, cmd_func in client.get_plugin_methods().items():
cmd_name = func_prefix + cmd_name
# register the function and its help
if cmd_func.preserve_history:
f = partial(self.history_preserver, cmd_func)
f.__doc__ = cmd_func.__doc__
f.name = cmd_func.name
f.group = cmd_func.group
setattr(self.__class__, 'do_' + cmd_name, f)
else:
setattr(self.__class__, 'do_' + cmd_name, cmd_func)
setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h'))
def unload_client_plugin_functions (self, func_prefix):
do_func_pre, help_func_pre = 'do_%s' % func_prefix, 'help_%s' % func_prefix
for cmd_name, cmd_func in inspect.getmembers(self.__class__, predicate=inspect.ismethod):
if cmd_name.startswith(do_func_pre) or cmd_name.startswith(help_func_pre):
delattr(self.__class__, cmd_name)
def generate_prompt (self, prefix = 'trex'):
if not self.client.is_connected():
return "{0}(offline)>".format(prefix)
elif not self.client.get_acquired_ports():
return "{0}(read-only)>".format(prefix)
elif self.client.is_all_ports_acquired():
p = prefix
# HACK
service_ports = self.client.get_service_enabled_ports()
filtered_ports = self.client.get_service_filtered_ports()
if (self.client.get_mode() == "STL" or self.client.get_mode() == "ASTF") and (service_ports or filtered_ports):
if filtered_ports == self.client.get_acquired_ports():
p += '(service-filtered)'
elif service_ports == self.client.get_acquired_ports():
p += '(service)'
else:
p += '(service: {0})'.format(', '.join(map(str, service_ports)))
return "{0}>".format(p)
else:
return "{0} (ports: {1})>".format(prefix, ', '.join(map(str, self.client.get_acquired_ports())))
def prompt_redraw (self):
self.postcmd(False, "")
sys.stdout.write("\n" + self.prompt + readline.get_line_buffer())
sys.stdout.flush()
def get_console_identifier(self):
conn = self.client.get_connection_info()
return "%s_%s_%s_%s" % (get_current_user(), conn['server'], conn['sync_port'], conn['async_port'])
def register_main_console_methods(self):
main_names = set(self.trex_console.get_names()).difference(set(dir(self.__class__)))
for name in main_names:
for prefix in 'do_', 'help_', 'complete_':
if name.startswith(prefix):
self.__dict__[name] = getattr(self.trex_console, name)
def precmd(self, line):
lines = line.split(';')
try:
self.cmd_lock.acquire()
for line in lines:
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
if stop:
return "quit"
return ""
except KeyboardInterrupt:
print(bold('Interrupted by a keyboard signal (probably ctrl + c)'))
except TRexError as e:
print(e)
finally:
self.cmd_lock.release()
return ''
def postcmd(self, stop, line):
self.prompt = self.generate_prompt(prefix = 'trex')
return stop
def default(self, line):
print("'{0}' is an unrecognized command. type 'help' or '?' for a list\n".format(line))
@staticmethod
def tree_autocomplete(text):
dir = os.path.dirname(text)
if dir:
path = dir
else:
path = "."
start_string = os.path.basename(text)
targets = []
for x in os.listdir(path):
if x.startswith(start_string):
y = os.path.join(path, x)
if os.path.isfile(y):
targets.append(x + ' ')
elif os.path.isdir(y):
targets.append(x + '/')
return targets
####################### shell commands #######################
# set verbose on / off
def do_verbose(self, line):
'''Shows or set verbose mode\n'''
if line == "":
print("\nverbose is " + ("on\n" if self.verbose else "off\n"))
elif line == "on":
self.verbose = True
self.client.set_verbose("debug")
print(format_text("\nverbose set to on\n", 'green', 'bold'))
elif line == "off":
self.verbose = False
self.client.set_verbose("info")
print(format_text("\nverbose set to off\n", 'green', 'bold'))
else:
print(format_text("\nplease specify 'on' or 'off'\n", 'bold'))
# show history
def help_history (self):
self.do_history("-h")
def do_shell (self, line):
self.do_history(line)
def help_plugins(self):
self.do_plugins('-h')
@verify_connected
def do_capture (self, line):
'''Manage PCAP captures'''
self.cap_mngr.parse_line(line)
def help_capture (self):
self.do_capture("-h")
# save current history to a temp file
def _push_history(self):
tmp_file = tempfile.NamedTemporaryFile()
write_history_file(tmp_file.name)
readline.clear_history()
return tmp_file
# restore history from a temp file
def _pop_history(self, tmp_file):
readline.clear_history()
readline.read_history_file(tmp_file.name)
tmp_file.close()
def do_debug(self, line):
'''Internal debugger for development.
Requires IPython module installed
'''
parser = parsing_opts.gen_parser(self.client,
"debug",
self.do_debug.__doc__)
opts = parser.parse_args(line.split())
try:
from IPython.terminal.ipapp import load_default_config
from IPython.terminal.embed import InteractiveShellEmbed
from IPython import embed
except ImportError:
embed = None
if not embed:
try:
import code
except ImportError:
self.client.logger.info(format_text("\n*** 'IPython' and 'code' library are not available ***\n", 'bold'))
return
auto_completer = readline.get_completer()
console_history_file = self._push_history()
client = self.client
descr = 'IPython' if embed else "'code' library"
self.client.logger.info(format_text("\n*** Starting Python shell (%s)... use 'client' as client object, Ctrl + D to exit ***\n" % descr, 'bold'))
try:
if embed:
cfg = load_default_config()
cfg['TerminalInteractiveShell']['confirm_exit'] = False
embed(config = cfg, display_banner = False)
#InteractiveShellEmbed.clear_instance()
else:
ns = {}
ns.update(globals())
ns.update(locals())
code.InteractiveConsole(ns).interact('')
finally:
readline.set_completer(auto_completer)
self._pop_history(console_history_file)
self.client.logger.info(format_text("\n*** Leaving Python shell ***\n"))
def do_history (self, line):
'''Manage the command history\n'''
item = parsing_opts.ArgumentPack(['item'],
{"nargs": '?',
'metavar': 'item',
'type': parsing_opts.check_negative,
'help': "an history item index",
'default': 0})
parser = parsing_opts.gen_parser(self.client,
"history",
self.do_history.__doc__,
item)
try:
opts = parser.parse_args(line.split())
except TRexError:
return
if opts.item == 0:
self.print_history()
else:
cmd = self.get_history_item(opts.item)
if cmd == None:
return
print("Executing '{0}'".format(cmd))
return self.onecmd(cmd)
def do_plugins(self, line):
'''Show / load / use plugins\n'''
self.plugins_mngr.do_plugins(line)
def complete_plugins(self, text, line, start_index, end_index):
return self.plugins_mngr.complete_plugins(text, line, start_index, end_index)
def complete_emu_load_profile(self, text, line, start_index, end_index):
return self.complete_start(text, line, start_index, end_index)
############### connect
def do_connect (self, line):
'''Connects to the server and acquire ports\n'''
self.client.connect_line(line)
def do_disconnect (self, line):
'''Disconnect from the server\n'''
# stop any monitors before disconnecting
self.plugins_mngr._unload_plugin()
self.cap_mngr.stop()
self.client.disconnect_line(line)
############### start
def complete_start(self, text, line, begidx, endidx):
s = line.split()
l = len(s)
file_flags = parsing_opts.get_flags(parsing_opts.FILE_PATH)
if (l > 1) and (s[l - 1] in file_flags):
return TRexConsole.tree_autocomplete("")
if (l > 2) and (s[l - 2] in file_flags):
return TRexConsole.tree_autocomplete(s[l - 1])
complete_push = complete_start
complete_hello = complete_start
def complete_profile(self, text, line, begidx, endidx):
return self.complete_start(text,line, begidx, endidx)
# tui
@verify_connected
def do_tui (self, line):
'''Shows a graphical console\n'''
parser = parsing_opts.gen_parser(self.client,
"tui",
self.do_tui.__doc__,
parsing_opts.XTERM,
parsing_opts.LOCKED)
try:
opts = parser.parse_args(line.split())
except TRexError:
return
if opts.xterm:
if not os.path.exists('/usr/bin/xterm'):
print(format_text("XTERM does not exists on this machine", 'bold'))
return
info = self.client.get_connection_info()
exe = './trex-console --top -t -q -s {0} -p {1} --async_port {2}'.format(info['server'], info['sync_port'], info['async_port'])
cmd = ['/usr/bin/xterm', '-geometry', '{0}x{1}'.format(self.tui.MIN_COLS, self.tui.MIN_ROWS), '-sl', '0', '-title', 'trex_tui', '-e', exe]
# detach child
self.terminal = subprocess.Popen(cmd, preexec_fn = os.setpgrp)
return
try:
with self.client.logger.supress(verbose = 'none'):
self.tui.show(self.client, self.save_console_history, locked = opts.locked)
except self.tui.ScreenSizeException as e:
print(format_text(str(e) + "\n", 'bold'))
def help_tui (self):
do_tui("-h")
# quit function
def do_quit(self, line):
'''Exit the console\n'''
return True
def do_help (self, line):
'''Shows This Help Screen\n'''
if line:
try:
func = getattr(self, 'help_' + line)
except AttributeError:
try:
doc = getattr(self, 'do_' + line).__doc__
if doc:
self.stdout.write("%s\n"%str(doc))
return
except AttributeError:
pass
self.stdout.write("%s\n"%str(self.nohelp % (line,)))
return
func()
return
cmds = [x[3:] for x in self.get_names() if x.startswith("do_")]
hidden = ['EOF', 'q', 'exit', 'h', 'shell']
categories = collections.defaultdict(list)
for cmd in cmds:
if cmd in hidden:
continue
category = getattr(getattr(self, 'do_' + cmd), 'group', 'basic')
categories[category].append(cmd)
# basic commands
if 'basic' in categories:
self._help_cmds('Console Commands', categories['basic'])
# common
if 'common' in categories:
self._help_cmds('Common Commands', categories['common'])
if 'STL' in categories:
self._help_cmds('Stateless Commands', categories['STL'])
if 'ASTF' in categories:
self._help_cmds('Advanced Stateful Commands', categories['ASTF'])
if 'emu' in categories:
self._help_cmds('Emulation Commands', categories['emu'])
def _help_cmds (self, title, cmds):
print(format_text("\n{0}:\n".format(title), 'bold', 'underline'))
for cmd in cmds:
try:
doc = getattr(self, 'do_' + cmd).__doc__
if doc:
help = str(doc)
else:
help = "*** Undocumented Function ***\n"
except AttributeError:
help = "*** Undocumented Function ***\n"
l=help.splitlines()
print("{:<30} {:<30}".format(cmd + " - ",l[0] ))
# a custorm cmdloop wrapper
def start(self):
try:
while True:
try:
self.cmdloop()
break
except KeyboardInterrupt as e:
if not readline.get_line_buffer():
raise KeyboardInterrupt
else:
print("")
self.intro = None
continue
finally:
# capture manager is not presistent - kill it before going out
self.plugins_mngr._unload_plugin()
self.cap_mngr.stop()
if self.terminal:
self.terminal.kill()
# aliases
do_exit = do_EOF = do_q = do_quit
do_h = do_history
# run a script of commands
def run_script_file(filename, client):
client.logger.info(format_text("\nRunning script file '{0}'...".format(filename), 'bold'))
with open(filename) as f:
script_lines = f.readlines()
# register all the commands
cmd_table = {}
for cmd_name, cmd_func in client.get_console_methods().items():
cmd_table[cmd_name] = cmd_func
for index, line in enumerate(script_lines, start = 1):
line = line.strip()
if line == "":
continue
if line.startswith("#"):
continue
sp = line.split(' ', 1)
cmd = sp[0]
if len(sp) == 2:
args = sp[1]
else:
args = ""
client.logger.info(format_text("Executing line {0} : '{1}'\n".format(index, line)))
if cmd not in cmd_table:
client.logger.error(format_text("Unknown command '%s', available commands are:\n%s" % (cmd, '\n'.join(sorted(cmd_table.keys()))), 'bold'))
return False
rc = cmd_table[cmd](args)
if isinstance(rc, RC) and not rc:
return False
client.logger.info(format_text("\n[Done]", 'bold'))
return True
#
def is_valid_file(filename):
if not os.path.isfile(filename):
raise argparse.ArgumentTypeError("The file '%s' does not exist" % filename)
return filename
def setParserOptions():
parser = argparse.ArgumentParser(prog="trex_console.py")
parser.add_argument("-s", "--server", help = "TRex Server [default is localhost]",
default = "localhost",
type = str)
parser.add_argument("-p", "--port", help = "TRex Server Port [default is 4501]\n",
default = 4501,
type = int)
parser.add_argument("--async_port", help = "TRex ASync Publisher Port [default is 4500]\n",
default = 4500,
dest='pub',
type = int)
parser.add_argument("-u", "--user", help = "User Name [default is currently logged in user]\n",
default = get_current_user(),
type = str)
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", help="Switch ON verbose option. Default is: OFF.",
default = False)
parser.add_argument( "--timeout",
dest="timeout",
help="timeout for ZMQ connection, the default is 3 sec, higher value will make it more resilient to Firewalls",
default = False,type = int)
group = parser.add_mutually_exclusive_group()
group.add_argument("-a", "--acquire", dest="acquire",
nargs = '+',
type = int,
help="Acquire ports on connect. default is all available ports",
default = None)
group.add_argument("-r", "--readonly", dest="readonly",
action="store_true",
help="Starts console in a read only mode",
default = False)
parser.add_argument("--emu", action="store_true",
help="Run emulation client on startup",
default = False)
parser.add_argument("--emu-server",
help="Emulation client server, default is TRex server address")
parser.add_argument("-f", "--force", dest="force",
action="store_true",
help="Force acquire the requested ports",
default = False)
parser.add_argument("--batch", dest="batch",
nargs = 1,
type = is_valid_file,
help = "Run the console in a batch mode with file",
default = None)
parser.add_argument("-t", "--tui", dest="tui",
action="store_true", help="Starts with TUI mode",
default = False)
parser.add_argument("-x", "--xtui", dest="xtui",
action="store_true", help="Starts with XTERM TUI mode",
default = False)
parser.add_argument("--top", dest="top",
action="store_true", help="Set the window as always on top",
default = False)
parser.add_argument("-q", "--quiet", dest="quiet",
action="store_true", help="Starts with all outputs suppressed",
default = False)
return parser
# a simple info printed on log on
def show_intro (logger, c):
modes = {'STL': 'Stateless', 'ASTF': 'Advanced Stateful'}
x = c.get_server_system_info()
ver = c.get_server_version().get('version', 'N/A')
mode = c.get_server_version().get('mode', 'N/A')
# find out which NICs the server has
port_types = {}
for port in x['ports']:
if 'supp_speeds' in port and port['supp_speeds']:
speed = max(port['supp_speeds']) // 1000
else:
speed = c.ports[port['index']].get_speed_gbps()
key = (speed, port.get('description', port['driver']))
if key not in port_types:
port_types[key] = 0
port_types[key] += 1
port_line = ''
for k, v in port_types.items():
port_line += "{0} x {1}Gbps @ {2}\t".format(v, k[0], k[1])
logger.info(format_text("\nServer Info:\n", 'underline'))
logger.info("Server version: {:>}".format(format_text(ver + ' @ ' + mode, 'bold')))
logger.info("Server mode: {:>}".format(format_text(modes.get(mode, 'N/A'), 'bold')))
logger.info("Server CPU: {:>}".format(format_text("{:>} x {:>}".format(x.get('dp_core_count'), x.get('core_type')), 'bold')))
logger.info("Ports count: {:>}".format(format_text(port_line, 'bold')))
def probe_server_mode (options):
# first we create a 'dummy' client and probe the server
client = TRexClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = ConsoleLogger(),
verbose_level = 'error')
return client.probe_server()['mode']
def run_console(client, logger, options):
# console
try:
show_intro(logger, client)
# a script mode
if options.batch:
cont = run_script_file(options.batch[0], client)
if not cont:
return
console = TRexConsole(client, options.verbose)
# run emu if needed
console.emu_server = options.emu_server
if options.emu:
console.do_plugins('load emu')
logger.prompt_redraw = console.prompt_redraw
# TUI
if options.tui:
console.do_tui("-x" if options.xtui else "-l")
else:
console.start()
except KeyboardInterrupt as e:
print("\n\n*** Caught Ctrl + C... Exiting...\n\n")
finally:
with client.logger.supress():
client.disconnect(stop_traffic = False)
def main():
parser = setParserOptions()
options = parser.parse_args()
if options.emu_server is None:
options.emu_server = options.server
if options.xtui:
options.tui = True
# always on top
if options.top:
set_window_always_on_top('trex_tui')
# verbose
if options.quiet:
verbose_level = "none"
elif options.verbose:
verbose_level = "debug"
else:
verbose_level = "info"
sync_timeout = None
async_timeout = None
if options.timeout:
sync_timeout = options.timeout
async_timeout = options.timeout
logger = ConsoleLogger()
# determine server mode
try:
mode = probe_server_mode(options)
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
return
acquire_options = {'force': options.force}
if mode == 'STL':
acquire_options['ports'] = options.acquire
client = STLClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = logger,
verbose_level = verbose_level,
sync_timeout = sync_timeout,
async_timeout = async_timeout)
elif mode == 'ASTF':
if options.acquire:
logger.critical('Acquire option is not available in ASTF. Must acquire all ports.')
return
client = ASTFClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = logger,
verbose_level = verbose_level,
sync_timeout = sync_timeout,
async_timeout = async_timeout)
else:
logger.critical("Unknown server mode: '{0}'".format(mode))
return
try:
client.connect()
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
return
# TUI or no acquire will give us READ ONLY mode
if not options.tui and not options.readonly:
try:
# acquire ports
client.acquire(**acquire_options)
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
logger.error("\n*** Failed to acquire all required ports ***\n")
return
if options.readonly:
logger.info(format_text("\nRead only mode - only few commands will be available", 'bold'))
run_console(client, logger, options)
if __name__ == '__main__':
main()
| 32.088088 | 153 | 0.551816 |
from __future__ import print_function
import collections
import subprocess
import inspect
import cmd
import json
import argparse
import random
import readline
import string
import os
import sys
import tty, termios
from threading import Lock
from functools import wraps, partial
import threading
import atexit
import tempfile
if __package__ == None:
print("TRex console must be launched as a module")
sys.exit(1)
from ..stl.api import *
from ..astf.api import *
from ..common.trex_client import TRexClient
from ..utils.text_opts import *
from ..utils.common import user_input, get_current_user, set_window_always_on_top
from ..utils import parsing_opts
from .trex_capture import CaptureManager
from .plugins_mngr import PluginsManager
from . import trex_tui
__version__ = "3.0"
def write_history_file(hist_file):
hist_end = readline.get_current_history_length()
hist_start = max(0, hist_end - readline.get_history_length())
with open(hist_file, 'w') as f:
for i in range(hist_start, hist_end):
f.write('%s\n' % readline.get_history_item(i + 1))
class ConsoleLogger(Logger):
def __init__ (self):
Logger.__init__(self)
self.prompt_redraw = lambda: None
self.tid = threading.current_thread().ident
def _write (self, msg, newline = True):
if threading.current_thread().ident != self.tid:
self._write_async(msg, newline)
else:
self._write_sync(msg, newline)
def _write_sync (self, msg, newline):
if newline:
print(msg)
else:
print(msg, end=' ')
def _write_async (self, msg, newline):
print('\n')
self._write_sync(msg, newline)
self.prompt_redraw()
self._flush()
def _flush (self):
sys.stdout.flush()
class TRexGeneralCmd(cmd.Cmd):
def __init__(self, client_mode):
cmd.Cmd.__init__(self)
self._history_file_dir = "/tmp/trex/console/"
self._history_file = self.get_history_file_full_path(client_mode)
readline.set_history_length(100)
self.load_console_history()
atexit.register(self.save_console_history)
def get_history_file_full_path(self, client_mode):
return "{dir}{filename}_{mode}.hist".format(dir=self._history_file_dir,
filename=self.get_console_identifier(),
mode=client_mode)
def load_console_history(self):
if os.path.exists(self._history_file):
readline.read_history_file(self._history_file)
return
def save_console_history(self):
if not os.path.exists(self._history_file_dir):
try:
original_umask = os.umask(0)
os.makedirs(self._history_file_dir, mode = 0o777)
finally:
os.umask(original_umask)
try:
write_history_file(self._history_file)
except BaseException as e:
print(bold('\nCould not save history file: %s\nError: %s\n' % (self._history_file, e)))
def print_history (self):
length = readline.get_current_history_length()
for i in range(1, length + 1):
cmd = readline.get_history_item(i)
print("{:<5} {:}".format(i, cmd))
def get_history_item (self, index):
length = readline.get_current_history_length()
if index > length:
print(format_text("please select an index between {0} and {1}".format(0, length)))
return None
return readline.get_history_item(index)
def emptyline(self):
return
def completenames(self, text, *ignored):
dotext = 'do_'+text
return [a[3:]+' ' for a in self.get_names() if a.startswith(dotext)]
class TRexConsole(TRexGeneralCmd):
def __init__(self, client, verbose = False):
self.cmd_lock = Lock()
self.client = client
self.verbose = verbose
TRexGeneralCmd.__init__(self, client.get_mode())
self.plugins_mngr = PluginsManager(self)
self.intro = "\n-=TRex Console v{ver}=-\n".format(ver=__version__)
self.intro += "\nType 'help' or '?' for supported actions\n"
self.terminal = None
self.tui = trex_tui.TrexTUI(self)
self.cap_mngr = CaptureManager(client, self.cmd_lock)
self.load_client_console_functions()
self.postcmd(False, "")
help_' + cmd_name, lambda _, func = cmd_func: func('-h'))
def load_client_plugin_functions (self, client, func_prefix):
for cmd_name, cmd_func in client.get_plugin_methods().items():
cmd_name = func_prefix + cmd_name
if cmd_func.preserve_history:
f = partial(self.history_preserver, cmd_func)
f.__doc__ = cmd_func.__doc__
f.name = cmd_func.name
f.group = cmd_func.group
setattr(self.__class__, 'do_' + cmd_name, f)
else:
setattr(self.__class__, 'do_' + cmd_name, cmd_func)
setattr(self.__class__, 'help_' + cmd_name, lambda _, func = cmd_func: func('-h'))
def unload_client_plugin_functions (self, func_prefix):
do_func_pre, help_func_pre = 'do_%s' % func_prefix, 'help_%s' % func_prefix
for cmd_name, cmd_func in inspect.getmembers(self.__class__, predicate=inspect.ismethod):
if cmd_name.startswith(do_func_pre) or cmd_name.startswith(help_func_pre):
delattr(self.__class__, cmd_name)
def generate_prompt (self, prefix = 'trex'):
if not self.client.is_connected():
return "{0}(offline)>".format(prefix)
elif not self.client.get_acquired_ports():
return "{0}(read-only)>".format(prefix)
elif self.client.is_all_ports_acquired():
p = prefix
service_ports = self.client.get_service_enabled_ports()
filtered_ports = self.client.get_service_filtered_ports()
if (self.client.get_mode() == "STL" or self.client.get_mode() == "ASTF") and (service_ports or filtered_ports):
if filtered_ports == self.client.get_acquired_ports():
p += '(service-filtered)'
elif service_ports == self.client.get_acquired_ports():
p += '(service)'
else:
p += '(service: {0})'.format(', '.join(map(str, service_ports)))
return "{0}>".format(p)
else:
return "{0} (ports: {1})>".format(prefix, ', '.join(map(str, self.client.get_acquired_ports())))
def prompt_redraw (self):
self.postcmd(False, "")
sys.stdout.write("\n" + self.prompt + readline.get_line_buffer())
sys.stdout.flush()
def get_console_identifier(self):
conn = self.client.get_connection_info()
return "%s_%s_%s_%s" % (get_current_user(), conn['server'], conn['sync_port'], conn['async_port'])
def register_main_console_methods(self):
main_names = set(self.trex_console.get_names()).difference(set(dir(self.__class__)))
for name in main_names:
for prefix in 'do_', 'help_', 'complete_':
if name.startswith(prefix):
self.__dict__[name] = getattr(self.trex_console, name)
def precmd(self, line):
lines = line.split(';')
try:
self.cmd_lock.acquire()
for line in lines:
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
if stop:
return "quit"
return ""
except KeyboardInterrupt:
print(bold('Interrupted by a keyboard signal (probably ctrl + c)'))
except TRexError as e:
print(e)
finally:
self.cmd_lock.release()
return ''
def postcmd(self, stop, line):
self.prompt = self.generate_prompt(prefix = 'trex')
return stop
def default(self, line):
print("'{0}' is an unrecognized command. type 'help' or '?' for a list\n".format(line))
@staticmethod
def tree_autocomplete(text):
dir = os.path.dirname(text)
if dir:
path = dir
else:
path = "."
start_string = os.path.basename(text)
targets = []
for x in os.listdir(path):
if x.startswith(start_string):
y = os.path.join(path, x)
if os.path.isfile(y):
targets.append(x + ' ')
elif os.path.isdir(y):
targets.append(x + '/')
return targets
"debug",
self.do_debug.__doc__)
opts = parser.parse_args(line.split())
try:
from IPython.terminal.ipapp import load_default_config
from IPython.terminal.embed import InteractiveShellEmbed
from IPython import embed
except ImportError:
embed = None
if not embed:
try:
import code
except ImportError:
self.client.logger.info(format_text("\n*** 'IPython' and 'code' library are not available ***\n", 'bold'))
return
auto_completer = readline.get_completer()
console_history_file = self._push_history()
client = self.client
descr = 'IPython' if embed else "'code' library"
self.client.logger.info(format_text("\n*** Starting Python shell (%s)... use 'client' as client object, Ctrl + D to exit ***\n" % descr, 'bold'))
try:
if embed:
cfg = load_default_config()
cfg['TerminalInteractiveShell']['confirm_exit'] = False
embed(config = cfg, display_banner = False)
else:
ns = {}
ns.update(globals())
ns.update(locals())
code.InteractiveConsole(ns).interact('')
finally:
readline.set_completer(auto_completer)
self._pop_history(console_history_file)
self.client.logger.info(format_text("\n*** Leaving Python shell ***\n"))
def do_history (self, line):
item = parsing_opts.ArgumentPack(['item'],
{"nargs": '?',
'metavar': 'item',
'type': parsing_opts.check_negative,
'help': "an history item index",
'default': 0})
parser = parsing_opts.gen_parser(self.client,
"history",
self.do_history.__doc__,
item)
try:
opts = parser.parse_args(line.split())
except TRexError:
return
if opts.item == 0:
self.print_history()
else:
cmd = self.get_history_item(opts.item)
if cmd == None:
return
print("Executing '{0}'".format(cmd))
return self.onecmd(cmd)
def do_plugins(self, line):
self.plugins_mngr.do_plugins(line)
def complete_plugins(self, text, line, start_index, end_index):
return self.plugins_mngr.complete_plugins(text, line, start_index, end_index)
def complete_emu_load_profile(self, text, line, start_index, end_index):
return self.complete_start(text, line, start_index, end_index)
.client.disconnect_line(line)
1) and (s[l - 1] in file_flags):
return TRexConsole.tree_autocomplete("")
if (l > 2) and (s[l - 2] in file_flags):
return TRexConsole.tree_autocomplete(s[l - 1])
complete_push = complete_start
complete_hello = complete_start
def complete_profile(self, text, line, begidx, endidx):
return self.complete_start(text,line, begidx, endidx)
@verify_connected
def do_tui (self, line):
parser = parsing_opts.gen_parser(self.client,
"tui",
self.do_tui.__doc__,
parsing_opts.XTERM,
parsing_opts.LOCKED)
try:
opts = parser.parse_args(line.split())
except TRexError:
return
if opts.xterm:
if not os.path.exists('/usr/bin/xterm'):
print(format_text("XTERM does not exists on this machine", 'bold'))
return
info = self.client.get_connection_info()
exe = './trex-console --top -t -q -s {0} -p {1} --async_port {2}'.format(info['server'], info['sync_port'], info['async_port'])
cmd = ['/usr/bin/xterm', '-geometry', '{0}x{1}'.format(self.tui.MIN_COLS, self.tui.MIN_ROWS), '-sl', '0', '-title', 'trex_tui', '-e', exe]
self.terminal = subprocess.Popen(cmd, preexec_fn = os.setpgrp)
return
try:
with self.client.logger.supress(verbose = 'none'):
self.tui.show(self.client, self.save_console_history, locked = opts.locked)
except self.tui.ScreenSizeException as e:
print(format_text(str(e) + "\n", 'bold'))
def help_tui (self):
do_tui("-h")
def do_quit(self, line):
return True
def do_help (self, line):
if line:
try:
func = getattr(self, 'help_' + line)
except AttributeError:
try:
doc = getattr(self, 'do_' + line).__doc__
if doc:
self.stdout.write("%s\n"%str(doc))
return
except AttributeError:
pass
self.stdout.write("%s\n"%str(self.nohelp % (line,)))
return
func()
return
cmds = [x[3:] for x in self.get_names() if x.startswith("do_")]
hidden = ['EOF', 'q', 'exit', 'h', 'shell']
categories = collections.defaultdict(list)
for cmd in cmds:
if cmd in hidden:
continue
category = getattr(getattr(self, 'do_' + cmd), 'group', 'basic')
categories[category].append(cmd)
if 'basic' in categories:
self._help_cmds('Console Commands', categories['basic'])
if 'common' in categories:
self._help_cmds('Common Commands', categories['common'])
if 'STL' in categories:
self._help_cmds('Stateless Commands', categories['STL'])
if 'ASTF' in categories:
self._help_cmds('Advanced Stateful Commands', categories['ASTF'])
if 'emu' in categories:
self._help_cmds('Emulation Commands', categories['emu'])
def _help_cmds (self, title, cmds):
print(format_text("\n{0}:\n".format(title), 'bold', 'underline'))
for cmd in cmds:
try:
doc = getattr(self, 'do_' + cmd).__doc__
if doc:
help = str(doc)
else:
help = "*** Undocumented Function ***\n"
except AttributeError:
help = "*** Undocumented Function ***\n"
l=help.splitlines()
print("{:<30} {:<30}".format(cmd + " - ",l[0] ))
def start(self):
try:
while True:
try:
self.cmdloop()
break
except KeyboardInterrupt as e:
if not readline.get_line_buffer():
raise KeyboardInterrupt
else:
print("")
self.intro = None
continue
finally:
self.plugins_mngr._unload_plugin()
self.cap_mngr.stop()
if self.terminal:
self.terminal.kill()
do_exit = do_EOF = do_q = do_quit
do_h = do_history
def run_script_file(filename, client):
client.logger.info(format_text("\nRunning script file '{0}'...".format(filename), 'bold'))
with open(filename) as f:
script_lines = f.readlines()
cmd_table = {}
for cmd_name, cmd_func in client.get_console_methods().items():
cmd_table[cmd_name] = cmd_func
for index, line in enumerate(script_lines, start = 1):
line = line.strip()
if line == "":
continue
if line.startswith("#"):
continue
sp = line.split(' ', 1)
cmd = sp[0]
if len(sp) == 2:
args = sp[1]
else:
args = ""
client.logger.info(format_text("Executing line {0} : '{1}'\n".format(index, line)))
if cmd not in cmd_table:
client.logger.error(format_text("Unknown command '%s', available commands are:\n%s" % (cmd, '\n'.join(sorted(cmd_table.keys()))), 'bold'))
return False
rc = cmd_table[cmd](args)
if isinstance(rc, RC) and not rc:
return False
client.logger.info(format_text("\n[Done]", 'bold'))
return True
def is_valid_file(filename):
if not os.path.isfile(filename):
raise argparse.ArgumentTypeError("The file '%s' does not exist" % filename)
return filename
def setParserOptions():
parser = argparse.ArgumentParser(prog="trex_console.py")
parser.add_argument("-s", "--server", help = "TRex Server [default is localhost]",
default = "localhost",
type = str)
parser.add_argument("-p", "--port", help = "TRex Server Port [default is 4501]\n",
default = 4501,
type = int)
parser.add_argument("--async_port", help = "TRex ASync Publisher Port [default is 4500]\n",
default = 4500,
dest='pub',
type = int)
parser.add_argument("-u", "--user", help = "User Name [default is currently logged in user]\n",
default = get_current_user(),
type = str)
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", help="Switch ON verbose option. Default is: OFF.",
default = False)
parser.add_argument( "--timeout",
dest="timeout",
help="timeout for ZMQ connection, the default is 3 sec, higher value will make it more resilient to Firewalls",
default = False,type = int)
group = parser.add_mutually_exclusive_group()
group.add_argument("-a", "--acquire", dest="acquire",
nargs = '+',
type = int,
help="Acquire ports on connect. default is all available ports",
default = None)
group.add_argument("-r", "--readonly", dest="readonly",
action="store_true",
help="Starts console in a read only mode",
default = False)
parser.add_argument("--emu", action="store_true",
help="Run emulation client on startup",
default = False)
parser.add_argument("--emu-server",
help="Emulation client server, default is TRex server address")
parser.add_argument("-f", "--force", dest="force",
action="store_true",
help="Force acquire the requested ports",
default = False)
parser.add_argument("--batch", dest="batch",
nargs = 1,
type = is_valid_file,
help = "Run the console in a batch mode with file",
default = None)
parser.add_argument("-t", "--tui", dest="tui",
action="store_true", help="Starts with TUI mode",
default = False)
parser.add_argument("-x", "--xtui", dest="xtui",
action="store_true", help="Starts with XTERM TUI mode",
default = False)
parser.add_argument("--top", dest="top",
action="store_true", help="Set the window as always on top",
default = False)
parser.add_argument("-q", "--quiet", dest="quiet",
action="store_true", help="Starts with all outputs suppressed",
default = False)
return parser
def show_intro (logger, c):
modes = {'STL': 'Stateless', 'ASTF': 'Advanced Stateful'}
x = c.get_server_system_info()
ver = c.get_server_version().get('version', 'N/A')
mode = c.get_server_version().get('mode', 'N/A')
port_types = {}
for port in x['ports']:
if 'supp_speeds' in port and port['supp_speeds']:
speed = max(port['supp_speeds']) // 1000
else:
speed = c.ports[port['index']].get_speed_gbps()
key = (speed, port.get('description', port['driver']))
if key not in port_types:
port_types[key] = 0
port_types[key] += 1
port_line = ''
for k, v in port_types.items():
port_line += "{0} x {1}Gbps @ {2}\t".format(v, k[0], k[1])
logger.info(format_text("\nServer Info:\n", 'underline'))
logger.info("Server version: {:>}".format(format_text(ver + ' @ ' + mode, 'bold')))
logger.info("Server mode: {:>}".format(format_text(modes.get(mode, 'N/A'), 'bold')))
logger.info("Server CPU: {:>}".format(format_text("{:>} x {:>}".format(x.get('dp_core_count'), x.get('core_type')), 'bold')))
logger.info("Ports count: {:>}".format(format_text(port_line, 'bold')))
def probe_server_mode (options):
client = TRexClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = ConsoleLogger(),
verbose_level = 'error')
return client.probe_server()['mode']
def run_console(client, logger, options):
try:
show_intro(logger, client)
if options.batch:
cont = run_script_file(options.batch[0], client)
if not cont:
return
console = TRexConsole(client, options.verbose)
console.emu_server = options.emu_server
if options.emu:
console.do_plugins('load emu')
logger.prompt_redraw = console.prompt_redraw
if options.tui:
console.do_tui("-x" if options.xtui else "-l")
else:
console.start()
except KeyboardInterrupt as e:
print("\n\n*** Caught Ctrl + C... Exiting...\n\n")
finally:
with client.logger.supress():
client.disconnect(stop_traffic = False)
def main():
parser = setParserOptions()
options = parser.parse_args()
if options.emu_server is None:
options.emu_server = options.server
if options.xtui:
options.tui = True
if options.top:
set_window_always_on_top('trex_tui')
if options.quiet:
verbose_level = "none"
elif options.verbose:
verbose_level = "debug"
else:
verbose_level = "info"
sync_timeout = None
async_timeout = None
if options.timeout:
sync_timeout = options.timeout
async_timeout = options.timeout
logger = ConsoleLogger()
try:
mode = probe_server_mode(options)
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
return
acquire_options = {'force': options.force}
if mode == 'STL':
acquire_options['ports'] = options.acquire
client = STLClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = logger,
verbose_level = verbose_level,
sync_timeout = sync_timeout,
async_timeout = async_timeout)
elif mode == 'ASTF':
if options.acquire:
logger.critical('Acquire option is not available in ASTF. Must acquire all ports.')
return
client = ASTFClient(username = options.user,
server = options.server,
sync_port = options.port,
async_port = options.pub,
logger = logger,
verbose_level = verbose_level,
sync_timeout = sync_timeout,
async_timeout = async_timeout)
else:
logger.critical("Unknown server mode: '{0}'".format(mode))
return
try:
client.connect()
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
return
if not options.tui and not options.readonly:
try:
client.acquire(**acquire_options)
except TRexError as e:
logger.error("Log:\n" + format_text(e.brief() + "\n", 'bold'))
logger.error("\n*** Failed to acquire all required ports ***\n")
return
if options.readonly:
logger.info(format_text("\nRead only mode - only few commands will be available", 'bold'))
run_console(client, logger, options)
if __name__ == '__main__':
main()
| true | true |
f72c59dd8ce767d14399213927b2439b6c5d6359 | 5,582 | bzl | Python | external_plugin_deps.bzl | davido/plugins_saml | a876ef94a1a2988882bca9665356dd90628a828e | [
"Apache-2.0"
] | null | null | null | external_plugin_deps.bzl | davido/plugins_saml | a876ef94a1a2988882bca9665356dd90628a828e | [
"Apache-2.0"
] | null | null | null | external_plugin_deps.bzl | davido/plugins_saml | a876ef94a1a2988882bca9665356dd90628a828e | [
"Apache-2.0"
] | null | null | null | load("//tools/bzl:maven_jar.bzl", "maven_jar")
SHIBBOLETH = "https://build.shibboleth.net/nexus/content/repositories/releases/"
OPENSAML_VERSION = "3.4.3"
PAC4J_VERSION = "3.8.0"
def external_plugin_deps():
# Transitive dependency of velocity
maven_jar(
name = "commons-collections",
artifact = "commons-collections:commons-collections:3.2.2",
sha1 = "8ad72fe39fa8c91eaaf12aadb21e0c3661fe26d5",
)
maven_jar(
name = "cryptacular",
artifact = "org.cryptacular:cryptacular:1.2.1",
sha1 = "c470bac7309ac04b0b9529bd7dcb1e0b75954f11",
)
maven_jar(
name = "joda-time",
artifact = "joda-time:joda-time:2.9.9",
sha1 = "f7b520c458572890807d143670c9b24f4de90897",
)
maven_jar(
name = "opensaml-core",
artifact = "org.opensaml:opensaml-core:" + OPENSAML_VERSION,
sha1 = "406eedd86ea88c1442a6b1c7625a45cf696b9f55",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-saml-api",
artifact = "org.opensaml:opensaml-saml-api:" + OPENSAML_VERSION,
sha1 = "b2c68a7265e8b059ecbfff0ac6525720cd3e1a86",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-storage-api",
artifact = "org.opensaml:opensaml-storage-api:" + OPENSAML_VERSION,
sha1 = "80ff32a3df660fe71527f293a317813c51375dcc",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-saml-impl",
artifact = "org.opensaml:opensaml-saml-impl:" + OPENSAML_VERSION,
sha1 = "c4bce04bec8fd065bbc014a2c4003172ec612ba6",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-soap-impl",
artifact = "org.opensaml:opensaml-soap-impl:" + OPENSAML_VERSION,
sha1 = "9a1b9bc0ed6a0c62f3f607cc2c1164c76a57303e",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-soap-api",
artifact = "org.opensaml:opensaml-soap-api:" + OPENSAML_VERSION,
sha1 = "4fe18269fff79f7172d9dbe0d421886282baa434",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-xmlsec-api",
artifact = "org.opensaml:opensaml-xmlsec-api:" + OPENSAML_VERSION,
sha1 = "b7f0f8a9c17997008bcef75a8886faeb5e9d9ea9",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-xmlsec-impl",
artifact = "org.opensaml:opensaml-xmlsec-impl:" + OPENSAML_VERSION,
sha1 = "3dbdf38773a07d37f013dc9a2ecc4d0295a724de",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-security-api",
artifact = "org.opensaml:opensaml-security-api:" + OPENSAML_VERSION,
sha1 = "b6878bd144c15612ab899643e561e52f04d332c1",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-security-impl",
artifact = "org.opensaml:opensaml-security-impl:" + OPENSAML_VERSION,
sha1 = "72edf27dbce57ed29aebab8563a41942f7f15527",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-profile-api",
artifact = "org.opensaml:opensaml-profile-api:" + OPENSAML_VERSION,
sha1 = "8daff1c6b7ff47178054e17e78b0d4b19b622434",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-profile-impl",
artifact = "org.opensaml:opensaml-profile-impl:" + OPENSAML_VERSION,
sha1 = "175bd3d0ba07a17f0222ea799c3971119c9b32b3",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-messaging-api",
artifact = "org.opensaml:opensaml-messaging-api:" + OPENSAML_VERSION,
sha1 = "18f68283a3729e4355a29936861f6472ab20b2be",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-messaging-impl",
artifact = "org.opensaml:opensaml-messaging-impl:" + OPENSAML_VERSION,
sha1 = "d0cd65f2b0a167dc25477245adf5417a8735e132",
repository = SHIBBOLETH,
)
maven_jar(
name = "pac4j-saml",
artifact = "org.pac4j:pac4j-saml:" + PAC4J_VERSION,
sha1 = "6897faedf4131f71954963945e4dbc13788d8d22",
)
maven_jar(
name = "pac4j-core",
artifact = "org.pac4j:pac4j-core:" + PAC4J_VERSION,
sha1 = "e5a82ad0a4a0e246edc8950d1e2c632a36732715",
)
maven_jar(
name = "shibboleth-utilities",
artifact = "net.shibboleth.utilities:java-support:7.4.0",
sha1 = "e10c137cdb5045eea2c0ccf8ac5094052eaee36b",
repository = SHIBBOLETH,
)
maven_jar(
name = "shibboleth-xmlsectool",
artifact = "net.shibboleth.tool:xmlsectool:2.0.0",
sha1 = "c57f887f522c0e930341c7d86eff4d8ec9b797a1",
repository = SHIBBOLETH,
)
maven_jar(
name = "santuario-xmlsec",
artifact = "org.apache.santuario:xmlsec:2.1.4",
sha1 = "cb43326f02e3e77526c24269c8b5d3cc3f7f6653",
)
maven_jar(
name = "spring-core",
artifact = "org.springframework:spring-core:5.1.5.RELEASE",
sha1 = "aacc4555108f3da913a58114b2aebc819f58cce4",
)
maven_jar(
name = "stax2-api",
artifact = "org.codehaus.woodstox:stax2-api:3.1.4",
sha1 = "ac19014b1e6a7c08aad07fe114af792676b685b7",
)
maven_jar(
name = "velocity",
artifact = "org.apache.velocity:velocity:1.7",
sha1 = "2ceb567b8f3f21118ecdec129fe1271dbc09aa7a",
)
maven_jar(
name = "woodstox-core",
artifact = "com.fasterxml.woodstox:woodstox-core:5.0.3",
sha1 = "10aa199207fda142eff01cd61c69244877d71770",
)
| 30.67033 | 80 | 0.640989 | load("//tools/bzl:maven_jar.bzl", "maven_jar")
SHIBBOLETH = "https://build.shibboleth.net/nexus/content/repositories/releases/"
OPENSAML_VERSION = "3.4.3"
PAC4J_VERSION = "3.8.0"
def external_plugin_deps():
maven_jar(
name = "commons-collections",
artifact = "commons-collections:commons-collections:3.2.2",
sha1 = "8ad72fe39fa8c91eaaf12aadb21e0c3661fe26d5",
)
maven_jar(
name = "cryptacular",
artifact = "org.cryptacular:cryptacular:1.2.1",
sha1 = "c470bac7309ac04b0b9529bd7dcb1e0b75954f11",
)
maven_jar(
name = "joda-time",
artifact = "joda-time:joda-time:2.9.9",
sha1 = "f7b520c458572890807d143670c9b24f4de90897",
)
maven_jar(
name = "opensaml-core",
artifact = "org.opensaml:opensaml-core:" + OPENSAML_VERSION,
sha1 = "406eedd86ea88c1442a6b1c7625a45cf696b9f55",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-saml-api",
artifact = "org.opensaml:opensaml-saml-api:" + OPENSAML_VERSION,
sha1 = "b2c68a7265e8b059ecbfff0ac6525720cd3e1a86",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-storage-api",
artifact = "org.opensaml:opensaml-storage-api:" + OPENSAML_VERSION,
sha1 = "80ff32a3df660fe71527f293a317813c51375dcc",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-saml-impl",
artifact = "org.opensaml:opensaml-saml-impl:" + OPENSAML_VERSION,
sha1 = "c4bce04bec8fd065bbc014a2c4003172ec612ba6",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-soap-impl",
artifact = "org.opensaml:opensaml-soap-impl:" + OPENSAML_VERSION,
sha1 = "9a1b9bc0ed6a0c62f3f607cc2c1164c76a57303e",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-soap-api",
artifact = "org.opensaml:opensaml-soap-api:" + OPENSAML_VERSION,
sha1 = "4fe18269fff79f7172d9dbe0d421886282baa434",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-xmlsec-api",
artifact = "org.opensaml:opensaml-xmlsec-api:" + OPENSAML_VERSION,
sha1 = "b7f0f8a9c17997008bcef75a8886faeb5e9d9ea9",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-xmlsec-impl",
artifact = "org.opensaml:opensaml-xmlsec-impl:" + OPENSAML_VERSION,
sha1 = "3dbdf38773a07d37f013dc9a2ecc4d0295a724de",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-security-api",
artifact = "org.opensaml:opensaml-security-api:" + OPENSAML_VERSION,
sha1 = "b6878bd144c15612ab899643e561e52f04d332c1",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-security-impl",
artifact = "org.opensaml:opensaml-security-impl:" + OPENSAML_VERSION,
sha1 = "72edf27dbce57ed29aebab8563a41942f7f15527",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-profile-api",
artifact = "org.opensaml:opensaml-profile-api:" + OPENSAML_VERSION,
sha1 = "8daff1c6b7ff47178054e17e78b0d4b19b622434",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-profile-impl",
artifact = "org.opensaml:opensaml-profile-impl:" + OPENSAML_VERSION,
sha1 = "175bd3d0ba07a17f0222ea799c3971119c9b32b3",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-messaging-api",
artifact = "org.opensaml:opensaml-messaging-api:" + OPENSAML_VERSION,
sha1 = "18f68283a3729e4355a29936861f6472ab20b2be",
repository = SHIBBOLETH,
)
maven_jar(
name = "opensaml-messaging-impl",
artifact = "org.opensaml:opensaml-messaging-impl:" + OPENSAML_VERSION,
sha1 = "d0cd65f2b0a167dc25477245adf5417a8735e132",
repository = SHIBBOLETH,
)
maven_jar(
name = "pac4j-saml",
artifact = "org.pac4j:pac4j-saml:" + PAC4J_VERSION,
sha1 = "6897faedf4131f71954963945e4dbc13788d8d22",
)
maven_jar(
name = "pac4j-core",
artifact = "org.pac4j:pac4j-core:" + PAC4J_VERSION,
sha1 = "e5a82ad0a4a0e246edc8950d1e2c632a36732715",
)
maven_jar(
name = "shibboleth-utilities",
artifact = "net.shibboleth.utilities:java-support:7.4.0",
sha1 = "e10c137cdb5045eea2c0ccf8ac5094052eaee36b",
repository = SHIBBOLETH,
)
maven_jar(
name = "shibboleth-xmlsectool",
artifact = "net.shibboleth.tool:xmlsectool:2.0.0",
sha1 = "c57f887f522c0e930341c7d86eff4d8ec9b797a1",
repository = SHIBBOLETH,
)
maven_jar(
name = "santuario-xmlsec",
artifact = "org.apache.santuario:xmlsec:2.1.4",
sha1 = "cb43326f02e3e77526c24269c8b5d3cc3f7f6653",
)
maven_jar(
name = "spring-core",
artifact = "org.springframework:spring-core:5.1.5.RELEASE",
sha1 = "aacc4555108f3da913a58114b2aebc819f58cce4",
)
maven_jar(
name = "stax2-api",
artifact = "org.codehaus.woodstox:stax2-api:3.1.4",
sha1 = "ac19014b1e6a7c08aad07fe114af792676b685b7",
)
maven_jar(
name = "velocity",
artifact = "org.apache.velocity:velocity:1.7",
sha1 = "2ceb567b8f3f21118ecdec129fe1271dbc09aa7a",
)
maven_jar(
name = "woodstox-core",
artifact = "com.fasterxml.woodstox:woodstox-core:5.0.3",
sha1 = "10aa199207fda142eff01cd61c69244877d71770",
)
| true | true |
f72c5a8f517248059d2b01dd023847f9b1fa269d | 2,726 | py | Python | django_project/store_cms/settings/base.py | Chumbak/RetailstoreTV-Content-Player | ea26f14045c3d30a2e348abac4d0a0c8df171b4b | [
"Apache-2.0"
] | 2 | 2017-08-31T10:35:47.000Z | 2017-11-10T07:03:43.000Z | django_project/store_cms/settings/base.py | Chumbak/RetailstoreTV-Content-Player | ea26f14045c3d30a2e348abac4d0a0c8df171b4b | [
"Apache-2.0"
] | null | null | null | django_project/store_cms/settings/base.py | Chumbak/RetailstoreTV-Content-Player | ea26f14045c3d30a2e348abac4d0a0c8df171b4b | [
"Apache-2.0"
] | 5 | 2017-08-31T09:53:12.000Z | 2018-08-02T04:26:32.000Z | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = bool(os.environ.get('DEBUG', False))
ALLOWED_HOSTS = []
# Application definition
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = ['cloudinary', 'bulk_admin']
LOCAL_APPS = ['cms']
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'store_cms.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static'
],
},
},
]
WSGI_APPLICATION = 'store_cms.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
SESSION_SAVE_EVERY_REQUEST = True
| 25.240741 | 91 | 0.696992 | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = bool(os.environ.get('DEBUG', False))
ALLOWED_HOSTS = []
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = ['cloudinary', 'bulk_admin']
LOCAL_APPS = ['cms']
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'store_cms.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static'
],
},
},
]
WSGI_APPLICATION = 'store_cms.wsgi.application'
S = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
SESSION_SAVE_EVERY_REQUEST = True
| true | true |
f72c5b38b7252471247fc6364be4f544e55a623c | 1,047 | py | Python | Day_23/car_manager.py | johnsons-ux/100-days-of-python | 59f8f5b1be85542306103df44383423b00e48931 | [
"CC0-1.0"
] | 1 | 2022-03-12T07:17:56.000Z | 2022-03-12T07:17:56.000Z | Day_23/car_manager.py | johnsons-ux/100-days-of-python | 59f8f5b1be85542306103df44383423b00e48931 | [
"CC0-1.0"
] | null | null | null | Day_23/car_manager.py | johnsons-ux/100-days-of-python | 59f8f5b1be85542306103df44383423b00e48931 | [
"CC0-1.0"
] | null | null | null | from turtle import Turtle
import random
COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.all_cars = []
self.car_speed = STARTING_MOVE_DISTANCE
def create_car(self):
random_chance = random.randint(1, 6)
if random_chance == 1:
new_car = Turtle('square')
new_car.shapesize(1, 2)
new_car.penup()
new_car.color(random.choice(COLORS))
y_value = random.randint(-250, 250)
new_car.goto(300, y_value)
self.all_cars.append(new_car)
def move_cars(self):
for car in self.all_cars:
car.backward(self.car_speed) # #The car is moving 'backward' as the 'setheading' is 0. This
# means that it is facing east. Having it move forward would mean that the squares would be moving from
# left to right of the screen.
def new_level(self):
self.car_speed += MOVE_INCREMENT
| 30.794118 | 115 | 0.619866 | from turtle import Turtle
import random
COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.all_cars = []
self.car_speed = STARTING_MOVE_DISTANCE
def create_car(self):
random_chance = random.randint(1, 6)
if random_chance == 1:
new_car = Turtle('square')
new_car.shapesize(1, 2)
new_car.penup()
new_car.color(random.choice(COLORS))
y_value = random.randint(-250, 250)
new_car.goto(300, y_value)
self.all_cars.append(new_car)
def move_cars(self):
for car in self.all_cars:
car.backward(self.car_speed) self.car_speed += MOVE_INCREMENT
| true | true |
f72c5ca5cbb2721d967ad9ef9dfa896f7ccce240 | 2,924 | py | Python | tensorflow/python/estimator/canned/optimizers.py | tianyapiaozi/tensorflow | fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a | [
"Apache-2.0"
] | 522 | 2016-06-08T02:15:50.000Z | 2022-03-02T05:30:36.000Z | tensorflow/python/estimator/canned/optimizers.py | tianyapiaozi/tensorflow | fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a | [
"Apache-2.0"
] | 133 | 2017-04-26T16:49:49.000Z | 2019-10-15T11:39:26.000Z | tensorflow/python/estimator/canned/optimizers.py | tianyapiaozi/tensorflow | fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a | [
"Apache-2.0"
] | 108 | 2016-06-16T15:34:05.000Z | 2022-03-12T13:23:11.000Z | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Methods related to optimizers used in canned_estimators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python.training import adagrad
from tensorflow.python.training import adam
from tensorflow.python.training import ftrl
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import optimizer as optimizer_lib
from tensorflow.python.training import rmsprop
_OPTIMIZER_CLS_NAMES = {
'Adagrad': adagrad.AdagradOptimizer,
'Adam': adam.AdamOptimizer,
'Ftrl': ftrl.FtrlOptimizer,
'RMSProp': rmsprop.RMSPropOptimizer,
'SGD': gradient_descent.GradientDescentOptimizer,
}
def get_optimizer_instance(opt, learning_rate=None):
"""Returns an optimizer instance.
Supports the following types for the given `opt`:
* An `Optimizer` instance: Returns the given `opt`.
* A string: Creates an `Optimizer` subclass with the given `learning_rate`.
Supported strings:
* 'Adagrad': Returns an `AdagradOptimizer`.
* 'Adam': Returns an `AdamOptimizer`.
* 'Ftrl': Returns an `FtrlOptimizer`.
* 'RMSProp': Returns an `RMSPropOptimizer`.
* 'SGD': Returns a `GradientDescentOptimizer`.
Args:
opt: An `Optimizer` instance, or string, as discussed above.
learning_rate: A float. Only used if `opt` is a string.
Returns:
An `Optimizer` instance.
Raises:
ValueError: If `opt` is an unsupported string.
ValueError: If `opt` is a supported string but `learning_rate` was not
specified.
ValueError: If `opt` is none of the above types.
"""
if isinstance(opt, six.string_types):
if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES):
if not learning_rate:
raise ValueError('learning_rate must be specified when opt is string.')
return _OPTIMIZER_CLS_NAMES[opt](learning_rate=learning_rate)
raise ValueError(
'Unsupported optimizer name: {}. Supported names are: {}'.format(
opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES)))))
if not isinstance(opt, optimizer_lib.Optimizer):
raise ValueError(
'The given object is not an Optimizer instance. Given: {}'.format(opt))
return opt
| 37.012658 | 80 | 0.719904 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python.training import adagrad
from tensorflow.python.training import adam
from tensorflow.python.training import ftrl
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import optimizer as optimizer_lib
from tensorflow.python.training import rmsprop
_OPTIMIZER_CLS_NAMES = {
'Adagrad': adagrad.AdagradOptimizer,
'Adam': adam.AdamOptimizer,
'Ftrl': ftrl.FtrlOptimizer,
'RMSProp': rmsprop.RMSPropOptimizer,
'SGD': gradient_descent.GradientDescentOptimizer,
}
def get_optimizer_instance(opt, learning_rate=None):
if isinstance(opt, six.string_types):
if opt in six.iterkeys(_OPTIMIZER_CLS_NAMES):
if not learning_rate:
raise ValueError('learning_rate must be specified when opt is string.')
return _OPTIMIZER_CLS_NAMES[opt](learning_rate=learning_rate)
raise ValueError(
'Unsupported optimizer name: {}. Supported names are: {}'.format(
opt, tuple(sorted(six.iterkeys(_OPTIMIZER_CLS_NAMES)))))
if not isinstance(opt, optimizer_lib.Optimizer):
raise ValueError(
'The given object is not an Optimizer instance. Given: {}'.format(opt))
return opt
| true | true |
f72c5d1dce32355c3989c67add71367d80276cc4 | 6,188 | py | Python | code/common/preprocessing.py | monperrus/iFixR | 5548f3ba91341dc9e73057269f8c01a0b1b6fc68 | [
"MIT"
] | 8 | 2019-07-23T15:03:50.000Z | 2021-02-08T11:06:53.000Z | code/common/preprocessing.py | monperrus/iFixR | 5548f3ba91341dc9e73057269f8c01a0b1b6fc68 | [
"MIT"
] | null | null | null | code/common/preprocessing.py | monperrus/iFixR | 5548f3ba91341dc9e73057269f8c01a0b1b6fc68 | [
"MIT"
] | 4 | 2019-09-19T08:23:46.000Z | 2021-03-05T13:57:40.000Z | from nltk.tokenize import RegexpTokenizer
# from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
from string import punctuation
import re
from nltk.corpus import stopwords
en_stop = stopwords.words('english')
from nltk.corpus import wordnet
import html
from common.commons import *
CODE_PATH = os.environ["CODE_PATH"]
import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger', 'ner'])
nlp.max_length =100000000
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import sys
def preprocessingCodeElementsList(res):
printDetail = False
if isinstance(res, list):
merged = str()
for r in res:
if isinstance(r, list):
merged = merged + ' ' + ' '.join(r)
else:
merged = merged +' ' + r
else:
merged=res
res = html.unescape(merged)
tokens = getTokens(res,printDetail)
stripped = []
for t in tokens:
splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t)
for s in splits:
stripped.append(s)
punc = removeEndingPunct(stripped,printDetail)
non_empty = [i for i in punc if i != '']
stripped = removeEndingPunct(non_empty,printDetail)
camelCase = handleCamelCase(stripped,printDetail,True)
underScore = handleUnderScore(camelCase,printDetail,True)
lower = [i.lower() for i in underScore]
stopped_tokens = [i for i in lower if not i in en_stop]
stem2 = stem(stopped_tokens,printDetail)
if printDetail:
print('=====CLEANED=========')
print(stem2)
return stem2
def preprocessingNL(res):
printDetail = False
if isinstance(res, list):
merged = str()
for r in res:
if isinstance(r, list):
merged = merged + ' ' + ' '.join(r)
else:
merged = merged +' ' + r
else:
merged=res
res = html.unescape(merged)
html_decoded_string = res.replace("&", "&").replace(""", '"').replace("'", "'").replace(">",
">").replace(
"<", "<")
html_decoded_string = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '',html_decoded_string)
tokens = getTokens(html_decoded_string,printDetail)
stripped = []
for t in tokens:
splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t)
for s in splits:
stripped.append(s)
punc = removeEndingPunct(stripped,printDetail)
non_empty = [i for i in punc if i != '']
stripped = removeEndingPunct(non_empty,printDetail)
camelCase = handleCamelCase(stripped,printDetail,True)
underScore = handleUnderScore(camelCase,printDetail,True)
lower = [i.lower() for i in underScore]
stopped_tokens = [i for i in lower if not i in en_stop]
nonDigit = [i for i in stopped_tokens if (not i.isdigit())]
doc = nlp(' '.join(nonDigit))
newWord = []
for token in doc:
if(token.text in nlp.vocab):
newWord.append(token.text)
stem2 = stem(newWord,printDetail)
if printDetail:
print('=====CLEANED=========')
print(stem2)
return stem2
def getTokens(re,printDetail=False):
tokenizer = RegexpTokenizer(r'\S+')
tokens = tokenizer.tokenize(re)
if printDetail:
print('=====TOKENS=========')
print(tokens)
return tokens
def charLength(x, l=3):
if x.isalpha() and len(x) >= l:
return True
else:
return False
def removeEndingPunct(re,printDetail):
stripped = [i.strip(punctuation) for i in re]
if printDetail:
print('=====removeEndingPunct=========')
print(stripped)
return stripped
def handleCamelCase(re,printDetail=False,keepOriginal = False):
camelCased = list()
for i in re:
listOfCC = camel_case_split(i)
camelCased.extend(listOfCC)
if i not in listOfCC and keepOriginal:
camelCased.append(i)
if printDetail:
print('=====CAMEL CASE=========')
print(camelCased)
return camelCased
def handleUnderScore(re,printDetail=False,keepOriginal = False):
underScored = list()
for i in re:
listOfCC = i.split('_')
underScored.extend(listOfCC)
if i not in listOfCC and keepOriginal:
underScored.append(i)
if printDetail:
print('=====UNDER SCORE=========')
print(underScored)
return underScored
def camel_case_split(identifier):
matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
res = [m.group(0) for m in matches]
return res
def stem(res,printDetail):
p_stemmer = PorterStemmer()
stemmed_tokens = [p_stemmer.stem(i.strip()) for i in res if i]
if printDetail:
print('=====STEMMED=========')
print(stemmed_tokens)
return stemmed_tokens
def isEnglish(word_to_test):
if not wordnet.synsets(word_to_test):
#Not an English Word
#TODO
word_to_test
#print word_to_test
else:
return word_to_test
def dummy_fun(doc):
return doc
def calculateTfIdfCodeElementsList(aCorpus):
global progress
progress = 0
v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3)
m = v.fit(aCorpus)
return v
def calculateTfIdfNLList(aCorpus):
global progress
progress = 0
v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3)
m = v.fit(aCorpus)
return v
def getDTMNL(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getDTMCE(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getBRDTM(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getBRDTMCEs(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
| 26.672414 | 139 | 0.609082 | from nltk.tokenize import RegexpTokenizer
from nltk.stem.porter import PorterStemmer
from string import punctuation
import re
from nltk.corpus import stopwords
en_stop = stopwords.words('english')
from nltk.corpus import wordnet
import html
from common.commons import *
CODE_PATH = os.environ["CODE_PATH"]
import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger', 'ner'])
nlp.max_length =100000000
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import sys
def preprocessingCodeElementsList(res):
printDetail = False
if isinstance(res, list):
merged = str()
for r in res:
if isinstance(r, list):
merged = merged + ' ' + ' '.join(r)
else:
merged = merged +' ' + r
else:
merged=res
res = html.unescape(merged)
tokens = getTokens(res,printDetail)
stripped = []
for t in tokens:
splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t)
for s in splits:
stripped.append(s)
punc = removeEndingPunct(stripped,printDetail)
non_empty = [i for i in punc if i != '']
stripped = removeEndingPunct(non_empty,printDetail)
camelCase = handleCamelCase(stripped,printDetail,True)
underScore = handleUnderScore(camelCase,printDetail,True)
lower = [i.lower() for i in underScore]
stopped_tokens = [i for i in lower if not i in en_stop]
stem2 = stem(stopped_tokens,printDetail)
if printDetail:
print('=====CLEANED=========')
print(stem2)
return stem2
def preprocessingNL(res):
printDetail = False
if isinstance(res, list):
merged = str()
for r in res:
if isinstance(r, list):
merged = merged + ' ' + ' '.join(r)
else:
merged = merged +' ' + r
else:
merged=res
res = html.unescape(merged)
html_decoded_string = res.replace("&", "&").replace(""", '"').replace("'", "'").replace(">",
">").replace(
"<", "<")
html_decoded_string = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '',html_decoded_string)
tokens = getTokens(html_decoded_string,printDetail)
stripped = []
for t in tokens:
splits = re.split('\.|\(|\)|:|>|<|:|=|/|\\\\|\'|-',t)
for s in splits:
stripped.append(s)
punc = removeEndingPunct(stripped,printDetail)
non_empty = [i for i in punc if i != '']
stripped = removeEndingPunct(non_empty,printDetail)
camelCase = handleCamelCase(stripped,printDetail,True)
underScore = handleUnderScore(camelCase,printDetail,True)
lower = [i.lower() for i in underScore]
stopped_tokens = [i for i in lower if not i in en_stop]
nonDigit = [i for i in stopped_tokens if (not i.isdigit())]
doc = nlp(' '.join(nonDigit))
newWord = []
for token in doc:
if(token.text in nlp.vocab):
newWord.append(token.text)
stem2 = stem(newWord,printDetail)
if printDetail:
print('=====CLEANED=========')
print(stem2)
return stem2
def getTokens(re,printDetail=False):
tokenizer = RegexpTokenizer(r'\S+')
tokens = tokenizer.tokenize(re)
if printDetail:
print('=====TOKENS=========')
print(tokens)
return tokens
def charLength(x, l=3):
if x.isalpha() and len(x) >= l:
return True
else:
return False
def removeEndingPunct(re,printDetail):
stripped = [i.strip(punctuation) for i in re]
if printDetail:
print('=====removeEndingPunct=========')
print(stripped)
return stripped
def handleCamelCase(re,printDetail=False,keepOriginal = False):
camelCased = list()
for i in re:
listOfCC = camel_case_split(i)
camelCased.extend(listOfCC)
if i not in listOfCC and keepOriginal:
camelCased.append(i)
if printDetail:
print('=====CAMEL CASE=========')
print(camelCased)
return camelCased
def handleUnderScore(re,printDetail=False,keepOriginal = False):
underScored = list()
for i in re:
listOfCC = i.split('_')
underScored.extend(listOfCC)
if i not in listOfCC and keepOriginal:
underScored.append(i)
if printDetail:
print('=====UNDER SCORE=========')
print(underScored)
return underScored
def camel_case_split(identifier):
matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
res = [m.group(0) for m in matches]
return res
def stem(res,printDetail):
p_stemmer = PorterStemmer()
stemmed_tokens = [p_stemmer.stem(i.strip()) for i in res if i]
if printDetail:
print('=====STEMMED=========')
print(stemmed_tokens)
return stemmed_tokens
def isEnglish(word_to_test):
if not wordnet.synsets(word_to_test):
#Not an English Word
#TODO
word_to_test
#print word_to_test
else:
return word_to_test
def dummy_fun(doc):
return doc
def calculateTfIdfCodeElementsList(aCorpus):
global progress
progress = 0
v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3)
m = v.fit(aCorpus)
return v
def calculateTfIdfNLList(aCorpus):
global progress
progress = 0
v = TfidfVectorizer(tokenizer=dummy_fun,stop_words=None,lowercase=False,sublinear_tf=True)#,max_df=0.7,min_df=3)
m = v.fit(aCorpus)
return v
def getDTMNL(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getDTMCE(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getBRDTM(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
def getBRDTMCEs(x,v,corpus):
ind =x.name
v.tokenizer = dummy_fun
return v.transform([corpus[ind]])
| true | true |
f72c5e0a7a2455dfd966067814f820b39b4646a1 | 8,806 | py | Python | src/main/resources/pytz/zoneinfo/America/Moncton.py | TheEin/swagger-maven-plugin | cf93dce2d5c8d3534f4cf8c612b11e2d2313871b | [
"Apache-2.0"
] | 65 | 2015-11-14T13:46:01.000Z | 2021-08-14T05:54:04.000Z | lib/pytz/zoneinfo/America/Moncton.py | tjsavage/polymer-dashboard | 19bc467f1206613f8eec646b6f2bc43cc319ef75 | [
"CNRI-Python",
"Linux-OpenIB"
] | 13 | 2016-03-31T20:00:17.000Z | 2021-08-20T14:52:31.000Z | lib/pytz/zoneinfo/America/Moncton.py | tjsavage/polymer-dashboard | 19bc467f1206613f8eec646b6f2bc43cc319ef75 | [
"CNRI-Python",
"Linux-OpenIB"
] | 20 | 2015-03-18T08:41:37.000Z | 2020-12-18T02:58:30.000Z | '''tzinfo timezone information for America/Moncton.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Moncton(DstTzInfo):
'''America/Moncton timezone definition. See datetime.tzinfo for details'''
zone = 'America/Moncton'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1902,6,15,5,0,0),
d(1918,4,14,6,0,0),
d(1918,10,31,5,0,0),
d(1933,6,11,5,0,0),
d(1933,9,10,4,0,0),
d(1934,6,10,5,0,0),
d(1934,9,9,4,0,0),
d(1935,6,9,5,0,0),
d(1935,9,8,4,0,0),
d(1936,6,7,5,0,0),
d(1936,9,6,4,0,0),
d(1937,6,6,5,0,0),
d(1937,9,5,4,0,0),
d(1938,6,5,5,0,0),
d(1938,9,4,4,0,0),
d(1939,5,27,5,0,0),
d(1939,9,23,4,0,0),
d(1940,5,19,5,0,0),
d(1940,9,21,4,0,0),
d(1941,5,4,5,0,0),
d(1941,9,27,4,0,0),
d(1942,2,9,6,0,0),
d(1945,8,14,23,0,0),
d(1945,9,30,5,0,0),
d(1946,4,28,6,0,0),
d(1946,9,29,5,0,0),
d(1947,4,27,6,0,0),
d(1947,9,28,5,0,0),
d(1948,4,25,6,0,0),
d(1948,9,26,5,0,0),
d(1949,4,24,6,0,0),
d(1949,9,25,5,0,0),
d(1950,4,30,6,0,0),
d(1950,9,24,5,0,0),
d(1951,4,29,6,0,0),
d(1951,9,30,5,0,0),
d(1952,4,27,6,0,0),
d(1952,9,28,5,0,0),
d(1953,4,26,6,0,0),
d(1953,9,27,5,0,0),
d(1954,4,25,6,0,0),
d(1954,9,26,5,0,0),
d(1955,4,24,6,0,0),
d(1955,9,25,5,0,0),
d(1956,4,29,6,0,0),
d(1956,9,30,5,0,0),
d(1957,4,28,6,0,0),
d(1957,10,27,5,0,0),
d(1958,4,27,6,0,0),
d(1958,10,26,5,0,0),
d(1959,4,26,6,0,0),
d(1959,10,25,5,0,0),
d(1960,4,24,6,0,0),
d(1960,10,30,5,0,0),
d(1961,4,30,6,0,0),
d(1961,10,29,5,0,0),
d(1962,4,29,6,0,0),
d(1962,10,28,5,0,0),
d(1963,4,28,6,0,0),
d(1963,10,27,5,0,0),
d(1964,4,26,6,0,0),
d(1964,10,25,5,0,0),
d(1965,4,25,6,0,0),
d(1965,10,31,5,0,0),
d(1966,4,24,6,0,0),
d(1966,10,30,5,0,0),
d(1967,4,30,6,0,0),
d(1967,10,29,5,0,0),
d(1968,4,28,6,0,0),
d(1968,10,27,5,0,0),
d(1969,4,27,6,0,0),
d(1969,10,26,5,0,0),
d(1970,4,26,6,0,0),
d(1970,10,25,5,0,0),
d(1971,4,25,6,0,0),
d(1971,10,31,5,0,0),
d(1972,4,30,6,0,0),
d(1972,10,29,5,0,0),
d(1974,4,28,6,0,0),
d(1974,10,27,5,0,0),
d(1975,4,27,6,0,0),
d(1975,10,26,5,0,0),
d(1976,4,25,6,0,0),
d(1976,10,31,5,0,0),
d(1977,4,24,6,0,0),
d(1977,10,30,5,0,0),
d(1978,4,30,6,0,0),
d(1978,10,29,5,0,0),
d(1979,4,29,6,0,0),
d(1979,10,28,5,0,0),
d(1980,4,27,6,0,0),
d(1980,10,26,5,0,0),
d(1981,4,26,6,0,0),
d(1981,10,25,5,0,0),
d(1982,4,25,6,0,0),
d(1982,10,31,5,0,0),
d(1983,4,24,6,0,0),
d(1983,10,30,5,0,0),
d(1984,4,29,6,0,0),
d(1984,10,28,5,0,0),
d(1985,4,28,6,0,0),
d(1985,10,27,5,0,0),
d(1986,4,27,6,0,0),
d(1986,10,26,5,0,0),
d(1987,4,5,6,0,0),
d(1987,10,25,5,0,0),
d(1988,4,3,6,0,0),
d(1988,10,30,5,0,0),
d(1989,4,2,6,0,0),
d(1989,10,29,5,0,0),
d(1990,4,1,6,0,0),
d(1990,10,28,5,0,0),
d(1991,4,7,6,0,0),
d(1991,10,27,5,0,0),
d(1992,4,5,6,0,0),
d(1992,10,25,5,0,0),
d(1993,4,4,4,1,0),
d(1993,10,31,3,1,0),
d(1994,4,3,4,1,0),
d(1994,10,30,3,1,0),
d(1995,4,2,4,1,0),
d(1995,10,29,3,1,0),
d(1996,4,7,4,1,0),
d(1996,10,27,3,1,0),
d(1997,4,6,4,1,0),
d(1997,10,26,3,1,0),
d(1998,4,5,4,1,0),
d(1998,10,25,3,1,0),
d(1999,4,4,4,1,0),
d(1999,10,31,3,1,0),
d(2000,4,2,4,1,0),
d(2000,10,29,3,1,0),
d(2001,4,1,4,1,0),
d(2001,10,28,3,1,0),
d(2002,4,7,4,1,0),
d(2002,10,27,3,1,0),
d(2003,4,6,4,1,0),
d(2003,10,26,3,1,0),
d(2004,4,4,4,1,0),
d(2004,10,31,3,1,0),
d(2005,4,3,4,1,0),
d(2005,10,30,3,1,0),
d(2006,4,2,4,1,0),
d(2006,10,29,3,1,0),
d(2007,3,11,6,0,0),
d(2007,11,4,5,0,0),
d(2008,3,9,6,0,0),
d(2008,11,2,5,0,0),
d(2009,3,8,6,0,0),
d(2009,11,1,5,0,0),
d(2010,3,14,6,0,0),
d(2010,11,7,5,0,0),
d(2011,3,13,6,0,0),
d(2011,11,6,5,0,0),
d(2012,3,11,6,0,0),
d(2012,11,4,5,0,0),
d(2013,3,10,6,0,0),
d(2013,11,3,5,0,0),
d(2014,3,9,6,0,0),
d(2014,11,2,5,0,0),
d(2015,3,8,6,0,0),
d(2015,11,1,5,0,0),
d(2016,3,13,6,0,0),
d(2016,11,6,5,0,0),
d(2017,3,12,6,0,0),
d(2017,11,5,5,0,0),
d(2018,3,11,6,0,0),
d(2018,11,4,5,0,0),
d(2019,3,10,6,0,0),
d(2019,11,3,5,0,0),
d(2020,3,8,6,0,0),
d(2020,11,1,5,0,0),
d(2021,3,14,6,0,0),
d(2021,11,7,5,0,0),
d(2022,3,13,6,0,0),
d(2022,11,6,5,0,0),
d(2023,3,12,6,0,0),
d(2023,11,5,5,0,0),
d(2024,3,10,6,0,0),
d(2024,11,3,5,0,0),
d(2025,3,9,6,0,0),
d(2025,11,2,5,0,0),
d(2026,3,8,6,0,0),
d(2026,11,1,5,0,0),
d(2027,3,14,6,0,0),
d(2027,11,7,5,0,0),
d(2028,3,12,6,0,0),
d(2028,11,5,5,0,0),
d(2029,3,11,6,0,0),
d(2029,11,4,5,0,0),
d(2030,3,10,6,0,0),
d(2030,11,3,5,0,0),
d(2031,3,9,6,0,0),
d(2031,11,2,5,0,0),
d(2032,3,14,6,0,0),
d(2032,11,7,5,0,0),
d(2033,3,13,6,0,0),
d(2033,11,6,5,0,0),
d(2034,3,12,6,0,0),
d(2034,11,5,5,0,0),
d(2035,3,11,6,0,0),
d(2035,11,4,5,0,0),
d(2036,3,9,6,0,0),
d(2036,11,2,5,0,0),
d(2037,3,8,6,0,0),
d(2037,11,1,5,0,0),
]
_transition_info = [
i(-18000,0,'EST'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'AWT'),
i(-10800,3600,'APT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
]
Moncton = Moncton()
| 20.337182 | 78 | 0.563479 | from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Moncton(DstTzInfo):
zone = 'America/Moncton'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1902,6,15,5,0,0),
d(1918,4,14,6,0,0),
d(1918,10,31,5,0,0),
d(1933,6,11,5,0,0),
d(1933,9,10,4,0,0),
d(1934,6,10,5,0,0),
d(1934,9,9,4,0,0),
d(1935,6,9,5,0,0),
d(1935,9,8,4,0,0),
d(1936,6,7,5,0,0),
d(1936,9,6,4,0,0),
d(1937,6,6,5,0,0),
d(1937,9,5,4,0,0),
d(1938,6,5,5,0,0),
d(1938,9,4,4,0,0),
d(1939,5,27,5,0,0),
d(1939,9,23,4,0,0),
d(1940,5,19,5,0,0),
d(1940,9,21,4,0,0),
d(1941,5,4,5,0,0),
d(1941,9,27,4,0,0),
d(1942,2,9,6,0,0),
d(1945,8,14,23,0,0),
d(1945,9,30,5,0,0),
d(1946,4,28,6,0,0),
d(1946,9,29,5,0,0),
d(1947,4,27,6,0,0),
d(1947,9,28,5,0,0),
d(1948,4,25,6,0,0),
d(1948,9,26,5,0,0),
d(1949,4,24,6,0,0),
d(1949,9,25,5,0,0),
d(1950,4,30,6,0,0),
d(1950,9,24,5,0,0),
d(1951,4,29,6,0,0),
d(1951,9,30,5,0,0),
d(1952,4,27,6,0,0),
d(1952,9,28,5,0,0),
d(1953,4,26,6,0,0),
d(1953,9,27,5,0,0),
d(1954,4,25,6,0,0),
d(1954,9,26,5,0,0),
d(1955,4,24,6,0,0),
d(1955,9,25,5,0,0),
d(1956,4,29,6,0,0),
d(1956,9,30,5,0,0),
d(1957,4,28,6,0,0),
d(1957,10,27,5,0,0),
d(1958,4,27,6,0,0),
d(1958,10,26,5,0,0),
d(1959,4,26,6,0,0),
d(1959,10,25,5,0,0),
d(1960,4,24,6,0,0),
d(1960,10,30,5,0,0),
d(1961,4,30,6,0,0),
d(1961,10,29,5,0,0),
d(1962,4,29,6,0,0),
d(1962,10,28,5,0,0),
d(1963,4,28,6,0,0),
d(1963,10,27,5,0,0),
d(1964,4,26,6,0,0),
d(1964,10,25,5,0,0),
d(1965,4,25,6,0,0),
d(1965,10,31,5,0,0),
d(1966,4,24,6,0,0),
d(1966,10,30,5,0,0),
d(1967,4,30,6,0,0),
d(1967,10,29,5,0,0),
d(1968,4,28,6,0,0),
d(1968,10,27,5,0,0),
d(1969,4,27,6,0,0),
d(1969,10,26,5,0,0),
d(1970,4,26,6,0,0),
d(1970,10,25,5,0,0),
d(1971,4,25,6,0,0),
d(1971,10,31,5,0,0),
d(1972,4,30,6,0,0),
d(1972,10,29,5,0,0),
d(1974,4,28,6,0,0),
d(1974,10,27,5,0,0),
d(1975,4,27,6,0,0),
d(1975,10,26,5,0,0),
d(1976,4,25,6,0,0),
d(1976,10,31,5,0,0),
d(1977,4,24,6,0,0),
d(1977,10,30,5,0,0),
d(1978,4,30,6,0,0),
d(1978,10,29,5,0,0),
d(1979,4,29,6,0,0),
d(1979,10,28,5,0,0),
d(1980,4,27,6,0,0),
d(1980,10,26,5,0,0),
d(1981,4,26,6,0,0),
d(1981,10,25,5,0,0),
d(1982,4,25,6,0,0),
d(1982,10,31,5,0,0),
d(1983,4,24,6,0,0),
d(1983,10,30,5,0,0),
d(1984,4,29,6,0,0),
d(1984,10,28,5,0,0),
d(1985,4,28,6,0,0),
d(1985,10,27,5,0,0),
d(1986,4,27,6,0,0),
d(1986,10,26,5,0,0),
d(1987,4,5,6,0,0),
d(1987,10,25,5,0,0),
d(1988,4,3,6,0,0),
d(1988,10,30,5,0,0),
d(1989,4,2,6,0,0),
d(1989,10,29,5,0,0),
d(1990,4,1,6,0,0),
d(1990,10,28,5,0,0),
d(1991,4,7,6,0,0),
d(1991,10,27,5,0,0),
d(1992,4,5,6,0,0),
d(1992,10,25,5,0,0),
d(1993,4,4,4,1,0),
d(1993,10,31,3,1,0),
d(1994,4,3,4,1,0),
d(1994,10,30,3,1,0),
d(1995,4,2,4,1,0),
d(1995,10,29,3,1,0),
d(1996,4,7,4,1,0),
d(1996,10,27,3,1,0),
d(1997,4,6,4,1,0),
d(1997,10,26,3,1,0),
d(1998,4,5,4,1,0),
d(1998,10,25,3,1,0),
d(1999,4,4,4,1,0),
d(1999,10,31,3,1,0),
d(2000,4,2,4,1,0),
d(2000,10,29,3,1,0),
d(2001,4,1,4,1,0),
d(2001,10,28,3,1,0),
d(2002,4,7,4,1,0),
d(2002,10,27,3,1,0),
d(2003,4,6,4,1,0),
d(2003,10,26,3,1,0),
d(2004,4,4,4,1,0),
d(2004,10,31,3,1,0),
d(2005,4,3,4,1,0),
d(2005,10,30,3,1,0),
d(2006,4,2,4,1,0),
d(2006,10,29,3,1,0),
d(2007,3,11,6,0,0),
d(2007,11,4,5,0,0),
d(2008,3,9,6,0,0),
d(2008,11,2,5,0,0),
d(2009,3,8,6,0,0),
d(2009,11,1,5,0,0),
d(2010,3,14,6,0,0),
d(2010,11,7,5,0,0),
d(2011,3,13,6,0,0),
d(2011,11,6,5,0,0),
d(2012,3,11,6,0,0),
d(2012,11,4,5,0,0),
d(2013,3,10,6,0,0),
d(2013,11,3,5,0,0),
d(2014,3,9,6,0,0),
d(2014,11,2,5,0,0),
d(2015,3,8,6,0,0),
d(2015,11,1,5,0,0),
d(2016,3,13,6,0,0),
d(2016,11,6,5,0,0),
d(2017,3,12,6,0,0),
d(2017,11,5,5,0,0),
d(2018,3,11,6,0,0),
d(2018,11,4,5,0,0),
d(2019,3,10,6,0,0),
d(2019,11,3,5,0,0),
d(2020,3,8,6,0,0),
d(2020,11,1,5,0,0),
d(2021,3,14,6,0,0),
d(2021,11,7,5,0,0),
d(2022,3,13,6,0,0),
d(2022,11,6,5,0,0),
d(2023,3,12,6,0,0),
d(2023,11,5,5,0,0),
d(2024,3,10,6,0,0),
d(2024,11,3,5,0,0),
d(2025,3,9,6,0,0),
d(2025,11,2,5,0,0),
d(2026,3,8,6,0,0),
d(2026,11,1,5,0,0),
d(2027,3,14,6,0,0),
d(2027,11,7,5,0,0),
d(2028,3,12,6,0,0),
d(2028,11,5,5,0,0),
d(2029,3,11,6,0,0),
d(2029,11,4,5,0,0),
d(2030,3,10,6,0,0),
d(2030,11,3,5,0,0),
d(2031,3,9,6,0,0),
d(2031,11,2,5,0,0),
d(2032,3,14,6,0,0),
d(2032,11,7,5,0,0),
d(2033,3,13,6,0,0),
d(2033,11,6,5,0,0),
d(2034,3,12,6,0,0),
d(2034,11,5,5,0,0),
d(2035,3,11,6,0,0),
d(2035,11,4,5,0,0),
d(2036,3,9,6,0,0),
d(2036,11,2,5,0,0),
d(2037,3,8,6,0,0),
d(2037,11,1,5,0,0),
]
_transition_info = [
i(-18000,0,'EST'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'AWT'),
i(-10800,3600,'APT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
i(-10800,3600,'ADT'),
i(-14400,0,'AST'),
]
Moncton = Moncton()
| true | true |
f72c5ecb4c2bda8417b9edf7a53fca157ea84580 | 397 | py | Python | ReefberryPi/wsgi.py | reefberrypi/reefberrypi | f1e9977e8f56b402ef4d231ba8d4cdd0e469db42 | [
"MIT"
] | null | null | null | ReefberryPi/wsgi.py | reefberrypi/reefberrypi | f1e9977e8f56b402ef4d231ba8d4cdd0e469db42 | [
"MIT"
] | null | null | null | ReefberryPi/wsgi.py | reefberrypi/reefberrypi | f1e9977e8f56b402ef4d231ba8d4cdd0e469db42 | [
"MIT"
] | null | null | null | """
WSGI config for ReefberryPi project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ReefberryPi.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| 26.466667 | 78 | 0.793451 |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ReefberryPi.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| true | true |
f72c5ef7f4210f6058725bdb8a177f76f278f6d9 | 3,669 | py | Python | quetz/tests/test_workers.py | beenje/quetz | 1c9e5827e81f7ea89e7a0efc4c855ef63577a028 | [
"BSD-3-Clause"
] | null | null | null | quetz/tests/test_workers.py | beenje/quetz | 1c9e5827e81f7ea89e7a0efc4c855ef63577a028 | [
"BSD-3-Clause"
] | null | null | null | quetz/tests/test_workers.py | beenje/quetz | 1c9e5827e81f7ea89e7a0efc4c855ef63577a028 | [
"BSD-3-Clause"
] | null | null | null | import os
import socket
from contextlib import closing
import pytest
import requests
from fastapi import BackgroundTasks
from quetz.authorization import Rules
from quetz.dao import Dao
from quetz.db_models import User
from quetz.tasks.workers import RQManager, SubprocessWorker, ThreadingWorker
@pytest.fixture
def sqlite_url(config_dir):
# overriding sqlite_url to save to file so that
# we can access the same db from a sub-process
return f'sqlite:///{config_dir}/quetz.db'
@pytest.fixture
def http_session():
return requests.Session()
@pytest.fixture
def background_tasks():
bg_tasks = BackgroundTasks()
return bg_tasks
@pytest.fixture
def api_key():
return "api-key"
@pytest.fixture
def browser_session():
return {}
@pytest.fixture
def auth(db, api_key, browser_session):
return Rules(api_key, browser_session, db)
@pytest.fixture
def redis_ip():
return "127.0.0.1"
@pytest.fixture
def redis_port():
return 6379
@pytest.fixture
def redis_db():
return 0
@pytest.fixture
def threading_worker(background_tasks, dao, auth, http_session, config):
worker = ThreadingWorker(background_tasks, dao, auth, http_session, config)
return worker
@pytest.fixture
def subprocess_worker(api_key, browser_session, db, config):
SubprocessWorker._executor = None
worker = SubprocessWorker(api_key, browser_session, config)
return worker
@pytest.fixture
def redis_worker(redis_ip, redis_port, redis_db, api_key, browser_session, db, config):
worker = RQManager(
redis_ip,
redis_port,
redis_db,
api_key,
browser_session,
config,
no_testing=False,
)
return worker
def check_socket(host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.settimeout(2)
if sock.connect_ex((host, port)) == 0:
return True
else:
return False
def check_redis():
return check_socket('127.0.0.1', 6379)
@pytest.fixture(
params=[
"threading_worker",
"subprocess_worker",
pytest.param( # type: ignore
"redis_worker",
marks=pytest.mark.skipif(not check_redis(), reason='no redis'),
),
]
)
def any_worker(request):
val = request.getfixturevalue(request.param)
return val
def basic_function(config_dir):
os.chdir(config_dir)
with open("test.txt", "w") as fid:
fid.write("hello world!")
def function_with_dao(dao: Dao):
dao.create_user_with_role("my-user")
@pytest.fixture
def db_cleanup(config):
# we can't use the db fixture for cleaning up because
# it automatically rollsback all operations
yield
from quetz.database import get_session
db = get_session(config.sqlalchemy_database_url)
user = db.query(User).one_or_none()
if user:
db.delete(user)
db.commit()
@pytest.mark.asyncio
async def test_threading_worker_execute(background_tasks, any_worker, db, config_dir):
any_worker.execute(basic_function, config_dir=config_dir)
await any_worker.wait()
with open("test.txt") as fid:
output = fid.read()
assert output == "hello world!"
@pytest.mark.asyncio
async def test_threading_worker_execute_with_dao(
background_tasks, any_worker, db, db_cleanup
):
any_worker.execute(function_with_dao)
await any_worker.wait()
users = db.query(User).all()
assert len(users) == 1
assert users[0].username == 'my-user'
# we need to explicitly cleanup because sub-process did not use
# our db fixture, this will be done at teardown in the db_cleanup fixture
| 21.086207 | 87 | 0.696648 | import os
import socket
from contextlib import closing
import pytest
import requests
from fastapi import BackgroundTasks
from quetz.authorization import Rules
from quetz.dao import Dao
from quetz.db_models import User
from quetz.tasks.workers import RQManager, SubprocessWorker, ThreadingWorker
@pytest.fixture
def sqlite_url(config_dir):
return f'sqlite:///{config_dir}/quetz.db'
@pytest.fixture
def http_session():
return requests.Session()
@pytest.fixture
def background_tasks():
bg_tasks = BackgroundTasks()
return bg_tasks
@pytest.fixture
def api_key():
return "api-key"
@pytest.fixture
def browser_session():
return {}
@pytest.fixture
def auth(db, api_key, browser_session):
return Rules(api_key, browser_session, db)
@pytest.fixture
def redis_ip():
return "127.0.0.1"
@pytest.fixture
def redis_port():
return 6379
@pytest.fixture
def redis_db():
return 0
@pytest.fixture
def threading_worker(background_tasks, dao, auth, http_session, config):
worker = ThreadingWorker(background_tasks, dao, auth, http_session, config)
return worker
@pytest.fixture
def subprocess_worker(api_key, browser_session, db, config):
SubprocessWorker._executor = None
worker = SubprocessWorker(api_key, browser_session, config)
return worker
@pytest.fixture
def redis_worker(redis_ip, redis_port, redis_db, api_key, browser_session, db, config):
worker = RQManager(
redis_ip,
redis_port,
redis_db,
api_key,
browser_session,
config,
no_testing=False,
)
return worker
def check_socket(host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.settimeout(2)
if sock.connect_ex((host, port)) == 0:
return True
else:
return False
def check_redis():
return check_socket('127.0.0.1', 6379)
@pytest.fixture(
params=[
"threading_worker",
"subprocess_worker",
pytest.param(
"redis_worker",
marks=pytest.mark.skipif(not check_redis(), reason='no redis'),
),
]
)
def any_worker(request):
val = request.getfixturevalue(request.param)
return val
def basic_function(config_dir):
os.chdir(config_dir)
with open("test.txt", "w") as fid:
fid.write("hello world!")
def function_with_dao(dao: Dao):
dao.create_user_with_role("my-user")
@pytest.fixture
def db_cleanup(config):
# it automatically rollsback all operations
yield
from quetz.database import get_session
db = get_session(config.sqlalchemy_database_url)
user = db.query(User).one_or_none()
if user:
db.delete(user)
db.commit()
@pytest.mark.asyncio
async def test_threading_worker_execute(background_tasks, any_worker, db, config_dir):
any_worker.execute(basic_function, config_dir=config_dir)
await any_worker.wait()
with open("test.txt") as fid:
output = fid.read()
assert output == "hello world!"
@pytest.mark.asyncio
async def test_threading_worker_execute_with_dao(
background_tasks, any_worker, db, db_cleanup
):
any_worker.execute(function_with_dao)
await any_worker.wait()
users = db.query(User).all()
assert len(users) == 1
assert users[0].username == 'my-user'
# we need to explicitly cleanup because sub-process did not use
# our db fixture, this will be done at teardown in the db_cleanup fixture
| true | true |
f72c5f1f4d6cd6f6582fcd1e96aee59135e0c5f7 | 14,438 | py | Python | grr/lib/lexer.py | nexus-lab/relf-server | d46774799c20376691c38f9293f454a3aff3ccb3 | [
"Apache-2.0"
] | null | null | null | grr/lib/lexer.py | nexus-lab/relf-server | d46774799c20376691c38f9293f454a3aff3ccb3 | [
"Apache-2.0"
] | null | null | null | grr/lib/lexer.py | nexus-lab/relf-server | d46774799c20376691c38f9293f454a3aff3ccb3 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
"""An LL(1) lexer. This lexer is very tolerant of errors and can resync."""
import logging
import re
from grr.lib import utils
class Token(object):
"""A token action."""
state_regex = None
def __init__(self, state_regex, regex, actions, next_state, flags=re.I):
"""Constructor.
Args:
state_regex: If this regular expression matches the current state this
rule is considered.
regex: A regular expression to try and match from the current point.
actions: A command separated list of method names in the Lexer to call.
next_state: The next state we transition to if this Token matches.
flags: re flags.
"""
if state_regex:
self.state_regex = re.compile(state_regex, re.DOTALL | re.M | re.S | re.U
| flags)
self.regex = re.compile(regex, re.DOTALL | re.M | re.S | re.U | flags)
self.re_str = regex
self.actions = []
if actions:
self.actions = actions.split(",")
self.next_state = next_state
def Action(self, lexer):
"""Method is called when the token matches."""
class Error(Exception):
"""Module exception."""
class ParseError(Error):
"""A parse error occured."""
class Lexer(object):
"""A generic feed lexer."""
# A list of Token() instances.
tokens = []
# Regex flags
flags = 0
def __init__(self, data=""):
# Set the lexer up to process a new data feed.
self.Reset()
# Populate internal token list with class tokens, if defined.
self._tokens = self.tokens[:]
# Populate the lexer with any data we got.
self.buffer = utils.SmartStr(data)
def Reset(self):
"""Reset the lexer to process a new data feed."""
# The first state
self.state = "INITIAL"
self.state_stack = []
# The buffer we are parsing now
self.buffer = ""
self.error = 0
self.verbose = 0
# The index into the buffer where we are currently pointing
self.processed = 0
self.processed_buffer = ""
def NextToken(self):
"""Fetch the next token by trying to match any of the regexes in order."""
# Nothing in the input stream - no token can match.
if not self.buffer:
return
current_state = self.state
for token in self._tokens:
# Does the rule apply to us?
if token.state_regex and not token.state_regex.match(current_state):
continue
if self.verbose:
logging.debug("%s: Trying to match %r with %r", self.state,
self.buffer[:10], token.re_str)
# Try to match the rule
m = token.regex.match(self.buffer)
if not m:
continue
if self.verbose:
logging.debug("%s matched %s", token.re_str, m.group(0))
# A token matched the empty string. We can not consume the token from the
# input stream.
if m.end() == 0:
raise RuntimeError("Lexer bug! Token can not match the empty string.")
# The match consumes the data off the buffer (the handler can put it back
# if it likes)
self.processed_buffer += self.buffer[:m.end()]
self.buffer = self.buffer[m.end():]
self.processed += m.end()
next_state = token.next_state
for action in token.actions:
if self.verbose:
logging.debug("Calling %s with %s", action, m.group(0))
# Is there a callback to handle this action?
cb = getattr(self, action, self.Default)
# Allow a callback to skip other callbacks.
try:
possible_next_state = cb(string=m.group(0), match=m)
if possible_next_state == "CONTINUE":
continue
# Override the state from the Token
elif possible_next_state:
next_state = possible_next_state
except ParseError as e:
self.Error(e)
# Update the next state
if next_state:
self.state = next_state
return token
# Check that we are making progress - if we are too full, we assume we are
# stuck.
self.Error("Lexer stuck at state %s" % (self.state))
self.processed_buffer += self.buffer[:1]
self.buffer = self.buffer[1:]
return "Error"
def Feed(self, data):
self.buffer += data
def Empty(self):
return not self.buffer
def Default(self, **kwarg):
logging.debug("Default handler: %s", kwarg)
def Error(self, message=None, weight=1):
logging.debug("Error(%s): %s", weight, message)
# Keep a count of errors
self.error += weight
def PushState(self, **_):
"""Push the current state on the state stack."""
if self.verbose:
logging.debug("Storing state %r", self.state)
self.state_stack.append(self.state)
def PopState(self, **_):
"""Pop the previous state from the stack."""
try:
self.state = self.state_stack.pop()
if self.verbose:
logging.debug("Returned state to %s", self.state)
return self.state
except IndexError:
self.Error("Tried to pop the state but failed - possible recursion error")
def PushBack(self, string="", **_):
"""Push the match back on the stream."""
self.buffer = string + self.buffer
self.processed_buffer = self.processed_buffer[:-len(string)]
def Close(self):
"""A convenience function to force us to parse all the data."""
while self.NextToken():
if not self.buffer:
return
class SelfFeederMixIn(Lexer):
"""This mixin is used to make a lexer which feeds itself.
Note that self.fd must be the fd we read from.
"""
def __init__(self, fd=""):
self.fd = fd
super(SelfFeederMixIn, self).__init__()
def NextToken(self, end=True):
# If we dont have enough data - feed ourselves: We assume
# that we must have at least one sector in our buffer.
if len(self.buffer) < 512:
if self.Feed() == 0 and not self.buffer:
return None
return Lexer.next_token(self, end)
def Feed(self, size=512):
data = self.fd.read(size)
Lexer.feed(self, data)
return len(data)
class Expression(object):
"""A class representing an expression."""
attribute = None
args = None
operator = None
# The expected number of args
number_of_args = 1
def __init__(self):
self.args = []
def SetAttribute(self, attribute):
self.attribute = attribute
def SetOperator(self, operator):
self.operator = operator
def AddArg(self, arg):
"""Adds a new arg to this expression.
Args:
arg: The argument to add (string).
Returns:
True if this arg is the last arg, False otherwise.
Raises:
ParseError: If there are too many args.
"""
self.args.append(arg)
if len(self.args) > self.number_of_args:
raise ParseError("Too many args for this expression.")
elif len(self.args) == self.number_of_args:
return True
return False
def __str__(self):
return "Expression: (%s) (%s) %s" % (self.attribute, self.operator,
self.args)
def PrintTree(self, depth=""):
return "%s %s" % (depth, self)
def Compile(self, filter_implemention):
"""Given a filter implementation, compile this expression."""
raise NotImplementedError(
"%s does not implement Compile." % self.__class__.__name__)
class BinaryExpression(Expression):
"""An expression which takes two other expressions."""
def __init__(self, operator="", part=None):
self.operator = operator
self.args = []
if part:
self.args.append(part)
super(BinaryExpression, self).__init__()
def __str__(self):
return "Binary Expression: %s %s" % (self.operator,
[str(x) for x in self.args])
def AddOperands(self, lhs, rhs):
if isinstance(lhs, Expression) and isinstance(rhs, Expression):
self.args.insert(0, lhs)
self.args.append(rhs)
else:
raise ParseError("Expected expression, got %s %s %s" %
(lhs, self.operator, rhs))
def PrintTree(self, depth=""):
result = "%s%s\n" % (depth, self.operator)
for part in self.args:
result += "%s-%s\n" % (depth, part.PrintTree(depth + " "))
return result
def Compile(self, filter_implemention):
"""Compile the binary expression into a filter object."""
operator = self.operator.lower()
if operator == "and" or operator == "&&":
method = "AndFilter"
elif operator == "or" or operator == "||":
method = "OrFilter"
else:
raise ParseError("Invalid binary operator %s" % operator)
args = [x.Compile(filter_implemention) for x in self.args]
return filter_implemention.GetFilter(method)(*args)
class IdentityExpression(Expression):
"""An Expression which always evaluates to True."""
def Compile(self, filter_implemention):
return filter_implemention.IdentityFilter()
class SearchParser(Lexer):
"""This parser can parse the mini query language and build an AST.
Examples of valid syntax:
filename contains "foo" and (size > 100k or date before "2011-10")
date between 2011 and 2010
files older than 1 year
"""
expression_cls = Expression
binary_expression_cls = BinaryExpression
identity_expression_cls = IdentityExpression
string = ""
tokens = [
# Double quoted string
Token("STRING", "\"", "PopState,StringFinish", None),
Token("STRING", r"\\(.)", "StringEscape", None),
Token("STRING", r"[^\\\"]+", "StringInsert", None),
# Single quoted string
Token("SQ_STRING", "'", "PopState,StringFinish", None),
Token("SQ_STRING", r"\\(.)", "StringEscape", None),
Token("SQ_STRING", r"[^\\']+", "StringInsert", None),
# TODO(user): Implement a unary not operator.
# The first thing we see in the initial state takes up to the ATTRIBUTE
Token("INITIAL", r"(and|or|\&\&|\|\|)", "BinaryOperator", None),
Token("INITIAL", r"[^\s\(\)]", "PushState,PushBack", "ATTRIBUTE"),
Token("INITIAL", r"\(", "BracketOpen", None),
Token("INITIAL", r"\)", "BracketClose", None),
Token("ATTRIBUTE", r"[\w._0-9]+", "StoreAttribute", "OPERATOR"),
Token("OPERATOR", r"[a-z0-9<>=\-\+\!\^\&%]+", "StoreOperator",
"ARG_LIST"),
Token("OPERATOR", "(!=|[<>=])", "StoreSpecialOperator", "ARG_LIST"),
Token("ARG_LIST", r"[^\s'\"]+", "InsertArg", None),
# Start a string.
Token(".", "\"", "PushState,StringStart", "STRING"),
Token(".", "'", "PushState,StringStart", "SQ_STRING"),
# Skip whitespace.
Token(".", r"\s+", None, None),
]
def __init__(self, data):
# Holds expression
self.current_expression = self.expression_cls()
self.filter_string = data
# The token stack
self.stack = []
Lexer.__init__(self, data)
def BinaryOperator(self, string=None, **_):
self.stack.append(self.binary_expression_cls(string))
def BracketOpen(self, **_):
self.stack.append("(")
def BracketClose(self, **_):
self.stack.append(")")
def StringStart(self, **_):
self.string = ""
def StringEscape(self, string, match, **_):
"""Escape backslashes found inside a string quote.
Backslashes followed by anything other than ['"rnbt] will just be included
in the string.
Args:
string: The string that matched.
match: The match object (m.group(1) is the escaped code)
"""
if match.group(1) in "'\"rnbt":
self.string += string.decode("string_escape")
else:
self.string += string
def StringInsert(self, string="", **_):
self.string += string
def StringFinish(self, **_):
if self.state == "ATTRIBUTE":
return self.StoreAttribute(string=self.string)
elif self.state == "ARG_LIST":
return self.InsertArg(string=self.string)
def StoreAttribute(self, string="", **_):
if self.verbose:
logging.debug("Storing attribute %r", string)
# TODO(user): Update the expected number_of_args
try:
self.current_expression.SetAttribute(string)
except AttributeError:
raise ParseError("Invalid attribute '%s'" % string)
return "OPERATOR"
def StoreOperator(self, string="", **_):
if self.verbose:
logging.debug("Storing operator %r", string)
self.current_expression.SetOperator(string)
def InsertArg(self, string="", **_):
"""Insert an arg to the current expression."""
if self.verbose:
logging.debug("Storing Argument %s", utils.SmartUnicode(string))
# This expression is complete
if self.current_expression.AddArg(string):
self.stack.append(self.current_expression)
self.current_expression = self.expression_cls()
return self.PopState()
def _CombineBinaryExpressions(self, operator):
for i in range(1, len(self.stack) - 1):
item = self.stack[i]
if (isinstance(item, BinaryExpression) and item.operator == operator and
isinstance(self.stack[i - 1], Expression) and
isinstance(self.stack[i + 1], Expression)):
lhs = self.stack[i - 1]
rhs = self.stack[i + 1]
self.stack[i].AddOperands(lhs, rhs)
self.stack[i - 1] = None
self.stack[i + 1] = None
self.stack = filter(None, self.stack)
def _CombineParenthesis(self):
for i in range(len(self.stack) - 2):
if (self.stack[i] == "(" and self.stack[i + 2] == ")" and
isinstance(self.stack[i + 1], Expression)):
self.stack[i] = None
self.stack[i + 2] = None
self.stack = filter(None, self.stack)
def Reduce(self):
"""Reduce the token stack into an AST."""
# Check for sanity
if self.state != "INITIAL":
self.Error("Premature end of expression")
length = len(self.stack)
while length > 1:
# Precendence order
self._CombineParenthesis()
self._CombineBinaryExpressions("and")
self._CombineBinaryExpressions("or")
# No change
if len(self.stack) == length:
break
length = len(self.stack)
if length != 1:
self.Error("Illegal query expression")
return self.stack[0]
def Error(self, message=None, weight=1):
raise ParseError(u"%s in position %s: %s <----> %s )" %
(utils.SmartUnicode(message), len(self.processed_buffer),
self.processed_buffer, self.buffer))
def Parse(self):
if not self.filter_string:
return self.identity_expression_cls()
self.Close()
return self.Reduce()
| 28.991968 | 80 | 0.626333 |
import logging
import re
from grr.lib import utils
class Token(object):
state_regex = None
def __init__(self, state_regex, regex, actions, next_state, flags=re.I):
if state_regex:
self.state_regex = re.compile(state_regex, re.DOTALL | re.M | re.S | re.U
| flags)
self.regex = re.compile(regex, re.DOTALL | re.M | re.S | re.U | flags)
self.re_str = regex
self.actions = []
if actions:
self.actions = actions.split(",")
self.next_state = next_state
def Action(self, lexer):
class Error(Exception):
class ParseError(Error):
class Lexer(object):
tokens = []
flags = 0
def __init__(self, data=""):
self.Reset()
self._tokens = self.tokens[:]
self.buffer = utils.SmartStr(data)
def Reset(self):
self.state = "INITIAL"
self.state_stack = []
self.buffer = ""
self.error = 0
self.verbose = 0
self.processed = 0
self.processed_buffer = ""
def NextToken(self):
if not self.buffer:
return
current_state = self.state
for token in self._tokens:
if token.state_regex and not token.state_regex.match(current_state):
continue
if self.verbose:
logging.debug("%s: Trying to match %r with %r", self.state,
self.buffer[:10], token.re_str)
m = token.regex.match(self.buffer)
if not m:
continue
if self.verbose:
logging.debug("%s matched %s", token.re_str, m.group(0))
if m.end() == 0:
raise RuntimeError("Lexer bug! Token can not match the empty string.")
self.processed_buffer += self.buffer[:m.end()]
self.buffer = self.buffer[m.end():]
self.processed += m.end()
next_state = token.next_state
for action in token.actions:
if self.verbose:
logging.debug("Calling %s with %s", action, m.group(0))
cb = getattr(self, action, self.Default)
try:
possible_next_state = cb(string=m.group(0), match=m)
if possible_next_state == "CONTINUE":
continue
elif possible_next_state:
next_state = possible_next_state
except ParseError as e:
self.Error(e)
if next_state:
self.state = next_state
return token
self.Error("Lexer stuck at state %s" % (self.state))
self.processed_buffer += self.buffer[:1]
self.buffer = self.buffer[1:]
return "Error"
def Feed(self, data):
self.buffer += data
def Empty(self):
return not self.buffer
def Default(self, **kwarg):
logging.debug("Default handler: %s", kwarg)
def Error(self, message=None, weight=1):
logging.debug("Error(%s): %s", weight, message)
self.error += weight
def PushState(self, **_):
if self.verbose:
logging.debug("Storing state %r", self.state)
self.state_stack.append(self.state)
def PopState(self, **_):
try:
self.state = self.state_stack.pop()
if self.verbose:
logging.debug("Returned state to %s", self.state)
return self.state
except IndexError:
self.Error("Tried to pop the state but failed - possible recursion error")
def PushBack(self, string="", **_):
self.buffer = string + self.buffer
self.processed_buffer = self.processed_buffer[:-len(string)]
def Close(self):
while self.NextToken():
if not self.buffer:
return
class SelfFeederMixIn(Lexer):
def __init__(self, fd=""):
self.fd = fd
super(SelfFeederMixIn, self).__init__()
def NextToken(self, end=True):
if len(self.buffer) < 512:
if self.Feed() == 0 and not self.buffer:
return None
return Lexer.next_token(self, end)
def Feed(self, size=512):
data = self.fd.read(size)
Lexer.feed(self, data)
return len(data)
class Expression(object):
attribute = None
args = None
operator = None
number_of_args = 1
def __init__(self):
self.args = []
def SetAttribute(self, attribute):
self.attribute = attribute
def SetOperator(self, operator):
self.operator = operator
def AddArg(self, arg):
self.args.append(arg)
if len(self.args) > self.number_of_args:
raise ParseError("Too many args for this expression.")
elif len(self.args) == self.number_of_args:
return True
return False
def __str__(self):
return "Expression: (%s) (%s) %s" % (self.attribute, self.operator,
self.args)
def PrintTree(self, depth=""):
return "%s %s" % (depth, self)
def Compile(self, filter_implemention):
raise NotImplementedError(
"%s does not implement Compile." % self.__class__.__name__)
class BinaryExpression(Expression):
def __init__(self, operator="", part=None):
self.operator = operator
self.args = []
if part:
self.args.append(part)
super(BinaryExpression, self).__init__()
def __str__(self):
return "Binary Expression: %s %s" % (self.operator,
[str(x) for x in self.args])
def AddOperands(self, lhs, rhs):
if isinstance(lhs, Expression) and isinstance(rhs, Expression):
self.args.insert(0, lhs)
self.args.append(rhs)
else:
raise ParseError("Expected expression, got %s %s %s" %
(lhs, self.operator, rhs))
def PrintTree(self, depth=""):
result = "%s%s\n" % (depth, self.operator)
for part in self.args:
result += "%s-%s\n" % (depth, part.PrintTree(depth + " "))
return result
def Compile(self, filter_implemention):
operator = self.operator.lower()
if operator == "and" or operator == "&&":
method = "AndFilter"
elif operator == "or" or operator == "||":
method = "OrFilter"
else:
raise ParseError("Invalid binary operator %s" % operator)
args = [x.Compile(filter_implemention) for x in self.args]
return filter_implemention.GetFilter(method)(*args)
class IdentityExpression(Expression):
def Compile(self, filter_implemention):
return filter_implemention.IdentityFilter()
class SearchParser(Lexer):
expression_cls = Expression
binary_expression_cls = BinaryExpression
identity_expression_cls = IdentityExpression
string = ""
tokens = [
Token("STRING", "\"", "PopState,StringFinish", None),
Token("STRING", r"\\(.)", "StringEscape", None),
Token("STRING", r"[^\\\"]+", "StringInsert", None),
Token("SQ_STRING", "'", "PopState,StringFinish", None),
Token("SQ_STRING", r"\\(.)", "StringEscape", None),
Token("SQ_STRING", r"[^\\']+", "StringInsert", None),
Token("INITIAL", r"(and|or|\&\&|\|\|)", "BinaryOperator", None),
Token("INITIAL", r"[^\s\(\)]", "PushState,PushBack", "ATTRIBUTE"),
Token("INITIAL", r"\(", "BracketOpen", None),
Token("INITIAL", r"\)", "BracketClose", None),
Token("ATTRIBUTE", r"[\w._0-9]+", "StoreAttribute", "OPERATOR"),
Token("OPERATOR", r"[a-z0-9<>=\-\+\!\^\&%]+", "StoreOperator",
"ARG_LIST"),
Token("OPERATOR", "(!=|[<>=])", "StoreSpecialOperator", "ARG_LIST"),
Token("ARG_LIST", r"[^\s'\"]+", "InsertArg", None),
# Start a string.
Token(".", "\"", "PushState,StringStart", "STRING"),
Token(".", "'", "PushState,StringStart", "SQ_STRING"),
Token(".", r"\s+", None, None),
]
def __init__(self, data):
self.current_expression = self.expression_cls()
self.filter_string = data
self.stack = []
Lexer.__init__(self, data)
def BinaryOperator(self, string=None, **_):
self.stack.append(self.binary_expression_cls(string))
def BracketOpen(self, **_):
self.stack.append("(")
def BracketClose(self, **_):
self.stack.append(")")
def StringStart(self, **_):
self.string = ""
def StringEscape(self, string, match, **_):
if match.group(1) in "'\"rnbt":
self.string += string.decode("string_escape")
else:
self.string += string
def StringInsert(self, string="", **_):
self.string += string
def StringFinish(self, **_):
if self.state == "ATTRIBUTE":
return self.StoreAttribute(string=self.string)
elif self.state == "ARG_LIST":
return self.InsertArg(string=self.string)
def StoreAttribute(self, string="", **_):
if self.verbose:
logging.debug("Storing attribute %r", string)
# TODO(user): Update the expected number_of_args
try:
self.current_expression.SetAttribute(string)
except AttributeError:
raise ParseError("Invalid attribute '%s'" % string)
return "OPERATOR"
def StoreOperator(self, string="", **_):
if self.verbose:
logging.debug("Storing operator %r", string)
self.current_expression.SetOperator(string)
def InsertArg(self, string="", **_):
if self.verbose:
logging.debug("Storing Argument %s", utils.SmartUnicode(string))
# This expression is complete
if self.current_expression.AddArg(string):
self.stack.append(self.current_expression)
self.current_expression = self.expression_cls()
return self.PopState()
def _CombineBinaryExpressions(self, operator):
for i in range(1, len(self.stack) - 1):
item = self.stack[i]
if (isinstance(item, BinaryExpression) and item.operator == operator and
isinstance(self.stack[i - 1], Expression) and
isinstance(self.stack[i + 1], Expression)):
lhs = self.stack[i - 1]
rhs = self.stack[i + 1]
self.stack[i].AddOperands(lhs, rhs)
self.stack[i - 1] = None
self.stack[i + 1] = None
self.stack = filter(None, self.stack)
def _CombineParenthesis(self):
for i in range(len(self.stack) - 2):
if (self.stack[i] == "(" and self.stack[i + 2] == ")" and
isinstance(self.stack[i + 1], Expression)):
self.stack[i] = None
self.stack[i + 2] = None
self.stack = filter(None, self.stack)
def Reduce(self):
# Check for sanity
if self.state != "INITIAL":
self.Error("Premature end of expression")
length = len(self.stack)
while length > 1:
# Precendence order
self._CombineParenthesis()
self._CombineBinaryExpressions("and")
self._CombineBinaryExpressions("or")
# No change
if len(self.stack) == length:
break
length = len(self.stack)
if length != 1:
self.Error("Illegal query expression")
return self.stack[0]
def Error(self, message=None, weight=1):
raise ParseError(u"%s in position %s: %s <----> %s )" %
(utils.SmartUnicode(message), len(self.processed_buffer),
self.processed_buffer, self.buffer))
def Parse(self):
if not self.filter_string:
return self.identity_expression_cls()
self.Close()
return self.Reduce()
| true | true |
f72c5f21b10b223a9ba7876395cff13950f436cd | 5,375 | py | Python | hw2skeleton/k_means.py | egilbertson-ucsf/algHW2 | eec0f4e42e27d4c7633cc907d6f523285fadd79c | [
"Apache-2.0"
] | 1 | 2022-02-07T21:00:46.000Z | 2022-02-07T21:00:46.000Z | hw2skeleton/k_means.py | egilbertson-ucsf/algHW2 | eec0f4e42e27d4c7633cc907d6f523285fadd79c | [
"Apache-2.0"
] | null | null | null | hw2skeleton/k_means.py | egilbertson-ucsf/algHW2 | eec0f4e42e27d4c7633cc907d6f523285fadd79c | [
"Apache-2.0"
] | null | null | null | from hw2skeleton import cluster as cl
from hw2skeleton import io
import sklearn.metrics as sk
import os
import pandas as pd
import numpy as np
import math
aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split()
aa_df = pd.DataFrame(0, index=list(aa3), columns=['Count'])
def calc_avg_site_length(sites):
'''
calculate the average size of an active site
for use in generating random sites
'''
ss = []
for site in sites:
ss.append(len(site.residues))
return [sum(ss) / len(sites), max(ss), min(ss)]
def generate_random_site(sites):
'''
generate a random site by filling in a 1x20 vector repr of amino acids with counts
'''
lens = calc_avg_site_length(sites)
num_res = np.random.randint(lens[2],lens[1])
site = aa_df.copy()
for pos in range(num_res):
aa = np.random.randint(0,19)
site.iloc[aa] += 1
return site
def generate_k_random_centroids(k, sites):
'''
generate k random sites using above function
'''
centroids = {}
for i in range(k):
centroids[i] = generate_random_site(sites)
return centroids
def assign_single_site_to_cluster(site, centroids):
'''
check which cluster centroid is closest to the given site and assign the
site to that cluster
'''
loc = site.counts
dists = {}
for c in centroids.keys():
dist = cl.compute_similarity(loc, centroids[c])
dists[dist] = c
closest = dists[min(dists.keys())]
return closest
def assign_all_sites_to_cluster(sites, centroids, clusters):
'''
loop through all sites and assign them to the appropriate clusters
'''
for site in sites:
close = assign_single_site_to_cluster(site, centroids)
if close not in clusters:
clusters[close] = [site]
else:
clusters[close].append(site)
for cent in centroids:
if cent not in clusters:
clusters[cent] = []
return clusters
def compute_cluster_center(cluster_list, sites_dict):
'''
compute the center of a cluster by taking the average of the vector representations
of all sites in the cluster
'''
sites = aa_df.copy()
for j in cluster_list:
if isinstance(j, str):
sites += sites_dict[j].counts
else:
sites += j.counts
return sites / len(sites)
def get_new_centroids(clusters, sites_dict=None):
'''
use the compute_cluster_center function to get the new centroids after updating
assignments
'''
centroids = {}
for cluster in clusters.keys():
centroids[cluster] = compute_cluster_center(clusters[cluster], sites_dict)
return centroids
def check_change_in_centroids(old_centroids, new_centroids):
''' check how far the centroids have moved '''
diff = 0
for c in old_centroids.keys():
diff += cl.compute_similarity(old_centroids[c], new_centroids[c])
return diff
def one_full_k_means(sites, k):
''' using all above functions, one full iteration of k means'''
centroids = generate_k_random_centroids(k, sites)
clusters = {}
clusters = assign_all_sites_to_cluster(sites, centroids, clusters)
new_centroids = get_new_centroids(clusters)
old_diff = check_change_in_centroids(centroids, new_centroids)
new_diff = 0
while old_diff - new_diff > 0.00001:
old_diff = check_change_in_centroids(centroids, new_centroids)
centroids = new_centroids.copy()
clusters = {}
clusters = assign_all_sites_to_cluster(sites, centroids, clusters)
new_centroids = get_new_centroids(clusters)
new_diff = check_change_in_centroids(centroids, new_centroids)
return clusters, centroids
def compute_similarity_matrix(sites):
''' copy of computer similarity matrix from utils '''
simMat = []
names = []
for i in range(len(sites)):
names.append(sites[i].name)
row = []
for j in range(len(sites)):
row.append(cl.compute_similarity(sites[i].counts,sites[j].counts))
simMat.append(row)
simMat = pd.DataFrame(simMat, columns = names, index = names)
return simMat
def make_cluster_assign_df(clusters, simMat):
''' make a nice df repr of the cluster assignments'''
assgn = pd.DataFrame(index = simMat.index, columns = ['Cluster Assignment'])
for cluster in clusters.keys():
for site in clusters[cluster]:
assgn.loc[site.name] = cluster
return assgn
def avg_sl(sites, k, simMat):
''' average silhouette_score for i random starts of k means for k clusters'''
scores = []
c_list = []
for i in range(1):
clusters, centroids = one_full_k_means(sites, k)
assgn = make_cluster_assign_df(clusters, simMat)
c_list.append(clusters)
scores.append(sk.silhouette_score(simMat, assgn['Cluster Assignment'], metric='precomputed'))
return scores, clusters
def k_means(sites=None):
''' run k means '''
sites = io.read_active_sites('data')
simMat = compute_similarity_matrix(sites)
points = [[],[]]
clusters = []
for i in range(2,5):
points[0].append(i)
temp = avg_sl(sites, i , simMat)
points[1].append(temp[0])
clusters.append(temp[1])
return clusters[points[1].index(max(points[1]))], max(points[1])
| 31.25 | 101 | 0.661767 | from hw2skeleton import cluster as cl
from hw2skeleton import io
import sklearn.metrics as sk
import os
import pandas as pd
import numpy as np
import math
aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split()
aa_df = pd.DataFrame(0, index=list(aa3), columns=['Count'])
def calc_avg_site_length(sites):
ss = []
for site in sites:
ss.append(len(site.residues))
return [sum(ss) / len(sites), max(ss), min(ss)]
def generate_random_site(sites):
lens = calc_avg_site_length(sites)
num_res = np.random.randint(lens[2],lens[1])
site = aa_df.copy()
for pos in range(num_res):
aa = np.random.randint(0,19)
site.iloc[aa] += 1
return site
def generate_k_random_centroids(k, sites):
centroids = {}
for i in range(k):
centroids[i] = generate_random_site(sites)
return centroids
def assign_single_site_to_cluster(site, centroids):
loc = site.counts
dists = {}
for c in centroids.keys():
dist = cl.compute_similarity(loc, centroids[c])
dists[dist] = c
closest = dists[min(dists.keys())]
return closest
def assign_all_sites_to_cluster(sites, centroids, clusters):
for site in sites:
close = assign_single_site_to_cluster(site, centroids)
if close not in clusters:
clusters[close] = [site]
else:
clusters[close].append(site)
for cent in centroids:
if cent not in clusters:
clusters[cent] = []
return clusters
def compute_cluster_center(cluster_list, sites_dict):
sites = aa_df.copy()
for j in cluster_list:
if isinstance(j, str):
sites += sites_dict[j].counts
else:
sites += j.counts
return sites / len(sites)
def get_new_centroids(clusters, sites_dict=None):
centroids = {}
for cluster in clusters.keys():
centroids[cluster] = compute_cluster_center(clusters[cluster], sites_dict)
return centroids
def check_change_in_centroids(old_centroids, new_centroids):
diff = 0
for c in old_centroids.keys():
diff += cl.compute_similarity(old_centroids[c], new_centroids[c])
return diff
def one_full_k_means(sites, k):
centroids = generate_k_random_centroids(k, sites)
clusters = {}
clusters = assign_all_sites_to_cluster(sites, centroids, clusters)
new_centroids = get_new_centroids(clusters)
old_diff = check_change_in_centroids(centroids, new_centroids)
new_diff = 0
while old_diff - new_diff > 0.00001:
old_diff = check_change_in_centroids(centroids, new_centroids)
centroids = new_centroids.copy()
clusters = {}
clusters = assign_all_sites_to_cluster(sites, centroids, clusters)
new_centroids = get_new_centroids(clusters)
new_diff = check_change_in_centroids(centroids, new_centroids)
return clusters, centroids
def compute_similarity_matrix(sites):
simMat = []
names = []
for i in range(len(sites)):
names.append(sites[i].name)
row = []
for j in range(len(sites)):
row.append(cl.compute_similarity(sites[i].counts,sites[j].counts))
simMat.append(row)
simMat = pd.DataFrame(simMat, columns = names, index = names)
return simMat
def make_cluster_assign_df(clusters, simMat):
assgn = pd.DataFrame(index = simMat.index, columns = ['Cluster Assignment'])
for cluster in clusters.keys():
for site in clusters[cluster]:
assgn.loc[site.name] = cluster
return assgn
def avg_sl(sites, k, simMat):
scores = []
c_list = []
for i in range(1):
clusters, centroids = one_full_k_means(sites, k)
assgn = make_cluster_assign_df(clusters, simMat)
c_list.append(clusters)
scores.append(sk.silhouette_score(simMat, assgn['Cluster Assignment'], metric='precomputed'))
return scores, clusters
def k_means(sites=None):
sites = io.read_active_sites('data')
simMat = compute_similarity_matrix(sites)
points = [[],[]]
clusters = []
for i in range(2,5):
points[0].append(i)
temp = avg_sl(sites, i , simMat)
points[1].append(temp[0])
clusters.append(temp[1])
return clusters[points[1].index(max(points[1]))], max(points[1])
| true | true |
f72c5fd356bc70a6fedc8a393b6f0f7e3a5126db | 3,817 | py | Python | zester/client.py | Rahul09123/zester | e878ba5ce66156a642bc7513a69dc4175f9393be | [
"ISC"
] | 10 | 2015-10-17T16:12:30.000Z | 2021-12-09T04:08:47.000Z | zester/client.py | Rahul09123/zester | e878ba5ce66156a642bc7513a69dc4175f9393be | [
"ISC"
] | null | null | null | zester/client.py | Rahul09123/zester | e878ba5ce66156a642bc7513a69dc4175f9393be | [
"ISC"
] | 2 | 2020-05-05T04:04:28.000Z | 2020-09-30T14:19:16.000Z | from collections import namedtuple
import inspect
import os
from ghost import Ghost
class Client(object):
def __init__(self, url=None):
if url:
self.url = url
assert self.url, "All clients must have a URL attribute"
self._attributes = self._collect_attributes()
self._class_model = self._setup_class_model()
self._ghost = Ghost()
def process(self):
self._load_ghost()
attribute_results = self._process_attributes()
self._object_results = self._make_objects(attribute_results)
return self._object_results
def _setup_class_model(self):
class_name = self.__class__.__name__
return namedtuple(class_name + "Response", self._attributes.keys())
def _process_attributes(self):
results = []
for attribute_name, attribute in self._attributes.iteritems():
result, resources = self._ghost.evaluate(attribute.query)
# If a node was selected, return it's data
if isinstance(result, dict):
if 'data' in result:
result = result['data']
elif 'selector' in result:
raise TypeError("The attribute {} returned a selector"
" instead of a node.".format(attribute_name))
results.append(result)
return results
def _make_objects(self, attribute_results):
raise NotImplementedError()
def _collect_attributes(self):
attrs = [(attr_name, attr) for (attr_name, attr) in
inspect.getmembers(self) if isinstance(attr, Attribute)]
return dict(attrs)
def _load_ghost(self):
page, extra_resources = self._ghost.open(self.url)
# For local testing, page is None
if page:
# TODO should error better
assert page.http_status < 400
# Load jquery
jquery_path = os.path.join(os.path.abspath(os.curdir),
'zester', 'fixtures', 'jquery.min.js')
jquery_text = open(jquery_path, 'r').read()
result, resources = self._ghost.evaluate(jquery_text)
class MultipleClient(Client):
def _process_attributes(self):
results = super(MultipleClient, self)._process_attributes()
if not results:
return results
zipped_results = zip(*results)
return zipped_results
def _make_objects(self, attribute_results):
object_results = []
attribute_names = self._attributes.keys()
for attribute_result in attribute_results:
result_dict = dict(zip(attribute_names, attribute_result))
object_results.append(self._class_model(**result_dict))
return object_results
class SingleClient(Client):
def _process_attributes(self):
result = super(SingleClient, self)._process_attributes()
number_of_attributes = len(self._attributes)
if len(result) > number_of_attributes:
# If we found more attributes than we were looking for
result = result[:number_of_attributes]
return result
def _make_objects(self, attribute_result):
attribute_names = self._attributes.keys()
result_dict = dict(zip(attribute_names, attribute_result))
object_result = self._class_model(**result_dict)
return object_result
class Attribute(object):
def __init__(self, selector, modifier=None):
self.selector = selector
self.modifier = modifier
@property
def query(self):
if self.modifier:
# Escaping braces in here
base = "$.map({selector}, function(el){{ return {modifier}}});"
return base.format(selector=self.selector, modifier=self.modifier)
else:
return self.selector
| 34.387387 | 78 | 0.637674 | from collections import namedtuple
import inspect
import os
from ghost import Ghost
class Client(object):
def __init__(self, url=None):
if url:
self.url = url
assert self.url, "All clients must have a URL attribute"
self._attributes = self._collect_attributes()
self._class_model = self._setup_class_model()
self._ghost = Ghost()
def process(self):
self._load_ghost()
attribute_results = self._process_attributes()
self._object_results = self._make_objects(attribute_results)
return self._object_results
def _setup_class_model(self):
class_name = self.__class__.__name__
return namedtuple(class_name + "Response", self._attributes.keys())
def _process_attributes(self):
results = []
for attribute_name, attribute in self._attributes.iteritems():
result, resources = self._ghost.evaluate(attribute.query)
if isinstance(result, dict):
if 'data' in result:
result = result['data']
elif 'selector' in result:
raise TypeError("The attribute {} returned a selector"
" instead of a node.".format(attribute_name))
results.append(result)
return results
def _make_objects(self, attribute_results):
raise NotImplementedError()
def _collect_attributes(self):
attrs = [(attr_name, attr) for (attr_name, attr) in
inspect.getmembers(self) if isinstance(attr, Attribute)]
return dict(attrs)
def _load_ghost(self):
page, extra_resources = self._ghost.open(self.url)
# For local testing, page is None
if page:
# TODO should error better
assert page.http_status < 400
# Load jquery
jquery_path = os.path.join(os.path.abspath(os.curdir),
'zester', 'fixtures', 'jquery.min.js')
jquery_text = open(jquery_path, 'r').read()
result, resources = self._ghost.evaluate(jquery_text)
class MultipleClient(Client):
def _process_attributes(self):
results = super(MultipleClient, self)._process_attributes()
if not results:
return results
zipped_results = zip(*results)
return zipped_results
def _make_objects(self, attribute_results):
object_results = []
attribute_names = self._attributes.keys()
for attribute_result in attribute_results:
result_dict = dict(zip(attribute_names, attribute_result))
object_results.append(self._class_model(**result_dict))
return object_results
class SingleClient(Client):
def _process_attributes(self):
result = super(SingleClient, self)._process_attributes()
number_of_attributes = len(self._attributes)
if len(result) > number_of_attributes:
# If we found more attributes than we were looking for
result = result[:number_of_attributes]
return result
def _make_objects(self, attribute_result):
attribute_names = self._attributes.keys()
result_dict = dict(zip(attribute_names, attribute_result))
object_result = self._class_model(**result_dict)
return object_result
class Attribute(object):
def __init__(self, selector, modifier=None):
self.selector = selector
self.modifier = modifier
@property
def query(self):
if self.modifier:
# Escaping braces in here
base = "$.map({selector}, function(el){{ return {modifier}}});"
return base.format(selector=self.selector, modifier=self.modifier)
else:
return self.selector
| true | true |
f72c603dfc8ecbd5f63c67e5d3ff1d9b9f2bae6b | 662 | py | Python | rotateMatrix90/rotMat90.py | lowylow/InterviewQuestions | e267a601ff336b0a2a581db4ae985283a29fed51 | [
"MIT"
] | null | null | null | rotateMatrix90/rotMat90.py | lowylow/InterviewQuestions | e267a601ff336b0a2a581db4ae985283a29fed51 | [
"MIT"
] | null | null | null | rotateMatrix90/rotMat90.py | lowylow/InterviewQuestions | e267a601ff336b0a2a581db4ae985283a29fed51 | [
"MIT"
] | null | null | null | def rotate90acw(matrix):
outMatrix = []
for x in range(len(matrix)):
outArray = []
for y in range(len(matrix)):
outArray.append(matrix[len(matrix)-1-y][len(matrix)-1-x])
outMatrix.append(outArray[::-1])
return outMatrix
def rotate90cw(matrix):
outMatrix = []
for x in range(len(matrix)):
outArray = []
for y in range(len(matrix)):
outArray.append(matrix[y][x])
outMatrix.append(outArray[::-1])
return outMatrix
Matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(rotate90cw(Matrix)) | 23.642857 | 70 | 0.5 | def rotate90acw(matrix):
outMatrix = []
for x in range(len(matrix)):
outArray = []
for y in range(len(matrix)):
outArray.append(matrix[len(matrix)-1-y][len(matrix)-1-x])
outMatrix.append(outArray[::-1])
return outMatrix
def rotate90cw(matrix):
outMatrix = []
for x in range(len(matrix)):
outArray = []
for y in range(len(matrix)):
outArray.append(matrix[y][x])
outMatrix.append(outArray[::-1])
return outMatrix
Matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(rotate90cw(Matrix)) | true | true |
f72c60682595bfbd3fa6b5191c70b2cc02dd5f4c | 36,930 | py | Python | tests/hwsim/test_owe.py | cschuber/hostap | b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f | [
"Unlicense"
] | 21 | 2018-11-25T17:42:48.000Z | 2021-12-17T11:04:56.000Z | tests/hwsim/test_owe.py | cschuber/hostap | b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f | [
"Unlicense"
] | 3 | 2017-08-11T16:48:19.000Z | 2020-03-10T21:18:17.000Z | tests/hwsim/test_owe.py | cschuber/hostap | b26f5c0fe35cd0472ea43f533b981ac2d91cdf1f | [
"Unlicense"
] | 18 | 2015-03-11T07:09:31.000Z | 2022-03-25T08:29:18.000Z | # Test cases for Opportunistic Wireless Encryption (OWE)
# Copyright (c) 2017, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import binascii
import logging
logger = logging.getLogger()
import time
import os
import struct
import hostapd
from wpasupplicant import WpaSupplicant
import hwsim_utils
from tshark import run_tshark
from utils import HwsimSkip, fail_test, alloc_fail, wait_fail_trigger
from test_ap_acs import wait_acs
def test_owe(dev, apdev):
"""Opportunistic Wireless Encryption"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
conf = hapd.request("GET_CONFIG")
if "key_mgmt=OWE" not in conf.splitlines():
logger.info("GET_CONFIG:\n" + conf)
raise Exception("GET_CONFIG did not report correct key_mgmt")
dev[0].scan_for_bss(bssid, freq="2412")
bss = dev[0].get_bss(bssid)
if "[WPA2-OWE-CCMP]" not in bss['flags']:
raise Exception("OWE AKM not recognized: " + bss['flags'])
id = dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", scan_freq="2412")
hapd.wait_sta()
pmk_h = hapd.request("GET_PMK " + dev[0].own_addr())
pmk_w = dev[0].get_pmk(id)
if pmk_h != pmk_w:
raise Exception("Fetched PMK does not match: hostapd %s, wpa_supplicant %s" % (pmk_h, pmk_w))
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_groups(dev, apdev):
"""Opportunistic Wireless Encryption - DH groups"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
for group in [19, 20, 21]:
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group))
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
hapd.dump_monitor()
def test_owe_pmksa_caching(dev, apdev):
"""Opportunistic Wireless Encryption and PMKSA caching"""
try:
run_owe_pmksa_caching(dev, apdev)
finally:
dev[0].set("reassoc_same_bss_optim", "0")
def test_owe_pmksa_caching_connect_cmd(dev, apdev):
"""Opportunistic Wireless Encryption and PMKSA caching using cfg80211 connect command"""
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
try:
run_owe_pmksa_caching([wpas], apdev)
finally:
wpas.set("reassoc_same_bss_optim", "0")
def run_owe_pmksa_caching(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].set("reassoc_same_bss_optim", "1")
dev[0].scan_for_bss(bssid, freq="2412")
id = dev[0].connect("owe", key_mgmt="OWE")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa = dev[0].get_pmksa(bssid)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa2 = dev[0].get_pmksa(bssid)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
if "OK" not in hapd.request("PMKSA_FLUSH"):
raise Exception("PMKSA_FLUSH failed")
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa3 = dev[0].get_pmksa(bssid)
if pmksa is None or pmksa2 is None or pmksa3 is None:
raise Exception("PMKSA entry missing")
if pmksa['pmkid'] != pmksa2['pmkid']:
raise Exception("Unexpected PMKID change when using PMKSA caching")
if pmksa['pmkid'] == pmksa3['pmkid']:
raise Exception("PMKID did not change after PMKSA cache flush")
dev[0].request("REASSOCIATE")
dev[0].wait_connected()
pmksa4 = dev[0].get_pmksa(bssid)
if pmksa3['pmkid'] != pmksa4['pmkid']:
raise Exception("Unexpected PMKID change when using PMKSA caching [2]")
def test_owe_and_psk(dev, apdev):
"""Opportunistic Wireless Encryption and WPA2-PSK enabled"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe+psk",
"wpa": "2",
"wpa_key_mgmt": "OWE WPA-PSK",
"rsn_pairwise": "CCMP",
"wpa_passphrase": "12345678"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe+psk", psk="12345678")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
dev[1].scan_for_bss(bssid, freq="2412")
dev[1].connect("owe+psk", key_mgmt="OWE")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[1], hapd)
def test_owe_transition_mode(dev, apdev):
"""Opportunistic Wireless Encryption transition mode"""
run_owe_transition_mode(dev, apdev)
def test_owe_transition_mode_connect_cmd(dev, apdev):
"""Opportunistic Wireless Encryption transition mode using cfg80211 connect command"""
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_transition_mode([wpas], apdev)
def test_owe_transition_mode_mismatch1(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (mismatch 1)"""
run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55")
def test_owe_transition_mode_mismatch2(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (mismatch 2)"""
run_owe_transition_mode(dev, apdev, adv_bssid1="02:11:22:33:44:66")
def test_owe_transition_mode_mismatch3(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (mismatch 3)"""
run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55",
adv_bssid1="02:11:22:33:44:66")
def run_owe_transition_mode(dev, apdev, adv_bssid0=None, adv_bssid1=None):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
adv_bssid = adv_bssid0 if adv_bssid0 else apdev[1]['bssid']
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_bssid": adv_bssid,
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
adv_bssid = adv_bssid1 if adv_bssid1 else apdev[0]['bssid']
params = {"ssid": "owe-test",
"owe_transition_bssid": adv_bssid,
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
bss = dev[0].get_bss(bssid)
if "[WPA2-OWE-CCMP]" not in bss['flags']:
raise Exception("OWE AKM not recognized: " + bss['flags'])
if "[OWE-TRANS]" not in bss['flags']:
raise Exception("OWE transition not recognized: " + bss['flags'])
bss = dev[0].get_bss(bssid2)
if "[OWE-TRANS-OPEN]" not in bss['flags']:
raise Exception("OWE transition (open) not recognized: " + bss['flags'])
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
logger.info("Move to OWE only mode (disable transition mode)")
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
hapd2.disable()
hapd.disable()
dev[0].flush_scan_cache()
hapd.set("owe_transition_bssid", "00:00:00:00:00:00")
hapd.set("ignore_broadcast_ssid", '0')
hapd.set("ssid", 'owe-test')
hapd.enable()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
def test_owe_transition_mode_ifname(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (ifname)"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_ifname": apdev[1]['ifname'],
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_ifname": apdev[0]['ifname']}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_ifname_acs(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (ifname, ACS)"""
run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=False)
def test_owe_transition_mode_ifname_acs2(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (ifname, ACS)"""
run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=True)
def run_owe_transition_mode_ifname_acs(dev, apdev, wait_first):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"channel": "0",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_ifname": apdev[1]['ifname'],
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params, wait_enabled=False)
bssid = hapd.own_addr()
if wait_first:
wait_acs(hapd)
params = {"ssid": "owe-test",
"channel": "0",
"owe_transition_ifname": apdev[0]['ifname']}
hapd2 = hostapd.add_ap(apdev[1], params, wait_enabled=False)
bssid2 = hapd2.own_addr()
wait_acs(hapd2)
if not wait_first:
state = hapd.get_status_field("state")
if state == "ACS-STARTED":
time.sleep(5)
state = hapd.get_status_field("state")
if state != "ENABLED":
raise Exception("AP1 startup did not succeed")
freq = hapd.get_status_field("freq")
freq2 = hapd2.get_status_field("freq")
dev[0].scan_for_bss(bssid, freq=freq)
dev[0].scan_for_bss(bssid2, freq=freq2)
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="%s %s" % (freq, freq2))
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_open_only_ap(dev, apdev):
"""Opportunistic Wireless Encryption transition mode connect to open-only AP"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test-open"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
bss = dev[0].get_bss(bssid)
id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "NONE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_only_sta(dev, apdev):
"""Opportunistic Wireless Encryption transition mode disabled on STA"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test-open"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", owe_only="1", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
if not ev:
raise Exception("Unknown result for the connection attempt")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection to open network")
dev[0].request("DISCONNECT")
dev[0].dump_monitor()
params = {"ssid": "owe-test-open",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd2 = hostapd.add_ap(apdev[1], params)
dev[0].request("RECONNECT")
dev[0].wait_connected()
def test_owe_transition_mode_open_multiple_scans(dev, apdev):
"""Opportunistic Wireless Encryption transition mode and need for multiple scans"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid2, freq="2412")
dev[0].dump_monitor()
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=1)
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].wait_connected()
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_multi_bss(dev, apdev):
"""Opportunistic Wireless Encryption transition mode (multi BSS)"""
try:
run_owe_transition_mode_multi_bss(dev, apdev)
finally:
dev[0].request("SCAN_INTERVAL 5")
def run_owe_transition_mode_multi_bss(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
ifname1 = apdev[0]['ifname']
ifname2 = apdev[0]['ifname'] + '-2'
hapd1 = hostapd.add_bss(apdev[0], ifname1, 'owe-bss-1.conf')
hapd2 = hostapd.add_bss(apdev[0], ifname2, 'owe-bss-2.conf')
hapd2.bssidx = 1
bssid = hapd1.own_addr()
bssid2 = hapd2.own_addr()
# Beaconing with the OWE Transition Mode element can start only once both
# BSSs are enabled, so the very first Beacon frame may go out without this
# element. Wait a bit to avoid getting incomplete scan results.
time.sleep(0.1)
dev[0].request("SCAN_INTERVAL 1")
dev[0].scan_for_bss(bssid2, freq="2412")
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("transition-mode-open", key_mgmt="OWE")
val = dev[0].get_status_field("bssid")
if val != bssid2:
raise Exception("Unexpected bssid: " + val)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
hwsim_utils.test_connectivity(dev[0], hapd2)
def test_owe_transition_mode_rsne_mismatch(dev, apdev):
"""Opportunistic Wireless Encryption transition mode and RSNE mismatch"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"rsne_override_eapol": "30140100000fac040100000fac040100000fac020c00",
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=5)
if ev is None:
raise Exception("OWE PMKSA not created")
ev = dev[0].wait_event(["WPA: IE in 3/4 msg does not match with IE in Beacon/ProbeResp"],
timeout=5)
if ev is None:
raise Exception("RSNE mismatch not reported")
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-DISCONNECTED"], timeout=5)
dev[0].request("REMOVE_NETWORK all")
if ev is None:
raise Exception("No disconnection seen")
if "CTRL-EVENT-DISCONNECTED" not in ev:
raise Exception("Unexpected connection")
if "reason=17 locally_generated=1" not in ev:
raise Exception("Unexpected disconnection reason: " + ev)
def test_owe_unsupported_group(dev, apdev):
"""Opportunistic Wireless Encryption and unsupported group"""
try:
run_owe_unsupported_group(dev, apdev)
finally:
dev[0].request("VENDOR_ELEM_REMOVE 13 *")
def test_owe_unsupported_group_connect_cmd(dev, apdev):
"""Opportunistic Wireless Encryption and unsupported group using cfg80211 connect command"""
try:
wpas = None
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_unsupported_group([wpas], apdev)
finally:
if wpas:
wpas.request("VENDOR_ELEM_REMOVE 13 *")
def run_owe_unsupported_group(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
# Override OWE Dh Parameters element with a payload that uses invalid group
# 0 (and actual group 19 data) to make the AP reject this with the specific
# status code 77.
dev[0].request("VENDOR_ELEM_ADD 13 ff23200000783590fb7440e03d5b3b33911f86affdcc6b4411b707846ac4ff08ddc8831ccd")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
def test_owe_limited_group_set(dev, apdev):
"""Opportunistic Wireless Encryption and limited group set"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "20 21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
for group in [20, 21]:
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group))
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
def test_owe_limited_group_set_pmf(dev, apdev, params):
"""Opportunistic Wireless Encryption and limited group set (PMF)"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
pcapng = os.path.join(params['logdir'], "hwsim0.pcapng")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected (2)")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason (2): " + ev)
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="21", ieee80211w="2",
scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
out = run_tshark(pcapng,
"wlan.fc.type_subtype == 1",
display=['wlan_mgt.fixed.status_code'])
status = out.splitlines()
logger.info("Association Response frame status codes: " + str(status))
if len(status) != 3:
raise Exception("Unexpected number of Association Response frames")
if (int(status[0], base=0) != 77 or int(status[1], base=0) != 77 or
int(status[2], base=0) != 0):
raise Exception("Unexpected Association Response frame status code")
def test_owe_group_negotiation(dev, apdev):
"""Opportunistic Wireless Encryption and group negotiation"""
run_owe_group_negotiation(dev[0], apdev)
def test_owe_group_negotiation_connect_cmd(dev, apdev):
"""Opportunistic Wireless Encryption and group negotiation (connect command)"""
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_group_negotiation(wpas, apdev)
def run_owe_group_negotiation(dev, apdev):
if "OWE" not in dev.get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev.scan_for_bss(bssid, freq="2412")
dev.connect("owe", key_mgmt="OWE")
def test_owe_assoc_reject(dev, apdev):
"""Opportunistic Wireless Encryption association rejection handling"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"require_ht": "1",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "19"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
# First, reject two associations with HT-required (i.e., not OWE related)
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
disable_ht="1", scan_freq="2412", wait_connect=False)
for i in range(0, 2):
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
if ev is None:
raise Exception("Association rejection not reported")
# Then, verify that STA tries OWE with the default group (19) on the next
# attempt instead of having moved to testing another group.
hapd.set("require_ht", "0")
for i in range(0, 2):
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT",
"CTRL-EVENT-CONNECTED"], timeout=10)
if ev is None:
raise Exception("Association result not reported")
if "CTRL-EVENT-CONNECTED" in ev:
break
if "status_code=77" in ev:
raise Exception("Unexpected unsupport group rejection")
if "CTRL-EVENT-CONNECTED" not in ev:
raise Exception("Did not connect successfully")
def test_owe_local_errors(dev, apdev):
"""Opportunistic Wireless Encryption - local errors on supplicant"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
tests = [(1, "crypto_ecdh_init;owe_build_assoc_req"),
(1, "crypto_ecdh_get_pubkey;owe_build_assoc_req"),
(1, "wpabuf_alloc;owe_build_assoc_req")]
for count, func in tests:
with alloc_fail(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group="20",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
tests = [(1, "crypto_ecdh_set_peerkey;owe_process_assoc_resp"),
(1, "crypto_ecdh_get_pubkey;owe_process_assoc_resp"),
(1, "wpabuf_alloc;=owe_process_assoc_resp")]
for count, func in tests:
with alloc_fail(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group="20",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
tests = [(1, "hmac_sha256;owe_process_assoc_resp", 19),
(1, "hmac_sha256_kdf;owe_process_assoc_resp", 19),
(1, "hmac_sha384;owe_process_assoc_resp", 20),
(1, "hmac_sha384_kdf;owe_process_assoc_resp", 20),
(1, "hmac_sha512;owe_process_assoc_resp", 21),
(1, "hmac_sha512_kdf;owe_process_assoc_resp", 21)]
for count, func, group in tests:
with fail_test(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group),
ieee80211w="2",
scan_freq="2412", wait_connect=False)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="18",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=5)
if ev is None:
raise Exception("No authentication attempt")
time.sleep(0.5)
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
def hapd_auth(hapd):
for i in range(0, 10):
req = hapd.mgmt_rx()
if req is None:
raise Exception("MGMT RX wait timed out")
if req['subtype'] == 11:
break
req = None
if not req:
raise Exception("Authentication frame not received")
resp = {}
resp['fc'] = req['fc']
resp['da'] = req['sa']
resp['sa'] = req['da']
resp['bssid'] = req['bssid']
resp['payload'] = struct.pack('<HHH', 0, 2, 0)
hapd.mgmt_tx(resp)
def hapd_assoc(hapd, extra):
for i in range(0, 10):
req = hapd.mgmt_rx()
if req is None:
raise Exception("MGMT RX wait timed out")
if req['subtype'] == 0:
break
req = None
if not req:
raise Exception("Association Request frame not received")
resp = {}
resp['fc'] = 0x0010
resp['da'] = req['sa']
resp['sa'] = req['da']
resp['bssid'] = req['bssid']
payload = struct.pack('<HHH', 0x0411, 0, 0xc001)
payload += binascii.unhexlify("010882848b960c121824")
resp['payload'] = payload + extra
hapd.mgmt_tx(resp)
def test_owe_invalid_assoc_resp(dev, apdev):
"""Opportunistic Wireless Encryption - invalid Association Response frame"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
hapd.set("ext_mgmt_frame_handling", "1")
# OWE: No Diffie-Hellman Parameter element found in Association Response frame
tests = [b'']
# No room for group --> no DH Params
tests += [binascii.unhexlify('ff0120')]
# OWE: Unexpected Diffie-Hellman group in response: 18
tests += [binascii.unhexlify('ff03201200')]
# OWE: Invalid peer DH public key
tests += [binascii.unhexlify('ff23201300' + 31*'00' + '01')]
# OWE: Invalid peer DH public key
tests += [binascii.unhexlify('ff24201300' + 33*'ee')]
for extra in tests:
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
hapd_auth(hapd)
hapd_assoc(hapd, extra)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
# OWE: Empty public key (this ends up getting padded to a valid point)
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
hapd_auth(hapd)
hapd_assoc(hapd, binascii.unhexlify('ff03201300'))
ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED", "PMKSA-CACHE-ADDED"],
timeout=5)
if ev is None:
raise Exception("No result reported for empty public key")
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
def start_owe(dev, apdev, workaround=0):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"owe_ptk_workaround": str(workaround),
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
dev[0].scan_for_bss(hapd.own_addr(), freq="2412")
return hapd
def owe_check_ok(dev, hapd, owe_group, owe_ptk_workaround):
dev.connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group=owe_group, owe_ptk_workaround=owe_ptk_workaround,
scan_freq="2412")
hapd.wait_sta()
dev.request("REMOVE_NETWORK all")
dev.wait_disconnected()
dev.dump_monitor()
def test_owe_ptk_workaround_ap(dev, apdev):
"""Opportunistic Wireless Encryption - AP using PTK workaround"""
hapd = start_owe(dev, apdev, workaround=1)
for group, workaround in [(19, 0), (20, 0), (21, 0),
(19, 1), (20, 1), (21, 1)]:
owe_check_ok(dev[0], hapd, str(group), str(workaround))
def test_owe_ptk_hash(dev, apdev):
"""Opportunistic Wireless Encryption - PTK derivation hash alg"""
hapd = start_owe(dev, apdev)
for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1)]:
owe_check_ok(dev[0], hapd, str(group), str(workaround))
for group in [20, 21]:
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group=str(group), owe_ptk_workaround="1",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=10)
if ev is None:
raise Exception("Could not complete OWE association")
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-DISCONNECTED"], timeout=5)
if ev is None:
raise Exception("Unknown connection result")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection")
dev[0].request("REMOVE_NETWORK all")
ev = dev[0].wait_event(["PMKSA-CACHE-REMOVED"], timeout=5)
if ev is None:
raise Exception("No PMKSA cache removal event seen")
dev[0].dump_monitor()
def test_owe_transition_mode_disable(dev, apdev):
"""Opportunistic Wireless Encryption transition mode disable"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"transition_disable": '0x08',
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=1)
if ev is None:
raise Exception("Transition disable not indicated")
if ev.split(' ')[1] != "08":
raise Exception("Unexpected transition disable bitmap: " + ev)
val = dev[0].get_network(id, "owe_only")
if val != "1":
raise Exception("Unexpected owe_only value: " + val)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].request("RECONNECT")
dev[0].wait_connected()
def test_owe_sa_query(dev, apdev):
"""Opportunistic Wireless Encryption - SA Query"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412")
hapd.wait_sta()
hapd.set("ext_mgmt_frame_handling", "1")
dev[0].request("DISCONNECT")
dev[0].wait_disconnected(timeout=10)
hapd.set("ext_mgmt_frame_handling", "0")
dev[0].request("PMKSA_FLUSH")
dev[0].request("REASSOCIATE")
dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
| 38.710692 | 115 | 0.616951 |
import binascii
import logging
logger = logging.getLogger()
import time
import os
import struct
import hostapd
from wpasupplicant import WpaSupplicant
import hwsim_utils
from tshark import run_tshark
from utils import HwsimSkip, fail_test, alloc_fail, wait_fail_trigger
from test_ap_acs import wait_acs
def test_owe(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
conf = hapd.request("GET_CONFIG")
if "key_mgmt=OWE" not in conf.splitlines():
logger.info("GET_CONFIG:\n" + conf)
raise Exception("GET_CONFIG did not report correct key_mgmt")
dev[0].scan_for_bss(bssid, freq="2412")
bss = dev[0].get_bss(bssid)
if "[WPA2-OWE-CCMP]" not in bss['flags']:
raise Exception("OWE AKM not recognized: " + bss['flags'])
id = dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2", scan_freq="2412")
hapd.wait_sta()
pmk_h = hapd.request("GET_PMK " + dev[0].own_addr())
pmk_w = dev[0].get_pmk(id)
if pmk_h != pmk_w:
raise Exception("Fetched PMK does not match: hostapd %s, wpa_supplicant %s" % (pmk_h, pmk_w))
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_groups(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
for group in [19, 20, 21]:
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group))
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
hapd.dump_monitor()
def test_owe_pmksa_caching(dev, apdev):
try:
run_owe_pmksa_caching(dev, apdev)
finally:
dev[0].set("reassoc_same_bss_optim", "0")
def test_owe_pmksa_caching_connect_cmd(dev, apdev):
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
try:
run_owe_pmksa_caching([wpas], apdev)
finally:
wpas.set("reassoc_same_bss_optim", "0")
def run_owe_pmksa_caching(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].set("reassoc_same_bss_optim", "1")
dev[0].scan_for_bss(bssid, freq="2412")
id = dev[0].connect("owe", key_mgmt="OWE")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa = dev[0].get_pmksa(bssid)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa2 = dev[0].get_pmksa(bssid)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
if "OK" not in hapd.request("PMKSA_FLUSH"):
raise Exception("PMKSA_FLUSH failed")
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
pmksa3 = dev[0].get_pmksa(bssid)
if pmksa is None or pmksa2 is None or pmksa3 is None:
raise Exception("PMKSA entry missing")
if pmksa['pmkid'] != pmksa2['pmkid']:
raise Exception("Unexpected PMKID change when using PMKSA caching")
if pmksa['pmkid'] == pmksa3['pmkid']:
raise Exception("PMKID did not change after PMKSA cache flush")
dev[0].request("REASSOCIATE")
dev[0].wait_connected()
pmksa4 = dev[0].get_pmksa(bssid)
if pmksa3['pmkid'] != pmksa4['pmkid']:
raise Exception("Unexpected PMKID change when using PMKSA caching [2]")
def test_owe_and_psk(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe+psk",
"wpa": "2",
"wpa_key_mgmt": "OWE WPA-PSK",
"rsn_pairwise": "CCMP",
"wpa_passphrase": "12345678"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe+psk", psk="12345678")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
dev[1].scan_for_bss(bssid, freq="2412")
dev[1].connect("owe+psk", key_mgmt="OWE")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[1], hapd)
def test_owe_transition_mode(dev, apdev):
run_owe_transition_mode(dev, apdev)
def test_owe_transition_mode_connect_cmd(dev, apdev):
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_transition_mode([wpas], apdev)
def test_owe_transition_mode_mismatch1(dev, apdev):
run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55")
def test_owe_transition_mode_mismatch2(dev, apdev):
run_owe_transition_mode(dev, apdev, adv_bssid1="02:11:22:33:44:66")
def test_owe_transition_mode_mismatch3(dev, apdev):
run_owe_transition_mode(dev, apdev, adv_bssid0="02:11:22:33:44:55",
adv_bssid1="02:11:22:33:44:66")
def run_owe_transition_mode(dev, apdev, adv_bssid0=None, adv_bssid1=None):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
adv_bssid = adv_bssid0 if adv_bssid0 else apdev[1]['bssid']
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_bssid": adv_bssid,
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
adv_bssid = adv_bssid1 if adv_bssid1 else apdev[0]['bssid']
params = {"ssid": "owe-test",
"owe_transition_bssid": adv_bssid,
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
bss = dev[0].get_bss(bssid)
if "[WPA2-OWE-CCMP]" not in bss['flags']:
raise Exception("OWE AKM not recognized: " + bss['flags'])
if "[OWE-TRANS]" not in bss['flags']:
raise Exception("OWE transition not recognized: " + bss['flags'])
bss = dev[0].get_bss(bssid2)
if "[OWE-TRANS-OPEN]" not in bss['flags']:
raise Exception("OWE transition (open) not recognized: " + bss['flags'])
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
logger.info("Move to OWE only mode (disable transition mode)")
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].dump_monitor()
hapd2.disable()
hapd.disable()
dev[0].flush_scan_cache()
hapd.set("owe_transition_bssid", "00:00:00:00:00:00")
hapd.set("ignore_broadcast_ssid", '0')
hapd.set("ssid", 'owe-test')
hapd.enable()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].select_network(id, 2412)
dev[0].wait_connected()
hapd.wait_sta()
hwsim_utils.test_connectivity(dev[0], hapd)
def test_owe_transition_mode_ifname(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_ifname": apdev[1]['ifname'],
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_ifname": apdev[0]['ifname']}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_ifname_acs(dev, apdev):
run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=False)
def test_owe_transition_mode_ifname_acs2(dev, apdev):
run_owe_transition_mode_ifname_acs(dev, apdev, wait_first=True)
def run_owe_transition_mode_ifname_acs(dev, apdev, wait_first):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"channel": "0",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_ifname": apdev[1]['ifname'],
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params, wait_enabled=False)
bssid = hapd.own_addr()
if wait_first:
wait_acs(hapd)
params = {"ssid": "owe-test",
"channel": "0",
"owe_transition_ifname": apdev[0]['ifname']}
hapd2 = hostapd.add_ap(apdev[1], params, wait_enabled=False)
bssid2 = hapd2.own_addr()
wait_acs(hapd2)
if not wait_first:
state = hapd.get_status_field("state")
if state == "ACS-STARTED":
time.sleep(5)
state = hapd.get_status_field("state")
if state != "ENABLED":
raise Exception("AP1 startup did not succeed")
freq = hapd.get_status_field("freq")
freq2 = hapd2.get_status_field("freq")
dev[0].scan_for_bss(bssid, freq=freq)
dev[0].scan_for_bss(bssid2, freq=freq2)
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="%s %s" % (freq, freq2))
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_open_only_ap(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test-open"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
bss = dev[0].get_bss(bssid)
id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
hwsim_utils.test_connectivity(dev[0], hapd)
val = dev[0].get_status_field("key_mgmt")
if val != "NONE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_only_sta(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test-open"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
id = dev[0].connect("owe-test-open", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", owe_only="1", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
if not ev:
raise Exception("Unknown result for the connection attempt")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection to open network")
dev[0].request("DISCONNECT")
dev[0].dump_monitor()
params = {"ssid": "owe-test-open",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd2 = hostapd.add_ap(apdev[1], params)
dev[0].request("RECONNECT")
dev[0].wait_connected()
def test_owe_transition_mode_open_multiple_scans(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid2, freq="2412")
dev[0].dump_monitor()
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=1)
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].wait_connected()
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
def test_owe_transition_mode_multi_bss(dev, apdev):
try:
run_owe_transition_mode_multi_bss(dev, apdev)
finally:
dev[0].request("SCAN_INTERVAL 5")
def run_owe_transition_mode_multi_bss(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
ifname1 = apdev[0]['ifname']
ifname2 = apdev[0]['ifname'] + '-2'
hapd1 = hostapd.add_bss(apdev[0], ifname1, 'owe-bss-1.conf')
hapd2 = hostapd.add_bss(apdev[0], ifname2, 'owe-bss-2.conf')
hapd2.bssidx = 1
bssid = hapd1.own_addr()
bssid2 = hapd2.own_addr()
time.sleep(0.1)
dev[0].request("SCAN_INTERVAL 1")
dev[0].scan_for_bss(bssid2, freq="2412")
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("transition-mode-open", key_mgmt="OWE")
val = dev[0].get_status_field("bssid")
if val != bssid2:
raise Exception("Unexpected bssid: " + val)
val = dev[0].get_status_field("key_mgmt")
if val != "OWE":
raise Exception("Unexpected key_mgmt: " + val)
hwsim_utils.test_connectivity(dev[0], hapd2)
def test_owe_transition_mode_rsne_mismatch(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"rsne_override_eapol": "30140100000fac040100000fac040100000fac020c00",
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=5)
if ev is None:
raise Exception("OWE PMKSA not created")
ev = dev[0].wait_event(["WPA: IE in 3/4 msg does not match with IE in Beacon/ProbeResp"],
timeout=5)
if ev is None:
raise Exception("RSNE mismatch not reported")
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-DISCONNECTED"], timeout=5)
dev[0].request("REMOVE_NETWORK all")
if ev is None:
raise Exception("No disconnection seen")
if "CTRL-EVENT-DISCONNECTED" not in ev:
raise Exception("Unexpected connection")
if "reason=17 locally_generated=1" not in ev:
raise Exception("Unexpected disconnection reason: " + ev)
def test_owe_unsupported_group(dev, apdev):
try:
run_owe_unsupported_group(dev, apdev)
finally:
dev[0].request("VENDOR_ELEM_REMOVE 13 *")
def test_owe_unsupported_group_connect_cmd(dev, apdev):
try:
wpas = None
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_unsupported_group([wpas], apdev)
finally:
if wpas:
wpas.request("VENDOR_ELEM_REMOVE 13 *")
def run_owe_unsupported_group(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].request("VENDOR_ELEM_ADD 13 ff23200000783590fb7440e03d5b3b33911f86affdcc6b4411b707846ac4ff08ddc8831ccd")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
def test_owe_limited_group_set(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "20 21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
for group in [20, 21]:
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group))
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
def test_owe_limited_group_set_pmf(dev, apdev, params):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
pcapng = os.path.join(params['logdir'], "hwsim0.pcapng")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="20", ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected (2)")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason (2): " + ev)
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="21", ieee80211w="2",
scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].dump_monitor()
out = run_tshark(pcapng,
"wlan.fc.type_subtype == 1",
display=['wlan_mgt.fixed.status_code'])
status = out.splitlines()
logger.info("Association Response frame status codes: " + str(status))
if len(status) != 3:
raise Exception("Unexpected number of Association Response frames")
if (int(status[0], base=0) != 77 or int(status[1], base=0) != 77 or
int(status[2], base=0) != 0):
raise Exception("Unexpected Association Response frame status code")
def test_owe_group_negotiation(dev, apdev):
run_owe_group_negotiation(dev[0], apdev)
def test_owe_group_negotiation_connect_cmd(dev, apdev):
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
run_owe_group_negotiation(wpas, apdev)
def run_owe_group_negotiation(dev, apdev):
if "OWE" not in dev.get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "21"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev.scan_for_bss(bssid, freq="2412")
dev.connect("owe", key_mgmt="OWE")
def test_owe_assoc_reject(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"require_ht": "1",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"owe_groups": "19"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
disable_ht="1", scan_freq="2412", wait_connect=False)
for i in range(0, 2):
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
if ev is None:
raise Exception("Association rejection not reported")
hapd.set("require_ht", "0")
for i in range(0, 2):
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT",
"CTRL-EVENT-CONNECTED"], timeout=10)
if ev is None:
raise Exception("Association result not reported")
if "CTRL-EVENT-CONNECTED" in ev:
break
if "status_code=77" in ev:
raise Exception("Unexpected unsupport group rejection")
if "CTRL-EVENT-CONNECTED" not in ev:
raise Exception("Did not connect successfully")
def test_owe_local_errors(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
tests = [(1, "crypto_ecdh_init;owe_build_assoc_req"),
(1, "crypto_ecdh_get_pubkey;owe_build_assoc_req"),
(1, "wpabuf_alloc;owe_build_assoc_req")]
for count, func in tests:
with alloc_fail(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group="20",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
tests = [(1, "crypto_ecdh_set_peerkey;owe_process_assoc_resp"),
(1, "crypto_ecdh_get_pubkey;owe_process_assoc_resp"),
(1, "wpabuf_alloc;=owe_process_assoc_resp")]
for count, func in tests:
with alloc_fail(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group="20",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
tests = [(1, "hmac_sha256;owe_process_assoc_resp", 19),
(1, "hmac_sha256_kdf;owe_process_assoc_resp", 19),
(1, "hmac_sha384;owe_process_assoc_resp", 20),
(1, "hmac_sha384_kdf;owe_process_assoc_resp", 20),
(1, "hmac_sha512;owe_process_assoc_resp", 21),
(1, "hmac_sha512_kdf;owe_process_assoc_resp", 21)]
for count, func, group in tests:
with fail_test(dev[0], count, func):
dev[0].connect("owe", key_mgmt="OWE", owe_group=str(group),
ieee80211w="2",
scan_freq="2412", wait_connect=False)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="18",
ieee80211w="2",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=5)
if ev is None:
raise Exception("No authentication attempt")
time.sleep(0.5)
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
def hapd_auth(hapd):
for i in range(0, 10):
req = hapd.mgmt_rx()
if req is None:
raise Exception("MGMT RX wait timed out")
if req['subtype'] == 11:
break
req = None
if not req:
raise Exception("Authentication frame not received")
resp = {}
resp['fc'] = req['fc']
resp['da'] = req['sa']
resp['sa'] = req['da']
resp['bssid'] = req['bssid']
resp['payload'] = struct.pack('<HHH', 0, 2, 0)
hapd.mgmt_tx(resp)
def hapd_assoc(hapd, extra):
for i in range(0, 10):
req = hapd.mgmt_rx()
if req is None:
raise Exception("MGMT RX wait timed out")
if req['subtype'] == 0:
break
req = None
if not req:
raise Exception("Association Request frame not received")
resp = {}
resp['fc'] = 0x0010
resp['da'] = req['sa']
resp['sa'] = req['da']
resp['bssid'] = req['bssid']
payload = struct.pack('<HHH', 0x0411, 0, 0xc001)
payload += binascii.unhexlify("010882848b960c121824")
resp['payload'] = payload + extra
hapd.mgmt_tx(resp)
def test_owe_invalid_assoc_resp(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
hapd.set("ext_mgmt_frame_handling", "1")
tests = [b'']
tests += [binascii.unhexlify('ff0120')]
tests += [binascii.unhexlify('ff03201200')]
tests += [binascii.unhexlify('ff23201300' + 31*'00' + '01')]
tests += [binascii.unhexlify('ff24201300' + 33*'ee')]
for extra in tests:
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
hapd_auth(hapd)
hapd_assoc(hapd, extra)
dev[0].wait_disconnected()
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412", wait_connect=False)
hapd_auth(hapd)
hapd_assoc(hapd, binascii.unhexlify('ff03201300'))
ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED", "PMKSA-CACHE-ADDED"],
timeout=5)
if ev is None:
raise Exception("No result reported for empty public key")
dev[0].request("REMOVE_NETWORK all")
dev[0].dump_monitor()
def start_owe(dev, apdev, workaround=0):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"owe_ptk_workaround": str(workaround),
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
dev[0].scan_for_bss(hapd.own_addr(), freq="2412")
return hapd
def owe_check_ok(dev, hapd, owe_group, owe_ptk_workaround):
dev.connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group=owe_group, owe_ptk_workaround=owe_ptk_workaround,
scan_freq="2412")
hapd.wait_sta()
dev.request("REMOVE_NETWORK all")
dev.wait_disconnected()
dev.dump_monitor()
def test_owe_ptk_workaround_ap(dev, apdev):
hapd = start_owe(dev, apdev, workaround=1)
for group, workaround in [(19, 0), (20, 0), (21, 0),
(19, 1), (20, 1), (21, 1)]:
owe_check_ok(dev[0], hapd, str(group), str(workaround))
def test_owe_ptk_hash(dev, apdev):
hapd = start_owe(dev, apdev)
for group, workaround in [(19, 0), (20, 0), (21, 0), (19, 1)]:
owe_check_ok(dev[0], hapd, str(group), str(workaround))
for group in [20, 21]:
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group=str(group), owe_ptk_workaround="1",
scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["PMKSA-CACHE-ADDED"], timeout=10)
if ev is None:
raise Exception("Could not complete OWE association")
ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
"CTRL-EVENT-DISCONNECTED"], timeout=5)
if ev is None:
raise Exception("Unknown connection result")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection")
dev[0].request("REMOVE_NETWORK all")
ev = dev[0].wait_event(["PMKSA-CACHE-REMOVED"], timeout=5)
if ev is None:
raise Exception("No PMKSA cache removal event seen")
dev[0].dump_monitor()
def test_owe_transition_mode_disable(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
dev[0].flush_scan_cache()
params = {"ssid": "owe-random",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP",
"ieee80211w": "2",
"transition_disable": '0x08',
"owe_transition_bssid": apdev[1]['bssid'],
"owe_transition_ssid": '"owe-test"',
"ignore_broadcast_ssid": "1"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
params = {"ssid": "owe-test",
"owe_transition_bssid": apdev[0]['bssid'],
"owe_transition_ssid": '"owe-random"'}
hapd2 = hostapd.add_ap(apdev[1], params)
bssid2 = hapd2.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].scan_for_bss(bssid2, freq="2412")
id = dev[0].connect("owe-test", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=1)
if ev is None:
raise Exception("Transition disable not indicated")
if ev.split(' ')[1] != "08":
raise Exception("Unexpected transition disable bitmap: " + ev)
val = dev[0].get_network(id, "owe_only")
if val != "1":
raise Exception("Unexpected owe_only value: " + val)
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
dev[0].request("RECONNECT")
dev[0].wait_connected()
def test_owe_sa_query(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
params = {"ssid": "owe",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "OWE",
"rsn_pairwise": "CCMP"}
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
dev[0].scan_for_bss(bssid, freq="2412")
dev[0].connect("owe", key_mgmt="OWE", owe_group="19", ieee80211w="2",
scan_freq="2412")
hapd.wait_sta()
hapd.set("ext_mgmt_frame_handling", "1")
dev[0].request("DISCONNECT")
dev[0].wait_disconnected(timeout=10)
hapd.set("ext_mgmt_frame_handling", "0")
dev[0].request("PMKSA_FLUSH")
dev[0].request("REASSOCIATE")
dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
| true | true |
f72c6125a11e0ae38fd3d3c079c6d6047cfb6b22 | 2,373 | py | Python | backend/alembic/env.py | jflad17/pilot_logbook | f75c9866d073c33d001ae2d0eb0994496eb49045 | [
"MIT"
] | 1 | 2022-03-25T23:41:37.000Z | 2022-03-25T23:41:37.000Z | backend/alembic/env.py | jflad17/pilot_logbook | f75c9866d073c33d001ae2d0eb0994496eb49045 | [
"MIT"
] | null | null | null | backend/alembic/env.py | jflad17/pilot_logbook | f75c9866d073c33d001ae2d0eb0994496eb49045 | [
"MIT"
] | null | null | null | from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from models import *
from db.base import Base
from core.config import settings
from alembic import context
from models import *
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URI)
url = config.get_main_option("sqlalchemy.url")
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
version_table="AlembicVersion",
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
version_table="AlembicVersion",
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| 27.275862 | 74 | 0.714286 | from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from models import *
from db.base import Base
from core.config import settings
from alembic import context
from models import *
config = context.config
fileConfig(config.config_file_name)
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URI)
url = config.get_main_option("sqlalchemy.url")
def run_migrations_offline():
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
version_table="AlembicVersion",
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
version_table="AlembicVersion",
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| true | true |
f72c61450c801c44dc77e1b98289e540685b544a | 1,343 | py | Python | bootleg/embeddings/word_embeddings/base_word_emb.py | mleszczy/bootleg | 162d74001cdfbbe146753393641d549e0328acb1 | [
"Apache-2.0"
] | 1 | 2021-01-11T18:40:09.000Z | 2021-01-11T18:40:09.000Z | bootleg/embeddings/word_embeddings/base_word_emb.py | mleszczy/bootleg | 162d74001cdfbbe146753393641d549e0328acb1 | [
"Apache-2.0"
] | null | null | null | bootleg/embeddings/word_embeddings/base_word_emb.py | mleszczy/bootleg | 162d74001cdfbbe146753393641d549e0328acb1 | [
"Apache-2.0"
] | null | null | null | """Base word embedding"""
import torch
import torch.nn as nn
import os
from bootleg.utils import logging_utils
class BaseWordEmbedding(nn.Module):
"""
Base word embedding class. We split the word embedding from the sentence encoder, similar to BERT.
Attributes:
pad_id: id of the pad word index
"""
def __init__(self, args, main_args, word_symbols):
super(BaseWordEmbedding, self).__init__()
self.logger = logging_utils.get_logger(main_args)
self._key = "word"
self.pad_id = word_symbols.pad_id
def freeze_params(self):
for name, param in self.named_parameters():
param.requires_grad = False
self.logger.debug(f'Freezing {name}')
return
# This mask is for downstream pytorch multiheadattention
# This assumes that TRUE means MASK (aka IGNORE). For the sentence embedding, the mask therefore is if an index is equal to the pad id
# Note: This mask cannot be used for a BERT model as they use the reverse mask.
def get_downstream_mask(self, word_indices):
return word_indices == self.pad_id
def forward(self, word_indices):
raise ValueError("Not implemented.")
def get_dim(self):
raise ValueError("Not implemented.")
def get_key(self):
raise ValueError("Not implemented.") | 32.756098 | 138 | 0.684289 | import torch
import torch.nn as nn
import os
from bootleg.utils import logging_utils
class BaseWordEmbedding(nn.Module):
def __init__(self, args, main_args, word_symbols):
super(BaseWordEmbedding, self).__init__()
self.logger = logging_utils.get_logger(main_args)
self._key = "word"
self.pad_id = word_symbols.pad_id
def freeze_params(self):
for name, param in self.named_parameters():
param.requires_grad = False
self.logger.debug(f'Freezing {name}')
return
def get_downstream_mask(self, word_indices):
return word_indices == self.pad_id
def forward(self, word_indices):
raise ValueError("Not implemented.")
def get_dim(self):
raise ValueError("Not implemented.")
def get_key(self):
raise ValueError("Not implemented.") | true | true |
f72c63c7014f8654c874d4b6bc686d7d1259981c | 1,815 | py | Python | exampleapp/view1/views.py | thomasjiangcy/django-rest-mock | 09e91de20d1a5efd5c47c6e3d7fe979443012e2c | [
"MIT"
] | 9 | 2018-03-05T12:45:07.000Z | 2021-11-15T15:22:18.000Z | exampleapp/view1/views.py | thomasjiangcy/django-rest-mock | 09e91de20d1a5efd5c47c6e3d7fe979443012e2c | [
"MIT"
] | null | null | null | exampleapp/view1/views.py | thomasjiangcy/django-rest-mock | 09e91de20d1a5efd5c47c6e3d7fe979443012e2c | [
"MIT"
] | null | null | null | from rest_framework import generics, views
from rest_framework.response import Response
class SomeView(views.APIView):
"""
URL: /api/someview
"""
def get(self, request, *args, **kwargs):
"""
```
{
"success": "Hello, world!"
}
```
"""
pass
class ResourceListView(generics.ListCreateAPIView):
"""
URL: /api/resource/__key
"""
def post(self, request, *args, **kwargs):
"""
```
{
"__options": {
"excludeKey": true
}
}
```
"""
pass
class ResourceView(generics.RetrieveUpdateDestroyAPIView):
"""
URL: /api/resource/__key
"""
def get(self, request, *args, **kwargs):
"""
```
{
"__key": "<id:int>",
"__key_position": "url",
"__mockcount": 5,
"__options": {
"modifiers": ["patch", "put", "delete"],
"excludeKey": false
},
"id": "<int>",
"name": "<name>",
"complexStructure": [
{
"link": "<int::10>",
"url": "<uri>",
"related_user": {
"id": "<int:1:5>",
"hash": "<sha256>"
}
}
]
}
```
"""
return Response({'success': 'Successful request and response!'}, status=200)
def patch(self, request, *args, **kwargs):
"""Some docstring"""
pass
def put(self, request, *args, **kwargs):
"""some docstring"""
pass
def delete(self, request, *args, **kwargs):
"""Some docstring"""
pass
| 21.86747 | 84 | 0.406061 | from rest_framework import generics, views
from rest_framework.response import Response
class SomeView(views.APIView):
def get(self, request, *args, **kwargs):
pass
class ResourceListView(generics.ListCreateAPIView):
def post(self, request, *args, **kwargs):
pass
class ResourceView(generics.RetrieveUpdateDestroyAPIView):
def get(self, request, *args, **kwargs):
return Response({'success': 'Successful request and response!'}, status=200)
def patch(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| true | true |
f72c64df1da4e00b9d299b8a5608883b2530e2c8 | 7,812 | py | Python | scons/scons-local-4.1.0/SCons/Tool/mingw.py | vishalbelsare/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | [
"BSD-2-Clause"
] | null | null | null | scons/scons-local-4.1.0/SCons/Tool/mingw.py | vishalbelsare/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | [
"BSD-2-Clause"
] | null | null | null | scons/scons-local-4.1.0/SCons/Tool/mingw.py | vishalbelsare/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | [
"BSD-2-Clause"
] | null | null | null | # MIT License
#
# Copyright The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""SCons.Tool.gcc
Tool-specific initialization for MinGW (http://www.mingw.org/)
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
import os
import os.path
import glob
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Tool
import SCons.Util
mingw_paths = [
r'c:\MinGW\bin',
r'C:\cygwin64\bin',
r'C:\msys64',
r'C:\msys64\mingw64\bin',
r'C:\cygwin\bin',
r'C:\msys',
r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin'
]
def shlib_generator(target, source, env, for_signature):
cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS'])
dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
if dll: cmd.extend(['-o', dll])
cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])
implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
if implib: cmd.append('-Wl,--out-implib,' + implib.get_string(for_signature))
def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
insert_def = env.subst("$WINDOWS_INSERT_DEF")
if insert_def not in ['', '0', 0] and def_target: \
cmd.append('-Wl,--output-def,' + def_target.get_string(for_signature))
return [cmd]
def shlib_emitter(target, source, env):
dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
no_import_lib = env.get('no_import_lib', 0)
if not dll:
raise SCons.Errors.UserError(
"A shared library should have exactly one target with the suffix: %s Target(s) are:%s" % \
(env.subst("$SHLIBSUFFIX"), ",".join([str(t) for t in target])))
if not no_import_lib and \
not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'):
# Create list of target libraries as strings
targetStrings = env.ReplaceIxes(dll,
'SHLIBPREFIX', 'SHLIBSUFFIX',
'LIBPREFIX', 'LIBSUFFIX')
# Now add file nodes to target list
target.append(env.fs.File(targetStrings))
# Append a def file target if there isn't already a def file target
# or a def file source or the user has explicitly asked for the target
# to be emitted.
def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0]
if not def_source and not def_target and not skip_def_insert:
# Create list of target libraries and def files as strings
targetStrings = env.ReplaceIxes(dll,
'SHLIBPREFIX', 'SHLIBSUFFIX',
'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
# Now add file nodes to target list
target.append(env.fs.File(targetStrings))
return (target, source)
shlib_action = SCons.Action.Action(shlib_generator, '$SHLINKCOMSTR', generator=1)
ldmodule_action = SCons.Action.Action(shlib_generator, '$LDMODULECOMSTR', generator=1)
res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
res_builder = SCons.Builder.Builder(action=res_action, suffix='.o',
source_scanner=SCons.Tool.SourceFileScanner)
SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
# This is what we search for to find mingw:
# key_program = 'mingw32-gcc'
key_program = 'mingw32-make'
def find_version_specific_mingw_paths():
r"""
One example of default mingw install paths is:
C:\mingw-w64\x86_64-6.3.0-posix-seh-rt_v5-rev2\mingw64\bin
Use glob'ing to find such and add to mingw_paths
"""
new_paths = glob.glob(r"C:\mingw-w64\*\mingw64\bin")
return new_paths
def generate(env):
global mingw_paths
# Check for reasoanble mingw default paths
mingw_paths += find_version_specific_mingw_paths()
mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths)
if mingw:
mingw_bin_dir = os.path.dirname(mingw)
# Adjust path if we found it in a chocolatey install
if mingw_bin_dir == r'C:\ProgramData\chocolatey\bin':
mingw_bin_dir = r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin'
env.AppendENVPath('PATH', mingw_bin_dir)
# Most of mingw is the same as gcc and friends...
gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'gfortran', 'm4']
for tool in gnu_tools:
SCons.Tool.Tool(tool)(env)
# ... but a few things differ:
env['CC'] = 'gcc'
# make sure the msvc tool doesnt break us, it added a /flag
if 'CCFLAGS' in env:
# make sure its a CLVar to handle list or str cases
if type(env['CCFLAGS']) is not SCons.Util.CLVar:
env['CCFLAGS'] = SCons.Util.CLVar(env['CCFLAGS'])
env['CCFLAGS'] = SCons.Util.CLVar(str(env['CCFLAGS']).replace('/nologo', ''))
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['CXX'] = 'g++'
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
env['SHLINKCOM'] = shlib_action
env['SHLINKCOMSTR'] = shlib_generator
env['LDMODULECOM'] = ldmodule_action
env.Append(SHLIBEMITTER=[shlib_emitter])
env.Append(LDMODULEEMITTER=[shlib_emitter])
env['AS'] = 'as'
env['WIN32DEFPREFIX'] = ''
env['WIN32DEFSUFFIX'] = '.def'
env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}'
env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['RC'] = 'windres'
env['RCFLAGS'] = SCons.Util.CLVar('')
env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['RCINCPREFIX'] = '--include-dir '
env['RCINCSUFFIX'] = ''
env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
env['BUILDERS']['RES'] = res_builder
# Some setting from the platform also have to be overridden:
env['OBJSUFFIX'] = '.o'
env['LIBPREFIX'] = 'lib'
env['LIBSUFFIX'] = '.a'
env['PROGSUFFIX'] = '.exe'
# Handle new versioned shared library logic
env['_SHLIBSUFFIX'] = '$SHLIBSUFFIX'
env["SHLIBPREFIX"] = ""
def exists(env):
mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths)
if mingw:
mingw_bin_dir = os.path.dirname(mingw)
env.AppendENVPath('PATH', mingw_bin_dir)
return mingw
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| 36.166667 | 110 | 0.670123 |
import os
import os.path
import glob
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Tool
import SCons.Util
mingw_paths = [
r'c:\MinGW\bin',
r'C:\cygwin64\bin',
r'C:\msys64',
r'C:\msys64\mingw64\bin',
r'C:\cygwin\bin',
r'C:\msys',
r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin'
]
def shlib_generator(target, source, env, for_signature):
cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS'])
dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
if dll: cmd.extend(['-o', dll])
cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])
implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
if implib: cmd.append('-Wl,--out-implib,' + implib.get_string(for_signature))
def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
insert_def = env.subst("$WINDOWS_INSERT_DEF")
if insert_def not in ['', '0', 0] and def_target: \
cmd.append('-Wl,--output-def,' + def_target.get_string(for_signature))
return [cmd]
def shlib_emitter(target, source, env):
dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
no_import_lib = env.get('no_import_lib', 0)
if not dll:
raise SCons.Errors.UserError(
"A shared library should have exactly one target with the suffix: %s Target(s) are:%s" % \
(env.subst("$SHLIBSUFFIX"), ",".join([str(t) for t in target])))
if not no_import_lib and \
not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'):
targetStrings = env.ReplaceIxes(dll,
'SHLIBPREFIX', 'SHLIBSUFFIX',
'LIBPREFIX', 'LIBSUFFIX')
target.append(env.fs.File(targetStrings))
# or a def file source or the user has explicitly asked for the target
# to be emitted.
def_source = env.FindIxes(source, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
def_target = env.FindIxes(target, 'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
skip_def_insert = env.subst("$WINDOWS_INSERT_DEF") in ['', '0', 0]
if not def_source and not def_target and not skip_def_insert:
# Create list of target libraries and def files as strings
targetStrings = env.ReplaceIxes(dll,
'SHLIBPREFIX', 'SHLIBSUFFIX',
'WINDOWSDEFPREFIX', 'WINDOWSDEFSUFFIX')
# Now add file nodes to target list
target.append(env.fs.File(targetStrings))
return (target, source)
shlib_action = SCons.Action.Action(shlib_generator, '$SHLINKCOMSTR', generator=1)
ldmodule_action = SCons.Action.Action(shlib_generator, '$LDMODULECOMSTR', generator=1)
res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
res_builder = SCons.Builder.Builder(action=res_action, suffix='.o',
source_scanner=SCons.Tool.SourceFileScanner)
SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
# This is what we search for to find mingw:
# key_program = 'mingw32-gcc'
key_program = 'mingw32-make'
def find_version_specific_mingw_paths():
new_paths = glob.glob(r"C:\mingw-w64\*\mingw64\bin")
return new_paths
def generate(env):
global mingw_paths
# Check for reasoanble mingw default paths
mingw_paths += find_version_specific_mingw_paths()
mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths)
if mingw:
mingw_bin_dir = os.path.dirname(mingw)
# Adjust path if we found it in a chocolatey install
if mingw_bin_dir == r'C:\ProgramData\chocolatey\bin':
mingw_bin_dir = r'C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin'
env.AppendENVPath('PATH', mingw_bin_dir)
# Most of mingw is the same as gcc and friends...
gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'gfortran', 'm4']
for tool in gnu_tools:
SCons.Tool.Tool(tool)(env)
# ... but a few things differ:
env['CC'] = 'gcc'
# make sure the msvc tool doesnt break us, it added a /flag
if 'CCFLAGS' in env:
# make sure its a CLVar to handle list or str cases
if type(env['CCFLAGS']) is not SCons.Util.CLVar:
env['CCFLAGS'] = SCons.Util.CLVar(env['CCFLAGS'])
env['CCFLAGS'] = SCons.Util.CLVar(str(env['CCFLAGS']).replace('/nologo', ''))
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['CXX'] = 'g++'
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
env['SHLINKCOM'] = shlib_action
env['SHLINKCOMSTR'] = shlib_generator
env['LDMODULECOM'] = ldmodule_action
env.Append(SHLIBEMITTER=[shlib_emitter])
env.Append(LDMODULEEMITTER=[shlib_emitter])
env['AS'] = 'as'
env['WIN32DEFPREFIX'] = ''
env['WIN32DEFSUFFIX'] = '.def'
env['WINDOWSDEFPREFIX'] = '${WIN32DEFPREFIX}'
env['WINDOWSDEFSUFFIX'] = '${WIN32DEFSUFFIX}'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['RC'] = 'windres'
env['RCFLAGS'] = SCons.Util.CLVar('')
env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['RCINCPREFIX'] = '--include-dir '
env['RCINCSUFFIX'] = ''
env['RCCOM'] = '$RC $_CPPDEFFLAGS $RCINCFLAGS ${RCINCPREFIX} ${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
env['BUILDERS']['RES'] = res_builder
# Some setting from the platform also have to be overridden:
env['OBJSUFFIX'] = '.o'
env['LIBPREFIX'] = 'lib'
env['LIBSUFFIX'] = '.a'
env['PROGSUFFIX'] = '.exe'
# Handle new versioned shared library logic
env['_SHLIBSUFFIX'] = '$SHLIBSUFFIX'
env["SHLIBPREFIX"] = ""
def exists(env):
mingw = SCons.Tool.find_program_path(env, key_program, default_paths=mingw_paths)
if mingw:
mingw_bin_dir = os.path.dirname(mingw)
env.AppendENVPath('PATH', mingw_bin_dir)
return mingw
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| true | true |
f72c66e743146c7a5b70a5440e9ab5459f10245b | 6,426 | py | Python | Lib/site-packages/pyparsing/actions.py | edupyter/EDUPYTER38 | 396183cea72987506f1ef647c0272a2577c56218 | [
"bzip2-1.0.6"
] | 1 | 2020-10-05T05:38:26.000Z | 2020-10-05T05:38:26.000Z | Lib/site-packages/pyparsing/actions.py | edupyter/EDUPYTER38 | 396183cea72987506f1ef647c0272a2577c56218 | [
"bzip2-1.0.6"
] | null | null | null | Lib/site-packages/pyparsing/actions.py | edupyter/EDUPYTER38 | 396183cea72987506f1ef647c0272a2577c56218 | [
"bzip2-1.0.6"
] | null | null | null | # actions.py
from .exceptions import ParseException
from .util import col
class OnlyOnce:
"""
Wrapper for parse actions, to ensure they are only called once.
"""
def __init__(self, method_call):
from .core import _trim_arity
self.callable = _trim_arity(method_call)
self.called = False
def __call__(self, s, l, t):
if not self.called:
results = self.callable(s, l, t)
self.called = True
return results
raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
def reset(self):
"""
Allow the associated parse action to be called once more.
"""
self.called = False
def match_only_at_col(n):
"""
Helper method for defining parse actions that require matching at
a specific column in the input text.
"""
def verify_col(strg, locn, toks):
if col(locn, strg) != n:
raise ParseException(strg, locn, "matched token not at column {}".format(n))
return verify_col
def replace_with(repl_str):
"""
Helper method for common parse actions that simply return
a literal value. Especially useful when used with
:class:`transform_string<ParserElement.transform_string>` ().
Example::
num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
term = na | num
term[1, ...].parse_string("324 234 N/A 234") # -> [324, 234, nan, 234]
"""
return lambda s, l, t: [repl_str]
def remove_quotes(s, l, t):
"""
Helper parse action for removing quotation marks from parsed
quoted strings.
Example::
# by default, quotation marks are included in parsed results
quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
# use remove_quotes to strip quotation marks from parsed results
quoted_string.set_parse_action(remove_quotes)
quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
"""
return t[0][1:-1]
def with_attribute(*args, **attr_dict):
"""
Helper to create a validating parse action to be used with start
tags created with :class:`make_xml_tags` or
:class:`make_html_tags`. Use ``with_attribute`` to qualify
a starting tag with a required attribute value, to avoid false
matches on common tags such as ``<TD>`` or ``<DIV>``.
Call ``with_attribute`` with a series of attribute names and
values. Specify the list of filter attributes names and values as:
- keyword arguments, as in ``(align="right")``, or
- as an explicit dict with ``**`` operator, when an attribute
name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
- a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
For attribute names with a namespace prefix, you must use the second
form. Attribute names are matched insensitive to upper/lower case.
If just testing for ``class`` (with or without a namespace), use
:class:`with_class`.
To verify that the attribute exists, but without specifying a value,
pass ``with_attribute.ANY_VALUE`` as the value.
Example::
html = '''
<div>
Some text
<div type="grid">1 4 0 1 0</div>
<div type="graph">1,3 2,3 1,1</div>
<div>this has no type</div>
</div>
'''
div,div_end = make_html_tags("div")
# only match div tag having a type attribute with value "grid"
div_grid = div().set_parse_action(with_attribute(type="grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.search_string(html):
print(grid_header.body)
# construct a match with any div tag having a type attribute, regardless of the value
div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.search_string(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
if args:
attrs = args[:]
else:
attrs = attr_dict.items()
attrs = [(k, v) for k, v in attrs]
def pa(s, l, tokens):
for attrName, attrValue in attrs:
if attrName not in tokens:
raise ParseException(s, l, "no matching attribute " + attrName)
if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(
s,
l,
"attribute {!r} has value {!r}, must be {!r}".format(
attrName, tokens[attrName], attrValue
),
)
return pa
with_attribute.ANY_VALUE = object()
def with_class(classname, namespace=""):
"""
Simplified version of :class:`with_attribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = make_html_tags("div")
div_grid = div().set_parse_action(with_class("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.search_string(html):
print(grid_header.body)
div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.search_string(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
classattr = "{}:class".format(namespace) if namespace else "class"
return with_attribute(**{classattr: classname})
# pre-PEP8 compatibility symbols
replaceWith = replace_with
removeQuotes = remove_quotes
withAttribute = with_attribute
withClass = with_class
matchOnlyAtCol = match_only_at_col
| 30.894231 | 122 | 0.613601 |
from .exceptions import ParseException
from .util import col
class OnlyOnce:
def __init__(self, method_call):
from .core import _trim_arity
self.callable = _trim_arity(method_call)
self.called = False
def __call__(self, s, l, t):
if not self.called:
results = self.callable(s, l, t)
self.called = True
return results
raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
def reset(self):
self.called = False
def match_only_at_col(n):
def verify_col(strg, locn, toks):
if col(locn, strg) != n:
raise ParseException(strg, locn, "matched token not at column {}".format(n))
return verify_col
def replace_with(repl_str):
return lambda s, l, t: [repl_str]
def remove_quotes(s, l, t):
return t[0][1:-1]
def with_attribute(*args, **attr_dict):
if args:
attrs = args[:]
else:
attrs = attr_dict.items()
attrs = [(k, v) for k, v in attrs]
def pa(s, l, tokens):
for attrName, attrValue in attrs:
if attrName not in tokens:
raise ParseException(s, l, "no matching attribute " + attrName)
if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(
s,
l,
"attribute {!r} has value {!r}, must be {!r}".format(
attrName, tokens[attrName], attrValue
),
)
return pa
with_attribute.ANY_VALUE = object()
def with_class(classname, namespace=""):
classattr = "{}:class".format(namespace) if namespace else "class"
return with_attribute(**{classattr: classname})
replaceWith = replace_with
removeQuotes = remove_quotes
withAttribute = with_attribute
withClass = with_class
matchOnlyAtCol = match_only_at_col
| true | true |
f72c68b5184364eaf2b32e9631fcdb1b88247b70 | 702 | py | Python | setup.py | luk036/ellpy | 07fe4377a18ae9b38be9ad34eceb701f26873607 | [
"MIT"
] | 7 | 2019-01-01T00:30:03.000Z | 2021-07-11T12:54:46.000Z | setup.py | luk036/ellpy | 07fe4377a18ae9b38be9ad34eceb701f26873607 | [
"MIT"
] | 1 | 2018-06-03T09:01:26.000Z | 2018-06-03T09:01:26.000Z | setup.py | luk036/ellpy | 07fe4377a18ae9b38be9ad34eceb701f26873607 | [
"MIT"
] | 1 | 2018-06-03T08:59:05.000Z | 2018-06-03T08:59:05.000Z | """
Setup file for ellpy.
Use setup.cfg to configure your project.
This file was generated with PyScaffold 4.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: https://pyscaffold.org/
"""
from setuptools import setup
if __name__ == "__main__":
try:
setup(use_scm_version={"version_scheme": "no-guess-dev"})
except: # noqa
print(
"\n\nAn error occurred while building the project, "
"please ensure you have the most updated version of setuptools, "
"setuptools_scm and wheel with:\n"
" pip install -U setuptools setuptools_scm wheel\n\n"
)
raise
| 31.909091 | 77 | 0.638177 | from setuptools import setup
if __name__ == "__main__":
try:
setup(use_scm_version={"version_scheme": "no-guess-dev"})
except:
print(
"\n\nAn error occurred while building the project, "
"please ensure you have the most updated version of setuptools, "
"setuptools_scm and wheel with:\n"
" pip install -U setuptools setuptools_scm wheel\n\n"
)
raise
| true | true |
f72c692cf8cf1539d1b99caf1dd1a442c8da420c | 7,899 | py | Python | lib/modeling/keypoint_rcnn_heads.py | skokec/detectron-villard | 9e420bf3fb75a8f06f6e3fd970fc2600d8969d10 | [
"Apache-2.0"
] | 287 | 2018-12-23T08:31:09.000Z | 2022-02-27T14:52:21.000Z | lib/modeling/keypoint_rcnn_heads.py | absorbguo/Detectron | 2f8161edc3092b0382cab535c977a180a8b3cc4d | [
"Apache-2.0"
] | 54 | 2018-12-26T13:04:32.000Z | 2020-04-24T04:09:30.000Z | lib/modeling/keypoint_rcnn_heads.py | absorbguo/Detectron | 2f8161edc3092b0382cab535c977a180a8b3cc4d | [
"Apache-2.0"
] | 96 | 2018-12-24T05:12:36.000Z | 2021-04-23T15:51:21.000Z | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
"""Various network "heads" for predicting keypoints in Mask R-CNN.
The design is as follows:
... -> RoI ----\
-> RoIFeatureXform -> keypoint head -> keypoint output -> loss
... -> Feature /
Map
The keypoint head produces a feature representation of the RoI for the purpose
of keypoint prediction. The keypoint output module converts the feature
representation into keypoint heatmaps.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from core.config import cfg
from utils.c2 import const_fill
from utils.c2 import gauss_fill
import modeling.ResNet as ResNet
import utils.blob as blob_utils
# ---------------------------------------------------------------------------- #
# Keypoint R-CNN outputs and losses
# ---------------------------------------------------------------------------- #
def add_keypoint_outputs(model, blob_in, dim):
"""Add Mask R-CNN keypoint specific outputs: keypoint heatmaps."""
# NxKxHxW
upsample_heatmap = (cfg.KRCNN.UP_SCALE > 1)
if cfg.KRCNN.USE_DECONV:
# Apply ConvTranspose to the feature representation; results in 2x
# upsampling
blob_in = model.ConvTranspose(
blob_in,
'kps_deconv',
dim,
cfg.KRCNN.DECONV_DIM,
kernel=cfg.KRCNN.DECONV_KERNEL,
pad=int(cfg.KRCNN.DECONV_KERNEL / 2 - 1),
stride=2,
weight_init=gauss_fill(0.01),
bias_init=const_fill(0.0)
)
model.Relu('kps_deconv', 'kps_deconv')
dim = cfg.KRCNN.DECONV_DIM
if upsample_heatmap:
blob_name = 'kps_score_lowres'
else:
blob_name = 'kps_score'
if cfg.KRCNN.USE_DECONV_OUTPUT:
# Use ConvTranspose to predict heatmaps; results in 2x upsampling
blob_out = model.ConvTranspose(
blob_in,
blob_name,
dim,
cfg.KRCNN.NUM_KEYPOINTS,
kernel=cfg.KRCNN.DECONV_KERNEL,
pad=int(cfg.KRCNN.DECONV_KERNEL / 2 - 1),
stride=2,
weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.001}),
bias_init=const_fill(0.0)
)
else:
# Use Conv to predict heatmaps; does no upsampling
blob_out = model.Conv(
blob_in,
blob_name,
dim,
cfg.KRCNN.NUM_KEYPOINTS,
kernel=1,
pad=0,
stride=1,
weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.001}),
bias_init=const_fill(0.0)
)
if upsample_heatmap:
# Increase heatmap output size via bilinear upsampling
blob_out = model.BilinearInterpolation(
blob_out, 'kps_score', cfg.KRCNN.NUM_KEYPOINTS,
cfg.KRCNN.NUM_KEYPOINTS, cfg.KRCNN.UP_SCALE
)
return blob_out
def add_keypoint_losses(model):
"""Add Mask R-CNN keypoint specific losses."""
# Reshape input from (N, K, H, W) to (NK, HW)
model.net.Reshape(
['kps_score'], ['kps_score_reshaped', '_kps_score_old_shape'],
shape=(-1, cfg.KRCNN.HEATMAP_SIZE * cfg.KRCNN.HEATMAP_SIZE)
)
# Softmax across **space** (woahh....space!)
# Note: this is not what is commonly called "spatial softmax"
# (i.e., softmax applied along the channel dimension at each spatial
# location); This is softmax applied over a set of spatial locations (i.e.,
# each spatial location is a "class").
kps_prob, loss_kps = model.net.SoftmaxWithLoss(
['kps_score_reshaped', 'keypoint_locations_int32', 'keypoint_weights'],
['kps_prob', 'loss_kps'],
scale=cfg.KRCNN.LOSS_WEIGHT / cfg.NUM_GPUS,
spatial=0
)
if not cfg.KRCNN.NORMALIZE_BY_VISIBLE_KEYPOINTS:
# Discussion: the softmax loss above will average the loss by the sum of
# keypoint_weights, i.e. the total number of visible keypoints. Since
# the number of visible keypoints can vary significantly between
# minibatches, this has the effect of up-weighting the importance of
# minibatches with few visible keypoints. (Imagine the extreme case of
# only one visible keypoint versus N: in the case of N, each one
# contributes 1/N to the gradient compared to the single keypoint
# determining the gradient direction). Instead, we can normalize the
# loss by the total number of keypoints, if it were the case that all
# keypoints were visible in a full minibatch. (Returning to the example,
# this means that the one visible keypoint contributes as much as each
# of the N keypoints.)
model.StopGradient(
'keypoint_loss_normalizer', 'keypoint_loss_normalizer'
)
loss_kps = model.net.Mul(
['loss_kps', 'keypoint_loss_normalizer'], 'loss_kps_normalized'
)
loss_gradients = blob_utils.get_loss_gradients(model, [loss_kps])
model.AddLosses(loss_kps)
return loss_gradients
# ---------------------------------------------------------------------------- #
# Keypoint heads
# ---------------------------------------------------------------------------- #
def add_ResNet_roi_conv5_head_for_keypoints(
model, blob_in, dim_in, spatial_scale
):
"""Add a ResNet "conv5" / "stage5" head for Mask R-CNN keypoint prediction.
"""
model.RoIFeatureTransform(
blob_in,
'_[pose]_pool5',
blob_rois='keypoint_rois',
method=cfg.KRCNN.ROI_XFORM_METHOD,
resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION,
sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO,
spatial_scale=spatial_scale
)
# Using the prefix '_[pose]_' to 'res5' enables initializing the head's
# parameters using pretrained 'res5' parameters if given (see
# utils.net.initialize_gpu_0_from_weights_file)
s, dim_in = ResNet.add_stage(
model,
'_[pose]_res5',
'_[pose]_pool5',
3,
dim_in,
2048,
512,
cfg.KRCNN.DILATION,
stride_init=int(cfg.KRCNN.ROI_XFORM_RESOLUTION / 7)
)
return s, 2048
def add_roi_pose_head_v1convX(model, blob_in, dim_in, spatial_scale):
"""Add a Mask R-CNN keypoint head. v1convX design: X * (conv)."""
hidden_dim = cfg.KRCNN.CONV_HEAD_DIM
kernel_size = cfg.KRCNN.CONV_HEAD_KERNEL
pad_size = kernel_size // 2
current = model.RoIFeatureTransform(
blob_in,
'_[pose]_roi_feat',
blob_rois='keypoint_rois',
method=cfg.KRCNN.ROI_XFORM_METHOD,
resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION,
sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO,
spatial_scale=spatial_scale
)
for i in range(cfg.KRCNN.NUM_STACKED_CONVS):
current = model.Conv(
current,
'conv_fcn' + str(i + 1),
dim_in,
hidden_dim,
kernel_size,
stride=1,
pad=pad_size,
weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.01}),
bias_init=('ConstantFill', {'value': 0.})
)
current = model.Relu(current, current)
dim_in = hidden_dim
return current, hidden_dim
| 36.233945 | 80 | 0.617547 |
model, blob_in, dim_in, spatial_scale
):
model.RoIFeatureTransform(
blob_in,
'_[pose]_pool5',
blob_rois='keypoint_rois',
method=cfg.KRCNN.ROI_XFORM_METHOD,
resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION,
sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO,
spatial_scale=spatial_scale
)
# parameters using pretrained 'res5' parameters if given (see
# utils.net.initialize_gpu_0_from_weights_file)
s, dim_in = ResNet.add_stage(
model,
'_[pose]_res5',
'_[pose]_pool5',
3,
dim_in,
2048,
512,
cfg.KRCNN.DILATION,
stride_init=int(cfg.KRCNN.ROI_XFORM_RESOLUTION / 7)
)
return s, 2048
def add_roi_pose_head_v1convX(model, blob_in, dim_in, spatial_scale):
hidden_dim = cfg.KRCNN.CONV_HEAD_DIM
kernel_size = cfg.KRCNN.CONV_HEAD_KERNEL
pad_size = kernel_size // 2
current = model.RoIFeatureTransform(
blob_in,
'_[pose]_roi_feat',
blob_rois='keypoint_rois',
method=cfg.KRCNN.ROI_XFORM_METHOD,
resolution=cfg.KRCNN.ROI_XFORM_RESOLUTION,
sampling_ratio=cfg.KRCNN.ROI_XFORM_SAMPLING_RATIO,
spatial_scale=spatial_scale
)
for i in range(cfg.KRCNN.NUM_STACKED_CONVS):
current = model.Conv(
current,
'conv_fcn' + str(i + 1),
dim_in,
hidden_dim,
kernel_size,
stride=1,
pad=pad_size,
weight_init=(cfg.KRCNN.CONV_INIT, {'std': 0.01}),
bias_init=('ConstantFill', {'value': 0.})
)
current = model.Relu(current, current)
dim_in = hidden_dim
return current, hidden_dim
| true | true |
f72c69bd895eea56254b314d4418757ffc5e1cbe | 1,266 | py | Python | Scripts/Legacy/line1prep.py | rhong3/CPTAC-UCEC | ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9 | [
"MIT"
] | 4 | 2019-01-04T21:11:03.000Z | 2020-12-11T16:56:15.000Z | Scripts/Legacy/line1prep.py | rhong3/CPTAC-UCEC | ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9 | [
"MIT"
] | null | null | null | Scripts/Legacy/line1prep.py | rhong3/CPTAC-UCEC | ec83fbee234b5ad3df6524cdd960b5f0f3da9ea9 | [
"MIT"
] | null | null | null | import pandas as pd
labels = pd.read_csv('../Fusion_dummy_His_MUT_joined.csv', header=0)
# line = pd.read_csv('../../Line1.csv', header=0)
line = pd.read_csv('../EC_cyclin_expression.csv', header=0)
# line['name'] = line['Proteomics_Participant_ID']
# line = line.drop(['Proteomics_Participant_ID', 'Histologic_type', 'Genomics_subtype', 'TP53_TP53'], axis=1)
# labels = labels.join(line.set_index('name'), on='name')
# labels['LINE1_ORF1p'] = (labels['LINE1_ORF1p'].dropna() > 0).astype(int)
# labels['RAD50-S635'] = (labels['RAD50-S635'].dropna() > 0).astype(int)
# labels['NBN-S343'] = (labels['NBN-S343'].dropna() > 0).astype(int)
# labels['ATR-T1989'] = (labels['ATR-T1989'].dropna() > 0).astype(int)
# labels['ATM-S1981'] = (labels['ATM-S1981'].dropna() > 0).astype(int)
line['name'] = line['Sample_ID'].str.slice(start=0, stop=9)
line = line.drop(['Sample_ID', 'Genomic_subtype'], axis=1)
labels = labels.join(line.set_index('name'), on='name')
labels['CCND1'] = (labels['CCND1'].dropna() > 0).astype(int)
labels['CCNE1'] = (labels['CCNE1'].dropna() > 0).astype(int)
labels['CCNA2'] = (labels['CCNA2'].dropna() > 0).astype(int)
labels['CCNB1'] = (labels['CCNB1'].dropna() > 0).astype(int)
labels.to_csv('../Fusion_dummy_His_MUT_joined.csv', index=False)
| 48.692308 | 109 | 0.671406 | import pandas as pd
labels = pd.read_csv('../Fusion_dummy_His_MUT_joined.csv', header=0)
line = pd.read_csv('../EC_cyclin_expression.csv', header=0)
line['name'] = line['Sample_ID'].str.slice(start=0, stop=9)
line = line.drop(['Sample_ID', 'Genomic_subtype'], axis=1)
labels = labels.join(line.set_index('name'), on='name')
labels['CCND1'] = (labels['CCND1'].dropna() > 0).astype(int)
labels['CCNE1'] = (labels['CCNE1'].dropna() > 0).astype(int)
labels['CCNA2'] = (labels['CCNA2'].dropna() > 0).astype(int)
labels['CCNB1'] = (labels['CCNB1'].dropna() > 0).astype(int)
labels.to_csv('../Fusion_dummy_His_MUT_joined.csv', index=False)
| true | true |
f72c6a4e0c25397651cfa6ffd566d94b400550f8 | 87,446 | py | Python | Lib/zipfile.py | fochoao/CPython | c92e0770af558fe3e440e44d3605c3acaf3c5b68 | [
"TCL",
"0BSD"
] | null | null | null | Lib/zipfile.py | fochoao/CPython | c92e0770af558fe3e440e44d3605c3acaf3c5b68 | [
"TCL",
"0BSD"
] | null | null | null | Lib/zipfile.py | fochoao/CPython | c92e0770af558fe3e440e44d3605c3acaf3c5b68 | [
"TCL",
"0BSD"
] | null | null | null | """
Read and write ZIP files.
XXX references to utf-8 need further investigation.
"""
import binascii
import importlib.util
import io
import itertools
import os
import posixpath
import shutil
import stat
import struct
import sys
import threading
import time
import contextlib
try:
import zlib # We may need its compression method
crc32 = zlib.crc32
except ImportError:
zlib = None
crc32 = binascii.crc32
try:
import bz2 # We may need its compression method
except ImportError:
bz2 = None
try:
import lzma # We may need its compression method
except ImportError:
lzma = None
__all__ = ["BadZipFile", "BadZipfile", "error",
"ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA",
"is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile",
"Path"]
class BadZipFile(Exception):
pass
class LargeZipFile(Exception):
"""
Raised when writing a zipfile, the zipfile requires ZIP64 extensions
and those extensions are disabled.
"""
error = BadZipfile = BadZipFile # Pre-3.2 compatibility names
ZIP64_LIMIT = (1 << 31) - 1
ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
ZIP_MAX_COMMENT = (1 << 16) - 1
# constants for Zip file compression methods
ZIP_STORED = 0
ZIP_DEFLATED = 8
ZIP_BZIP2 = 12
ZIP_LZMA = 14
# Other ZIP compression methods not supported
DEFAULT_VERSION = 20
ZIP64_VERSION = 45
BZIP2_VERSION = 46
LZMA_VERSION = 63
# we recognize (but not necessarily support) all features up to that version
MAX_EXTRACT_VERSION = 63
# Below are some formats and associated data for reading/writing headers using
# the struct module. The names and structures of headers/records are those used
# in the PKWARE description of the ZIP file format:
# http://www.pkware.com/documents/casestudies/APPNOTE.TXT
# (URL valid as of January 2008)
# The "end of central directory" structure, magic number, size, and indices
# (section V.I in the format document)
structEndArchive = b"<4s4H2LH"
stringEndArchive = b"PK\005\006"
sizeEndCentDir = struct.calcsize(structEndArchive)
_ECD_SIGNATURE = 0
_ECD_DISK_NUMBER = 1
_ECD_DISK_START = 2
_ECD_ENTRIES_THIS_DISK = 3
_ECD_ENTRIES_TOTAL = 4
_ECD_SIZE = 5
_ECD_OFFSET = 6
_ECD_COMMENT_SIZE = 7
# These last two indices are not part of the structure as defined in the
# spec, but they are used internally by this module as a convenience
_ECD_COMMENT = 8
_ECD_LOCATION = 9
# The "central directory" structure, magic number, size, and indices
# of entries in the structure (section V.F in the format document)
structCentralDir = "<4s4B4HL2L5H2L"
stringCentralDir = b"PK\001\002"
sizeCentralDir = struct.calcsize(structCentralDir)
# indexes of entries in the central directory structure
_CD_SIGNATURE = 0
_CD_CREATE_VERSION = 1
_CD_CREATE_SYSTEM = 2
_CD_EXTRACT_VERSION = 3
_CD_EXTRACT_SYSTEM = 4
_CD_FLAG_BITS = 5
_CD_COMPRESS_TYPE = 6
_CD_TIME = 7
_CD_DATE = 8
_CD_CRC = 9
_CD_COMPRESSED_SIZE = 10
_CD_UNCOMPRESSED_SIZE = 11
_CD_FILENAME_LENGTH = 12
_CD_EXTRA_FIELD_LENGTH = 13
_CD_COMMENT_LENGTH = 14
_CD_DISK_NUMBER_START = 15
_CD_INTERNAL_FILE_ATTRIBUTES = 16
_CD_EXTERNAL_FILE_ATTRIBUTES = 17
_CD_LOCAL_HEADER_OFFSET = 18
# The "local file header" structure, magic number, size, and indices
# (section V.A in the format document)
structFileHeader = "<4s2B4HL2L2H"
stringFileHeader = b"PK\003\004"
sizeFileHeader = struct.calcsize(structFileHeader)
_FH_SIGNATURE = 0
_FH_EXTRACT_VERSION = 1
_FH_EXTRACT_SYSTEM = 2
_FH_GENERAL_PURPOSE_FLAG_BITS = 3
_FH_COMPRESSION_METHOD = 4
_FH_LAST_MOD_TIME = 5
_FH_LAST_MOD_DATE = 6
_FH_CRC = 7
_FH_COMPRESSED_SIZE = 8
_FH_UNCOMPRESSED_SIZE = 9
_FH_FILENAME_LENGTH = 10
_FH_EXTRA_FIELD_LENGTH = 11
# The "Zip64 end of central directory locator" structure, magic number, and size
structEndArchive64Locator = "<4sLQL"
stringEndArchive64Locator = b"PK\x06\x07"
sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
# The "Zip64 end of central directory" record, magic number, size, and indices
# (section V.G in the format document)
structEndArchive64 = "<4sQ2H2L4Q"
stringEndArchive64 = b"PK\x06\x06"
sizeEndCentDir64 = struct.calcsize(structEndArchive64)
_CD64_SIGNATURE = 0
_CD64_DIRECTORY_RECSIZE = 1
_CD64_CREATE_VERSION = 2
_CD64_EXTRACT_VERSION = 3
_CD64_DISK_NUMBER = 4
_CD64_DISK_NUMBER_START = 5
_CD64_NUMBER_ENTRIES_THIS_DISK = 6
_CD64_NUMBER_ENTRIES_TOTAL = 7
_CD64_DIRECTORY_SIZE = 8
_CD64_OFFSET_START_CENTDIR = 9
_DD_SIGNATURE = 0x08074b50
_EXTRA_FIELD_STRUCT = struct.Struct('<HH')
def _strip_extra(extra, xids):
# Remove Extra Fields with specified IDs.
unpack = _EXTRA_FIELD_STRUCT.unpack
modified = False
buffer = []
start = i = 0
while i + 4 <= len(extra):
xid, xlen = unpack(extra[i : i + 4])
j = i + 4 + xlen
if xid in xids:
if i != start:
buffer.append(extra[start : i])
start = j
modified = True
i = j
if not modified:
return extra
return b''.join(buffer)
def _check_zipfile(fp):
try:
if _EndRecData(fp):
return True # file has correct magic number
except OSError:
pass
return False
def is_zipfile(filename):
"""Quickly see if a file is a ZIP file by checking the magic number.
The filename argument may be a file or file-like object too.
"""
result = False
try:
if hasattr(filename, "read"):
result = _check_zipfile(fp=filename)
else:
with open(filename, "rb") as fp:
result = _check_zipfile(fp)
except OSError:
pass
return result
def _EndRecData64(fpin, offset, endrec):
"""
Read the ZIP64 end-of-archive records and use that to update endrec
"""
try:
fpin.seek(offset - sizeEndCentDir64Locator, 2)
except OSError:
# If the seek fails, the file is not large enough to contain a ZIP64
# end-of-archive record, so just return the end record we were given.
return endrec
data = fpin.read(sizeEndCentDir64Locator)
if len(data) != sizeEndCentDir64Locator:
return endrec
sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
if sig != stringEndArchive64Locator:
return endrec
if diskno != 0 or disks > 1:
raise BadZipFile("zipfiles that span multiple disks are not supported")
# Assume no 'zip64 extensible data'
fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
data = fpin.read(sizeEndCentDir64)
if len(data) != sizeEndCentDir64:
return endrec
sig, sz, create_version, read_version, disk_num, disk_dir, \
dircount, dircount2, dirsize, diroffset = \
struct.unpack(structEndArchive64, data)
if sig != stringEndArchive64:
return endrec
# Update the original endrec using data from the ZIP64 record
endrec[_ECD_SIGNATURE] = sig
endrec[_ECD_DISK_NUMBER] = disk_num
endrec[_ECD_DISK_START] = disk_dir
endrec[_ECD_ENTRIES_THIS_DISK] = dircount
endrec[_ECD_ENTRIES_TOTAL] = dircount2
endrec[_ECD_SIZE] = dirsize
endrec[_ECD_OFFSET] = diroffset
return endrec
def _EndRecData(fpin):
"""Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record."""
# Determine file size
fpin.seek(0, 2)
filesize = fpin.tell()
# Check to see if this is ZIP file with no archive comment (the
# "end of central directory" structure should be the last item in the
# file if this is the case).
try:
fpin.seek(-sizeEndCentDir, 2)
except OSError:
return None
data = fpin.read()
if (len(data) == sizeEndCentDir and
data[0:4] == stringEndArchive and
data[-2:] == b"\000\000"):
# the signature is correct and there's no comment, unpack structure
endrec = struct.unpack(structEndArchive, data)
endrec=list(endrec)
# Append a blank comment and record start offset
endrec.append(b"")
endrec.append(filesize - sizeEndCentDir)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
# Either this is not a ZIP file, or it is a ZIP file with an archive
# comment. Search the end of the file for the "end of central directory"
# record signature. The comment is the last item in the ZIP file and may be
# up to 64K long. It is assumed that the "end of central directory" magic
# number does not appear in the comment.
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
fpin.seek(maxCommentStart, 0)
data = fpin.read()
start = data.rfind(stringEndArchive)
if start >= 0:
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
if len(recData) != sizeEndCentDir:
# Zip file is corrupted.
return None
endrec = list(struct.unpack(structEndArchive, recData))
commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
endrec.append(comment)
endrec.append(maxCommentStart + start)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, maxCommentStart + start - filesize,
endrec)
# Unable to find a valid end of central directory structure
return None
class ZipInfo (object):
"""Class with attributes describing each file in the ZIP archive."""
__slots__ = (
'orig_filename',
'filename',
'date_time',
'compress_type',
'_compresslevel',
'comment',
'extra',
'create_system',
'create_version',
'extract_version',
'reserved',
'flag_bits',
'volume',
'internal_attr',
'external_attr',
'header_offset',
'CRC',
'compress_size',
'file_size',
'_raw_time',
)
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
self.orig_filename = filename # Original file name in archive
# Terminate the file name at the first null byte. Null bytes in file
# names are used as tricks by viruses in archives.
null_byte = filename.find(chr(0))
if null_byte >= 0:
filename = filename[0:null_byte]
# This is used to ensure paths in generated ZIP files always use
# forward slashes as the directory separator, as required by the
# ZIP format specification.
if os.sep != "/" and os.sep in filename:
filename = filename.replace(os.sep, "/")
self.filename = filename # Normalized file name
self.date_time = date_time # year, month, day, hour, min, sec
if date_time[0] < 1980:
raise ValueError('ZIP does not support timestamps before 1980')
# Standard values:
self.compress_type = ZIP_STORED # Type of compression for the file
self._compresslevel = None # Level for the compressor
self.comment = b"" # Comment for each file
self.extra = b"" # ZIP extra data
if sys.platform == 'win32':
self.create_system = 0 # System which created ZIP archive
else:
# Assume everything else is unix-y
self.create_system = 3 # System which created ZIP archive
self.create_version = DEFAULT_VERSION # Version which created ZIP archive
self.extract_version = DEFAULT_VERSION # Version needed to extract archive
self.reserved = 0 # Must be zero
self.flag_bits = 0 # ZIP flag bits
self.volume = 0 # Volume number of file header
self.internal_attr = 0 # Internal attributes
self.external_attr = 0 # External file attributes
self.compress_size = 0 # Size of the compressed file
self.file_size = 0 # Size of the uncompressed file
# Other attributes are set by class ZipFile:
# header_offset Byte offset to the file header
# CRC CRC-32 of the uncompressed file
def __repr__(self):
result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)]
if self.compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self.compress_type,
self.compress_type))
hi = self.external_attr >> 16
lo = self.external_attr & 0xFFFF
if hi:
result.append(' filemode=%r' % stat.filemode(hi))
if lo:
result.append(' external_attr=%#x' % lo)
isdir = self.is_dir()
if not isdir or self.file_size:
result.append(' file_size=%r' % self.file_size)
if ((not isdir or self.compress_size) and
(self.compress_type != ZIP_STORED or
self.file_size != self.compress_size)):
result.append(' compress_size=%r' % self.compress_size)
result.append('>')
return ''.join(result)
def FileHeader(self, zip64=None):
"""Return the per-file header as a bytes object."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the file data
CRC = compress_size = file_size = 0
else:
CRC = self.CRC
compress_size = self.compress_size
file_size = self.file_size
extra = self.extra
min_version = 0
if zip64 is None:
zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
if zip64:
fmt = '<HHQQ'
extra = extra + struct.pack(fmt,
1, struct.calcsize(fmt)-4, file_size, compress_size)
if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
if not zip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
# File is larger than what fits into a 4 byte integer,
# fall back to the ZIP64 extension
file_size = 0xffffffff
compress_size = 0xffffffff
min_version = ZIP64_VERSION
if self.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif self.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
self.extract_version = max(min_version, self.extract_version)
self.create_version = max(min_version, self.create_version)
filename, flag_bits = self._encodeFilenameFlags()
header = struct.pack(structFileHeader, stringFileHeader,
self.extract_version, self.reserved, flag_bits,
self.compress_type, dostime, dosdate, CRC,
compress_size, file_size,
len(filename), len(extra))
return header + filename + extra
def _encodeFilenameFlags(self):
try:
return self.filename.encode('ascii'), self.flag_bits
except UnicodeEncodeError:
return self.filename.encode('utf-8'), self.flag_bits | 0x800
def _decodeExtra(self):
# Try to decode the extra field.
extra = self.extra
unpack = struct.unpack
while len(extra) >= 4:
tp, ln = unpack('<HH', extra[:4])
if ln+4 > len(extra):
raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln))
if tp == 0x0001:
data = extra[4:ln+4]
# ZIP64 extension (large files and/or large archives)
try:
if self.file_size in (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF):
field = "File size"
self.file_size, = unpack('<Q', data[:8])
data = data[8:]
if self.compress_size == 0xFFFF_FFFF:
field = "Compress size"
self.compress_size, = unpack('<Q', data[:8])
data = data[8:]
if self.header_offset == 0xFFFF_FFFF:
field = "Header offset"
self.header_offset, = unpack('<Q', data[:8])
except struct.error:
raise BadZipFile(f"Corrupt zip64 extra field. "
f"{field} not found.") from None
extra = extra[ln+4:]
@classmethod
def from_file(cls, filename, arcname=None, *, strict_timestamps=True):
"""Construct an appropriate ZipInfo for a file on the filesystem.
filename should be the path to a file or directory on the filesystem.
arcname is the name which it will have within the archive (by default,
this will be the same as filename, but without a drive letter and with
leading path separators removed).
"""
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
st = os.stat(filename)
isdir = stat.S_ISDIR(st.st_mode)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
if not strict_timestamps and date_time[0] < 1980:
date_time = (1980, 1, 1, 0, 0, 0)
elif not strict_timestamps and date_time[0] > 2107:
date_time = (2107, 12, 31, 23, 59, 59)
# Create ZipInfo instance to store file information
if arcname is None:
arcname = filename
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
if isdir:
arcname += '/'
zinfo = cls(arcname, date_time)
zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes
if isdir:
zinfo.file_size = 0
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.file_size = st.st_size
return zinfo
def is_dir(self):
"""Return True if this archive member is a directory."""
return self.filename[-1] == '/'
# ZIP encryption uses the CRC32 one-byte primitive for scrambling some
# internal keys. We noticed that a direct implementation is faster than
# relying on binascii.crc32().
_crctable = None
def _gen_crc(crc):
for j in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0xEDB88320
else:
crc >>= 1
return crc
# ZIP supports a password-based form of encryption. Even though known
# plaintext attacks have been found against it, it is still useful
# to be able to get data out of such a file.
#
# Usage:
# zd = _ZipDecrypter(mypwd)
# plain_bytes = zd(cypher_bytes)
def _ZipDecrypter(pwd):
key0 = 305419896
key1 = 591751049
key2 = 878082192
global _crctable
if _crctable is None:
_crctable = list(map(_gen_crc, range(256)))
crctable = _crctable
def crc32(ch, crc):
"""Compute the CRC32 primitive on one byte."""
return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF]
def update_keys(c):
nonlocal key0, key1, key2
key0 = crc32(c, key0)
key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF
key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF
key2 = crc32(key1 >> 24, key2)
for p in pwd:
update_keys(p)
def decrypter(data):
"""Decrypt a bytes object."""
result = bytearray()
append = result.append
for c in data:
k = key2 | 2
c ^= ((k * (k^1)) >> 8) & 0xFF
update_keys(c)
append(c)
return bytes(result)
return decrypter
class LZMACompressor:
def __init__(self):
self._comp = None
def _init(self):
props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1})
self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1, props)
])
return struct.pack('<BBH', 9, 4, len(props)) + props
def compress(self, data):
if self._comp is None:
return self._init() + self._comp.compress(data)
return self._comp.compress(data)
def flush(self):
if self._comp is None:
return self._init() + self._comp.flush()
return self._comp.flush()
class LZMADecompressor:
def __init__(self):
self._decomp = None
self._unconsumed = b''
self.eof = False
def decompress(self, data):
if self._decomp is None:
self._unconsumed += data
if len(self._unconsumed) <= 4:
return b''
psize, = struct.unpack('<H', self._unconsumed[2:4])
if len(self._unconsumed) <= 4 + psize:
return b''
self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1,
self._unconsumed[4:4 + psize])
])
data = self._unconsumed[4 + psize:]
del self._unconsumed
result = self._decomp.decompress(data)
self.eof = self._decomp.eof
return result
compressor_names = {
0: 'store',
1: 'shrink',
2: 'reduce',
3: 'reduce',
4: 'reduce',
5: 'reduce',
6: 'implode',
7: 'tokenize',
8: 'deflate',
9: 'deflate64',
10: 'implode',
12: 'bzip2',
14: 'lzma',
18: 'terse',
19: 'lz77',
97: 'wavpack',
98: 'ppmd',
}
def _check_compression(compression):
if compression == ZIP_STORED:
pass
elif compression == ZIP_DEFLATED:
if not zlib:
raise RuntimeError(
"Compression requires the (missing) zlib module")
elif compression == ZIP_BZIP2:
if not bz2:
raise RuntimeError(
"Compression requires the (missing) bz2 module")
elif compression == ZIP_LZMA:
if not lzma:
raise RuntimeError(
"Compression requires the (missing) lzma module")
else:
raise NotImplementedError("That compression method is not supported")
def _get_compressor(compress_type, compresslevel=None):
if compress_type == ZIP_DEFLATED:
if compresslevel is not None:
return zlib.compressobj(compresslevel, zlib.DEFLATED, -15)
return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
elif compress_type == ZIP_BZIP2:
if compresslevel is not None:
return bz2.BZ2Compressor(compresslevel)
return bz2.BZ2Compressor()
# compresslevel is ignored for ZIP_LZMA
elif compress_type == ZIP_LZMA:
return LZMACompressor()
else:
return None
def _get_decompressor(compress_type):
_check_compression(compress_type)
if compress_type == ZIP_STORED:
return None
elif compress_type == ZIP_DEFLATED:
return zlib.decompressobj(-15)
elif compress_type == ZIP_BZIP2:
return bz2.BZ2Decompressor()
elif compress_type == ZIP_LZMA:
return LZMADecompressor()
else:
descr = compressor_names.get(compress_type)
if descr:
raise NotImplementedError("compression type %d (%s)" % (compress_type, descr))
else:
raise NotImplementedError("compression type %d" % (compress_type,))
class _SharedFile:
def __init__(self, file, pos, close, lock, writing):
self._file = file
self._pos = pos
self._close = close
self._lock = lock
self._writing = writing
self.seekable = file.seekable
self.tell = file.tell
def seek(self, offset, whence=0):
with self._lock:
if self._writing():
raise ValueError("Can't reposition in the ZIP file while "
"there is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(offset, whence)
self._pos = self._file.tell()
return self._pos
def read(self, n=-1):
with self._lock:
if self._writing():
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(self._pos)
data = self._file.read(n)
self._pos = self._file.tell()
return data
def close(self):
if self._file is not None:
fileobj = self._file
self._file = None
self._close(fileobj)
# Provide the tell method for unseekable stream
class _Tellable:
def __init__(self, fp):
self.fp = fp
self.offset = 0
def write(self, data):
n = self.fp.write(data)
self.offset += n
return n
def tell(self):
return self.offset
def flush(self):
self.fp.flush()
def close(self):
self.fp.close()
class ZipExtFile(io.BufferedIOBase):
"""File-like object for reading an archive member.
Is returned by ZipFile.open().
"""
# Max size supported by decompressor.
MAX_N = 1 << 31 - 1
# Read from compressed files in 4k blocks.
MIN_READ_SIZE = 4096
# Chunk size to read during seek
MAX_SEEK_READ = 1 << 24
def __init__(self, fileobj, mode, zipinfo, pwd=None,
close_fileobj=False):
self._fileobj = fileobj
self._pwd = pwd
self._close_fileobj = close_fileobj
self._compress_type = zipinfo.compress_type
self._compress_left = zipinfo.compress_size
self._left = zipinfo.file_size
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
self._readbuffer = b''
self._offset = 0
self.newlines = None
self.mode = mode
self.name = zipinfo.filename
if hasattr(zipinfo, 'CRC'):
self._expected_crc = zipinfo.CRC
self._running_crc = crc32(b'')
else:
self._expected_crc = None
self._seekable = False
try:
if fileobj.seekable():
self._orig_compress_start = fileobj.tell()
self._orig_compress_size = zipinfo.compress_size
self._orig_file_size = zipinfo.file_size
self._orig_start_crc = self._running_crc
self._seekable = True
except AttributeError:
pass
self._decrypter = None
if pwd:
if zipinfo.flag_bits & 0x8:
# compare against the file type from extended local headers
check_byte = (zipinfo._raw_time >> 8) & 0xff
else:
# compare against the CRC otherwise
check_byte = (zipinfo.CRC >> 24) & 0xff
h = self._init_decrypter()
if h != check_byte:
raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename)
def _init_decrypter(self):
self._decrypter = _ZipDecrypter(self._pwd)
# The first 12 bytes in the cypher stream is an encryption header
# used to strengthen the algorithm. The first 11 bytes are
# completely random, while the 12th contains the MSB of the CRC,
# or the MSB of the file time depending on the header type
# and is used to check the correctness of the password.
header = self._fileobj.read(12)
self._compress_left -= 12
return self._decrypter(header)[11]
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if not self.closed:
result.append(' name=%r mode=%r' % (self.name, self.mode))
if self._compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self._compress_type,
self._compress_type))
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def readline(self, limit=-1):
"""Read and return a line from the stream.
If limit is specified, at most limit bytes will be read.
"""
if limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find(b'\n', self._offset) + 1
if i > 0:
line = self._readbuffer[self._offset: i]
self._offset = i
return line
return io.BufferedIOBase.readline(self, limit)
def peek(self, n=1):
"""Returns buffered bytes without advancing the position."""
if n > len(self._readbuffer) - self._offset:
chunk = self.read(n)
if len(chunk) > self._offset:
self._readbuffer = chunk + self._readbuffer[self._offset:]
self._offset = 0
else:
self._offset -= len(chunk)
# Return up to 512 bytes to reduce allocation overhead for tight loops.
return self._readbuffer[self._offset: self._offset + 512]
def readable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return True
def read(self, n=-1):
"""Read and return up to n bytes.
If the argument is omitted, None, or negative, data is read and returned until EOF is reached.
"""
if self.closed:
raise ValueError("read from closed file.")
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
buf += self._read1(self.MAX_N)
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while n > 0 and not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
buf += data
n -= len(data)
return buf
def _update_crc(self, newdata):
# Update the CRC using the given data.
if self._expected_crc is None:
# No need to compute the CRC if we don't have a reference value
return
self._running_crc = crc32(newdata, self._running_crc)
# Check the CRC if we're at the end of the file
if self._eof and self._running_crc != self._expected_crc:
raise BadZipFile("Bad CRC-32 for file %r" % self.name)
def read1(self, n):
"""Read up to n bytes with at most one read() system call."""
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
data = self._read1(self.MAX_N)
if data:
buf += data
break
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
if n > 0:
while not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
if data:
buf += data
break
return buf
def _read1(self, n):
# Read up to n compressed bytes with at most one read() system call,
# decrypt and decompress them.
if self._eof or n <= 0:
return b''
# Read from file.
if self._compress_type == ZIP_DEFLATED:
## Handle unconsumed data.
data = self._decompressor.unconsumed_tail
if n > len(data):
data += self._read2(n - len(data))
else:
data = self._read2(n)
if self._compress_type == ZIP_STORED:
self._eof = self._compress_left <= 0
elif self._compress_type == ZIP_DEFLATED:
n = max(n, self.MIN_READ_SIZE)
data = self._decompressor.decompress(data, n)
self._eof = (self._decompressor.eof or
self._compress_left <= 0 and
not self._decompressor.unconsumed_tail)
if self._eof:
data += self._decompressor.flush()
else:
data = self._decompressor.decompress(data)
self._eof = self._decompressor.eof or self._compress_left <= 0
data = data[:self._left]
self._left -= len(data)
if self._left <= 0:
self._eof = True
self._update_crc(data)
return data
def _read2(self, n):
if self._compress_left <= 0:
return b''
n = max(n, self.MIN_READ_SIZE)
n = min(n, self._compress_left)
data = self._fileobj.read(n)
self._compress_left -= len(data)
if not data:
raise EOFError
if self._decrypter is not None:
data = self._decrypter(data)
return data
def close(self):
try:
if self._close_fileobj:
self._fileobj.close()
finally:
super().close()
def seekable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return self._seekable
def seek(self, offset, whence=0):
if self.closed:
raise ValueError("seek on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
curr_pos = self.tell()
if whence == 0: # Seek from start of file
new_pos = offset
elif whence == 1: # Seek from current position
new_pos = curr_pos + offset
elif whence == 2: # Seek from EOF
new_pos = self._orig_file_size + offset
else:
raise ValueError("whence must be os.SEEK_SET (0), "
"os.SEEK_CUR (1), or os.SEEK_END (2)")
if new_pos > self._orig_file_size:
new_pos = self._orig_file_size
if new_pos < 0:
new_pos = 0
read_offset = new_pos - curr_pos
buff_offset = read_offset + self._offset
if buff_offset >= 0 and buff_offset < len(self._readbuffer):
# Just move the _offset index if the new position is in the _readbuffer
self._offset = buff_offset
read_offset = 0
elif read_offset < 0:
# Position is before the current position. Reset the ZipExtFile
self._fileobj.seek(self._orig_compress_start)
self._running_crc = self._orig_start_crc
self._compress_left = self._orig_compress_size
self._left = self._orig_file_size
self._readbuffer = b''
self._offset = 0
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
read_offset = new_pos
if self._decrypter is not None:
self._init_decrypter()
while read_offset > 0:
read_len = min(self.MAX_SEEK_READ, read_offset)
self.read(read_len)
read_offset -= read_len
return self.tell()
def tell(self):
if self.closed:
raise ValueError("tell on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset
return filepos
class _ZipWriteFile(io.BufferedIOBase):
def __init__(self, zf, zinfo, zip64):
self._zinfo = zinfo
self._zip64 = zip64
self._zipfile = zf
self._compressor = _get_compressor(zinfo.compress_type,
zinfo._compresslevel)
self._file_size = 0
self._compress_size = 0
self._crc = 0
@property
def _fileobj(self):
return self._zipfile.fp
def writable(self):
return True
def write(self, data):
if self.closed:
raise ValueError('I/O operation on closed file.')
# Accept any data that supports the buffer protocol
if isinstance(data, (bytes, bytearray)):
nbytes = len(data)
else:
data = memoryview(data)
nbytes = data.nbytes
self._file_size += nbytes
self._crc = crc32(data, self._crc)
if self._compressor:
data = self._compressor.compress(data)
self._compress_size += len(data)
self._fileobj.write(data)
return nbytes
def close(self):
if self.closed:
return
try:
super().close()
# Flush any data from the compressor, and update header info
if self._compressor:
buf = self._compressor.flush()
self._compress_size += len(buf)
self._fileobj.write(buf)
self._zinfo.compress_size = self._compress_size
else:
self._zinfo.compress_size = self._file_size
self._zinfo.CRC = self._crc
self._zinfo.file_size = self._file_size
# Write updated header info
if self._zinfo.flag_bits & 0x08:
# Write CRC and file sizes after the file data
fmt = '<LLQQ' if self._zip64 else '<LLLL'
self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC,
self._zinfo.compress_size, self._zinfo.file_size))
self._zipfile.start_dir = self._fileobj.tell()
else:
if not self._zip64:
if self._file_size > ZIP64_LIMIT:
raise RuntimeError(
'File size unexpectedly exceeded ZIP64 limit')
if self._compress_size > ZIP64_LIMIT:
raise RuntimeError(
'Compressed size unexpectedly exceeded ZIP64 limit')
# Seek backwards and write file header (which will now include
# correct CRC and file sizes)
# Preserve current position in file
self._zipfile.start_dir = self._fileobj.tell()
self._fileobj.seek(self._zinfo.header_offset)
self._fileobj.write(self._zinfo.FileHeader(self._zip64))
self._fileobj.seek(self._zipfile.start_dir)
# Successfully written: Add file to our caches
self._zipfile.filelist.append(self._zinfo)
self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo
finally:
self._zipfile._writing = False
class ZipFile:
""" Class with methods to open, read, write, close, list zip files.
z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True,
compresslevel=None)
file: Either the path to the file, or a file-like object.
If it is a path, the file will be opened and closed by ZipFile.
mode: The mode can be either read 'r', write 'w', exclusive create 'x',
or append 'a'.
compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
allowZip64: if True ZipFile will create files with ZIP64 extensions when
needed, otherwise it will raise an exception when this would
be necessary.
compresslevel: None (default for the given compression type) or an integer
specifying the level to pass to the compressor.
When using ZIP_STORED or ZIP_LZMA this keyword has no effect.
When using ZIP_DEFLATED integers 0 through 9 are accepted.
When using ZIP_BZIP2 integers 1 through 9 are accepted.
"""
fp = None # Set here since __del__ checks it
_windows_illegal_name_trans_table = None
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
compresslevel=None, *, strict_timestamps=True):
"""Open the ZIP file with mode read 'r', write 'w', exclusive create 'x',
or append 'a'."""
if mode not in ('r', 'w', 'x', 'a'):
raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'")
_check_compression(compression)
self._allowZip64 = allowZip64
self._didModify = False
self.debug = 0 # Level of printing: 0 through 3
self.NameToInfo = {} # Find file info given name
self.filelist = [] # List of ZipInfo instances for archive
self.compression = compression # Method of compression
self.compresslevel = compresslevel
self.mode = mode
self.pwd = None
self._comment = b''
self._strict_timestamps = strict_timestamps
# Check if we were passed a file-like object
if isinstance(file, os.PathLike):
file = os.fspath(file)
if isinstance(file, str):
# No, it's a filename
self._filePassed = 0
self.filename = file
modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b',
'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'}
filemode = modeDict[mode]
while True:
try:
self.fp = io.open(file, filemode)
except OSError:
if filemode in modeDict:
filemode = modeDict[filemode]
continue
raise
break
else:
self._filePassed = 1
self.fp = file
self.filename = getattr(file, 'name', None)
self._fileRefCnt = 1
self._lock = threading.RLock()
self._seekable = True
self._writing = False
try:
if mode == 'r':
self._RealGetContents()
elif mode in ('w', 'x'):
# set the modified flag so central directory gets written
# even if no files are added to the archive
self._didModify = True
try:
self.start_dir = self.fp.tell()
except (AttributeError, OSError):
self.fp = _Tellable(self.fp)
self.start_dir = 0
self._seekable = False
else:
# Some file-like objects can provide tell() but not seek()
try:
self.fp.seek(self.start_dir)
except (AttributeError, OSError):
self._seekable = False
elif mode == 'a':
try:
# See if file is a zip file
self._RealGetContents()
# seek to start of directory and overwrite
self.fp.seek(self.start_dir)
except BadZipFile:
# file is not a zip file, just append
self.fp.seek(0, 2)
# set the modified flag so central directory gets written
# even if no files are added to the archive
self._didModify = True
self.start_dir = self.fp.tell()
else:
raise ValueError("Mode must be 'r', 'w', 'x', or 'a'")
except:
fp = self.fp
self.fp = None
self._fpclose(fp)
raise
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if self.fp is not None:
if self._filePassed:
result.append(' file=%r' % self.fp)
elif self.filename is not None:
result.append(' filename=%r' % self.filename)
result.append(' mode=%r' % self.mode)
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def _RealGetContents(self):
"""Read in the table of contents for the ZIP file."""
fp = self.fp
try:
endrec = _EndRecData(fp)
except OSError:
raise BadZipFile("File is not a zip file")
if not endrec:
raise BadZipFile("File is not a zip file")
if self.debug > 1:
print(endrec)
size_cd = endrec[_ECD_SIZE] # bytes in central directory
offset_cd = endrec[_ECD_OFFSET] # offset of central directory
self._comment = endrec[_ECD_COMMENT] # archive comment
# "concat" is zero, unless zip was concatenated to another file
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
if endrec[_ECD_SIGNATURE] == stringEndArchive64:
# If Zip64 extension structures are present, account for them
concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
if self.debug > 2:
inferred = concat + offset_cd
print("given, inferred, offset", offset_cd, inferred, concat)
# self.start_dir: Position of start of central directory
self.start_dir = offset_cd + concat
fp.seek(self.start_dir, 0)
data = fp.read(size_cd)
fp = io.BytesIO(data)
total = 0
while total < size_cd:
centdir = fp.read(sizeCentralDir)
if len(centdir) != sizeCentralDir:
raise BadZipFile("Truncated central directory")
centdir = struct.unpack(structCentralDir, centdir)
if centdir[_CD_SIGNATURE] != stringCentralDir:
raise BadZipFile("Bad magic number for central directory")
if self.debug > 2:
print(centdir)
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
flags = centdir[5]
if flags & 0x800:
# UTF-8 file names extension
filename = filename.decode('utf-8')
else:
# Historical ZIP filename encoding
filename = filename.decode('cp437')
# Create ZipInfo instance to store file information
x = ZipInfo(filename)
x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
(x.create_version, x.create_system, x.extract_version, x.reserved,
x.flag_bits, x.compress_type, t, d,
x.CRC, x.compress_size, x.file_size) = centdir[1:12]
if x.extract_version > MAX_EXTRACT_VERSION:
raise NotImplementedError("zip file version %.1f" %
(x.extract_version / 10))
x.volume, x.internal_attr, x.external_attr = centdir[15:18]
# Convert date/time code to (year, month, day, hour, min, sec)
x._raw_time = t
x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
x._decodeExtra()
x.header_offset = x.header_offset + concat
self.filelist.append(x)
self.NameToInfo[x.filename] = x
# update total bytes read from central directory
total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
+ centdir[_CD_EXTRA_FIELD_LENGTH]
+ centdir[_CD_COMMENT_LENGTH])
if self.debug > 2:
print("total", total)
def namelist(self):
"""Return a list of file names in the archive."""
return [data.filename for data in self.filelist]
def infolist(self):
"""Return a list of class ZipInfo instances for files in the
archive."""
return self.filelist
def printdir(self, file=None):
"""Print a table of contents for the zip file."""
print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"),
file=file)
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
file=file)
def testzip(self):
"""Read all the files and check the CRC."""
chunk_size = 2 ** 20
for zinfo in self.filelist:
try:
# Read by chunks, to avoid an OverflowError or a
# MemoryError with very large embedded files.
with self.open(zinfo.filename, "r") as f:
while f.read(chunk_size): # Check CRC-32
pass
except BadZipFile:
return zinfo.filename
def getinfo(self, name):
"""Return the instance of ZipInfo given 'name'."""
info = self.NameToInfo.get(name)
if info is None:
raise KeyError(
'There is no item named %r in the archive' % name)
return info
def setpassword(self, pwd):
"""Set default password for encrypted files."""
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd:
self.pwd = pwd
else:
self.pwd = None
@property
def comment(self):
"""The comment text associated with the ZIP file."""
return self._comment
@comment.setter
def comment(self, comment):
if not isinstance(comment, bytes):
raise TypeError("comment: expected bytes, got %s" % type(comment).__name__)
# check for valid comment length
if len(comment) > ZIP_MAX_COMMENT:
import warnings
warnings.warn('Archive comment is too long; truncating to %d bytes'
% ZIP_MAX_COMMENT, stacklevel=2)
comment = comment[:ZIP_MAX_COMMENT]
self._comment = comment
self._didModify = True
def read(self, name, pwd=None):
"""Return file bytes for name."""
with self.open(name, "r", pwd) as fp:
return fp.read()
def open(self, name, mode="r", pwd=None, *, force_zip64=False):
"""Return file-like object for 'name'.
name is a string for the file name within the ZIP file, or a ZipInfo
object.
mode should be 'r' to read a file already in the ZIP file, or 'w' to
write to a file newly added to the archive.
pwd is the password to decrypt files (only used for reading).
When writing, if the file size is not known in advance but may exceed
2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large
files. If the size is known in advance, it is best to pass a ZipInfo
instance for name, with zinfo.file_size set.
"""
if mode not in {"r", "w"}:
raise ValueError('open() requires mode "r" or "w"')
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd and (mode == "w"):
raise ValueError("pwd is only supported for reading files")
if not self.fp:
raise ValueError(
"Attempt to use ZIP archive that was already closed")
# Make sure we have an info object
if isinstance(name, ZipInfo):
# 'name' is already an info object
zinfo = name
elif mode == 'w':
zinfo = ZipInfo(name)
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
else:
# Get info object for name
zinfo = self.getinfo(name)
if mode == 'w':
return self._open_to_write(zinfo, force_zip64=force_zip64)
if self._writing:
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
# Open for reading:
self._fileRefCnt += 1
zef_file = _SharedFile(self.fp, zinfo.header_offset,
self._fpclose, self._lock, lambda: self._writing)
try:
# Skip the file header:
fheader = zef_file.read(sizeFileHeader)
if len(fheader) != sizeFileHeader:
raise BadZipFile("Truncated file header")
fheader = struct.unpack(structFileHeader, fheader)
if fheader[_FH_SIGNATURE] != stringFileHeader:
raise BadZipFile("Bad magic number for file header")
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
if fheader[_FH_EXTRA_FIELD_LENGTH]:
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
if zinfo.flag_bits & 0x20:
# Zip 2.7: compressed patched data
raise NotImplementedError("compressed patched data (flag bit 5)")
if zinfo.flag_bits & 0x40:
# strong encryption
raise NotImplementedError("strong encryption (flag bit 6)")
if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
fname_str = fname.decode("cp437")
if fname_str != zinfo.orig_filename:
raise BadZipFile(
'File name in directory %r and header %r differ.'
% (zinfo.orig_filename, fname))
# check for encrypted flag & handle password
is_encrypted = zinfo.flag_bits & 0x1
if is_encrypted:
if not pwd:
pwd = self.pwd
if not pwd:
raise RuntimeError("File %r is encrypted, password "
"required for extraction" % name)
else:
pwd = None
return ZipExtFile(zef_file, mode, zinfo, pwd, True)
except:
zef_file.close()
raise
def _open_to_write(self, zinfo, force_zip64=False):
if force_zip64 and not self._allowZip64:
raise ValueError(
"force_zip64 is True, but allowZip64 was False when opening "
"the ZIP file."
)
if self._writing:
raise ValueError("Can't write to the ZIP file while there is "
"another write handle open on it. "
"Close the first handle before opening another.")
# Size and CRC are overwritten with correct data after processing the file
zinfo.compress_size = 0
zinfo.CRC = 0
zinfo.flag_bits = 0x00
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
if not self._seekable:
zinfo.flag_bits |= 0x08
if not zinfo.external_attr:
zinfo.external_attr = 0o600 << 16 # permissions: ?rw-------
# Compressed size can be larger than uncompressed size
zip64 = self._allowZip64 and \
(force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT)
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
self.fp.write(zinfo.FileHeader(zip64))
self._writing = True
return _ZipWriteFile(self, zinfo, zip64)
def extract(self, member, path=None, pwd=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a ZipInfo object. You can
specify a different directory using `path'.
"""
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
return self._extract_member(member, path, pwd)
def extractall(self, path=None, members=None, pwd=None):
"""Extract all members from the archive to the current working
directory. `path' specifies a different directory to extract to.
`members' is optional and must be a subset of the list returned
by namelist().
"""
if members is None:
members = self.namelist()
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
for zipinfo in members:
self._extract_member(zipinfo, path, pwd)
@classmethod
def _sanitize_windows_name(cls, arcname, pathsep):
"""Replace bad characters and remove trailing dots from parts."""
table = cls._windows_illegal_name_trans_table
if not table:
illegal = ':<>|"?*'
table = str.maketrans(illegal, '_' * len(illegal))
cls._windows_illegal_name_trans_table = table
arcname = arcname.translate(table)
# remove trailing dots
arcname = (x.rstrip('.') for x in arcname.split(pathsep))
# rejoin, removing empty parts.
arcname = pathsep.join(x for x in arcname if x)
return arcname
def _extract_member(self, member, targetpath, pwd):
"""Extract the ZipInfo object 'member' to a physical
file on the path targetpath.
"""
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
# build the destination pathname, replacing
# forward slashes to platform specific separators.
arcname = member.filename.replace('/', os.path.sep)
if os.path.altsep:
arcname = arcname.replace(os.path.altsep, os.path.sep)
# interpret absolute pathname as relative, remove drive letter or
# UNC path, redundant separators, "." and ".." components.
arcname = os.path.splitdrive(arcname)[1]
invalid_path_parts = ('', os.path.curdir, os.path.pardir)
arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
if x not in invalid_path_parts)
if os.path.sep == '\\':
# filter illegal characters on Windows
arcname = self._sanitize_windows_name(arcname, os.path.sep)
targetpath = os.path.join(targetpath, arcname)
targetpath = os.path.normpath(targetpath)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.is_dir():
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
open(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath
def _writecheck(self, zinfo):
"""Check for errors before writing a file to the archive."""
if zinfo.filename in self.NameToInfo:
import warnings
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
if self.mode not in ('w', 'x', 'a'):
raise ValueError("write() requires mode 'w', 'x', or 'a'")
if not self.fp:
raise ValueError(
"Attempt to write ZIP archive that was already closed")
_check_compression(zinfo.compress_type)
if not self._allowZip64:
requires_zip64 = None
if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif zinfo.file_size > ZIP64_LIMIT:
requires_zip64 = "Filesize"
elif zinfo.header_offset > ZIP64_LIMIT:
requires_zip64 = "Zipfile size"
if requires_zip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
def write(self, filename, arcname=None,
compress_type=None, compresslevel=None):
"""Put the bytes from filename into the archive under the name
arcname."""
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists"
)
zinfo = ZipInfo.from_file(filename, arcname,
strict_timestamps=self._strict_timestamps)
if zinfo.is_dir():
zinfo.compress_size = 0
zinfo.CRC = 0
else:
if compress_type is not None:
zinfo.compress_type = compress_type
else:
zinfo.compress_type = self.compression
if compresslevel is not None:
zinfo._compresslevel = compresslevel
else:
zinfo._compresslevel = self.compresslevel
if zinfo.is_dir():
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell() # Start of header bytes
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
self._writecheck(zinfo)
self._didModify = True
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
self.fp.write(zinfo.FileHeader(False))
self.start_dir = self.fp.tell()
else:
with open(filename, "rb") as src, self.open(zinfo, 'w') as dest:
shutil.copyfileobj(src, dest, 1024*8)
def writestr(self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None):
"""Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive."""
if isinstance(data, str):
data = data.encode("utf-8")
if not isinstance(zinfo_or_arcname, ZipInfo):
zinfo = ZipInfo(filename=zinfo_or_arcname,
date_time=time.localtime(time.time())[:6])
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
if zinfo.filename[-1] == '/':
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.external_attr = 0o600 << 16 # ?rw-------
else:
zinfo = zinfo_or_arcname
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists."
)
if compress_type is not None:
zinfo.compress_type = compress_type
if compresslevel is not None:
zinfo._compresslevel = compresslevel
zinfo.file_size = len(data) # Uncompressed size
with self._lock:
with self.open(zinfo, mode='w') as dest:
dest.write(data)
def __del__(self):
"""Call the "close()" method in case the user forgot."""
self.close()
def close(self):
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
records."""
if self.fp is None:
return
if self._writing:
raise ValueError("Can't close the ZIP file while there is "
"an open writing handle on it. "
"Close the writing handle before closing the zip.")
try:
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
self._write_end_record()
finally:
fp = self.fp
self.fp = None
self._fpclose(fp)
def _write_end_record(self):
for zinfo in self.filelist: # write central directory
dt = zinfo.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
extra = []
if zinfo.file_size > ZIP64_LIMIT \
or zinfo.compress_size > ZIP64_LIMIT:
extra.append(zinfo.file_size)
extra.append(zinfo.compress_size)
file_size = 0xffffffff
compress_size = 0xffffffff
else:
file_size = zinfo.file_size
compress_size = zinfo.compress_size
if zinfo.header_offset > ZIP64_LIMIT:
extra.append(zinfo.header_offset)
header_offset = 0xffffffff
else:
header_offset = zinfo.header_offset
extra_data = zinfo.extra
min_version = 0
if extra:
# Append a ZIP64 field to the extra's
extra_data = _strip_extra(extra_data, (1,))
extra_data = struct.pack(
'<HH' + 'Q'*len(extra),
1, 8*len(extra), *extra) + extra_data
min_version = ZIP64_VERSION
if zinfo.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif zinfo.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
extract_version = max(min_version, zinfo.extract_version)
create_version = max(min_version, zinfo.create_version)
filename, flag_bits = zinfo._encodeFilenameFlags()
centdir = struct.pack(structCentralDir,
stringCentralDir, create_version,
zinfo.create_system, extract_version, zinfo.reserved,
flag_bits, zinfo.compress_type, dostime, dosdate,
zinfo.CRC, compress_size, file_size,
len(filename), len(extra_data), len(zinfo.comment),
0, zinfo.internal_attr, zinfo.external_attr,
header_offset)
self.fp.write(centdir)
self.fp.write(filename)
self.fp.write(extra_data)
self.fp.write(zinfo.comment)
pos2 = self.fp.tell()
# Write end-of-zip-archive record
centDirCount = len(self.filelist)
centDirSize = pos2 - self.start_dir
centDirOffset = self.start_dir
requires_zip64 = None
if centDirCount > ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif centDirOffset > ZIP64_LIMIT:
requires_zip64 = "Central directory offset"
elif centDirSize > ZIP64_LIMIT:
requires_zip64 = "Central directory size"
if requires_zip64:
# Need to write the ZIP64 end-of-archive records
if not self._allowZip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
zip64endrec = struct.pack(
structEndArchive64, stringEndArchive64,
44, 45, 45, 0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset)
self.fp.write(zip64endrec)
zip64locrec = struct.pack(
structEndArchive64Locator,
stringEndArchive64Locator, 0, pos2, 1)
self.fp.write(zip64locrec)
centDirCount = min(centDirCount, 0xFFFF)
centDirSize = min(centDirSize, 0xFFFFFFFF)
centDirOffset = min(centDirOffset, 0xFFFFFFFF)
endrec = struct.pack(structEndArchive, stringEndArchive,
0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset, len(self._comment))
self.fp.write(endrec)
self.fp.write(self._comment)
if self.mode == "a":
self.fp.truncate()
self.fp.flush()
def _fpclose(self, fp):
assert self._fileRefCnt > 0
self._fileRefCnt -= 1
if not self._fileRefCnt and not self._filePassed:
fp.close()
class PyZipFile(ZipFile):
"""Class to create ZIP archives with Python library files and packages."""
def __init__(self, file, mode="r", compression=ZIP_STORED,
allowZip64=True, optimize=-1):
ZipFile.__init__(self, file, mode=mode, compression=compression,
allowZip64=allowZip64)
self._optimize = optimize
def writepy(self, pathname, basename="", filterfunc=None):
"""Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive. If pathname is a plain
directory, listdir *.py and enter all modules. Else, pathname
must be a Python *.py file and the module will be put into the
archive. Added modules are always module.pyc.
This method will compile the module.py into module.pyc if
necessary.
If filterfunc(pathname) is given, it is called with every argument.
When it is False, the file or directory is skipped.
"""
pathname = os.fspath(pathname)
if filterfunc and not filterfunc(pathname):
if self.debug:
label = 'path' if os.path.isdir(pathname) else 'file'
print('%s %r skipped by filterfunc' % (label, pathname))
return
dir, name = os.path.split(pathname)
if os.path.isdir(pathname):
initname = os.path.join(pathname, "__init__.py")
if os.path.isfile(initname):
# This is a package directory, add it
if basename:
basename = "%s/%s" % (basename, name)
else:
basename = name
if self.debug:
print("Adding package in", pathname, "as", basename)
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
dirlist = sorted(os.listdir(pathname))
dirlist.remove("__init__.py")
# Add all *.py files and package subdirectories
for filename in dirlist:
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, "__init__.py")):
# This is a package directory, add it
self.writepy(path, basename,
filterfunc=filterfunc) # Recursive call
elif ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
print("Adding files from directory", pathname)
for filename in sorted(os.listdir(pathname)):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError(
'Files added with writepy() must end with ".py"')
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print("Adding file", arcname)
self.write(fname, arcname)
def _get_codename(self, pathname, basename):
"""Return (filename, archivename) for the path.
Given a module name path, return the correct file path and
archive name, compiling if necessary. For example, given
/python/lib/string, return (/python/lib/string.pyc, string).
"""
def _compile(file, optimize=-1):
import py_compile
if self.debug:
print("Compiling", file)
try:
py_compile.compile(file, doraise=True, optimize=optimize)
except py_compile.PyCompileError as err:
print(err.msg)
return False
return True
file_py = pathname + ".py"
file_pyc = pathname + ".pyc"
pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='')
pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1)
pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2)
if self._optimize == -1:
# legacy mode: use whatever file is present
if (os.path.isfile(file_pyc) and
os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
# Use .pyc file.
arcname = fname = file_pyc
elif (os.path.isfile(pycache_opt0) and
os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt0
arcname = file_pyc
elif (os.path.isfile(pycache_opt1) and
os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt1
arcname = file_pyc
elif (os.path.isfile(pycache_opt2) and
os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt2
arcname = file_pyc
else:
# Compile py into PEP 3147 pyc file.
if _compile(file_py):
if sys.flags.optimize == 0:
fname = pycache_opt0
elif sys.flags.optimize == 1:
fname = pycache_opt1
else:
fname = pycache_opt2
arcname = file_pyc
else:
fname = arcname = file_py
else:
# new mode: use given optimization level
if self._optimize == 0:
fname = pycache_opt0
arcname = file_pyc
else:
arcname = file_pyc
if self._optimize == 1:
fname = pycache_opt1
elif self._optimize == 2:
fname = pycache_opt2
else:
msg = "invalid value for 'optimize': {!r}".format(self._optimize)
raise ValueError(msg)
if not (os.path.isfile(fname) and
os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
if not _compile(file_py, optimize=self._optimize):
fname = arcname = file_py
archivename = os.path.split(arcname)[1]
if basename:
archivename = "%s/%s" % (basename, archivename)
return (fname, archivename)
def _parents(path):
"""
Given a path with elements separated by
posixpath.sep, generate all parents of that path.
>>> list(_parents('b/d'))
['b']
>>> list(_parents('/b/d/'))
['/b']
>>> list(_parents('b/d/f/'))
['b/d', 'b']
>>> list(_parents('b'))
[]
>>> list(_parents(''))
[]
"""
return itertools.islice(_ancestry(path), 1, None)
def _ancestry(path):
"""
Given a path with elements separated by
posixpath.sep, generate all elements of that path
>>> list(_ancestry('b/d'))
['b/d', 'b']
>>> list(_ancestry('/b/d/'))
['/b/d', '/b']
>>> list(_ancestry('b/d/f/'))
['b/d/f', 'b/d', 'b']
>>> list(_ancestry('b'))
['b']
>>> list(_ancestry(''))
[]
"""
path = path.rstrip(posixpath.sep)
while path and path != posixpath.sep:
yield path
path, tail = posixpath.split(path)
_dedupe = dict.fromkeys
"""Deduplicate an iterable in original order"""
def _difference(minuend, subtrahend):
"""
Return items in minuend not in subtrahend, retaining order
with O(1) lookup.
"""
return itertools.filterfalse(set(subtrahend).__contains__, minuend)
class CompleteDirs(ZipFile):
"""
A ZipFile subclass that ensures that implied directories
are always included in the namelist.
"""
@staticmethod
def _implied_dirs(names):
parents = itertools.chain.from_iterable(map(_parents, names))
as_dirs = (p + posixpath.sep for p in parents)
return _dedupe(_difference(as_dirs, names))
def namelist(self):
names = super(CompleteDirs, self).namelist()
return names + list(self._implied_dirs(names))
def _name_set(self):
return set(self.namelist())
def resolve_dir(self, name):
"""
If the name represents a directory, return that name
as a directory (with the trailing slash).
"""
names = self._name_set()
dirname = name + '/'
dir_match = name not in names and dirname in names
return dirname if dir_match else name
@classmethod
def make(cls, source):
"""
Given a source (filename or zipfile), return an
appropriate CompleteDirs subclass.
"""
if isinstance(source, CompleteDirs):
return source
if not isinstance(source, ZipFile):
return cls(source)
# Only allow for FastPath when supplied zipfile is read-only
if 'r' not in source.mode:
cls = CompleteDirs
res = cls.__new__(cls)
vars(res).update(vars(source))
return res
class FastLookup(CompleteDirs):
"""
ZipFile subclass to ensure implicit
dirs exist and are resolved rapidly.
"""
def namelist(self):
with contextlib.suppress(AttributeError):
return self.__names
self.__names = super(FastLookup, self).namelist()
return self.__names
def _name_set(self):
with contextlib.suppress(AttributeError):
return self.__lookup
self.__lookup = super(FastLookup, self)._name_set()
return self.__lookup
class Path:
"""
A pathlib-compatible interface for zip files.
Consider a zip file with this structure::
.
├── a.txt
└── b
├── c.txt
└── d
└── e.txt
>>> data = io.BytesIO()
>>> zf = ZipFile(data, 'w')
>>> zf.writestr('a.txt', 'content of a')
>>> zf.writestr('b/c.txt', 'content of c')
>>> zf.writestr('b/d/e.txt', 'content of e')
>>> zf.filename = 'abcde.zip'
Path accepts the zipfile object itself or a filename
>>> root = Path(zf)
From there, several path operations are available.
Directory iteration (including the zip file itself):
>>> a, b = root.iterdir()
>>> a
Path('abcde.zip', 'a.txt')
>>> b
Path('abcde.zip', 'b/')
name property:
>>> b.name
'b'
join with divide operator:
>>> c = b / 'c.txt'
>>> c
Path('abcde.zip', 'b/c.txt')
>>> c.name
'c.txt'
Read text:
>>> c.read_text()
'content of c'
existence:
>>> c.exists()
True
>>> (b / 'missing.txt').exists()
False
Coercion to string:
>>> str(c)
'abcde.zip/b/c.txt'
"""
__repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
def __init__(self, root, at=""):
self.root = FastLookup.make(root)
self.at = at
def open(self, mode='r', *args, **kwargs):
"""
Open this entry as text or binary following the semantics
of ``pathlib.Path.open()`` by passing arguments through
to io.TextIOWrapper().
"""
pwd = kwargs.pop('pwd', None)
zip_mode = mode[0]
stream = self.root.open(self.at, zip_mode, pwd=pwd)
if 'b' in mode:
if args or kwargs:
raise ValueError("encoding args invalid for binary operation")
return stream
return io.TextIOWrapper(stream, *args, **kwargs)
@property
def name(self):
return posixpath.basename(self.at.rstrip("/"))
def read_text(self, *args, **kwargs):
with self.open('r', *args, **kwargs) as strm:
return strm.read()
def read_bytes(self):
with self.open('rb') as strm:
return strm.read()
def _is_child(self, path):
return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
def _next(self, at):
return Path(self.root, at)
def is_dir(self):
return not self.at or self.at.endswith("/")
def is_file(self):
return not self.is_dir()
def exists(self):
return self.at in self.root._name_set()
def iterdir(self):
if not self.is_dir():
raise ValueError("Can't listdir a file")
subs = map(self._next, self.root.namelist())
return filter(self._is_child, subs)
def __str__(self):
return posixpath.join(self.root.filename, self.at)
def __repr__(self):
return self.__repr.format(self=self)
def joinpath(self, add):
next = posixpath.join(self.at, add)
return self._next(self.root.resolve_dir(next))
__truediv__ = joinpath
@property
def parent(self):
parent_at = posixpath.dirname(self.at.rstrip('/'))
if parent_at:
parent_at += '/'
return self._next(parent_at)
def main(args=None):
import argparse
description = 'A simple command-line interface for zipfile module.'
parser = argparse.ArgumentParser(description=description)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', metavar='<zipfile>',
help='Show listing of a zipfile')
group.add_argument('-e', '--extract', nargs=2,
metavar=('<zipfile>', '<output_dir>'),
help='Extract zipfile into target dir')
group.add_argument('-c', '--create', nargs='+',
metavar=('<name>', '<file>'),
help='Create zipfile from sources')
group.add_argument('-t', '--test', metavar='<zipfile>',
help='Test if a zipfile is valid')
args = parser.parse_args(args)
if args.test is not None:
src = args.test
with ZipFile(src, 'r') as zf:
badfile = zf.testzip()
if badfile:
print("The following enclosed file is corrupted: {!r}".format(badfile))
print("Done testing")
elif args.list is not None:
src = args.list
with ZipFile(src, 'r') as zf:
zf.printdir()
elif args.extract is not None:
src, curdir = args.extract
with ZipFile(src, 'r') as zf:
zf.extractall(curdir)
elif args.create is not None:
zip_name = args.create.pop(0)
files = args.create
def addToZip(zf, path, zippath):
if os.path.isfile(path):
zf.write(path, zippath, ZIP_DEFLATED)
elif os.path.isdir(path):
if zippath:
zf.write(path, zippath)
for nm in sorted(os.listdir(path)):
addToZip(zf,
os.path.join(path, nm), os.path.join(zippath, nm))
# else: ignore
with ZipFile(zip_name, 'w') as zf:
for path in files:
zippath = os.path.basename(path)
if not zippath:
zippath = os.path.basename(os.path.dirname(path))
if zippath in ('', os.curdir, os.pardir):
zippath = ''
addToZip(zf, path, zippath)
if __name__ == "__main__":
main()
| 35.897373 | 102 | 0.569471 | import binascii
import importlib.util
import io
import itertools
import os
import posixpath
import shutil
import stat
import struct
import sys
import threading
import time
import contextlib
try:
import zlib
crc32 = zlib.crc32
except ImportError:
zlib = None
crc32 = binascii.crc32
try:
import bz2
except ImportError:
bz2 = None
try:
import lzma
except ImportError:
lzma = None
__all__ = ["BadZipFile", "BadZipfile", "error",
"ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA",
"is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile",
"Path"]
class BadZipFile(Exception):
pass
class LargeZipFile(Exception):
error = BadZipfile = BadZipFile
ZIP64_LIMIT = (1 << 31) - 1
ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
ZIP_MAX_COMMENT = (1 << 16) - 1
ZIP_STORED = 0
ZIP_DEFLATED = 8
ZIP_BZIP2 = 12
ZIP_LZMA = 14
DEFAULT_VERSION = 20
ZIP64_VERSION = 45
BZIP2_VERSION = 46
LZMA_VERSION = 63
MAX_EXTRACT_VERSION = 63
structEndArchive = b"<4s4H2LH"
stringEndArchive = b"PK\005\006"
sizeEndCentDir = struct.calcsize(structEndArchive)
_ECD_SIGNATURE = 0
_ECD_DISK_NUMBER = 1
_ECD_DISK_START = 2
_ECD_ENTRIES_THIS_DISK = 3
_ECD_ENTRIES_TOTAL = 4
_ECD_SIZE = 5
_ECD_OFFSET = 6
_ECD_COMMENT_SIZE = 7
_ECD_COMMENT = 8
_ECD_LOCATION = 9
structCentralDir = "<4s4B4HL2L5H2L"
stringCentralDir = b"PK\001\002"
sizeCentralDir = struct.calcsize(structCentralDir)
_CD_SIGNATURE = 0
_CD_CREATE_VERSION = 1
_CD_CREATE_SYSTEM = 2
_CD_EXTRACT_VERSION = 3
_CD_EXTRACT_SYSTEM = 4
_CD_FLAG_BITS = 5
_CD_COMPRESS_TYPE = 6
_CD_TIME = 7
_CD_DATE = 8
_CD_CRC = 9
_CD_COMPRESSED_SIZE = 10
_CD_UNCOMPRESSED_SIZE = 11
_CD_FILENAME_LENGTH = 12
_CD_EXTRA_FIELD_LENGTH = 13
_CD_COMMENT_LENGTH = 14
_CD_DISK_NUMBER_START = 15
_CD_INTERNAL_FILE_ATTRIBUTES = 16
_CD_EXTERNAL_FILE_ATTRIBUTES = 17
_CD_LOCAL_HEADER_OFFSET = 18
structFileHeader = "<4s2B4HL2L2H"
stringFileHeader = b"PK\003\004"
sizeFileHeader = struct.calcsize(structFileHeader)
_FH_SIGNATURE = 0
_FH_EXTRACT_VERSION = 1
_FH_EXTRACT_SYSTEM = 2
_FH_GENERAL_PURPOSE_FLAG_BITS = 3
_FH_COMPRESSION_METHOD = 4
_FH_LAST_MOD_TIME = 5
_FH_LAST_MOD_DATE = 6
_FH_CRC = 7
_FH_COMPRESSED_SIZE = 8
_FH_UNCOMPRESSED_SIZE = 9
_FH_FILENAME_LENGTH = 10
_FH_EXTRA_FIELD_LENGTH = 11
structEndArchive64Locator = "<4sLQL"
stringEndArchive64Locator = b"PK\x06\x07"
sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
structEndArchive64 = "<4sQ2H2L4Q"
stringEndArchive64 = b"PK\x06\x06"
sizeEndCentDir64 = struct.calcsize(structEndArchive64)
_CD64_SIGNATURE = 0
_CD64_DIRECTORY_RECSIZE = 1
_CD64_CREATE_VERSION = 2
_CD64_EXTRACT_VERSION = 3
_CD64_DISK_NUMBER = 4
_CD64_DISK_NUMBER_START = 5
_CD64_NUMBER_ENTRIES_THIS_DISK = 6
_CD64_NUMBER_ENTRIES_TOTAL = 7
_CD64_DIRECTORY_SIZE = 8
_CD64_OFFSET_START_CENTDIR = 9
_DD_SIGNATURE = 0x08074b50
_EXTRA_FIELD_STRUCT = struct.Struct('<HH')
def _strip_extra(extra, xids):
unpack = _EXTRA_FIELD_STRUCT.unpack
modified = False
buffer = []
start = i = 0
while i + 4 <= len(extra):
xid, xlen = unpack(extra[i : i + 4])
j = i + 4 + xlen
if xid in xids:
if i != start:
buffer.append(extra[start : i])
start = j
modified = True
i = j
if not modified:
return extra
return b''.join(buffer)
def _check_zipfile(fp):
try:
if _EndRecData(fp):
return True
except OSError:
pass
return False
def is_zipfile(filename):
result = False
try:
if hasattr(filename, "read"):
result = _check_zipfile(fp=filename)
else:
with open(filename, "rb") as fp:
result = _check_zipfile(fp)
except OSError:
pass
return result
def _EndRecData64(fpin, offset, endrec):
try:
fpin.seek(offset - sizeEndCentDir64Locator, 2)
except OSError:
return endrec
data = fpin.read(sizeEndCentDir64Locator)
if len(data) != sizeEndCentDir64Locator:
return endrec
sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
if sig != stringEndArchive64Locator:
return endrec
if diskno != 0 or disks > 1:
raise BadZipFile("zipfiles that span multiple disks are not supported")
fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
data = fpin.read(sizeEndCentDir64)
if len(data) != sizeEndCentDir64:
return endrec
sig, sz, create_version, read_version, disk_num, disk_dir, \
dircount, dircount2, dirsize, diroffset = \
struct.unpack(structEndArchive64, data)
if sig != stringEndArchive64:
return endrec
endrec[_ECD_SIGNATURE] = sig
endrec[_ECD_DISK_NUMBER] = disk_num
endrec[_ECD_DISK_START] = disk_dir
endrec[_ECD_ENTRIES_THIS_DISK] = dircount
endrec[_ECD_ENTRIES_TOTAL] = dircount2
endrec[_ECD_SIZE] = dirsize
endrec[_ECD_OFFSET] = diroffset
return endrec
def _EndRecData(fpin):
fpin.seek(0, 2)
filesize = fpin.tell()
try:
fpin.seek(-sizeEndCentDir, 2)
except OSError:
return None
data = fpin.read()
if (len(data) == sizeEndCentDir and
data[0:4] == stringEndArchive and
data[-2:] == b"\000\000"):
endrec = struct.unpack(structEndArchive, data)
endrec=list(endrec)
# Append a blank comment and record start offset
endrec.append(b"")
endrec.append(filesize - sizeEndCentDir)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
# Either this is not a ZIP file, or it is a ZIP file with an archive
# comment. Search the end of the file for the "end of central directory"
# record signature. The comment is the last item in the ZIP file and may be
# up to 64K long. It is assumed that the "end of central directory" magic
# number does not appear in the comment.
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
fpin.seek(maxCommentStart, 0)
data = fpin.read()
start = data.rfind(stringEndArchive)
if start >= 0:
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
if len(recData) != sizeEndCentDir:
# Zip file is corrupted.
return None
endrec = list(struct.unpack(structEndArchive, recData))
commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
endrec.append(comment)
endrec.append(maxCommentStart + start)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, maxCommentStart + start - filesize,
endrec)
# Unable to find a valid end of central directory structure
return None
class ZipInfo (object):
__slots__ = (
'orig_filename',
'filename',
'date_time',
'compress_type',
'_compresslevel',
'comment',
'extra',
'create_system',
'create_version',
'extract_version',
'reserved',
'flag_bits',
'volume',
'internal_attr',
'external_attr',
'header_offset',
'CRC',
'compress_size',
'file_size',
'_raw_time',
)
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
self.orig_filename = filename # Original file name in archive
# Terminate the file name at the first null byte. Null bytes in file
# names are used as tricks by viruses in archives.
null_byte = filename.find(chr(0))
if null_byte >= 0:
filename = filename[0:null_byte]
# This is used to ensure paths in generated ZIP files always use
# forward slashes as the directory separator, as required by the
# ZIP format specification.
if os.sep != "/" and os.sep in filename:
filename = filename.replace(os.sep, "/")
self.filename = filename # Normalized file name
self.date_time = date_time # year, month, day, hour, min, sec
if date_time[0] < 1980:
raise ValueError('ZIP does not support timestamps before 1980')
# Standard values:
self.compress_type = ZIP_STORED # Type of compression for the file
self._compresslevel = None # Level for the compressor
self.comment = b"" # Comment for each file
self.extra = b"" # ZIP extra data
if sys.platform == 'win32':
self.create_system = 0 # System which created ZIP archive
else:
# Assume everything else is unix-y
self.create_system = 3 # System which created ZIP archive
self.create_version = DEFAULT_VERSION # Version which created ZIP archive
self.extract_version = DEFAULT_VERSION # Version needed to extract archive
self.reserved = 0 # Must be zero
self.flag_bits = 0 # ZIP flag bits
self.volume = 0 # Volume number of file header
self.internal_attr = 0 # Internal attributes
self.external_attr = 0 # External file attributes
self.compress_size = 0 # Size of the compressed file
self.file_size = 0 # Size of the uncompressed file
# Other attributes are set by class ZipFile:
# header_offset Byte offset to the file header
# CRC CRC-32 of the uncompressed file
def __repr__(self):
result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)]
if self.compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self.compress_type,
self.compress_type))
hi = self.external_attr >> 16
lo = self.external_attr & 0xFFFF
if hi:
result.append(' filemode=%r' % stat.filemode(hi))
if lo:
result.append(' external_attr=%
isdir = self.is_dir()
if not isdir or self.file_size:
result.append(' file_size=%r' % self.file_size)
if ((not isdir or self.compress_size) and
(self.compress_type != ZIP_STORED or
self.file_size != self.compress_size)):
result.append(' compress_size=%r' % self.compress_size)
result.append('>')
return ''.join(result)
def FileHeader(self, zip64=None):
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the file data
CRC = compress_size = file_size = 0
else:
CRC = self.CRC
compress_size = self.compress_size
file_size = self.file_size
extra = self.extra
min_version = 0
if zip64 is None:
zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
if zip64:
fmt = '<HHQQ'
extra = extra + struct.pack(fmt,
1, struct.calcsize(fmt)-4, file_size, compress_size)
if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
if not zip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
# File is larger than what fits into a 4 byte integer,
# fall back to the ZIP64 extension
file_size = 0xffffffff
compress_size = 0xffffffff
min_version = ZIP64_VERSION
if self.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif self.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
self.extract_version = max(min_version, self.extract_version)
self.create_version = max(min_version, self.create_version)
filename, flag_bits = self._encodeFilenameFlags()
header = struct.pack(structFileHeader, stringFileHeader,
self.extract_version, self.reserved, flag_bits,
self.compress_type, dostime, dosdate, CRC,
compress_size, file_size,
len(filename), len(extra))
return header + filename + extra
def _encodeFilenameFlags(self):
try:
return self.filename.encode('ascii'), self.flag_bits
except UnicodeEncodeError:
return self.filename.encode('utf-8'), self.flag_bits | 0x800
def _decodeExtra(self):
# Try to decode the extra field.
extra = self.extra
unpack = struct.unpack
while len(extra) >= 4:
tp, ln = unpack('<HH', extra[:4])
if ln+4 > len(extra):
raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln))
if tp == 0x0001:
data = extra[4:ln+4]
# ZIP64 extension (large files and/or large archives)
try:
if self.file_size in (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF):
field = "File size"
self.file_size, = unpack('<Q', data[:8])
data = data[8:]
if self.compress_size == 0xFFFF_FFFF:
field = "Compress size"
self.compress_size, = unpack('<Q', data[:8])
data = data[8:]
if self.header_offset == 0xFFFF_FFFF:
field = "Header offset"
self.header_offset, = unpack('<Q', data[:8])
except struct.error:
raise BadZipFile(f"Corrupt zip64 extra field. "
f"{field} not found.") from None
extra = extra[ln+4:]
@classmethod
def from_file(cls, filename, arcname=None, *, strict_timestamps=True):
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
st = os.stat(filename)
isdir = stat.S_ISDIR(st.st_mode)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
if not strict_timestamps and date_time[0] < 1980:
date_time = (1980, 1, 1, 0, 0, 0)
elif not strict_timestamps and date_time[0] > 2107:
date_time = (2107, 12, 31, 23, 59, 59)
# Create ZipInfo instance to store file information
if arcname is None:
arcname = filename
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
if isdir:
arcname += '/'
zinfo = cls(arcname, date_time)
zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes
if isdir:
zinfo.file_size = 0
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.file_size = st.st_size
return zinfo
def is_dir(self):
return self.filename[-1] == '/'
# ZIP encryption uses the CRC32 one-byte primitive for scrambling some
# internal keys. We noticed that a direct implementation is faster than
# relying on binascii.crc32().
_crctable = None
def _gen_crc(crc):
for j in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0xEDB88320
else:
crc >>= 1
return crc
# ZIP supports a password-based form of encryption. Even though known
# plaintext attacks have been found against it, it is still useful
# to be able to get data out of such a file.
#
# Usage:
# zd = _ZipDecrypter(mypwd)
# plain_bytes = zd(cypher_bytes)
def _ZipDecrypter(pwd):
key0 = 305419896
key1 = 591751049
key2 = 878082192
global _crctable
if _crctable is None:
_crctable = list(map(_gen_crc, range(256)))
crctable = _crctable
def crc32(ch, crc):
return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF]
def update_keys(c):
nonlocal key0, key1, key2
key0 = crc32(c, key0)
key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF
key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF
key2 = crc32(key1 >> 24, key2)
for p in pwd:
update_keys(p)
def decrypter(data):
result = bytearray()
append = result.append
for c in data:
k = key2 | 2
c ^= ((k * (k^1)) >> 8) & 0xFF
update_keys(c)
append(c)
return bytes(result)
return decrypter
class LZMACompressor:
def __init__(self):
self._comp = None
def _init(self):
props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1})
self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1, props)
])
return struct.pack('<BBH', 9, 4, len(props)) + props
def compress(self, data):
if self._comp is None:
return self._init() + self._comp.compress(data)
return self._comp.compress(data)
def flush(self):
if self._comp is None:
return self._init() + self._comp.flush()
return self._comp.flush()
class LZMADecompressor:
def __init__(self):
self._decomp = None
self._unconsumed = b''
self.eof = False
def decompress(self, data):
if self._decomp is None:
self._unconsumed += data
if len(self._unconsumed) <= 4:
return b''
psize, = struct.unpack('<H', self._unconsumed[2:4])
if len(self._unconsumed) <= 4 + psize:
return b''
self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1,
self._unconsumed[4:4 + psize])
])
data = self._unconsumed[4 + psize:]
del self._unconsumed
result = self._decomp.decompress(data)
self.eof = self._decomp.eof
return result
compressor_names = {
0: 'store',
1: 'shrink',
2: 'reduce',
3: 'reduce',
4: 'reduce',
5: 'reduce',
6: 'implode',
7: 'tokenize',
8: 'deflate',
9: 'deflate64',
10: 'implode',
12: 'bzip2',
14: 'lzma',
18: 'terse',
19: 'lz77',
97: 'wavpack',
98: 'ppmd',
}
def _check_compression(compression):
if compression == ZIP_STORED:
pass
elif compression == ZIP_DEFLATED:
if not zlib:
raise RuntimeError(
"Compression requires the (missing) zlib module")
elif compression == ZIP_BZIP2:
if not bz2:
raise RuntimeError(
"Compression requires the (missing) bz2 module")
elif compression == ZIP_LZMA:
if not lzma:
raise RuntimeError(
"Compression requires the (missing) lzma module")
else:
raise NotImplementedError("That compression method is not supported")
def _get_compressor(compress_type, compresslevel=None):
if compress_type == ZIP_DEFLATED:
if compresslevel is not None:
return zlib.compressobj(compresslevel, zlib.DEFLATED, -15)
return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
elif compress_type == ZIP_BZIP2:
if compresslevel is not None:
return bz2.BZ2Compressor(compresslevel)
return bz2.BZ2Compressor()
# compresslevel is ignored for ZIP_LZMA
elif compress_type == ZIP_LZMA:
return LZMACompressor()
else:
return None
def _get_decompressor(compress_type):
_check_compression(compress_type)
if compress_type == ZIP_STORED:
return None
elif compress_type == ZIP_DEFLATED:
return zlib.decompressobj(-15)
elif compress_type == ZIP_BZIP2:
return bz2.BZ2Decompressor()
elif compress_type == ZIP_LZMA:
return LZMADecompressor()
else:
descr = compressor_names.get(compress_type)
if descr:
raise NotImplementedError("compression type %d (%s)" % (compress_type, descr))
else:
raise NotImplementedError("compression type %d" % (compress_type,))
class _SharedFile:
def __init__(self, file, pos, close, lock, writing):
self._file = file
self._pos = pos
self._close = close
self._lock = lock
self._writing = writing
self.seekable = file.seekable
self.tell = file.tell
def seek(self, offset, whence=0):
with self._lock:
if self._writing():
raise ValueError("Can't reposition in the ZIP file while "
"there is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(offset, whence)
self._pos = self._file.tell()
return self._pos
def read(self, n=-1):
with self._lock:
if self._writing():
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(self._pos)
data = self._file.read(n)
self._pos = self._file.tell()
return data
def close(self):
if self._file is not None:
fileobj = self._file
self._file = None
self._close(fileobj)
# Provide the tell method for unseekable stream
class _Tellable:
def __init__(self, fp):
self.fp = fp
self.offset = 0
def write(self, data):
n = self.fp.write(data)
self.offset += n
return n
def tell(self):
return self.offset
def flush(self):
self.fp.flush()
def close(self):
self.fp.close()
class ZipExtFile(io.BufferedIOBase):
# Max size supported by decompressor.
MAX_N = 1 << 31 - 1
# Read from compressed files in 4k blocks.
MIN_READ_SIZE = 4096
# Chunk size to read during seek
MAX_SEEK_READ = 1 << 24
def __init__(self, fileobj, mode, zipinfo, pwd=None,
close_fileobj=False):
self._fileobj = fileobj
self._pwd = pwd
self._close_fileobj = close_fileobj
self._compress_type = zipinfo.compress_type
self._compress_left = zipinfo.compress_size
self._left = zipinfo.file_size
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
self._readbuffer = b''
self._offset = 0
self.newlines = None
self.mode = mode
self.name = zipinfo.filename
if hasattr(zipinfo, 'CRC'):
self._expected_crc = zipinfo.CRC
self._running_crc = crc32(b'')
else:
self._expected_crc = None
self._seekable = False
try:
if fileobj.seekable():
self._orig_compress_start = fileobj.tell()
self._orig_compress_size = zipinfo.compress_size
self._orig_file_size = zipinfo.file_size
self._orig_start_crc = self._running_crc
self._seekable = True
except AttributeError:
pass
self._decrypter = None
if pwd:
if zipinfo.flag_bits & 0x8:
# compare against the file type from extended local headers
check_byte = (zipinfo._raw_time >> 8) & 0xff
else:
# compare against the CRC otherwise
check_byte = (zipinfo.CRC >> 24) & 0xff
h = self._init_decrypter()
if h != check_byte:
raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename)
def _init_decrypter(self):
self._decrypter = _ZipDecrypter(self._pwd)
# The first 12 bytes in the cypher stream is an encryption header
# used to strengthen the algorithm. The first 11 bytes are
# completely random, while the 12th contains the MSB of the CRC,
# or the MSB of the file time depending on the header type
# and is used to check the correctness of the password.
header = self._fileobj.read(12)
self._compress_left -= 12
return self._decrypter(header)[11]
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if not self.closed:
result.append(' name=%r mode=%r' % (self.name, self.mode))
if self._compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self._compress_type,
self._compress_type))
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def readline(self, limit=-1):
if limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find(b'\n', self._offset) + 1
if i > 0:
line = self._readbuffer[self._offset: i]
self._offset = i
return line
return io.BufferedIOBase.readline(self, limit)
def peek(self, n=1):
if n > len(self._readbuffer) - self._offset:
chunk = self.read(n)
if len(chunk) > self._offset:
self._readbuffer = chunk + self._readbuffer[self._offset:]
self._offset = 0
else:
self._offset -= len(chunk)
# Return up to 512 bytes to reduce allocation overhead for tight loops.
return self._readbuffer[self._offset: self._offset + 512]
def readable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return True
def read(self, n=-1):
if self.closed:
raise ValueError("read from closed file.")
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
buf += self._read1(self.MAX_N)
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while n > 0 and not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
buf += data
n -= len(data)
return buf
def _update_crc(self, newdata):
# Update the CRC using the given data.
if self._expected_crc is None:
# No need to compute the CRC if we don't have a reference value
return
self._running_crc = crc32(newdata, self._running_crc)
if self._eof and self._running_crc != self._expected_crc:
raise BadZipFile("Bad CRC-32 for file %r" % self.name)
def read1(self, n):
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
data = self._read1(self.MAX_N)
if data:
buf += data
break
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
if n > 0:
while not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
if data:
buf += data
break
return buf
def _read1(self, n):
# Read up to n compressed bytes with at most one read() system call,
# decrypt and decompress them.
if self._eof or n <= 0:
return b''
# Read from file.
if self._compress_type == ZIP_DEFLATED:
## Handle unconsumed data.
data = self._decompressor.unconsumed_tail
if n > len(data):
data += self._read2(n - len(data))
else:
data = self._read2(n)
if self._compress_type == ZIP_STORED:
self._eof = self._compress_left <= 0
elif self._compress_type == ZIP_DEFLATED:
n = max(n, self.MIN_READ_SIZE)
data = self._decompressor.decompress(data, n)
self._eof = (self._decompressor.eof or
self._compress_left <= 0 and
not self._decompressor.unconsumed_tail)
if self._eof:
data += self._decompressor.flush()
else:
data = self._decompressor.decompress(data)
self._eof = self._decompressor.eof or self._compress_left <= 0
data = data[:self._left]
self._left -= len(data)
if self._left <= 0:
self._eof = True
self._update_crc(data)
return data
def _read2(self, n):
if self._compress_left <= 0:
return b''
n = max(n, self.MIN_READ_SIZE)
n = min(n, self._compress_left)
data = self._fileobj.read(n)
self._compress_left -= len(data)
if not data:
raise EOFError
if self._decrypter is not None:
data = self._decrypter(data)
return data
def close(self):
try:
if self._close_fileobj:
self._fileobj.close()
finally:
super().close()
def seekable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return self._seekable
def seek(self, offset, whence=0):
if self.closed:
raise ValueError("seek on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
curr_pos = self.tell()
if whence == 0: # Seek from start of file
new_pos = offset
elif whence == 1: # Seek from current position
new_pos = curr_pos + offset
elif whence == 2: # Seek from EOF
new_pos = self._orig_file_size + offset
else:
raise ValueError("whence must be os.SEEK_SET (0), "
"os.SEEK_CUR (1), or os.SEEK_END (2)")
if new_pos > self._orig_file_size:
new_pos = self._orig_file_size
if new_pos < 0:
new_pos = 0
read_offset = new_pos - curr_pos
buff_offset = read_offset + self._offset
if buff_offset >= 0 and buff_offset < len(self._readbuffer):
# Just move the _offset index if the new position is in the _readbuffer
self._offset = buff_offset
read_offset = 0
elif read_offset < 0:
# Position is before the current position. Reset the ZipExtFile
self._fileobj.seek(self._orig_compress_start)
self._running_crc = self._orig_start_crc
self._compress_left = self._orig_compress_size
self._left = self._orig_file_size
self._readbuffer = b''
self._offset = 0
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
read_offset = new_pos
if self._decrypter is not None:
self._init_decrypter()
while read_offset > 0:
read_len = min(self.MAX_SEEK_READ, read_offset)
self.read(read_len)
read_offset -= read_len
return self.tell()
def tell(self):
if self.closed:
raise ValueError("tell on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset
return filepos
class _ZipWriteFile(io.BufferedIOBase):
def __init__(self, zf, zinfo, zip64):
self._zinfo = zinfo
self._zip64 = zip64
self._zipfile = zf
self._compressor = _get_compressor(zinfo.compress_type,
zinfo._compresslevel)
self._file_size = 0
self._compress_size = 0
self._crc = 0
@property
def _fileobj(self):
return self._zipfile.fp
def writable(self):
return True
def write(self, data):
if self.closed:
raise ValueError('I/O operation on closed file.')
# Accept any data that supports the buffer protocol
if isinstance(data, (bytes, bytearray)):
nbytes = len(data)
else:
data = memoryview(data)
nbytes = data.nbytes
self._file_size += nbytes
self._crc = crc32(data, self._crc)
if self._compressor:
data = self._compressor.compress(data)
self._compress_size += len(data)
self._fileobj.write(data)
return nbytes
def close(self):
if self.closed:
return
try:
super().close()
# Flush any data from the compressor, and update header info
if self._compressor:
buf = self._compressor.flush()
self._compress_size += len(buf)
self._fileobj.write(buf)
self._zinfo.compress_size = self._compress_size
else:
self._zinfo.compress_size = self._file_size
self._zinfo.CRC = self._crc
self._zinfo.file_size = self._file_size
# Write updated header info
if self._zinfo.flag_bits & 0x08:
# Write CRC and file sizes after the file data
fmt = '<LLQQ' if self._zip64 else '<LLLL'
self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC,
self._zinfo.compress_size, self._zinfo.file_size))
self._zipfile.start_dir = self._fileobj.tell()
else:
if not self._zip64:
if self._file_size > ZIP64_LIMIT:
raise RuntimeError(
'File size unexpectedly exceeded ZIP64 limit')
if self._compress_size > ZIP64_LIMIT:
raise RuntimeError(
'Compressed size unexpectedly exceeded ZIP64 limit')
# Seek backwards and write file header (which will now include
# correct CRC and file sizes)
# Preserve current position in file
self._zipfile.start_dir = self._fileobj.tell()
self._fileobj.seek(self._zinfo.header_offset)
self._fileobj.write(self._zinfo.FileHeader(self._zip64))
self._fileobj.seek(self._zipfile.start_dir)
# Successfully written: Add file to our caches
self._zipfile.filelist.append(self._zinfo)
self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo
finally:
self._zipfile._writing = False
class ZipFile:
fp = None # Set here since __del__ checks it
_windows_illegal_name_trans_table = None
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
compresslevel=None, *, strict_timestamps=True):
if mode not in ('r', 'w', 'x', 'a'):
raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'")
_check_compression(compression)
self._allowZip64 = allowZip64
self._didModify = False
self.debug = 0 # Level of printing: 0 through 3
self.NameToInfo = {} # Find file info given name
self.filelist = [] # List of ZipInfo instances for archive
self.compression = compression # Method of compression
self.compresslevel = compresslevel
self.mode = mode
self.pwd = None
self._comment = b''
self._strict_timestamps = strict_timestamps
# Check if we were passed a file-like object
if isinstance(file, os.PathLike):
file = os.fspath(file)
if isinstance(file, str):
# No, it's a filename
self._filePassed = 0
self.filename = file
modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b',
'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'}
filemode = modeDict[mode]
while True:
try:
self.fp = io.open(file, filemode)
except OSError:
if filemode in modeDict:
filemode = modeDict[filemode]
continue
raise
break
else:
self._filePassed = 1
self.fp = file
self.filename = getattr(file, 'name', None)
self._fileRefCnt = 1
self._lock = threading.RLock()
self._seekable = True
self._writing = False
try:
if mode == 'r':
self._RealGetContents()
elif mode in ('w', 'x'):
self._didModify = True
try:
self.start_dir = self.fp.tell()
except (AttributeError, OSError):
self.fp = _Tellable(self.fp)
self.start_dir = 0
self._seekable = False
else:
try:
self.fp.seek(self.start_dir)
except (AttributeError, OSError):
self._seekable = False
elif mode == 'a':
try:
self._RealGetContents()
self.fp.seek(self.start_dir)
except BadZipFile:
self.fp.seek(0, 2)
self._didModify = True
self.start_dir = self.fp.tell()
else:
raise ValueError("Mode must be 'r', 'w', 'x', or 'a'")
except:
fp = self.fp
self.fp = None
self._fpclose(fp)
raise
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if self.fp is not None:
if self._filePassed:
result.append(' file=%r' % self.fp)
elif self.filename is not None:
result.append(' filename=%r' % self.filename)
result.append(' mode=%r' % self.mode)
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def _RealGetContents(self):
fp = self.fp
try:
endrec = _EndRecData(fp)
except OSError:
raise BadZipFile("File is not a zip file")
if not endrec:
raise BadZipFile("File is not a zip file")
if self.debug > 1:
print(endrec)
size_cd = endrec[_ECD_SIZE]
offset_cd = endrec[_ECD_OFFSET]
self._comment = endrec[_ECD_COMMENT]
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
if endrec[_ECD_SIGNATURE] == stringEndArchive64:
concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
if self.debug > 2:
inferred = concat + offset_cd
print("given, inferred, offset", offset_cd, inferred, concat)
self.start_dir = offset_cd + concat
fp.seek(self.start_dir, 0)
data = fp.read(size_cd)
fp = io.BytesIO(data)
total = 0
while total < size_cd:
centdir = fp.read(sizeCentralDir)
if len(centdir) != sizeCentralDir:
raise BadZipFile("Truncated central directory")
centdir = struct.unpack(structCentralDir, centdir)
if centdir[_CD_SIGNATURE] != stringCentralDir:
raise BadZipFile("Bad magic number for central directory")
if self.debug > 2:
print(centdir)
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
flags = centdir[5]
if flags & 0x800:
filename = filename.decode('utf-8')
else:
filename = filename.decode('cp437')
x = ZipInfo(filename)
x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
(x.create_version, x.create_system, x.extract_version, x.reserved,
x.flag_bits, x.compress_type, t, d,
x.CRC, x.compress_size, x.file_size) = centdir[1:12]
if x.extract_version > MAX_EXTRACT_VERSION:
raise NotImplementedError("zip file version %.1f" %
(x.extract_version / 10))
x.volume, x.internal_attr, x.external_attr = centdir[15:18]
x._raw_time = t
x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
x._decodeExtra()
x.header_offset = x.header_offset + concat
self.filelist.append(x)
self.NameToInfo[x.filename] = x
total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
+ centdir[_CD_EXTRA_FIELD_LENGTH]
+ centdir[_CD_COMMENT_LENGTH])
if self.debug > 2:
print("total", total)
def namelist(self):
return [data.filename for data in self.filelist]
def infolist(self):
return self.filelist
def printdir(self, file=None):
print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"),
file=file)
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
file=file)
def testzip(self):
chunk_size = 2 ** 20
for zinfo in self.filelist:
try:
with self.open(zinfo.filename, "r") as f:
while f.read(chunk_size):
pass
except BadZipFile:
return zinfo.filename
def getinfo(self, name):
info = self.NameToInfo.get(name)
if info is None:
raise KeyError(
'There is no item named %r in the archive' % name)
return info
def setpassword(self, pwd):
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd:
self.pwd = pwd
else:
self.pwd = None
@property
def comment(self):
return self._comment
@comment.setter
def comment(self, comment):
if not isinstance(comment, bytes):
raise TypeError("comment: expected bytes, got %s" % type(comment).__name__)
if len(comment) > ZIP_MAX_COMMENT:
import warnings
warnings.warn('Archive comment is too long; truncating to %d bytes'
% ZIP_MAX_COMMENT, stacklevel=2)
comment = comment[:ZIP_MAX_COMMENT]
self._comment = comment
self._didModify = True
def read(self, name, pwd=None):
with self.open(name, "r", pwd) as fp:
return fp.read()
def open(self, name, mode="r", pwd=None, *, force_zip64=False):
if mode not in {"r", "w"}:
raise ValueError('open() requires mode "r" or "w"')
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd and (mode == "w"):
raise ValueError("pwd is only supported for reading files")
if not self.fp:
raise ValueError(
"Attempt to use ZIP archive that was already closed")
if isinstance(name, ZipInfo):
zinfo = name
elif mode == 'w':
zinfo = ZipInfo(name)
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
else:
zinfo = self.getinfo(name)
if mode == 'w':
return self._open_to_write(zinfo, force_zip64=force_zip64)
if self._writing:
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
# Open for reading:
self._fileRefCnt += 1
zef_file = _SharedFile(self.fp, zinfo.header_offset,
self._fpclose, self._lock, lambda: self._writing)
try:
# Skip the file header:
fheader = zef_file.read(sizeFileHeader)
if len(fheader) != sizeFileHeader:
raise BadZipFile("Truncated file header")
fheader = struct.unpack(structFileHeader, fheader)
if fheader[_FH_SIGNATURE] != stringFileHeader:
raise BadZipFile("Bad magic number for file header")
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
if fheader[_FH_EXTRA_FIELD_LENGTH]:
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
if zinfo.flag_bits & 0x20:
# Zip 2.7: compressed patched data
raise NotImplementedError("compressed patched data (flag bit 5)")
if zinfo.flag_bits & 0x40:
# strong encryption
raise NotImplementedError("strong encryption (flag bit 6)")
if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
fname_str = fname.decode("cp437")
if fname_str != zinfo.orig_filename:
raise BadZipFile(
'File name in directory %r and header %r differ.'
% (zinfo.orig_filename, fname))
# check for encrypted flag & handle password
is_encrypted = zinfo.flag_bits & 0x1
if is_encrypted:
if not pwd:
pwd = self.pwd
if not pwd:
raise RuntimeError("File %r is encrypted, password "
"required for extraction" % name)
else:
pwd = None
return ZipExtFile(zef_file, mode, zinfo, pwd, True)
except:
zef_file.close()
raise
def _open_to_write(self, zinfo, force_zip64=False):
if force_zip64 and not self._allowZip64:
raise ValueError(
"force_zip64 is True, but allowZip64 was False when opening "
"the ZIP file."
)
if self._writing:
raise ValueError("Can't write to the ZIP file while there is "
"another write handle open on it. "
"Close the first handle before opening another.")
zinfo.compress_size = 0
zinfo.CRC = 0
zinfo.flag_bits = 0x00
if zinfo.compress_type == ZIP_LZMA:
zinfo.flag_bits |= 0x02
if not self._seekable:
zinfo.flag_bits |= 0x08
if not zinfo.external_attr:
zinfo.external_attr = 0o600 << 16
zip64 = self._allowZip64 and \
(force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT)
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
self.fp.write(zinfo.FileHeader(zip64))
self._writing = True
return _ZipWriteFile(self, zinfo, zip64)
def extract(self, member, path=None, pwd=None):
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
return self._extract_member(member, path, pwd)
def extractall(self, path=None, members=None, pwd=None):
if members is None:
members = self.namelist()
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
for zipinfo in members:
self._extract_member(zipinfo, path, pwd)
@classmethod
def _sanitize_windows_name(cls, arcname, pathsep):
table = cls._windows_illegal_name_trans_table
if not table:
illegal = ':<>|"?*'
table = str.maketrans(illegal, '_' * len(illegal))
cls._windows_illegal_name_trans_table = table
arcname = arcname.translate(table)
# remove trailing dots
arcname = (x.rstrip('.') for x in arcname.split(pathsep))
# rejoin, removing empty parts.
arcname = pathsep.join(x for x in arcname if x)
return arcname
def _extract_member(self, member, targetpath, pwd):
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
# build the destination pathname, replacing
# forward slashes to platform specific separators.
arcname = member.filename.replace('/', os.path.sep)
if os.path.altsep:
arcname = arcname.replace(os.path.altsep, os.path.sep)
# interpret absolute pathname as relative, remove drive letter or
# UNC path, redundant separators, "." and ".." components.
arcname = os.path.splitdrive(arcname)[1]
invalid_path_parts = ('', os.path.curdir, os.path.pardir)
arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
if x not in invalid_path_parts)
if os.path.sep == '\\':
# filter illegal characters on Windows
arcname = self._sanitize_windows_name(arcname, os.path.sep)
targetpath = os.path.join(targetpath, arcname)
targetpath = os.path.normpath(targetpath)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.is_dir():
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
open(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath
def _writecheck(self, zinfo):
if zinfo.filename in self.NameToInfo:
import warnings
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
if self.mode not in ('w', 'x', 'a'):
raise ValueError("write() requires mode 'w', 'x', or 'a'")
if not self.fp:
raise ValueError(
"Attempt to write ZIP archive that was already closed")
_check_compression(zinfo.compress_type)
if not self._allowZip64:
requires_zip64 = None
if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif zinfo.file_size > ZIP64_LIMIT:
requires_zip64 = "Filesize"
elif zinfo.header_offset > ZIP64_LIMIT:
requires_zip64 = "Zipfile size"
if requires_zip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
def write(self, filename, arcname=None,
compress_type=None, compresslevel=None):
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists"
)
zinfo = ZipInfo.from_file(filename, arcname,
strict_timestamps=self._strict_timestamps)
if zinfo.is_dir():
zinfo.compress_size = 0
zinfo.CRC = 0
else:
if compress_type is not None:
zinfo.compress_type = compress_type
else:
zinfo.compress_type = self.compression
if compresslevel is not None:
zinfo._compresslevel = compresslevel
else:
zinfo._compresslevel = self.compresslevel
if zinfo.is_dir():
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell() # Start of header bytes
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
self._writecheck(zinfo)
self._didModify = True
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
self.fp.write(zinfo.FileHeader(False))
self.start_dir = self.fp.tell()
else:
with open(filename, "rb") as src, self.open(zinfo, 'w') as dest:
shutil.copyfileobj(src, dest, 1024*8)
def writestr(self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None):
if isinstance(data, str):
data = data.encode("utf-8")
if not isinstance(zinfo_or_arcname, ZipInfo):
zinfo = ZipInfo(filename=zinfo_or_arcname,
date_time=time.localtime(time.time())[:6])
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
if zinfo.filename[-1] == '/':
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.external_attr = 0o600 << 16 # ?rw-------
else:
zinfo = zinfo_or_arcname
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists."
)
if compress_type is not None:
zinfo.compress_type = compress_type
if compresslevel is not None:
zinfo._compresslevel = compresslevel
zinfo.file_size = len(data) # Uncompressed size
with self._lock:
with self.open(zinfo, mode='w') as dest:
dest.write(data)
def __del__(self):
self.close()
def close(self):
if self.fp is None:
return
if self._writing:
raise ValueError("Can't close the ZIP file while there is "
"an open writing handle on it. "
"Close the writing handle before closing the zip.")
try:
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
self._write_end_record()
finally:
fp = self.fp
self.fp = None
self._fpclose(fp)
def _write_end_record(self):
for zinfo in self.filelist: # write central directory
dt = zinfo.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
extra = []
if zinfo.file_size > ZIP64_LIMIT \
or zinfo.compress_size > ZIP64_LIMIT:
extra.append(zinfo.file_size)
extra.append(zinfo.compress_size)
file_size = 0xffffffff
compress_size = 0xffffffff
else:
file_size = zinfo.file_size
compress_size = zinfo.compress_size
if zinfo.header_offset > ZIP64_LIMIT:
extra.append(zinfo.header_offset)
header_offset = 0xffffffff
else:
header_offset = zinfo.header_offset
extra_data = zinfo.extra
min_version = 0
if extra:
# Append a ZIP64 field to the extra's
extra_data = _strip_extra(extra_data, (1,))
extra_data = struct.pack(
'<HH' + 'Q'*len(extra),
1, 8*len(extra), *extra) + extra_data
min_version = ZIP64_VERSION
if zinfo.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif zinfo.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
extract_version = max(min_version, zinfo.extract_version)
create_version = max(min_version, zinfo.create_version)
filename, flag_bits = zinfo._encodeFilenameFlags()
centdir = struct.pack(structCentralDir,
stringCentralDir, create_version,
zinfo.create_system, extract_version, zinfo.reserved,
flag_bits, zinfo.compress_type, dostime, dosdate,
zinfo.CRC, compress_size, file_size,
len(filename), len(extra_data), len(zinfo.comment),
0, zinfo.internal_attr, zinfo.external_attr,
header_offset)
self.fp.write(centdir)
self.fp.write(filename)
self.fp.write(extra_data)
self.fp.write(zinfo.comment)
pos2 = self.fp.tell()
# Write end-of-zip-archive record
centDirCount = len(self.filelist)
centDirSize = pos2 - self.start_dir
centDirOffset = self.start_dir
requires_zip64 = None
if centDirCount > ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif centDirOffset > ZIP64_LIMIT:
requires_zip64 = "Central directory offset"
elif centDirSize > ZIP64_LIMIT:
requires_zip64 = "Central directory size"
if requires_zip64:
# Need to write the ZIP64 end-of-archive records
if not self._allowZip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
zip64endrec = struct.pack(
structEndArchive64, stringEndArchive64,
44, 45, 45, 0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset)
self.fp.write(zip64endrec)
zip64locrec = struct.pack(
structEndArchive64Locator,
stringEndArchive64Locator, 0, pos2, 1)
self.fp.write(zip64locrec)
centDirCount = min(centDirCount, 0xFFFF)
centDirSize = min(centDirSize, 0xFFFFFFFF)
centDirOffset = min(centDirOffset, 0xFFFFFFFF)
endrec = struct.pack(structEndArchive, stringEndArchive,
0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset, len(self._comment))
self.fp.write(endrec)
self.fp.write(self._comment)
if self.mode == "a":
self.fp.truncate()
self.fp.flush()
def _fpclose(self, fp):
assert self._fileRefCnt > 0
self._fileRefCnt -= 1
if not self._fileRefCnt and not self._filePassed:
fp.close()
class PyZipFile(ZipFile):
def __init__(self, file, mode="r", compression=ZIP_STORED,
allowZip64=True, optimize=-1):
ZipFile.__init__(self, file, mode=mode, compression=compression,
allowZip64=allowZip64)
self._optimize = optimize
def writepy(self, pathname, basename="", filterfunc=None):
pathname = os.fspath(pathname)
if filterfunc and not filterfunc(pathname):
if self.debug:
label = 'path' if os.path.isdir(pathname) else 'file'
print('%s %r skipped by filterfunc' % (label, pathname))
return
dir, name = os.path.split(pathname)
if os.path.isdir(pathname):
initname = os.path.join(pathname, "__init__.py")
if os.path.isfile(initname):
# This is a package directory, add it
if basename:
basename = "%s/%s" % (basename, name)
else:
basename = name
if self.debug:
print("Adding package in", pathname, "as", basename)
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
dirlist = sorted(os.listdir(pathname))
dirlist.remove("__init__.py")
# Add all *.py files and package subdirectories
for filename in dirlist:
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, "__init__.py")):
# This is a package directory, add it
self.writepy(path, basename,
filterfunc=filterfunc) # Recursive call
elif ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
print("Adding files from directory", pathname)
for filename in sorted(os.listdir(pathname)):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError(
'Files added with writepy() must end with ".py"')
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print("Adding file", arcname)
self.write(fname, arcname)
def _get_codename(self, pathname, basename):
def _compile(file, optimize=-1):
import py_compile
if self.debug:
print("Compiling", file)
try:
py_compile.compile(file, doraise=True, optimize=optimize)
except py_compile.PyCompileError as err:
print(err.msg)
return False
return True
file_py = pathname + ".py"
file_pyc = pathname + ".pyc"
pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='')
pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1)
pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2)
if self._optimize == -1:
# legacy mode: use whatever file is present
if (os.path.isfile(file_pyc) and
os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
# Use .pyc file.
arcname = fname = file_pyc
elif (os.path.isfile(pycache_opt0) and
os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt0
arcname = file_pyc
elif (os.path.isfile(pycache_opt1) and
os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt1
arcname = file_pyc
elif (os.path.isfile(pycache_opt2) and
os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt2
arcname = file_pyc
else:
# Compile py into PEP 3147 pyc file.
if _compile(file_py):
if sys.flags.optimize == 0:
fname = pycache_opt0
elif sys.flags.optimize == 1:
fname = pycache_opt1
else:
fname = pycache_opt2
arcname = file_pyc
else:
fname = arcname = file_py
else:
# new mode: use given optimization level
if self._optimize == 0:
fname = pycache_opt0
arcname = file_pyc
else:
arcname = file_pyc
if self._optimize == 1:
fname = pycache_opt1
elif self._optimize == 2:
fname = pycache_opt2
else:
msg = "invalid value for 'optimize': {!r}".format(self._optimize)
raise ValueError(msg)
if not (os.path.isfile(fname) and
os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
if not _compile(file_py, optimize=self._optimize):
fname = arcname = file_py
archivename = os.path.split(arcname)[1]
if basename:
archivename = "%s/%s" % (basename, archivename)
return (fname, archivename)
def _parents(path):
return itertools.islice(_ancestry(path), 1, None)
def _ancestry(path):
path = path.rstrip(posixpath.sep)
while path and path != posixpath.sep:
yield path
path, tail = posixpath.split(path)
_dedupe = dict.fromkeys
def _difference(minuend, subtrahend):
return itertools.filterfalse(set(subtrahend).__contains__, minuend)
class CompleteDirs(ZipFile):
@staticmethod
def _implied_dirs(names):
parents = itertools.chain.from_iterable(map(_parents, names))
as_dirs = (p + posixpath.sep for p in parents)
return _dedupe(_difference(as_dirs, names))
def namelist(self):
names = super(CompleteDirs, self).namelist()
return names + list(self._implied_dirs(names))
def _name_set(self):
return set(self.namelist())
def resolve_dir(self, name):
names = self._name_set()
dirname = name + '/'
dir_match = name not in names and dirname in names
return dirname if dir_match else name
@classmethod
def make(cls, source):
if isinstance(source, CompleteDirs):
return source
if not isinstance(source, ZipFile):
return cls(source)
# Only allow for FastPath when supplied zipfile is read-only
if 'r' not in source.mode:
cls = CompleteDirs
res = cls.__new__(cls)
vars(res).update(vars(source))
return res
class FastLookup(CompleteDirs):
def namelist(self):
with contextlib.suppress(AttributeError):
return self.__names
self.__names = super(FastLookup, self).namelist()
return self.__names
def _name_set(self):
with contextlib.suppress(AttributeError):
return self.__lookup
self.__lookup = super(FastLookup, self)._name_set()
return self.__lookup
class Path:
__repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
def __init__(self, root, at=""):
self.root = FastLookup.make(root)
self.at = at
def open(self, mode='r', *args, **kwargs):
pwd = kwargs.pop('pwd', None)
zip_mode = mode[0]
stream = self.root.open(self.at, zip_mode, pwd=pwd)
if 'b' in mode:
if args or kwargs:
raise ValueError("encoding args invalid for binary operation")
return stream
return io.TextIOWrapper(stream, *args, **kwargs)
@property
def name(self):
return posixpath.basename(self.at.rstrip("/"))
def read_text(self, *args, **kwargs):
with self.open('r', *args, **kwargs) as strm:
return strm.read()
def read_bytes(self):
with self.open('rb') as strm:
return strm.read()
def _is_child(self, path):
return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
def _next(self, at):
return Path(self.root, at)
def is_dir(self):
return not self.at or self.at.endswith("/")
def is_file(self):
return not self.is_dir()
def exists(self):
return self.at in self.root._name_set()
def iterdir(self):
if not self.is_dir():
raise ValueError("Can't listdir a file")
subs = map(self._next, self.root.namelist())
return filter(self._is_child, subs)
def __str__(self):
return posixpath.join(self.root.filename, self.at)
def __repr__(self):
return self.__repr.format(self=self)
def joinpath(self, add):
next = posixpath.join(self.at, add)
return self._next(self.root.resolve_dir(next))
__truediv__ = joinpath
@property
def parent(self):
parent_at = posixpath.dirname(self.at.rstrip('/'))
if parent_at:
parent_at += '/'
return self._next(parent_at)
def main(args=None):
import argparse
description = 'A simple command-line interface for zipfile module.'
parser = argparse.ArgumentParser(description=description)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', metavar='<zipfile>',
help='Show listing of a zipfile')
group.add_argument('-e', '--extract', nargs=2,
metavar=('<zipfile>', '<output_dir>'),
help='Extract zipfile into target dir')
group.add_argument('-c', '--create', nargs='+',
metavar=('<name>', '<file>'),
help='Create zipfile from sources')
group.add_argument('-t', '--test', metavar='<zipfile>',
help='Test if a zipfile is valid')
args = parser.parse_args(args)
if args.test is not None:
src = args.test
with ZipFile(src, 'r') as zf:
badfile = zf.testzip()
if badfile:
print("The following enclosed file is corrupted: {!r}".format(badfile))
print("Done testing")
elif args.list is not None:
src = args.list
with ZipFile(src, 'r') as zf:
zf.printdir()
elif args.extract is not None:
src, curdir = args.extract
with ZipFile(src, 'r') as zf:
zf.extractall(curdir)
elif args.create is not None:
zip_name = args.create.pop(0)
files = args.create
def addToZip(zf, path, zippath):
if os.path.isfile(path):
zf.write(path, zippath, ZIP_DEFLATED)
elif os.path.isdir(path):
if zippath:
zf.write(path, zippath)
for nm in sorted(os.listdir(path)):
addToZip(zf,
os.path.join(path, nm), os.path.join(zippath, nm))
# else: ignore
with ZipFile(zip_name, 'w') as zf:
for path in files:
zippath = os.path.basename(path)
if not zippath:
zippath = os.path.basename(os.path.dirname(path))
if zippath in ('', os.curdir, os.pardir):
zippath = ''
addToZip(zf, path, zippath)
if __name__ == "__main__":
main()
| true | true |
f72c6a5b0a88709c33bc15b7b8f421bdb28239fe | 806 | py | Python | Scripts/bulk_image_download.py | POSCON-United-Kingdom/UK-Radar-Data | 6a020b03fbfeffe9f7eb53e4b4559de48134e351 | [
"Apache-2.0"
] | 2 | 2022-01-15T14:01:36.000Z | 2022-01-15T22:54:40.000Z | Scripts/bulk_image_download.py | POSCON-United-Kingdom/UK-Radar-Data | 6a020b03fbfeffe9f7eb53e4b4559de48134e351 | [
"Apache-2.0"
] | null | null | null | Scripts/bulk_image_download.py | POSCON-United-Kingdom/UK-Radar-Data | 6a020b03fbfeffe9f7eb53e4b4559de48134e351 | [
"Apache-2.0"
] | null | null | null | import re
import requests
import urllib.request
import urllib3
from bs4 import BeautifulSoup
print('Beginning file download with urllib2...')
url = "https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/html/eSUP/EG-eSUP-2020-017-en-GB.html"
"""Parse the given table into a beautifulsoup object"""
count = 0
http = urllib3.PoolManager()
error = http.request("GET", url)
if (error.status == 404):
print("File not found")
page = requests.get(url)
soup = BeautifulSoup(page.content, "lxml")
searchData = soup.find_all("img")
for img in searchData:
file = re.search(r"(ID_[\d]{7}\.gif)", str(img))
if file:
url = f'https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/graphics/{file.group(1)}'
urllib.request.urlretrieve(url, f'{count}.gif')
count += 1 | 29.851852 | 107 | 0.69727 | import re
import requests
import urllib.request
import urllib3
from bs4 import BeautifulSoup
print('Beginning file download with urllib2...')
url = "https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/html/eSUP/EG-eSUP-2020-017-en-GB.html"
count = 0
http = urllib3.PoolManager()
error = http.request("GET", url)
if (error.status == 404):
print("File not found")
page = requests.get(url)
soup = BeautifulSoup(page.content, "lxml")
searchData = soup.find_all("img")
for img in searchData:
file = re.search(r"(ID_[\d]{7}\.gif)", str(img))
if file:
url = f'https://www.aurora.nats.co.uk/htmlAIP/Publications/2020-04-09/graphics/{file.group(1)}'
urllib.request.urlretrieve(url, f'{count}.gif')
count += 1 | true | true |
f72c6be17e996073ee98833c5d3263506ac82ca5 | 987 | py | Python | test/unit/sorting/test_wordle_solver.py | bestpersonyes2/algorithms | 4225b3ebcdcbd29c80abe0b086d986875526dfcc | [
"MIT"
] | null | null | null | test/unit/sorting/test_wordle_solver.py | bestpersonyes2/algorithms | 4225b3ebcdcbd29c80abe0b086d986875526dfcc | [
"MIT"
] | null | null | null | test/unit/sorting/test_wordle_solver.py | bestpersonyes2/algorithms | 4225b3ebcdcbd29c80abe0b086d986875526dfcc | [
"MIT"
] | null | null | null | import os
from algorithms.sorting.wordle_solver import _read_file, get_best_guess, get_most_common
def test_get_most_common():
file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
most_common_start, most_common_letters, possible_words = get_most_common(file_data)
assert type(most_common_start) == list
assert type(most_common_letters) == list
assert type(possible_words) == list
def test_get_best_guess():
file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
best_guess = get_best_guess(file_data)
assert type(best_guess) == list
def test_read_file():
answer_file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
non_answer_file_data = _read_file(
os.path.join('algorithms', 'assets', 'wordle_non_answer_possible_words_list.json')
)
assert len(answer_file_data) == 2309
assert len(non_answer_file_data) == 10638
| 32.9 | 98 | 0.749747 | import os
from algorithms.sorting.wordle_solver import _read_file, get_best_guess, get_most_common
def test_get_most_common():
file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
most_common_start, most_common_letters, possible_words = get_most_common(file_data)
assert type(most_common_start) == list
assert type(most_common_letters) == list
assert type(possible_words) == list
def test_get_best_guess():
file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
best_guess = get_best_guess(file_data)
assert type(best_guess) == list
def test_read_file():
answer_file_data = _read_file(os.path.join('algorithms', 'assets', 'wordle_answer_list.json'))
non_answer_file_data = _read_file(
os.path.join('algorithms', 'assets', 'wordle_non_answer_possible_words_list.json')
)
assert len(answer_file_data) == 2309
assert len(non_answer_file_data) == 10638
| true | true |
f72c6c14815e59ace61d84641f721f81f31b67ac | 8,156 | py | Python | sentence_transformers/datasets/SentenceLabelDataset.py | dd-dos/sentence-transformers | 8f9c36b788e15141f723d80fea67ed16785cd18e | [
"Apache-2.0"
] | 31 | 2021-04-06T16:20:30.000Z | 2022-02-16T08:29:24.000Z | sentence_transformers/datasets/SentenceLabelDataset.py | dd-dos/sentence-transformers | 8f9c36b788e15141f723d80fea67ed16785cd18e | [
"Apache-2.0"
] | 5 | 2021-07-02T04:37:04.000Z | 2021-07-21T00:02:58.000Z | sentence_transformers/datasets/SentenceLabelDataset.py | dd-dos/sentence-transformers | 8f9c36b788e15141f723d80fea67ed16785cd18e | [
"Apache-2.0"
] | 5 | 2021-04-07T08:35:06.000Z | 2022-03-08T08:33:05.000Z | from torch.utils.data import Dataset
from typing import List
import bisect
import torch
import logging
import numpy as np
from tqdm import tqdm
from .. import SentenceTransformer
from ..readers.InputExample import InputExample
from multiprocessing import Pool, cpu_count
import multiprocessing
class SentenceLabelDataset(Dataset):
"""
Dataset for training with triplet loss.
This dataset takes a list of sentences grouped by their label and uses this grouping to dynamically select a
positive example from the same group and a negative example from the other sentences for a selected anchor sentence.
This dataset should be used in combination with dataset_reader.LabelSentenceReader
One iteration over this dataset selects every sentence as anchor once.
This also uses smart batching like SentenceDataset.
"""
def __init__(self, examples: List[InputExample], model: SentenceTransformer, provide_positive: bool = True,
provide_negative: bool = True,
parallel_tokenization: bool = True,
max_processes: int = 4,
chunk_size: int = 5000):
"""
Converts input examples to a SentenceLabelDataset usable to train the model with
SentenceTransformer.smart_batching_collate as the collate_fn for the DataLoader
Assumes only one sentence per InputExample and labels as integers from 0 to max_num_labels
and should be used in combination with dataset_reader.LabelSentenceReader.
Labels with only one example are ignored.
smart_batching_collate as collate_fn is required because it transforms the tokenized texts to the tensors.
:param examples:
the input examples for the training
:param model
the Sentence BERT model for the conversion
:param provide_positive:
set this to False, if you don't need a positive example (e.g. for BATCH_HARD_TRIPLET_LOSS).
:param provide_negative:
set this to False, if you don't need a negative example (e.g. for BATCH_HARD_TRIPLET_LOSS
or MULTIPLE_NEGATIVES_RANKING_LOSS).
:param parallel_tokenization
If true, multiple processes will be started for the tokenization
:param max_processes
Maximum number of processes started for tokenization. Cannot be larger can cpu_count()
:param chunk_size
#chunk_size number of examples are send to each process. Larger values increase overall tokenization speed
"""
self.model = model
self.groups_right_border = []
self.grouped_inputs = []
self.grouped_labels = []
self.num_labels = 0
self.max_processes = min(max_processes, cpu_count())
self.chunk_size = chunk_size
self.parallel_tokenization = parallel_tokenization
if self.parallel_tokenization:
if multiprocessing.get_start_method() != 'fork':
logging.info("Parallel tokenization is only available on Unix systems which allow to fork processes. Fall back to sequential tokenization")
self.parallel_tokenization = False
self.convert_input_examples(examples, model)
self.idxs = np.arange(len(self.grouped_inputs))
self.provide_positive = provide_positive
self.provide_negative = provide_negative
def convert_input_examples(self, examples: List[InputExample], model: SentenceTransformer):
"""
Converts input examples to a SentenceLabelDataset.
Assumes only one sentence per InputExample and labels as integers from 0 to max_num_labels
and should be used in combination with dataset_reader.LabelSentenceReader.
Labels with only one example are ignored.
:param examples:
the input examples for the training
:param model
the Sentence Transformer model for the conversion
:param is_pretokenized
If set to true, no tokenization will be applied. It is expected that the input is tokenized via model.tokenize
"""
inputs = []
labels = []
label_sent_mapping = {}
too_long = 0
label_type = None
logging.info("Start tokenization")
if not self.parallel_tokenization or self.max_processes == 1 or len(examples) <= self.chunk_size:
tokenized_texts = [self.tokenize_example(example) for example in examples]
else:
logging.info("Use multi-process tokenization with {} processes".format(self.max_processes))
self.model.to('cpu')
with Pool(self.max_processes) as p:
tokenized_texts = list(p.imap(self.tokenize_example, examples, chunksize=self.chunk_size))
# Group examples and labels
# Add examples with the same label to the same dict
for ex_index, example in enumerate(tqdm(examples, desc="Convert dataset")):
if label_type is None:
if isinstance(example.label, int):
label_type = torch.long
elif isinstance(example.label, float):
label_type = torch.float
tokenized_text = tokenized_texts[ex_index][0]
if hasattr(model, 'max_seq_length') and model.max_seq_length is not None and model.max_seq_length > 0 and len(tokenized_text) > model.max_seq_length:
too_long += 1
if example.label in label_sent_mapping:
label_sent_mapping[example.label].append(ex_index)
else:
label_sent_mapping[example.label] = [ex_index]
inputs.append(tokenized_text)
labels.append(example.label)
# Group sentences, such that sentences with the same label
# are besides each other. Only take labels with at least 2 examples
distinct_labels = list(label_sent_mapping.keys())
for i in range(len(distinct_labels)):
label = distinct_labels[i]
if len(label_sent_mapping[label]) >= 2:
self.grouped_inputs.extend([inputs[j] for j in label_sent_mapping[label]])
self.grouped_labels.extend([labels[j] for j in label_sent_mapping[label]])
self.groups_right_border.append(len(self.grouped_inputs)) #At which position does this label group / bucket end?
self.num_labels += 1
self.grouped_labels = torch.tensor(self.grouped_labels, dtype=label_type)
logging.info("Num sentences: %d" % (len(self.grouped_inputs)))
logging.info("Sentences longer than max_seqence_length: {}".format(too_long))
logging.info("Number of labels with >1 examples: {}".format(len(distinct_labels)))
def tokenize_example(self, example):
if example.texts_tokenized is not None:
return example.texts_tokenized
return [self.model.tokenize(text) for text in example.texts]
def __getitem__(self, item):
if not self.provide_positive and not self.provide_negative:
return [self.grouped_inputs[item]], self.grouped_labels[item]
# Anchor element
anchor = self.grouped_inputs[item]
# Check start and end position for this label in our list of grouped sentences
group_idx = bisect.bisect_right(self.groups_right_border, item)
left_border = 0 if group_idx == 0 else self.groups_right_border[group_idx - 1]
right_border = self.groups_right_border[group_idx]
if self.provide_positive:
positive_item_idx = np.random.choice(np.concatenate([self.idxs[left_border:item], self.idxs[item + 1:right_border]]))
positive = self.grouped_inputs[positive_item_idx]
else:
positive = []
if self.provide_negative:
negative_item_idx = np.random.choice(np.concatenate([self.idxs[0:left_border], self.idxs[right_border:]]))
negative = self.grouped_inputs[negative_item_idx]
else:
negative = []
return [anchor, positive, negative], self.grouped_labels[item]
def __len__(self):
return len(self.grouped_inputs) | 44.086486 | 161 | 0.676067 | from torch.utils.data import Dataset
from typing import List
import bisect
import torch
import logging
import numpy as np
from tqdm import tqdm
from .. import SentenceTransformer
from ..readers.InputExample import InputExample
from multiprocessing import Pool, cpu_count
import multiprocessing
class SentenceLabelDataset(Dataset):
def __init__(self, examples: List[InputExample], model: SentenceTransformer, provide_positive: bool = True,
provide_negative: bool = True,
parallel_tokenization: bool = True,
max_processes: int = 4,
chunk_size: int = 5000):
self.model = model
self.groups_right_border = []
self.grouped_inputs = []
self.grouped_labels = []
self.num_labels = 0
self.max_processes = min(max_processes, cpu_count())
self.chunk_size = chunk_size
self.parallel_tokenization = parallel_tokenization
if self.parallel_tokenization:
if multiprocessing.get_start_method() != 'fork':
logging.info("Parallel tokenization is only available on Unix systems which allow to fork processes. Fall back to sequential tokenization")
self.parallel_tokenization = False
self.convert_input_examples(examples, model)
self.idxs = np.arange(len(self.grouped_inputs))
self.provide_positive = provide_positive
self.provide_negative = provide_negative
def convert_input_examples(self, examples: List[InputExample], model: SentenceTransformer):
inputs = []
labels = []
label_sent_mapping = {}
too_long = 0
label_type = None
logging.info("Start tokenization")
if not self.parallel_tokenization or self.max_processes == 1 or len(examples) <= self.chunk_size:
tokenized_texts = [self.tokenize_example(example) for example in examples]
else:
logging.info("Use multi-process tokenization with {} processes".format(self.max_processes))
self.model.to('cpu')
with Pool(self.max_processes) as p:
tokenized_texts = list(p.imap(self.tokenize_example, examples, chunksize=self.chunk_size))
for ex_index, example in enumerate(tqdm(examples, desc="Convert dataset")):
if label_type is None:
if isinstance(example.label, int):
label_type = torch.long
elif isinstance(example.label, float):
label_type = torch.float
tokenized_text = tokenized_texts[ex_index][0]
if hasattr(model, 'max_seq_length') and model.max_seq_length is not None and model.max_seq_length > 0 and len(tokenized_text) > model.max_seq_length:
too_long += 1
if example.label in label_sent_mapping:
label_sent_mapping[example.label].append(ex_index)
else:
label_sent_mapping[example.label] = [ex_index]
inputs.append(tokenized_text)
labels.append(example.label)
distinct_labels = list(label_sent_mapping.keys())
for i in range(len(distinct_labels)):
label = distinct_labels[i]
if len(label_sent_mapping[label]) >= 2:
self.grouped_inputs.extend([inputs[j] for j in label_sent_mapping[label]])
self.grouped_labels.extend([labels[j] for j in label_sent_mapping[label]])
self.groups_right_border.append(len(self.grouped_inputs))
self.num_labels += 1
self.grouped_labels = torch.tensor(self.grouped_labels, dtype=label_type)
logging.info("Num sentences: %d" % (len(self.grouped_inputs)))
logging.info("Sentences longer than max_seqence_length: {}".format(too_long))
logging.info("Number of labels with >1 examples: {}".format(len(distinct_labels)))
def tokenize_example(self, example):
if example.texts_tokenized is not None:
return example.texts_tokenized
return [self.model.tokenize(text) for text in example.texts]
def __getitem__(self, item):
if not self.provide_positive and not self.provide_negative:
return [self.grouped_inputs[item]], self.grouped_labels[item]
anchor = self.grouped_inputs[item]
group_idx = bisect.bisect_right(self.groups_right_border, item)
left_border = 0 if group_idx == 0 else self.groups_right_border[group_idx - 1]
right_border = self.groups_right_border[group_idx]
if self.provide_positive:
positive_item_idx = np.random.choice(np.concatenate([self.idxs[left_border:item], self.idxs[item + 1:right_border]]))
positive = self.grouped_inputs[positive_item_idx]
else:
positive = []
if self.provide_negative:
negative_item_idx = np.random.choice(np.concatenate([self.idxs[0:left_border], self.idxs[right_border:]]))
negative = self.grouped_inputs[negative_item_idx]
else:
negative = []
return [anchor, positive, negative], self.grouped_labels[item]
def __len__(self):
return len(self.grouped_inputs) | true | true |
f72c6cbe53ce184511d53967dee75da42ddc4cbb | 11,828 | py | Python | main_multi.py | erfanMhi/Cooperative-Coevolution-Transfer-Optimization | e75b7930bd8b55a160668b1039ac154a0d0270d7 | [
"MIT"
] | 3 | 2019-08-04T18:37:58.000Z | 2020-08-16T13:01:40.000Z | main_multi.py | erfanMhi/Cooperative-Coevolution-Transfer-Optimization | e75b7930bd8b55a160668b1039ac154a0d0270d7 | [
"MIT"
] | null | null | null | main_multi.py | erfanMhi/Cooperative-Coevolution-Transfer-Optimization | e75b7930bd8b55a160668b1039ac154a0d0270d7 | [
"MIT"
] | null | null | null |
import argparse
import os
import queue
import multiprocessing as mp
# import SharedArray as sa
import numpy as np
from copy import deepcopy
from time import time
from pprint import pprint
from utils.data_manipulators import *
from evolution.operators import *
from to.probabilistic_model import ProbabilisticModel
from to.mixture_model import MixtureModel
from evolution.chromosome import *
class EAProcess(mp.Process):
def __init__(self, dims, psize, gen, problem, shared_queue,
shared_array, t_lock, list_lock, return_list, transfer_interval=2):
super(EAProcess, self).__init__()
self.dims = dims
self.psize = psize
print('hi')
self.gen = gen
self.problem = problem
self.shared_queue = shared_queue
self.shared_array = shared_array
# self.shared_lock = shared_lock
self.t_lock = t_lock
self.list_lock = list_lock
self.transfer_interval = transfer_interval
self.reinitialize()
self.return_list = return_list
def reinitialize(self):
self.fitness_hist = np.zeros((self.gen, self.psize))
self.fitness_time = np.zeros((self.gen))
init_func = lambda n: np.round(np.random.rand(n))
self.pop = get_pop_init(self.psize, self.dims, init_func)
def _ea(self):
start = time()
for i in range(self.psize): self.pop[i].fitness_calc(self.problem)
self.bestfitness = np.max(self.pop).fitness
self.fitness = Chromosome.fitness_to_numpy(self.pop)
self.fitness_hist[0, :] = self.fitness
self.fitness_time[0] = start - time()
for i in range(1, self.gen):
start = time()
if i%self.transfer_interval == 0 and i//self.transfer_interval == 1:
print('transfer start')
self.t_lock.release()
if i%self.transfer_interval == 0:
recieved_pops = None
try:
while True:
if recieved_pops is None:
recieved_pops = list(self.shared_queue.get(block=True))
else:
recieved_pops += list(self.shared_queue.get(block=False))
except queue.Empty:
print('Queue is empty now')
print('recieved_pops: ', len(recieved_pops))
self.pop = total_selection_pop(np.concatenate((self.pop, recieved_pops)), self.psize)
offsprings = total_crossover(self.pop)
for j in range(self.psize): offsprings[j].mutation(1/self.dims)
# Fitness Calculation
cfitness = np.zeros(self.psize)
for j in range(self.psize):
cfitness[j] = offsprings[j].fitness_calc(self.problem)
self.pop, self.fitness = total_selection(np.concatenate((self.pop, offsprings)),
np.concatenate((self.fitness, cfitness)), self.psize)
self.fitness_hist[i, :] = self.fitness
if self.fitness[0] > self.bestfitness:
self.bestfitness = self.fitness[0]
print('Generation %d best fitness = %f' % (i, self.bestfitness))
self.list_lock.acquire()
self.shared_array[:] = Chromosome.genes_to_list(self.pop)
self.list_lock.release()
self.fitness_time[i] = time() - start
print('Shared Array is now available')
self.return_list.append([self.fitness_time, self.fitness_hist])
def run(self):
# When target array is prepared it will be unlocked
print ('called run method in process: %s' %self.name)
self._ea()
return
class TransferProcess(mp.Process):
def __init__(self, dims, problem, mutation_strength,
sample_size, sub_sample_size, src_models,
shared_queue, shared_array, t_lock,
list_lock, transfer_interval=2):
super(TransferProcess, self).__init__()
self.dims = dims
self.problem = problem
self.src_models = src_models
self.mutation_strength = mutation_strength
self.sample_size = sample_size
self.sub_sample_size = sub_sample_size
self.shared_queue = shared_queue
self.shared_array = shared_array
# self.shared_lock = shared_lock
self.t_lock = t_lock
self.list_lock = list_lock
self.transfer_interval = transfer_interval
self.reinitialize()
def reinitialize(self):
# self.fitness_hist = np.zeros((self.gen, self.psize))
# self.fitness_time = np.zeros((self.gen))
dims_s2 = len(self.src_models)+1
self.second_specie = StrategyChromosome(dims_s2)
def _transfer_ea(self):
prev_samples = None
genes_differ = None
target_model = ProbabilisticModel(modelType='umd')
self.list_lock.acquire()
target_array = np.array(self.shared_array[:])
self.list_lock.release()
target_model.buildModel(target_array)
_, sampled_offsprings, prev_samples = \
self.second_specie.fitness_calc(self.problem, self.src_models, target_model, self.sample_size,
self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples),
efficient_version=True)
self.shared_queue.put(sampled_offsprings)
while True:
offspring = deepcopy(self.second_specie)
genes_differ = offspring.mutation(self.mutation_strength, 0, 1)
target_model = ProbabilisticModel(modelType='umd')
self.list_lock.acquire()
target_array = np.array(self.shared_array[:])
self.list_lock.release()
target_model.buildModel(target_array)
_, sampled_offsprings, prev_samples_tmp = \
offspring.fitness_calc(self.problem, self.src_models, target_model, self.sample_size,
self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples),
efficient_version=True)
self.shared_queue.put(sampled_offsprings)
self.second_specie, self.mutation_strength, is_off_selected = selection_adoption(self.second_specie, offspring, self.mutation_strength)
if is_off_selected:
prev_samples = prev_samples_tmp
# second_species_gen_num += 1
# while True:
def run(self):
self.t_lock.acquire()
print ('called run method in process: %s' %self.name)
self._transfer_ea()
return
def get_args():
parser = argparse.ArgumentParser(description='CoOperative CoEvolution Transfer Optimization Algorithm for Solving Multi-location Inventory Planning with Lateral Transshipments')
parser.add_argument('--stop_condition', default=True,
type=bool, nargs='?',
help="Stop after i number of iteraction if fitness didn't changed")
parser.add_argument('--reps', default=1,
type=int, nargs='?',
help='Number of repetition')
parser.add_argument('--delta', default=2,
type=int, nargs='?',
help='Step for switiching between transfer optimization and evolutionary operations')
# parser.add_argument('--buildmodel', default=True,
# type=bool, nargs='?',
# help='Should we build source models?')
parser.add_argument('--src_version', default='v1',
type=str, nargs='?',
help='What version of source models should be used?')
parser.add_argument('--s1_psize', default=50,
type=int, nargs='?',
help='Population size for the first species?')
# parser.add_argument('--s2_psize', default=20,
# type=int, nargs='?',
# help='Population size for the second species?')
parser.add_argument('--sample_size', default=50,
type=int, nargs='?',
help='Number of samples generated from each AlphaChromosome?')
parser.add_argument('--sub_sample_size', default=50,
type=int, nargs='?',
help='How many samples should we take from sample_size number of samples generated?')
# parser.add_argument('-v', dest='version', default='v1',
# type=str, nargs='?',
# help='What version should be executed?')
parser.add_argument('--mutation_strength', default=1,
type=int, nargs='?',
help='The same step-size which we use in evolution strategy')
parser.add_argument('--injection_type', default='elite',
type=str, nargs='?',
help='What method do you want to use for injection of species 2 to species 1?')
parser.add_argument('--to_repititon_num', default=1,
type=int, nargs='?',
help='How many time should we repeat the transferring step in evolution strategy?')
parser.add_argument('--selection_version', default='v1',
type=str, nargs='?',
help='What selection version should we use in evolution strategy E(1 + 1)?')
parser.add_argument('-c', default=2,
type=int, nargs='?',
help='Parameter of E(1 + 1) algorithm selection')
parser.add_argument('--efficient_version', default=False,
type=bool, nargs='?',
help='Efficient version of evaluation strategy version?')
parser.add_argument('--transfer_repeat_num', default=None,
type=int, nargs='?',
help=''' Number of times transfer optimization should be run.
if it is None, it will be repeated in every delta iteration''')
# parser.add_argument('-q', dest='matrix_num', default='a',
# type=str, nargs='?',
# help='T^0_H matrix selector for section b')
return parser.parse_args()
def main_multi(args):
# constants
models_path = 'models'
source_models_path = os.path.join(models_path, 'knapsack_source_models')
knapsack_problem_path = 'problems/knapsack'
dims = 1000
psize = args.s1_psize
mutation_strength = args.mutation_strength
reps = args.reps
transfer_interval = args.delta
sub_sample_size = args.sub_sample_size
sample_size = args.sample_size
gen = 100
# Loading Target Problem
target_problem = Tools.load_from_file(os.path.join(knapsack_problem_path, 'KP_uc_ak'))
# Loading Source Models
src_models = Tools.load_from_file(source_models_path + '_{}'.format(args.src_version))
main_m = mp.Manager()
return_list = main_m.list()
for i in range(reps):
# Shared Variables
m = mp.Manager()
shared_queue = m.Queue()
shared_array = m.list([[0 for j in range(dims)] for i in range(psize)])
# prep_lock = m.Lock() # This lock is used for starting transfer learning
# prep_lock.acquire()
list_lock = m.Lock() # \\ for synchronozing read & write of the list
# q_lock = m.Lock() # \\ for synchronozing put & get of the queue
transfer_lock = m.Lock() # \\ will synchronize the transfer_interval for EAProcess
transfer_lock.acquire()
ea_process = EAProcess(dims, psize, gen, target_problem, shared_queue,
shared_array, transfer_lock, list_lock, return_list,
transfer_interval=transfer_interval)
tr_process = TransferProcess(dims, target_problem, mutation_strength,
sample_size, sub_sample_size, src_models,
shared_queue, shared_array, transfer_lock,
list_lock, transfer_interval=transfer_interval)
ea_process.start()
tr_process.start()
ea_process.join()
tr_process.terminate()
tr_process.join()
Tools.save_to_file(args.save_path, return_list[:])
if __name__ == '__main__':
args = get_args()
main_multi(args)
| 34.086455 | 179 | 0.633581 |
import argparse
import os
import queue
import multiprocessing as mp
import numpy as np
from copy import deepcopy
from time import time
from pprint import pprint
from utils.data_manipulators import *
from evolution.operators import *
from to.probabilistic_model import ProbabilisticModel
from to.mixture_model import MixtureModel
from evolution.chromosome import *
class EAProcess(mp.Process):
def __init__(self, dims, psize, gen, problem, shared_queue,
shared_array, t_lock, list_lock, return_list, transfer_interval=2):
super(EAProcess, self).__init__()
self.dims = dims
self.psize = psize
print('hi')
self.gen = gen
self.problem = problem
self.shared_queue = shared_queue
self.shared_array = shared_array
self.t_lock = t_lock
self.list_lock = list_lock
self.transfer_interval = transfer_interval
self.reinitialize()
self.return_list = return_list
def reinitialize(self):
self.fitness_hist = np.zeros((self.gen, self.psize))
self.fitness_time = np.zeros((self.gen))
init_func = lambda n: np.round(np.random.rand(n))
self.pop = get_pop_init(self.psize, self.dims, init_func)
def _ea(self):
start = time()
for i in range(self.psize): self.pop[i].fitness_calc(self.problem)
self.bestfitness = np.max(self.pop).fitness
self.fitness = Chromosome.fitness_to_numpy(self.pop)
self.fitness_hist[0, :] = self.fitness
self.fitness_time[0] = start - time()
for i in range(1, self.gen):
start = time()
if i%self.transfer_interval == 0 and i//self.transfer_interval == 1:
print('transfer start')
self.t_lock.release()
if i%self.transfer_interval == 0:
recieved_pops = None
try:
while True:
if recieved_pops is None:
recieved_pops = list(self.shared_queue.get(block=True))
else:
recieved_pops += list(self.shared_queue.get(block=False))
except queue.Empty:
print('Queue is empty now')
print('recieved_pops: ', len(recieved_pops))
self.pop = total_selection_pop(np.concatenate((self.pop, recieved_pops)), self.psize)
offsprings = total_crossover(self.pop)
for j in range(self.psize): offsprings[j].mutation(1/self.dims)
cfitness = np.zeros(self.psize)
for j in range(self.psize):
cfitness[j] = offsprings[j].fitness_calc(self.problem)
self.pop, self.fitness = total_selection(np.concatenate((self.pop, offsprings)),
np.concatenate((self.fitness, cfitness)), self.psize)
self.fitness_hist[i, :] = self.fitness
if self.fitness[0] > self.bestfitness:
self.bestfitness = self.fitness[0]
print('Generation %d best fitness = %f' % (i, self.bestfitness))
self.list_lock.acquire()
self.shared_array[:] = Chromosome.genes_to_list(self.pop)
self.list_lock.release()
self.fitness_time[i] = time() - start
print('Shared Array is now available')
self.return_list.append([self.fitness_time, self.fitness_hist])
def run(self):
print ('called run method in process: %s' %self.name)
self._ea()
return
class TransferProcess(mp.Process):
def __init__(self, dims, problem, mutation_strength,
sample_size, sub_sample_size, src_models,
shared_queue, shared_array, t_lock,
list_lock, transfer_interval=2):
super(TransferProcess, self).__init__()
self.dims = dims
self.problem = problem
self.src_models = src_models
self.mutation_strength = mutation_strength
self.sample_size = sample_size
self.sub_sample_size = sub_sample_size
self.shared_queue = shared_queue
self.shared_array = shared_array
self.t_lock = t_lock
self.list_lock = list_lock
self.transfer_interval = transfer_interval
self.reinitialize()
def reinitialize(self):
dims_s2 = len(self.src_models)+1
self.second_specie = StrategyChromosome(dims_s2)
def _transfer_ea(self):
prev_samples = None
genes_differ = None
target_model = ProbabilisticModel(modelType='umd')
self.list_lock.acquire()
target_array = np.array(self.shared_array[:])
self.list_lock.release()
target_model.buildModel(target_array)
_, sampled_offsprings, prev_samples = \
self.second_specie.fitness_calc(self.problem, self.src_models, target_model, self.sample_size,
self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples),
efficient_version=True)
self.shared_queue.put(sampled_offsprings)
while True:
offspring = deepcopy(self.second_specie)
genes_differ = offspring.mutation(self.mutation_strength, 0, 1)
target_model = ProbabilisticModel(modelType='umd')
self.list_lock.acquire()
target_array = np.array(self.shared_array[:])
self.list_lock.release()
target_model.buildModel(target_array)
_, sampled_offsprings, prev_samples_tmp = \
offspring.fitness_calc(self.problem, self.src_models, target_model, self.sample_size,
self.sub_sample_size, mutation_vec=genes_differ, prev_samples=deepcopy(prev_samples),
efficient_version=True)
self.shared_queue.put(sampled_offsprings)
self.second_specie, self.mutation_strength, is_off_selected = selection_adoption(self.second_specie, offspring, self.mutation_strength)
if is_off_selected:
prev_samples = prev_samples_tmp
def run(self):
self.t_lock.acquire()
print ('called run method in process: %s' %self.name)
self._transfer_ea()
return
def get_args():
parser = argparse.ArgumentParser(description='CoOperative CoEvolution Transfer Optimization Algorithm for Solving Multi-location Inventory Planning with Lateral Transshipments')
parser.add_argument('--stop_condition', default=True,
type=bool, nargs='?',
help="Stop after i number of iteraction if fitness didn't changed")
parser.add_argument('--reps', default=1,
type=int, nargs='?',
help='Number of repetition')
parser.add_argument('--delta', default=2,
type=int, nargs='?',
help='Step for switiching between transfer optimization and evolutionary operations')
# parser.add_argument('--buildmodel', default=True,
# type=bool, nargs='?',
# help='Should we build source models?')
parser.add_argument('--src_version', default='v1',
type=str, nargs='?',
help='What version of source models should be used?')
parser.add_argument('--s1_psize', default=50,
type=int, nargs='?',
help='Population size for the first species?')
# parser.add_argument('--s2_psize', default=20,
# type=int, nargs='?',
# help='Population size for the second species?')
parser.add_argument('--sample_size', default=50,
type=int, nargs='?',
help='Number of samples generated from each AlphaChromosome?')
parser.add_argument('--sub_sample_size', default=50,
type=int, nargs='?',
help='How many samples should we take from sample_size number of samples generated?')
# parser.add_argument('-v', dest='version', default='v1',
# type=str, nargs='?',
# help='What version should be executed?')
parser.add_argument('--mutation_strength', default=1,
type=int, nargs='?',
help='The same step-size which we use in evolution strategy')
parser.add_argument('--injection_type', default='elite',
type=str, nargs='?',
help='What method do you want to use for injection of species 2 to species 1?')
parser.add_argument('--to_repititon_num', default=1,
type=int, nargs='?',
help='How many time should we repeat the transferring step in evolution strategy?')
parser.add_argument('--selection_version', default='v1',
type=str, nargs='?',
help='What selection version should we use in evolution strategy E(1 + 1)?')
parser.add_argument('-c', default=2,
type=int, nargs='?',
help='Parameter of E(1 + 1) algorithm selection')
parser.add_argument('--efficient_version', default=False,
type=bool, nargs='?',
help='Efficient version of evaluation strategy version?')
parser.add_argument('--transfer_repeat_num', default=None,
type=int, nargs='?',
help=''' Number of times transfer optimization should be run.
if it is None, it will be repeated in every delta iteration''')
# parser.add_argument('-q', dest='matrix_num', default='a',
# type=str, nargs='?',
# help='T^0_H matrix selector for section b')
return parser.parse_args()
def main_multi(args):
# constants
models_path = 'models'
source_models_path = os.path.join(models_path, 'knapsack_source_models')
knapsack_problem_path = 'problems/knapsack'
dims = 1000
psize = args.s1_psize
mutation_strength = args.mutation_strength
reps = args.reps
transfer_interval = args.delta
sub_sample_size = args.sub_sample_size
sample_size = args.sample_size
gen = 100
# Loading Target Problem
target_problem = Tools.load_from_file(os.path.join(knapsack_problem_path, 'KP_uc_ak'))
# Loading Source Models
src_models = Tools.load_from_file(source_models_path + '_{}'.format(args.src_version))
main_m = mp.Manager()
return_list = main_m.list()
for i in range(reps):
# Shared Variables
m = mp.Manager()
shared_queue = m.Queue()
shared_array = m.list([[0 for j in range(dims)] for i in range(psize)])
# prep_lock = m.Lock() # This lock is used for starting transfer learning
# prep_lock.acquire()
list_lock = m.Lock() # \\ for synchronozing read & write of the list
# q_lock = m.Lock() # \\ for synchronozing put & get of the queue
transfer_lock = m.Lock() # \\ will synchronize the transfer_interval for EAProcess
transfer_lock.acquire()
ea_process = EAProcess(dims, psize, gen, target_problem, shared_queue,
shared_array, transfer_lock, list_lock, return_list,
transfer_interval=transfer_interval)
tr_process = TransferProcess(dims, target_problem, mutation_strength,
sample_size, sub_sample_size, src_models,
shared_queue, shared_array, transfer_lock,
list_lock, transfer_interval=transfer_interval)
ea_process.start()
tr_process.start()
ea_process.join()
tr_process.terminate()
tr_process.join()
Tools.save_to_file(args.save_path, return_list[:])
if __name__ == '__main__':
args = get_args()
main_multi(args)
| true | true |
f72c6d1c6f29288f9f93496e8adfb3d17d94900b | 291 | py | Python | orb_simulator/other_language/testing_ast/Div.py | dmguezjaviersnet/IA-Sim-Comp-Project | 8165b9546efc45f98091a3774e2dae4f45942048 | [
"MIT"
] | 1 | 2022-01-19T22:49:09.000Z | 2022-01-19T22:49:09.000Z | orb_simulator/other_language/testing_ast/Div.py | dmguezjaviersnet/IA-Sim-Comp-Project | 8165b9546efc45f98091a3774e2dae4f45942048 | [
"MIT"
] | 15 | 2021-11-10T14:25:02.000Z | 2022-02-12T19:17:11.000Z | orb_simulator/other_language/testing_ast/Div.py | dmguezjaviersnet/IA-Sim-Comp-Project | 8165b9546efc45f98091a3774e2dae4f45942048 | [
"MIT"
] | null | null | null | from other_language.testing_ast.BinaryExpression import *
class Div(BinaryExpression):
def __init__(self, left: Expression, right: Expression):
super().__init__(left, right)
def eval(self):
self.left.eval() // self.right.eval()
| 19.4 | 60 | 0.608247 | from other_language.testing_ast.BinaryExpression import *
class Div(BinaryExpression):
def __init__(self, left: Expression, right: Expression):
super().__init__(left, right)
def eval(self):
self.left.eval() // self.right.eval()
| true | true |
f72c6dc05c0249cca7efdc46371d16e808b21190 | 7,782 | py | Python | tests/dataset.py | Juan0001/yellowbrick-docs-zh | 36275d9704fc2a946c5bec5f802106bb5281efd1 | [
"Apache-2.0"
] | 20 | 2018-03-24T02:29:20.000Z | 2022-03-03T05:01:40.000Z | tests/dataset.py | Juan0001/yellowbrick-docs-zh | 36275d9704fc2a946c5bec5f802106bb5281efd1 | [
"Apache-2.0"
] | 4 | 2018-03-20T12:01:17.000Z | 2019-04-07T16:02:19.000Z | tests/dataset.py | Juan0001/yellowbrick-docs-zh | 36275d9704fc2a946c5bec5f802106bb5281efd1 | [
"Apache-2.0"
] | 5 | 2018-03-17T08:18:57.000Z | 2019-11-15T02:20:20.000Z | # tests.dataset
# Helper functions for tests that utilize downloadable datasets.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Thu Oct 13 19:55:53 2016 -0400
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: dataset.py [8f4de77] benjamin@bengfort.com $
"""
Helper functions for tests that utilize downloadable datasets.
"""
##########################################################################
## Imports
##########################################################################
import os
import shutil
import hashlib
import zipfile
import numpy as np
from sklearn.datasets.base import Bunch
try:
import requests
except ImportError:
requests = None
##########################################################################
## Fixtures
##########################################################################
DATASETS = {
'concrete': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/concrete.zip',
'signature': 'b9ea5f26a7bb272a040e2f1a993b26babbf8dc4a04ab8198bb315ca66d71f10d',
'type': 'numpy',
},
'energy': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/energy.zip',
'signature': '19fb86f3bcdde208eed46944172cb643ef6a7d58da103fb568fae43205ed89d3',
'type': 'numpy',
},
'credit': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/credit.zip',
'signature': '4a91339c69f55e18f3f48004328fbcb7868070b618208fed099920427b084e5e',
'type': 'numpy',
},
'occupancy': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/occupancy.zip',
'signature': '429cfe376dc9929a1fa528da89f0e1626e34e19695f3f555d8954025bbc522b8',
'type': 'numpy',
},
'mushroom': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/mushroom.zip',
'signature': '884c43cb70db35d211c67b1cf6a3683b2b4569393d2789d5c07840da4dc85ba8',
'type': 'numpy',
},
'hobbies': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/hobbies.zip',
'signature': '415c8f68df1486d5d84a1d1757a5aa3035aef5ad63ede5013c261d622fbd29d8',
'type': 'corpus',
},
'game': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/game.zip',
'signature': 'b1bd85789a014a898daa34cb5f89ceab6d2cd6488a2e572187e34aa4ec21a43b',
'type': 'numpy',
},
'bikeshare': {
'url': 'https://s3.amazonaws.com/ddl-data-lake/yellowbrick/bikeshare.zip',
'signature': 'a9b440f65549746dff680c92ff8bdca3c7265f09db1cf09e708e6e26fc8aba44',
'type': 'numpy',
},
}
FIXTURES = os.path.join(os.path.dirname(__file__), "fixtures")
##########################################################################
## Test Cases that Require Download
##########################################################################
class DatasetMixin(object):
"""
Mixin for unittest.TestCase class to download datasets from S3 for
testing real world machine learning visual diagnostics.
"""
@staticmethod
def sha256sum(path, blocksize=65536):
"""
Computes the SHA256 signature of a file to verify that the file has not
been modified in transit and that it is the correct version of the data.
"""
sig = hashlib.sha256()
with open(path, 'rb') as f:
buf = f.read(blocksize)
while len(buf) > 0:
sig.update(buf)
buf = f.read(blocksize)
return sig.hexdigest()
@staticmethod
def download_data(url, path=FIXTURES, signature=None, extract=True):
"""
Downloads the zipped data set specified at the given URL, saving it to
the output path specified. This function verifies the download with the
given signature (if supplied) and extracts the zip file if requested.
"""
if requests is None:
raise ImportError(
"The requests module is required to download data --\n"
"please install it with pip install requests."
)
# Create the output directory if it does not exist
if not os.path.exists(path):
os.mkdir(path)
# Get the name of the file from the URL
name = os.path.basename(url)
dlpath = os.path.join(path, name)
# Fetch the response in a streaming fashion and write it to disk.
response = requests.get(url, stream=True)
with open(dlpath, 'wb') as f:
for chunk in response.iter_content(65536):
f.write(chunk)
# If verify, compare the signature
if signature is not None:
dlsignature = DatasetMixin.sha256sum(dlpath)
if signature != dlsignature:
raise ValueError(
"Download signature does not match hardcoded signature!"
)
# If extract, extract the zipfile.
if extract:
zf = zipfile.ZipFile(dlpath)
zf.extractall(path)
@staticmethod
def download_all(path=FIXTURES, verify=True, extract=True):
"""
Downloads all the example datasets. If verify is True then compare the
download signature with the hardcoded signature. If extract is True then
extract the contents of the zipfile to the given path.
"""
for name, meta in DATASETS.items():
url = meta['url']
signature = meta['signature'] if verify else None
DatasetMixin.download_data(
url, path=path, signature=signature, extract=extract
)
@staticmethod
def remove_all(fixtures=FIXTURES):
"""
Removes all the downloaded datasets as clean up
"""
shutil.rmtree(fixtures)
@staticmethod
def load_data(name, fixtures=FIXTURES):
"""
Loads the numpy matrix from the specified data set, downloads it if
it hasn't already been downloaded.
"""
# Just in case this is a corpus data set, then do that instead.
if DATASETS[name]['type'] == 'corpus':
return DatasetMixin.load_corpus(name, fixtures)
path = os.path.join(fixtures, name, "{}.csv".format(name))
if not os.path.exists(path):
DatasetMixin.download_all(path=fixtures)
return np.genfromtxt(path, dtype=float, delimiter=',', names=True)
@staticmethod
def load_corpus(name, fixtures=FIXTURES):
"""
Loads a sklearn Bunch with the corpus and downloads it if it hasn't
already been downloaded. Used to test text visualizers.
"""
path = os.path.join(fixtures, name)
if not os.path.exists(path):
DatasetMixin.download_all(path=fixtures)
# Read the directories in the directory as the categories.
categories = [
cat for cat in os.listdir(path)
if os.path.isdir(os.path.join(path, cat))
]
files = [] # holds the file names relative to the root
data = [] # holds the text read from the file
target = [] # holds the string of the category
# Load the data from the files in the corpus
for cat in categories:
for name in os.listdir(os.path.join(path, cat)):
files.append(os.path.join(path, cat, name))
target.append(cat)
with open(os.path.join(path, cat, name), 'r') as f:
data.append(f.read())
# Return the data bunch for use similar to the newsgroups example
return Bunch(
categories=categories,
files=files,
data=data,
target=target,
)
| 34.741071 | 88 | 0.585582 | true | true | |
f72c705b69032d729b976d015ba6742b4d314c78 | 17,180 | py | Python | src/olympia/files/tests/test_file_viewer.py | shashwatsingh/addons-server | 8fce98901104349055a828b5a47865f5e8f4120b | [
"BSD-3-Clause"
] | null | null | null | src/olympia/files/tests/test_file_viewer.py | shashwatsingh/addons-server | 8fce98901104349055a828b5a47865f5e8f4120b | [
"BSD-3-Clause"
] | null | null | null | src/olympia/files/tests/test_file_viewer.py | shashwatsingh/addons-server | 8fce98901104349055a828b5a47865f5e8f4120b | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import mimetypes
import os
import shutil
import zipfile
from django import forms
from django.conf import settings
from django.core.cache import cache
from django.core.files.storage import default_storage as storage
import pytest
from freezegun import freeze_time
from unittest.mock import Mock, patch
from olympia import amo
from olympia.amo.tests import TestCase
from olympia.files.file_viewer import DiffHelper, FileViewer, extract_file
from olympia.files.models import File
from olympia.files.utils import SafeZip, get_all_files
from olympia.files.tests.test_utils import _run_lock_holding_process
root = os.path.join(settings.ROOT, 'src/olympia/files/fixtures/files')
def get_file(filename):
return os.path.join(root, filename)
def make_file(pk, file_path, **kwargs):
obj = Mock()
obj.id = obj.pk = pk
for k, v in kwargs.items():
setattr(obj, k, v)
obj.file_path = file_path
obj.current_file_path = file_path
obj.__str__ = lambda x: x.pk
obj.version = Mock()
obj.version.version = 1
return obj
class TestFileViewer(TestCase):
def setUp(self):
super(TestFileViewer, self).setUp()
self.viewer = FileViewer(make_file(1, get_file('dictionary-test.xpi')))
def tearDown(self):
self.viewer.cleanup()
super(TestFileViewer, self).tearDown()
def test_files_not_extracted(self):
assert not self.viewer.is_extracted()
def test_files_extracted(self):
self.viewer.extract()
assert self.viewer.is_extracted()
def test_recurse_extract(self):
self.viewer.src = get_file('recurse.xpi')
self.viewer.extract()
assert self.viewer.is_extracted()
def test_recurse_contents(self):
self.viewer.src = get_file('recurse.xpi')
self.viewer.extract()
files = self.viewer.get_files()
# We do not extract nested .zip or .xpi files anymore
assert list(files.keys()) == [
u'recurse',
u'recurse/chrome',
u'recurse/chrome/test-root.txt',
u'recurse/chrome/test.jar',
u'recurse/notazip.jar',
u'recurse/recurse.xpi',
u'recurse/somejar.jar']
def test_locked(self):
self.viewer.src = get_file('dictionary-test.xpi')
# Lock was successfully attained
assert self.viewer.extract()
lock_name = f'file-viewer-{self.viewer.file.pk}'
with _run_lock_holding_process(lock_name, sleep=3):
# Not extracting, the viewer is locked, lock could not be attained
assert not self.viewer.extract()
def test_extract_file_locked_message(self):
self.viewer.src = get_file('dictionary-test.xpi')
assert not self.viewer.is_extracted()
lock_name = f'file-viewer-{self.viewer.file.pk}'
with _run_lock_holding_process(lock_name, sleep=3):
msg = extract_file(self.viewer)
assert str(msg.get()).startswith(u'File viewer is locked')
msg.delete()
def test_cleanup(self):
self.viewer.extract()
self.viewer.cleanup()
assert not self.viewer.is_extracted()
@freeze_time('2017-01-08 02:01:00')
def test_dest(self):
viewer = FileViewer(make_file(1, get_file('webextension.xpi')))
assert viewer.dest == os.path.join(
settings.TMP_PATH, 'file_viewer',
'0108', str(self.viewer.file.pk))
def test_isbinary(self):
binary = self.viewer._is_binary
for f in ['foo.rdf', 'foo.xml', 'foo.js', 'foo.py'
'foo.html', 'foo.txt', 'foo.dtd', 'foo.xul', 'foo.sh',
'foo.properties', 'foo.json', 'foo.src', 'CHANGELOG']:
m, encoding = mimetypes.guess_type(f)
assert not binary(m, f), '%s should not be binary' % f
for f in ['foo.png', 'foo.gif', 'foo.exe', 'foo.swf']:
m, encoding = mimetypes.guess_type(f)
assert binary(m, f), '%s should be binary' % f
filename = os.path.join(settings.TMP_PATH, 'test_isbinary')
for txt in ['#!/usr/bin/python', '#python', u'\0x2']:
open(filename, 'w').write(txt)
m, encoding = mimetypes.guess_type(filename)
assert not binary(m, filename), '%s should not be binary' % txt
for txt in ['MZ']:
open(filename, 'w').write(txt)
m, encoding = mimetypes.guess_type(filename)
assert binary(m, filename), '%s should be binary' % txt
os.remove(filename)
def test_truncate(self):
truncate = self.viewer.truncate
for x, y in (['foo.rdf', 'foo.rdf'],
['somelongfilename.rdf', 'somelongfilenam...rdf'],
[u'unicode삮.txt', u'unicode\uc0ae.txt'],
[u'unicodesomelong삮.txt', u'unicodesomelong...txt'],
['somelongfilename.somelongextension',
'somelongfilenam...somelonge..'],):
assert truncate(x) == y
def test_get_files_not_extracted_runs_extraction(self):
self.viewer.src = get_file('dictionary-test.xpi')
assert not self.viewer.is_extracted()
self.viewer.get_files()
assert self.viewer.is_extracted()
def test_get_files_size(self):
self.viewer.extract()
files = self.viewer.get_files()
assert len(files) == 14
def test_get_files_directory(self):
self.viewer.extract()
files = self.viewer.get_files()
assert not files['install.js']['directory']
assert not files['install.js']['binary']
assert files['__MACOSX']['directory']
assert not files['__MACOSX']['binary']
def test_get_files_depth(self):
self.viewer.extract()
files = self.viewer.get_files()
assert files['dictionaries/license.txt']['depth'] == 1
def test_bom(self):
dest = os.path.join(settings.TMP_PATH, 'test_bom')
with open(dest, 'wb') as f:
f.write('foo'.encode('utf-16'))
self.viewer.select('foo')
self.viewer.selected = {'full': dest, 'size': 1}
assert self.viewer.read_file() == u'foo'
os.remove(dest)
def test_syntax(self):
for filename, syntax in [('foo.rdf', 'xml'),
('foo.xul', 'xml'),
('foo.json', 'js'),
('foo.jsm', 'js'),
('foo.htm', 'html'),
('foo.bar', 'plain'),
('foo.diff', 'plain')]:
assert self.viewer.get_syntax(filename) == syntax
def test_file_order(self):
self.viewer.extract()
dest = self.viewer.dest
open(os.path.join(dest, 'chrome.manifest'), 'w')
subdir = os.path.join(dest, 'chrome')
os.mkdir(subdir)
open(os.path.join(subdir, 'foo'), 'w')
cache.delete(self.viewer._cache_key())
files = list(self.viewer.get_files().keys())
rt = files.index(u'chrome')
assert files[rt:rt + 3] == [u'chrome', u'chrome/foo', u'dictionaries']
@patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
def test_file_size(self):
self.viewer.extract()
self.viewer.get_files()
self.viewer.select('install.js')
res = self.viewer.read_file()
assert res == ''
assert self.viewer.selected['msg'].startswith('File size is')
@pytest.mark.needs_locales_compilation
@patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
def test_file_size_unicode(self):
with self.activate(locale='he'):
self.viewer.extract()
self.viewer.get_files()
self.viewer.select('install.js')
res = self.viewer.read_file()
assert res == ''
assert (
self.viewer.selected['msg'].startswith(u'גודל הקובץ חורג'))
@patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
def test_contents_size(self):
self.assertRaises(forms.ValidationError, self.viewer.extract)
def test_default(self):
self.viewer.extract()
assert self.viewer.get_default(None) == 'install.rdf'
def test_default_webextension(self):
viewer = FileViewer(make_file(2, get_file('webextension.xpi')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_webextension_zip(self):
viewer = FileViewer(make_file(2, get_file('webextension_no_id.zip')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_webextension_crx(self):
viewer = FileViewer(make_file(2, get_file('webextension.crx')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_package_json(self):
viewer = FileViewer(make_file(3, get_file('new-format-0.0.1.xpi')))
viewer.extract()
assert viewer.get_default(None) == 'package.json'
def test_delete_mid_read(self):
self.viewer.extract()
self.viewer.select('install.js')
os.remove(os.path.join(self.viewer.dest, 'install.js'))
res = self.viewer.read_file()
assert res == ''
assert self.viewer.selected['msg'].startswith('That file no')
@patch('olympia.files.file_viewer.get_sha256')
def test_delete_mid_tree(self, get_sha256):
get_sha256.side_effect = IOError('ow')
self.viewer.extract()
with self.assertRaises(IOError):
self.viewer.get_files()
@patch('olympia.files.file_viewer.os.fsync')
def test_verify_files_doesnt_call_fsync_regularly(self, fsync):
self.viewer.extract()
assert not fsync.called
@patch('olympia.files.file_viewer.os.fsync')
def test_verify_files_calls_fsync_on_differences(self, fsync):
self.viewer.extract()
assert not fsync.called
files_to_verify = get_all_files(self.viewer.dest)
files_to_verify.pop()
module_path = 'olympia.files.file_viewer.get_all_files'
with patch(module_path) as get_all_files_mck:
get_all_files_mck.return_value = files_to_verify
with pytest.raises(ValueError):
# We don't put things back into place after fsync
# so a `ValueError` is raised
self.viewer._verify_files(files_to_verify)
assert len(fsync.call_args_list) == len(files_to_verify) + 1
class TestSearchEngineHelper(TestCase):
fixtures = ['base/addon_4594_a9']
def setUp(self):
super(TestSearchEngineHelper, self).setUp()
self.left = File.objects.get(pk=25753)
self.viewer = FileViewer(self.left)
if not os.path.exists(os.path.dirname(self.viewer.src)):
os.makedirs(os.path.dirname(self.viewer.src))
with storage.open(self.viewer.src, 'w') as f:
f.write('some data\n')
def tearDown(self):
self.viewer.cleanup()
super(TestSearchEngineHelper, self).tearDown()
def test_is_search_engine(self):
assert self.viewer.is_search_engine()
def test_extract_search_engine(self):
self.viewer.extract()
assert os.path.exists(self.viewer.dest)
def test_default(self):
self.viewer.extract()
assert self.viewer.get_default(None) == 'a9.xml'
def test_default_no_files(self):
self.viewer.extract()
os.remove(os.path.join(self.viewer.dest, 'a9.xml'))
assert self.viewer.get_default(None) is None
class TestDiffSearchEngine(TestCase):
def setUp(self):
super(TestDiffSearchEngine, self).setUp()
src = os.path.join(settings.ROOT, get_file('search.xml'))
if not storage.exists(src):
with storage.open(src, 'w') as f:
f.write(open(src).read())
self.helper = DiffHelper(make_file(1, src, filename='search.xml'),
make_file(2, src, filename='search.xml'))
def tearDown(self):
self.helper.cleanup()
super(TestDiffSearchEngine, self).tearDown()
@patch(
'olympia.files.file_viewer.FileViewer.is_search_engine')
def test_diff_search(self, is_search_engine):
is_search_engine.return_value = True
self.helper.extract()
shutil.copyfile(os.path.join(self.helper.left.dest, 'search.xml'),
os.path.join(self.helper.right.dest, 's-20010101.xml'))
assert self.helper.select('search.xml')
assert len(self.helper.get_deleted_files()) == 0
class TestDiffHelper(TestCase):
def setUp(self):
super(TestDiffHelper, self).setUp()
src = os.path.join(settings.ROOT, get_file('dictionary-test.xpi'))
self.helper = DiffHelper(make_file(1, src), make_file(2, src))
def tearDown(self):
self.helper.cleanup()
super(TestDiffHelper, self).tearDown()
def clear_cache(self):
cache.delete(self.helper.left._cache_key())
cache.delete(self.helper.right._cache_key())
def test_files_not_extracted(self):
assert not self.helper.is_extracted()
def test_files_extracted(self):
self.helper.extract()
assert self.helper.is_extracted()
def test_get_files(self):
assert self.helper.left.get_files() == (
self.helper.get_files())
def test_diffable(self):
self.helper.extract()
self.helper.select('install.js')
assert self.helper.is_diffable()
def test_diffable_one_missing(self):
self.helper.extract()
os.remove(os.path.join(self.helper.right.dest, 'install.js'))
self.helper.select('install.js')
assert self.helper.is_diffable()
def test_diffable_allow_empty(self):
self.helper.extract()
self.assertRaises(AssertionError, self.helper.right.read_file)
assert self.helper.right.read_file(allow_empty=True) == ''
def test_diffable_both_missing(self):
self.helper.extract()
self.helper.select('foo.js')
assert not self.helper.is_diffable()
def test_diffable_deleted_files(self):
self.helper.extract()
os.remove(os.path.join(self.helper.left.dest, 'install.js'))
assert 'install.js' in self.helper.get_deleted_files()
def test_diffable_one_binary_same(self):
self.helper.extract()
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_one_binary_diff(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd')
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_two_binary_diff(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd')
self.change(self.helper.right.dest, 'asd123')
self.clear_cache()
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
self.helper.right.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_one_directory(self):
self.helper.extract()
self.helper.select('install.js')
self.helper.left.selected['directory'] = True
assert not self.helper.is_diffable()
assert self.helper.left.selected['msg'].startswith('This file')
def test_diffable_parent(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd',
filename='__MACOSX/._dictionaries')
self.clear_cache()
files = self.helper.get_files()
assert files['__MACOSX/._dictionaries']['diff']
assert files['__MACOSX']['diff']
def change(self, file, text, filename='install.js'):
path = os.path.join(file, filename)
with open(path, 'rb') as f:
data = f.read()
data += text.encode('utf-8')
with open(path, 'wb') as f2:
f2.write(data)
class TestSafeZipFile(TestCase, amo.tests.AMOPaths):
# TODO(andym): get full coverage for existing SafeZip methods, most
# is covered in the file viewer tests.
@patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
def test_unzip_limit(self):
with pytest.raises(forms.ValidationError):
SafeZip(self.xpi_path('langpack-localepicker'))
def test_unzip_fatal(self):
with pytest.raises(zipfile.BadZipFile):
SafeZip(self.xpi_path('search.xml'))
def test_read(self):
zip_file = SafeZip(self.xpi_path('langpack-localepicker'))
assert b'locale browser de' in zip_file.read('chrome.manifest')
def test_not_secure(self):
zip_file = SafeZip(self.xpi_path('extension'))
assert not zip_file.is_signed()
def test_is_secure(self):
zip_file = SafeZip(self.xpi_path('signed'))
assert zip_file.is_signed()
def test_is_broken(self):
zip_file = SafeZip(self.xpi_path('signed'))
zip_file.info_list[2].filename = 'META-INF/foo.sf'
assert not zip_file.is_signed()
| 35.349794 | 79 | 0.626659 |
import mimetypes
import os
import shutil
import zipfile
from django import forms
from django.conf import settings
from django.core.cache import cache
from django.core.files.storage import default_storage as storage
import pytest
from freezegun import freeze_time
from unittest.mock import Mock, patch
from olympia import amo
from olympia.amo.tests import TestCase
from olympia.files.file_viewer import DiffHelper, FileViewer, extract_file
from olympia.files.models import File
from olympia.files.utils import SafeZip, get_all_files
from olympia.files.tests.test_utils import _run_lock_holding_process
root = os.path.join(settings.ROOT, 'src/olympia/files/fixtures/files')
def get_file(filename):
return os.path.join(root, filename)
def make_file(pk, file_path, **kwargs):
obj = Mock()
obj.id = obj.pk = pk
for k, v in kwargs.items():
setattr(obj, k, v)
obj.file_path = file_path
obj.current_file_path = file_path
obj.__str__ = lambda x: x.pk
obj.version = Mock()
obj.version.version = 1
return obj
class TestFileViewer(TestCase):
def setUp(self):
super(TestFileViewer, self).setUp()
self.viewer = FileViewer(make_file(1, get_file('dictionary-test.xpi')))
def tearDown(self):
self.viewer.cleanup()
super(TestFileViewer, self).tearDown()
def test_files_not_extracted(self):
assert not self.viewer.is_extracted()
def test_files_extracted(self):
self.viewer.extract()
assert self.viewer.is_extracted()
def test_recurse_extract(self):
self.viewer.src = get_file('recurse.xpi')
self.viewer.extract()
assert self.viewer.is_extracted()
def test_recurse_contents(self):
self.viewer.src = get_file('recurse.xpi')
self.viewer.extract()
files = self.viewer.get_files()
assert list(files.keys()) == [
u'recurse',
u'recurse/chrome',
u'recurse/chrome/test-root.txt',
u'recurse/chrome/test.jar',
u'recurse/notazip.jar',
u'recurse/recurse.xpi',
u'recurse/somejar.jar']
def test_locked(self):
self.viewer.src = get_file('dictionary-test.xpi')
assert self.viewer.extract()
lock_name = f'file-viewer-{self.viewer.file.pk}'
with _run_lock_holding_process(lock_name, sleep=3):
assert not self.viewer.extract()
def test_extract_file_locked_message(self):
self.viewer.src = get_file('dictionary-test.xpi')
assert not self.viewer.is_extracted()
lock_name = f'file-viewer-{self.viewer.file.pk}'
with _run_lock_holding_process(lock_name, sleep=3):
msg = extract_file(self.viewer)
assert str(msg.get()).startswith(u'File viewer is locked')
msg.delete()
def test_cleanup(self):
self.viewer.extract()
self.viewer.cleanup()
assert not self.viewer.is_extracted()
@freeze_time('2017-01-08 02:01:00')
def test_dest(self):
viewer = FileViewer(make_file(1, get_file('webextension.xpi')))
assert viewer.dest == os.path.join(
settings.TMP_PATH, 'file_viewer',
'0108', str(self.viewer.file.pk))
def test_isbinary(self):
binary = self.viewer._is_binary
for f in ['foo.rdf', 'foo.xml', 'foo.js', 'foo.py'
'foo.html', 'foo.txt', 'foo.dtd', 'foo.xul', 'foo.sh',
'foo.properties', 'foo.json', 'foo.src', 'CHANGELOG']:
m, encoding = mimetypes.guess_type(f)
assert not binary(m, f), '%s should not be binary' % f
for f in ['foo.png', 'foo.gif', 'foo.exe', 'foo.swf']:
m, encoding = mimetypes.guess_type(f)
assert binary(m, f), '%s should be binary' % f
filename = os.path.join(settings.TMP_PATH, 'test_isbinary')
for txt in ['#!/usr/bin/python', '#python', u'\0x2']:
open(filename, 'w').write(txt)
m, encoding = mimetypes.guess_type(filename)
assert not binary(m, filename), '%s should not be binary' % txt
for txt in ['MZ']:
open(filename, 'w').write(txt)
m, encoding = mimetypes.guess_type(filename)
assert binary(m, filename), '%s should be binary' % txt
os.remove(filename)
def test_truncate(self):
truncate = self.viewer.truncate
for x, y in (['foo.rdf', 'foo.rdf'],
['somelongfilename.rdf', 'somelongfilenam...rdf'],
[u'unicode삮.txt', u'unicode\uc0ae.txt'],
[u'unicodesomelong삮.txt', u'unicodesomelong...txt'],
['somelongfilename.somelongextension',
'somelongfilenam...somelonge..'],):
assert truncate(x) == y
def test_get_files_not_extracted_runs_extraction(self):
self.viewer.src = get_file('dictionary-test.xpi')
assert not self.viewer.is_extracted()
self.viewer.get_files()
assert self.viewer.is_extracted()
def test_get_files_size(self):
self.viewer.extract()
files = self.viewer.get_files()
assert len(files) == 14
def test_get_files_directory(self):
self.viewer.extract()
files = self.viewer.get_files()
assert not files['install.js']['directory']
assert not files['install.js']['binary']
assert files['__MACOSX']['directory']
assert not files['__MACOSX']['binary']
def test_get_files_depth(self):
self.viewer.extract()
files = self.viewer.get_files()
assert files['dictionaries/license.txt']['depth'] == 1
def test_bom(self):
dest = os.path.join(settings.TMP_PATH, 'test_bom')
with open(dest, 'wb') as f:
f.write('foo'.encode('utf-16'))
self.viewer.select('foo')
self.viewer.selected = {'full': dest, 'size': 1}
assert self.viewer.read_file() == u'foo'
os.remove(dest)
def test_syntax(self):
for filename, syntax in [('foo.rdf', 'xml'),
('foo.xul', 'xml'),
('foo.json', 'js'),
('foo.jsm', 'js'),
('foo.htm', 'html'),
('foo.bar', 'plain'),
('foo.diff', 'plain')]:
assert self.viewer.get_syntax(filename) == syntax
def test_file_order(self):
self.viewer.extract()
dest = self.viewer.dest
open(os.path.join(dest, 'chrome.manifest'), 'w')
subdir = os.path.join(dest, 'chrome')
os.mkdir(subdir)
open(os.path.join(subdir, 'foo'), 'w')
cache.delete(self.viewer._cache_key())
files = list(self.viewer.get_files().keys())
rt = files.index(u'chrome')
assert files[rt:rt + 3] == [u'chrome', u'chrome/foo', u'dictionaries']
@patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
def test_file_size(self):
self.viewer.extract()
self.viewer.get_files()
self.viewer.select('install.js')
res = self.viewer.read_file()
assert res == ''
assert self.viewer.selected['msg'].startswith('File size is')
@pytest.mark.needs_locales_compilation
@patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5)
def test_file_size_unicode(self):
with self.activate(locale='he'):
self.viewer.extract()
self.viewer.get_files()
self.viewer.select('install.js')
res = self.viewer.read_file()
assert res == ''
assert (
self.viewer.selected['msg'].startswith(u'גודל הקובץ חורג'))
@patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
def test_contents_size(self):
self.assertRaises(forms.ValidationError, self.viewer.extract)
def test_default(self):
self.viewer.extract()
assert self.viewer.get_default(None) == 'install.rdf'
def test_default_webextension(self):
viewer = FileViewer(make_file(2, get_file('webextension.xpi')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_webextension_zip(self):
viewer = FileViewer(make_file(2, get_file('webextension_no_id.zip')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_webextension_crx(self):
viewer = FileViewer(make_file(2, get_file('webextension.crx')))
viewer.extract()
assert viewer.get_default(None) == 'manifest.json'
def test_default_package_json(self):
viewer = FileViewer(make_file(3, get_file('new-format-0.0.1.xpi')))
viewer.extract()
assert viewer.get_default(None) == 'package.json'
def test_delete_mid_read(self):
self.viewer.extract()
self.viewer.select('install.js')
os.remove(os.path.join(self.viewer.dest, 'install.js'))
res = self.viewer.read_file()
assert res == ''
assert self.viewer.selected['msg'].startswith('That file no')
@patch('olympia.files.file_viewer.get_sha256')
def test_delete_mid_tree(self, get_sha256):
get_sha256.side_effect = IOError('ow')
self.viewer.extract()
with self.assertRaises(IOError):
self.viewer.get_files()
@patch('olympia.files.file_viewer.os.fsync')
def test_verify_files_doesnt_call_fsync_regularly(self, fsync):
self.viewer.extract()
assert not fsync.called
@patch('olympia.files.file_viewer.os.fsync')
def test_verify_files_calls_fsync_on_differences(self, fsync):
self.viewer.extract()
assert not fsync.called
files_to_verify = get_all_files(self.viewer.dest)
files_to_verify.pop()
module_path = 'olympia.files.file_viewer.get_all_files'
with patch(module_path) as get_all_files_mck:
get_all_files_mck.return_value = files_to_verify
with pytest.raises(ValueError):
# so a `ValueError` is raised
self.viewer._verify_files(files_to_verify)
assert len(fsync.call_args_list) == len(files_to_verify) + 1
class TestSearchEngineHelper(TestCase):
fixtures = ['base/addon_4594_a9']
def setUp(self):
super(TestSearchEngineHelper, self).setUp()
self.left = File.objects.get(pk=25753)
self.viewer = FileViewer(self.left)
if not os.path.exists(os.path.dirname(self.viewer.src)):
os.makedirs(os.path.dirname(self.viewer.src))
with storage.open(self.viewer.src, 'w') as f:
f.write('some data\n')
def tearDown(self):
self.viewer.cleanup()
super(TestSearchEngineHelper, self).tearDown()
def test_is_search_engine(self):
assert self.viewer.is_search_engine()
def test_extract_search_engine(self):
self.viewer.extract()
assert os.path.exists(self.viewer.dest)
def test_default(self):
self.viewer.extract()
assert self.viewer.get_default(None) == 'a9.xml'
def test_default_no_files(self):
self.viewer.extract()
os.remove(os.path.join(self.viewer.dest, 'a9.xml'))
assert self.viewer.get_default(None) is None
class TestDiffSearchEngine(TestCase):
def setUp(self):
super(TestDiffSearchEngine, self).setUp()
src = os.path.join(settings.ROOT, get_file('search.xml'))
if not storage.exists(src):
with storage.open(src, 'w') as f:
f.write(open(src).read())
self.helper = DiffHelper(make_file(1, src, filename='search.xml'),
make_file(2, src, filename='search.xml'))
def tearDown(self):
self.helper.cleanup()
super(TestDiffSearchEngine, self).tearDown()
@patch(
'olympia.files.file_viewer.FileViewer.is_search_engine')
def test_diff_search(self, is_search_engine):
is_search_engine.return_value = True
self.helper.extract()
shutil.copyfile(os.path.join(self.helper.left.dest, 'search.xml'),
os.path.join(self.helper.right.dest, 's-20010101.xml'))
assert self.helper.select('search.xml')
assert len(self.helper.get_deleted_files()) == 0
class TestDiffHelper(TestCase):
def setUp(self):
super(TestDiffHelper, self).setUp()
src = os.path.join(settings.ROOT, get_file('dictionary-test.xpi'))
self.helper = DiffHelper(make_file(1, src), make_file(2, src))
def tearDown(self):
self.helper.cleanup()
super(TestDiffHelper, self).tearDown()
def clear_cache(self):
cache.delete(self.helper.left._cache_key())
cache.delete(self.helper.right._cache_key())
def test_files_not_extracted(self):
assert not self.helper.is_extracted()
def test_files_extracted(self):
self.helper.extract()
assert self.helper.is_extracted()
def test_get_files(self):
assert self.helper.left.get_files() == (
self.helper.get_files())
def test_diffable(self):
self.helper.extract()
self.helper.select('install.js')
assert self.helper.is_diffable()
def test_diffable_one_missing(self):
self.helper.extract()
os.remove(os.path.join(self.helper.right.dest, 'install.js'))
self.helper.select('install.js')
assert self.helper.is_diffable()
def test_diffable_allow_empty(self):
self.helper.extract()
self.assertRaises(AssertionError, self.helper.right.read_file)
assert self.helper.right.read_file(allow_empty=True) == ''
def test_diffable_both_missing(self):
self.helper.extract()
self.helper.select('foo.js')
assert not self.helper.is_diffable()
def test_diffable_deleted_files(self):
self.helper.extract()
os.remove(os.path.join(self.helper.left.dest, 'install.js'))
assert 'install.js' in self.helper.get_deleted_files()
def test_diffable_one_binary_same(self):
self.helper.extract()
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_one_binary_diff(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd')
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_two_binary_diff(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd')
self.change(self.helper.right.dest, 'asd123')
self.clear_cache()
self.helper.select('install.js')
self.helper.left.selected['binary'] = True
self.helper.right.selected['binary'] = True
assert self.helper.is_binary()
def test_diffable_one_directory(self):
self.helper.extract()
self.helper.select('install.js')
self.helper.left.selected['directory'] = True
assert not self.helper.is_diffable()
assert self.helper.left.selected['msg'].startswith('This file')
def test_diffable_parent(self):
self.helper.extract()
self.change(self.helper.left.dest, 'asd',
filename='__MACOSX/._dictionaries')
self.clear_cache()
files = self.helper.get_files()
assert files['__MACOSX/._dictionaries']['diff']
assert files['__MACOSX']['diff']
def change(self, file, text, filename='install.js'):
path = os.path.join(file, filename)
with open(path, 'rb') as f:
data = f.read()
data += text.encode('utf-8')
with open(path, 'wb') as f2:
f2.write(data)
class TestSafeZipFile(TestCase, amo.tests.AMOPaths):
# TODO(andym): get full coverage for existing SafeZip methods, most
# is covered in the file viewer tests.
@patch.object(settings, 'FILE_UNZIP_SIZE_LIMIT', 5)
def test_unzip_limit(self):
with pytest.raises(forms.ValidationError):
SafeZip(self.xpi_path('langpack-localepicker'))
def test_unzip_fatal(self):
with pytest.raises(zipfile.BadZipFile):
SafeZip(self.xpi_path('search.xml'))
def test_read(self):
zip_file = SafeZip(self.xpi_path('langpack-localepicker'))
assert b'locale browser de' in zip_file.read('chrome.manifest')
def test_not_secure(self):
zip_file = SafeZip(self.xpi_path('extension'))
assert not zip_file.is_signed()
def test_is_secure(self):
zip_file = SafeZip(self.xpi_path('signed'))
assert zip_file.is_signed()
def test_is_broken(self):
zip_file = SafeZip(self.xpi_path('signed'))
zip_file.info_list[2].filename = 'META-INF/foo.sf'
assert not zip_file.is_signed()
| true | true |
f72c7105b40a75a34bc96103e54bc62ef812eb03 | 4,785 | py | Python | rapvis/rapvis_process.py | liuwell/rapvis | a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9 | [
"MIT"
] | 1 | 2020-10-25T10:23:45.000Z | 2020-10-25T10:23:45.000Z | rapvis/rapvis_process.py | liuwell/rapvis | a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9 | [
"MIT"
] | null | null | null | rapvis/rapvis_process.py | liuwell/rapvis | a69d06a31b1d7fe4510c1c90bfeee22b68a9b3b9 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import glob
import argparse
import numpy as np
import subprocess
import os
import time
import sys
#from rapvis_merge import merge_profiles, merge_gene_counts
#from rapvis_gene_dis import gene_dis
#from rapvis_quality import rRNAratio
from rapvis_general import current_time
import rapvis_rRNA
def process2(R1, R2, output, adapter, threads, libpath, mapper, minlen, trim5, counts, rRNA):
file_name = R1.split("/")[-1].split("_")[0]
outdir = os.path.join(output, file_name)
### make directory
if not os.path.exists(outdir):
try:
os.makedirs(outdir)
except Exception as e:
pass
prefix = os.path.join(outdir, file_name)
out_R1_p = prefix + "_R1.fq.gz"
out_R1_u = prefix + "_R1_unpaired.gz"
out_R2_p = prefix + "_R2.fq.gz"
out_R2_u = prefix + "_R2_unpaired.gz"
out_log = prefix + "_trimmomatic.log"
print("\n%s Processing: %s, %s" % (current_time(), R1,R2))
realpath = sys.path[0]
### trimmomatic
subprocess.call("trimmomatic PE -threads %d -phred33 %s %s %s %s %s %s ILLUMINACLIP:%s/../library/adapter/%s:1:30:10:5 SLIDINGWINDOW:4:20 MINLEN:%d HEADCROP:%d 2> %s" % (threads, R1, R2, out_R1_p, out_R1_u, out_R2_p, out_R2_u, realpath, adapter, minlen, trim5, out_log), shell=True)
### Mapping by hisat2
if mapper == 'hisat2':
SummaryFile = prefix + "_hisat_summary.txt"
MapOut = prefix + "_hisat_sort.bam"
subprocess.call("hisat2 -p %d -x %s/genome_tran -1 %s -2 %s -U %s,%s -t --dta --summary-file %s --new-summary|samtools sort -@ %d -m 10G -o %s" % (threads, libpath, out_R1_p, out_R2_p, out_R1_u, out_R2_u, SummaryFile, threads, MapOut), shell=True)
### Mapping by STAR
elif mapper == 'STAR':
STARprefix = prefix + "_STAR_"
subprocess.call("STAR --runThreadN %d --outSAMtype BAM SortedByCoordinate --genomeDir %s --readFilesIn %s %s --readFilesCommand zcat --outFileNamePrefix %s --quantMode GeneCounts --outFilterScoreMinOverLread 0.1 --outFilterMatchNminOverLread 0.1 --outFilterMatchNmin 0 --outFilterMismatchNmax 2" % (threads, libpath, out_R1_p, out_R2_p, STARprefix), shell=True)
MapOut = prefix + "_STAR_Aligned.sortedByCoord.out.bam" ## sorted bam file
### Asemble by stringtie
print("%s Asemble ..." % current_time())
stringtieGTF = prefix + '_stringtie.gtf'
stringtieGene = prefix + '_gene_abund.tab'
subprocess.call("stringtie %s -e -G %s/annotation.gtf -p %d -o %s -A %s" % (MapOut, libpath, threads, stringtieGTF, stringtieGene), shell=True)
### Gene counts
if counts:
countOut = prefix + '_gene_counts.txt'
subprocess.call("featureCounts -a %s/annotation.gtf -o %s %s -t exon -g gene_name -T %d -Q 30 -p" % (libpath, countOut, MapOut, threads), shell=True)
### rRNA
if rRNA:
rapvis_rRNA.rRNA(R1, R2, output, threads)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A tool for RNAseq processing and visualization')
parser.add_argument('-R1', required=True, help='the input data R1')
parser.add_argument('-R2', required=True, help='the input data R2')
parser.add_argument('-o', '--output', default = 'processed_data', help = 'output directory (default: processed_data)')
parser.add_argument('-p', '--threads', default=5, type=int, help='number of threads (CPUs) to use (default: 5)')
#parser.add_argument('-s', '--species', default='Human', choices=['Human', 'Mouse', 'Rat', 'Rabbit', 'GoldenHamster', 'Zebrafish'], type=str, help='choose reference species for mapping and annotaion (default: Human)')
parser.add_argument('-lib', '--libraryPath', type=str, help='choose reference species for mapping and annotaion')
parser.add_argument('-m', '--mapper', default='hisat2', choices=['hisat2', 'STAR'], type=str, help='choose the mapping program (default: hisat2)')
parser.add_argument('-a', '--adapter', default='nextera', type=str, help='choose illumina adaptor (default: nextera), choices {nextera, universal, pAAAAA}')
parser.add_argument('--minlen', default=35, type=int, help='discard reads shorter than LEN (default: 35)')
parser.add_argument('--trim5', default=0, type=int, help='remove bases from the begining of each read (default:0)')
parser.add_argument('--counts', action='store_true', help='Get gene counts')
parser.add_argument('--rRNA', action='store_true', help='whether mapping to rRNA(Human)')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.2')
args = parser.parse_args()
#print("\n%s ..... Start RNAseq processing" % (current_time()))
#start_time = time.time()
process2(args.R1, args.R2, args.output, args.adapter, args.threads, args.libraryPath, args.mapper, args.minlen, args.trim5, args.counts, args.rRNA)
###
#end_time = time.time()
#run_time = round((end_time - start_time)/60, 5)
#print("\n%s ..... Finished all. Used time: %s m\n" % (current_time(), run_time))
| 47.376238 | 366 | 0.708255 |
import glob
import argparse
import numpy as np
import subprocess
import os
import time
import sys
from rapvis_general import current_time
import rapvis_rRNA
def process2(R1, R2, output, adapter, threads, libpath, mapper, minlen, trim5, counts, rRNA):
file_name = R1.split("/")[-1].split("_")[0]
outdir = os.path.join(output, file_name)
try:
os.makedirs(outdir)
except Exception as e:
pass
prefix = os.path.join(outdir, file_name)
out_R1_p = prefix + "_R1.fq.gz"
out_R1_u = prefix + "_R1_unpaired.gz"
out_R2_p = prefix + "_R2.fq.gz"
out_R2_u = prefix + "_R2_unpaired.gz"
out_log = prefix + "_trimmomatic.log"
print("\n%s Processing: %s, %s" % (current_time(), R1,R2))
realpath = sys.path[0]
tic PE -threads %d -phred33 %s %s %s %s %s %s ILLUMINACLIP:%s/../library/adapter/%s:1:30:10:5 SLIDINGWINDOW:4:20 MINLEN:%d HEADCROP:%d 2> %s" % (threads, R1, R2, out_R1_p, out_R1_u, out_R2_p, out_R2_u, realpath, adapter, minlen, trim5, out_log), shell=True)
= prefix + "_hisat_summary.txt"
MapOut = prefix + "_hisat_sort.bam"
subprocess.call("hisat2 -p %d -x %s/genome_tran -1 %s -2 %s -U %s,%s -t --dta --summary-file %s --new-summary|samtools sort -@ %d -m 10G -o %s" % (threads, libpath, out_R1_p, out_R2_p, out_R1_u, out_R2_u, SummaryFile, threads, MapOut), shell=True)
ix = prefix + "_STAR_"
subprocess.call("STAR --runThreadN %d --outSAMtype BAM SortedByCoordinate --genomeDir %s --readFilesIn %s %s --readFilesCommand zcat --outFileNamePrefix %s --quantMode GeneCounts --outFilterScoreMinOverLread 0.1 --outFilterMatchNminOverLread 0.1 --outFilterMatchNmin 0 --outFilterMismatchNmax 2" % (threads, libpath, out_R1_p, out_R2_p, STARprefix), shell=True)
MapOut = prefix + "_STAR_Aligned.sortedByCoord.out.bam" = prefix + '_stringtie.gtf'
stringtieGene = prefix + '_gene_abund.tab'
subprocess.call("stringtie %s -e -G %s/annotation.gtf -p %d -o %s -A %s" % (MapOut, libpath, threads, stringtieGTF, stringtieGene), shell=True)
refix + '_gene_counts.txt'
subprocess.call("featureCounts -a %s/annotation.gtf -o %s %s -t exon -g gene_name -T %d -Q 30 -p" % (libpath, countOut, MapOut, threads), shell=True)
rapvis_rRNA.rRNA(R1, R2, output, threads)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A tool for RNAseq processing and visualization')
parser.add_argument('-R1', required=True, help='the input data R1')
parser.add_argument('-R2', required=True, help='the input data R2')
parser.add_argument('-o', '--output', default = 'processed_data', help = 'output directory (default: processed_data)')
parser.add_argument('-p', '--threads', default=5, type=int, help='number of threads (CPUs) to use (default: 5)')
parser.add_argument('-lib', '--libraryPath', type=str, help='choose reference species for mapping and annotaion')
parser.add_argument('-m', '--mapper', default='hisat2', choices=['hisat2', 'STAR'], type=str, help='choose the mapping program (default: hisat2)')
parser.add_argument('-a', '--adapter', default='nextera', type=str, help='choose illumina adaptor (default: nextera), choices {nextera, universal, pAAAAA}')
parser.add_argument('--minlen', default=35, type=int, help='discard reads shorter than LEN (default: 35)')
parser.add_argument('--trim5', default=0, type=int, help='remove bases from the begining of each read (default:0)')
parser.add_argument('--counts', action='store_true', help='Get gene counts')
parser.add_argument('--rRNA', action='store_true', help='whether mapping to rRNA(Human)')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.2')
args = parser.parse_args()
process2(args.R1, args.R2, args.output, args.adapter, args.threads, args.libraryPath, args.mapper, args.minlen, args.trim5, args.counts, args.rRNA)
| true | true |
f72c731f3e730de450ee248c0486bff1226a032a | 322 | py | Python | bin/gen-nfs-fstab.py | french-tries/auto-distro | bd2fccd7862f97b0f91e742b3c53af045b0a4475 | [
"MIT"
] | null | null | null | bin/gen-nfs-fstab.py | french-tries/auto-distro | bd2fccd7862f97b0f91e742b3c53af045b0a4475 | [
"MIT"
] | null | null | null | bin/gen-nfs-fstab.py | french-tries/auto-distro | bd2fccd7862f97b0f91e742b3c53af045b0a4475 | [
"MIT"
] | null | null | null | import os
import configuration
output = '/etc/fstab'
with open(output, mode='a') as fstab:
fstab.write('\n\n')
for entry in configuration.nfs_entries:
os.makedirs(entry[1], exist_ok=True)
fstab.write(entry[0].ljust(50) + entry[1].ljust(40) + 'nfs'.ljust(10) + 'noauto'.ljust(30) + '0 0\n')
| 24.769231 | 109 | 0.630435 | import os
import configuration
output = '/etc/fstab'
with open(output, mode='a') as fstab:
fstab.write('\n\n')
for entry in configuration.nfs_entries:
os.makedirs(entry[1], exist_ok=True)
fstab.write(entry[0].ljust(50) + entry[1].ljust(40) + 'nfs'.ljust(10) + 'noauto'.ljust(30) + '0 0\n')
| true | true |
f72c73488e94790062a1acf9156e490fc7770946 | 7,753 | py | Python | sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/datalakeanalytics/compute_policy.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ._enums import *
__all__ = ['ComputePolicy']
class ComputePolicy(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
compute_policy_name: Optional[pulumi.Input[str]] = None,
max_degree_of_parallelism_per_job: Optional[pulumi.Input[int]] = None,
min_priority_per_job: Optional[pulumi.Input[int]] = None,
object_id: Optional[pulumi.Input[str]] = None,
object_type: Optional[pulumi.Input[Union[str, 'AADObjectType']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Data Lake Analytics compute policy information.
API Version: 2016-11-01.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: The name of the Data Lake Analytics account.
:param pulumi.Input[str] compute_policy_name: The name of the compute policy to create or update.
:param pulumi.Input[int] max_degree_of_parallelism_per_job: The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed.
:param pulumi.Input[int] min_priority_per_job: The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed.
:param pulumi.Input[str] object_id: The AAD object identifier for the entity to create a policy for.
:param pulumi.Input[Union[str, 'AADObjectType']] object_type: The type of AAD object the object identifier refers to.
:param pulumi.Input[str] resource_group_name: The name of the Azure resource group.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if account_name is None and not opts.urn:
raise TypeError("Missing required property 'account_name'")
__props__['account_name'] = account_name
__props__['compute_policy_name'] = compute_policy_name
__props__['max_degree_of_parallelism_per_job'] = max_degree_of_parallelism_per_job
__props__['min_priority_per_job'] = min_priority_per_job
if object_id is None and not opts.urn:
raise TypeError("Missing required property 'object_id'")
__props__['object_id'] = object_id
if object_type is None and not opts.urn:
raise TypeError("Missing required property 'object_type'")
__props__['object_type'] = object_type
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datalakeanalytics:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20161101:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20161101:ComputePolicy")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ComputePolicy, __self__).__init__(
'azure-native:datalakeanalytics:ComputePolicy',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'ComputePolicy':
"""
Get an existing ComputePolicy resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["max_degree_of_parallelism_per_job"] = None
__props__["min_priority_per_job"] = None
__props__["name"] = None
__props__["object_id"] = None
__props__["object_type"] = None
__props__["type"] = None
return ComputePolicy(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="maxDegreeOfParallelismPerJob")
def max_degree_of_parallelism_per_job(self) -> pulumi.Output[int]:
"""
The maximum degree of parallelism per job this user can use to submit jobs.
"""
return pulumi.get(self, "max_degree_of_parallelism_per_job")
@property
@pulumi.getter(name="minPriorityPerJob")
def min_priority_per_job(self) -> pulumi.Output[int]:
"""
The minimum priority per job this user can use to submit jobs.
"""
return pulumi.get(self, "min_priority_per_job")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="objectId")
def object_id(self) -> pulumi.Output[str]:
"""
The AAD object identifier for the entity to create a policy for.
"""
return pulumi.get(self, "object_id")
@property
@pulumi.getter(name="objectType")
def object_type(self) -> pulumi.Output[str]:
"""
The type of AAD object the object identifier refers to.
"""
return pulumi.get(self, "object_type")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The resource type.
"""
return pulumi.get(self, "type")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 47.564417 | 601 | 0.665549 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ._enums import *
__all__ = ['ComputePolicy']
class ComputePolicy(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
compute_policy_name: Optional[pulumi.Input[str]] = None,
max_degree_of_parallelism_per_job: Optional[pulumi.Input[int]] = None,
min_priority_per_job: Optional[pulumi.Input[int]] = None,
object_id: Optional[pulumi.Input[str]] = None,
object_type: Optional[pulumi.Input[Union[str, 'AADObjectType']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if account_name is None and not opts.urn:
raise TypeError("Missing required property 'account_name'")
__props__['account_name'] = account_name
__props__['compute_policy_name'] = compute_policy_name
__props__['max_degree_of_parallelism_per_job'] = max_degree_of_parallelism_per_job
__props__['min_priority_per_job'] = min_priority_per_job
if object_id is None and not opts.urn:
raise TypeError("Missing required property 'object_id'")
__props__['object_id'] = object_id
if object_type is None and not opts.urn:
raise TypeError("Missing required property 'object_type'")
__props__['object_type'] = object_type
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:datalakeanalytics:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/latest:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20151001preview:ComputePolicy"), pulumi.Alias(type_="azure-native:datalakeanalytics/v20161101:ComputePolicy"), pulumi.Alias(type_="azure-nextgen:datalakeanalytics/v20161101:ComputePolicy")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ComputePolicy, __self__).__init__(
'azure-native:datalakeanalytics:ComputePolicy',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'ComputePolicy':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["max_degree_of_parallelism_per_job"] = None
__props__["min_priority_per_job"] = None
__props__["name"] = None
__props__["object_id"] = None
__props__["object_type"] = None
__props__["type"] = None
return ComputePolicy(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="maxDegreeOfParallelismPerJob")
def max_degree_of_parallelism_per_job(self) -> pulumi.Output[int]:
return pulumi.get(self, "max_degree_of_parallelism_per_job")
@property
@pulumi.getter(name="minPriorityPerJob")
def min_priority_per_job(self) -> pulumi.Output[int]:
return pulumi.get(self, "min_priority_per_job")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="objectId")
def object_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "object_id")
@property
@pulumi.getter(name="objectType")
def object_type(self) -> pulumi.Output[str]:
return pulumi.get(self, "object_type")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| true | true |
f72c7352f5956d525aae8e8f597fdae21fe13578 | 547 | py | Python | examples/get_server_info.py | edvinerikson/frostbite-rcon-utils | 089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3 | [
"MIT"
] | 7 | 2016-10-10T08:21:15.000Z | 2022-03-12T23:45:24.000Z | examples/get_server_info.py | EdvinErikson/frostbite-rcon-utils | 089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3 | [
"MIT"
] | 2 | 2016-02-18T16:11:48.000Z | 2016-02-18T17:24:14.000Z | examples/get_server_info.py | EdvinErikson/frostbite-rcon-utils | 089e1a59b7fcd72b8d8d3153fb396cfd8d4869f3 | [
"MIT"
] | 2 | 2016-02-17T22:14:47.000Z | 2016-08-13T01:52:32.000Z | import socket
from frostbite_rcon_utils import create_packet, encode_packet, decode_packet, contains_complete_packet
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.settimeout(1)
connection.connect(('188.126.64.4', 47215))
connection.setblocking(1)
packet_to_send = encode_packet(create_packet(0, False, False, ['serverInfo']))
connection.send(packet_to_send)
data_buffer = ""
while not contains_complete_packet(data_buffer):
data_buffer += connection.recv(2048)
packet = decode_packet(data_buffer)
print(packet) | 30.388889 | 102 | 0.8117 | import socket
from frostbite_rcon_utils import create_packet, encode_packet, decode_packet, contains_complete_packet
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.settimeout(1)
connection.connect(('188.126.64.4', 47215))
connection.setblocking(1)
packet_to_send = encode_packet(create_packet(0, False, False, ['serverInfo']))
connection.send(packet_to_send)
data_buffer = ""
while not contains_complete_packet(data_buffer):
data_buffer += connection.recv(2048)
packet = decode_packet(data_buffer)
print(packet) | true | true |
f72c73592fff23ee5fe753971e6446fe835d7fc5 | 1,158 | py | Python | sympy/strategies/branch/tests/test_traverse.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 1 | 2016-02-22T22:46:50.000Z | 2016-02-22T22:46:50.000Z | sympy/strategies/branch/tests/test_traverse.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 7 | 2017-05-01T14:15:32.000Z | 2017-09-06T20:44:24.000Z | sympy/strategies/branch/tests/test_traverse.py | ovolve/sympy | 0a15782f20505673466b940454b33b8014a25c13 | [
"BSD-3-Clause"
] | 1 | 2020-09-09T15:20:27.000Z | 2020-09-09T15:20:27.000Z | from sympy import Basic
from sympy.strategies.branch.traverse import top_down, sall
from sympy.strategies.branch.core import do_one, identity
def inc(x):
if isinstance(x, int):
yield x + 1
def test_top_down_easy():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_big_tree():
expr = Basic(1, Basic(2), Basic(3, Basic(4), 5))
expected = Basic(2, Basic(3), Basic(4, Basic(5), 6))
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_harder_function():
def split5(x):
if x == 5:
yield x - 1
yield x + 1
expr = Basic(Basic(5, 6), 1)
expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)])
brl = top_down(split5)
assert set(brl(expr)) == expected
def test_sall():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = sall(inc)
assert list(brl(expr)) == [expected]
expr = Basic(1, 2, Basic(3, 4))
expected = Basic(2, 3, Basic(3, 4))
brl = sall(do_one(inc, identity))
assert list(brl(expr)) == [expected]
| 24.638298 | 66 | 0.58981 | from sympy import Basic
from sympy.strategies.branch.traverse import top_down, sall
from sympy.strategies.branch.core import do_one, identity
def inc(x):
if isinstance(x, int):
yield x + 1
def test_top_down_easy():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_big_tree():
expr = Basic(1, Basic(2), Basic(3, Basic(4), 5))
expected = Basic(2, Basic(3), Basic(4, Basic(5), 6))
brl = top_down(inc)
assert set(brl(expr)) == set([expected])
def test_top_down_harder_function():
def split5(x):
if x == 5:
yield x - 1
yield x + 1
expr = Basic(Basic(5, 6), 1)
expected = set([Basic(Basic(4, 6), 1), Basic(Basic(6, 6), 1)])
brl = top_down(split5)
assert set(brl(expr)) == expected
def test_sall():
expr = Basic(1, 2)
expected = Basic(2, 3)
brl = sall(inc)
assert list(brl(expr)) == [expected]
expr = Basic(1, 2, Basic(3, 4))
expected = Basic(2, 3, Basic(3, 4))
brl = sall(do_one(inc, identity))
assert list(brl(expr)) == [expected]
| true | true |
f72c73b22f0837188e5fc58d0e9f23032e5dba90 | 2,695 | py | Python | data/p4VQE/R4/benchmark/startQiskit_QC277.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p4VQE/R4/benchmark/startQiskit_QC277.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | data/p4VQE/R4/benchmark/startQiskit_QC277.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=3
# total number=15
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.cx(input_qubit[0],input_qubit[2]) # number=9
prog.x(input_qubit[2]) # number=10
prog.h(input_qubit[2]) # number=12
prog.cz(input_qubit[0],input_qubit[2]) # number=13
prog.h(input_qubit[2]) # number=14
prog.h(input_qubit[3]) # number=4
prog.y(input_qubit[3]) # number=5
for edge in E:
k = edge[0]
l = edge[1]
prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])
prog.p(gamma, k)
prog.p(gamma, l)
prog.rx(2 * beta, range(len(V)))
prog.cx(input_qubit[1],input_qubit[0]) # number=7
prog.cx(input_qubit[1],input_qubit[0]) # number=8
# circuit end
return prog
if __name__ == '__main__':
n = 4
V = np.arange(0, n, 1)
E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_weighted_edges_from(E)
step_size = 0.1
a_gamma = np.arange(0, np.pi, step_size)
a_beta = np.arange(0, np.pi, step_size)
a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)
F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (
1 + np.cos(4 * a_gamma) ** 2)
result = np.where(F1 == np.amax(F1))
a = list(zip(result[0], result[1]))[0]
gamma = a[0] * step_size
beta = a[1] * step_size
prog = make_circuit(4)
sample_shot =5600
writefile = open("../data/startQiskit_QC277.csv", "w")
# prog.draw('mpl', filename=(kernel + '.png'))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend("ibmq_5_yorktown")
circuit1 = transpile(prog, FakeYorktown())
circuit1.measure_all()
prog = circuit1
info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
| 28.072917 | 118 | 0.636735 |
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def make_circuit(n:int) -> QuantumCircuit:
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0])
prog.h(input_qubit[1])
prog.h(input_qubit[2])
prog.cx(input_qubit[0],input_qubit[2])
prog.x(input_qubit[2])
prog.h(input_qubit[2])
prog.cz(input_qubit[0],input_qubit[2])
prog.h(input_qubit[2])
prog.h(input_qubit[3])
prog.y(input_qubit[3])
for edge in E:
k = edge[0]
l = edge[1]
prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])
prog.p(gamma, k)
prog.p(gamma, l)
prog.rx(2 * beta, range(len(V)))
prog.cx(input_qubit[1],input_qubit[0])
prog.cx(input_qubit[1],input_qubit[0])
return prog
if __name__ == '__main__':
n = 4
V = np.arange(0, n, 1)
E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_weighted_edges_from(E)
step_size = 0.1
a_gamma = np.arange(0, np.pi, step_size)
a_beta = np.arange(0, np.pi, step_size)
a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)
F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (
1 + np.cos(4 * a_gamma) ** 2)
result = np.where(F1 == np.amax(F1))
a = list(zip(result[0], result[1]))[0]
gamma = a[0] * step_size
beta = a[1] * step_size
prog = make_circuit(4)
sample_shot =5600
writefile = open("../data/startQiskit_QC277.csv", "w")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend("ibmq_5_yorktown")
circuit1 = transpile(prog, FakeYorktown())
circuit1.measure_all()
prog = circuit1
info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
| true | true |
f72c757fb6a92103d778c73856fcee6786544a37 | 6,342 | py | Python | test/test_conventions.py | takluyver/xray | 80c30ae343a2171c541da0387fed3926004030a7 | [
"Apache-2.0"
] | null | null | null | test/test_conventions.py | takluyver/xray | 80c30ae343a2171c541da0387fed3926004030a7 | [
"Apache-2.0"
] | null | null | null | test/test_conventions.py | takluyver/xray | 80c30ae343a2171c541da0387fed3926004030a7 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import pandas as pd
from datetime import datetime
import warnings
from xray import conventions
from . import TestCase, requires_netCDF4
class TestMaskedAndScaledArray(TestCase):
def test(self):
x = conventions.MaskedAndScaledArray(np.arange(3), fill_value=0)
self.assertEqual(x.dtype, np.dtype('float'))
self.assertEqual(x.shape, (3,))
self.assertEqual(x.size, 3)
self.assertEqual(x.ndim, 1)
self.assertEqual(len(x), 3)
self.assertArrayEqual([np.nan, 1, 2], x)
x = conventions.MaskedAndScaledArray(np.arange(3), add_offset=1)
self.assertArrayEqual(np.arange(3) + 1, x)
x = conventions.MaskedAndScaledArray(np.arange(3), scale_factor=2)
self.assertArrayEqual(2 * np.arange(3), x)
x = conventions.MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), -99, 0.01, 1)
expected = np.array([np.nan, 0.99, 1, 1.01, 1.02])
self.assertArrayEqual(expected, x)
def test_0d(self):
x = conventions.MaskedAndScaledArray(np.array(0), fill_value=0)
self.assertTrue(np.isnan(x))
self.assertTrue(np.isnan(x[...]))
x = conventions.MaskedAndScaledArray(np.array(0), fill_value=10)
self.assertEqual(0, x[...])
class TestCharToStringArray(TestCase):
def test(self):
array = np.array(list('abc'))
actual = conventions.CharToStringArray(array)
expected = np.array('abc')
self.assertEqual(actual.dtype, expected.dtype)
self.assertEqual(actual.shape, expected.shape)
self.assertEqual(actual.size, expected.size)
self.assertEqual(actual.ndim, expected.ndim)
with self.assertRaises(TypeError):
len(actual)
self.assertArrayEqual(expected, actual)
with self.assertRaises(IndexError):
actual[:2]
self.assertEqual(str(actual), 'abc')
array = np.array([list('abc'), list('cdf')])
actual = conventions.CharToStringArray(array)
expected = np.array(['abc', 'cdf'])
self.assertEqual(actual.dtype, expected.dtype)
self.assertEqual(actual.shape, expected.shape)
self.assertEqual(actual.size, expected.size)
self.assertEqual(actual.ndim, expected.ndim)
self.assertEqual(len(actual), len(expected))
self.assertArrayEqual(expected, actual)
self.assertArrayEqual(expected[:1], actual[:1])
with self.assertRaises(IndexError):
actual[:, :2]
class TestDatetime(TestCase):
@requires_netCDF4
def test_cf_datetime(self):
import netCDF4 as nc4
for num_dates, units in [
(np.arange(100), 'days since 2000-01-01'),
(np.arange(100).reshape(10, 10), 'days since 2000-01-01'),
(12300 + np.arange(50), 'hours since 1680-01-01 00:00:00'),
(10, 'days since 2000-01-01'),
([10], 'days since 2000-01-01'),
([[10]], 'days since 2000-01-01'),
([10, 10], 'days since 2000-01-01'),
(0, 'days since 1000-01-01'),
([0], 'days since 1000-01-01'),
([[0]], 'days since 1000-01-01'),
(np.arange(20), 'days since 1000-01-01'),
(np.arange(0, 100000, 10000), 'days since 1900-01-01')
]:
for calendar in ['standard', 'gregorian', 'proleptic_gregorian']:
expected = nc4.num2date(num_dates, units, calendar)
actual = conventions.decode_cf_datetime(num_dates, units, calendar)
if (isinstance(actual, np.ndarray)
and np.issubdtype(actual.dtype, np.datetime64)):
self.assertEqual(actual.dtype, np.dtype('M8[ns]'))
# For some reason, numpy 1.8 does not compare ns precision
# datetime64 arrays as equal to arrays of datetime objects,
# but it works for us precision. Thus, convert to us
# precision for the actual array equal comparison...
actual_cmp = actual.astype('M8[us]')
else:
actual_cmp = actual
self.assertArrayEqual(expected, actual_cmp)
encoded, _, _ = conventions.encode_cf_datetime(actual, units, calendar)
self.assertArrayEqual(num_dates, np.around(encoded))
if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1
and '1000' not in units):
# verify that wrapping with a pandas.Index works
# note that it *does not* currently work to even put
# non-datetime64 compatible dates into a pandas.Index :(
encoded, _, _ = conventions.encode_cf_datetime(
pd.Index(actual), units, calendar)
self.assertArrayEqual(num_dates, np.around(encoded))
@requires_netCDF4
def test_cf_datetime_nan(self):
for num_dates, units, expected_list in [
([np.nan], 'days since 2000-01-01', ['NaT']),
([np.nan, 0], 'days since 2000-01-01',
['NaT', '2000-01-01T00:00:00Z']),
([np.nan, 0, 1], 'days since 2000-01-01',
['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']),
]:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'All-NaN')
actual = conventions.decode_cf_datetime(num_dates, units)
expected = np.array(expected_list, dtype='datetime64[ns]')
self.assertArrayEqual(expected, actual)
def test_guess_time_units(self):
for dates, expected in [(pd.date_range('1900-01-01', periods=5),
'days since 1900-01-01 00:00:00'),
(pd.date_range('1900-01-01 12:00:00', freq='H',
periods=2),
'hours since 1900-01-01 12:00:00'),
(['1900-01-01', '1900-01-02',
'1900-01-02 00:00:01'],
'seconds since 1900-01-01 00:00:00')]:
self.assertEquals(expected, conventions.guess_time_units(dates))
| 46.291971 | 88 | 0.564018 | import numpy as np
import pandas as pd
from datetime import datetime
import warnings
from xray import conventions
from . import TestCase, requires_netCDF4
class TestMaskedAndScaledArray(TestCase):
def test(self):
x = conventions.MaskedAndScaledArray(np.arange(3), fill_value=0)
self.assertEqual(x.dtype, np.dtype('float'))
self.assertEqual(x.shape, (3,))
self.assertEqual(x.size, 3)
self.assertEqual(x.ndim, 1)
self.assertEqual(len(x), 3)
self.assertArrayEqual([np.nan, 1, 2], x)
x = conventions.MaskedAndScaledArray(np.arange(3), add_offset=1)
self.assertArrayEqual(np.arange(3) + 1, x)
x = conventions.MaskedAndScaledArray(np.arange(3), scale_factor=2)
self.assertArrayEqual(2 * np.arange(3), x)
x = conventions.MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), -99, 0.01, 1)
expected = np.array([np.nan, 0.99, 1, 1.01, 1.02])
self.assertArrayEqual(expected, x)
def test_0d(self):
x = conventions.MaskedAndScaledArray(np.array(0), fill_value=0)
self.assertTrue(np.isnan(x))
self.assertTrue(np.isnan(x[...]))
x = conventions.MaskedAndScaledArray(np.array(0), fill_value=10)
self.assertEqual(0, x[...])
class TestCharToStringArray(TestCase):
def test(self):
array = np.array(list('abc'))
actual = conventions.CharToStringArray(array)
expected = np.array('abc')
self.assertEqual(actual.dtype, expected.dtype)
self.assertEqual(actual.shape, expected.shape)
self.assertEqual(actual.size, expected.size)
self.assertEqual(actual.ndim, expected.ndim)
with self.assertRaises(TypeError):
len(actual)
self.assertArrayEqual(expected, actual)
with self.assertRaises(IndexError):
actual[:2]
self.assertEqual(str(actual), 'abc')
array = np.array([list('abc'), list('cdf')])
actual = conventions.CharToStringArray(array)
expected = np.array(['abc', 'cdf'])
self.assertEqual(actual.dtype, expected.dtype)
self.assertEqual(actual.shape, expected.shape)
self.assertEqual(actual.size, expected.size)
self.assertEqual(actual.ndim, expected.ndim)
self.assertEqual(len(actual), len(expected))
self.assertArrayEqual(expected, actual)
self.assertArrayEqual(expected[:1], actual[:1])
with self.assertRaises(IndexError):
actual[:, :2]
class TestDatetime(TestCase):
@requires_netCDF4
def test_cf_datetime(self):
import netCDF4 as nc4
for num_dates, units in [
(np.arange(100), 'days since 2000-01-01'),
(np.arange(100).reshape(10, 10), 'days since 2000-01-01'),
(12300 + np.arange(50), 'hours since 1680-01-01 00:00:00'),
(10, 'days since 2000-01-01'),
([10], 'days since 2000-01-01'),
([[10]], 'days since 2000-01-01'),
([10, 10], 'days since 2000-01-01'),
(0, 'days since 1000-01-01'),
([0], 'days since 1000-01-01'),
([[0]], 'days since 1000-01-01'),
(np.arange(20), 'days since 1000-01-01'),
(np.arange(0, 100000, 10000), 'days since 1900-01-01')
]:
for calendar in ['standard', 'gregorian', 'proleptic_gregorian']:
expected = nc4.num2date(num_dates, units, calendar)
actual = conventions.decode_cf_datetime(num_dates, units, calendar)
if (isinstance(actual, np.ndarray)
and np.issubdtype(actual.dtype, np.datetime64)):
self.assertEqual(actual.dtype, np.dtype('M8[ns]'))
actual_cmp = actual.astype('M8[us]')
else:
actual_cmp = actual
self.assertArrayEqual(expected, actual_cmp)
encoded, _, _ = conventions.encode_cf_datetime(actual, units, calendar)
self.assertArrayEqual(num_dates, np.around(encoded))
if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1
and '1000' not in units):
encoded, _, _ = conventions.encode_cf_datetime(
pd.Index(actual), units, calendar)
self.assertArrayEqual(num_dates, np.around(encoded))
@requires_netCDF4
def test_cf_datetime_nan(self):
for num_dates, units, expected_list in [
([np.nan], 'days since 2000-01-01', ['NaT']),
([np.nan, 0], 'days since 2000-01-01',
['NaT', '2000-01-01T00:00:00Z']),
([np.nan, 0, 1], 'days since 2000-01-01',
['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']),
]:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'All-NaN')
actual = conventions.decode_cf_datetime(num_dates, units)
expected = np.array(expected_list, dtype='datetime64[ns]')
self.assertArrayEqual(expected, actual)
def test_guess_time_units(self):
for dates, expected in [(pd.date_range('1900-01-01', periods=5),
'days since 1900-01-01 00:00:00'),
(pd.date_range('1900-01-01 12:00:00', freq='H',
periods=2),
'hours since 1900-01-01 12:00:00'),
(['1900-01-01', '1900-01-02',
'1900-01-02 00:00:01'],
'seconds since 1900-01-01 00:00:00')]:
self.assertEquals(expected, conventions.guess_time_units(dates))
| true | true |
f72c7674672d02999eb1ca6e63915c7fe5ac8ab5 | 57 | py | Python | Exp2/Strategy/StrategyManager.py | inventivejon/INPROLA-Python | 8aab11a868b37a64c46e6287bf358b5b05673a28 | [
"Apache-2.0"
] | null | null | null | Exp2/Strategy/StrategyManager.py | inventivejon/INPROLA-Python | 8aab11a868b37a64c46e6287bf358b5b05673a28 | [
"Apache-2.0"
] | null | null | null | Exp2/Strategy/StrategyManager.py | inventivejon/INPROLA-Python | 8aab11a868b37a64c46e6287bf358b5b05673a28 | [
"Apache-2.0"
] | null | null | null | class StrategyManager():
def __init__():
pass | 19 | 24 | 0.614035 | class StrategyManager():
def __init__():
pass | true | true |
f72c7888070e1278b4c5a0b55319ce31c0795378 | 23,442 | py | Python | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | 4 | 2018-07-04T17:20:12.000Z | 2019-07-14T18:07:25.000Z | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | null | null | null | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/sympy/printing/octave.py | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | 1 | 2018-09-03T03:02:06.000Z | 2018-09-03T03:02:06.000Z | """
Octave (and Matlab) code printer
The `OctaveCodePrinter` converts SymPy expressions into Octave expressions.
It uses a subset of the Octave language for Matlab compatibility.
A complete code generator, which uses `octave_code` extensively, can be found
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
complete source code files.
"""
from __future__ import print_function, division
from sympy.core import Mul, Pow, S, Rational
from sympy.core.compatibility import string_types, range
from sympy.core.mul import _keep_coeff
from sympy.codegen.ast import Assignment
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence
from re import search
# List of known functions. First, those that have the same name in
# SymPy and Octave. This is almost certainly incomplete!
known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
"asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
"sinh", "cosh", "tanh", "coth", "csch", "sech",
"asinh", "acosh", "atanh", "acoth", "asech", "acsch",
"erfc", "erfi", "erf", "erfinv", "erfcinv",
"besseli", "besselj", "besselk", "bessely",
"exp", "factorial", "floor", "fresnelc", "fresnels",
"gamma", "log", "polylog", "sign", "zeta"]
# These functions have different names ("Sympy": "Octave"), more
# generally a mapping to (argument_conditions, octave_function).
known_fcns_src2 = {
"Abs": "abs",
"ceiling": "ceil",
"Chi": "coshint",
"Ci": "cosint",
"conjugate": "conj",
"DiracDelta": "dirac",
"Heaviside": "heaviside",
"laguerre": "laguerreL",
"li": "logint",
"loggamma": "gammaln",
"polygamma": "psi",
"Shi": "sinhint",
"Si": "sinint",
}
class OctaveCodePrinter(CodePrinter):
"""
A printer to convert expressions to strings of Octave/Matlab code.
"""
printmethod = "_octave"
language = "Octave"
_operators = {
'and': '&',
'or': '|',
'not': '~',
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 16,
'user_functions': {},
'human': True,
'contract': True,
'inline': True,
}
# Note: contract is for expressing tensors as loops (if True), or just
# assignment (if False). FIXME: this should be looked a more carefully
# for Octave.
def __init__(self, settings={}):
super(OctaveCodePrinter, self).__init__(settings)
self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
self.known_functions.update(dict(known_fcns_src2))
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "% {0}".format(text)
def _declare_number_const(self, name, value):
return "{0} = {1};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
# Octave uses Fortran order (column-major)
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
# Octave arrays start at 1 and end at dimension
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("for %s = %s:%s" % (var, start, stop))
close_lines.append("end")
return open_lines, close_lines
def _print_Mul(self, expr):
# print complex numbers nicely in Octave
if (expr.is_number and expr.is_imaginary and
expr.as_coeff_Mul()[0].is_integer):
return "%si" % self._print(-S.ImaginaryUnit*expr)
# cribbed from str.py
prec = precedence(expr)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = [] # items in the numerator
b = [] # items that are in the denominator (if any)
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
# use make_args in case expr was something like -x -> x
args = Mul.make_args(expr)
# Gather args for numerator/denominator
for item in args:
if (item.is_commutative and item.is_Pow and item.exp.is_Rational
and item.exp.is_negative):
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append(Rational(item.p))
if item.q != 1:
b.append(Rational(item.q))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec) for x in a]
b_str = [self.parenthesize(x, prec) for x in b]
# from here it differs from str.py to deal with "*" and ".*"
def multjoin(a, a_str):
# here we probably are assuming the constants will come first
r = a_str[0]
for i in range(1, len(a)):
mulsym = '*' if a[i-1].is_number else '.*'
r = r + mulsym + a_str[i]
return r
if len(b) == 0:
return sign + multjoin(a, a_str)
elif len(b) == 1:
divsym = '/' if b[0].is_number else './'
return sign + multjoin(a, a_str) + divsym + b_str[0]
else:
divsym = '/' if all([bi.is_number for bi in b]) else './'
return (sign + multjoin(a, a_str) +
divsym + "(%s)" % multjoin(b, b_str))
def _print_Pow(self, expr):
powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^'
PREC = precedence(expr)
if expr.exp == S.Half:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if expr.exp == -S.Half:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "sqrt(%s)" % self._print(expr.base)
if expr.exp == -S.One:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
self.parenthesize(expr.exp, PREC))
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_Pi(self, expr):
return 'pi'
def _print_ImaginaryUnit(self, expr):
return "1i"
def _print_Exp1(self, expr):
return "exp(1)"
def _print_GoldenRatio(self, expr):
# FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
#return self._print((1+sqrt(S(5)))/2)
return "(1+sqrt(5))/2"
def _print_NumberSymbol(self, expr):
if self._settings["inline"]:
return self._print(expr.evalf(self._settings["precision"]))
else:
# assign to a variable, perhaps more readable for longer program
return super(OctaveCodePrinter, self)._print_NumberSymbol(expr)
def _print_Assignment(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
from sympy.tensor.indexed import IndexedBase
# Copied from codeprinter, but remove special MatrixSymbol treatment
lhs = expr.lhs
rhs = expr.rhs
# We special case assignments that take multiple lines
if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
# Here we modify Piecewise so each expression is now
# an Assignment, and then continue on the print.
expressions = []
conditions = []
for (e, c) in rhs.args:
expressions.append(Assignment(lhs, e))
conditions.append(c)
temp = Piecewise(*zip(expressions, conditions))
return self._print(temp)
if self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
# Here we check if there is looping to be done, and if so
# print the required loops.
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Infinity(self, expr):
return 'inf'
def _print_NegativeInfinity(self, expr):
return '-inf'
def _print_NaN(self, expr):
return 'NaN'
def _print_list(self, expr):
return '{' + ', '.join(self._print(a) for a in expr) + '}'
_print_tuple = _print_list
_print_Tuple = _print_list
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return str(expr).lower()
# Could generate quadrature code for definite Integrals?
#_print_Integral = _print_not_supported
def _print_MatrixBase(self, A):
# Handle zero dimensions:
if (A.rows, A.cols) == (0, 0):
return '[]'
elif A.rows == 0 or A.cols == 0:
return 'zeros(%s, %s)' % (A.rows, A.cols)
elif (A.rows, A.cols) == (1, 1):
# Octave does not distinguish between scalars and 1x1 matrices
return self._print(A[0, 0])
elif A.rows == 1:
return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
elif A.cols == 1:
# note .table would unnecessarily equispace the rows
return "[%s]" % "; ".join([self._print(a) for a in A])
return "[%s]" % A.table(self, rowstart='', rowend='',
rowsep=';\n', colsep=' ')
def _print_SparseMatrix(self, A):
from sympy.matrices import Matrix
L = A.col_list();
# make row vectors of the indices and entries
I = Matrix([[k[0] + 1 for k in L]])
J = Matrix([[k[1] + 1 for k in L]])
AIJ = Matrix([[k[2] for k in L]])
return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
self._print(AIJ), A.rows, A.cols)
# FIXME: Str/CodePrinter could define each of these to call the _print
# method from higher up the class hierarchy (see _print_NumberSymbol).
# Then subclasses like us would not need to repeat all this.
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
_print_MatrixBase
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_SparseMatrix
def _print_MatrixElement(self, expr):
return self._print(expr.parent) + '(%s, %s)'%(expr.i+1, expr.j+1)
def _print_MatrixSlice(self, expr):
def strslice(x, lim):
l = x[0] + 1
h = x[1]
step = x[2]
lstr = self._print(l)
hstr = 'end' if h == lim else self._print(h)
if step == 1:
if l == 1 and h == lim:
return ':'
if l == h:
return lstr
else:
return lstr + ':' + hstr
else:
return ':'.join((lstr, self._print(step), hstr))
return (self._print(expr.parent) + '(' +
strslice(expr.rowslice, expr.parent.shape[0]) + ', ' +
strslice(expr.colslice, expr.parent.shape[1]) + ')')
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Identity(self, expr):
return "eye(%s)" % self._print(expr.shape[0])
def _print_uppergamma(self, expr):
return "gammainc(%s, %s, 'upper')" % (self._print(expr.args[1]),
self._print(expr.args[0]))
def _print_lowergamma(self, expr):
return "gammainc(%s, %s, 'lower')" % (self._print(expr.args[1]),
self._print(expr.args[0]))
def _print_sinc(self, expr):
#Note: Divide by pi because Octave implements normalized sinc function.
return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
def _print_hankel1(self, expr):
return "besselh(%s, 1, %s)" % (self._print(expr.order),
self._print(expr.argument))
def _print_hankel2(self, expr):
return "besselh(%s, 2, %s)" % (self._print(expr.order),
self._print(expr.argument))
# Note: as of 2015, Octave doesn't have spherical Bessel functions
def _print_jn(self, expr):
from sympy.functions import sqrt, besselj
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
return self._print(expr2)
def _print_yn(self, expr):
from sympy.functions import sqrt, bessely
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
return self._print(expr2)
def _print_airyai(self, expr):
return "airy(0, %s)" % self._print(expr.args[0])
def _print_airyaiprime(self, expr):
return "airy(1, %s)" % self._print(expr.args[0])
def _print_airybi(self, expr):
return "airy(2, %s)" % self._print(expr.args[0])
def _print_airybiprime(self, expr):
return "airy(3, %s)" % self._print(expr.args[0])
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if self._settings["inline"]:
# Express each (cond, expr) pair in a nested Horner form:
# (condition) .* (expr) + (not cond) .* (<others>)
# Expressions that result in multiple statements won't work here.
ecpairs = ["({0}).*({1}) + (~({0})).*(".format
(self._print(c), self._print(e))
for e, c in expr.args[:-1]]
elast = "%s" % self._print(expr.args[-1].expr)
pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
# Note: current need these outer brackets for 2*pw. Would be
# nicer to teach parenthesize() to do this for us when needed!
return "(" + pw + ")"
else:
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s)" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("elseif (%s)" % self._print(c))
code0 = self._print(e)
lines.append(code0)
if i == len(expr.args) - 1:
lines.append("end")
return "\n".join(lines)
def indent_code(self, code):
"""Accepts a string of code or a list of code lines"""
# code mostly copied from ccode
if isinstance(code, string_types):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
dec_regex = ('^end$', '^elseif ', '^else$')
# pre-strip left-space from the code
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any([search(re, line) for re in inc_regex]))
for line in code ]
decrease = [ int(any([search(re, line) for re in dec_regex]))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def octave_code(expr, assign_to=None, **settings):
r"""Converts `expr` to a string of Octave (or Matlab) code.
The string uses a subset of the Octave language for Matlab compatibility.
Parameters
==========
expr : Expr
A sympy expression to be converted.
assign_to : optional
When given, the argument is used as the name of the variable to which
the expression is assigned. Can be a string, ``Symbol``,
``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
expressions that generate multi-line statements.
precision : integer, optional
The precision for numbers such as pi [default=16].
user_functions : dict, optional
A dictionary where keys are ``FunctionClass`` instances and values are
their string representations. Alternatively, the dictionary value can
be a list of tuples i.e. [(argument_test, cfunction_string)]. See
below for examples.
human : bool, optional
If True, the result is a single string that may contain some constant
declarations for the number symbols. If False, the same information is
returned in a tuple of (symbols_to_declare, not_supported_functions,
code_text). [default=True].
contract: bool, optional
If True, ``Indexed`` instances are assumed to obey tensor contraction
rules and the corresponding nested loops over indices are generated.
Setting contract=False will not generate loops, instead the user is
responsible to provide values for the indices in the code.
[default=True].
inline: bool, optional
If True, we try to create single-statement code instead of multiple
statements. [default=True].
Examples
========
>>> from sympy import octave_code, symbols, sin, pi
>>> x = symbols('x')
>>> octave_code(sin(x).series(x).removeO())
'x.^5/120 - x.^3/6 + x'
>>> from sympy import Rational, ceiling, Abs
>>> x, y, tau = symbols("x, y, tau")
>>> octave_code((2*tau)**Rational(7, 2))
'8*sqrt(2)*tau.^(7/2)'
Note that element-wise (Hadamard) operations are used by default between
symbols. This is because its very common in Octave to write "vectorized"
code. It is harmless if the values are scalars.
>>> octave_code(sin(pi*x*y), assign_to="s")
's = sin(pi*x.*y);'
If you need a matrix product "*" or matrix power "^", you can specify the
symbol as a ``MatrixSymbol``.
>>> from sympy import Symbol, MatrixSymbol
>>> n = Symbol('n', integer=True, positive=True)
>>> A = MatrixSymbol('A', n, n)
>>> octave_code(3*pi*A**3)
'(3*pi)*A^3'
This class uses several rules to decide which symbol to use a product.
Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
A HadamardProduct can be used to specify componentwise multiplication ".*"
of two MatrixSymbols. There is currently there is no easy way to specify
scalar symbols, so sometimes the code might have some minor cosmetic
issues. For example, suppose x and y are scalars and A is a Matrix, then
while a human programmer might write "(x^2*y)*A^3", we generate:
>>> octave_code(x**2*y*A**3)
'(x.^2.*y)*A^3'
Matrices are supported using Octave inline notation. When using
``assign_to`` with matrices, the name can be specified either as a string
or as a ``MatrixSymbol``. The dimenions must align in the latter case.
>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 sin(x) ceil(x)];'
``Piecewise`` expressions are implemented with logical masking by default.
Alternatively, you can pass "inline=False" to use if-else conditionals.
Note that if the ``Piecewise`` lacks a default term, represented by
``(expr, True)`` then an error will be thrown. This is to prevent
generating an expression that may not evaluate to anything.
>>> from sympy import Piecewise
>>> pw = Piecewise((x + 1, x > 0), (x, True))
>>> octave_code(pw, assign_to=tau)
'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
Note that any expression that can be generated normally can also exist
inside a Matrix:
>>> mat = Matrix([[x**2, pw, sin(x)]])
>>> octave_code(mat, assign_to='A')
'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
Custom printing can be defined for certain types by passing a dictionary of
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
dictionary value can be a list of tuples i.e., [(argument_test,
cfunction_string)]. This can be used to call a custom Octave function.
>>> from sympy import Function
>>> f = Function('f')
>>> g = Function('g')
>>> custom_functions = {
... "f": "existing_octave_fcn",
... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
... (lambda x: not x.is_Matrix, "my_fcn")]
... }
>>> mat = Matrix([[1, x]])
>>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:
>>> from sympy import Eq, IndexedBase, Idx, ccode
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
"""
return OctaveCodePrinter(settings).doprint(expr, assign_to)
def print_octave_code(expr, **settings):
"""Prints the Octave (or Matlab) representation of the given expression.
See `octave_code` for the meaning of the optional arguments.
"""
print(octave_code(expr, **settings))
| 35.789313 | 80 | 0.569533 |
from __future__ import print_function, division
from sympy.core import Mul, Pow, S, Rational
from sympy.core.compatibility import string_types, range
from sympy.core.mul import _keep_coeff
from sympy.codegen.ast import Assignment
from sympy.printing.codeprinter import CodePrinter
from sympy.printing.precedence import precedence
from re import search
known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
"asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
"sinh", "cosh", "tanh", "coth", "csch", "sech",
"asinh", "acosh", "atanh", "acoth", "asech", "acsch",
"erfc", "erfi", "erf", "erfinv", "erfcinv",
"besseli", "besselj", "besselk", "bessely",
"exp", "factorial", "floor", "fresnelc", "fresnels",
"gamma", "log", "polylog", "sign", "zeta"]
known_fcns_src2 = {
"Abs": "abs",
"ceiling": "ceil",
"Chi": "coshint",
"Ci": "cosint",
"conjugate": "conj",
"DiracDelta": "dirac",
"Heaviside": "heaviside",
"laguerre": "laguerreL",
"li": "logint",
"loggamma": "gammaln",
"polygamma": "psi",
"Shi": "sinhint",
"Si": "sinint",
}
class OctaveCodePrinter(CodePrinter):
printmethod = "_octave"
language = "Octave"
_operators = {
'and': '&',
'or': '|',
'not': '~',
}
_default_settings = {
'order': None,
'full_prec': 'auto',
'precision': 16,
'user_functions': {},
'human': True,
'contract': True,
'inline': True,
}
def __init__(self, settings={}):
super(OctaveCodePrinter, self).__init__(settings)
self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
self.known_functions.update(dict(known_fcns_src2))
userfuncs = settings.get('user_functions', {})
self.known_functions.update(userfuncs)
def _rate_index_position(self, p):
return p*5
def _get_statement(self, codestring):
return "%s;" % codestring
def _get_comment(self, text):
return "% {0}".format(text)
def _declare_number_const(self, name, value):
return "{0} = {1};".format(name, value)
def _format_code(self, lines):
return self.indent_code(lines)
def _traverse_matrix_indices(self, mat):
rows, cols = mat.shape
return ((i, j) for j in range(cols) for i in range(rows))
def _get_loop_opening_ending(self, indices):
open_lines = []
close_lines = []
for i in indices:
var, start, stop = map(self._print,
[i.label, i.lower + 1, i.upper + 1])
open_lines.append("for %s = %s:%s" % (var, start, stop))
close_lines.append("end")
return open_lines, close_lines
def _print_Mul(self, expr):
if (expr.is_number and expr.is_imaginary and
expr.as_coeff_Mul()[0].is_integer):
return "%si" % self._print(-S.ImaginaryUnit*expr)
prec = precedence(expr)
c, e = expr.as_coeff_Mul()
if c < 0:
expr = _keep_coeff(-c, e)
sign = "-"
else:
sign = ""
a = []
b = []
if self.order not in ('old', 'none'):
args = expr.as_ordered_factors()
else:
args = Mul.make_args(expr)
for item in args:
if (item.is_commutative and item.is_Pow and item.exp.is_Rational
and item.exp.is_negative):
if item.exp != -1:
b.append(Pow(item.base, -item.exp, evaluate=False))
else:
b.append(Pow(item.base, -item.exp))
elif item.is_Rational and item is not S.Infinity:
if item.p != 1:
a.append(Rational(item.p))
if item.q != 1:
b.append(Rational(item.q))
else:
a.append(item)
a = a or [S.One]
a_str = [self.parenthesize(x, prec) for x in a]
b_str = [self.parenthesize(x, prec) for x in b]
def multjoin(a, a_str):
r = a_str[0]
for i in range(1, len(a)):
mulsym = '*' if a[i-1].is_number else '.*'
r = r + mulsym + a_str[i]
return r
if len(b) == 0:
return sign + multjoin(a, a_str)
elif len(b) == 1:
divsym = '/' if b[0].is_number else './'
return sign + multjoin(a, a_str) + divsym + b_str[0]
else:
divsym = '/' if all([bi.is_number for bi in b]) else './'
return (sign + multjoin(a, a_str) +
divsym + "(%s)" % multjoin(b, b_str))
def _print_Pow(self, expr):
powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^'
PREC = precedence(expr)
if expr.exp == S.Half:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if expr.exp == -S.Half:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "sqrt(%s)" % self._print(expr.base)
if expr.exp == -S.One:
sym = '/' if expr.base.is_number else './'
return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
self.parenthesize(expr.exp, PREC))
def _print_MatPow(self, expr):
PREC = precedence(expr)
return '%s^%s' % (self.parenthesize(expr.base, PREC),
self.parenthesize(expr.exp, PREC))
def _print_Pi(self, expr):
return 'pi'
def _print_ImaginaryUnit(self, expr):
return "1i"
def _print_Exp1(self, expr):
return "exp(1)"
def _print_GoldenRatio(self, expr):
return "(1+sqrt(5))/2"
def _print_NumberSymbol(self, expr):
if self._settings["inline"]:
return self._print(expr.evalf(self._settings["precision"]))
else:
return super(OctaveCodePrinter, self)._print_NumberSymbol(expr)
def _print_Assignment(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
from sympy.tensor.indexed import IndexedBase
lhs = expr.lhs
rhs = expr.rhs
if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
expressions = []
conditions = []
for (e, c) in rhs.args:
expressions.append(Assignment(lhs, e))
conditions.append(c)
temp = Piecewise(*zip(expressions, conditions))
return self._print(temp)
if self._settings["contract"] and (lhs.has(IndexedBase) or
rhs.has(IndexedBase)):
return self._doprint_loops(rhs, lhs)
else:
lhs_code = self._print(lhs)
rhs_code = self._print(rhs)
return self._get_statement("%s = %s" % (lhs_code, rhs_code))
def _print_Infinity(self, expr):
return 'inf'
def _print_NegativeInfinity(self, expr):
return '-inf'
def _print_NaN(self, expr):
return 'NaN'
def _print_list(self, expr):
return '{' + ', '.join(self._print(a) for a in expr) + '}'
_print_tuple = _print_list
_print_Tuple = _print_list
def _print_BooleanTrue(self, expr):
return "true"
def _print_BooleanFalse(self, expr):
return "false"
def _print_bool(self, expr):
return str(expr).lower()
def _print_MatrixBase(self, A):
if (A.rows, A.cols) == (0, 0):
return '[]'
elif A.rows == 0 or A.cols == 0:
return 'zeros(%s, %s)' % (A.rows, A.cols)
elif (A.rows, A.cols) == (1, 1):
return self._print(A[0, 0])
elif A.rows == 1:
return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
elif A.cols == 1:
return "[%s]" % "; ".join([self._print(a) for a in A])
return "[%s]" % A.table(self, rowstart='', rowend='',
rowsep=';\n', colsep=' ')
def _print_SparseMatrix(self, A):
from sympy.matrices import Matrix
L = A.col_list();
I = Matrix([[k[0] + 1 for k in L]])
J = Matrix([[k[1] + 1 for k in L]])
AIJ = Matrix([[k[2] for k in L]])
return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
self._print(AIJ), A.rows, A.cols)
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
_print_MatrixBase
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_SparseMatrix
def _print_MatrixElement(self, expr):
return self._print(expr.parent) + '(%s, %s)'%(expr.i+1, expr.j+1)
def _print_MatrixSlice(self, expr):
def strslice(x, lim):
l = x[0] + 1
h = x[1]
step = x[2]
lstr = self._print(l)
hstr = 'end' if h == lim else self._print(h)
if step == 1:
if l == 1 and h == lim:
return ':'
if l == h:
return lstr
else:
return lstr + ':' + hstr
else:
return ':'.join((lstr, self._print(step), hstr))
return (self._print(expr.parent) + '(' +
strslice(expr.rowslice, expr.parent.shape[0]) + ', ' +
strslice(expr.colslice, expr.parent.shape[1]) + ')')
def _print_Indexed(self, expr):
inds = [ self._print(i) for i in expr.indices ]
return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
def _print_Idx(self, expr):
return self._print(expr.label)
def _print_Identity(self, expr):
return "eye(%s)" % self._print(expr.shape[0])
def _print_uppergamma(self, expr):
return "gammainc(%s, %s, 'upper')" % (self._print(expr.args[1]),
self._print(expr.args[0]))
def _print_lowergamma(self, expr):
return "gammainc(%s, %s, 'lower')" % (self._print(expr.args[1]),
self._print(expr.args[0]))
def _print_sinc(self, expr):
return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
def _print_hankel1(self, expr):
return "besselh(%s, 1, %s)" % (self._print(expr.order),
self._print(expr.argument))
def _print_hankel2(self, expr):
return "besselh(%s, 2, %s)" % (self._print(expr.order),
self._print(expr.argument))
def _print_jn(self, expr):
from sympy.functions import sqrt, besselj
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
return self._print(expr2)
def _print_yn(self, expr):
from sympy.functions import sqrt, bessely
x = expr.argument
expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
return self._print(expr2)
def _print_airyai(self, expr):
return "airy(0, %s)" % self._print(expr.args[0])
def _print_airyaiprime(self, expr):
return "airy(1, %s)" % self._print(expr.args[0])
def _print_airybi(self, expr):
return "airy(2, %s)" % self._print(expr.args[0])
def _print_airybiprime(self, expr):
return "airy(3, %s)" % self._print(expr.args[0])
def _print_Piecewise(self, expr):
if expr.args[-1].cond != True:
# We need the last conditional to be a True, otherwise the resulting
# function may not return a result.
raise ValueError("All Piecewise expressions must contain an "
"(expr, True) statement to be used as a default "
"condition. Without one, the generated "
"expression may not evaluate to anything under "
"some condition.")
lines = []
if self._settings["inline"]:
# Express each (cond, expr) pair in a nested Horner form:
# (condition) .* (expr) + (not cond) .* (<others>)
# Expressions that result in multiple statements won't work here.
ecpairs = ["({0}).*({1}) + (~({0})).*(".format
(self._print(c), self._print(e))
for e, c in expr.args[:-1]]
elast = "%s" % self._print(expr.args[-1].expr)
pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
return "(" + pw + ")"
else:
for i, (e, c) in enumerate(expr.args):
if i == 0:
lines.append("if (%s)" % self._print(c))
elif i == len(expr.args) - 1 and c == True:
lines.append("else")
else:
lines.append("elseif (%s)" % self._print(c))
code0 = self._print(e)
lines.append(code0)
if i == len(expr.args) - 1:
lines.append("end")
return "\n".join(lines)
def indent_code(self, code):
if isinstance(code, string_types):
code_lines = self.indent_code(code.splitlines(True))
return ''.join(code_lines)
tab = " "
inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
dec_regex = ('^end$', '^elseif ', '^else$')
code = [ line.lstrip(' \t') for line in code ]
increase = [ int(any([search(re, line) for re in inc_regex]))
for line in code ]
decrease = [ int(any([search(re, line) for re in dec_regex]))
for line in code ]
pretty = []
level = 0
for n, line in enumerate(code):
if line == '' or line == '\n':
pretty.append(line)
continue
level -= decrease[n]
pretty.append("%s%s" % (tab*level, line))
level += increase[n]
return pretty
def octave_code(expr, assign_to=None, **settings):
return OctaveCodePrinter(settings).doprint(expr, assign_to)
def print_octave_code(expr, **settings):
print(octave_code(expr, **settings))
| true | true |
f72c79f3f9a9af03ac560d30164899d30e36c861 | 692 | py | Python | src/examples/animations/AnimationGif.py | Gabvaztor/tensorflowCode | e206ea4544552b87c2d43274cea3182f6b385a87 | [
"Apache-2.0"
] | 4 | 2019-12-14T08:06:18.000Z | 2020-09-12T10:09:31.000Z | src/examples/animations/AnimationGif.py | Gabvaztor/tensorflowCode | e206ea4544552b87c2d43274cea3182f6b385a87 | [
"Apache-2.0"
] | null | null | null | src/examples/animations/AnimationGif.py | Gabvaztor/tensorflowCode | e206ea4544552b87c2d43274cea3182f6b385a87 | [
"Apache-2.0"
] | 2 | 2020-09-12T10:10:07.000Z | 2021-09-15T11:58:37.000Z | #IMPORTAMOS LIBRERIAS.
import numpy as np
import matplotlib.pyplot as plt
import animatplot as amp
#INTRODUCIMOS DATOS.
x = np.linspace(0, 1, 50)
t = np.linspace(0, 1, 20)
X, T = np.meshgrid(x, t)
Y = np.zeros(int(51*(X+T)))
#CREAMOS OBJETO "timeline".
timeline = amp.Timeline(t, units='s', fps=60)
#GENERAMOS ANIMACIÓN.
block = amp.blocks.Line(X, Y, marker=".", linestyle="-", color="r")
anim = amp.Animation([block],timeline)
#DEFINICIÓN DE ETIQUETAS PARA TITULO Y EJES.
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("y")
#GUARDAMOS ANIMACIÓN.
#anim.save_gif('graph_anim.gif')
#INTRODUCIMOS LÍNEA DE TIEMPO
#Y BOTÓN PAUSE/PLAY
anim.controls()
#REPRESENTAMOS GRÁFICA.
plt.show() | 20.352941 | 67 | 0.710983 |
import numpy as np
import matplotlib.pyplot as plt
import animatplot as amp
x = np.linspace(0, 1, 50)
t = np.linspace(0, 1, 20)
X, T = np.meshgrid(x, t)
Y = np.zeros(int(51*(X+T)))
timeline = amp.Timeline(t, units='s', fps=60)
block = amp.blocks.Line(X, Y, marker=".", linestyle="-", color="r")
anim = amp.Animation([block],timeline)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("y")
anim.controls()
plt.show() | true | true |
f72c7b00779b23f24e5f6b86d0f4c382d11780f4 | 4,931 | py | Python | sdks/python/apache_beam/runners/worker/log_handler.py | dxichen/beam | d02b859cb37e3c9f565785e93384905f1078b409 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2018-12-08T05:19:04.000Z | 2018-12-08T05:19:07.000Z | sdks/python/apache_beam/runners/worker/log_handler.py | dxichen/beam | d02b859cb37e3c9f565785e93384905f1078b409 | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2016-03-21T22:50:43.000Z | 2016-07-12T16:59:21.000Z | sdks/python/apache_beam/runners/worker/log_handler.py | swegner/incubator-beam | 5466ac0b8819625b1d0ada3577c1fc103797f9a2 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2018-11-23T11:49:03.000Z | 2018-11-23T11:49:03.000Z | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Beam fn API log handler."""
from __future__ import absolute_import
from __future__ import print_function
import logging
import math
import queue
import sys
import threading
from builtins import range
import grpc
from apache_beam.portability.api import beam_fn_api_pb2
from apache_beam.portability.api import beam_fn_api_pb2_grpc
from apache_beam.runners.worker.worker_id_interceptor import WorkerIdInterceptor
# This module is experimental. No backwards-compatibility guarantees.
class FnApiLogRecordHandler(logging.Handler):
"""A handler that writes log records to the fn API."""
# Maximum number of log entries in a single stream request.
_MAX_BATCH_SIZE = 1000
# Used to indicate the end of stream.
_FINISHED = object()
# Size of the queue used to buffer messages. Once full, messages will be
# dropped. If the average log size is 1KB this may use up to 10MB of memory.
_QUEUE_SIZE = 10000
# Mapping from logging levels to LogEntry levels.
LOG_LEVEL_MAP = {
logging.FATAL: beam_fn_api_pb2.LogEntry.Severity.CRITICAL,
logging.ERROR: beam_fn_api_pb2.LogEntry.Severity.ERROR,
logging.WARNING: beam_fn_api_pb2.LogEntry.Severity.WARN,
logging.INFO: beam_fn_api_pb2.LogEntry.Severity.INFO,
logging.DEBUG: beam_fn_api_pb2.LogEntry.Severity.DEBUG
}
def __init__(self, log_service_descriptor):
super(FnApiLogRecordHandler, self).__init__()
self._dropped_logs = 0
self._log_entry_queue = queue.Queue(maxsize=self._QUEUE_SIZE)
ch = grpc.insecure_channel(log_service_descriptor.url)
# Make sure the channel is ready to avoid [BEAM-4649]
grpc.channel_ready_future(ch).result(timeout=60)
self._log_channel = grpc.intercept_channel(ch, WorkerIdInterceptor())
self._logging_stub = beam_fn_api_pb2_grpc.BeamFnLoggingStub(
self._log_channel)
self._reader = threading.Thread(
target=lambda: self._read_log_control_messages(),
name='read_log_control_messages')
self._reader.daemon = True
self._reader.start()
def connect(self):
return self._logging_stub.Logging(self._write_log_entries())
def emit(self, record):
log_entry = beam_fn_api_pb2.LogEntry()
log_entry.severity = self.LOG_LEVEL_MAP[record.levelno]
log_entry.message = self.format(record)
log_entry.thread = record.threadName
log_entry.log_location = record.module + '.' + record.funcName
(fraction, seconds) = math.modf(record.created)
nanoseconds = 1e9 * fraction
log_entry.timestamp.seconds = int(seconds)
log_entry.timestamp.nanos = int(nanoseconds)
try:
self._log_entry_queue.put(log_entry, block=False)
except queue.Full:
self._dropped_logs += 1
def close(self):
"""Flush out all existing log entries and unregister this handler."""
# Acquiring the handler lock ensures ``emit`` is not run until the lock is
# released.
self.acquire()
self._log_entry_queue.put(self._FINISHED, timeout=5)
# wait on server to close.
self._reader.join()
self.release()
# Unregister this handler.
super(FnApiLogRecordHandler, self).close()
def _write_log_entries(self):
done = False
while not done:
log_entries = [self._log_entry_queue.get()]
try:
for _ in range(self._MAX_BATCH_SIZE):
log_entries.append(self._log_entry_queue.get_nowait())
except queue.Empty:
pass
if log_entries[-1] is self._FINISHED:
done = True
log_entries.pop()
if log_entries:
yield beam_fn_api_pb2.LogEntry.List(log_entries=log_entries)
def _read_log_control_messages(self):
while True:
log_control_iterator = self.connect()
if self._dropped_logs > 0:
logging.warn("Dropped %d logs while logging client disconnected",
self._dropped_logs)
self._dropped_logs = 0
try:
for _ in log_control_iterator:
# TODO(vikasrk): Handle control messages.
pass
# iterator is closed
return
except Exception as ex:
print("Logging client failed: {}... resetting".format(ex),
file=sys.stderr)
| 35.47482 | 80 | 0.724599 |
from __future__ import absolute_import
from __future__ import print_function
import logging
import math
import queue
import sys
import threading
from builtins import range
import grpc
from apache_beam.portability.api import beam_fn_api_pb2
from apache_beam.portability.api import beam_fn_api_pb2_grpc
from apache_beam.runners.worker.worker_id_interceptor import WorkerIdInterceptor
class FnApiLogRecordHandler(logging.Handler):
_MAX_BATCH_SIZE = 1000
_FINISHED = object()
_QUEUE_SIZE = 10000
LOG_LEVEL_MAP = {
logging.FATAL: beam_fn_api_pb2.LogEntry.Severity.CRITICAL,
logging.ERROR: beam_fn_api_pb2.LogEntry.Severity.ERROR,
logging.WARNING: beam_fn_api_pb2.LogEntry.Severity.WARN,
logging.INFO: beam_fn_api_pb2.LogEntry.Severity.INFO,
logging.DEBUG: beam_fn_api_pb2.LogEntry.Severity.DEBUG
}
def __init__(self, log_service_descriptor):
super(FnApiLogRecordHandler, self).__init__()
self._dropped_logs = 0
self._log_entry_queue = queue.Queue(maxsize=self._QUEUE_SIZE)
ch = grpc.insecure_channel(log_service_descriptor.url)
grpc.channel_ready_future(ch).result(timeout=60)
self._log_channel = grpc.intercept_channel(ch, WorkerIdInterceptor())
self._logging_stub = beam_fn_api_pb2_grpc.BeamFnLoggingStub(
self._log_channel)
self._reader = threading.Thread(
target=lambda: self._read_log_control_messages(),
name='read_log_control_messages')
self._reader.daemon = True
self._reader.start()
def connect(self):
return self._logging_stub.Logging(self._write_log_entries())
def emit(self, record):
log_entry = beam_fn_api_pb2.LogEntry()
log_entry.severity = self.LOG_LEVEL_MAP[record.levelno]
log_entry.message = self.format(record)
log_entry.thread = record.threadName
log_entry.log_location = record.module + '.' + record.funcName
(fraction, seconds) = math.modf(record.created)
nanoseconds = 1e9 * fraction
log_entry.timestamp.seconds = int(seconds)
log_entry.timestamp.nanos = int(nanoseconds)
try:
self._log_entry_queue.put(log_entry, block=False)
except queue.Full:
self._dropped_logs += 1
def close(self):
self.acquire()
self._log_entry_queue.put(self._FINISHED, timeout=5)
self._reader.join()
self.release()
super(FnApiLogRecordHandler, self).close()
def _write_log_entries(self):
done = False
while not done:
log_entries = [self._log_entry_queue.get()]
try:
for _ in range(self._MAX_BATCH_SIZE):
log_entries.append(self._log_entry_queue.get_nowait())
except queue.Empty:
pass
if log_entries[-1] is self._FINISHED:
done = True
log_entries.pop()
if log_entries:
yield beam_fn_api_pb2.LogEntry.List(log_entries=log_entries)
def _read_log_control_messages(self):
while True:
log_control_iterator = self.connect()
if self._dropped_logs > 0:
logging.warn("Dropped %d logs while logging client disconnected",
self._dropped_logs)
self._dropped_logs = 0
try:
for _ in log_control_iterator:
pass
return
except Exception as ex:
print("Logging client failed: {}... resetting".format(ex),
file=sys.stderr)
| true | true |
f72c7bed0beea334637a18a2edf4a3137820bc39 | 6,213 | py | Python | sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 8 | 2021-01-13T23:44:08.000Z | 2021-03-17T10:13:36.000Z | sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 226 | 2019-07-24T07:57:21.000Z | 2019-10-15T01:07:24.000Z | sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_percentile_source_target_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 2 | 2020-05-21T22:51:22.000Z | 2020-05-26T20:53:01.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class PercentileSourceTargetOperations(object):
"""PercentileSourceTargetOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: The API version to use for this operation. Constant value: "2020-03-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2020-03-01"
self.config = config
def list_metrics(
self, resource_group_name, account_name, source_region, target_region, filter, custom_headers=None, raw=False, **operation_config):
"""Retrieves the metrics determined by the given filter for the given
account, source and target region. This url is only for PBS and
Replication Latency data.
:param resource_group_name: The name of the resource group. The name
is case insensitive.
:type resource_group_name: str
:param account_name: Cosmos DB database account name.
:type account_name: str
:param source_region: Source region from which data is written. Cosmos
DB region, with spaces between words and each word capitalized.
:type source_region: str
:param target_region: Target region to which data is written. Cosmos
DB region, with spaces between words and each word capitalized.
:type target_region: str
:param filter: An OData filter expression that describes a subset of
metrics to return. The parameters that can be filtered are name.value
(name of the metric, can have an or of multiple names), startTime,
endTime, and timeGrain. The supported operator is eq.
:type filter: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of PercentileMetric
:rtype:
~azure.mgmt.cosmosdb.models.PercentileMetricPaged[~azure.mgmt.cosmosdb.models.PercentileMetric]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list_metrics.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'),
'sourceRegion': self._serialize.url("source_region", source_region, 'str'),
'targetRegion': self._serialize.url("target_region", target_region, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.PercentileMetricPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_metrics.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics'}
| 47.792308 | 242 | 0.652503 |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class PercentileSourceTargetOperations(object):
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2020-03-01"
self.config = config
def list_metrics(
self, resource_group_name, account_name, source_region, target_region, filter, custom_headers=None, raw=False, **operation_config):
def prepare_request(next_link=None):
if not next_link:
url = self.list_metrics.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'),
'sourceRegion': self._serialize.url("source_region", source_region, 'str'),
'targetRegion': self._serialize.url("target_region", target_region, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
else:
url = next_link
query_parameters = {}
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
header_dict = None
if raw:
header_dict = {}
deserialized = models.PercentileMetricPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_metrics.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sourceRegion/{sourceRegion}/targetRegion/{targetRegion}/percentile/metrics'}
| true | true |
f72c7c71e236df55dac3c772bf1accd371c155c5 | 586 | py | Python | python/sdssdb/__init__.py | albireox/sdssdb | 02d165d3a4347e8241aacdbdca0cec86058c8d29 | [
"BSD-3-Clause"
] | 6 | 2019-04-10T21:28:44.000Z | 2021-03-01T18:39:55.000Z | python/sdssdb/__init__.py | albireox/sdssdb | 02d165d3a4347e8241aacdbdca0cec86058c8d29 | [
"BSD-3-Clause"
] | 44 | 2018-10-31T17:48:20.000Z | 2022-01-27T20:52:26.000Z | python/sdssdb/__init__.py | albireox/sdssdb | 02d165d3a4347e8241aacdbdca0cec86058c8d29 | [
"BSD-3-Clause"
] | 2 | 2021-07-13T17:09:43.000Z | 2021-07-13T19:33:18.000Z | # encoding: utf-8
import warnings
from sdsstools import get_config, get_logger, get_package_version
warnings.filterwarnings(
'ignore', '.*Skipped unsupported reflection of expression-based index .*q3c.*')
NAME = 'sdssdb'
__version__ = get_package_version(path=__file__, package_name=NAME)
log = get_logger(NAME)
# This looks for user configuration in the usual places (including
# ~/.config/sdss/sdssdb.yml and ~/.sdssdb/sdssdb.yml).
config = get_config(NAME)
from .connection import PeeweeDatabaseConnection # noqa
from .connection import SQLADatabaseConnection # noqa
| 24.416667 | 83 | 0.776451 |
import warnings
from sdsstools import get_config, get_logger, get_package_version
warnings.filterwarnings(
'ignore', '.*Skipped unsupported reflection of expression-based index .*q3c.*')
NAME = 'sdssdb'
__version__ = get_package_version(path=__file__, package_name=NAME)
log = get_logger(NAME)
config = get_config(NAME)
from .connection import PeeweeDatabaseConnection
from .connection import SQLADatabaseConnection
| true | true |
f72c7c8922dfe217f75499b4645d20bbcc563d6b | 768 | py | Python | saltapi/loader.py | techdragon/salt-api | e1ea6dd89bca61a7b8e885efcbc818faea33ea51 | [
"Apache-2.0"
] | 1 | 2019-06-27T13:05:14.000Z | 2019-06-27T13:05:14.000Z | saltapi/loader.py | techdragon/salt-api | e1ea6dd89bca61a7b8e885efcbc818faea33ea51 | [
"Apache-2.0"
] | null | null | null | saltapi/loader.py | techdragon/salt-api | e1ea6dd89bca61a7b8e885efcbc818faea33ea51 | [
"Apache-2.0"
] | null | null | null | '''
The salt api module loader interface
'''
# Import python libs
import os
# Import Salt libs
import salt.loader
import saltapi
def netapi(opts):
'''
Return the network api functions
'''
load = salt.loader._create_loader(
opts,
'netapi',
'netapi',
base_path=os.path.dirname(saltapi.__file__)
)
return load.gen_functions()
def runner(opts):
'''
Load the runners, this function bypasses the issue with the altered
basepath
'''
load = salt.loader._create_loader(
opts,
'runners',
'runner',
ext_type_dirs='runner_dirs',
base_path=os.path.dirname(salt.__file__)
)
return load.gen_functions()
| 20.756757 | 71 | 0.580729 |
import os
import salt.loader
import saltapi
def netapi(opts):
load = salt.loader._create_loader(
opts,
'netapi',
'netapi',
base_path=os.path.dirname(saltapi.__file__)
)
return load.gen_functions()
def runner(opts):
load = salt.loader._create_loader(
opts,
'runners',
'runner',
ext_type_dirs='runner_dirs',
base_path=os.path.dirname(salt.__file__)
)
return load.gen_functions()
| true | true |
f72c7ca68f363a382646aaf1c7a8b8116abf92d5 | 51,548 | py | Python | Lib/test/test_compile.py | emontnemery/cpython | 99fcf1505218464c489d419d4500f126b6d6dc28 | [
"0BSD"
] | 18 | 2017-09-21T18:22:31.000Z | 2022-02-22T19:40:01.000Z | Lib/test/test_compile.py | emontnemery/cpython | 99fcf1505218464c489d419d4500f126b6d6dc28 | [
"0BSD"
] | 25 | 2020-04-16T17:21:30.000Z | 2022-03-01T05:00:45.000Z | Lib/test/test_compile.py | emontnemery/cpython | 99fcf1505218464c489d419d4500f126b6d6dc28 | [
"0BSD"
] | 8 | 2018-08-31T07:49:21.000Z | 2020-11-21T21:31:48.000Z | import dis
import math
import os
import unittest
import sys
import ast
import _ast
import tempfile
import types
import textwrap
from test import support
from test.support import script_helper, requires_debug_ranges
from test.support.os_helper import FakePath
class TestSpecifics(unittest.TestCase):
def compile_single(self, source):
compile(source, "<single>", "single")
def assertInvalidSingle(self, source):
self.assertRaises(SyntaxError, self.compile_single, source)
def test_no_ending_newline(self):
compile("hi", "<test>", "exec")
compile("hi\r", "<test>", "exec")
def test_empty(self):
compile("", "<test>", "exec")
def test_other_newlines(self):
compile("\r\n", "<test>", "exec")
compile("\r", "<test>", "exec")
compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
def test_debug_assignment(self):
# catch assignments to __debug__
self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
import builtins
prev = builtins.__debug__
setattr(builtins, '__debug__', 'sure')
self.assertEqual(__debug__, prev)
setattr(builtins, '__debug__', prev)
def test_argument_handling(self):
# detect duplicate positional and keyword arguments
self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
def test_syntax_error(self):
self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
def test_none_keyword_arg(self):
self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
def test_duplicate_global_local(self):
self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
def test_exec_with_general_mapping_for_locals(self):
class M:
"Test mapping interface versus possible calls from eval()."
def __getitem__(self, key):
if key == 'a':
return 12
raise KeyError
def __setitem__(self, key, value):
self.results = (key, value)
def keys(self):
return list('xyz')
m = M()
g = globals()
exec('z = a', g, m)
self.assertEqual(m.results, ('z', 12))
try:
exec('z = b', g, m)
except NameError:
pass
else:
self.fail('Did not detect a KeyError')
exec('z = dir()', g, m)
self.assertEqual(m.results, ('z', list('xyz')))
exec('z = globals()', g, m)
self.assertEqual(m.results, ('z', g))
exec('z = locals()', g, m)
self.assertEqual(m.results, ('z', m))
self.assertRaises(TypeError, exec, 'z = b', m)
class A:
"Non-mapping"
pass
m = A()
self.assertRaises(TypeError, exec, 'z = a', g, m)
# Verify that dict subclasses work as well
class D(dict):
def __getitem__(self, key):
if key == 'a':
return 12
return dict.__getitem__(self, key)
d = D()
exec('z = a', g, d)
self.assertEqual(d['z'], 12)
def test_extended_arg(self):
longexpr = 'x = x or ' + '-x' * 2500
g = {}
code = '''
def f(x):
%s
%s
%s
%s
%s
%s
%s
%s
%s
%s
# the expressions above have no effect, x == argument
while x:
x -= 1
# EXTENDED_ARG/JUMP_ABSOLUTE here
return x
''' % ((longexpr,)*10)
exec(code, g)
self.assertEqual(g['f'](5), 0)
def test_argument_order(self):
self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
def test_float_literals(self):
# testing bad float literals
self.assertRaises(SyntaxError, eval, "2e")
self.assertRaises(SyntaxError, eval, "2.0e+")
self.assertRaises(SyntaxError, eval, "1e-")
self.assertRaises(SyntaxError, eval, "3-4e/21")
def test_indentation(self):
# testing compile() of indented block w/o trailing newline"
s = """
if 1:
if 2:
pass"""
compile(s, "<string>", "exec")
# This test is probably specific to CPython and may not generalize
# to other implementations. We are trying to ensure that when
# the first line of code starts after 256, correct line numbers
# in tracebacks are still produced.
def test_leading_newlines(self):
s256 = "".join(["\n"] * 256 + ["spam"])
co = compile(s256, 'fn', 'exec')
self.assertEqual(co.co_firstlineno, 1)
self.assertEqual(list(co.co_lines()), [(0, 8, 257)])
def test_literals_with_leading_zeroes(self):
for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
"080000000000000", "000000000000009", "000000000000008",
"0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
"0b101j", "0o153j", "0b100e1", "0o777e1", "0777",
"000777", "000000000000007"]:
self.assertRaises(SyntaxError, eval, arg)
self.assertEqual(eval("0xff"), 255)
self.assertEqual(eval("0777."), 777)
self.assertEqual(eval("0777.0"), 777)
self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
self.assertEqual(eval("0777e1"), 7770)
self.assertEqual(eval("0e0"), 0)
self.assertEqual(eval("0000e-012"), 0)
self.assertEqual(eval("09.5"), 9.5)
self.assertEqual(eval("0777j"), 777j)
self.assertEqual(eval("000"), 0)
self.assertEqual(eval("00j"), 0j)
self.assertEqual(eval("00.0"), 0)
self.assertEqual(eval("0e3"), 0)
self.assertEqual(eval("090000000000000."), 90000000000000.)
self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
self.assertEqual(eval("090000000000000e0"), 90000000000000.)
self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
self.assertEqual(eval("090000000000000j"), 90000000000000j)
self.assertEqual(eval("000000000000008."), 8.)
self.assertEqual(eval("000000000000009."), 9.)
self.assertEqual(eval("0b101010"), 42)
self.assertEqual(eval("-0b000000000010"), -2)
self.assertEqual(eval("0o777"), 511)
self.assertEqual(eval("-0o0000010"), -8)
def test_unary_minus(self):
# Verify treatment of unary minus on negative numbers SF bug #660455
if sys.maxsize == 2147483647:
# 32-bit machine
all_one_bits = '0xffffffff'
self.assertEqual(eval(all_one_bits), 4294967295)
self.assertEqual(eval("-" + all_one_bits), -4294967295)
elif sys.maxsize == 9223372036854775807:
# 64-bit machine
all_one_bits = '0xffffffffffffffff'
self.assertEqual(eval(all_one_bits), 18446744073709551615)
self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
else:
self.fail("How many bits *does* this machine have???")
# Verify treatment of constant folding on -(sys.maxsize+1)
# i.e. -2147483648 on 32 bit platforms. Should return int.
self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
if sys.maxsize == 9223372036854775807:
def test_32_63_bit_values(self):
a = +4294967296 # 1 << 32
b = -4294967296 # 1 << 32
c = +281474976710656 # 1 << 48
d = -281474976710656 # 1 << 48
e = +4611686018427387904 # 1 << 62
f = -4611686018427387904 # 1 << 62
g = +9223372036854775807 # 1 << 63 - 1
h = -9223372036854775807 # 1 << 63 - 1
for variable in self.test_32_63_bit_values.__code__.co_consts:
if variable is not None:
self.assertIsInstance(variable, int)
def test_sequence_unpacking_error(self):
# Verify sequence packing/unpacking with "or". SF bug #757818
i,j = (1, -1) or (-1, 1)
self.assertEqual(i, 1)
self.assertEqual(j, -1)
def test_none_assignment(self):
stmts = [
'None = 0',
'None += 0',
'__builtins__.None = 0',
'def None(): pass',
'class None: pass',
'(a, None) = 0, 0',
'for None in range(10): pass',
'def f(None): pass',
'import None',
'import x as None',
'from x import None',
'from x import y as None'
]
for stmt in stmts:
stmt += "\n"
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
def test_import(self):
succeed = [
'import sys',
'import os, sys',
'import os as bar',
'import os.path as bar',
'from __future__ import nested_scopes, generators',
'from __future__ import (nested_scopes,\ngenerators)',
'from __future__ import (nested_scopes,\ngenerators,)',
'from sys import stdin, stderr, stdout',
'from sys import (stdin, stderr,\nstdout)',
'from sys import (stdin, stderr,\nstdout,)',
'from sys import (stdin\n, stderr, stdout)',
'from sys import (stdin\n, stderr, stdout,)',
'from sys import stdin as si, stdout as so, stderr as se',
'from sys import (stdin as si, stdout as so, stderr as se)',
'from sys import (stdin as si, stdout as so, stderr as se,)',
]
fail = [
'import (os, sys)',
'import (os), (sys)',
'import ((os), (sys))',
'import (sys',
'import sys)',
'import (os,)',
'import os As bar',
'import os.path a bar',
'from sys import stdin As stdout',
'from sys import stdin a stdout',
'from (sys) import stdin',
'from __future__ import (nested_scopes',
'from __future__ import nested_scopes)',
'from __future__ import nested_scopes,\ngenerators',
'from sys import (stdin',
'from sys import stdin)',
'from sys import stdin, stdout,\nstderr',
'from sys import stdin si',
'from sys import stdin,',
'from sys import (*)',
'from sys import (stdin,, stdout, stderr)',
'from sys import (stdin, stdout),',
]
for stmt in succeed:
compile(stmt, 'tmp', 'exec')
for stmt in fail:
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
def test_for_distinct_code_objects(self):
# SF bug 1048870
def f():
f1 = lambda x=1: x
f2 = lambda x=2: x
return f1, f2
f1, f2 = f()
self.assertNotEqual(id(f1.__code__), id(f2.__code__))
def test_lambda_doc(self):
l = lambda: "foo"
self.assertIsNone(l.__doc__)
def test_encoding(self):
code = b'# -*- coding: badencoding -*-\npass\n'
self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
compile(code, 'tmp', 'exec')
self.assertEqual(eval(code), '\xc2\xa4')
code = '"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\xa4')
code = b'"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xa4')
code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\xa4')
code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xa4')
code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\u20ac')
code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
def test_subscripts(self):
# SF bug 1448804
# Class to make testing subscript results easy
class str_map(object):
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[str(key)]
def __setitem__(self, key, value):
self.data[str(key)] = value
def __delitem__(self, key):
del self.data[str(key)]
def __contains__(self, key):
return str(key) in self.data
d = str_map()
# Index
d[1] = 1
self.assertEqual(d[1], 1)
d[1] += 1
self.assertEqual(d[1], 2)
del d[1]
self.assertNotIn(1, d)
# Tuple of indices
d[1, 1] = 1
self.assertEqual(d[1, 1], 1)
d[1, 1] += 1
self.assertEqual(d[1, 1], 2)
del d[1, 1]
self.assertNotIn((1, 1), d)
# Simple slice
d[1:2] = 1
self.assertEqual(d[1:2], 1)
d[1:2] += 1
self.assertEqual(d[1:2], 2)
del d[1:2]
self.assertNotIn(slice(1, 2), d)
# Tuple of simple slices
d[1:2, 1:2] = 1
self.assertEqual(d[1:2, 1:2], 1)
d[1:2, 1:2] += 1
self.assertEqual(d[1:2, 1:2], 2)
del d[1:2, 1:2]
self.assertNotIn((slice(1, 2), slice(1, 2)), d)
# Extended slice
d[1:2:3] = 1
self.assertEqual(d[1:2:3], 1)
d[1:2:3] += 1
self.assertEqual(d[1:2:3], 2)
del d[1:2:3]
self.assertNotIn(slice(1, 2, 3), d)
# Tuple of extended slices
d[1:2:3, 1:2:3] = 1
self.assertEqual(d[1:2:3, 1:2:3], 1)
d[1:2:3, 1:2:3] += 1
self.assertEqual(d[1:2:3, 1:2:3], 2)
del d[1:2:3, 1:2:3]
self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
# Ellipsis
d[...] = 1
self.assertEqual(d[...], 1)
d[...] += 1
self.assertEqual(d[...], 2)
del d[...]
self.assertNotIn(Ellipsis, d)
# Tuple of Ellipses
d[..., ...] = 1
self.assertEqual(d[..., ...], 1)
d[..., ...] += 1
self.assertEqual(d[..., ...], 2)
del d[..., ...]
self.assertNotIn((Ellipsis, Ellipsis), d)
def test_annotation_limit(self):
# more than 255 annotations, should compile ok
s = "def f(%s): pass"
s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
compile(s, '?', 'exec')
def test_mangling(self):
class A:
def f():
__mangled = 1
__not_mangled__ = 2
import __mangled_mod
import __package__.module
self.assertIn("_A__mangled", A.f.__code__.co_varnames)
self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
self.assertIn("__package__", A.f.__code__.co_varnames)
def test_compile_ast(self):
fname = __file__
if fname.lower().endswith('pyc'):
fname = fname[:-1]
with open(fname, encoding='utf-8') as f:
fcontents = f.read()
sample_code = [
['<assign>', 'x = 5'],
['<ifblock>', """if True:\n pass\n"""],
['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
['<deffunc>', """def foo():\n pass\nfoo()\n"""],
[fname, fcontents],
]
for fname, code in sample_code:
co1 = compile(code, '%s1' % fname, 'exec')
ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
self.assertTrue(type(ast) == _ast.Module)
co2 = compile(ast, '%s3' % fname, 'exec')
self.assertEqual(co1, co2)
# the code object's filename comes from the second compilation step
self.assertEqual(co2.co_filename, '%s3' % fname)
# raise exception when node type doesn't match with compile mode
co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
# raise exception when node type is no start node
self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
# raise exception when node has invalid children
ast = _ast.Module()
ast.body = [_ast.BoolOp()]
self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
def test_dict_evaluation_order(self):
i = 0
def f():
nonlocal i
i += 1
return i
d = {f(): f(), f(): f()}
self.assertEqual(d, {1: 2, 3: 4})
def test_compile_filename(self):
for filename in 'file.py', b'file.py':
code = compile('pass', filename, 'exec')
self.assertEqual(code.co_filename, 'file.py')
for filename in bytearray(b'file.py'), memoryview(b'file.py'):
with self.assertWarns(DeprecationWarning):
code = compile('pass', filename, 'exec')
self.assertEqual(code.co_filename, 'file.py')
self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
@support.cpython_only
def test_same_filename_used(self):
s = """def f(): pass\ndef g(): pass"""
c = compile(s, "myfile", "exec")
for obj in c.co_consts:
if isinstance(obj, types.CodeType):
self.assertIs(obj.co_filename, c.co_filename)
def test_single_statement(self):
self.compile_single("1 + 2")
self.compile_single("\n1 + 2")
self.compile_single("1 + 2\n")
self.compile_single("1 + 2\n\n")
self.compile_single("1 + 2\t\t\n")
self.compile_single("1 + 2\t\t\n ")
self.compile_single("1 + 2 # one plus two")
self.compile_single("1; 2")
self.compile_single("import sys; sys")
self.compile_single("def f():\n pass")
self.compile_single("while False:\n pass")
self.compile_single("if x:\n f(x)")
self.compile_single("if x:\n f(x)\nelse:\n g(x)")
self.compile_single("class T:\n pass")
def test_bad_single_statement(self):
self.assertInvalidSingle('1\n2')
self.assertInvalidSingle('def f(): pass')
self.assertInvalidSingle('a = 13\nb = 187')
self.assertInvalidSingle('del x\ndel y')
self.assertInvalidSingle('f()\ng()')
self.assertInvalidSingle('f()\n# blah\nblah()')
self.assertInvalidSingle('f()\nxy # blah\nblah()')
self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
def test_particularly_evil_undecodable(self):
# Issue 24022
src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
with tempfile.TemporaryDirectory() as tmpd:
fn = os.path.join(tmpd, "bad.py")
with open(fn, "wb") as fp:
fp.write(src)
res = script_helper.run_python_until_end(fn)[0]
self.assertIn(b"Non-UTF-8", res.err)
def test_yet_more_evil_still_undecodable(self):
# Issue #25388
src = b"#\x00\n#\xfd\n"
with tempfile.TemporaryDirectory() as tmpd:
fn = os.path.join(tmpd, "bad.py")
with open(fn, "wb") as fp:
fp.write(src)
res = script_helper.run_python_until_end(fn)[0]
self.assertIn(b"Non-UTF-8", res.err)
@support.cpython_only
def test_compiler_recursion_limit(self):
# Expected limit is sys.getrecursionlimit() * the scaling factor
# in symtable.c (currently 3)
# We expect to fail *at* that limit, because we use up some of
# the stack depth limit in the test suite code
# So we check the expected limit and 75% of that
# XXX (ncoghlan): duplicating the scaling factor here is a little
# ugly. Perhaps it should be exposed somewhere...
fail_depth = sys.getrecursionlimit() * 3
crash_depth = sys.getrecursionlimit() * 300
success_depth = int(fail_depth * 0.75)
def check_limit(prefix, repeated, mode="single"):
expect_ok = prefix + repeated * success_depth
compile(expect_ok, '<test>', mode)
for depth in (fail_depth, crash_depth):
broken = prefix + repeated * depth
details = "Compiling ({!r} + {!r} * {})".format(
prefix, repeated, depth)
with self.assertRaises(RecursionError, msg=details):
compile(broken, '<test>', mode)
check_limit("a", "()")
check_limit("a", ".b")
check_limit("a", "[0]")
check_limit("a", "*a")
# XXX Crashes in the parser.
# check_limit("a", " if a else a")
# check_limit("if a: pass", "\nelif a: pass", mode="exec")
def test_null_terminated(self):
# The source code is null-terminated internally, but bytes-like
# objects are accepted, which could be not terminated.
with self.assertRaisesRegex(ValueError, "cannot contain null"):
compile("123\x00", "<dummy>", "eval")
with self.assertRaisesRegex(ValueError, "cannot contain null"):
compile(memoryview(b"123\x00"), "<dummy>", "eval")
code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
# Also test when eval() and exec() do the compilation step
self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
namespace = dict()
exec(memoryview(b"ax = 123")[1:-1], namespace)
self.assertEqual(namespace['x'], 12)
def check_constant(self, func, expected):
for const in func.__code__.co_consts:
if repr(const) == repr(expected):
break
else:
self.fail("unable to find constant %r in %r"
% (expected, func.__code__.co_consts))
# Merging equal constants is not a strict requirement for the Python
# semantics, it's a more an implementation detail.
@support.cpython_only
def test_merge_constants(self):
# Issue #25843: compile() must merge constants which are equal
# and have the same type.
def check_same_constant(const):
ns = {}
code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
exec(code, ns)
f1 = ns['f1']
f2 = ns['f2']
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, const)
self.assertEqual(repr(f1()), repr(const))
check_same_constant(None)
check_same_constant(0)
check_same_constant(0.0)
check_same_constant(b'abc')
check_same_constant('abc')
# Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
# whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
f1, f2 = lambda: ..., lambda: ...
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, Ellipsis)
self.assertEqual(repr(f1()), repr(Ellipsis))
# Merge constants in tuple or frozenset
f1, f2 = lambda: "not a name", lambda: ("not a name",)
f3 = lambda x: x in {("not a name",)}
self.assertIs(f1.__code__.co_consts[1],
f2.__code__.co_consts[1][0])
self.assertIs(next(iter(f3.__code__.co_consts[1])),
f2.__code__.co_consts[1])
# {0} is converted to a constant frozenset({0}) by the peephole
# optimizer
f1, f2 = lambda x: x in {0}, lambda x: x in {0}
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, frozenset({0}))
self.assertTrue(f1(0))
# Merging equal co_linetable and co_code is not a strict requirement
# for the Python semantics, it's a more an implementation detail.
@support.cpython_only
def test_merge_code_attrs(self):
# See https://bugs.python.org/issue42217
f1 = lambda x: x.y.z
f2 = lambda a: a.b.c
self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable)
self.assertIs(f1.__code__.co_code, f2.__code__.co_code)
# Stripping unused constants is not a strict requirement for the
# Python semantics, it's a more an implementation detail.
@support.cpython_only
def test_strip_unused_consts(self):
# Python 3.10rc1 appended None to co_consts when None is not used
# at all. See bpo-45056.
def f1():
"docstring"
return 42
self.assertEqual(f1.__code__.co_consts, ("docstring", 42))
# This is a regression test for a CPython specific peephole optimizer
# implementation bug present in a few releases. It's assertion verifies
# that peephole optimization was actually done though that isn't an
# indication of the bugs presence or not (crashing is).
@support.cpython_only
def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
"""Regression test for issue35193 when run under clang msan."""
def unused_code_at_end():
return 3
raise RuntimeError("unreachable")
# The above function definition will trigger the out of bounds
# bug in the peephole optimizer as it scans opcodes past the
# RETURN_VALUE opcode. This does not always crash an interpreter.
# When you build with the clang memory sanitizer it reliably aborts.
self.assertEqual(
'RETURN_VALUE',
list(dis.get_instructions(unused_code_at_end))[-1].opname)
def test_dont_merge_constants(self):
# Issue #25843: compile() must not merge constants which are equal
# but have a different type.
def check_different_constants(const1, const2):
ns = {}
exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
f1 = ns['f1']
f2 = ns['f2']
self.assertIsNot(f1.__code__, f2.__code__)
self.assertNotEqual(f1.__code__, f2.__code__)
self.check_constant(f1, const1)
self.check_constant(f2, const2)
self.assertEqual(repr(f1()), repr(const1))
self.assertEqual(repr(f2()), repr(const2))
check_different_constants(0, 0.0)
check_different_constants(+0.0, -0.0)
check_different_constants((0,), (0.0,))
check_different_constants('a', b'a')
check_different_constants(('a',), (b'a',))
# check_different_constants() cannot be used because repr(-0j) is
# '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
f1, f2 = lambda: +0.0j, lambda: -0.0j
self.assertIsNot(f1.__code__, f2.__code__)
self.check_constant(f1, +0.0j)
self.check_constant(f2, -0.0j)
self.assertEqual(repr(f1()), repr(+0.0j))
self.assertEqual(repr(f2()), repr(-0.0j))
# {0} is converted to a constant frozenset({0}) by the peephole
# optimizer
f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
self.assertIsNot(f1.__code__, f2.__code__)
self.check_constant(f1, frozenset({0}))
self.check_constant(f2, frozenset({0.0}))
self.assertTrue(f1(0))
self.assertTrue(f2(0.0))
def test_path_like_objects(self):
# An implicit test for PyUnicode_FSDecoder().
compile("42", FakePath("test_compile_pathlike"), "single")
def test_stack_overflow(self):
# bpo-31113: Stack overflow when compile a long sequence of
# complex statements.
compile("if a: b\n" * 200000, "<dummy>", "exec")
# Multiple users rely on the fact that CPython does not generate
# bytecode for dead code blocks. See bpo-37500 for more context.
@support.cpython_only
def test_dead_blocks_do_not_generate_bytecode(self):
def unused_block_if():
if 0:
return 42
def unused_block_while():
while 0:
return 42
def unused_block_if_else():
if 1:
return None
else:
return 42
def unused_block_while_else():
while 1:
return None
else:
return 42
funcs = [unused_block_if, unused_block_while,
unused_block_if_else, unused_block_while_else]
for func in funcs:
opcodes = list(dis.get_instructions(func))
self.assertLessEqual(len(opcodes), 3)
self.assertEqual('LOAD_CONST', opcodes[-2].opname)
self.assertEqual(None, opcodes[-2].argval)
self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
def test_false_while_loop(self):
def break_in_while():
while False:
break
def continue_in_while():
while False:
continue
funcs = [break_in_while, continue_in_while]
# Check that we did not raise but we also don't generate bytecode
for func in funcs:
opcodes = list(dis.get_instructions(func))
self.assertEqual(2, len(opcodes))
self.assertEqual('LOAD_CONST', opcodes[0].opname)
self.assertEqual(None, opcodes[0].argval)
self.assertEqual('RETURN_VALUE', opcodes[1].opname)
def test_consts_in_conditionals(self):
def and_true(x):
return True and x
def and_false(x):
return False and x
def or_true(x):
return True or x
def or_false(x):
return False or x
funcs = [and_true, and_false, or_true, or_false]
# Check that condition is removed.
for func in funcs:
with self.subTest(func=func):
opcodes = list(dis.get_instructions(func))
self.assertEqual(2, len(opcodes))
self.assertIn('LOAD_', opcodes[0].opname)
self.assertEqual('RETURN_VALUE', opcodes[1].opname)
def test_imported_load_method(self):
sources = [
"""\
import os
def foo():
return os.uname()
""",
"""\
import os as operating_system
def foo():
return operating_system.uname()
""",
"""\
from os import path
def foo(x):
return path.join(x)
""",
"""\
from os import path as os_path
def foo(x):
return os_path.join(x)
"""
]
for source in sources:
namespace = {}
exec(textwrap.dedent(source), namespace)
func = namespace['foo']
with self.subTest(func=func.__name__):
opcodes = list(dis.get_instructions(func))
instructions = [opcode.opname for opcode in opcodes]
self.assertNotIn('LOAD_METHOD', instructions)
self.assertNotIn('CALL_METHOD', instructions)
self.assertIn('LOAD_ATTR', instructions)
self.assertIn('CALL_FUNCTION', instructions)
def test_lineno_procedure_call(self):
def call():
(
print()
)
line1 = call.__code__.co_firstlineno + 1
assert line1 not in [line for (_, _, line) in call.__code__.co_lines()]
def test_lineno_after_implicit_return(self):
TRUE = True
# Don't use constant True or False, as compiler will remove test
def if1(x):
x()
if TRUE:
pass
def if2(x):
x()
if TRUE:
pass
else:
pass
def if3(x):
x()
if TRUE:
pass
else:
return None
def if4(x):
x()
if not TRUE:
pass
funcs = [ if1, if2, if3, if4]
lastlines = [ 3, 3, 3, 2]
frame = None
def save_caller_frame():
nonlocal frame
frame = sys._getframe(1)
for func, lastline in zip(funcs, lastlines, strict=True):
with self.subTest(func=func):
func(save_caller_frame)
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline)
def test_lineno_after_no_code(self):
def no_code1():
"doc string"
def no_code2():
a: int
for func in (no_code1, no_code2):
with self.subTest(func=func):
code = func.__code__
lines = list(code.co_lines())
self.assertEqual(len(lines), 1)
start, end, line = lines[0]
self.assertEqual(start, 0)
self.assertEqual(end, len(code.co_code))
self.assertEqual(line, code.co_firstlineno)
def test_lineno_attribute(self):
def load_attr():
return (
o.
a
)
load_attr_lines = [ 2, 3, 1 ]
def load_method():
return (
o.
m(
0
)
)
load_method_lines = [ 2, 3, 4, 3, 1 ]
def store_attr():
(
o.
a
) = (
v
)
store_attr_lines = [ 5, 2, 3 ]
def aug_store_attr():
(
o.
a
) += (
v
)
aug_store_attr_lines = [ 2, 3, 5, 1, 3 ]
funcs = [ load_attr, load_method, store_attr, aug_store_attr]
func_lines = [ load_attr_lines, load_method_lines,
store_attr_lines, aug_store_attr_lines]
for func, lines in zip(funcs, func_lines, strict=True):
with self.subTest(func=func):
code_lines = [ line-func.__code__.co_firstlineno
for (_, _, line) in func.__code__.co_lines() ]
self.assertEqual(lines, code_lines)
def test_line_number_genexp(self):
def return_genexp():
return (1
for
x
in
y)
genexp_lines = [None, 1, 3, 1]
genexp_code = return_genexp.__code__.co_consts[1]
code_lines = [ None if line is None else line-return_genexp.__code__.co_firstlineno
for (_, _, line) in genexp_code.co_lines() ]
self.assertEqual(genexp_lines, code_lines)
def test_line_number_implicit_return_after_async_for(self):
async def test(aseq):
async for i in aseq:
body
expected_lines = [None, 1, 2, 1]
code_lines = [ None if line is None else line-test.__code__.co_firstlineno
for (_, _, line) in test.__code__.co_lines() ]
self.assertEqual(expected_lines, code_lines)
def test_big_dict_literal(self):
# The compiler has a flushing point in "compiler_dict" that calls compiles
# a portion of the dictionary literal when the loop that iterates over the items
# reaches 0xFFFF elements but the code was not including the boundary element,
# dropping the key at position 0xFFFF. See bpo-41531 for more information
dict_size = 0xFFFF + 1
the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}"
self.assertEqual(len(eval(the_dict)), dict_size)
def test_redundant_jump_in_if_else_break(self):
# Check if bytecode containing jumps that simply point to the next line
# is generated around if-else-break style structures. See bpo-42615.
def if_else_break():
val = 1
while True:
if val > 0:
val -= 1
else:
break
val = -1
INSTR_SIZE = 2
HANDLED_JUMPS = (
'POP_JUMP_IF_FALSE',
'POP_JUMP_IF_TRUE',
'JUMP_ABSOLUTE',
'JUMP_FORWARD',
)
for line, instr in enumerate(dis.Bytecode(if_else_break)):
if instr.opname == 'JUMP_FORWARD':
self.assertNotEqual(instr.arg, 0)
elif instr.opname in HANDLED_JUMPS:
self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE)
@requires_debug_ranges()
class TestSourcePositions(unittest.TestCase):
# Ensure that compiled code snippets have correct line and column numbers
# in `co_positions()`.
def check_positions_against_ast(self, snippet):
# Basic check that makes sure each line and column is at least present
# in one of the AST nodes of the source code.
code = compile(snippet, 'test_compile.py', 'exec')
ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
self.assertTrue(type(ast_tree) == _ast.Module)
# Use an AST visitor that notes all the offsets.
lines, end_lines, columns, end_columns = set(), set(), set(), set()
class SourceOffsetVisitor(ast.NodeVisitor):
def generic_visit(self, node):
super().generic_visit(node)
if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt):
return
lines.add(node.lineno)
end_lines.add(node.end_lineno)
columns.add(node.col_offset)
end_columns.add(node.end_col_offset)
SourceOffsetVisitor().visit(ast_tree)
# Check against the positions in the code object.
for (line, end_line, col, end_col) in code.co_positions():
# If the offset is not None (indicating missing data), ensure that
# it was part of one of the AST nodes.
if line is not None:
self.assertIn(line, lines)
if end_line is not None:
self.assertIn(end_line, end_lines)
if col is not None:
self.assertIn(col, columns)
if end_col is not None:
self.assertIn(end_col, end_columns)
return code, ast_tree
def assertOpcodeSourcePositionIs(self, code, opcode,
line, end_line, column, end_column, occurrence=1):
for instr, position in zip(dis.Bytecode(code), code.co_positions()):
if instr.opname == opcode:
occurrence -= 1
if not occurrence:
self.assertEqual(position[0], line)
self.assertEqual(position[1], end_line)
self.assertEqual(position[2], column)
self.assertEqual(position[3], end_column)
return
self.fail(f"Opcode {opcode} not found in code")
def test_simple_assignment(self):
snippet = "x = 1"
self.check_positions_against_ast(snippet)
def test_compiles_to_extended_op_arg(self):
# Make sure we still have valid positions when the code compiles to an
# EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after
# a bunch of opcodes.
snippet = "x = x\n" * 10_000
snippet += ("while x != 0:\n"
" x -= 1\n"
"while x != 0:\n"
" x += 1\n"
)
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=10_000 + 2, end_line=10_000 + 2,
column=2, end_column=8, occurrence=1)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=10_000 + 4, end_line=10_000 + 4,
column=2, end_column=9, occurrence=2)
def test_multiline_expression(self):
snippet = """\
f(
1, 2, 3, 4
)
"""
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION',
line=1, end_line=3, column=0, end_column=1)
def test_very_long_line_end_offset(self):
# Make sure we get None for when the column offset is too large to
# store in a byte.
long_string = "a" * 1000
snippet = f"g('{long_string}')"
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION',
line=1, end_line=1, column=None, end_column=None)
def test_complex_single_line_expression(self):
snippet = "a - b @ (c * x['key'] + 23)"
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR',
line=1, end_line=1, column=13, end_column=21)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=9, end_column=21, occurrence=1)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=9, end_column=26, occurrence=2)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=4, end_column=27, occurrence=3)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=0, end_column=27, occurrence=4)
class TestExpressionStackSize(unittest.TestCase):
# These tests check that the computed stack size for a code object
# stays within reasonable bounds (see issue #21523 for an example
# dysfunction).
N = 100
def check_stack_size(self, code):
# To assert that the alleged stack size is not O(N), we
# check that it is smaller than log(N).
if isinstance(code, str):
code = compile(code, "<foo>", "single")
max_size = math.ceil(math.log(len(code.co_code)))
self.assertLessEqual(code.co_stacksize, max_size)
def test_and(self):
self.check_stack_size("x and " * self.N + "x")
def test_or(self):
self.check_stack_size("x or " * self.N + "x")
def test_and_or(self):
self.check_stack_size("x and x or " * self.N + "x")
def test_chained_comparison(self):
self.check_stack_size("x < " * self.N + "x")
def test_if_else(self):
self.check_stack_size("x if x else " * self.N + "x")
def test_binop(self):
self.check_stack_size("x + " * self.N + "x")
def test_list(self):
self.check_stack_size("[" + "x, " * self.N + "x]")
def test_tuple(self):
self.check_stack_size("(" + "x, " * self.N + "x)")
def test_set(self):
self.check_stack_size("{" + "x, " * self.N + "x}")
def test_dict(self):
self.check_stack_size("{" + "x:x, " * self.N + "x:x}")
def test_func_args(self):
self.check_stack_size("f(" + "x, " * self.N + ")")
def test_func_kwargs(self):
kwargs = (f'a{i}=x' for i in range(self.N))
self.check_stack_size("f(" + ", ".join(kwargs) + ")")
def test_func_args(self):
self.check_stack_size("o.m(" + "x, " * self.N + ")")
def test_meth_kwargs(self):
kwargs = (f'a{i}=x' for i in range(self.N))
self.check_stack_size("o.m(" + ", ".join(kwargs) + ")")
def test_func_and(self):
code = "def f(x):\n"
code += " x and x\n" * self.N
self.check_stack_size(code)
class TestStackSizeStability(unittest.TestCase):
# Check that repeating certain snippets doesn't increase the stack size
# beyond what a single snippet requires.
def check_stack_size(self, snippet, async_=False):
def compile_snippet(i):
ns = {}
script = """def func():\n""" + i * snippet
if async_:
script = "async " + script
code = compile(script, "<script>", "exec")
exec(code, ns, ns)
return ns['func'].__code__
sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
if len(set(sizes)) != 1:
import dis, io
out = io.StringIO()
dis.dis(compile_snippet(1), file=out)
self.fail("stack sizes diverge with # of consecutive snippets: "
"%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
def test_if(self):
snippet = """
if x:
a
"""
self.check_stack_size(snippet)
def test_if_else(self):
snippet = """
if x:
a
elif y:
b
else:
c
"""
self.check_stack_size(snippet)
def test_try_except_bare(self):
snippet = """
try:
a
except:
b
"""
self.check_stack_size(snippet)
def test_try_except_qualified(self):
snippet = """
try:
a
except ImportError:
b
except:
c
else:
d
"""
self.check_stack_size(snippet)
def test_try_except_as(self):
snippet = """
try:
a
except ImportError as e:
b
except:
c
else:
d
"""
self.check_stack_size(snippet)
def test_try_finally(self):
snippet = """
try:
a
finally:
b
"""
self.check_stack_size(snippet)
def test_with(self):
snippet = """
with x as y:
a
"""
self.check_stack_size(snippet)
def test_while_else(self):
snippet = """
while x:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for(self):
snippet = """
for x in y:
a
"""
self.check_stack_size(snippet)
def test_for_else(self):
snippet = """
for x in y:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue(self):
snippet = """
for x in y:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_try_finally_block(self):
snippet = """
for x in y:
try:
if z:
break
elif u:
continue
else:
a
finally:
f
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_finally_block(self):
snippet = """
for x in y:
try:
t
finally:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_except_block(self):
snippet = """
for x in y:
try:
t
except:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_with_block(self):
snippet = """
for x in y:
with c:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_return_inside_try_finally_block(self):
snippet = """
try:
if z:
return
else:
a
finally:
f
"""
self.check_stack_size(snippet)
def test_return_inside_finally_block(self):
snippet = """
try:
t
finally:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_return_inside_except_block(self):
snippet = """
try:
t
except:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_return_inside_with_block(self):
snippet = """
with c:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_async_with(self):
snippet = """
async with x as y:
a
"""
self.check_stack_size(snippet, async_=True)
def test_async_for(self):
snippet = """
async for x in y:
a
"""
self.check_stack_size(snippet, async_=True)
def test_async_for_else(self):
snippet = """
async for x in y:
a
else:
b
"""
self.check_stack_size(snippet, async_=True)
def test_for_break_continue_inside_async_with_block(self):
snippet = """
for x in y:
async with c:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet, async_=True)
def test_return_inside_async_with_block(self):
snippet = """
async with c:
if z:
return
else:
a
"""
self.check_stack_size(snippet, async_=True)
if __name__ == "__main__":
unittest.main()
| 34.782726 | 95 | 0.536122 | import dis
import math
import os
import unittest
import sys
import ast
import _ast
import tempfile
import types
import textwrap
from test import support
from test.support import script_helper, requires_debug_ranges
from test.support.os_helper import FakePath
class TestSpecifics(unittest.TestCase):
def compile_single(self, source):
compile(source, "<single>", "single")
def assertInvalidSingle(self, source):
self.assertRaises(SyntaxError, self.compile_single, source)
def test_no_ending_newline(self):
compile("hi", "<test>", "exec")
compile("hi\r", "<test>", "exec")
def test_empty(self):
compile("", "<test>", "exec")
def test_other_newlines(self):
compile("\r\n", "<test>", "exec")
compile("\r", "<test>", "exec")
compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")
def test_debug_assignment(self):
self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
import builtins
prev = builtins.__debug__
setattr(builtins, '__debug__', 'sure')
self.assertEqual(__debug__, prev)
setattr(builtins, '__debug__', prev)
def test_argument_handling(self):
self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
self.assertRaises(SyntaxError, exec, 'def f(a, a): pass')
self.assertRaises(SyntaxError, exec, 'def f(a = 0, a = 1): pass')
self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
def test_syntax_error(self):
self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
def test_none_keyword_arg(self):
self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
def test_duplicate_global_local(self):
self.assertRaises(SyntaxError, exec, 'def f(a): global a; a = 1')
def test_exec_with_general_mapping_for_locals(self):
class M:
def __getitem__(self, key):
if key == 'a':
return 12
raise KeyError
def __setitem__(self, key, value):
self.results = (key, value)
def keys(self):
return list('xyz')
m = M()
g = globals()
exec('z = a', g, m)
self.assertEqual(m.results, ('z', 12))
try:
exec('z = b', g, m)
except NameError:
pass
else:
self.fail('Did not detect a KeyError')
exec('z = dir()', g, m)
self.assertEqual(m.results, ('z', list('xyz')))
exec('z = globals()', g, m)
self.assertEqual(m.results, ('z', g))
exec('z = locals()', g, m)
self.assertEqual(m.results, ('z', m))
self.assertRaises(TypeError, exec, 'z = b', m)
class A:
pass
m = A()
self.assertRaises(TypeError, exec, 'z = a', g, m)
class D(dict):
def __getitem__(self, key):
if key == 'a':
return 12
return dict.__getitem__(self, key)
d = D()
exec('z = a', g, d)
self.assertEqual(d['z'], 12)
def test_extended_arg(self):
longexpr = 'x = x or ' + '-x' * 2500
g = {}
code = '''
def f(x):
%s
%s
%s
%s
%s
%s
%s
%s
%s
%s
# the expressions above have no effect, x == argument
while x:
x -= 1
# EXTENDED_ARG/JUMP_ABSOLUTE here
return x
''' % ((longexpr,)*10)
exec(code, g)
self.assertEqual(g['f'](5), 0)
def test_argument_order(self):
self.assertRaises(SyntaxError, exec, 'def f(a=1, b): pass')
def test_float_literals(self):
self.assertRaises(SyntaxError, eval, "2e")
self.assertRaises(SyntaxError, eval, "2.0e+")
self.assertRaises(SyntaxError, eval, "1e-")
self.assertRaises(SyntaxError, eval, "3-4e/21")
def test_indentation(self):
s = """
if 1:
if 2:
pass"""
compile(s, "<string>", "exec")
# This test is probably specific to CPython and may not generalize
# to other implementations. We are trying to ensure that when
# the first line of code starts after 256, correct line numbers
# in tracebacks are still produced.
def test_leading_newlines(self):
s256 = "".join(["\n"] * 256 + ["spam"])
co = compile(s256, 'fn', 'exec')
self.assertEqual(co.co_firstlineno, 1)
self.assertEqual(list(co.co_lines()), [(0, 8, 257)])
def test_literals_with_leading_zeroes(self):
for arg in ["077787", "0xj", "0x.", "0e", "090000000000000",
"080000000000000", "000000000000009", "000000000000008",
"0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
"0b101j", "0o153j", "0b100e1", "0o777e1", "0777",
"000777", "000000000000007"]:
self.assertRaises(SyntaxError, eval, arg)
self.assertEqual(eval("0xff"), 255)
self.assertEqual(eval("0777."), 777)
self.assertEqual(eval("0777.0"), 777)
self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
self.assertEqual(eval("0777e1"), 7770)
self.assertEqual(eval("0e0"), 0)
self.assertEqual(eval("0000e-012"), 0)
self.assertEqual(eval("09.5"), 9.5)
self.assertEqual(eval("0777j"), 777j)
self.assertEqual(eval("000"), 0)
self.assertEqual(eval("00j"), 0j)
self.assertEqual(eval("00.0"), 0)
self.assertEqual(eval("0e3"), 0)
self.assertEqual(eval("090000000000000."), 90000000000000.)
self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
self.assertEqual(eval("090000000000000e0"), 90000000000000.)
self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
self.assertEqual(eval("090000000000000j"), 90000000000000j)
self.assertEqual(eval("000000000000008."), 8.)
self.assertEqual(eval("000000000000009."), 9.)
self.assertEqual(eval("0b101010"), 42)
self.assertEqual(eval("-0b000000000010"), -2)
self.assertEqual(eval("0o777"), 511)
self.assertEqual(eval("-0o0000010"), -8)
def test_unary_minus(self):
# Verify treatment of unary minus on negative numbers SF bug #660455
if sys.maxsize == 2147483647:
# 32-bit machine
all_one_bits = '0xffffffff'
self.assertEqual(eval(all_one_bits), 4294967295)
self.assertEqual(eval("-" + all_one_bits), -4294967295)
elif sys.maxsize == 9223372036854775807:
# 64-bit machine
all_one_bits = '0xffffffffffffffff'
self.assertEqual(eval(all_one_bits), 18446744073709551615)
self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
else:
self.fail("How many bits *does* this machine have???")
# Verify treatment of constant folding on -(sys.maxsize+1)
# i.e. -2147483648 on 32 bit platforms. Should return int.
self.assertIsInstance(eval("%s" % (-sys.maxsize - 1)), int)
self.assertIsInstance(eval("%s" % (-sys.maxsize - 2)), int)
if sys.maxsize == 9223372036854775807:
def test_32_63_bit_values(self):
a = +4294967296 # 1 << 32
b = -4294967296 # 1 << 32
c = +281474976710656 # 1 << 48
d = -281474976710656 # 1 << 48
e = +4611686018427387904 # 1 << 62
f = -4611686018427387904 # 1 << 62
g = +9223372036854775807 # 1 << 63 - 1
h = -9223372036854775807 # 1 << 63 - 1
for variable in self.test_32_63_bit_values.__code__.co_consts:
if variable is not None:
self.assertIsInstance(variable, int)
def test_sequence_unpacking_error(self):
# Verify sequence packing/unpacking with "or". SF bug #757818
i,j = (1, -1) or (-1, 1)
self.assertEqual(i, 1)
self.assertEqual(j, -1)
def test_none_assignment(self):
stmts = [
'None = 0',
'None += 0',
'__builtins__.None = 0',
'def None(): pass',
'class None: pass',
'(a, None) = 0, 0',
'for None in range(10): pass',
'def f(None): pass',
'import None',
'import x as None',
'from x import None',
'from x import y as None'
]
for stmt in stmts:
stmt += "\n"
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
def test_import(self):
succeed = [
'import sys',
'import os, sys',
'import os as bar',
'import os.path as bar',
'from __future__ import nested_scopes, generators',
'from __future__ import (nested_scopes,\ngenerators)',
'from __future__ import (nested_scopes,\ngenerators,)',
'from sys import stdin, stderr, stdout',
'from sys import (stdin, stderr,\nstdout)',
'from sys import (stdin, stderr,\nstdout,)',
'from sys import (stdin\n, stderr, stdout)',
'from sys import (stdin\n, stderr, stdout,)',
'from sys import stdin as si, stdout as so, stderr as se',
'from sys import (stdin as si, stdout as so, stderr as se)',
'from sys import (stdin as si, stdout as so, stderr as se,)',
]
fail = [
'import (os, sys)',
'import (os), (sys)',
'import ((os), (sys))',
'import (sys',
'import sys)',
'import (os,)',
'import os As bar',
'import os.path a bar',
'from sys import stdin As stdout',
'from sys import stdin a stdout',
'from (sys) import stdin',
'from __future__ import (nested_scopes',
'from __future__ import nested_scopes)',
'from __future__ import nested_scopes,\ngenerators',
'from sys import (stdin',
'from sys import stdin)',
'from sys import stdin, stdout,\nstderr',
'from sys import stdin si',
'from sys import stdin,',
'from sys import (*)',
'from sys import (stdin,, stdout, stderr)',
'from sys import (stdin, stdout),',
]
for stmt in succeed:
compile(stmt, 'tmp', 'exec')
for stmt in fail:
self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
def test_for_distinct_code_objects(self):
# SF bug 1048870
def f():
f1 = lambda x=1: x
f2 = lambda x=2: x
return f1, f2
f1, f2 = f()
self.assertNotEqual(id(f1.__code__), id(f2.__code__))
def test_lambda_doc(self):
l = lambda: "foo"
self.assertIsNone(l.__doc__)
def test_encoding(self):
code = b'# -*- coding: badencoding -*-\npass\n'
self.assertRaises(SyntaxError, compile, code, 'tmp', 'exec')
code = '# -*- coding: badencoding -*-\n"\xc2\xa4"\n'
compile(code, 'tmp', 'exec')
self.assertEqual(eval(code), '\xc2\xa4')
code = '"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\xa4')
code = b'"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xa4')
code = b'# -*- coding: latin1 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\xa4')
code = b'# -*- coding: utf-8 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xa4')
code = b'# -*- coding: iso8859-15 -*-\n"\xc2\xa4"\n'
self.assertEqual(eval(code), '\xc2\u20ac')
code = '"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xc2\xa4')
code = b'"""\\\n# -*- coding: iso8859-15 -*-\n\xc2\xa4"""\n'
self.assertEqual(eval(code), '# -*- coding: iso8859-15 -*-\n\xa4')
def test_subscripts(self):
# SF bug 1448804
# Class to make testing subscript results easy
class str_map(object):
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data[str(key)]
def __setitem__(self, key, value):
self.data[str(key)] = value
def __delitem__(self, key):
del self.data[str(key)]
def __contains__(self, key):
return str(key) in self.data
d = str_map()
# Index
d[1] = 1
self.assertEqual(d[1], 1)
d[1] += 1
self.assertEqual(d[1], 2)
del d[1]
self.assertNotIn(1, d)
# Tuple of indices
d[1, 1] = 1
self.assertEqual(d[1, 1], 1)
d[1, 1] += 1
self.assertEqual(d[1, 1], 2)
del d[1, 1]
self.assertNotIn((1, 1), d)
# Simple slice
d[1:2] = 1
self.assertEqual(d[1:2], 1)
d[1:2] += 1
self.assertEqual(d[1:2], 2)
del d[1:2]
self.assertNotIn(slice(1, 2), d)
# Tuple of simple slices
d[1:2, 1:2] = 1
self.assertEqual(d[1:2, 1:2], 1)
d[1:2, 1:2] += 1
self.assertEqual(d[1:2, 1:2], 2)
del d[1:2, 1:2]
self.assertNotIn((slice(1, 2), slice(1, 2)), d)
# Extended slice
d[1:2:3] = 1
self.assertEqual(d[1:2:3], 1)
d[1:2:3] += 1
self.assertEqual(d[1:2:3], 2)
del d[1:2:3]
self.assertNotIn(slice(1, 2, 3), d)
# Tuple of extended slices
d[1:2:3, 1:2:3] = 1
self.assertEqual(d[1:2:3, 1:2:3], 1)
d[1:2:3, 1:2:3] += 1
self.assertEqual(d[1:2:3, 1:2:3], 2)
del d[1:2:3, 1:2:3]
self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
# Ellipsis
d[...] = 1
self.assertEqual(d[...], 1)
d[...] += 1
self.assertEqual(d[...], 2)
del d[...]
self.assertNotIn(Ellipsis, d)
# Tuple of Ellipses
d[..., ...] = 1
self.assertEqual(d[..., ...], 1)
d[..., ...] += 1
self.assertEqual(d[..., ...], 2)
del d[..., ...]
self.assertNotIn((Ellipsis, Ellipsis), d)
def test_annotation_limit(self):
# more than 255 annotations, should compile ok
s = "def f(%s): pass"
s %= ', '.join('a%d:%d' % (i,i) for i in range(300))
compile(s, '?', 'exec')
def test_mangling(self):
class A:
def f():
__mangled = 1
__not_mangled__ = 2
import __mangled_mod
import __package__.module
self.assertIn("_A__mangled", A.f.__code__.co_varnames)
self.assertIn("__not_mangled__", A.f.__code__.co_varnames)
self.assertIn("_A__mangled_mod", A.f.__code__.co_varnames)
self.assertIn("__package__", A.f.__code__.co_varnames)
def test_compile_ast(self):
fname = __file__
if fname.lower().endswith('pyc'):
fname = fname[:-1]
with open(fname, encoding='utf-8') as f:
fcontents = f.read()
sample_code = [
['<assign>', 'x = 5'],
['<ifblock>', """if True:\n pass\n"""],
['<forblock>', """for n in [1, 2, 3]:\n print(n)\n"""],
['<deffunc>', """def foo():\n pass\nfoo()\n"""],
[fname, fcontents],
]
for fname, code in sample_code:
co1 = compile(code, '%s1' % fname, 'exec')
ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
self.assertTrue(type(ast) == _ast.Module)
co2 = compile(ast, '%s3' % fname, 'exec')
self.assertEqual(co1, co2)
# the code object's filename comes from the second compilation step
self.assertEqual(co2.co_filename, '%s3' % fname)
# raise exception when node type doesn't match with compile mode
co1 = compile('print(1)', '<string>', 'exec', _ast.PyCF_ONLY_AST)
self.assertRaises(TypeError, compile, co1, '<ast>', 'eval')
# raise exception when node type is no start node
self.assertRaises(TypeError, compile, _ast.If(), '<ast>', 'exec')
# raise exception when node has invalid children
ast = _ast.Module()
ast.body = [_ast.BoolOp()]
self.assertRaises(TypeError, compile, ast, '<ast>', 'exec')
def test_dict_evaluation_order(self):
i = 0
def f():
nonlocal i
i += 1
return i
d = {f(): f(), f(): f()}
self.assertEqual(d, {1: 2, 3: 4})
def test_compile_filename(self):
for filename in 'file.py', b'file.py':
code = compile('pass', filename, 'exec')
self.assertEqual(code.co_filename, 'file.py')
for filename in bytearray(b'file.py'), memoryview(b'file.py'):
with self.assertWarns(DeprecationWarning):
code = compile('pass', filename, 'exec')
self.assertEqual(code.co_filename, 'file.py')
self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
@support.cpython_only
def test_same_filename_used(self):
s = """def f(): pass\ndef g(): pass"""
c = compile(s, "myfile", "exec")
for obj in c.co_consts:
if isinstance(obj, types.CodeType):
self.assertIs(obj.co_filename, c.co_filename)
def test_single_statement(self):
self.compile_single("1 + 2")
self.compile_single("\n1 + 2")
self.compile_single("1 + 2\n")
self.compile_single("1 + 2\n\n")
self.compile_single("1 + 2\t\t\n")
self.compile_single("1 + 2\t\t\n ")
self.compile_single("1 + 2
self.compile_single("1; 2")
self.compile_single("import sys; sys")
self.compile_single("def f():\n pass")
self.compile_single("while False:\n pass")
self.compile_single("if x:\n f(x)")
self.compile_single("if x:\n f(x)\nelse:\n g(x)")
self.compile_single("class T:\n pass")
def test_bad_single_statement(self):
self.assertInvalidSingle('1\n2')
self.assertInvalidSingle('def f(): pass')
self.assertInvalidSingle('a = 13\nb = 187')
self.assertInvalidSingle('del x\ndel y')
self.assertInvalidSingle('f()\ng()')
self.assertInvalidSingle('f()\n# blah\nblah()')
self.assertInvalidSingle('f()\nxy # blah\nblah()')
self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
def test_particularly_evil_undecodable(self):
# Issue 24022
src = b'0000\x00\n00000000000\n\x00\n\x9e\n'
with tempfile.TemporaryDirectory() as tmpd:
fn = os.path.join(tmpd, "bad.py")
with open(fn, "wb") as fp:
fp.write(src)
res = script_helper.run_python_until_end(fn)[0]
self.assertIn(b"Non-UTF-8", res.err)
def test_yet_more_evil_still_undecodable(self):
# Issue #25388
src = b" with tempfile.TemporaryDirectory() as tmpd:
fn = os.path.join(tmpd, "bad.py")
with open(fn, "wb") as fp:
fp.write(src)
res = script_helper.run_python_until_end(fn)[0]
self.assertIn(b"Non-UTF-8", res.err)
@support.cpython_only
def test_compiler_recursion_limit(self):
# Expected limit is sys.getrecursionlimit() * the scaling factor
# in symtable.c (currently 3)
# We expect to fail *at* that limit, because we use up some of
# the stack depth limit in the test suite code
# So we check the expected limit and 75% of that
# XXX (ncoghlan): duplicating the scaling factor here is a little
# ugly. Perhaps it should be exposed somewhere...
fail_depth = sys.getrecursionlimit() * 3
crash_depth = sys.getrecursionlimit() * 300
success_depth = int(fail_depth * 0.75)
def check_limit(prefix, repeated, mode="single"):
expect_ok = prefix + repeated * success_depth
compile(expect_ok, '<test>', mode)
for depth in (fail_depth, crash_depth):
broken = prefix + repeated * depth
details = "Compiling ({!r} + {!r} * {})".format(
prefix, repeated, depth)
with self.assertRaises(RecursionError, msg=details):
compile(broken, '<test>', mode)
check_limit("a", "()")
check_limit("a", ".b")
check_limit("a", "[0]")
check_limit("a", "*a")
# XXX Crashes in the parser.
# check_limit("a", " if a else a")
# check_limit("if a: pass", "\nelif a: pass", mode="exec")
def test_null_terminated(self):
# The source code is null-terminated internally, but bytes-like
# objects are accepted, which could be not terminated.
with self.assertRaisesRegex(ValueError, "cannot contain null"):
compile("123\x00", "<dummy>", "eval")
with self.assertRaisesRegex(ValueError, "cannot contain null"):
compile(memoryview(b"123\x00"), "<dummy>", "eval")
code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
code = compile(memoryview(b"1234")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
code = compile(memoryview(b"$23$")[1:-1], "<dummy>", "eval")
self.assertEqual(eval(code), 23)
# Also test when eval() and exec() do the compilation step
self.assertEqual(eval(memoryview(b"1234")[1:-1]), 23)
namespace = dict()
exec(memoryview(b"ax = 123")[1:-1], namespace)
self.assertEqual(namespace['x'], 12)
def check_constant(self, func, expected):
for const in func.__code__.co_consts:
if repr(const) == repr(expected):
break
else:
self.fail("unable to find constant %r in %r"
% (expected, func.__code__.co_consts))
# Merging equal constants is not a strict requirement for the Python
# semantics, it's a more an implementation detail.
@support.cpython_only
def test_merge_constants(self):
# Issue #25843: compile() must merge constants which are equal
# and have the same type.
def check_same_constant(const):
ns = {}
code = "f1, f2 = lambda: %r, lambda: %r" % (const, const)
exec(code, ns)
f1 = ns['f1']
f2 = ns['f2']
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, const)
self.assertEqual(repr(f1()), repr(const))
check_same_constant(None)
check_same_constant(0)
check_same_constant(0.0)
check_same_constant(b'abc')
check_same_constant('abc')
# Note: "lambda: ..." emits "LOAD_CONST Ellipsis",
# whereas "lambda: Ellipsis" emits "LOAD_GLOBAL Ellipsis"
f1, f2 = lambda: ..., lambda: ...
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, Ellipsis)
self.assertEqual(repr(f1()), repr(Ellipsis))
# Merge constants in tuple or frozenset
f1, f2 = lambda: "not a name", lambda: ("not a name",)
f3 = lambda x: x in {("not a name",)}
self.assertIs(f1.__code__.co_consts[1],
f2.__code__.co_consts[1][0])
self.assertIs(next(iter(f3.__code__.co_consts[1])),
f2.__code__.co_consts[1])
# {0} is converted to a constant frozenset({0}) by the peephole
# optimizer
f1, f2 = lambda x: x in {0}, lambda x: x in {0}
self.assertIs(f1.__code__, f2.__code__)
self.check_constant(f1, frozenset({0}))
self.assertTrue(f1(0))
# Merging equal co_linetable and co_code is not a strict requirement
# for the Python semantics, it's a more an implementation detail.
@support.cpython_only
def test_merge_code_attrs(self):
# See https://bugs.python.org/issue42217
f1 = lambda x: x.y.z
f2 = lambda a: a.b.c
self.assertIs(f1.__code__.co_linetable, f2.__code__.co_linetable)
self.assertIs(f1.__code__.co_code, f2.__code__.co_code)
# Stripping unused constants is not a strict requirement for the
# Python semantics, it's a more an implementation detail.
@support.cpython_only
def test_strip_unused_consts(self):
# Python 3.10rc1 appended None to co_consts when None is not used
# at all. See bpo-45056.
def f1():
return 42
self.assertEqual(f1.__code__.co_consts, ("docstring", 42))
# This is a regression test for a CPython specific peephole optimizer
# implementation bug present in a few releases. It's assertion verifies
# that peephole optimization was actually done though that isn't an
# indication of the bugs presence or not (crashing is).
@support.cpython_only
def test_peephole_opt_unreachable_code_array_access_in_bounds(self):
def unused_code_at_end():
return 3
raise RuntimeError("unreachable")
# The above function definition will trigger the out of bounds
# bug in the peephole optimizer as it scans opcodes past the
# RETURN_VALUE opcode. This does not always crash an interpreter.
# When you build with the clang memory sanitizer it reliably aborts.
self.assertEqual(
'RETURN_VALUE',
list(dis.get_instructions(unused_code_at_end))[-1].opname)
def test_dont_merge_constants(self):
# Issue #25843: compile() must not merge constants which are equal
# but have a different type.
def check_different_constants(const1, const2):
ns = {}
exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns)
f1 = ns['f1']
f2 = ns['f2']
self.assertIsNot(f1.__code__, f2.__code__)
self.assertNotEqual(f1.__code__, f2.__code__)
self.check_constant(f1, const1)
self.check_constant(f2, const2)
self.assertEqual(repr(f1()), repr(const1))
self.assertEqual(repr(f2()), repr(const2))
check_different_constants(0, 0.0)
check_different_constants(+0.0, -0.0)
check_different_constants((0,), (0.0,))
check_different_constants('a', b'a')
check_different_constants(('a',), (b'a',))
# check_different_constants() cannot be used because repr(-0j) is
# '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign.
f1, f2 = lambda: +0.0j, lambda: -0.0j
self.assertIsNot(f1.__code__, f2.__code__)
self.check_constant(f1, +0.0j)
self.check_constant(f2, -0.0j)
self.assertEqual(repr(f1()), repr(+0.0j))
self.assertEqual(repr(f2()), repr(-0.0j))
# {0} is converted to a constant frozenset({0}) by the peephole
# optimizer
f1, f2 = lambda x: x in {0}, lambda x: x in {0.0}
self.assertIsNot(f1.__code__, f2.__code__)
self.check_constant(f1, frozenset({0}))
self.check_constant(f2, frozenset({0.0}))
self.assertTrue(f1(0))
self.assertTrue(f2(0.0))
def test_path_like_objects(self):
# An implicit test for PyUnicode_FSDecoder().
compile("42", FakePath("test_compile_pathlike"), "single")
def test_stack_overflow(self):
# bpo-31113: Stack overflow when compile a long sequence of
# complex statements.
compile("if a: b\n" * 200000, "<dummy>", "exec")
# Multiple users rely on the fact that CPython does not generate
# bytecode for dead code blocks. See bpo-37500 for more context.
@support.cpython_only
def test_dead_blocks_do_not_generate_bytecode(self):
def unused_block_if():
if 0:
return 42
def unused_block_while():
while 0:
return 42
def unused_block_if_else():
if 1:
return None
else:
return 42
def unused_block_while_else():
while 1:
return None
else:
return 42
funcs = [unused_block_if, unused_block_while,
unused_block_if_else, unused_block_while_else]
for func in funcs:
opcodes = list(dis.get_instructions(func))
self.assertLessEqual(len(opcodes), 3)
self.assertEqual('LOAD_CONST', opcodes[-2].opname)
self.assertEqual(None, opcodes[-2].argval)
self.assertEqual('RETURN_VALUE', opcodes[-1].opname)
def test_false_while_loop(self):
def break_in_while():
while False:
break
def continue_in_while():
while False:
continue
funcs = [break_in_while, continue_in_while]
# Check that we did not raise but we also don't generate bytecode
for func in funcs:
opcodes = list(dis.get_instructions(func))
self.assertEqual(2, len(opcodes))
self.assertEqual('LOAD_CONST', opcodes[0].opname)
self.assertEqual(None, opcodes[0].argval)
self.assertEqual('RETURN_VALUE', opcodes[1].opname)
def test_consts_in_conditionals(self):
def and_true(x):
return True and x
def and_false(x):
return False and x
def or_true(x):
return True or x
def or_false(x):
return False or x
funcs = [and_true, and_false, or_true, or_false]
# Check that condition is removed.
for func in funcs:
with self.subTest(func=func):
opcodes = list(dis.get_instructions(func))
self.assertEqual(2, len(opcodes))
self.assertIn('LOAD_', opcodes[0].opname)
self.assertEqual('RETURN_VALUE', opcodes[1].opname)
def test_imported_load_method(self):
sources = [
"""\
import os
def foo():
return os.uname()
""",
"""\
import os as operating_system
def foo():
return operating_system.uname()
""",
"""\
from os import path
def foo(x):
return path.join(x)
""",
"""\
from os import path as os_path
def foo(x):
return os_path.join(x)
"""
]
for source in sources:
namespace = {}
exec(textwrap.dedent(source), namespace)
func = namespace['foo']
with self.subTest(func=func.__name__):
opcodes = list(dis.get_instructions(func))
instructions = [opcode.opname for opcode in opcodes]
self.assertNotIn('LOAD_METHOD', instructions)
self.assertNotIn('CALL_METHOD', instructions)
self.assertIn('LOAD_ATTR', instructions)
self.assertIn('CALL_FUNCTION', instructions)
def test_lineno_procedure_call(self):
def call():
(
print()
)
line1 = call.__code__.co_firstlineno + 1
assert line1 not in [line for (_, _, line) in call.__code__.co_lines()]
def test_lineno_after_implicit_return(self):
TRUE = True
# Don't use constant True or False, as compiler will remove test
def if1(x):
x()
if TRUE:
pass
def if2(x):
x()
if TRUE:
pass
else:
pass
def if3(x):
x()
if TRUE:
pass
else:
return None
def if4(x):
x()
if not TRUE:
pass
funcs = [ if1, if2, if3, if4]
lastlines = [ 3, 3, 3, 2]
frame = None
def save_caller_frame():
nonlocal frame
frame = sys._getframe(1)
for func, lastline in zip(funcs, lastlines, strict=True):
with self.subTest(func=func):
func(save_caller_frame)
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, lastline)
def test_lineno_after_no_code(self):
def no_code1():
def no_code2():
a: int
for func in (no_code1, no_code2):
with self.subTest(func=func):
code = func.__code__
lines = list(code.co_lines())
self.assertEqual(len(lines), 1)
start, end, line = lines[0]
self.assertEqual(start, 0)
self.assertEqual(end, len(code.co_code))
self.assertEqual(line, code.co_firstlineno)
def test_lineno_attribute(self):
def load_attr():
return (
o.
a
)
load_attr_lines = [ 2, 3, 1 ]
def load_method():
return (
o.
m(
0
)
)
load_method_lines = [ 2, 3, 4, 3, 1 ]
def store_attr():
(
o.
a
) = (
v
)
store_attr_lines = [ 5, 2, 3 ]
def aug_store_attr():
(
o.
a
) += (
v
)
aug_store_attr_lines = [ 2, 3, 5, 1, 3 ]
funcs = [ load_attr, load_method, store_attr, aug_store_attr]
func_lines = [ load_attr_lines, load_method_lines,
store_attr_lines, aug_store_attr_lines]
for func, lines in zip(funcs, func_lines, strict=True):
with self.subTest(func=func):
code_lines = [ line-func.__code__.co_firstlineno
for (_, _, line) in func.__code__.co_lines() ]
self.assertEqual(lines, code_lines)
def test_line_number_genexp(self):
def return_genexp():
return (1
for
x
in
y)
genexp_lines = [None, 1, 3, 1]
genexp_code = return_genexp.__code__.co_consts[1]
code_lines = [ None if line is None else line-return_genexp.__code__.co_firstlineno
for (_, _, line) in genexp_code.co_lines() ]
self.assertEqual(genexp_lines, code_lines)
def test_line_number_implicit_return_after_async_for(self):
async def test(aseq):
async for i in aseq:
body
expected_lines = [None, 1, 2, 1]
code_lines = [ None if line is None else line-test.__code__.co_firstlineno
for (_, _, line) in test.__code__.co_lines() ]
self.assertEqual(expected_lines, code_lines)
def test_big_dict_literal(self):
# The compiler has a flushing point in "compiler_dict" that calls compiles
# a portion of the dictionary literal when the loop that iterates over the items
# reaches 0xFFFF elements but the code was not including the boundary element,
# dropping the key at position 0xFFFF. See bpo-41531 for more information
dict_size = 0xFFFF + 1
the_dict = "{" + ",".join(f"{x}:{x}" for x in range(dict_size)) + "}"
self.assertEqual(len(eval(the_dict)), dict_size)
def test_redundant_jump_in_if_else_break(self):
# Check if bytecode containing jumps that simply point to the next line
# is generated around if-else-break style structures. See bpo-42615.
def if_else_break():
val = 1
while True:
if val > 0:
val -= 1
else:
break
val = -1
INSTR_SIZE = 2
HANDLED_JUMPS = (
'POP_JUMP_IF_FALSE',
'POP_JUMP_IF_TRUE',
'JUMP_ABSOLUTE',
'JUMP_FORWARD',
)
for line, instr in enumerate(dis.Bytecode(if_else_break)):
if instr.opname == 'JUMP_FORWARD':
self.assertNotEqual(instr.arg, 0)
elif instr.opname in HANDLED_JUMPS:
self.assertNotEqual(instr.arg, (line + 1)*INSTR_SIZE)
@requires_debug_ranges()
class TestSourcePositions(unittest.TestCase):
# Ensure that compiled code snippets have correct line and column numbers
# in `co_positions()`.
def check_positions_against_ast(self, snippet):
# Basic check that makes sure each line and column is at least present
# in one of the AST nodes of the source code.
code = compile(snippet, 'test_compile.py', 'exec')
ast_tree = compile(snippet, 'test_compile.py', 'exec', _ast.PyCF_ONLY_AST)
self.assertTrue(type(ast_tree) == _ast.Module)
# Use an AST visitor that notes all the offsets.
lines, end_lines, columns, end_columns = set(), set(), set(), set()
class SourceOffsetVisitor(ast.NodeVisitor):
def generic_visit(self, node):
super().generic_visit(node)
if not isinstance(node, ast.expr) and not isinstance(node, ast.stmt):
return
lines.add(node.lineno)
end_lines.add(node.end_lineno)
columns.add(node.col_offset)
end_columns.add(node.end_col_offset)
SourceOffsetVisitor().visit(ast_tree)
# Check against the positions in the code object.
for (line, end_line, col, end_col) in code.co_positions():
# If the offset is not None (indicating missing data), ensure that
# it was part of one of the AST nodes.
if line is not None:
self.assertIn(line, lines)
if end_line is not None:
self.assertIn(end_line, end_lines)
if col is not None:
self.assertIn(col, columns)
if end_col is not None:
self.assertIn(end_col, end_columns)
return code, ast_tree
def assertOpcodeSourcePositionIs(self, code, opcode,
line, end_line, column, end_column, occurrence=1):
for instr, position in zip(dis.Bytecode(code), code.co_positions()):
if instr.opname == opcode:
occurrence -= 1
if not occurrence:
self.assertEqual(position[0], line)
self.assertEqual(position[1], end_line)
self.assertEqual(position[2], column)
self.assertEqual(position[3], end_column)
return
self.fail(f"Opcode {opcode} not found in code")
def test_simple_assignment(self):
snippet = "x = 1"
self.check_positions_against_ast(snippet)
def test_compiles_to_extended_op_arg(self):
# Make sure we still have valid positions when the code compiles to an
# EXTENDED_ARG by performing a loop which needs a JUMP_ABSOLUTE after
# a bunch of opcodes.
snippet = "x = x\n" * 10_000
snippet += ("while x != 0:\n"
" x -= 1\n"
"while x != 0:\n"
" x += 1\n"
)
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=10_000 + 2, end_line=10_000 + 2,
column=2, end_column=8, occurrence=1)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=10_000 + 4, end_line=10_000 + 4,
column=2, end_column=9, occurrence=2)
def test_multiline_expression(self):
snippet = """\
f(
1, 2, 3, 4
)
"""
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION',
line=1, end_line=3, column=0, end_column=1)
def test_very_long_line_end_offset(self):
# Make sure we get None for when the column offset is too large to
# store in a byte.
long_string = "a" * 1000
snippet = f"g('{long_string}')"
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'CALL_FUNCTION',
line=1, end_line=1, column=None, end_column=None)
def test_complex_single_line_expression(self):
snippet = "a - b @ (c * x['key'] + 23)"
compiled_code, _ = self.check_positions_against_ast(snippet)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_SUBSCR',
line=1, end_line=1, column=13, end_column=21)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=9, end_column=21, occurrence=1)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=9, end_column=26, occurrence=2)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=4, end_column=27, occurrence=3)
self.assertOpcodeSourcePositionIs(compiled_code, 'BINARY_OP',
line=1, end_line=1, column=0, end_column=27, occurrence=4)
class TestExpressionStackSize(unittest.TestCase):
# These tests check that the computed stack size for a code object
# stays within reasonable bounds (see issue #21523 for an example
# dysfunction).
N = 100
def check_stack_size(self, code):
# To assert that the alleged stack size is not O(N), we
# check that it is smaller than log(N).
if isinstance(code, str):
code = compile(code, "<foo>", "single")
max_size = math.ceil(math.log(len(code.co_code)))
self.assertLessEqual(code.co_stacksize, max_size)
def test_and(self):
self.check_stack_size("x and " * self.N + "x")
def test_or(self):
self.check_stack_size("x or " * self.N + "x")
def test_and_or(self):
self.check_stack_size("x and x or " * self.N + "x")
def test_chained_comparison(self):
self.check_stack_size("x < " * self.N + "x")
def test_if_else(self):
self.check_stack_size("x if x else " * self.N + "x")
def test_binop(self):
self.check_stack_size("x + " * self.N + "x")
def test_list(self):
self.check_stack_size("[" + "x, " * self.N + "x]")
def test_tuple(self):
self.check_stack_size("(" + "x, " * self.N + "x)")
def test_set(self):
self.check_stack_size("{" + "x, " * self.N + "x}")
def test_dict(self):
self.check_stack_size("{" + "x:x, " * self.N + "x:x}")
def test_func_args(self):
self.check_stack_size("f(" + "x, " * self.N + ")")
def test_func_kwargs(self):
kwargs = (f'a{i}=x' for i in range(self.N))
self.check_stack_size("f(" + ", ".join(kwargs) + ")")
def test_func_args(self):
self.check_stack_size("o.m(" + "x, " * self.N + ")")
def test_meth_kwargs(self):
kwargs = (f'a{i}=x' for i in range(self.N))
self.check_stack_size("o.m(" + ", ".join(kwargs) + ")")
def test_func_and(self):
code = "def f(x):\n"
code += " x and x\n" * self.N
self.check_stack_size(code)
class TestStackSizeStability(unittest.TestCase):
# Check that repeating certain snippets doesn't increase the stack size
# beyond what a single snippet requires.
def check_stack_size(self, snippet, async_=False):
def compile_snippet(i):
ns = {}
script = """def func():\n""" + i * snippet
if async_:
script = "async " + script
code = compile(script, "<script>", "exec")
exec(code, ns, ns)
return ns['func'].__code__
sizes = [compile_snippet(i).co_stacksize for i in range(2, 5)]
if len(set(sizes)) != 1:
import dis, io
out = io.StringIO()
dis.dis(compile_snippet(1), file=out)
self.fail("stack sizes diverge with
"%s\n%s\n%s" % (sizes, snippet, out.getvalue()))
def test_if(self):
snippet = """
if x:
a
"""
self.check_stack_size(snippet)
def test_if_else(self):
snippet = """
if x:
a
elif y:
b
else:
c
"""
self.check_stack_size(snippet)
def test_try_except_bare(self):
snippet = """
try:
a
except:
b
"""
self.check_stack_size(snippet)
def test_try_except_qualified(self):
snippet = """
try:
a
except ImportError:
b
except:
c
else:
d
"""
self.check_stack_size(snippet)
def test_try_except_as(self):
snippet = """
try:
a
except ImportError as e:
b
except:
c
else:
d
"""
self.check_stack_size(snippet)
def test_try_finally(self):
snippet = """
try:
a
finally:
b
"""
self.check_stack_size(snippet)
def test_with(self):
snippet = """
with x as y:
a
"""
self.check_stack_size(snippet)
def test_while_else(self):
snippet = """
while x:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for(self):
snippet = """
for x in y:
a
"""
self.check_stack_size(snippet)
def test_for_else(self):
snippet = """
for x in y:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue(self):
snippet = """
for x in y:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_try_finally_block(self):
snippet = """
for x in y:
try:
if z:
break
elif u:
continue
else:
a
finally:
f
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_finally_block(self):
snippet = """
for x in y:
try:
t
finally:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_except_block(self):
snippet = """
for x in y:
try:
t
except:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_for_break_continue_inside_with_block(self):
snippet = """
for x in y:
with c:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet)
def test_return_inside_try_finally_block(self):
snippet = """
try:
if z:
return
else:
a
finally:
f
"""
self.check_stack_size(snippet)
def test_return_inside_finally_block(self):
snippet = """
try:
t
finally:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_return_inside_except_block(self):
snippet = """
try:
t
except:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_return_inside_with_block(self):
snippet = """
with c:
if z:
return
else:
a
"""
self.check_stack_size(snippet)
def test_async_with(self):
snippet = """
async with x as y:
a
"""
self.check_stack_size(snippet, async_=True)
def test_async_for(self):
snippet = """
async for x in y:
a
"""
self.check_stack_size(snippet, async_=True)
def test_async_for_else(self):
snippet = """
async for x in y:
a
else:
b
"""
self.check_stack_size(snippet, async_=True)
def test_for_break_continue_inside_async_with_block(self):
snippet = """
for x in y:
async with c:
if z:
break
elif u:
continue
else:
a
else:
b
"""
self.check_stack_size(snippet, async_=True)
def test_return_inside_async_with_block(self):
snippet = """
async with c:
if z:
return
else:
a
"""
self.check_stack_size(snippet, async_=True)
if __name__ == "__main__":
unittest.main()
| true | true |
f72c7e77f2ce593a9f65d35942b6d6d6225b5155 | 1,001 | py | Python | audiovisual_stream.py | yagguc/deep_impression | ad45d6640cdb46ff68dd44d8055b53ac57f3d342 | [
"MIT"
] | 36 | 2016-11-10T08:05:08.000Z | 2022-03-25T12:55:55.000Z | audiovisual_stream.py | yagguc/deep_impression | ad45d6640cdb46ff68dd44d8055b53ac57f3d342 | [
"MIT"
] | 5 | 2018-01-04T02:03:21.000Z | 2022-03-13T13:04:56.000Z | audiovisual_stream.py | yagguc/deep_impression | ad45d6640cdb46ff68dd44d8055b53ac57f3d342 | [
"MIT"
] | 24 | 2016-09-26T01:41:31.000Z | 2022-03-07T08:16:58.000Z | import auditory_stream
import chainer
import visual_stream
### MODEL ###
class ResNet18(chainer.Chain):
def __init__(self):
super(ResNet18, self).__init__(
aud = auditory_stream.ResNet18(),
vis = visual_stream.ResNet18(),
fc = chainer.links.Linear(512, 5, initialW = chainer.initializers.HeNormal())
)
def __call__(self, x):
h = [self.aud(True, chainer.Variable(chainer.cuda.to_gpu(x[0]), True)), chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][:256]), True)), 0), 0)]
for i in xrange(256, x[1].shape[0], 256):
h[1] += chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][i : i + 256]), True)), 0), 0)
h[1] /= x[1].shape[0]
return chainer.cuda.to_cpu(((chainer.functions.tanh(self.fc(chainer.functions.concat(h))) + 1) / 2).data[0])
### MODEL ###
| 41.708333 | 212 | 0.621379 | import auditory_stream
import chainer
import visual_stream
):
def __init__(self):
super(ResNet18, self).__init__(
aud = auditory_stream.ResNet18(),
vis = visual_stream.ResNet18(),
fc = chainer.links.Linear(512, 5, initialW = chainer.initializers.HeNormal())
)
def __call__(self, x):
h = [self.aud(True, chainer.Variable(chainer.cuda.to_gpu(x[0]), True)), chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][:256]), True)), 0), 0)]
for i in xrange(256, x[1].shape[0], 256):
h[1] += chainer.functions.expand_dims(chainer.functions.sum(self.vis(True, chainer.Variable(chainer.cuda.to_gpu(x[1][i : i + 256]), True)), 0), 0)
h[1] /= x[1].shape[0]
return chainer.cuda.to_cpu(((chainer.functions.tanh(self.fc(chainer.functions.concat(h))) + 1) / 2).data[0])
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.