Send a file to the client, it is a convenient method to avoid duplicated code
15767
def send_file(self, file):
        
        if self.logger:
            self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file)

        self.send_file_header(file)

        fp = open(file, 'rb')
        self.write(fp.read())

        fp.close()
792151
def send(self):
        
        log = logging.getLogger(self.cls_logger + '.send')

        if self.attachments:
            self.payload['attachments'] = self.attachments

        # Encode payload in JSON
        log.debug('Using payload: %s', self.payload)
        try:
            json_payload = json.JSONEncoder().encode(self.payload)
        except(TypeError, ValueError, OverflowError):
            _, ex, trace = sys.exc_info()
            msg = 'There was a problem encoding the JSON payload\n{e}'.format(e=str(ex))
            raise OSError, msg, trace
        else:
            log.debug('JSON payload: %s', json_payload)

        # Post to Slack!
        log.debug('Posting message to Slack...')
        try:
            result = requests.post(url=self.webhook_url, data=json_payload)
        except requests.exceptions.ConnectionError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem posting to Slack\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise OSError, msg, trace

        # Check return code
        if result.status_code != 200:
            log.error('Slack post to url {u} failed with code: {c}'.format(c=result.status_code, u=self.webhook_url))
        else:
            log.debug('Posted message to Slack successfully.')

        # Clear out attachments after sending
        self.attachments = []
        self.payload.pop('attachments', None)
540197
function send(httpMethod, path, req) {
    req = req || {};
    httpMethod = httpMethod.toUpperCase();

    var deferred = Q.defer();
    var url = baseUrl + path;
    var data = req.data || {};          // separate out data from request
    delete req.data;

    var isAdmin = req.caller && req.caller.role === 'admin';
    delete req.caller;

    var id = req._id || data._id;       // get id from request or data
    if (req._id) { delete req._id; }    // delete id from request so no dupe

    var session = cls.getNamespace('appSession');
    var caller = session && session.active && session.get('caller');
    if (caller && !isAdmin) {
        _.extend(req, {                 // onBehalfOf used by API to know who is the caller
            onBehalfOfType: caller.type,
            onBehalfOfId:   caller._id + '',
            onBehalfOfRole: caller.role,
            onBehalfOfName: caller.name
        });
    }

    _.each(req, function (val, key) {
        if (!_.isString(val)) { req[key] = JSON.stringify(val); }
    });

    // replace the ID portion of the URL
    url = id ?
        url.replace('{_id}', id + '') :
        url.replace('/{_id}', '');

    var reqConfig = {
        headers:    headers,
        url:        url,
        method:     httpMethod,
        qs:         _.isEmpty(req) ? undefined : req,
        json:       _.isEmpty(data) ? true : data
    };

    // if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup)
    if (!baseUrl) {
        setTimeout(function () {
            makeRequest(reqConfig, deferred);
        }, 100);
    }
    else {
        makeRequest(reqConfig, deferred);
    }

    return deferred.promise;
}
915359
public void send(Object object) {
        if (object instanceof File) {
            file((File) object);
        } else {
            send(object, getContentType());
        }
    }
681141
def sendfile(self, data, zlib_compress=None, compress_level=6):
        """"""
        if hasattr(data, 'seek'):
            data.seek(0)

        chunk_size = CHUNK_SIZE

        if zlib_compress:
            chunk_size = BLOCK_SIZE
            compressor = compressobj(compress_level)

        while 1:
            binarydata = data.read(chunk_size)
            if binarydata == '':
                break
            if zlib_compress:
                binarydata = compressor.compress(binarydata)
                if not binarydata:
                    continue
            self.send(binarydata)

        if zlib_compress:
            remaining = compressor.flush()
            while remaining:
                binarydata = remaining[:BLOCK_SIZE]
                remaining = remaining[BLOCK_SIZE:]
                self.send(binarydata)
1051338
def dcc_send(self, mask, filepath):
        """"""
        return self.dcc.create('send', mask, filepath=filepath).ready
1130056
def send_file(path, opts = {})
      if opts[:type] or not response['Content-Type']
        content_type opts[:type] || File.extname(path), :default => 'application/octet-stream'
      end

      disposition = opts[:disposition]
      filename    = opts[:filename]
      disposition = :attachment if disposition.nil? and filename
      filename    = path        if filename.nil?
      attachment(filename, disposition) if disposition

      last_modified opts[:last_modified] if opts[:last_modified]

      file   = Rack::File.new(File.dirname(settings.app_file))
      result = file.serving(request, path)

      result[1].each { |k,v| headers[k] ||= v }
      headers['Content-Length'] = result[1]['Content-Length']
      opts[:status] &&= Integer(opts[:status])
      halt (opts[:status] || result[0]), result[2]
    rescue Errno::ENOENT
      not_found
    end
273977
def send_text_file(self, text_file, sender=None, recipient=None):
        
        log = logging.getLogger(self.cls_logger + '.send_text_file')

        if not isinstance(text_file, basestring):
            msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
            raise AssetMailerError(msg)

        if not os.path.isfile(text_file):
            msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
            raise AssetMailerError(msg)

        # Determine sender/recipient
        if sender is None:
            sender = default_sender_email
        if recipient is None:
            recipient = self.recipient_email

        # Set the email subject
        file_name = text_file.split(os.path.sep)[-1]
        subject = self.subject + file_name

        # Read the input text file
        try:
            fp = open(text_file, 'rb')
            mail_message = MIMEText(fp.read())
            fp.close()
        except OSError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
                n=ex.__class__.__name__, f=text_file, e=str(ex))
            raise AssetMailerError, msg, trace

        # Configure the mail message
        mail_message['Subject'] = subject
        mail_message['From'] = sender
        mail_message['To'] = recipient

        # Configure the SMTP server
        log.debug('Configuring the SMTP server...')
        try:
            s = smtplib.SMTP(self.smtp_server)
        except (smtplib.SMTPConnectError, socket.timeout, socket.error):
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
                n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
            raise AssetMailerError, msg, trace

        # Set the SMTP log level
        # s.set_debuglevel(debuglevel=__debug__)

        # Set the SMTP server to be localhost
        log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
        try:
            s.sendmail(sender, [recipient], mail_message.as_string())
        except smtplib.SMTPRecipientsRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
                n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPSenderRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
                n=ex.__class__.__name__, s=sender, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPHeloError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPDataError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPConnectError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a connection error\n{e}'. \
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        else:
            log.info('Sent email to: {r}'.format(r=recipient))
        finally:
            s.quit()
707676
def send_file(self, filename, restricted=True, mimetype=None,
                  trusted=False, chunk_size=None, as_attachment=False,
                  **kwargs):
        """"""
        return self.storage(**kwargs).send_file(
            filename,
            mimetype=mimetype,
            restricted=restricted,
            checksum=self.checksum,
            trusted=trusted,
            chunk_size=chunk_size,
            as_attachment=as_attachment,
        )
1266460
private AFTPClient actionGetFile() throws PageException, IOException {
	required("remotefile", remotefile);
	required("localfile", localfile);

	AFTPClient client = getClient();
	Resource local = ResourceUtil.toResourceExistingParent(pageContext, localfile);// new File(localfile);
	pageContext.getConfig().getSecurityManager().checkFileLocation(local);
	if (failifexists && local.exists()) throw new ApplicationException("File [" + local + "] already exist, if you want to overwrite, set attribute failIfExists to false");
	OutputStream fos = null;
	client.setFileType(getType(local));
	boolean success = false;
	try {
	    fos = IOUtil.toBufferedOutputStream(local.getOutputStream());
	    success = client.retrieveFile(remotefile, fos);
	}
	finally {
	    IOUtil.closeEL(fos);
	    if (!success) local.delete();
	}
	writeCfftp(client);

	return client;
    }
1015639
def send_file_to_host(src_filename, dst_file, filesize):
    """"""
    import sys
    import ubinascii
    try:
        with open(src_filename, 'rb') as src_file:
            bytes_remaining = filesize
            if HAS_BUFFER:
                buf_size = BUFFER_SIZE
            else:
                buf_size = BUFFER_SIZE // 2
            while bytes_remaining > 0:
                read_size = min(bytes_remaining, buf_size)
                buf = src_file.read(read_size)
                if HAS_BUFFER:
                    sys.stdout.buffer.write(buf)
                else:
                    sys.stdout.write(ubinascii.hexlify(buf))
                bytes_remaining -= read_size
                # Wait for an ack so we don't get ahead of the remote
                while True:
                    char = sys.stdin.read(1)
                    if char:
                        if char == '\x06':
                            break
                        # This should only happen if an error occurs
                        sys.stdout.write(char)
        return True
    except:
        return False
447199
static function sendFile($file_path,$display_name = null){
        if($display_name ===null){
            $display_name = basename($file_path);
        }
        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename='.urlencode($display_name));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Content-Length: '.filesize($file_path));
        readfile($file_path);
    }
128462
async def send_data(self):
        """"""
        self.connection._ensure_alive()
        conn = self.connection

        try:
            await self._open_file()
            with self._file_object:
                chunk_size = MAX_PACKET_LEN
                while True:
                    chunk = await self._file_read(chunk_size)
                    if not chunk:
                        break
                    # TODO: consider drain data
                    conn.write_packet(chunk)
        except asyncio.CancelledError:
            self.connection._close_on_cancel()
            raise
        finally:
            # send the empty packet to signify we are done sending data
            conn.write_packet(b"")
958880
def send_response(self, code, message=None, size='-'):
        
        # pylint: disable-msg=W0221
        if self._to_log or LOG.isEnabledFor(logging.DEBUG):
            self.log_request(code, size)

        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
            else:
                message = ''

        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                             ("HTTP/1.1", code, message))
        self.send_header('Server', self.version_string())
        self.send_header('Date', self.date_time_string())
34048
def put_file(client, source_file, destination_file):
    
    try:
        sftp_client = client.open_sftp()
        sftp_client.put(source_file, destination_file)
    except Exception as error:
        raise IpaUtilsException(
            'Error copying file to instance: {0}.'.format(error)
        )
    finally:
        with ignored(Exception):
            sftp_client.close()
9222
def send_single_file(self, sender, receiver, media_id):
        
        return self.send_file(sender, 'single', receiver, media_id)
1014085
function copyFile(source, target, copyCallback) {
    const readStream = fs.createReadStream(source);
    const writeStream = fs.createWriteStream(target);
    let done = false;

    readStream.on('error', copyDone);
    writeStream.on('error', copyDone);

    writeStream.on('close', function onWriteCb() {
        copyDone(null);
    });

    readStream.pipe(writeStream);

    /**
     * Finish copying. Reports error when needed
     * @param [error] optional error
     */
    function copyDone(error) {
        if (!done) {
            done = true;
            copyCallback(error);
        }
    }
}