return an instance of `val` that is of type `datatype`.
    keep track of exceptions so we can produce meaningful error messages.
496710
def val_factory(val, datatypes):
    
    exceptions = []
    for dt in datatypes:
        try:
            if isinstance(val, dt):
                return val
            return type_handler_object(val, dt)
        except Exception as e:
            exceptions.append(str(e))
    # if we get here, we never found a valid value. raise an error
    raise ValueError('val_factory: Unable to instantiate {val} from types {types}. Exceptions: {excs}'.
                     format(val=val, types=datatypes, excs=exceptions))
573651
function castType(val, type, def) {
    function cast() {
        if (!is_1.isValue(val))
            return to_1.toDefault(null, def);
        // If no type specified try to get automatically.
        type = type || getType(val);
        if (is_1.isArray(type)) {
            return to_1.toArray(val)
                .map(function (v, i) { return castType(v, type[i] || type[i - 1] || type[0]); });
        }
        else if (is_1.isFunction(type)) {
            val = to_1.toArray(val);
            return type.apply(void 0, val);
        }
        else if (is_1.isString(type)) {
            type = type.toLowerCase();
            var func = toMap[type];
            if (func)
                return func(val);
            return to_1.toDefault(null, def);
        }
        else {
            return val;
        }
    }
    return function_1.tryWrap(cast)(def);
}
713719
def _ValidateValue(value, type_check):
  """"""
  if inspect.isclass(type_check):
    return isinstance(value, type_check)
  if isinstance(type_check, tuple):
    return _ValidateTuple(value, type_check)
  elif callable(type_check):
    return type_check(value)
  else:
    raise TypeError("Invalid type check '%s'" % repr(type_check))
173077
def from_val(val_schema):
    """"""
    definition = getattr(val_schema, "definition", val_schema) if isinstance(
        val_schema, BaseSchema) else val_schema
    if isinstance(definition, dict):
        return _dict_to_teleport(definition)

    if isinstance(definition, list):
        # teleport only supports a single type by default
        if len(definition) == 1:
            return {"Array": from_val(definition[0])}

    if definition in VAL_PRIMITIVES:
        return VAL_PRIMITIVES[definition]

    raise SerializationError(
        "Serializing %r not (yet) supported." % definition)
431935
def validate(self, val):
        
        self.validate_type_only(val)
        self.validate_fields_only(val)
        return val
400341
def str_val(val):
    
    str_val = val
    if val is None:
        str_val = "NA"
    elif type(val) == float:
        str_val = '%0.2f' % val
    else:
        str_val = str(val)
    return str_val
240691
def _cast_value(value, _type):
    
    if _type.upper() == 'FLOAT64':
        return float64(value)
    elif _type.upper() == 'FLOAT32':
        return float32(value)
    elif _type.upper() == 'INT32':
        return int32(value)
    elif _type.upper() == 'UINT16':
        return uint16(value)
    elif _type.upper() == 'INT16':
        return int16(value)
    elif _type.upper() == 'BOOLEAN':
        return uint8(value)
    else:
        return float64(value)
200692
def datatype(self, value):
        
        self._datatype = self.validate_datatype(value)
        self._cutout_ready = True
593045
def _cast_to_type(self, value):
        
        try:
            return float(value)
        except (ValueError, TypeError):
            self.fail('invalid', value=value)
68258
def printableVal(val, type_bit=True, justlength=False):
    
    from utool import util_dev
    # Move to util_dev
    # NUMPY ARRAY
    import numpy as np
    if type(val) is np.ndarray:
        info = npArrInfo(val)
        if info.dtypestr.startswith('bool'):
            _valstr = '{ shape:' + info.shapestr + ' bittotal: ' + info.bittotal + '}'
            # + '\n  |_____'
        elif info.dtypestr.startswith('float'):
            _valstr = util_dev.get_stats_str(val)
        else:
            _valstr = '{ shape:' + info.shapestr + ' mM:' + info.minmaxstr + ' }'  # + '\n  |_____'
    # String
    elif isinstance(val, (str, unicode)):  # NOQA
        _valstr = '\'%s\'' % val
    # List
    elif isinstance(val, list):
        if justlength or len(val) > 30:
            _valstr = 'len=' + str(len(val))
        else:
            _valstr = '[ ' + (', \n  '.join([str(v) for v in val])) + ' ]'
    # ??? isinstance(val, AbstractPrintable):
    elif hasattr(val, 'get_printable') and type(val) != type:
        _valstr = val.get_printable(type_bit=type_bit)
    elif isinstance(val, dict):
        _valstr = '{\n'
        for val_key in val.keys():
            val_val = val[val_key]
            _valstr += '  ' + str(val_key) + ' : ' + str(val_val) + '\n'
        _valstr += '}'
    else:
        _valstr = str(val)
    if _valstr.find('\n') > 0:  # Indent if necessary
        _valstr = _valstr.replace('\n', '\n    ')
        _valstr = '\n    ' + _valstr
    _valstr = re.sub('\n *$', '', _valstr)  # Replace empty lines
    return _valstr
1207998
def valid_anytype(val):
    
    for validator in VALIDATOR.values():
        if validator == valid_anytype:  # To hinder recursion
            continue
        try:
            if validator(val):
                return True
        except NotValid:
            pass

    if isinstance(val, type):
        return True

    raise NotValid("AnyType")
916100
def cast_value(val, totype):
    
    t = type(val)
    if issubclass(t, totype):
        return val  # no cast needed
    if issubclass(totype, bytes):
        return bytes(val)
    if issubclass(totype, str):
        return str(val)
    if issubclass(totype, bool):
        if issubclass(t, str):
            _v = val.lower()
            if _v in ("true", "yes", "y"):
                return True
            if _v in ("false", "no", "n"):
                return False
            raise TypeError("Not able to cast value: " + str(val) +
                            " with " + str(t) +
                            " to " + str(totype))

    if (issubclass(totype, (int, float)) and
        issubclass(t, (bytes, str, int, float))):
        if val:
            return totype(float(val))
        else:
            return totype(0)

    raise TypeError("Not able to cast value:" + str(val) +
                    " with " + str(t) +
                    " to " + str(totype))
56822
def value(self, datatype):
        
        value = self.lib.tdSensorValue(
            self.protocol, self.model, self.id, datatype)
        return SensorValue(datatype, value['value'], value['timestamp'])
698426
def _pretty_const_type_val(typecode, val):
    

    if typecode == CONST_Utf8:
        typestr = "Utf8"  # formerly Asciz, which was considered Java bug
        if not isinstance(val, str):  # Py2, val is 'unicode'
            val = repr(val)[2:-1]  # trim off the surrounding u"" (HACK)
        else:
            val = repr(val)[1:-1]  # trim off the surrounding "" (HACK)
    elif typecode == CONST_Integer:
        typestr = "int"
    elif typecode == CONST_Float:
        typestr = "float"
        val = "%ff" % val
    elif typecode == CONST_Long:
        typestr = "long"
        val = "%il" % val
    elif typecode == CONST_Double:
        typestr = "double"
        val = "%fd" % val
    elif typecode == CONST_Class:
        typestr = "class"
        val = "#%i" % val
    elif typecode == CONST_String:
        typestr = "String"
        val = "#%i" % val
    elif typecode == CONST_Fieldref:
        typestr = "Field"
        val = "#%i.#%i" % val
    elif typecode == CONST_Methodref:
        typestr = "Method"
        val = "#%i.#%i" % val
    elif typecode == CONST_InterfaceMethodref:
        typestr = "InterfaceMethod"
        val = "#%i.#%i" % val
    elif typecode == CONST_NameAndType:
        typestr = "NameAndType"
        val = "#%i:#%i" % val
    elif typecode == CONST_ModuleId:
        typestr = "ModuleId"
        val = "#%i@#%i" % val
    elif typecode == CONST_MethodHandle:
        typestr = "MethodHandle"
        val = repr(val)
    elif typecode == CONST_MethodType:
        typestr = "MethodType"
        val = repr(val)
    elif typecode == CONST_InvokeDynamic:
        typestr = "InvokeDynamic"
        val = repr(val)
    else:
        raise Unimplemented("unknown constant type %r" % typecode)

    return typestr, val
1078596
def _protobuf_value_type(value):
  
  if value.HasField("number_value"):
    return api_pb2.DATA_TYPE_FLOAT64
  if value.HasField("string_value"):
    return api_pb2.DATA_TYPE_STRING
  if value.HasField("bool_value"):
    return api_pb2.DATA_TYPE_BOOL
  return None
637621
def _value_is_type_text(val):
    
    if ((u'type' in val.keys()) and
            (val['type'].lower() == u"text")):
        return True
    return False
633592
def _get_avro_type(val):
    
    if isinstance(val, dict):
        assert val.get("class") == "File" or "File" in val.get("class")
        return "File"
    elif isinstance(val, (tuple, list)):
        types = []
        for ctype in [_get_avro_type(v) for v in val]:
            if isinstance(ctype, dict):
                nested_types = [x["items"] for x in types if isinstance(x, dict)]
                if ctype["items"] not in nested_types:
                    if isinstance(ctype["items"], (list, tuple)):
                        for t in ctype["items"]:
                            if t not in types:
                                types.append(t)
                    else:
                        if ctype not in types:
                            types.append(ctype)
            elif isinstance(ctype, (list, tuple)):
                for x in ctype:
                    if x not in types:
                        types.append(x)
            elif ctype not in types:
                types.append(ctype)
        # handle empty types, allow null
        if len(types) == 0:
            types = ["null"]
            # empty lists
            if isinstance(val, (list, tuple)) and len(val) == 0:
                types.append({"type": "array", "items": ["null"]})
        types = _avoid_duplicate_arrays(types)
        # Avoid empty null only arrays which confuse some runners
        if len(types) == 1 and types[0] == "null":
            types.append("string")
        return {"type": "array", "items": (types[0] if len(types) == 1 else types)}
    elif val is None:
        return ["null"]
    # encode booleans as string True/False and unencode on other side
    elif isinstance(val, bool) or isinstance(val, six.string_types) and val.lower() in ["true", "false", "none"]:
        return ["string", "null", "boolean"]
    elif isinstance(val, int):
        return "long"
    elif isinstance(val, float):
        return "double"
    else:
        return "string"