Encodes a video to a specified file. All encoder specific options
        are passed in using `params`.
191712
def encode(self, source_path, target_path, params):  # NOQA: C901
        
        total_time = self.get_media_info(source_path)['duration']

        cmds = [self.ffmpeg_path, '-i', source_path]
        cmds.extend(self.params)
        cmds.extend(params)
        cmds.extend([target_path])

        process = self._spawn(cmds)

        buf = output = ''
        # update progress
        while True:
            # any more data?
            out = process.stderr.read(10)
            if not out:
                break

            out = out.decode(console_encoding)
            output += out
            buf += out

            try:
                line, buf = buf.split('\r', 1)
            except ValueError:
                continue

            try:
                time_str = RE_TIMECODE.findall(line)[0]
            except IndexError:
                continue

            # convert progress to percent
            time = 0
            for part in time_str.split(':'):
                time = 60 * time + float(part)

            percent = time / total_time
            logger.debug('yield {}%'.format(percent))
            yield percent

        if os.path.getsize(target_path) == 0:
            raise exceptions.FFmpegError("File size of generated file is 0")

        # wait for process to exit
        self._check_returncode(process)

        logger.debug(output)
        if not output:
            raise exceptions.FFmpegError("No output from FFmpeg.")

        yield 100
133286
function encodeParams(cache, API_URL, params) {
  var obj = {}, v;
  for (var k in params) {
    if (!params.hasOwnProperty(k)) continue;
    v = obj[k] = encode(cache, API_URL, params[k]);
    if (!v) return;
  }
  return obj;
}
502809
def combine_pyramid_and_save(g_video, orig_video, enlarge_multiple, fps, save_filename='media/output.avi'):
    """"""
    width, height = get_frame_dimensions(orig_video[0])
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    print("Outputting to %s" % save_filename)
    writer = cv2.VideoWriter(save_filename, fourcc, fps, (width, height), 1)
    for x in range(0, g_video.shape[0]):
        img = np.ndarray(shape=g_video[x].shape, dtype='float')
        img[:] = g_video[x]
        for i in range(enlarge_multiple):
            img = cv2.pyrUp(img)

        img[:height, :width] = img[:height, :width] + orig_video[x]
        res = cv2.convertScaleAbs(img[:height, :width])
        writer.write(res)
916243
def multipart_encode(self, vars):
        ""
        boundary = mimetools.choose_boundary()
        buf = StringIO()
        for key, value in vars.items():
            if not isinstance(value, file):
                buf.write('--%s\r\n' % boundary)
                buf.write('Content-Disposition: form-data; name="%s"' % key)
                buf.write('\r\n\r\n' + value + '\r\n')
            else:
                fd = value
                file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
                filename = os.path.basename(fd.name)
                contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
                buf.write('--%s\r\n' % boundary)
                buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
                buf.write('Content-Type: %s\r\n' % contenttype)
                # buffer += 'Content-Length: %s\r\n' % file_size
                fd.seek(0)
                buf.write('\r\n' + fd.read() + '\r\n')
        buf.write('--' + boundary + '--\r\n\r\n')
        buf = buf.getvalue()
        return boundary, buf
478802
def encode(self):
        """"""
        tftpassert(self.filename, "filename required in initial packet")
        tftpassert(self.mode, "mode required in initial packet")
        # Make sure filename and mode are bytestrings.
        filename = self.filename
        mode = self.mode
        if not isinstance(filename, bytes):
            filename = filename.encode('ascii')
        if not isinstance(self.mode, bytes):
            mode = mode.encode('ascii')

        ptype = None
        if self.opcode == 1: ptype = "RRQ"
        else:                ptype = "WRQ"
        log.debug("Encoding %s packet, filename = %s, mode = %s",
            ptype, filename, mode)
        for key in self.options:
            log.debug("    Option %s = %s", key, self.options[key])

        fmt = b"!H"
        fmt += b"%dsx" % len(filename)
        if mode == b"octet":
            fmt += b"5sx"
        else:
            raise AssertionError("Unsupported mode: %s" % mode)
        # Add options. Note that the options list must be bytes.
        options_list = []
        if len(list(self.options.keys())) > 0:
            log.debug("there are options to encode")
            for key in self.options:
                # Populate the option name
                name = key
                if not isinstance(name, bytes):
                    name = name.encode('ascii')
                options_list.append(name)
                fmt += b"%dsx" % len(name)
                # Populate the option value
                value = self.options[key]
                # Work with all strings.
                if isinstance(value, int):
                    value = str(value)
                if not isinstance(value, bytes):
                    value = value.encode('ascii')
                options_list.append(value)
                fmt += b"%dsx" % len(value)

        log.debug("fmt is %s", fmt)
        log.debug("options_list is %s", options_list)
        log.debug("size of struct is %d", struct.calcsize(fmt))
        
        self.buffer = struct.pack(fmt,
                                  self.opcode,
                                  filename,
                                  mode,
                                  *options_list)

        log.debug("buffer is %s", repr(self.buffer))
        return self
1151891
protected void encodeOptionalParameters(Map<Integer, ISUPParameter> parameters, ByteArrayOutputStream bos)
            throws ParameterException {

        // NOTE: parameters MUST have as last endOfOptionalParametersParameter+1
        // param
        for (ISUPParameter p : parameters.values()) {

            if (p == null)
                continue;

            byte[] b = ((AbstractISUPParameter) p).encode();
            // System.err.println("ENCODE O: "+p.getCode()+"---> "+Utils.toHex(b));
            // FIXME: this can be slow, maybe we shoudl remove that, and code
            // this explicitly?
            if (b.length > 255) {
                throw new ParameterException("Parameter length is over 255: " + p);
            }
            if (!(p instanceof EndOfOptionalParametersImpl)) {
                bos.write(p.getCode());

                bos.write(b.length);
            }
            try {
                bos.write(b);
            } catch (IOException e) {
                throw new ParameterException("Failed to encode optional parameters.", e);
            }
        }

    }
586880
def encoded_image(image, options = {})
      target_format = options[:format] || default_render_format

      unless target_format.in?(Alchemy::Picture.allowed_filetypes)
        raise WrongImageFormatError.new(self, target_format)
      end

      options = {
        flatten: target_format != 'gif' && image_file_format == 'gif'
      }.merge(options)

      encoding_options = []

      if target_format =~ /jpe?g/
        quality = options[:quality] || Config.get(:output_image_jpg_quality)
        encoding_options << "-quality #{quality}"
      end

      if options[:flatten]
        encoding_options << '-flatten'
      end

      convertion_needed = target_format != image_file_format || encoding_options.present?

      if has_convertible_format? && convertion_needed
        image = image.encode(target_format, encoding_options.join(' '))
      end

      image
    end
376886
def encode(self, file):
        
        tag = Tag()
        tag.sigma = list()

        state = State(Random.new().read(32), Random.new().read(32))

        f = KeyedPRF(state.f_key, self.prime)
        alpha = KeyedPRF(state.alpha_key, self.prime)

        done = False
        chunk_id = 0

        while (not done):
            sigma = f.eval(chunk_id)
            for j in range(0, self.sectors):
                buffer = file.read(self.sectorsize)

                if (len(buffer) > 0):
                    sigma += alpha.eval(j) * number.bytes_to_long(buffer)

                if (len(buffer) != self.sectorsize):
                    done = True
                    break
            sigma %= self.prime
            tag.sigma.append(sigma)
            chunk_id += 1

        state.chunks = chunk_id
        state.encrypt(self.key)

        return (tag, state)
158997
function Utf16Encoder(options, codec) {
    options = options || {};
    if (options.addBOM === undefined)
        options.addBOM = true;
    this.encoder = codec.iconv.getEncoder('utf-16le', options);
}
492911
function encodeBuffer( encoder, buffer_type, mime_type, buffer ) {

	// Write buffer header according to buffer length
	if (buffer.length < UINT8_MAX) {
		encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x00 ) );
		encoder.stream8.write( pack1b( buffer.length ) );
		encoder.counters.dat_hdr+=2;
	} else if (buffer.length < UINT16_MAX) {
		encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x08 ) );
		encoder.stream16.write( pack2b( buffer.length ) );
		encoder.counters.dat_hdr+=3;
	} else if (buffer.length < UINT32_MAX) {
		encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x10 ) );
		encoder.stream32.write( pack4b( buffer.length ) );
		encoder.counters.dat_hdr+=5;
	} else {
		// 4 Gigs? Are you serious? Of course we can fit it in a Float64, but WHY?
		throw new Errors.RangeError('The buffer you are trying to encode is bigger than the supported size!');
	}

	// Write MIME Type (from string lookup table)
	if (mime_type != null) {
		encoder.stream16.write( pack2b( mime_type ) );
		encoder.counters.dat_hdr+=2;
	}

	// Write buffer
	if (buffer_type === PRIM_BUFFER_TYPE.STRING_UTF8) {

		// NOTE: UTF-8 is a special case. For optimisation
		// purposes it's better to use the 16-bit stream
		// rather than downcasting to 8-bit and then 
		// re-constructing the 16-bit stream at decoding time.
		encoder.stream16.write( packTypedArray(buffer) );

	} else {
		encoder.stream8.write( packTypedArray(buffer) );
	}

}
248144
function encode (filename) {
  var ext = path.extname(filename)
  var data = fs.readFileSync(filename)
  var prefix = 'data:audio/' + ext.substring(1) + ';base64,'
  var encoded = new Buffer(data).toString('base64')
  return prefix + encoded
}
42909
def save_params_to_file(self, fname: str):
        
        if self.aux_params is not None:
            utils.save_params(self.params.copy(), fname, self.aux_params.copy())
        else:
            utils.save_params(self.params.copy(), fname)
        logging.info('Saved params to "%s"', fname)
1285181
def send_video(self, *args, **kwargs):
        """"""
        return send_video(*args, **self._merge_overrides(**kwargs)).run()
47503
def video(query, opts = {})
      invoke 'Video',
        query,
        opts,
        passthrough_opts: %i(filters sort),
        enum_opt_to_module: {filters: VideoFilter, sort: VideoSort},
        param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'}
    end
136708
def encodeWithCoder(encoder)
      #self.class.tk_vars = instance_variables
      instance_variables.each do |prop|
        reader_sig = reader_sig_for(prop)
        encoder.encodeObject(self.send(reader_sig), forKey: reader_sig)
      end
    end
90475
def _encode_params(**kw):
    '''
    
    '''
    args = []
    for k, v in kw.iteritems():
        if isinstance(v, basestring):
            qv = v.encode('utf-8') if isinstance(v, unicode) else v
            args.append('%s=%s' % (k, urllib.quote(qv)))
        elif isinstance(v, collections.Iterable):
            for i in v:
                qv = i.encode('utf-8') if isinstance(i, unicode) else str(i)
                args.append('%s=%s' % (k, urllib.quote(qv)))
        else:
            qv = str(v)
            args.append('%s=%s' % (k, urllib.quote(qv)))
    return '&'.join(args)
1164622
def file_writer(self, in_frame):
        """"""
        self.update_config()
        path = self.config['path']
        encoder = self.config['encoder']
        fps = self.config['fps']
        bit16 = self.config['16bit']
        numpy_image = in_frame.as_numpy()
        ylen, xlen, bpc = numpy_image.shape
        if bpc == 3:
            if in_frame.type != 'RGB':
                self.logger.warning('Expected RGB input, got %s', in_frame.type)
            pix_fmt = ('rgb24', 'rgb48le')[bit16]
        elif bpc == 1:
            if in_frame.type != 'Y':
                self.logger.warning('Expected Y input, got %s', in_frame.type)
            pix_fmt = ('gray', 'gray16le')[bit16]
        else:
            self.logger.critical(
                'Cannot write %s frame with %d components', in_frame.type, bpc)
            return
        md = Metadata().copy(in_frame.metadata)
        audit = md.get('audit')
        audit += '%s = data\n' % path
        audit += '    encoder: "%s"\n' % (encoder)
        audit += '    16bit: %s\n' % (self.config['16bit'])
        md.set('audit', audit)
        md.to_file(path)
        with self.subprocess(
                ['ffmpeg', '-v', 'warning', '-y', '-an',
                 '-s', '%dx%d' % (xlen, ylen),
                 '-f', 'rawvideo', '-c:v', 'rawvideo',
                 '-r', '%d' % fps, '-pix_fmt', pix_fmt, '-i', '-',
                 '-r', '%d' % fps] + encoder.split() + [path],
                stdin=subprocess.PIPE) as sp:
            while True:
                in_frame = yield True
                if not in_frame:
                    break
                if bit16:
                    numpy_image = in_frame.as_numpy(dtype=pt_float)
                    numpy_image = numpy_image * pt_float(256.0)
                    numpy_image = numpy_image.clip(
                        pt_float(0), pt_float(2**16 - 1)).astype(numpy.uint16)
                else:
                    numpy_image = in_frame.as_numpy(dtype=numpy.uint8)
                sp.stdin.write(numpy_image.tostring())
                del in_frame