Uploads a notebook
        :param force: True/False
        :returns {}
497924
def upload(self, force=False):
        
        self.package and self.release
        try:
            return self.aserver_api.upload(self.username, self.project, self.version,
                                       basename(self.filepath), open(self.filepath, 'rb'),
                                       self.filepath.split('.')[-1])
        except errors.Conflict:
            if force:
                self.remove()
                return self.upload()
            else:
                msg = "Conflict: {} already exist in {}/{}".format(self.filepath,
                                                                   self.project,
                                                                   self.version)
                raise errors.BinstarError(msg)
56604
def ajax_upload(request, folder_id=None):
    
    folder = None
    if folder_id:
        try:
            # Get folder
            folder = Folder.objects.get(pk=folder_id)
        except Folder.DoesNotExist:
            return JsonResponse({'error': NO_FOLDER_ERROR})

    # check permissions
    if folder and not folder.has_add_children_permission(request):
        return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
    try:
        if len(request.FILES) == 1:
            # dont check if request is ajax or not, just grab the file
            upload, filename, is_raw = handle_request_files_upload(request)
        else:
            # else process the request as usual
            upload, filename, is_raw = handle_upload(request)
        # TODO: Deprecated/refactor
        # Get clipboad
        # clipboard = Clipboard.objects.get_or_create(user=request.user)[0]

        # find the file type
        for filer_class in filer_settings.FILER_FILE_MODELS:
            FileSubClass = load_model(filer_class)
            # TODO: What if there are more than one that qualify?
            if FileSubClass.matches_file_type(filename, upload, request):
                FileForm = modelform_factory(
                    model=FileSubClass,
                    fields=('original_filename', 'owner', 'file')
                )
                break
        uploadform = FileForm({'original_filename': filename,
                               'owner': request.user.pk},
                              {'file': upload})
        if uploadform.is_valid():
            file_obj = uploadform.save(commit=False)
            # Enforce the FILER_IS_PUBLIC_DEFAULT
            file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
            file_obj.folder = folder
            file_obj.save()
            # TODO: Deprecated/refactor
            # clipboard_item = ClipboardItem(
            #     clipboard=clipboard, file=file_obj)
            # clipboard_item.save()

            # Try to generate thumbnails.
            if not file_obj.icons:
                # There is no point to continue, as we can't generate
                # thumbnails for this file. Usual reasons: bad format or
                # filename.
                file_obj.delete()
                # This would be logged in BaseImage._generate_thumbnails()
                # if FILER_ENABLE_LOGGING is on.
                return JsonResponse(
                    {'error': 'failed to generate icons for file'},
                    status=500,
                )
            thumbnail = None
            # Backwards compatibility: try to get specific icon size (32px)
            # first. Then try medium icon size (they are already sorted),
            # fallback to the first (smallest) configured icon.
            for size in (['32']
                        + filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
                try:
                    thumbnail = file_obj.icons[size]
                    break
                except KeyError:
                    continue

            data = {
                'thumbnail': thumbnail,
                'alt_text': '',
                'label': str(file_obj),
                'file_id': file_obj.pk,
            }
            # prepare preview thumbnail
            if type(file_obj) == Image:
                thumbnail_180_options = {
                    'size': (180, 180),
                    'crop': True,
                    'upscale': True,
                }
                thumbnail_180 = file_obj.file.get_thumbnail(
                    thumbnail_180_options)
                data['thumbnail_180'] = thumbnail_180.url
                data['original_image'] = file_obj.url
            return JsonResponse(data)
        else:
            form_errors = '; '.join(['%s: %s' % (
                field,
                ', '.join(errors)) for field, errors in list(
                    uploadform.errors.items())
            ])
            raise UploadException(
                "AJAX request not valid: form invalid '%s'" % (
                    form_errors,))
    except UploadException as e:
        return JsonResponse({'error': str(e)}, status=500)
826973
def save_notebook(self):
        
        try:
            from IPython.display import display, Javascript
        except ImportError:
            log.warning("Could not import IPython Display Function")
            print("Make sure to save your notebook before sending it to OK!")
            return

        if self.mode == "jupyter":
            display(Javascript('IPython.notebook.save_checkpoint();'))
            display(Javascript('IPython.notebook.save_notebook();'))
        elif self.mode == "jupyterlab":
            display(Javascript('document.querySelector(\'[data-command="docmanager:save"]\').click();'))   
                       
        print('Saving notebook...', end=' ')

        ipynbs = [path for path in self.assignment.src
                  if os.path.splitext(path)[1] == '.ipynb']
        # Wait for first .ipynb to save
        if ipynbs:
            if wait_for_save(ipynbs[0]):
                print("Saved '{}'.".format(ipynbs[0]))
            else:
                log.warning("Timed out waiting for IPython save")
                print("Could not automatically save \'{}\'".format(ipynbs[0]))
                print("Make sure your notebook"
                      " is correctly named and saved before submitting to OK!".format(ipynbs[0]))
                return False                
        else:
            print("No valid file sources found")
        return True
1200795
def _upload_media(self,directory,files=None,resize_request=None, \
            movealbum_request=None,changetitle_request=None):
        """"""
        # Connect if we aren't already
        if not self._connectToFB():
            logger.error("%s - Couldn't connect to fb")
            return False

        _megapixels=self._load_megapixels(directory)

        # Get an album ID (create album if not exists)
        _album_id,_album_name=self._get_album(directory)

        if not _megapixels:
            mpstring="original"
        else:
            mpstring=("%0.1f MP"%(_megapixels))

        # If no files given, use files from DB in dir
        if not files:
            db=self._loadDB(directory)
            files=db.keys()

        #If only one file given, make it a list
        if isinstance(files,basestring):
            files=[files]

        files.sort()

        for filename in files:

            # Get title here if any
            title=self._get_title(directory,filename)

            if title:
                print("%s - Uploading to fb, album[%s] size=%s title=%s"\
                        %(filename,_album_name,mpstring,title))
            else:
                print("%s - Uploading to fb, album[%s] size=%s"\
                        %(filename,_album_name,mpstring))

            status=self._upload_or_replace_fb(directory,filename, \
                    _album_id, _megapixels,resize_request,movealbum_request,\
                    changetitle_request,title)
            if not status:
                return False

        return True
964996
def create(self, **kwargs):
        
        obj = self.resource(**kwargs)
        obj.save(force_insert=True)
        return obj
490073
def create_notebook(self, model=None, path=''):
        """"""
        path = path.strip('/')
        if model is None:
            model = {}
        if 'content' not in model:
            metadata = current.new_metadata(name=u'')
            model['content'] = current.new_notebook(metadata=metadata)
        if 'name' not in model:
            model['name'] = self.increment_filename('Untitled', path)

        model['path'] = path
        model['type'] = 'notebook'
        model = self.save_notebook(model, model['name'], model['path'])

        return model
997933
def upload(cookie, source_path, path, upload_mode):
    '''
    '''
    ondup = const.UPLOAD_ONDUP[upload_mode]
    dir_name, file_name = os.path.split(path)
    url = ''.join([
        const.PCS_URL_C,
        'file?method=upload&app_id=250528',
        '&ondup=', ondup,
        '&dir=', encoder.encode_uri_component(dir_name),
        '&filename=', encoder.encode_uri_component(file_name),
        '&', cookie.sub_output('BDUSS'),
    ])
    with open(source_path, 'rb') as fh:
        data = fh.read()
    fields = []
    files = [('file', file_name, data)]
    headers = {'Accept': const.ACCEPT_HTML, 'Origin': const.PAN_URL}
    req = net.post_multipart(url, headers, fields, files)
    if req:
        return json.loads(req.data.decode())
    else:
        return None
1181627
function (files) {
      UI.widgets.uploadFiles(kb.fetcher, files, subject.uri, subject.uri, function (file, uri) {
        // A file has been uploaded
        let destination = kb.sym(uri)
        console.log(' Upload: put OK: ' + destination)
        kb.add(subject, ns.ldp('contains'), destination, subject.doc())
        mainTable.refresh()
      })
    }
1267564
def upload_from_fileobject(f, profile=None, label=None):
    
    if profile is None:
        profile = 'default'
    conf = get_profile_configs(profile)
    f.seek(0)
    if not is_image(f, types=conf['TYPES']):
        msg = (('Format of uploaded file is not allowed. '
                'Allowed formats is: %(formats)s.') %
               {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))})
        raise RuntimeError(msg)
    return _custom_upload(f, profile, label, conf)
1290903
def upload_attachments!(path, data)
      raise_exceptions = !!data.delete(:attachments_exception)
      attachments = [data.delete(:attachments)].flatten.compact
      return if attachments.empty?

      # retrieve the upload configuration for this record from ITRP
      storage = @client.get(path =~ /\d+$/ ? path : "#{path}/new", {attachment_upload_token: true}, @client.send(:expand_header))[:storage_upload]
      report_error("Attachments not allowed for #{path}", raise_exceptions) and return unless storage

      # upload each attachment and store the {key, filesize} has in the note_attachments parameter
      data[attachments_field(path)] = attachments.map {|attachment| upload_attachment(storage, attachment, raise_exceptions) }.compact.to_json
    end
560499
def upload_file(self, session, output, serverdir):
        
        name = output.metadata['filename']
        self.log.debug("uploading %r to %r as %r",
                       output.file.name, serverdir, name)

        kwargs = {}
        if self.blocksize is not None:
            kwargs['blocksize'] = self.blocksize
            self.log.debug("using blocksize %d", self.blocksize)

        upload_logger = KojiUploadLogger(self.log)
        session.uploadWrapper(output.file.name, serverdir, name=name,
                              callback=upload_logger.callback, **kwargs)
        path = os.path.join(serverdir, name)
        self.log.debug("uploaded %r", path)
        return path
470521
def upload_from_fs(fn, profile=None, label=None):
    
    if not os.path.isfile(fn):
        raise ValueError('File is not exists: {}'.format(fn))
    if profile is None:
        profile = 'default'
    conf = get_profile_configs(profile)
    with open(fn, 'rb') as f:
        if not is_image(f, types=conf['TYPES']):
            msg = (('Format of uploaded file "%(name)s" is not allowed. '
                    'Allowed formats is: %(formats)s.') %
                   {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))})
            raise RuntimeError(msg)
        return _custom_upload(f, profile, label, conf)
1159960
def upload(self, file_descriptor, settings):
        
        multipart_form_data = {
            'file': file_descriptor
        }
        params = {"settings": json.dumps(settings)}
        dr = self.__app.native_api_call('media', 'upload', params, self.__options, True, multipart_form_data, False, http_path="/api/meta/v1/", http_method='POST',
                                        connect_timeout_sec=60 * 10)
        return json.loads(dr.text)
723947
def upload_create(self, data, filename=None, token=None, **kwargs):
        ""
        api_path = "/api/v2/uploads.json"
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if filename:
            api_query.update({
                "filename": filename,
            })
        if token:
            api_query.update({
                "token": token,
            })
        return self.call(api_path, query=api_query, method="POST", data=data, **kwargs)
147121
def upload(self, href, vobject_item):
        """"""
        if self.is_fake:
            return

        content = vobject_item.serialize()
        try:
            item = self.get(href)
            etesync_item = item.etesync_item
            etesync_item.content = content
        except api.exceptions.DoesNotExist:
            etesync_item = self.collection.get_content_class().create(self.collection, content)

        etesync_item.save()

        return self.get(href)
915028
def upload_file(request):
    ''''''
    if request.method == 'POST':
        form = MediaForm(request.POST, request.FILES)
        if form.is_valid():
            context_dict = {}
            try:
                context_dict['copied_files'] = update_media_file(
                    request.FILES['zip_file'])
            except Exception as e:
                context_dict['error_message'] = e.message
            return render(request,
                          'django_admin/transfer_media_message.html',
                          context_dict)
    else:
        form = MediaForm()
    return render(request, 'django_admin/upload_media.html', {'form': form})
450047
def trust_notebook(self, path):
        """"""
        if path.endswith('.ipynb') or path not in self.paired_notebooks:
            super(TextFileContentsManager, self).trust_notebook(path)
            return

        fmt, formats = self.paired_notebooks[path]
        for alt_path, alt_fmt in paired_paths(path, fmt, formats):
            if alt_fmt['extension'] == '.ipynb':
                super(TextFileContentsManager, self).trust_notebook(alt_path)