Encode a set for the DynamoDB format
177624
def encode_set(dynamizer, value):
    
    inner_value = next(iter(value))
    inner_type = dynamizer.raw_encode(inner_value)[0]
    return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
495241
def dynamize_value(self, val):
        
        def _str(val):
            """
            DynamoDB stores booleans as numbers. True is 1, False is 0.
            This function converts Python booleans into DynamoDB friendly
            representation.
            """
            if isinstance(val, bool):
                return str(int(val))
            return str(val)

        dynamodb_type = self.get_dynamodb_type(val)
        if dynamodb_type == 'N':
            val = {dynamodb_type : _str(val)}
        elif dynamodb_type == 'S':
            val = {dynamodb_type : val}
        elif dynamodb_type == 'NS':
            val = {dynamodb_type : [ str(n) for n in val]}
        elif dynamodb_type == 'SS':
            val = {dynamodb_type : [ n for n in val]}
        return val
650560
public Map<String, String> encode(Map<String, Object> tableProperties)
    {
        return ImmutableMap.of();
    }
278187
def encode(self, value):
        '''
        
        '''
        packed = pack(self.fmt, value)
        return Bits(bytes=packed)
45605
def _encode_list(name, value, check_keys, opts):
    """"""
    lname = gen_list_name()
    data = b"".join([_name_value_to_bson(next(lname), item,
                                         check_keys, opts)
                     for item in value])
    return b"\x04" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
828419
def encode_params(self, data=None, **kwargs):
        
        charset = kwargs.get("charset", self.charset)
        collection_format = kwargs.get("collection_format", self.collection_format)
        output_str = kwargs.get("output_str", self.output_str)

        if data is None:
            return "", self.get_content_type(charset)
        elif isinstance(data, (str, bytes)):
            return data, self.get_content_type(charset)
        elif hasattr(data, 'read'):
            return data, self.get_content_type(charset)
        elif collection_format == 'multi' and hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    result.append(b"=".join([self._encode(k, charset), self._encode(v, charset, output_str)]))
            return b'\n'.join(result), self.get_content_type(charset)
        elif collection_format == 'plain' and hasattr(data, '__iter__'):
            results = []
            for k, vs in to_key_val_dict(data).items():
                results.append(b"=".join([self._encode(k, charset), self._encode(vs, charset, output_str)]))

            return b'\n'.join(results), self.get_content_type(charset)
        elif hasattr(data, '__iter__'):
            results = []
            for k, vs in to_key_val_dict(data).items():
                if isinstance(vs, list):
                    v = self.COLLECTION_SEPARATORS[collection_format].join(e for e in vs)
                    key = k + '[]'
                else:
                    v = vs
                    key = k
                results.append(b"=".join([self._encode(key, charset), self._encode(v, charset, output_str)]))

            return b"\n".join(results), self.get_content_type(charset)
        else:
            return str(data).encode(charset) if charset else str(data), self.get_content_type(charset)
884136
function encode(key, value, stringify) {
  var space = ' ', val = [], i, type = this.type;

  function coerce(type, val) {
    var out
      , enumerable = Array.isArray(type);
    if(enumerable) {
      if(!~type.indexOf(val)) {
        throw new TypeDefError(
          util.format('enum error on key \'%s\', got \'%s\' expected one of %s',
            key, val, type.join(', ')));
      }

      return '' + val;
    }
    switch(type) {
      case ByteSize:
        if(typeof val !== 'number') {
          throw new TypeDefError(
            util.format(
              'byte size number expected for \'%s\', got %s', key, val));
        }
        out = ByteSize.humanize(val);
        break;
      case Boolean:
        if(typeof val !== 'boolean') {
          throw new TypeDefError(
            util.format('boolean expected for \'%s\', got %s', key, val));
        }
        out = val === true ? YES : NO;
        break;
      case String:
        // strings must be quoted to allow the empty string
        out = '"' + val + '"';
        break;
      case Number:
        if(typeof val !== 'number') {
          throw new TypeDefError(
            util.format('number expected for \'%s\', got %s', key, val));
        }
        // just coerce numbers to strings
        out = '' + val;
        break;
    }
    return out;
  }

  // simple types
  if(!Array.isArray(this.type)) {
    return (!stringify ? key + space : '') + coerce(this.type, value);
  }

  if(stringify && this.repeats) {
    value.forEach(function(item) {
      item.forEach(function(entry, i) {
        val.push(coerce(type[i], entry));
      })
    });
    return val.join(space);
  }

  for(i = 0;i < this.type.length;i++) {
    if(this.arity > 1) {
      // expecting value to be an array
      val.push(coerce(this.type[i], value[i]));
    }else{
      val.push(coerce(this.type[i], value));
    }
  }

  return key + space + val.join(space);
}
232255
def encode_metadata(self):
        
        encoded_list = []
        for key, value in iteritems(self.metadata):
            key_str = str(key)  # dict keys may be of any object type.

            # confirm that the key does not contain unwanted characters.
            if re.search(r'^$|[\s,]+', key_str):
                msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.'
                raise ValueError(msg.format(key_str))

            value_bytes = b(value)  # python 3 only encodes bytes
            encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii')))
        return encoded_list
681097
function formatAttrs(attributes, opts, keyOnlyAttribs = []) {
  if (!attributes) return;

  var output = '',
    value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    if (!value && booleanAttributes[key] || isExpr(key) || isKeyOnlyAttr(key, keyOnlyAttribs)) {
      output += key;
    } else {
      output += key + `=${isExpr(value) ? '' : '"'}` + (opts.decodeEntities ? entities.encodeXML(value) : value) + (isExpr(value) ? '' : '"');
    }
  }

  return output;
}
1201157
function normalizeAttributes(attrs, strip) {

            // map for converting SQL types to Sequelize DataTypes.
            var map = {
                    TINYINT: 'BOOLEAN',
                    DATETIME: 'DATE',
                    TIMESTAMP: 'DATE',
                    'VARCHAR BINARY': 'STRING.BINARY',
                    'TINYBLOB': 'BLOB',
                    VARCHAR: 'STRING[LEN]',
                    'INTEGER UNSIGNED ZEORFILL': 'INTEGER[LEN].UNSIGNED.ZEROFILL',
                    'INTEGER UNSIGNED': 'INTEGER[LEN].UNSIGNED',
                    'INTEGER ZEROFILL': 'INTEGER[LEN].ZEROFILL',
                    INTEGER: 'INTEGER[LEN]',
                    'FLOAT UNSIGNED ZEORFILL': 'FLOAT[LEN].UNSIGNED.ZEROFILL',
                    'FLOAT ZEROFILL': 'FLOAT[LEN].ZEROFILL',
                    'FLOAT UNSIGNED': 'FLOAT[LEN].UNSIGNED',
                    FLOAT: 'FLOAT[LEN]',
                    'BIGINT UNSIGNED ZEORFILL': 'BIGINT[LEN].UNSIGNED.ZEROFILL',
                    'BIGINT ZEROFILL': 'BIGINT[LEN].ZEROFILL',
                    'BIGINT UNSIGNED': 'BIGINT[LEN].UNSIGNED',
                    BIGINT: 'BIGINT[LEN]',
                    DECIMAL: 'DECIMAL[LEN]',
                    ENUM: 'ENUM'
                },
                mapKeys = Object.keys(map);

            strip = strip || [];
            strip.push('Model');

            // convert and format to Sequelize Model Type.
            function getType(type, len, name) {

                if(!type) return undefined;
                type = type.split('(')[0];

                if(map[type]){
                    var tmp = map[type];
                    if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
                    else len = '';
                    type = tmp.replace('[LEN]', len);
                }

                return type;
            }

            // iterate properties.
            for(var prop in attrs) {

                if(attrs.hasOwnProperty(prop)){

                    var attr = attrs[prop],
                        type = attr.type,
                        prec = type._precision && type._scale ? type._precision + ',' + type._scale : false,
                        len = prec ? prec : type._length || false;

                    // strip properties.
                    strip.forEach(function (s) {
                        if(attr[s]) delete attr[s];
                    });

                    if(attr.validate && attr.validate._checkEnum)
                        type = 'ENUM';

                    if(!type._binary && type._length)
                        type = 'VARCHAR';

                    if(type._binary)
                        type = 'VARCHAR BINARY';

                    if(_.contains(['INTEGER', 'FLOAT', 'BIGINT'], type._typeName)){
                        var tmp = '';
                        tmp = type._unsigned ? tmp += ' UNSIGNED' : tmp;
                        tmp = type._zerofill ? tmp += ' ZEROFILL' : tmp;
                        type = type._typeName + tmp;

                    }

                    if(_.isObject(type))
                        type = type._typeName;

                    attrs[prop].type = getType(type, len, attr.fieldName);

                }

            }

            return attrs;
        }
396681
def _EncodeDateField(field, value):
    """"""
    if field.repeated:
        result = [d.isoformat() for d in value]
    else:
        result = value.isoformat()
    return encoding.CodecResult(value=result, complete=True)
1310841
def _encode_message_set(cls, messages):
        
        message_set = []
        for message in messages:
            encoded_message = KafkaProtocol._encode_message(message)
            message_set.append(struct.pack('>qi%ds' % len(encoded_message), 0,
                                           len(encoded_message),
                                           encoded_message))
        return b''.join(message_set)
1111661
def encode(self):
        

        blob = bytearray()

        for record in self.records:
            blob += record.encode()

        header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
        blob = header + blob

        sha = hashlib.sha256()
        sha.update(blob)
        hash_value = sha.digest()[:16]

        return bytearray(hash_value) + blob
1370782
@SuppressWarnings("unchecked")
    private String encodeAttribute(String s, Charset charset) throws ErrorDataEncoderException {
        if (s == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(s, charset.name());
            if (encoderMode == EncoderMode.RFC3986) {
                for (Map.Entry<Pattern, String> entry : percentEncodings) {
                    String replacement = entry.getValue();
                    encoded = entry.getKey().matcher(encoded).replaceAll(replacement);
                }
            }
            return encoded;
        } catch (UnsupportedEncodingException e) {
            throw new ErrorDataEncoderException(charset.name(), e);
        }
    }
833335
function toValueFromAttributeValue(attributeValue) {
  if (!attributeValue || typeof attributeValue !== 'object') {
    return attributeValue;
  }
  const values = Object.getOwnPropertyNames(attributeValue).map(type => {
    return toValueFromAttributeTypeAndValue(type, attributeValue[type])
  });
  if (values.length !== 1) {
    throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`);
  }
  return values[0];
}
1000362
def encode (self):
    """"""
    byte = self.default

    for bit, name, value0, value1, default in SeqCmdAttrs.Table:
      if name in self.attrs:
        value = self.attrs[name]
        byte  = setBit(byte, bit, value == value1)

    return struct.pack('B', byte)
582133
def getset(self, key, value, *, encoding=_NOTSET):
        """"""
        return self.execute(b'GETSET', key, value, encoding=encoding)