If you try to encode each element individually with python, this would take days!
499999
def encode(df, encoding='utf8', verbosity=1):
    """"""
    if verbosity > 0:
        # pbar_i = 0
        pbar = progressbar.ProgressBar(maxval=df.shape[1])
        pbar.start()
    # encode strings as UTF-8 so they'll work in python2 and python3
    for colnum, col in enumerate(df.columns):
        if isinstance(df[col], pd.Series):
            if verbosity:
                pbar.update(colnum)
            if df[col].dtype in (np.dtype('object'), np.dtype('U'), np.dtype('S')) and any(isinstance(obj, basestring) for obj in df[col]):
                strmask = np.array([isinstance(obj, basestring) for obj in df[col]])
                series = df[col].copy()
                try:
                    series[strmask] = np.char.encode(series[strmask].values.astype('U'))
                except TypeError:
                    print("Unable to convert {} elements starting at position {} in column {}".format(
                          sum(strmask), [i for i, b in enumerate(strmask) if b][:1], col))
                    raise
                except (UnicodeDecodeError, UnicodeEncodeError):
                    try:
                        series[strmask] = np.array([eval(s, {}, {}) for s in series[strmask]])
                    # FIXME: do something different for unicode and decode errors
                    except (SyntaxError, UnicodeDecodeError, UnicodeEncodeError):
                        newseries = []
                        for s in series[strmask]:
                            try:
                                newseries += [s.encode('utf8')]
                            except:
                                print(u'Had trouble encoding {} so used repr to turn it into {}'.format(s, repr(transcode_unicode(s))))
                                # strip all unicode chars are convert to ASCII str
                                newseries += [transcode_unicode(s)]
                        # for dtype('U'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 207: ordinal not in r
                        series[strmask] = np.array(newseries).astype('O')
                df[col] = series
                # df[col] = np.array([x.encode('utf8') if isinstance(x, unicode) else x for x in df[col]])

            # WARNING: this takes DAYS for only 100k tweets!
            # series = df[col].copy()
            # for i, value in series.iteritems():   

            #     if isinstance(value, basestring):
            #         series[i] = str(value.encode(encoding))
            # df[col] = series
    if verbosity:
        pbar.finish()
    return df
1131456
function encode(data) {
  $.checkArgument(data instanceof Array, 'Must be Array');
  var base32 = '';
  for (var i=0; i<data.length; i++) {
    var value = data[i];
    $.checkArgument(0 <= value && value < 32, 'Non-base32, value ' + value);
    base32 += CHARSET[value];
  }
  return base32;
}
1179184
def encode_list(cls, value):
        
        encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-"))
        return encoded.decode("utf-8") if six.PY3 else encoded
217948
def GetEncoding(self):
        ''''''
        if self.encoding:
            vals = string.split(self.encoding, ',')
            if len(vals) > 2:
                try:
                    return charset_table[int(vals[2])]
                except KeyError:
                    pass
        return None
1045305
def encode(strs):
    
    res = ''
    for string in strs.split():
        res += str(len(string)) + ":" + string
    return res
956367
def run_length_encode(in_array):
    """"""
    if(len(in_array)==0):
        return []
    curr_ans = in_array[0]
    out_array = [curr_ans]
    counter = 1
    for in_int in in_array[1:]:
        if in_int == curr_ans:
            counter+=1
        else:
            out_array.append(counter)
            out_array.append(in_int)
            curr_ans = in_int
            counter = 1
    # Add the final counter
    out_array.append(counter)
    return out_array
2966
def encode(self):
        

        match_id = self.match_id
        if match_id is None:
            match_id = (1 << 11) - 1

        return (self.match_type << 12) | DataStreamSelector.SpecifierEncodings[self.match_spec] | match_id
339098
function encodeBlocks($, prefix, blockType, args, block) {
      if (!prefix) prefix = "";
      if (blockType == "function") {
        // decode the function block (THIS IS THE IMPORTANT BIT)
        // We are retrieving all sub-blocks and will re-parse them in light
        // of newly shrunk variables
        block = args + decodeBlocks(block, SCOPED);
        prefix = prefix.replace(BRACKETS, "");
        
        // create the list of variable and argument names
        args = args.slice(1, -1);
        
        if (args != "_no_shrink_") {
          var vars = match(block, VARS).join(";").replace(VAR_g, ";var");
          while (BRACKETS.test(vars)) {
            vars = vars.replace(BRACKETS_g, "");
          }
          vars = vars.replace(VAR_TIDY, "").replace(VAR_EQUAL, "");
        }
        block = decodeBlocks(block, ENCODED_BLOCK);
        
        // process each identifier
        if (args != "_no_shrink_") {
          var count = 0, shortId;
          var ids = match([args, vars], IDENTIFIER);
          var processed = {};
          for (var i = 0; i < ids.length; i++) {
            id = ids[i];
            if (!processed["#" + id]) {
              processed["#" + id] = true;
              id = rescape(id);
              // encode variable names
              while (new RegExp(Shrinker.PREFIX + count + "\\b").test(block)) count++;
              var reg = new RegExp("([^\\w$.])" + id + "([^\\w$:])");
              while (reg.test(block)) {
                block = block.replace(global(reg), "$1" + Shrinker.PREFIX + count + "$2");
              }
              var reg = new RegExp("([^{,\\w$.])" + id + ":", "g");
              block = block.replace(reg, "$1" + Shrinker.PREFIX + count + ":");
              count++;
            }
          }
          total = Math.max(total, count);
        }
        var replacement = prefix + "~" + blocks.length + "~";
        blocks.push(block);
      } else {
        var replacement = "~#" + blocks.length + "~";
        blocks.push(prefix + block);
      }
      return replacement;
    }
407612
def encode(cls, value):
        
        val_encoding = 'utf-8'

        def encode_str(v):
            try:
                v_enc = encode(v, val_encoding)

            except UnicodeDecodeError:
                if PY3:
                    raise
                else:
                    # Suppose bytestring
                    v_enc = v

            prefix = encode('%s:' % len(v_enc), val_encoding)
            return prefix + v_enc

        def encode_(val):
            if isinstance(val, str_type):
                result = encode_str(val)

            elif isinstance(val, int_types):
                result = encode(('i%se' % val), val_encoding)

            elif isinstance(val, (list, set, tuple)):
                result = encode('l', val_encoding)
                for item in val:
                    result += encode_(item)
                result += encode('e', val_encoding)

            elif isinstance(val, dict):
                result = encode('d', val_encoding)

                # Dictionaries are expected to be sorted by key.
                for k, v in OrderedDict(sorted(val.items(), key=itemgetter(0))).items():
                    result += (encode_str(k) + encode_(v))

                result += encode('e', val_encoding)

            elif isinstance(val, byte_types):
                result = encode('%s:' % len(val), val_encoding)
                result += val

            else:
                raise BencodeEncodingError('Unable to encode `%s` %s' % (type(val), val))

            return result

        return encode_(value)
768779
@Override
    protected void encode() {
        int l = content.length();
        String localstr;
        int zeroes, count = 0, check_digit;
        Code3Of9 c = new Code3Of9();

        if (l > 7) {
            throw new OkapiException("Input data too long");
        }

        if (!content.matches("[0-9]+")) {
            throw new OkapiException("Invalid characters in input");
        }

        localstr = "-";
        zeroes = 7 - l + 1;
        for (int i = 1; i < zeroes; i++)
            localstr += '0';

        localstr += content;

        for (int i = 1; i < 8; i++) {
            count += i * Character.getNumericValue(localstr.charAt(i));
        }

        check_digit = count % 11;
        if (check_digit == 11) {
            check_digit = 0;
        }
        if (check_digit == 10) {
            throw new OkapiException("Not a valid PZN identifier");
        }

        encodeInfo += "Check Digit: " + check_digit + "\n";

        localstr += (char)(check_digit + '0');

        c.setContent(localstr);

        readable = "PZN" + localstr;
        pattern = new String[1];
        pattern[0] = c.pattern[0];
        row_count = 1;
        row_height = new int[1];
        row_height[0] = -1;
    }
1233271
def _byteify(input):
    
    if isinstance(input, dict):
        return {_byteify(key): _byteify(value) for key, value in input.items()}
    elif isinstance(input, list):
        return [_byteify(element) for element in input]
    elif _PYTHON_3 and isinstance(input, str):
        return str(input.encode('ascii', 'replace').decode('ascii'))
    elif not _PYTHON_3 and isinstance(input, unicode):
        return str(input.encode('ascii', 'replace').decode('ascii'))
    else:
        return input
1911
def bencode(canonical):
    '''
        
    '''
    in_dict = dict(canonical)

    def encode_str(in_str):
        out_str = str(len(in_str)) + ':' + in_str
        return out_str

    def encode_int(in_int):
        out_str = str('i' + str(in_int) + 'e')
        return out_str

    def encode_list(in_list):
        out_str = 'l'
        for item in in_list:
            out_str += encode_item(item)
        else:
            out_str += 'e'
        return out_str

    def encode_dict(in_dict):
        out_str = 'd'
        keys = sorted(in_dict.keys())
        for key in keys:
            val = in_dict[key]
            out_str = out_str + encode_item(key) + encode_item(val)
        else:
            out_str += 'e'
        return out_str

    def encode_item(x):
        if isinstance(x, str):
            return encode_str(x)
        elif isinstance(x, int):
            return encode_int(x)
        elif isinstance(x, list):
            return encode_list(x)
        elif isinstance(x, dict):
            return encode_dict(x)

    return encode_item(in_dict)
87539
def encode(cls, value):
        
        try:
            coerced = [str(v) for v in value]
            if coerced == value:
                return ",".join(coerced).encode(cls._encoding) if len(
                    value) > 0 else None
        except TypeError:
            pass

        raise InvalidValue('not a list of strings')
10344
def encode_contents(self):
        

        header = struct.pack("<LL", self.offset, len(self.raw_data))
        return bytearray(header) + self.raw_data
709267
def encode(string):
		

		result=".".join([ str(ord(s)) for s in string ])
		return  "%s." % (len(string)) + result
896857
function encodeInputs(inputs, add_address_to_previous_output_index) {
    //Initialize buffer and offset
    let offset = 0;
    var buffer = Buffer.allocUnsafe(100000);
    //Write number of inputs
    offset += bufferutils.writeVarInt(buffer, inputs.length, offset);

    inputs.forEach((input, index) => {
        //Write reversed hash
        offset += Buffer.from(input.previous_output.hash, 'hex').reverse().copy(buffer, offset);
        //Index
        offset = buffer.writeUInt32LE(input.previous_output.index, offset);
        if (add_address_to_previous_output_index !== undefined) {
            if (index == add_address_to_previous_output_index) {
                let lockregex = /^\[\ ([a-f0-9]+)\ \]\ numequalverify dup\ hash160\ \[ [a-f0-9]+\ \]\ equalverify\ checksig$/gi;
                if (input.previous_output.script && input.previous_output.script.match(lockregex)) {
                    let locktime = lockregex.exec(input.previous_output.script.match(lockregex)[0])[1];
                    offset = writeScriptLockedPayToPubKeyHash(input.previous_output.address, locktime, buffer, offset);
                } else {
                    if (Script.hasAttenuationModel(input.previous_output.script)) {
                        let params = Script.getAttenuationParams(input.previous_output.script);
                        offset = writeAttenuationScript(params.model, (params.hash !== '0000000000000000000000000000000000000000000000000000000000000000') ? params.hash : undefined, (params.index >= 0) ? params.index : undefined, input.previous_output.address, buffer, offset);
                    } else {
                        if (Script.isP2SH(input.previous_output.script)) {
                            let script_buffer = Buffer.from(input.redeem, 'hex');
                            offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset);
                            offset += script_buffer.copy(buffer, offset);
                        } else {
                            if (input.previous_output.script) {
                                let script_buffer = Script.fromASM(input.previous_output.script).toBuffer()
                                offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset);
                                offset += script_buffer.copy(buffer, offset);
                            } else {
                                offset = writeScriptPayToPubKeyHash(input.previous_output.address, buffer, offset);
                            }
                        }
                    }
                }
            } else {
                offset = buffer.writeUInt8(0, offset);
            }
        } else {
            //input script
            let script_buffer = encodeInputScript(input.script);
            offset += bufferutils.writeVarInt(buffer, script_buffer.length, offset);
            offset += script_buffer.copy(buffer, offset);
        }

        offset = buffer.writeUInt32LE(input.sequence, offset);
    });
    return buffer.slice(0, offset);
}
569009
function encodeArray(array, proto, offset, buffer, protos){
    let i = 0;

    if(util.isSimpleType(proto.type)){
      offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag));
      offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length));
      for(i = 0; i < array.length; i++){
        offset = encodeProp(array[i], proto.type, offset, buffer);
      }
    }else{
      for(i = 0; i < array.length; i++){
        offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag));
        offset = encodeProp(array[i], proto.type, offset, buffer, protos);
      }
    }

    return offset;
  }