Search the qemu-img binary in the same binary of the qemu binary
        for avoiding version incompatibily.

        :returns: qemu-img path or raise an error
2218
def _get_qemu_img(self):
        
        qemu_img_path = ""
        qemu_path_dir = os.path.dirname(self.qemu_path)
        try:
            for f in os.listdir(qemu_path_dir):
                if f.startswith("qemu-img"):
                    qemu_img_path = os.path.join(qemu_path_dir, f)
        except OSError as e:
            raise QemuError("Error while looking for qemu-img in {}: {}".format(qemu_path_dir, e))

        if not qemu_img_path:
            raise QemuError("Could not find qemu-img in {}".format(qemu_path_dir))

        return qemu_img_path
993742
def get_image_path(definition):
    
    path = resources_path(
        'img', 'wizard', 'keyword-subcategory-%s.svg' % definition['key'])
    if os.path.exists(path):
        return path
    else:
        return not_set_image_path
396384
def get_relative_image_path(self, path):
        

        if not path:
            return ""
        path = force_unix_path(self.get_abs_image_path(path))

        img_directory = self.get_images_directory()

        for directory in images_directories(self._NODE_TYPE):
            if os.path.commonprefix([directory, path]) == directory:
                relpath = os.path.relpath(path, directory)
                # We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases)
                if os.sep not in relpath or directory == img_directory:
                    return relpath
        return path
134079
def _qemu_image_create(disk, create_overlay=False, saltenv='base'):
    '''
    
    '''
    disk_size = disk.get('size', None)
    disk_image = disk.get('image', None)

    if not disk_size and not disk_image:
        raise CommandExecutionError(
            'Unable to create new disk {0}, please specify'
            ' disk size and/or disk image argument'
            .format(disk['filename'])
        )

    img_dest = disk['source_file']
    log.debug('Image destination will be %s', img_dest)
    img_dir = os.path.dirname(img_dest)
    log.debug('Image destination directory is %s', img_dir)
    if not os.path.exists(img_dir):
        os.makedirs(img_dir)

    if disk_image:
        log.debug('Create disk from specified image %s', disk_image)
        sfn = __salt__['cp.cache_file'](disk_image, saltenv)

        qcow2 = False
        if salt.utils.path.which('qemu-img'):
            res = __salt__['cmd.run']('qemu-img info {}'.format(sfn))
            imageinfo = salt.utils.yaml.safe_load(res)
            qcow2 = imageinfo['file format'] == 'qcow2'
        try:
            if create_overlay and qcow2:
                log.info('Cloning qcow2 image %s using copy on write', sfn)
                __salt__['cmd.run'](
                    'qemu-img create -f qcow2 -o backing_file={0} {1}'
                    .format(sfn, img_dest).split())
            else:
                log.debug('Copying %s to %s', sfn, img_dest)
                salt.utils.files.copyfile(sfn, img_dest)

            mask = salt.utils.files.get_umask()

            if disk_size and qcow2:
                log.debug('Resize qcow2 image to %sM', disk_size)
                __salt__['cmd.run'](
                    'qemu-img resize {0} {1}M'
                    .format(img_dest, disk_size)
                )

            log.debug('Apply umask and remove exec bit')
            mode = (0o0777 ^ mask) & 0o0666
            os.chmod(img_dest, mode)

        except (IOError, OSError) as err:
            raise CommandExecutionError(
                'Problem while copying image. {0} - {1}'
                .format(disk_image, err)
            )

    else:
        # Create empty disk
        try:
            mask = salt.utils.files.get_umask()

            if disk_size:
                log.debug('Create empty image with size %sM', disk_size)
                __salt__['cmd.run'](
                    'qemu-img create -f {0} {1} {2}M'
                    .format(disk.get('format', 'qcow2'), img_dest, disk_size)
                )
            else:
                raise CommandExecutionError(
                    'Unable to create new disk {0},'
                    ' please specify <size> argument'
                    .format(img_dest)
                )

            log.debug('Apply umask and remove exec bit')
            mode = (0o0777 ^ mask) & 0o0666
            os.chmod(img_dest, mode)

        except (IOError, OSError) as err:
            raise CommandExecutionError(
                'Problem while creating volume {0} - {1}'
                .format(img_dest, err)
            )

    return img_dest
1018254
def get_bin_and_lib(self, x64=False, native=False):
        
        if x64:
            msvc = self.bin64
            paths = self.lib64
        else:
            msvc = self.bin32
            paths = self.lib
        if native:
            arch = 'x64' if x64 else 'x86'
            paths += self.sdk.get_lib(arch, native=True)
        else:
            attr = 'lib64' if x64 else 'lib'
            paths += getattr(self.sdk, attr)
        return msvc, paths
639047
def which_bin(exes):
    '''
    
    '''
    def wrapper(function):
        def wrapped(*args, **kwargs):
            if salt.utils.path.which_bin(exes) is None:
                raise CommandNotFoundError(
                    'None of provided binaries({0}) was not found '
                    'in $PATH.'.format(
                        ['\'{0}\''.format(exe) for exe in exes]
                    )
                )
            return function(*args, **kwargs)
        return identical_signature_wrapper(function, wrapped)
    return wrapper
308851
def render_image_iterm2
      return nil unless valid?

      # References:
      # https://iterm2.com/documentation-images.html
      # https://iterm2.com/utilities/imgcat

      # tmux requires some extra work for unrecognised escape code sequences
      screen = ENV['TERM'].start_with? 'screen'
      prefix = screen ? "\ePtmux;\e\e]" : "\e]"
      suffix = screen ? "\a\e\\" : "\a"

      png = qrcode.as_png(size: 600)
      png_base64 = Base64.encode64(png.to_s).chomp
      options = 'inline=1'
      "#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
    end
1016395
def _linux_bin_exists(binary):
    '''
    
    '''
    for search_cmd in ('which', 'type -ap'):
        try:
            return __salt__['cmd.retcode'](
                '{0} {1}'.format(search_cmd, binary)
            ) == 0
        except salt.exceptions.CommandExecutionError:
            pass

    try:
        return len(__salt__['cmd.run_all'](
            'whereis -b {0}'.format(binary)
        )['stdout'].split()) > 1
    except salt.exceptions.CommandExecutionError:
        return False
1261027
def get_image(conn, vm_):
    '''
    
    '''
    images = conn.list_images()
    vm_image = config.get_cloud_config_value('image', vm_, __opts__)

    if not six.PY3:
        vm_image = vm_image.encode('ascii', 'salt-cloud-force-ascii')

    for img in images:
        if isinstance(img.id, six.string_types) and not six.PY3:
            img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_id = str(img.id)  # future lint: disable=blacklisted-function

        if isinstance(img.name, six.string_types) and not six.PY3:
            img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_name = str(img.name)  # future lint: disable=blacklisted-function

        if vm_image and vm_image in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image)
    )
1065205
def import_image(image_path, os_version):
    
    image_name = os.path.basename(image_path)
    print("\nChecking if image %s exists ..." % image_name)

    image_query_info = client.send_request('image_query', imagename = image_name)
    if image_query_info['overallRC']:
        print("Importing image %s ..." % image_name)
        url = "file://" + image_path
        image_import_info = client.send_request('image_import', image_name, url, 
                                                {'os_version': os_version})
        if image_import_info['overallRC']:
            raise RuntimeError("Failed to import image %s!\n%s" % 
                               (image_name, image_import_info))
        else:
            print("Succeeded to import image %s!" % image_name)
    else:
        print("Image %s already exists!" % image_name)
404502
def check_image_duplicates(file_list):
    
    master_hash = ''
    ham_dist = 0
    results = []
    print(" " )
    for ndx, fname in enumerate(file_list):
        #img = Image.open(fname)
        img = load_image(fname)
        hsh = get_img_hash(img)
        if ndx == 0:  # this is the test MASTER image
            master_hash = hsh
        else:
            # compare hamming distance against image 1  
            #print("hash=" + hash + "  MASTER_HASH=" + master_hash)
            ham_dist = hamming_distance(hsh, master_hash)
        #print(hsh + " <- " + fname + " ,  hamming dist to img1 = " + str(ham_dist))
        #results.append(hsh + " <- " + fname + " ,  hamming dist to img1 = " + str(ham_dist))
        results.append({'hsh':hsh, 'fname':fname, 'dist_to_img1':str(ham_dist)})
    return results
1105262
def import_image(image_path, os_version):
    
    image_name = os.path.basename(image_path)
    print("Checking if image %s exists or not, import it if not exists" %
          image_name)
    image_info = sdk_client.send_request('image_query', imagename=image_name)
    if 'overallRC' in image_info and image_info['overallRC']:
        print("Importing image %s ..." % image_name)
        url = 'file://' + image_path
        ret = sdk_client.send_request('image_import', image_name, url,
                                {'os_version': os_version})
    else:
        print("Image %s already exists" % image_name)
284719
def update_image(hdu_in, hdu=None):
    
    if hdu is None:
        hdu = fits.ImageHDU(
            data=hdu_in.data, header=hdu_in.header, name=hdu_in.name)
    else:
        hdu.data += hdu_in.data
    return hdu
504399
def version():
    '''
    
    '''
    ret = {}
    cmd = 'imgadm --version'
    res = __salt__['cmd.run'](cmd).splitlines()
    ret = res[0].split()
    return ret[-1]
910417
def redo(self):
        """"""
        image = self.channel.get_current_image()
        if image is None:
            return True

        path = image.get('path', None)
        if path is None:
            self.fv.show_error(
                "Cannot open image: no value for metadata key 'path'")
            return

        # TODO: How to properly reset GUI components?
        #       They are still showing info from prev FITS.
        # No-op for ASDF
        if path.endswith('asdf'):
            return True

        if path != self.img_path:
            # <-- New file is being looked at
            self.img_path = path

            # close previous file opener, if any
            if self.file_obj is not None:
                try:
                    self.file_obj.close()
                except Exception:
                    pass

            self.file_obj = io_fits.get_fitsloader(logger=self.logger)

            # TODO: specify 'readonly' somehow?
            self.file_obj.open_file(path)

            upper = len(self.file_obj) - 1
            self.prep_hdu_menu(self.w.hdu, self.file_obj.hdu_info)
            self.num_hdu = upper
            self.logger.debug("there are %d hdus" % (upper + 1))
            self.w.numhdu.set_text("%d" % (upper + 1))

            self.w.hdu.set_enabled(len(self.file_obj) > 0)

        name = image.get('name', iohelper.name_image_from_path(path))
        idx = image.get('idx', None)
        # remove index designation from root of name, if any
        match = re.match(r'^(.+)\[(.+)\]$', name)
        if match:
            name = match.group(1)
        self.name_pfx = name

        htype = None
        if idx is not None:
            # set the HDU in the drop down if known
            info = self.file_obj.hdu_db.get(idx, None)
            if info is not None:
                htype = info.htype.lower()
                toc_ent = self._toc_fmt % info
                self.w.hdu.show_text(toc_ent)

        # rebuild the NAXIS controls, if necessary
        # No two images in the same channel can have the same name.
        # Here we keep track of the name to decide if we need to rebuild
        if self.img_name != name:
            self.img_name = name
            dims = [0, 0]
            data = image.get_data()
            if data is None:
                # <- empty data part to this HDU
                self.logger.warning("Empty data part in HDU %s" % (str(idx)))

            elif htype in ('bintablehdu', 'tablehdu',):
                pass

            elif htype not in ('imagehdu', 'primaryhdu', 'compimagehdu'):
                self.logger.warning("HDU %s is not an image (%s)" % (
                    str(idx), htype))

            else:
                mddata = image.get_mddata()
                if mddata is not None:
                    dims = list(mddata.shape)
                    dims.reverse()

            self.build_naxis(dims, image)
104585
def image(version = nil)
      image = provide_attr(:image)

      return image.file.url(version) if image.respond_to?(:file)
      return image if image.present?

      fallback_image
    end
438596
def _is_good_file_for_multiqc(fpath):
    """"""
    # Use mimetypes to exclude binary files where possible
    (ftype, encoding) = mimetypes.guess_type(fpath)
    if encoding is not None:
        return False
    if ftype is not None and ftype.startswith('image'):
        return False
    return True