Ejemplo n.º 1
0
    def _validate_type(self, proposal):
        value = proposal["value"]

        if value == "custom":
            if not len(self._partials):
                raise TraitError("Cannot set 'custom' type, use the ``partials`` attribute instead")
            return value
        else:
            base_type, partial_count = parse_osc_type(value, types=self._valid_types)
            return base_type + partial_count
Ejemplo n.º 2
0
 def validate(self, obj, value):
     if value is None and not self.allow_none:
         self.error(obj, value)
     try:
         value = pd.DataFrame(value)
         for validator in self.validators:
             value = validator(self, value)
         return value
     except (ValueError, TypeError) as e:
         raise TraitError(e)
Ejemplo n.º 3
0
    def validate(self, obj, value):

        if isinstance(value, str):
            value = os.path.abspath(value)
            if self.exists is not None:
                if os.path.exists(value) != self.exists:
                    raise TraitError('Path "{}" {} exist'.format(
                        value, 'does not' if self.exists else 'must'))
            if os.path.exists(value):
                if os.path.isdir(value) and not self.directory_ok:
                    raise TraitError(
                        'Path "{}" must not be a directory'.format(value))
                if os.path.isfile(value) and not self.file_ok:
                    raise TraitError(
                        'Path "{}" must not be a file'.format(value))

            return value

        return self.error(obj, value)
Ejemplo n.º 4
0
 def validate(self, obj, value):
     if value is None and not self.allow_none:
         self.error(obj, value)
     try:
         value = np.asarray(value, dtype=self.dtype)
         for validator in self.validators:
             value = validator(self, value)
         return value
     except (ValueError, TypeError) as e:
         raise TraitError(e)
Ejemplo n.º 5
0
 def _valid_value_temp_files_server(self, proposal):
     try:
         if proposal["value"] != self.temp_files_server:
             if self.temp_files_server == "disabled":
                 raise ValueError(
                     "feature is 'disabled', due to missing 'flask' module")
     except (AttributeError, ValueError) as e:
         message = f"The 'temp_files_server' trait of a {Constants.MAGIC_CLASS_NAME} instance {str(e)}"
         raise TraitError(message)
     return proposal["value"]
Ejemplo n.º 6
0
 def _valid_value_auto_dataframe(self, proposal: Dict[str, Any]):
     try:
         if proposal["value"] is True and not Dependencies.is_installed(
                 "pandas"):
             raise ValueError(
                 "cannot be set to True, 'pandas' package is not installed")
     except (AttributeError, ValueError) as e:
         message = f"The 'auto_dataframe' trait of a {Constants.MAGIC_CLASS_NAME} instance {str(e)}"
         raise TraitError(message)
     return proposal["value"]
Ejemplo n.º 7
0
 def validate(self, obj, value):
     if value is None and not self.allow_none:
         self.error(obj, value)
     if value is None or value is Undefined:
         return super(XarrayType, self).validate(obj, value)
     try:
         value = self.klass(value)
     except (ValueError, TypeError) as e:
         raise TraitError(e)
     return super(XarrayType, self).validate(obj, value)
Ejemplo n.º 8
0
 def _validate_assignment_id(self, proposal):
     if '+' in proposal['value']:
         raise TraitError(
             'Assignment names should not contain the following characters: +'
         )
     if proposal['value'].strip() != proposal['value']:
         self.log.warning(
             "assignment_id '%s' has trailing whitespace, stripping it away",
             proposal['value'])
     return proposal['value'].strip()
Ejemplo n.º 9
0
    def _validate_colors(self, proposal):
        if type(proposal['value']) is dict or type(self.positions) is dict:
            return proposal['value']

        required = self.positions.size // 3  # (x, y, z) triplet per 1 color
        actual = proposal['value'].size
        if actual != 0 and required != actual:
            raise TraitError('colors has wrong size: %s (%s required)' %
                             (actual, required))
        return proposal['value']
Ejemplo n.º 10
0
    def validate(self, obj, value):
        # cast to proper unicode
        value = super(FilenameExtension, self).validate(obj, value)

        # check that it starts with a dot
        if value and not value.startswith('.'):
            msg = "FileExtension trait '{}' does not begin with a dot: {!r}"
            raise TraitError(msg.format(self.name, value))

        return value
Ejemplo n.º 11
0
    def _notebook_dir_validate(self, value, trait):
        # Strip any trailing slashes
        value = value.rstrip(os.sep)

        if not os.path.isabs(value):
            # If we receive a non-absolute path, make it absolute.
            value = os.path.abspath(value)
        if not os.path.isdir(value):
            raise TraitError("No such notebook dir: %r" % value)
        return value
Ejemplo n.º 12
0
    def validate(self, obj, value):
        if isinstance(value, bytes):
            value = os.fsdecode(value)

        if value is None:
            if self.allow_none:
                return None
            else:
                self.error(obj, value)

        if not isinstance(value, (str, pathlib.Path)):
            return self.error(obj, value)

        if isinstance(value, str):
            if value == "":
                return self.error(obj, value)

            try:
                url = urlparse(value)
            except ValueError:
                return self.error(obj, value)

            if url.scheme not in ("", "file"):
                return self.error(obj, value)

            value = pathlib.Path(url.netloc, url.path)

        value = value.absolute()
        exists = value.exists()
        if self.exists is not None:
            if exists != self.exists:
                raise TraitError(
                    'Path "{}" {} exist'.format(
                        value, "does not" if self.exists else "must not"
                    )
                )
        if exists:
            if not self.directory_ok and value.is_dir():
                raise TraitError(f'Path "{value}" must not be a directory')
            if not self.file_ok and value.is_file():
                raise TraitError(f'Path "{value}" must not be a file')

        return value
Ejemplo n.º 13
0
    def validate(self, obj, value):
        # Support a single value for all (check and convert into a default value)
        if not isinstance(value, (list, List, UserList, TelescopePatternList)):
            value = [("type", "*", self._trait.validate(obj, value))]

        # Check each value of list
        normalized_value = TelescopePatternList()

        for pattern in value:

            # now check for the standard 3-tuple of (command, argument, value)
            if len(pattern) != 3:
                raise TraitError(
                    "pattern should be a tuple of (command, argument, value)"
                )

            command, arg, val = pattern
            val = self._trait.validate(obj, val)

            if not isinstance(command, str):
                raise TraitError("command must be a string")

            if command not in ["type", "id"]:
                raise TraitError("command must be one of: 'type', 'id'")

            if command == "type":
                if not isinstance(arg, str):
                    raise TraitError("'type' argument should be a string")

            if command == "id":
                try:
                    arg = int(arg)
                except ValueError:
                    raise TraitError(f"Argument of 'id' should be an int (got '{arg}')")

            val = self._trait.validate(obj, val)
            normalized_value.append((command, arg, val))
            normalized_value._lookup = TelescopeParameterLookup(normalized_value)

            if isinstance(value, TelescopePatternList) and value._subarray is not None:
                normalized_value.attach_subarray(value._subarray)

        return normalized_value
Ejemplo n.º 14
0
 def _states_change(self, change):
     if change['new'] < 1:
         raise TraitError('State value cannot smaller than 1')
     else:
         if len(self.selected_colors) < change["new"]:
             additional_colors = ["#a6cee3", "#b2df8a", "#fdbf6f", "#6a3d9a", "#b15928", "#e31a1c", "#1f78b4", "#33a02c", "#ff7f00", "#cab2d6", "#ffff99"]
             self.selected_colors = self.selected_colors + additional_colors * (1 + (change["new"] - len(self.selected_colors)) // len(additional_colors))
             self.selected_colors = self.selected_colors[:change["new"]]
         elif len(self.selected_colors) > change["new"]:
             self.selected_colors = self.selected_colors[:change["new"]]
Ejemplo n.º 15
0
 def _db_changed(self, change):
     """validate the db, since it can be an Instance of two different types"""
     new = change['new']
     connection_types = (DummyDB, )
     if sqlite3 is not None:
         connection_types = (DummyDB, sqlite3.Connection)
     if not isinstance(new, connection_types):
         msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
                 (self.__class__.__name__, new)
         raise TraitError(msg)
Ejemplo n.º 16
0
    def validate(self, obj, value):
        if isinstance(value, (int, float)):
            return int(value)

        try:
            num = float(value[:-1])
        except ValueError:
            raise TraitError(
                "{val} is not a valid memory specification. Must be an int or "
                "a string with suffix K, M, G, T".format(val=value)
            )
        suffix = value[-1]

        if suffix not in self.UNIT_SUFFIXES:
            raise TraitError(
                "{val} is not a valid memory specification. Must be an int or "
                "a string with suffix K, M, G, T".format(val=value)
            )
        return int(float(num) * self.UNIT_SUFFIXES[suffix])
Ejemplo n.º 17
0
 def validate(self, obj, value):
     if isinstance(value, str):
         try:
             value = self._resolve_string(value)
         except ImportError as exc:
             raise TraitError(
                 "Failed to import %r for trait '%s.%s':\n\n%s"
                 % (value, type(obj).__name__, self.name, exc)
             )
     return super().validate(obj, value)
    def _valid_function_parameters(self, function_parameters):
        """
        Validate that the function parameters do not contain newlines

        These might allow string injection, and would be difficult to indent
        properly.
        """
        if '\n' in function_parameters['value']:
            raise TraitError("The function parameters cannot contain newlines")
        return function_parameters['value']
Ejemplo n.º 19
0
 def _validate_backend(self, proposed):
     if proposed['value'] not in (
             'custom',
             'dummy',
             'git',
             'sqla',
     ):
         raise TraitError('backend not recognized: {}'.format(
             proposed['value']))
     return proposed['value']
Ejemplo n.º 20
0
 def validate(self, obj, value):
     value = super(DataUnion, self).validate(obj, value)
     if isinstance(value, NDArrayWidget) and self.dtype is not None:
         if value.array.dtype != self.dtype:
             raise TraitError(
                 'dtypes must match exactly when passing a NDArrayWidget to '
                 'a dtype constrained DataUnion')
     if self.shape_constraint:
         self.shape_constraint(self, get_union_array(value))
     return value
Ejemplo n.º 21
0
 def _valid_spec(self, proposal):
     spec = proposal['value']
     spec_parts = len(spec.split(SPEC_DIVIDER))
     if spec_parts == 3:
         return spec
     elif spec_parts == 2:
         return spec + '/master'
     else:
         raise TraitError(
             'spec must contain two or three components but only got '
             '{} (original spec: {})'.format(spec_parts, spec))
Ejemplo n.º 22
0
    def validate(self, obj, value):
        if not isinstance(value, ureg.Quantity):
            self.error(obj, value)

        if (self.dimensionality is not None
                and self.dimensionality != value.dimensionality):
            raise TraitError(
                "The dimensionality of the '%s' trait of %s instance should "
                "be %s, but a value with dimensionality %s was "
                "specified" % (self.name, class_of(obj), self.dimensionality,
                               value.dimensionality))

        if ((self.max is not None and (value.to(self.max.units) > self.max)) or
            (self.min is not None and (value.to(self.min.units) < self.min))):
            raise TraitError(
                "The value of the '%s' trait of %s instance should "
                "be between %s and %s, but a value of %s was "
                "specified" %
                (self.name, class_of(obj), self.min, self.max, value))
        return value
Ejemplo n.º 23
0
    def validate(self, owner, stl):
        stl = super(BinaryStlData, self).validate(owner, stl)

        if len(stl) < self.HEADER + self.COUNT_SIZE:
            raise TraitError(
                'Given bytestring is too short ({}) for Binary STL data.'.
                format(len(stl)))

        (num_facets, ) = struct.unpack(
            '<I', stl[self.HEADER:self.HEADER + self.COUNT_SIZE])

        expected_size = self.HEADER + self.COUNT_SIZE + num_facets * self.FACET_SIZE

        if len(stl) != expected_size:
            raise TraitError(
                'Given bytestring has wrong length ({}) for Binary STL data. '
                'For {} facets {} bytes were expected.'.format(
                    len(stl), num_facets, expected_size))

        return stl
Ejemplo n.º 24
0
    def validate(self, obj, value):
        value = super(WebGLDataUnion, self).validate(obj, value)
        array = value.array if isinstance(value, NDArrayWidget) else value

        if array is not Undefined and str(array.dtype) == 'float64':
            if isinstance(value, NDArrayWidget):
                raise TraitError('Cannot use a float64 data widget as a BufferAttribute source.')
            else:
                # 64-bit not supported, coerce to 32-bit
                value = value.astype('float32')
        return value
Ejemplo n.º 25
0
    def validate(self, obj, value):
        """
        Validate that the passed in value is a valid memory specification

        It could either be a pure int, when it is taken as a byte value.
        If it has one of the suffixes, it is converted into the appropriate
        pure byte value.
        """
        if isinstance(value, (int, float)):
            return int(value)

        try:
            num = float(value[:-1])
        except ValueError:
            raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
        suffix = value[-1]
        if suffix not in self.UNIT_SUFFIXES:
            raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
        else:
            return int(float(num) * self.UNIT_SUFFIXES[suffix])
Ejemplo n.º 26
0
 def _scales_validate(self, scales, scales_trait):
     """validates the dictionary of scales based on the mark's scaled
     attributes metadata. First checks for missing scale and then for
     'rtype' compatibility."""
     # Validate scales' 'rtype' versus data attribute 'rtype' decoration
     # At this stage it is already validated that all values in self.scales
     # are instances of Scale.
     for name in self.trait_names(scaled=True):
         trait = self.traits()[name]
         if name not in scales:
             # Check for missing scale
             if not trait.allow_none:
                 raise TraitError("Missing scale for data attribute %s." %
                                  name)
         else:
             # Check scale range type compatibility
             if scales[name].rtype != trait.get_metadata('rtype'):
                 raise TraitError("Range type mismatch for scale %s." %
                                  name)
     return scales
Ejemplo n.º 27
0
def validate_dtype(value, dtype):
    try:
        r = np.asarray(value, dtype=dtype)
        if isinstance(value, np.ndarray) and r is not value:
            warnings.warn(
                'Given trait value dtype "%s" does not match required type "%s". '
                'A coerced copy has been created.' %
                (np.dtype(value.dtype).name, np.dtype(dtype).name))
        return r
    except (ValueError, TypeError) as e:
        raise TraitError(e)
Ejemplo n.º 28
0
    def _notebook_dir_changed(self, name, old, new):
        """Do a bit of validation of the notebook dir."""
        if not os.path.isabs(new):
            # If we receive a non-absolute path, make it absolute.
            self.notebook_dir = os.path.abspath(new)
            return
        if not os.path.isdir(new):
            raise TraitError("No such notebook dir: %r" % new)

        # setting App.notebook_dir implies setting notebook and kernel dirs as well
        self.config.FileContentsManager.root_dir = new
        self.config.MappingKernelManager.root_dir = new
def resolve_subclass(baseclass, subclass):
    if isinstance(subclass, basestring):
        subclasses = _all_subclasses(baseclass)
        subclass_matches = [
            sc for sc in subclasses
            if ("%s.%s" % (sc.__module__, sc.__name__)) == subclass
            or sc.__name__ == subclass
        ]
        if len(subclass_matches) == 1:
            return subclass_matches[0]
        elif len(subclass_matches) > 1:
            raise TraitError("Ambiguous subclass name: %s subclasses: %s" %
                             (subclass, subclass_matches))
        else:
            raise TraitError("No matching subclass name: %s" % subclass)
    else:
        if not issubclass(subclass, baseclass):
            raise TraitError("Specific class not subclass: %s base: %s" %
                             (subclass, baseclass))

        return subclass
Ejemplo n.º 30
0
 def _validate_post_save_hook(self, proposal):
     value = proposal["value"]
     if isinstance(value, str):
         value = import_item(value)
     if not callable(value):
         raise TraitError("post_save_hook must be callable")
     if callable(self.post_save_hook):
         warnings.warn(
             f"Overriding existing post_save_hook ({self.post_save_hook.__name__}) with a new one ({value.__name__}).",
             stacklevel=2,
         )
     return value