Ask user for a file to send to a work
338249
def send_work(baseurl, work_id=None, filename=None, command="make"):
    """"""
    while 1:
        if not work_id:
            try:
                work_id = input("id? ")
            except KeyboardInterrupt:
                exit(0)
        work = get_work(work_id)
        if not work:
            print("id '{0}' not found".format(work_id))
            work_id = None
            continue
        if not work.is_open:  # Verify it is open
            print('"It\'s too late for {0} baby..." (Arnold Schwarzenegger)'.format(work.title))
            work_id = None
            continue
        if not filename:
            try:
                filename = input("filename? ")
            except KeyboardInterrupt:
                exit(0)
        while 1:
            try:
                if command:
                    if not archive_compile(filename, command):
                        print("Compilation failed")
                        try:
                            send = input("Send anyway [y/N] ")
                        except KeyboardInterrupt:
                            exit(0)
                        if send != "y":
                            exit(1)
                            return
                work.upload(baseurl, filename)
                print("Uplodaed, but should verify it on the website")
                return
            except FileNotFoundError:
                print("{0} not found in current dir".format(filename))
                filename = None
120551
def __send_main_file(self, file_name):
        

        file_name = join(self.app.static_folder, file_name)

        with codecs.open(file_name, 'r', 'utf-8') as file:
            data = file.read()

        data = data.replace(
            'fields.article.url = apiProject.url + fields.article.url;',
            '''if (fields.article.url.substr(0, 4).toLowerCase() !== \'http\')
                        fields.article.url = apiProject.url + fields.article.url;''')

        headers = Headers()
        headers['Content-Length'] = getsize(file_name)

        response = self.app.response_class(data,
                                           mimetype=mimetypes.guess_type(file_name)[0],
                                           headers=headers,
                                           direct_passthrough=True)

        response.last_modified = int(getmtime(file_name))

        return response
54277
function write (item) {

  var filename = item.file;
  var message = item.message;
  var header = item.header;
  var file = path.join(p_, filename);

  fs.exists(file, function (exists) {
    if (exists) {
      fs.appendFile(file, message, function () {
        task();
      });

    } else {
      if (header) {
        message = header + EOL + message;
      }

      var dir = path.dirname(file);
      fs.exists(dir, function (exists) {
        if (exists) {
          fs.appendFile(file, message, function () {
            task();
          });

        } else {
          fs.mkdirs(dir, function (err) {
            if (err) {
              console.error(err);
              task();
            } else {
              fs.appendFile(file, message, function () {
                task();
              });
            }
          });
        }
      });
    }
  });
}
1051338
def dcc_send(self, mask, filepath):
        """"""
        return self.dcc.create('send', mask, filepath=filepath).ready
1269621
def send(self, save_to_sent_folder=True):
        

        if self.object_id and not self.__is_draft:
            return RuntimeError('Not possible to send a message that is not '
                                'new or a draft. Use Reply or Forward instead.')

        if self.__is_draft and self.object_id:
            url = self.build_url(
                self._endpoints.get('send_draft').format(id=self.object_id))
            if self._track_changes:
                # there are pending changes to be committed
                self.save_draft()
            data = None

        else:
            url = self.build_url(self._endpoints.get('send_mail'))
            data = {self._cc('message'): self.to_api_data()}
            if save_to_sent_folder is False:
                data[self._cc('saveToSentItems')] = False

        response = self.con.post(url, data=data)
        # response evaluates to false if 4XX or 5XX status codes are returned
        if not response:
            return False

        self.object_id = 'sent_message' if not self.object_id \
            else self.object_id
        self.__is_draft = False

        return True
696842
function uploadRequest(res, fileObject, showProgress) {
  var url = res.url;
  var expiration = res.expiration;
  var hmac = res.hmac;
  var uuid = res.uuid;
  var file = fileObject.file;
  var uid = fileObject.uid;

  var upload_url = buildUploadURL(url, uuid, expiration, hmac, file.name);

  return new Promise(function (resolve, reject) {
    reqs[uid] = _superagent2.default.put(upload_url).send(file).set({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }).on('progress', function (e) {
      showProgress(e, fileObject);
    }).end(function (err, res) {
      delete reqs[uid];

      // throw a custom error message
      if (err) return reject(customError('uploadRequest', err));

      resolve(res);
    });
  });
}
1274166
def send_request(self, *args, **kwargs):
        
        try:
            return super(JSHost, self).send_request(*args, **kwargs)
        except RequestsConnectionError as e:
            if (
                self.manager and
                self.has_connected and
                self.logfile and
                'unsafe' not in kwargs
            ):
                raise ProcessError(
                    '{} appears to have crashed, you can inspect the log file at {}'.format(
                        self.get_name(),
                        self.logfile,
                    )
                )
            raise six.reraise(RequestsConnectionError, RequestsConnectionError(*e.args), sys.exc_info()[2])
335944
function ask(file, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts;
    opts = {};
  }
  opts = opts || {};
  var prompt = lazy.inquirer.createPromptModule();
  var fp = path.relative(process.cwd(), file.path);

  var questions = {
    name: 'action',
    type: 'expand',
    message: 'Overwrite `' + fp + '`?',
    value: 'nothing',
    choices: [{
      key: 'n',
      name: 'do not overwrite',
      value: 'skip'
    }, {
      key: 'y',
      name: 'overwrite',
      value: 'write'
    }, {
      key: 'a',
      name: 'overwrite this and all others',
      value: 'force'
    }, {
      key: 'x',
      name: 'abort',
      value: 'abort'
    }, {
      key: 'd',
      name: 'diff comparison between the current and new:',
      value: 'diff'
    }]
  };

  prompt([questions], function (answers) {
    var msg = answers.action;

    switch(answers.action) {
      case 'skip':
        cb(answers.action);
        process.exit(0);

      case 'abort':
        msg = utils.red(utils.error) + ' Aborted. No action was taken.';
        if (!opts.silent) console.log(msg);
        cb(answers.action);
        process.exit(0);

      case 'diff':
        var existing = opts.existing || fs.readFileSync(fp, 'utf8');
        if (lazy.isBinary(existing) && typeof opts.binaryDiff === 'function') {
          opts.binaryDiff(existing, file.contents);
        } else {
          stringDiff(existing, file.contents.toString());
        }
        return ask(file, opts, cb);

      case 'force':
        opts.force = true;
        break;

      case 'write':
        msg = utils.green(utils.success) + ' file written to';
        opts.force = true;
        break;

      default: {
        msg = utils.red(utils.error) + utils.red(' Aborted.') + ' No action was taken.';
        if (!opts.silent) console.log(msg);
        cb(answers.action);
        process.exit(0);
      }
    }

    var rel = path.relative(process.cwd(), fp);
    var filepath = utils[answers.action](rel);
    if (!opts.silent) {
      console.log(msg, filepath);
    }
    return cb(answers.action);
  });
}
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
1293232
def submit(command_filename, workingdir, send_mail = False, username = None):
    ''''''

    # Open streams
    command_filename = command_filename
    outfile = command_filename + ".out"
    file_stdout = open(outfile, 'w')

    # Form command
    command = ['qsub']

    if send_mail and username:
        #username = 'Shane.OConnor@ucsf.edu'
        command.extend(['-m', 'eas', '-M', '%s@chef.compbio.ucsf.edu' % username])
    command.append(command_filename)

    # Submit the job and capture output.
    try:
        subp = subprocess.Popen(command, stdout=file_stdout, stderr=file_stdout, cwd=workingdir)
    except Exception, e:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise

    waitfor = 0
    errorcode = subp.wait()
    file_stdout.close()

    file_stdout = open(outfile, 'r')
    output = file_stdout.read().strip()
    file_stdout.close()

    if errorcode != 0:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise Exception(output)

    # Match job id
    # This part of the script may be error-prone as it depends on the server message.
    matches = re.match('Your job-array (\d+).(\d+)-(\d+):(\d+)', output)
    if not matches:
        matches = re.match('Your job (\d+) \(".*"\) has been submitted.*', output)

    if matches:
        jobid = int(matches.group(1))
    else:
        jobid = -1

    output = output.replace('"', "'")
    if output.startswith("qsub: ERROR"):
        raise Exception(output)

    os.remove(outfile)
    #os.remove(command_filename)

    return jobid, output
1175891
def _send_file(self, filename):
        
        # pylint: disable=E1101
        ftp = ftplib.FTP(host=self.host)
        ftp.login(user=self.user, passwd=self.password)
        ftp.set_pasv(True)
        ftp.storbinary("STOR %s" % os.path.basename(filename),
            file(filename, 'rb'))
408980
def _post(self, url, data={}, **kwargs):
        """"""
        if 'files' in kwargs:
            req = self._session.post(self._api_prefix + url, auth=self._session.auth, data=data, **kwargs)
            return self._action(req)

        req = self._session.post(self._api_prefix + url, data=data, **kwargs)
        return self._action(req)
1048454
async def send_document(self, path, entity):
        """"""
        await self.send_file(
            entity, path,
            force_document=True,
            progress_callback=self.upload_progress_callback
        )
        print('Document sent!')
692392
def write_to_file(chats, chatfile):
    """"""
    with open(chatfile, 'w') as handler:
        handler.write('\n'.join((str(id_) for id_ in chats)))
322892
async def send_file(self, file_type, method, file, payload) -> Union[Dict, base.Boolean]:
        
        if file is None:
            files = {}
        elif isinstance(file, str):
            # You can use file ID or URL in the most of requests
            payload[file_type] = file
            files = None
        else:
            files = {file_type: file}

        return await self.request(method, payload, files)
1258816
def _open_for_write(self):
        """"""
        def put_request(body):
            """

            :param body:
            """
            ownerid, datasetid = parse_dataset_key(self._dataset_key)
            response = requests.put(
                "{}/uploads/{}/{}/files/{}".format(
                    self._api_host, ownerid, datasetid, self._file_name),
                data=body,
                headers={
                    'User-Agent': self._user_agent,
                    'Authorization': 'Bearer {}'.format(
                        self._config.auth_token)
                })
            self._response_queue.put(response)

        body = iter(self._queue.get, self._sentinel)
        self._thread = Thread(target=put_request, args=(body,))
        self._thread.start()
768948
public function sendResponse()
    {
        if (!function_exists('ob_list_handlers') || ob_list_handlers()) {
            @ob_end_clean();
        }
        header("Content-Encoding: none");

        $this->checkConnector();
        $this->checkRequest();

        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_GET["FileName"]);
        $_resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

        if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if (!$_resourceTypeInfo->checkExtension($fileName, false)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $fileName);
        if ($_resourceTypeInfo->checkIsHiddenFile($fileName) || !file_exists($filePath) || !is_file($filePath)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
        }

        $fileName = CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($fileName);

        header("Cache-Control: cache, must-revalidate");
        header("Pragma: public");
        header("Expires: 0");
        if (!empty($_GET['format']) && $_GET['format'] == 'text') {
            header("Content-Type: text/plain; charset=utf-8");
        }
        else {
            $user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
            $encodedName = str_replace("\"", "\\\"", $fileName);
            if (strpos($user_agent, "MSIE") !== false) {
                $encodedName = str_replace(array("+", "%2E"), array(" ", "."), urlencode($encodedName));
            }
            header("Content-type: application/octet-stream; name=\"" . $fileName . "\"");
            header("Content-Disposition: attachment; filename=\"" . $encodedName. "\"");
        }
        header("Content-Length: " . filesize($filePath));
        CKFinder_Connector_Utils_FileSystem::sendFile($filePath);
        exit;
    }