Example #1
0
class GraphWrappingStrategy(LayoutOptionWidget):
    """For certain graphs and certain prescribed drawing areas it may be
    desirable to split the laid out graph into chunks that are placed side by
    side. The edges that connect different chunks are ‘wrapped’ around from the
    end of one chunk to the start of the other chunk. The points between the
    chunks are referred to as ‘cuts’.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-layered-wrapping-strategy.html
    """

    identifier = "org.eclipse.elk.layered.wrapping.strategy"
    metadata_provider = "options.LayeredMetaDataProvider"
    applies_to = ["parents"]
    group = "wrapping"

    horizontal = T.Enum(values=["left", "center", "right"],
                        default_value="left")
    value = T.Enum(value=WRAPPING_STRATEGY_OPTIONS.values(),
                   default_value="OFF")

    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(options=list(WRAPPING_STRATEGY_OPTIONS.items()))
        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
Example #2
0
class Shelf(BaseObject):

    skip = ['shorthand', 'config']

    def __init__(self, shorthand, **kwargs):
        kwargs['shorthand'] = shorthand
        super(Shelf, self).__init__(**kwargs)

    def _infer_type(self, data):
        if self.type is None and self.name in data:
            self.type = infer_vegalite_type(data[self.name])

    def _shorthand_changed(self, name, old, new):
        D = parse_shorthand(self.shorthand)
        for key, val in D.items():
            setattr(self, key, val)

    shorthand = T.Unicode('')
    name = T.Unicode('', config=True)
    type = T.Enum(['N', 'O', 'Q', 'T'],
                  default_value=None,
                  allow_none=True,
                  config=True)
    timeUnit = T.Enum(
        ['year', 'month', 'day', 'date', 'hours', 'minutes', 'seconds'],
        default_value=None,
        allow_none=True)
    bin = T.Union([T.Bool(), T.Instance(Bin)], default_value=False)
    sort = T.List(T.Instance(SortItems), default_value=None, allow_none=True)
    aggregate = T.Enum(['avg', 'sum', 'median', 'min', 'max', 'count'],
                       default_value=None,
                       allow_none=True,
                       config=True)
Example #3
0
class Shape(Shelf):
    value = T.Enum([
        'circle', 'square', 'cross', 'diamond', 'triangle-up', 'triangle-down'
    ],
                   default_value='circle')
    aggregate = T.Enum(['count'], default_value=None, allow_none=True)
    legend = T.Instance(Legend, default_value=None, allow_none=True)
    filled = T.Bool(False)
Example #4
0
File: api.py Project: mindis/altair
class Scale(BaseObject):
    """Scale object that represents the Scale property common to: X, Y, Size, Color"""
    # TODO: Supported types for type
    # TODO: Supported types for reverse
    # TODO: Supported types for zero
    # TODO: Supported types for nice

    type = T.Enum(['linear', 'log', 'pow', 'sqrt', 'quantile'],
                  default_value='linear')
    reverse = T.Bool(False)
    zero = T.Bool(True)
    nice = T.Enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'year'],
                  allow_none=True)
    useRawDomain = T.Bool(default_value=None, allow_none=True)
Example #5
0
class TimeScale(QuantitativeScale):

    type = T.Unicode('time')
    nice = T.Union([
        T.Unicode, T.CFloat,
        T.Enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'year'])
    ])
Example #6
0
class EdgeRouting(LayoutOptionWidget):
    """What kind of edge routing style should be applied for the content of a
    parent node. Algorithms may also set this option to single edges in order to
    mark them as splines. The bend point list of edges with this option set to
    SPLINES must be interpreted as control points for a piecewise cubic spline.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-edgeRouting.html
    """

    identifier = "org.eclipse.elk.edgeRouting"
    metadata_provider = "core.options.CoreOptions"
    applies_to = ["parents"]

    value = T.Enum(
        values=list(EDGE_ROUTING_OPTIONS.values()), default_value="UNDEFINED"
    )

    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(
            description="Edge Label Side Selection",
            options=list(EDGE_ROUTING_OPTIONS.items()),
        )

        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
 def __init__(
     self,
     trait_types=[tl.Dict(), tl.List(), tl.Enum(INTERPOLATION_METHODS), tl.Instance(InterpolationManager)],
     *args,
     **kwargs
 ):
     super(InterpolationTrait, self).__init__(trait_types=trait_types, *args, **kwargs)
Example #8
0
class MODIS(S3Mixin, OrderedCompositor):
    """MODIS whole-world compositor.
    For documentation about the data, start here: https://ladsweb.modaps.eosdis.nasa.gov/search/order/1
    For information about the bands, see here: https://modis.gsfc.nasa.gov/about/specifications.php

    Attributes
    ----------
    product : str
        MODIS product ('MCD43A4.006', 'MOD09GA.006', 'MYD09GA.006', 'MOD09GQ.006', or 'MYD09GQ.006')
    data_key : str
        individual object (varies by product)
    """

    product = tl.Enum(values=PRODUCTS, help="MODIS product ID").tag(attr=True)
    data_key = tl.Unicode(help="data to retrieve (varies by product)").tag(
        attr=True)

    tile_width = (1, 2400, 2400)
    start_date = "2013-01-01"
    end_date = datetime.date.today().strftime("%Y-%m-%d")
    anon = tl.Bool(True)

    dims = ["time", "lat", "lon"]

    _repr_keys = ["product", "data_key"]

    @cached_property
    def sources(self):
        return [self._make_tile(h, v) for h, v in self.available_tiles]

    @cached_property(use_cache_ctrl=True)
    def available_tiles(self):
        _logger.info("Looking up available tiles...")
        return [(h, v) for h in _available(self.s3, self.product)
                for v in _available(self.s3, self.product, h)]

    def select_sources(self, coordinates):
        """ 2d select sources filtering """

        sources = super(MODIS, self).select_sources(coordinates)

        # filter tiles spatially
        ct = coordinates.transform(CRS)
        return [
            source for source in sources
            if ct.select(source.tile_coordinates.bounds).size > 0
        ]

    def _make_tile(self, horizontal, vertical):
        return MODISTile(
            product=self.product,
            horizontal=horizontal,
            vertical=vertical,
            data_key=self.data_key,
            cache_ctrl=self.cache_ctrl,
            force_eval=self.force_eval,
            cache_output=self.cache_output,
            cache_dataset=True,
            s3=self.s3,
        )
Example #9
0
class PidginKernel(ipykernel.kernelapp.IPythonKernel):
    input = traitlets.Enum(input_formats, default_value="markdown")

    def __init__(self, *a, **k):
        super().__init__(*a, **k), traitlets.link((self, "input"),
                                                  (self.shell, "input"))

    shell_class = traitlets.Type(PidginShell)
Example #10
0
File: api.py Project: mindis/altair
class Shelf(BaseObject):
    # TODO: Supported enums & supported types for aggregate
    # TODO: Supported types for timeunit
    # TODO: Supported types for bin
    # TODO: supported role?
    # TODO: supported mark types?
    # TODO: assert name and type are required

    skip = ['shorthand', 'config']

    def __init__(self, shorthand, **kwargs):
        kwargs['shorthand'] = shorthand
        super(Shelf, self).__init__(**kwargs)

    def _infer_type(self, data):
        if self.type is None and self.name in data:
            self.type = infer_vegalite_type(data[self.name])

    def _shorthand_changed(self, name, old, new):
        # TODO: if name of shorthand changed, should it reset all properties of obj?
        D = parse_shorthand(self.shorthand)
        for key, val in D.items():
            setattr(self, key, val)

    def to_dict(self):
        if not self.name:
            return None
        return super(Shelf, self).to_dict()

    shorthand = T.Unicode('')
    name = T.Unicode('', config=True)
    type = T.Enum(['N', 'O', 'Q', 'T'],
                  default_value=None,
                  allow_none=True,
                  config=True)
    timeUnit = T.Enum(
        ['year', 'month', 'day', 'date', 'hours', 'minutes', 'seconds'],
        default_value=None,
        allow_none=True)
    bin = T.Union([T.Bool(), T.Instance(Bin)], default_value=False)
    sort = T.List(T.Instance(SortItems), default_value=None, allow_none=True)
    aggregate = T.Enum(['avg', 'sum', 'median', 'min', 'max', 'count'],
                       default_value=None,
                       allow_none=True,
                       config=True)
Example #11
0
File: api.py Project: mindis/altair
class SortItems(BaseObject):
    # TODO: Supported types for type
    # TODO: assert name and aggregate are required

    name = T.Unicode(default_value=None, allow_none=True)
    aggregate = T.Enum(['avg', 'sum', 'min', 'max', 'count'],
                       default_value=None,
                       allow_none=True)
    reverse = T.Bool(False)
Example #12
0
File: api.py Project: mindis/altair
class FacetCoordinate(Shelf):
    # TODO: supported types for aggregate
    # TODO: min and max for padding
    # TODO: min for height

    aggregate = T.Enum(['count'], default_value=None, allow_none=True)
    padding = T.CFloat(0.1)
    axis = T.Instance(Axis, default_value=None, allow_none=True)
    height = T.CInt(150)
Example #13
0
class QueryColorizer(W.VBox):
    """Takes sparql query and runs it through pygments lexer and html formatter"""

    query = T.Unicode()
    formatter_style = T.Enum(values=list(STYLE_MAP.keys()),
                             default_value="colorful")
    style_picker = T.Instance(W.Dropdown)
    html_output = T.Instance(W.HTML)

    _style_defs = T.Unicode(default_value="")
    formatter: HtmlFormatter = None
    _sqrl_lexer: SparqlLexer = None

    @T.default("style_picker")
    def make_default_style_picker(self) -> W.Dropdown:
        widget = W.Dropdown(
            description="Style",
            options=list(STYLE_MAP.keys()),
            layout=W.Layout(min_height="30px"),
        )
        T.link((self, "formatter_style"), (widget, "value"))
        return widget

    @T.default("html_output")
    def make_default_html_output(self) -> W.HTML:
        widget = W.HTML()
        widget.layout = {"width": "50%"}
        return widget

    @T.validate("children")
    def validate_children(self, proposal):
        """
        Validate method for default children.
        This is necessary because @trt.default does not work on children.
        """
        children = proposal.value
        if not children:
            children = (self.style_picker, self.html_output)
        return children

    @T.observe("formatter_style")
    def _update_style(self, change=None) -> HtmlFormatter:
        """update the css style from the formatter"""
        self.formatter = HtmlFormatter(style=self.formatter_style)
        self._sqrl_lexer = SparqlLexer()
        self._style_defs = f"<style>{self.formatter.get_style_defs()}</style>"

    @T.observe(
        "query",
        "_style_defs",
    )
    def update_formatted_query(self, change):
        """Update the html output widget with the highlighted query"""
        if not self.formatter or not self._sqrl_lexer:
            self._update_style()
        self.html_output.value = self._style_defs + highlight(
            self.query, self._sqrl_lexer, self.formatter)
Example #14
0
class MODISTile(S3Mixin, DataSource):
    product = tl.Enum(values=PRODUCTS, help="MODIS product ID").tag(attr=True)
    horizontal = tl.Unicode(
        help="column in the MODIS Sinusoidal Tiling System, e.g. '21'").tag(
            attr=True)
    vertical = tl.Unicode(
        help="row in the MODIS Sinusoidal Tiling System, e.g. '07'").tag(
            attr=True)
    data_key = tl.Unicode(help="data to retrieve (varies by product)").tag(
        attr=True)
    anon = tl.Bool(True)
    _repr_keys = ["product", "data_key"]

    @cached_property
    def sources(self):
        return [self._make_source(date) for date in self.available_dates]

    @cached_property(use_cache_ctrl=True)  # TODO expiration
    def available_dates(self):
        _logger.info("Looking up available dates (product=%s, h=%s, v=%s)..." %
                     (self.product, self.horizontal, self.vertical))
        return _available(self.s3, self.product, self.horizontal,
                          self.vertical)

    @cached_property
    def tile_coordinates(self):
        return get_tile_coordinates(self.horizontal, self.vertical)

    def get_coordinates(self):
        # lookup available dates and use pre-fetched lat and lon bounds
        time = podpac.Coordinates(
            [[_parse_modis_date(date) for date in self.available_dates]],
            dims=["time"],
            crs=CRS)
        return podpac.coordinates.merge_dims([time, self.tile_coordinates])

    def get_data(self, coordinates, coordinates_index):
        data = self.create_output_array(coordinates)
        for i, source in enumerate(self.sources[coordinates_index[0]]):
            data[i, :, :] = source.eval(coordinates.drop("time"))
        return data

    def _make_source(self, date):
        return MODISSource(
            product=self.product,
            horizontal=self.horizontal,
            vertical=self.vertical,
            date=date,
            data_key=self.data_key,
            check_exists=False,
            cache_ctrl=self.cache_ctrl,
            force_eval=self.force_eval,
            cache_output=self.cache_output,
            cache_dataset=True,
            s3=self.s3,
        )
class ANNOYModel(state.HasState):
    features = traitlets.List(traitlets.Unicode(), help='List of features to use.')
    n_trees = traitlets.Int(default_value=10, help="Number of trees to build.")
    search_k = traitlets.Int(default_value=-1, help='Jovan?')
    n_neighbours = traitlets.Int(default_value=10, help='Now many neighbours')
    metric = traitlets.Enum(values=['euclidean', 'manhattan', 'angular', 'hamming', 'dot'], default_value='euclidean', help='Metric to use for distance calculations')
    predcition_name = prediction_name = traitlets.Unicode(default_value='annoy_prediction', help='Output column name for the neighbours when transforming a DataFrame')

    def __call__(self, *args):
        data2d = np.vstack([arg.astype(np.float64) for arg in args]).T.copy()
        result = []
        for i in range(len(data2d)):
            result.append(self.index_builder.get_nns_by_vector(n=self.n_neighbours, vector=data2d[i], search_k=self.search_k))
        return np.array(result)

    def fit(self, dataframe):
        self.index_builder = annoy.AnnoyIndex(len(self.features), metric=self.metric)
        for i in range(len(dataframe)):
            self.index_builder.add_item(i, dataframe[self.features][i])
        self.index_builder.build(self.n_trees)

    def transform(self, dataframe):
        copy = dataframe.copy()
        lazy_function = copy.add_function('annoy_get_nns_by_vector_function', self, unique=True)
        expression = lazy_function(*self.features)
        copy.add_virtual_column(self.prediction_name, expression, unique=False)
        return copy

    def predict(self, dataframe, n_neighbours=None, search_k=None):
        search_k = search_k or self.search_k
        n_neighbours = n_neighbours or self.n_neighbours
        result = np.zeros((len(dataframe), n_neighbours), dtype=np.int)
        for i in range(len(dataframe)):
            result[i] = self.index_builder.get_nns_by_vector(n=n_neighbours, search_k=search_k, vector=dataframe[self.features][i])
        return result

    def state_get(self):
        filename = tempfile.mktemp()
        self.index_builder.save(filename)
        with open(filename, 'rb') as f:
            data = f.read()
        return dict(tree_state=base64.encodebytes(data).decode('ascii'),
                    substate=super(ANNOYModel, self).state_get(),
                    n_dimensions=len(self.features))

    def state_set(self, state, trusted=True):
        super(ANNOYModel, self).state_set(state['substate'])
        data = base64.decodebytes(state['tree_state'].encode('ascii'))
        n_dimensions = state['n_dimensions']
        filename = tempfile.mktemp()
        with open(filename, 'wb') as f:
            f.write(data)
        self.index_builder = annoy.AnnoyIndex(n_dimensions)
        self.index_builder.load(filename)
        return self.index_builder
Example #16
0
class FrequencyEncoder(Transformer):
    '''Encode categorical columns by the frequency of their respective samples.

    Example:

    >>> import vaex
    >>> df = vaex.from_arrays(color=['red', 'green', 'green', 'blue', 'red', 'green'])
    >>> df
     #  color
     0  red
     1  green
     2  green
     3  blue
     4  red
    >>> encoder = vaex.ml.FrequencyEncoder(features=['color'])
    >>> encoder.fit_transform(df)
     #  color      frequency_encoded_color
     0  red                       0.333333
     1  green                     0.5
     2  green                     0.5
     3  blue                      0.166667
     4  red                       0.333333
     5  green                     0.5
    '''
    prefix = traitlets.Unicode(default_value='frequency_encoded_', help=help_prefix).tag(ui='Text')
    unseen = traitlets.Enum(values=['zero', 'nan'], default_value='nan', help='Strategy to deal with unseen values.')
    mappings_ = traitlets.Dict()

    def fit(self, df):
        '''Fit FrequencyEncoder to the DataFrame.

        :param df: A vaex DataFrame.
        '''
        # number of samples
        nsamples = len(df)

        # Encoding
        for feature in self.features:
            self.mappings_[feature] = dict(df[feature].value_counts() / nsamples)

    def transform(self, df):
        '''Transform a DataFrame with a fitted FrequencyEncoder.

        :param df: A vaex DataFrame.
        :return: A shallow copy of the DataFrame that includes the encodings.
        :rtype: DataFrame
        '''
        copy = df.copy()
        default_value = {'zero': 0., 'nan': np.nan}[self.unseen]
        for feature in self.features:
            name = self.prefix + feature
            expression = copy[feature].map(self.mappings_[feature], nan_value=np.nan, missing_value=np.nan, default_value=default_value, allow_missing=True)

            copy[name] = expression
        return copy
class PassGen(traitlets.HasTraits):
    """
    Class to represent state of password generator and handle generation
    of password.
    """
    password_length = traitlets.Integer()
    include_numbers = traitlets.Bool()
    special_character_groups = traitlets.Enum(SPECIAL_GROUPS,
                                              default_value=SPECIAL_GROUPS[0])
    password = traitlets.Unicode("password")

    def __init__(self):
        super(PassGen, self).__init__(description='Password model')
        pass

    # The observe decorator is used to indicate that the function being
    # decorated should be called if any of the traits listed as arguments
    # change. The decorated function must have an argument named change;
    # in this example the change variable isn't used because we want to update
    # the generated password no matter what the change was.
    @traitlets.observe('password_length',
                       'include_numbers',
                       'special_character_groups')
    def generate_password(self, change):
        """
        Generate a password of the desired length including the user's chosen
        set of special characters and, if desired, including some numerals.
        """

        # Generate an initial password composed only of letters.
        new_pass = []
        for _ in range(self.password_length):
            new_pass.append(random.choice(string.ascii_letters))

        # Generate a list of indices for choosing which characters in the
        # initial password to replace, then shuffle it. We'll pop
        # elements off the list as we need them.
        order_for_replacements = list(range(self.password_length))
        random.shuffle(order_for_replacements)

        # Replace some of the letters with special characters
        n_special = random.randint(1, 3)
        for _ in range(n_special):
            loc = order_for_replacements.pop(0)
            new_pass[loc] = random.choice(self.special_character_groups)

        if self.include_numbers:
            # Number of digits to include.
            n_digits = random.randint(1, 3)
            for _ in range(n_digits):
                loc = order_for_replacements.pop(0)
                new_pass[loc] = random.choice(string.digits)

        self.password = ''.join(new_pass)
Example #18
0
class Data(BaseObject):

    formatType = T.Enum(['json', 'csv'], default_value='json')
    url = T.Unicode(default_value=None, allow_none=True)
    values = T.List(default_value=None, allow_none=True)

    def to_dict(self):
        result = {
            'formatType': self.formatType,
            'values': self.data.to_dict('records')
        }
        return result
Example #19
0
class Bus(t.HasTraits):
    '''Bus Model'''

    name = t.CUnicode(default_value='Bus1', help='Name of Generator (str)')
    bus_type = t.Enum(
        values=['SWING', 'PQ', 'PV'],
        default_value='PQ',
        help='Bus type',
    )
    real_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Active power demand (MW)')
    imag_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Reactive power demand (MVAR)')
    shunt_conductance = t.CFloat(default_value=0,
                                 help='Shunt Conductance (TODO: units)')
    shunt_susceptance = t.CFloat(default_value=0,
                                 help='Shunt Susceptance (TODO: units)')
    area = t.CUnicode(default_value='0', help='Area the bus is located in')
    voltage_magnitude = t.CFloat(default_value=1.0,
                                 help='Voltage magnitude (p.u.)')
    voltage_angle = t.CFloat(default_value=0.0, help='Voltage angle (deg)')
    base_voltage = t.CFloat(default_value=230, help='Base voltage (kV)')
    zone = t.CUnicode(default_value='0', help='Zone the bus is located in')
    maximum_voltage = t.CFloat(default_value=1.05, help='Maximum voltage')
    minimum_voltage = t.CFloat(default_value=0.95, help='Minimum voltage')

    def __init__(self, **kwargs):

        v = kwargs.pop('real_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['real_power_demand'] = v

        v = kwargs.pop('imag_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['imag_power_demand'] = v

        super(Bus, self).__init__(**kwargs)

    @t.validate('real_power_demand', 'imag_power_demand')
    def _coerce_value_to_list(self, proposal):
        v = proposal['value']
        if (v is not None and (isinstance(v, int) or isinstance(v, float))):
            v = [
                v,
            ]
        elif v is None:
            v = [
                0.0,
            ]

        return v
Example #20
0
File: api.py Project: mindis/altair
class ColorScale(Scale):
    """Scale object that adds additional properties to the Scale property for Color"""

    range = T.Union([T.Unicode(), T.List(T.Unicode)],
                    default_value=None,
                    allow_none=True)
    c10palette = T.Enum([
        'category10', 'category10k', 'Pastel1', 'Pastel2', 'Set1', 'Set2',
        'Set3'
    ],
                        default_value='category10')
    c20palette = T.Enum(['category20', 'category20b', 'category20c'],
                        default_value='category20')
    ordinalPalette = T.Enum([
        'YlGn', 'YlGnBu', 'GnBu', 'BuGn', 'PuBuGn', 'PuBu', 'BuPu', 'RdPu',
        'PuRd', 'OrRd', 'YlOrRd', 'YlOrBr', 'Purples', 'Blues', 'Greens',
        'Oranges', 'Reds', 'Greys', 'PuOr', 'BrBG', 'PRGn', 'PiYG', 'RdBu',
        'RdGy', 'RdYlBu', 'Spectral', 'RdYlGn', 'Accent', 'Dark2', 'Paired',
        'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3'
    ],
                            default_value='BuGn')
Example #21
0
File: api.py Project: mindis/altair
class Axis(BaseObject):

    grid = T.Bool(True)
    layer = T.Unicode(u'back')
    orient = T.Enum(['top', 'right', 'left', 'bottom'],
                    default_value=None,
                    allow_none=True)
    ticks = T.Int(5)
    title = T.Unicode(default_value=None, allow_none=True)
    titleMaxLength = T.Int(default_value=None, allow_none=True)
    titleOffset = T.Int(default_value=None, allow_none=True)
    format = T.Unicode(default_value=None, allow_none=True)
    maxLabelLength = T.Int(25, min=0)
Example #22
0
class Dataset(HasTraits):
    type = 'Dataset'

    phase_cycles = ['frame']

    path = traitlets.Unicode(help='location of the dataset on disk',
                             config=True,
                             allow_none=False)

    mode = traitlets.Enum(['r', 'r+', 'a'], default_value='r', config=True)

    allow_parallel = traitlets.Bool(default_value=False, config=True)

    def __init__(self, *args, **kwargs):
        '''open hdf5 file representing spectroscopy data
        
        Parameters
        ----------
        path : str or pathlib.Path
            the location of the dataset
        mode : str
            file mode used to open the dataset ('r', 'r+', 'w', 'a', etc.)
        '''
        config = kwargs.pop('config', None)

        if config:
            config = Config(config)

        super(Dataset, self).__init__(config=config, **kwargs)

        new_mode = kwargs.pop('mode', None)
        if new_mode:
            self.mode = new_mode

        path = pathlib.Path(self.path)
        log.debug('created dataset `{path!s}` ({type:s})'.format(
            type=self.type, path=path))

    def from_raw_data(self, iterable):
        pass

    def load(self):
        pass

    def save(self):
        pass

    @contextmanager
    def raw_hdf5(self):
        with h5py.File(self.path, self.mode) as sf:
            yield sf
Example #23
0
class PassGen(traitlets.HasTraits):
    """
    Class to represent state of the password generator and handle generation
    of password.
    """
    length = traitlets.Integer()
    password = traitlets.Unicode("password")

    # ↓↓↓↓↓↓↓↓ New traitlets ↓↓↓↓↓↓↓↓
    include_numbers = traitlets.Bool()
    special_character_groups = traitlets.Enum(SPECIAL_GROUPS,
                                              default_value=SPECIAL_GROUPS[0])

    def __init__(self):
        super(PassGen, self).__init__()
        pass

    @traitlets.observe('length', 'include_numbers', 'special_character_groups')
    def generate_password(self, change):
        """
        Generate a password of the desired length including the user's chosen
        set of special characters and, if desired, including some numerals.
        """

        # Generate an initial password composed only of letters.
        new_pass = []
        for _ in range(self.length):
            new_pass.append(random.choice(string.ascii_letters))

        # Generate a list of indices for choosing which characters in the
        # initial password to replace, then shuffle it. We'll pop
        # elements off the list as we need them.
        order_for_replacements = list(range(self.length))
        random.shuffle(order_for_replacements)

        # Replace some of the letters with special characters
        n_special = random.randint(1, 3)
        for _ in range(n_special):
            loc = order_for_replacements.pop(0)
            new_pass[loc] = random.choice(self.special_character_groups)

        if self.include_numbers:
            # Number of digits to include.
            n_digits = random.randint(1, 3)
            for _ in range(n_digits):
                loc = order_for_replacements.pop(0)
                new_pass[loc] = random.choice(string.digits)

        self.password = ''.join(new_pass)
Example #24
0
class TransformTimeUnits(ModifyCoordinates):
    time_units = tl.Enum([
        "day",
        "dayofweek",
        "dayofyear",
        "daysinmonth",
        "microsecond",
        "minute",
        "month",
        "nanosecond",
        "quarter",
        "season",
        "second",
        "time",
        "week",
        "weekday",
        "weekday_name",
        "weekofyear",
        "year",
    ]).tag(attr=True)

    # Remove tags from attributes
    lat = tl.List()
    lon = tl.List()
    time = tl.List()
    alt = tl.List()
    coordinates_source = None

    def get_modified_coordinates1d(self, coords, dim):
        """
        Get the desired 1d coordinates for the given dimension, depending on the selection attr for the given
        dimension::

        Parameters
        ----------
        coords : Coordinates
            The requested input coordinates
        dim : str
            Dimension for doing the selection

        Returns
        -------
        coords1d : ArrayCoordinates1d
            The selected coordinates for the given dimension.
        """
        if dim != "time":
            return coords[dim]

        return coords.transform_time(self.time_units)["time"]
Example #25
0
def interpolation_trait(default_value=INTERPOLATION_DEFAULT):
    """Create a new interpolation trait
    
    Returns
    -------
    tl.Union
        Union trait for an interpolation definition
    """
    return tl.Union([
        tl.Dict(),
        tl.Enum(INTERPOLATION_SHORTCUTS),
        tl.Instance(Interpolation)
    ],
                    allow_none=True,
                    default_value=default_value)
Example #26
0
class ConsiderModelOrder(LayoutOptionWidget):
    """Preserves the order of nodes and edges in the model file if this does not
    lead to edge crossings or conflicts between the ordering or edges and nodes.
    """

    identifier = "org.eclipse.elk.layered.considerModelOrder"
    metadata_provider = "options.LayeredMetaDataProvider"
    applies_to = ["parents", "nodes"]

    value = T.Enum(values=list(MODEL_ORDER_OPTIONS.values()),
                   default_value="NONE")

    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(options=list(MODEL_ORDER_OPTIONS.items()))
        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
Example #27
0
class Direction(LayoutOptionWidget):
    """Overall direction of edges: horizontal (right / left) or vertical (down / up).

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-direction.html
    """

    identifier = "org.eclipse.elk.direction"
    metadata_provider = "core.options.CoreOptions"
    applies_to = ["parents"]

    value = T.Enum(values=list(DIRECTION_OPTIONS.values()), default_value="UNDEFINED")

    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(options=list(DIRECTION_OPTIONS.items()))
        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
Example #28
0
class AirMOSS(podpac.OrderedCompositor):
    """Summary

    Attributes
    ----------
    product : TYPE
        Description
    site_url_re : TYPE
        Description
    """

    product = tl.Enum(['L4RZSM'], default_value='L4RZSM')
    site_url_re = tl.Any()

    @tl.default('site_url_re')
    def get_site_url_re(self):
        """Summary

        Returns
        -------
        TYPE
            Description
        """
        return re.compile(self.product + '_.*_' + '[0-9]{8}.*\.nc4')

    def get_available_sites(self):
        """Summary

        Returns
        -------
        TYPE
            Description
        """
        soup = BeautifulSoup(requests.get(self.base_dir_url).text, 'lxml')
        a = soup.find_all('a')
        regex = self.site_url_re

        sites = OrderedDict()
        for aa in a:
            text = aa.get_text()
            m = regex.match(text)
            if m:
                site = text.split('_')[1]
                sites[site] = 1 + sites.get(site, 0)

        return sites
Example #29
0
class Shell(traitlets.HasTraits):
    """
what

    """

    input = traitlets.Enum(input_formats, "markdown")
    enabled = traitlets.Bool(False, help="""""", allow_none=True)

    @traitlets.observe("enabled")
    def _observe_enabled(self, change=None):
        if self.is_ipython_extension():
            self.load_ipython_extension(
                self.parent
            ) if change["new"] else self.unload_ipython_extension(self.parent)

    #             self.parent.display_formatter.mimebundle_formatter.enabled = self.parent.display_formatter.ipython_display_formatter.enabled = True
    #             for type in self.parent.display_formatter.active_types: self.parent.display_formatter.formatters[type].enabled=True

    parent = traitlets.Instance(IPython.InteractiveShell, allow_none=True)

    @traitlets.default("parent")
    def _default_parent(self):
        return IPython.get_ipython()

    def _wrap_enabled(self, callable):
        def wraps(*a):
            self.enabled and callable(*a)

        return functools.wraps(callable)(wraps)

    def is_ipython_extension(self):
        return hasattr(self, "load_ipython_extension") and self.enabled

    def triggers(self):
        return list(object for object in IPython.core.events.available_events
                    if hasattr(self, object))

    def __init__(self, **kwargs):
        traitlets.HasTraits.__init__(self, **kwargs), self.parent
        self.is_ipython_extension() and self.load_ipython_extension(
            self.parent)
        for trigger in self.triggers():
            self.parent.events.register(
                trigger, self._wrap_enabled(getattr(self, trigger)))
Example #30
0
class Status(Configurable):
    mode = traitlets.Enum(RobotModeType)

    def __init__(self, connection):
        super(Status, self).__init__()
        self.connection = connection

    @traitlets.observe(u'mode')
    def __observe_mode(self, change):
        if self.mode == RobotModeType.CHASSIS_LEAD:
            self.connection.command(u'robot mode chassis_lead;')
        elif self.mode == RobotModeType.GIMBAL_LEAD:
            self.connection.command(u'robot mode gimbal_lead;')
        elif self.mode == RobotModeType.FREE:
            self.connection.command(u'robot mode free;')

    def get_battery_power(self):
        ret = self.connection.command(u'robot battery ?')
        return ret[1]