Process a piece that we've received from a peer, writing it out to
        one or more files
342261
def ppiece(self, content):
        '''
        
        '''
        piece_index, byte_begin = struct.unpack('!ii', content[0:8])

        # TODO -- figure out a better way to catch this error.
        # How is piece_index getting swapped out from under me?
        if piece_index != self.piece.index:
            return

        assert byte_begin % REQUEST_SIZE == 0
        block_begin = byte_begin / REQUEST_SIZE
        block = content[8:]
        self.piece.save(index=block_begin, bytes=block)
        if self.piece.complete:
            piece_bytes = self.piece.get_bytes()
            if self.piece.index == self.torrent.last_piece:
                piece_bytes = piece_bytes[:self.torrent.last_piece_length]
            if hashlib.sha1(piece_bytes).digest() == (self.torrent.torrent_dict
                                                      ['info']['pieces']
                                                      [20 * piece_index:20 *
                                                       piece_index + 20]):

                print 'hash matches'

                # Take care of visualizer stuff
                piece_dict = {'kind': 'piece', 'peer': self.sock.getpeername(),
                              'piece_index': piece_index}
                self.torrent.switchboard.broadcast(piece_dict)

                print ('writing piece {}. Length is '
                       '{}').format(repr(piece_bytes)[:10] + '...',
                                    len(piece_bytes))

                # Write out
                byte_index = piece_index * self.torrent.piece_length
                self.piece = self.init_piece()
                self.request_all()
                self.torrent.switchboard.write(byte_index, piece_bytes)
                self.torrent.switchboard.mark_off(piece_index)
                print self.torrent.switchboard.bitfield
                if self.torrent.switchboard.complete:
                    print '\nDownload complete\n'
                    self.reactor.is_running = False
            else:
                print "Bad data -- hash doesn't match. Discarding piece."
                self.piece = self.init_piece()
                self.request_all()
1281043
def write(self, data):
        
        while data:
            went = self._write_chunk(data)
            if went is None:
                continue
            data = data[went:]
1315112
def _process_items(items, user_conf, error_protocol):
    
    def process_meta(item, error_protocol):
        try:
            return item._parse()
        except Exception, e:
            error_protocol.append(
                "Can't parse %s: %s" % (item._get_filenames()[0], e.message)
            )

            if isinstance(item, DataPair):
                return item.ebook_file

    # process all items and put them to output queue
    out = []
    for item in items:
        if isinstance(item, EbookFile):
            out.append(item)
        else:
            out.append(process_meta(item, error_protocol))
    out = filter(lambda x: x, out)  # remove None items (process_meta() fails)

    # remove processed files
    fn_pool = []
    soon_removed = out if conf_merger(user_conf, "LEAVE_BAD_FILES") else items
    for item in soon_removed:
        fn_pool.extend(item._get_filenames())

    _remove_files(fn_pool)

    return out
996790
def regenerateToOutputFile(outFile, checkNoChanges = false)
      executeRubyComponents
      @pageObject.process
      writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
    end
225844
def write_chunks(out, chunks):
    """"""

    out.write(_signature)
    for chunk in chunks:
        write_chunk(out, *chunk)
1366488
def process_text(self, kind, context):
		""""""
		
		result = None
		
		while True:
			chunk = yield None
			
			if chunk is None:
				if result:
					yield result.clone(line=repr(result.line))
				
				return
			
			if not result:
				result = chunk
				continue
			
			result.line += chunk.line
589704
def write(self, data):
        """"""

        if len(data) > self.data_size:
            raise ValueError

        self.__fileobj.seek(self.data_offset)
        self.__fileobj.write(data)
866167
def write(self, arg, **kwargs):
        """"""
        if hasattr(arg, 'seek'):
            self._tofile(arg, **kwargs)
        else:
            with open(arg, 'wb') as fid:
                self._tofile(fid, **kwargs)
27630
def write_to_local(self, filepath_from, filepath_to, mtime_dt=None):
        """"""

        self.__log.debug("Writing R[%s] -> L[%s]." % (filepath_from, 
                                                      filepath_to))

        with SftpFile(self, filepath_from, 'r') as sf_from:
            with open(filepath_to, 'wb') as file_to:
                while 1:
                    part = sf_from.read(MAX_MIRROR_WRITE_CHUNK_SIZE)
                    file_to.write(part)

                    if len(part) < MAX_MIRROR_WRITE_CHUNK_SIZE:
                        break

        if mtime_dt is None:
            mtime_dt = datetime.now()

        mtime_epoch = mktime(mtime_dt.timetuple())
        utime(filepath_to, (mtime_epoch, mtime_epoch))
723899
def write_batch(self, batch):
        
        for item in batch:
            for key in item:
                self.aggregated_info['occurrences'][key] += 1
            self.increment_written_items()
            if self.items_limit and self.items_limit == self.get_metadata('items_count'):
                raise ItemsLimitReached('Finishing job after items_limit reached: {} items written.'
                                        .format(self.get_metadata('items_count')))
        self.logger.debug('Wrote items')
167944
def submit(self):
        """"""
        self._newflg = False
        ret = list()
        for buf in self._buffer.values():
            buf = copy.deepcopy(buf)
            if self._fdpext:
                buf['fpout'] = f"{self._fproot}/{buf['label']}.{self._fdpext}"
            else:
                del buf['fpout']
            buf['index'] = tuple(buf['index'])
            ret.append(Info(buf))
        ret += self._stream
        return tuple(ret)
445542
def write(self):
        """"""
        if self._path is None:
            raise ValueError("Instance was not initialized with a path, use to_file(...) instead")
        # END assert path
        self.to_file(self._path)
        return self
869483
def wrap(self, data, many):
        """"""
        if not many:
            return data
        else:
            data = {'parts': data}
            multipart = self.context.get('multipart')
            if multipart:
                data.update(MultipartObjectSchema(context={
                    'bucket': multipart.bucket}).dump(multipart).data)
            return data
224021
function wrapWrite(std, print) {
  process[std].write = function (data) {
    cachedData[std].push(data);

    if (print)
      originalWrites[std].apply(process[std], arguments);
  };
}
431917
function writeFiles (files, callback) {
  async.map(files, writeFile.bind(this), function (err) {
    if (err) callback(err);
    callback(null);
  });
}
829177
function _write (chunk, encoding, callback) {
  /* istanbul ignore else */
  if (Array.isArray(this.options.input.buffer)) {
    /* istanbul ignore else */
    if (is.buffer(chunk)) {
      if (this.options.input.buffer.length === 0) {
        const that = this;
        this.on('finish', function () {
          that.streamInFinished = true;
        });
      }
      this.options.input.buffer.push(chunk);
      callback();
    } else {
      callback(new Error('Non-Buffer data on Writable Stream'));
    }
  } else {
    callback(new Error('Unexpected data on Writable Stream'));
  }
}
791343
def process(parsed_files, opts)
      r = aggregate(parsed_files)
      r = pre_process(r, opts)
      r = to_class_objects(r, opts)
      return post_process(r, opts)
    end