Upload a document file (of any type) to One Codex
497210
def documents_upload(ctx, max_threads, files):
    """"""
    if len(files) == 0:
        click.echo(ctx.get_help())
        return

    files = list(files)

    bar = click.progressbar(length=sum([_file_size(x) for x in files]), label="Uploading... ")
    run_via_threadpool(
        ctx.obj["API"].Documents.upload,
        files,
        {"progressbar": bar},
        max_threads=max_threads,
        graceful_exit=False,
    )
1248157
def attach(doc_id, doc_rev, attachment_name, data, opts=nil)

      if opts.nil?
        opts = data
        data = attachment_name
        attachment_name = doc_rev
        doc_rev = doc_id['_rev']
        doc_id = doc_id['_id']
      end

      attachment_name = attachment_name.gsub(/\//, '%2F')

      ct = opts[:content_type]

      raise(ArgumentError.new(
        ":content_type option must be specified"
      )) unless ct

      opts[:cache] = false

      path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")

      if @http.variant == :patron

        # patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting
        # attachements
        # this is a fallback to net/http

        require 'net/http'

        http = Net::HTTP.new(@http.host, @http.port)

        req = Net::HTTP::Put.new(path)
        req['User-Agent'] =
          "rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)"
        req['Content-Type'] =
          opts[:content_type]
        req['Accept'] =
          'application/json'
        req.body = data

        res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) })

        return @http.send(:respond, :put, path, nil, opts, nil, res)
      end

      @http.put(path, data, opts)
    end
666116
def upload(self, release, filename, content_type=None):
        
        release = self.as_id(release)
        name = os.path.basename(filename)
        if not content_type:
            content_type, _ = mimetypes.guess_type(name)
        if not content_type:
            raise ValueError('content_type not known')
        inputs = {'name': name}
        url = '%s%s/%s/assets' % (self.uploads_url,
                                  urlsplit(self.api_url).path,
                                  release)
        info = os.stat(filename)
        size = info[stat.ST_SIZE]
        response = self.http.post(
            url, data=stream_upload(filename), auth=self.auth,
            params=inputs,
            headers={'content-type': content_type,
                     'content-length': str(size)})
        response.raise_for_status()
        return response.json()
728887
def import_doc(self, file_uris, docsearch, current_doc=None):
        
        if (current_doc is None or
                current_doc.is_new or
                not current_doc.can_edit):
            if not current_doc or not current_doc.can_edit:
                current_doc = ImgDoc(self.fs, docsearch.rootdir)
            new_docs = [current_doc]
            upd_docs = []
        else:
            new_docs = []
            upd_docs = [current_doc]
        new_docs_pages = []
        upd_docs_pages = []
        page = None

        file_uris = natsorted(file_uris)
        imported = []

        for file_uri in file_uris:
            file_uri = self.fs.safe(file_uri)
            logger.info("Importing images from '%s'" % (file_uri))

            for child in self.fs.recurse(file_uri):
                if ".thumb." in child:
                    # We are re-importing an old document --> ignore thumbnails
                    logger.info("{} ignored".format(child))
                    continue
                if not self.check_file_type(child):
                    continue
                imported.append(child)
                with self.fs.open(child, "rb") as fd:
                    img = Image.open(fd)
                    img.load()
                page = current_doc.add_page(img, [])
                if new_docs == []:
                    upd_docs_pages.append(page)
                else:
                    new_docs_pages.append(page)

        return ImportResult(
            imported_file_uris=imported,
            select_doc=current_doc, select_page=page,
            new_docs=new_docs, upd_docs=upd_docs,
            new_docs_pages=new_docs_pages,
            upd_docs_pages=upd_docs_pages,
            stats={
                _("Image file(s)"): len(file_uris),
                _("Document(s)"): 0 if new_docs == [] else 1,
                _("Page(s)"): len(new_docs_pages) + len(upd_docs_pages),
            }
        )
870380
def insert(collection_name, docs, check_keys,
           safe, last_error_args, continue_on_error, opts):
    """"""
    options = 0
    if continue_on_error:
        options += 1
    data = struct.pack("<i", options)
    data += bson._make_c_string(collection_name)
    encoded = [bson.BSON.encode(doc, check_keys, opts) for doc in docs]
    if not encoded:
        raise InvalidOperation("cannot do an empty bulk insert")
    max_bson_size = max(map(len, encoded))
    data += _EMPTY.join(encoded)
    if safe:
        (_, insert_message) = __pack_message(2002, data)
        (request_id, error_message, _) = __last_error(collection_name,
                                                      last_error_args)
        return (request_id, insert_message + error_message, max_bson_size)
    else:
        (request_id, insert_message) = __pack_message(2002, data)
        return (request_id, insert_message, max_bson_size)
1154855
def file_upload_to(self, instance, filename):
        
        ext = filename.split(".")[-1]
        filename = "{}.{}".format(uuid.uuid4(), ext)
        return os.path.join("document", filename)
1268582
def upload_masterfile(element_key, file, original_filename)
      # file, elementkey , name??
      content_length = file.size
      content_type = 'application/octet-stream; charset=utf-8'
      parameter = { basic_auth: @auth,
                    headers: { 'Content-Type' => content_type,
                               'Content-Length' => content_length.to_s,
                               'storageType' => 'MASTER',
                               'filename' => original_filename.to_s },
                    body: file.read }
      upload_file element_key, parameter
    end
584909
def UploadArtifactYamlFile(file_content,
                           overwrite=True,
                           overwrite_system_artifacts=False):
  """"""
  loaded_artifacts = []
  registry_obj = artifact_registry.REGISTRY
  # Make sure all artifacts are loaded so we don't accidentally overwrite one.
  registry_obj.GetArtifacts(reload_datastore_artifacts=True)

  new_artifacts = registry_obj.ArtifactsFromYaml(file_content)
  new_artifact_names = set()
  # A quick syntax check before we upload anything.
  for artifact_value in new_artifacts:
    artifact_registry.ValidateSyntax(artifact_value)
    new_artifact_names.add(artifact_value.name)

  # Iterate through each artifact adding it to the collection.
  artifact_coll = artifact_registry.ArtifactCollection(ARTIFACT_STORE_ROOT_URN)
  current_artifacts = list(artifact_coll)

  # We need to remove artifacts we are overwriting.
  filtered_artifacts = [
      art for art in current_artifacts if art.name not in new_artifact_names
  ]

  artifact_coll.Delete()
  with data_store.DB.GetMutationPool() as pool:
    for artifact_value in filtered_artifacts:
      artifact_coll.Add(artifact_value, mutation_pool=pool)

    for artifact_value in new_artifacts:
      registry_obj.RegisterArtifact(
          artifact_value,
          source="datastore:%s" % ARTIFACT_STORE_ROOT_URN,
          overwrite_if_exists=overwrite,
          overwrite_system_artifacts=overwrite_system_artifacts)

      artifact_coll.Add(artifact_value, mutation_pool=pool)
      if data_store.RelationalDBEnabled():
        data_store.REL_DB.WriteArtifact(artifact_value)

      loaded_artifacts.append(artifact_value)

      name = artifact_value.name
      logging.info("Uploaded artifact %s to %s", name, ARTIFACT_STORE_ROOT_URN)

  # Once all artifacts are loaded we can validate dependencies. Note that we do
  # not have to perform a syntax validation because it is already done after
  # YAML is parsed.
  for artifact_value in loaded_artifacts:
    artifact_registry.ValidateDependencies(artifact_value)
804732
function uploadFileList(files){

		// FileList
		if(!("FileList" in window) || (files instanceof File) || (files instanceof Blob)){
			// Make an Array
			files = [files];
		}


		var max = 20, len = files.length;
		if(len>max){
			var bool = confirm("You man only upload "+max+" files at a time");
			if(!bool){
				return;
			}
			len = max;
		}

		// Loop through the array and place the items on the page
		for(var i=0;i<len;i++){
			createRef(files[i]);
		}
	}
701061
def put_attachment(doc, name, file, options = {})
      file = StringIO.new(file) if file.is_a?(String)
      connection.put path_for_attachment(doc, name), file, options
    end
374241
def patch_file(actions, tree):
    """"""
    tree = etree.parse(tree)

    if isinstance(actions, six.string_types):
        # It's a string, so it's a filename
        with open(actions) as f:
            actions = f.read()
    else:
        # We assume it's a stream
        actions = actions.read()

    actions = patch.DiffParser().parse(actions)
    tree = patch_tree(actions, tree)
    return etree.tounicode(tree)
102380
def upload():
    """"""
    try:
        o = check_output(['twine', 'upload'] + glob('dist/*'))
    except CalledProcessError:
        call(['twine', 'upload'] + glob('dist/*'))
        raise
    print(o.decode('utf-8'))
198347
def upload(ctx):
    """"""
    settings.add_cli_options(ctx.cli_options, settings.TransferAction.Upload)
    ctx.initialize(settings.TransferAction.Upload)
    specs = settings.create_upload_specifications(
        ctx.cli_options, ctx.config)
    del ctx.cli_options
    for spec in specs:
        blobxfer.api.Uploader(
            ctx.general_options, ctx.credentials, spec
        ).start()
813965
def upload_file_mp(self, container, src_file_path, dst_name=None,
                       content_type=None):
        """"""
        if not os.path.exists(src_file_path):
            raise RuntimeError('file not found: ' + src_file_path)
        if not dst_name:
            dst_name = os.path.basename(src_file_path)
        if not content_type:
            content_type = "application/octet.stream"
        url = self.make_url(container, None, None)
        headers = self._base_headers
        with open(src_file_path, 'rb') as up_file:
            files = {'file': (dst_name, up_file, content_type)}
            try:
                rsp = requests.post(url, headers=headers, files=files,
                                    timeout=self._timeout)
            except requests.exceptions.ConnectionError as e:
                RestHttp._raise_conn_error(e)

        return self._handle_response(rsp)
217009
def bulk_upsert(self, docs, namespace, timestamp):
        
        if self.auto_commit_interval is not None:
            add_kwargs = {
                "commit": (self.auto_commit_interval == 0),
                "commitWithin": str(self.auto_commit_interval)
            }
        else:
            add_kwargs = {"commit": False}

        cleaned = (self._clean_doc(d, namespace, timestamp) for d in docs)
        if self.chunk_size > 0:
            batch = list(next(cleaned) for i in range(self.chunk_size))
            while batch:
                self.solr.add(batch, **add_kwargs)
                batch = list(next(cleaned)
                             for i in range(self.chunk_size))
        else:
            self.solr.add(cleaned, **add_kwargs)
818689
def add_fileobj(self, fname, fcontent):
        
        tar_info = tarfile.TarInfo(fname)
        if isinstance(fcontent, io.BytesIO):
            tar_info.size = len(fcontent.getvalue())
        elif isinstance(fcontent, io.StringIO):
            tar_info.size = len(fcontent.getvalue())
            fcontent = io.BytesIO(fcontent.getvalue().encode("utf8"))
        else:
            if hasattr(fcontent, "readable"):
                fcontent = fcontent
            tar_info.size = len(fcontent)
            if isinstance(fcontent, str):
                fcontent = fcontent.encode("utf8")
            fcontent = io.BytesIO(fcontent)
        self._ios_to_add[tar_info] = fcontent
690916
def attach_file(self, path, mimetype=None):
        """"""
        filename = os.path.basename(path)
        content = open(path, "rb").read()
        self.attach(filename, content, mimetype)