Create a new disk image in the specified format
500066
def as_new_format(self, format="ATR"):
        
        first_data = len(self.header)
        raw = self.rawdata[first_data:]
        data = add_atr_header(raw)
        newraw = SegmentData(data)
        image = self.__class__(newraw)
        return image
216595
def write_image(filename, image):
    
    data_format = get_data_format(filename)
    if data_format is MimeType.JPG:
        LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')
    return Image.fromarray(image).save(filename)
441996
def create_image_metadata(data):
    """"""

    # Default metadata
    meta = {'protected': data.get('protected', False),
            'disk_format': data.get('disk_format', 'raw'),
            'container_format': data.get('container_format', 'bare'),
            'min_disk': data.get('min_disk') or 0,
            'min_ram': data.get('min_ram') or 0,
            'name': data.get('name', '')}

    # Glance does not really do anything with container_format at the
    # moment. It requires it is set to the same disk_format for the three
    # Amazon image types, otherwise it just treats them as 'bare.' As such
    # we will just set that to be that here instead of bothering the user
    # with asking them for information we can already determine.
    if meta['disk_format'] in ('ami', 'aki', 'ari',):
        meta['container_format'] = meta['disk_format']
    elif meta['disk_format'] == 'docker':
        # To support docker containers we allow the user to specify
        # 'docker' as the format. In that case we really want to use
        # 'raw' as the disk format and 'docker' as the container format.
        meta['disk_format'] = 'raw'
        meta['container_format'] = 'docker'
    elif meta['disk_format'] == 'ova':
        # If the user wishes to upload an OVA using Horizon, then
        # 'ova' must be the container format and 'vmdk' must be the disk
        # format.
        meta['container_format'] = 'ova'
        meta['disk_format'] = 'vmdk'

    properties = {}

    for prop, key in [('description', 'description'),
                      ('kernel_id', 'kernel'),
                      ('ramdisk_id', 'ramdisk'),
                      ('architecture', 'architecture')]:
        if data.get(key):
            properties[prop] = data[key]

    _handle_unknown_properties(data, properties)

    if ('visibility' in data and
            data['visibility'] not in ['public', 'private', 'community',
                                       'shared']):
        raise KeyError('invalid visibility option: %s' % data['visibility'])
    _normalize_is_public_filter(data)

    if VERSIONS.active < 2:
        meta['properties'] = properties
        meta['is_public'] = data.get('is_public', False)
    else:
        meta['visibility'] = data.get('visibility', 'private')
        meta.update(properties)

    return meta
442365
def convert_image(from_file, to_file, image_format):
    """"""
    with Image(filename=from_file) as original:
        with original.convert(image_format) as converted:
            converted.save(filename=to_file)
    return to_file
780832
function createImage(svgHtml) {
        let img = new Image();

        img.src = `${config.imageSourceBase}${ b64EncodeUnicode(svgHtml) }`;

        return img;
    }
880159
def _generate_examples(self, archive):
    """"""
    prefix_len = len("SUN397")
    with tf.Graph().as_default():
      with utils.nogpu_session() as sess:
        for filepath, fobj in archive:
          if (filepath.endswith(".jpg") and
              filepath not in _SUN397_IGNORE_IMAGES):
            # Note: all files in the tar.gz are in SUN397/...
            filename = filepath[prefix_len:]
            # Example:
            # From filename: /c/car_interior/backseat/sun_aenygxwhhmjtisnf.jpg
            # To class: /c/car_interior/backseat
            label = "/".join(filename.split("/")[:-1])
            image = _process_image_file(fobj, sess, filepath)
            yield {
                "file_name": filename,
                "image": image,
                "label": label,
            }
1067828
def _create_file(self, filename):
        """"""
        file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
        return os.fdopen(file_descriptor, 'w')
827030
def create_thumbnail(img, width, height):
    
    size = (width, height)
    img.thumbnail(size)
    return img
26792
function(mode, targetHost, system, containerDef, container, out, newConfig, cb) {

    if (container.specific && container.specific.dockerContainerId && container.specific.configPath && container.specific.hup) {
      tmp.file(function(err, path) {
        if (err) { return cb(err); }

        fs.writeFile(path, newConfig, 'utf8', function(err) {
          if (err) { return cb(err); }

          var copyCmd = commands.generateCopyCommand(container.specific.dockerContainerId, container.specific.configPath, path);
          var hupCmd = commands.generateHupCommand(container);

          executor.exec(mode, copyCmd, config.imageCachePath, out, function(err) {
            if (err) { return cb(err); }
            executor.exec(mode, hupCmd, config.imageCachePath, out, function(err) {
              cb(err);
            });
          });
        });
      });
    }
    else { 
      cb();
    }
  }
77378
def create(self):
        
        if os.path.isfile(self.path):
            if not os.path.exists(self.path):
                with open(self.path, 'w') as fileobj:
                    fileobj.write('')
        else:
            os.makedirs(self.path)
474555
def __create_image(self, inpt, hashfun):
        """"""
        if hashfun not in generator.HASHES.keys():
            print ("Unknown or unsupported hash function. Using default: %s"
                   % self.DEFAULT_HASHFUN)
            algo = self.DEFAULT_HASHFUN
        else:
            algo = hashfun
        return generator.generate(inpt, algo)
316316
def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    cmdlist = [cmd, '--create']
    add_tar_opts(cmdlist, compression, verbosity)
    cmdlist.extend(["--file", archive, '--'])
    cmdlist.extend(filenames)
    return cmdlist
306412
def diskwarp(src_ds, res=None, extent=None, t_srs=None, r='cubic', outdir=None, dst_fn=None, dst_ndv=None, verbose=True):
    
    if dst_fn is None:
        dst_fn = os.path.splitext(src_ds.GetFileList()[0])[0]+'_warp.tif'
    if outdir is not None:
        dst_fn = os.path.join(outdir, os.path.basename(dst_fn))  
    driver = iolib.gtif_drv
    dst_ds = warp(src_ds, res, extent, t_srs, r, driver, dst_fn, dst_ndv=dst_ndv, verbose=verbose)
    #Write out
    dst_ds = None
    #Now reopen ds from disk
    dst_ds = gdal.Open(dst_fn)
    return dst_ds
789036
def create(self):
        """"""

        try:
            image_infos = yield from self._get_image_information()
        except DockerHttp404Error:
            log.info("Image %s is missing pulling it from docker hub", self._image)
            yield from self.pull_image(self._image)
            image_infos = yield from self._get_image_information()
            if image_infos is None:
                raise DockerError("Can't get image informations, please try again.")

        params = {
            "Hostname": self._name,
            "Name": self._name,
            "Image": self._image,
            "NetworkDisabled": True,
            "Tty": True,
            "OpenStdin": True,
            "StdinOnce": False,
            "HostConfig": {
                "CapAdd": ["ALL"],
                "Privileged": True,
                "Binds": self._mount_binds(image_infos)
            },
            "Volumes": {},
            "Env": ["container=docker"],  # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
            "Cmd": [],
            "Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
        }

        if params["Entrypoint"] is None:
            params["Entrypoint"] = []
        if self._start_command:
            params["Cmd"] = shlex.split(self._start_command)
        if len(params["Cmd"]) == 0:
            params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
            if params["Cmd"] is None:
                params["Cmd"] = []
        if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
            params["Cmd"] = ["/bin/sh"]
        params["Entrypoint"].insert(0, "/gns3/init.sh")  # FIXME /gns3/init.sh is not found?

        # Give the information to the container on how many interface should be inside
        params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
        # Give the information to the container the list of volume path mounted
        params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))

        if self._environment:
            for e in self._environment.strip().split("\n"):
                e = e.strip()
                if not e.startswith("GNS3_"):
                    params["Env"].append(e)

        if self._console_type == "vnc":
            yield from self._start_vnc()
            params["Env"].append("QT_GRAPHICSSYSTEM=native")  # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
            params["Env"].append("DISPLAY=:{}".format(self._display))
            params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")

        result = yield from self.manager.query("POST", "containers/create", data=params)
        self._cid = result['Id']
        log.info("Docker container '{name}' [{id}] created".format(
            name=self._name, id=self._id))
        return True
783714
def create_snapshot(self, volume, name, description=None, force=False):
        
        return self.api.create_snapshot(volume, name, description=description,
                force=force)
89382
function resizeImage(options, callback) {
  var size = options.size.width + 'x' + options.size.height;
  if (!options.size.maintainratio) {
    size += '\\!';
  }
  var command = [
    options.convert,
    options.org,
    '-adaptive-resize',
    options.size.width + 'x' + options.size.height,
    options.path
    ].join(' ');

  /* Create folder if we have to. */
  var dest = lib.path.join(options.dest, options.size.name);
  if (!lib.fs.existsSync(dest)) {
    lib.fs.mkdirSync(dest);
  }

  /* Create resize */
  lib.exec(command, function (err, stdout, stderr) {
    callback(err, options.path);
  });
}
1369430
def create(self):
        
        fdint = os.open(self.path, (os.O_EXCL |
                                    os.O_CREAT |
                                    os.O_RDWR))

        # XXX TODO: 'name' attribute of returned files is not mutable or
        # settable via fdopen, so this file is slighly less functional than the
        # one returned from 'open' by default.  send a patch to Python...

        return os.fdopen(fdint, 'w+b')