Upsert the ``file`` and ``media_type`` into the files table.
    Returns the ``fileid`` and ``sha1`` of the upserted file.
424816
def insert_file(file, media_type):
    
    resource_hash = get_file_sha1(file)
    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute("SELECT fileid FROM files WHERE sha1 = %s",
                           (resource_hash,))
            try:
                fileid = cursor.fetchone()[0]
            except (IndexError, TypeError):
                cursor.execute("INSERT INTO files (file, media_type) "
                               "VALUES (%s, %s)"
                               "RETURNING fileid",
                               (psycopg2.Binary(file.read()), media_type,))
                fileid = cursor.fetchone()[0]
    return fileid, resource_hash
562584
function convertFileType (data) {
  data['type'] = 'string'
  data['media'] = { 'binaryEncoding': 'binary' }
  if (data.fileTypes) {
    data['media']['anyOf'] = []
    data.fileTypes.forEach(function (el) {
      data['media']['anyOf'].push({ 'mediaType': el })
    })
    delete data.fileTypes
  }
  return data
}
304992
def upgradeUpload(self, file):
        """"""
        files = {'upfile': open(file, 'rb')}
        return self.__post_files('/upgrade/upload',
                                 files=files)
1272278
def update_media(media_uri, file_path, content_type)
      file_path = Pathname.new(file_path) unless file_path.is_a?(Pathname)
      stream = file_path.open { |f| f.binmode; f.read }
      update_resource(media_uri, stream, content_type)
    end
552404
def add_file(self, name="", hashalg="", hash="", comClasses=None, 
                 typelibs=None, comInterfaceProxyStubs=None, 
                 windowClasses=None):
        
        self.files.append(File(name, hashalg, hash, comClasses, 
                          typelibs, comInterfaceProxyStubs, windowClasses))
375086
def add(self, src):
        

        checksum = get_checksum(src)

        filename = self.get_filename(checksum)

        if not filename:

            new_name = self._get_new_name()
            new_realpath = self._storage_dir + '/' + new_name

            os.makedirs(os.path.split(new_realpath)[0], exist_ok=True)

            shutil.copyfile(src, new_realpath)

            self._log[new_name] = {
                'checksum': checksum,
                'mtime': os.path.getmtime(new_realpath),
                'size': os.path.getsize(new_realpath)
            }

            self.write_log()
        return checksum
1138028
def _save_artifact(build, data, content_type):
    """"""
    sha1sum = hashlib.sha1(data).hexdigest()
    artifact = models.Artifact.query.filter_by(id=sha1sum).first()

    if artifact:
      logging.debug('Upload already exists: artifact_id=%r', sha1sum)
    else:
      logging.info('Upload received: artifact_id=%r, content_type=%r',
                   sha1sum, content_type)
      artifact = models.Artifact(
          id=sha1sum,
          content_type=content_type,
          data=data)
      _artifact_created(artifact)

    artifact.owners.append(build)
    return artifact
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()
140669
def _get_asset(file_path):
    
    record = model.Image.get(file_path=file_path)
    fingerprint = ','.join((utils.file_fingerprint(file_path),
                            str(RENDITION_VERSION)))
    if not record or record.fingerprint != fingerprint:
        # Reindex the file
        logger.info("Updating image %s -> %s", file_path, fingerprint)

        # compute the md5sum; from https://stackoverflow.com/a/3431838/318857
        md5 = hashlib.md5()
        md5.update(bytes(RENDITION_VERSION))
        with open(file_path, 'rb') as file:
            for chunk in iter(lambda: file.read(16384), b""):
                md5.update(chunk)

        values = {
            'file_path': file_path,
            'checksum': md5.hexdigest(),
            'fingerprint': fingerprint,
        }

        try:
            image = PIL.Image.open(file_path)
            image = fix_orientation(image)
        except IOError:
            image = None

        if image:
            values['width'] = image.width
            values['height'] = image.height
            values['transparent'] = image.mode in ('RGBA', 'P')
            values['is_asset'] = False
        else:
            # PIL could not figure out what file type this is, so treat it as
            # an asset
            values['is_asset'] = True
            values['asset_name'] = os.path.join(values['checksum'][:5],
                                                os.path.basename(file_path))
        record = model.Image.get(file_path=file_path)
        if record:
            record.set(**values)
        else:
            record = model.Image(**values)
        orm.commit()

    return record
1052889
def put(self, local_path, destination_s3_path, **kwargs):
        
        self._check_deprecated_argument(**kwargs)

        # put the file
        self.put_multipart(local_path, destination_s3_path, **kwargs)
804552
def upsert_link_set(self, link_type, link_set):
        
        if link_set is None:
            self.links.pop(link_type, None)
            return
        links = copy.deepcopy(self.links)
        links.update({link_type: link_set})
        self.links = links
1180223
def upsert_module_file(module_ident, fileid, filename):
    
    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute("SELECT true FROM module_files "
                           "WHERE module_ident = %s "
                           "AND filename = %s",
                           (module_ident, filename,))
            try:
                cursor.fetchone()[0]
            except (IndexError, TypeError):
                cursor.execute("INSERT INTO module_files "
                               "(module_ident, fileid, filename) "
                               "VALUES (%s, %s, %s)",
                               (module_ident, fileid, filename,))
            else:
                cursor.execute("UPDATE module_files "
                               "SET (fileid) = (%s) "
                               "WHERE module_ident = %s AND filename = %s",
                               (fileid, module_ident, filename,))
943401
def put(self):
        
        self.fp = self.get_body_argument('filepath')
        self.action = self.get_body_argument('action')

        try:
            ptype = self.fs.get_type_from_path(self.fp)
        except OSError:
            raise tornado.web.HTTPError(404)
        if ptype == 'directory':
            self.handler_name = 'filesystem:directories-details'
        else:
            self.handler_name = 'filesystem:files-details'

        if self.action['action'] == 'move':
            newpath = self._move()
            self.write({'filepath':newpath})
        elif self.action['action'] == 'copy':
            newpath = self._copy()
            self.write({'filepath':newpath})
        elif self.action['action'] == 'rename':
            newpath = self._rename()
            self.write({'filepath':newpath})
        else:
            raise tornado.web.HTTPError(400)
414642
def upload_permanent_media(self, media_type, media_file):
        
        return self.post(
            url="https://api.weixin.qq.com/cgi-bin/material/add_material",
            params={
                "access_token": self.token,
                "type": media_type
            },
            files={"media": media_file}
        )
1146381
def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool:
        
        service = self.__get_service()
        media_body = MediaFileUpload(file_name, mimetype=mine_type, resumable=True)
        body = {
            'name': os.path.split(file_name)[-1],
            'mimeType': "text/csv",
            'parents': [folder_id],
        }
        return service.files().create(body=body, media_body=media_body).execute()
71118
def sha1_of_file(filepath):
    
    import hashlib
    try:
        with open(filepath, 'rb') as file_to_hash:
            return hashlib.sha1(file_to_hash.read()).hexdigest()
    except:  # pylint: disable=bare-except
        return None
162287
def add(self, src):
        
        if not audio.get_type(src):
            raise TypeError('The type of this file is not supported.')

        return super().add(src)