Convert a string to a :class:`FeatureBranchSpec` object.

    :param value: A string or :class:`FeatureBranchSpec` object.
    :returns: A :class:`FeatureBranchSpec` object.
188636
def coerce_feature_branch(value):
    
    # Repository objects pass through untouched.
    if isinstance(value, FeatureBranchSpec):
        return value
    # We expect a string with a name or URL.
    if not isinstance(value, string_types):
        msg = "Expected string or FeatureBranchSpec object as argument, got %s instead!"
        raise ValueError(msg % type(value))
    return FeatureBranchSpec(expression=value)
3708
def encode(cls, value):
        
        try:
            coerced = list(value)
            if coerced == value:
                return json.dumps(coerced).encode(cls._encoding)
        except TypeError:
            pass

        raise InvalidValue('not a list')
228712
def from_string_pairs(cls, string_value_pairs, **kwargs):
        
        return cls(re_value_pairs=[(re.compile(s), v)
                                   for s, v in string_value_pairs],
                   **kwargs)
150362
def to_internal_value(self, value):
        """"""
        if value == "":
            return None

        if isinstance(value, string_types):
            slug = slugify(value)
            feature_type, created = FeatureType.objects.get_or_create(
                slug=slug,
                defaults={"name": value}
            )
        else:
            if "id" in value:
                feature_type = FeatureType.objects.get(id=value["id"])
            elif "slug" in value:
                feature_type = FeatureType.objects.get(slug=value["slug"])
            else:
                raise ValidationError("Invalid feature type data")
        return feature_type
1230101
def validate_value_string (f, value_string):
    
    assert isinstance(f, Feature)
    assert isinstance(value_string, basestring)
    if f.free or value_string in f.values:
        return

    values = [value_string]

    if f.subfeatures:
        if not value_string in f.values and \
               not value_string in f.subfeatures:
            values = value_string.split('-')

    # An empty value is allowed for optional features
    if not values[0] in f.values and \
           (values[0] or not f.optional):
        raise InvalidValue ("'%s' is not a known value of feature '%s'\nlegal values: '%s'" % (values [0], f.name, f.values))

    for v in values [1:]:
        # this will validate any subfeature values in value-string
        implied_subfeature(f, v, values[0])
672675
def import_from_str(value):
    
    try:
        parts = value.split('.')
        module_path, class_name = '.'.join(parts[:-1]), parts[-1]
        module = importlib.import_module(module_path)
        return getattr(module, class_name)
    except ImportError as e:
        msg = 'Could not import %s for settings. %s: %s.' % (value, e.__class__.__name__, e)
        raise ImportError(msg)
308445
def _parse_feature_value(self, value):
        
        if isinstance(value, _FileLoader):
            return value
        if not hasattr(self, 'ndim'):  # Because of serialization/deserialization during multiprocessing
            return value

        if self.ndim:
            if not isinstance(value, np.ndarray):
                raise ValueError('{} feature has to be a numpy array'.format(self.feature_type))
            if value.ndim != self.ndim:
                raise ValueError('Numpy array of {} feature has to have {} '
                                 'dimension{}'.format(self.feature_type, self.ndim, 's' if self.ndim > 1 else ''))

            if self.feature_type.is_discrete():
                if not issubclass(value.dtype.type, (np.integer, np.bool, np.bool_, np.bool8)):
                    msg = '{} is a discrete feature type therefore dtype of data should be a subtype of ' \
                          'numpy.integer or numpy.bool, found type {}. In the future an error will be raised because' \
                          'of this'.format(self.feature_type, value.dtype.type)
                    warnings.warn(msg, DeprecationWarning, stacklevel=3)

                    # raise ValueError('{} is a discrete feature type therefore dtype of data has to be a subtype of '
                    #                  'numpy.integer or numpy.bool, found type {}'.format(self.feature_type,
                    #                                                                      value.dtype.type))
            # This checking is disabled for now
            # else:
            #     if not issubclass(value.dtype.type, (np.floating, np.float)):
            #         raise ValueError('{} is a floating feature type therefore dtype of data has to be a subtype of '
            #                          'numpy.floating or numpy.float, found type {}'.format(self.feature_type,
            #                                                                                value.dtype.type))
            return value

        if self.is_vector:
            if isinstance(value, gpd.GeoSeries):
                value = gpd.GeoDataFrame(dict(geometry=value), crs=value.crs)

            if isinstance(value, gpd.GeoDataFrame):
                if self.feature_type is FeatureType.VECTOR:
                    if FeatureType.TIMESTAMP.value.upper() not in value:
                        raise ValueError("{} feature has to contain a column 'TIMESTAMP' with "
                                         "timestamps".format(self.feature_type))

                return value

            raise ValueError('{} feature works with data of type {}, parsing data type {} is not supported'
                             'given'.format(self.feature_type, gpd.GeoDataFrame.__name__, type(value)))

        return value
463916
def from_value(cls, value: str) -> T:
        
        return [x for x in cls.__members__.values() if x.value[0] == value][0]
891785
def to_feature(value):
  """"""
  if isinstance(value, FeatureConnector):
    return value
  elif utils.is_dtype(value):  # tf.int32, tf.string,...
    return Tensor(shape=(), dtype=tf.as_dtype(value))
  elif isinstance(value, dict):
    return FeaturesDict(value)
  else:
    raise ValueError('Feature not supported: {}'.format(value))
192179
def to_representation(self, value):
        
        raise NotImplementedError(
            '{cls}.to_representation() must be implemented for field '
            '{field_name}. If you do not need to support write operations '
            'you probably want to subclass `ReadOnlyField` instead.'.format(
                cls=self.__class__.__name__,
                field_name=self.field_name,
            )
        )
642237
def to_python(self, value: Optional[str]) -> Optional[Any]:
        
        # https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
        # log.debug("to_python: {}, {}", value, type(value))
        if isinstance(value, datetime.datetime):
            return value
        if value is None:
            return value
        if value == '':
            return None
        return iso_string_to_python_datetime(value)
582366
def _to_python(self, value):
        
        if isinstance(value, (int, float, long, complex)):
            return value

        if isinstance(value, (list, tuple)):
            value = value[0]

        if value == 'true':
            return True
        elif value == 'false':
            return False

        is_string = False

        if IS_PY3:
            if isinstance(value, bytes):
                value = force_unicode(value)

            if isinstance(value, str):
                is_string = True
        else:
            if isinstance(value, str):
                value = force_unicode(value)

            if isinstance(value, basestring):  # NOQA: F821
                is_string = True

        if is_string:
            possible_datetime = DATETIME_REGEX.search(value)

            if possible_datetime:
                date_values = possible_datetime.groupdict()

                for dk, dv in date_values.items():
                    date_values[dk] = int(dv)

                return datetime.datetime(date_values['year'],
                                         date_values['month'],
                                         date_values['day'],
                                         date_values['hour'],
                                         date_values['minute'],
                                         date_values['second'])

        try:
            # This is slightly gross but it's hard to tell otherwise what the
            # string's original type might have been.
            return ast.literal_eval(value)
        except (ValueError, SyntaxError):
            # If it fails, continue on.
            pass

        return value
431777
def _serialize_value(self, value):
        

        if isinstance(value, datetime.datetime):
            return value.strftime(self.datetime_format)
        elif isinstance(value, datetime.date):
            return value.strftime(self.date_format)
        elif isinstance(value, datetime.time):
            return value.strftime(self.time_format)
        return text_type(value)
179755
def to_text(value):
    

    text = _by_value.get(value)
    if text is None:
        text = str(value)
    return text
1007394
def token(self, value):
        
        if value is None:
            self._token = value
            return
        if not isinstance(value, str):
            value = str(value)
        if len(value) > 256:
            raise AttributeError
        self._token = value
378561
def import_from_string(value):
    """"""
    value = value.replace('-', '_')
    try:
        module_path, class_name = value.rsplit('.', 1)
        module = import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as ex:
        raise ImportError("Could not import '{}'. {}: {}.".format(
            value, ex.__class__.__name__, ex))
86818
def to_simple(self, value, **options):  # nolint
        "  "

        # (string, unicode)
        if isinstance(value, basestring):
            return smart_unicode(value)

        # (int, long, float, real, complex, decimal)
        if isinstance(value, Number):
            return float(str(value)) if isinstance(value, Decimal) else value

        # (datetime, data, time)
        if isinstance(value, (datetime, date, time)):
            return self.to_simple_datetime(value)

        # (dict, ordereddict, mutable mapping)
        if isinstance(value, collections.MutableMapping):
            return dict(
                (k, self.to_simple(v, **options)) for k, v in value.items())

        # (tuple, list, set, iterators)
        if isinstance(value, collections.Iterable):
            return [self.to_simple(o, **options) for o in value]

        # (None, True, False)
        if value is None or value is True or value is False:
            return value

        if hasattr(value, 'to_simple') and not inspect.isclass(value):
            return self.to_simple(value.to_simple(self), **options)

        if isinstance(value, Model):
            return self.to_simple_model(value, **options)

        return str(value)