A simple YAML encode that can take a single-element datatype and return
    a string representation.
974696
def yaml_encode(data):
    '''
    
    '''
    yrepr = yaml.representer.SafeRepresenter()
    ynode = yrepr.represent_data(data)
    if not isinstance(ynode, yaml.ScalarNode):
        raise TypeError(
            "yaml_encode() only works with YAML scalar data;"
            " failed for {0}".format(type(data))
        )

    tag = ynode.tag.rsplit(':', 1)[-1]
    ret = ynode.value

    if tag == "str":
        ret = yaml_dquote(ynode.value)

    return ret
143044
def safe_dump(data, stream=None, **kwds):
    """"""
    return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)
512294
def as_document(data, schema=None, label=u"<unicode string>"):
    
    if schema is None:
        schema = Any()

    return schema(YAMLChunk(schema.to_yaml(data), label=label))
1004195
def yaml_parse(yamlstr):
    """"""
    try:
        # PyYAML doesn't support json as well as it should, so if the input
        # is actually just json it is better to parse it with the standard
        # json parser.
        return json.loads(yamlstr)
    except ValueError:
        yaml.SafeLoader.add_multi_constructor("!", intrinsics_multi_constructor)
        return yaml.safe_load(yamlstr)
1173757
def encodefuns():
    

    def desc(ascii):
        """Return textDescription type [ICC 2001] 6.5.17.  The ASCII part is
        filled in with the string `ascii`, the Unicode and ScriptCode parts
        are empty."""

        ascii += '\x00'
        n = len(ascii)

        return struct.pack('>L%ds2LHB67s' % n,
                           n, ascii, 0, 0, 0, 0, '')

    def text(ascii):
        """Return textType [ICC 2001] 6.5.18."""

        return ascii + '\x00'

    def curv(f=None, n=256):
        """Return a curveType, [ICC 2001] 6.5.3.  If no arguments are
        supplied then a TRC for a linear response is generated (no entries).
        If an argument is supplied and it is a number (for *f* to be a
        number it  means that ``float(f)==f``) then a TRC for that
        gamma value is generated.
        Otherwise `f` is assumed to be a function that maps [0.0, 1.0] to
        [0.0, 1.0]; an `n` element table is generated for it.
        """

        if f is None:
            return struct.pack('>L', 0)
        try:
            if float(f) == f:
                return struct.pack('>LH', 1, int(round(f * 2 ** 8)))
        except (TypeError, ValueError):
            pass
        assert n >= 2
        table = []
        M = float(n - 1)
        for i in range(n):
            x = i / M
            table.append(int(round(f(x) * 65535)))
        return struct.pack('>L%dH' % n, n, *table)

    def XYZ(*l):
        return struct.pack('>3l', *map(fs15f16, l))

    return locals()
720018
def StringEncoder(field_number, is_repeated, is_packed):
  """"""

  tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
  local_EncodeVarint = _EncodeVarint
  local_len = len
  assert not is_packed
  if is_repeated:
    def EncodeRepeatedField(write, value):
      for element in value:
        encoded = element.encode('utf-8')
        write(tag)
        local_EncodeVarint(write, local_len(encoded))
        write(encoded)
    return EncodeRepeatedField
  else:
    def EncodeField(write, value):
      encoded = value.encode('utf-8')
      write(tag)
      local_EncodeVarint(write, local_len(encoded))
      return write(encoded)
    return EncodeField
1196735
def raw_encode(data):
    """"""
    content_type = 'application/data'
    payload = data
    if isinstance(payload, unicode):
        content_encoding = 'utf-8'
        payload = payload.encode(content_encoding)
    else:
        content_encoding = 'binary'
    return content_type, content_encoding, payload
1314405
def to_s(data, eol: $/)
            content = ""
            content << "#{no} #{generation} #{TOKENS.first}" << eol if indirect? and numbered?
            content << data
            content << eol << TOKENS.last << eol if indirect? and numbered?

            content.force_encoding('binary')
        end
484407
def convert_none(key, val, attr_type, attr={}, cdata=False):
    """"""
    LOG.info('Inside convert_none(): key="%s"' % (unicode_me(key)))

    key, attr = make_valid_xml_name(key, attr)

    if attr_type:
        attr['type'] = get_xml_type(val)
    attrstring = make_attrstring(attr)
    return '<%s%s></%s>' % (key, attrstring, key)
283516
def encode_value(value):
    # type: (bytes) -> bytes
    
    return struct.pack(">I{attr_len:d}s".format(attr_len=len(value)), len(value), value)
1135807
def _preprocess_yml(path):
    """"""
    with open(path) as f:
        tmp_yaml = f.read()
    return re.sub(r"unicode", "str", tmp_yaml)
1205316
function stringYAML2JSON (doc, compact = false) {
  if (!doc || typeof doc !== 'string') {
    throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
  }

  let obj = yaml.safeLoad(doc)

  if (!obj || typeof obj !== 'object') {
    throw new TypeError('Argument must be in yaml format: ' + doc)
  }

  return JSON.stringify(obj, undefined, compact ? undefined : 2)
}
516417
def to_yaml(cls, representer, node):
        """"""
        return representer.represent_scalar(cls.yaml_tag, node.value)
160345
def to_xml(ele, encoding="UTF-8", pretty_print=False):
    ""
    xml = etree.tostring(ele, encoding=encoding, pretty_print=pretty_print)
    if sys.version < '3':
        return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
    else:
        return xml.decode('UTF-8') if xml.startswith(b'<?xml') \
            else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml.decode('UTF-8'))
87296
def as_value(ele):
        
        dtype = ele.datatype()
        # print '%s = %s' % (ele.name(), dtype)
        if dtype in (1, 2, 3, 4, 5, 6, 7, 9, 12):
            # BOOL, CHAR, BYTE, INT32, INT64, FLOAT32, FLOAT64, BYTEARRAY, DECIMAL)
            return ele.getValue()
        elif dtype == 8:  # String
            val = ele.getValue()
            """
            if val:
                # us centric :)
                val = val.encode('ascii', 'replace')
            """
            return str(val)
        elif dtype == 10:  # Date
            if ele.isNull():
                return pd.NaT
            else:
                v = ele.getValue()
                return datetime(year=v.year, month=v.month, day=v.day) if v else pd.NaT
        elif dtype == 11:  # Time
            if ele.isNull():
                return pd.NaT
            else:
                v = ele.getValue()
                now = pd.datetime.now()
                return datetime(year=now.year, month=now.month, day=now.day, hour=v.hour, minute=v.minute, second=v.second).time() if v else np.nan
        elif dtype == 13:  # Datetime
            if ele.isNull():
                return pd.NaT
            else:
                v = ele.getValue()
                return v
        elif dtype == 14:  # Enumeration
            # raise NotImplementedError('ENUMERATION data type needs implemented')
            return str(ele.getValue())
        elif dtype == 16:  # Choice
            raise NotImplementedError('CHOICE data type needs implemented')
        elif dtype == 15:  # SEQUENCE
            return XmlHelper.get_sequence_value(ele)
        else:
            raise NotImplementedError('Unexpected data type %s. Check documentation' % dtype)
72452
def safe_dump(data):
    
    # TODO(retr0h): Do we need to encode?
    # yaml.dump(data) produces the document as a str object in both python
    # 2 and 3.
    return yaml.dump(
        data, Dumper=SafeDumper, default_flow_style=False, explicit_start=True)
96768
def yaml_processor(entity):
    '''
    
    '''
    if six.PY2:
        body = entity.fp.read()
    else:
        # https://github.com/cherrypy/cherrypy/pull/1572
        contents = BytesIO()
        body = entity.fp.read(fp_out=contents)
        contents.seek(0)
        body = salt.utils.stringutils.to_unicode(contents.read())
    try:
        cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body)
    except ValueError:
        raise cherrypy.HTTPError(400, 'Invalid YAML document')

    cherrypy.serving.request.raw_body = body