Returns a function that attaches an image to page if it exists

    Currenlty assumes that images have already been imported and info
    has been stored in record_keeper
19075
def attach_image(field, nested_fields, page, record_keeper=None):
    '''
    
    '''
    if (field in nested_fields) and nested_fields[field]:
        foreign_image_id = nested_fields[field]["id"]
        # Handle the following
        # record keeper may not exist
        # record keeper may not have image ref
        if record_keeper:
            try:
                local_image_id = record_keeper.get_local_image(
                    foreign_image_id)
                local_image = Image.objects.get(id=local_image_id)
                setattr(page, field, local_image)
            except ObjectDoesNotExist:
                raise ObjectDoesNotExist(
                    ("executing attach_image: local image referenced"
                     "in record_keeper does not actually exist."),
                    None)
            except Exception:
                raise
        else:
            raise Exception(
                ("Attempted to attach image without record_keeper. "
                 "This functionality is not yet implemented"))
599536
def image(self, image, name):
        
        assert len(name.split(" ")) < 2, "Ensure that you don't have spaces in your variable name, use '_' instead."
        name = "image_" + name
        self.previous.append(name)
        if self.previous[-1] not in self.previous[:-1]:
            self.c.execute("""INSERT INTO {time_stamp_table} (
                              variable_name, variable_type
                              ) VALUES ('{variable}', '{type}')"""
                           .format(time_stamp_table=self.time_stamp, variable=name, type="image"))
        else:
            self.previous.pop()

        self.c.execute("""CREATE TABLE IF NOT EXISTS {variable_table_name} (
                          images BLOB, time VARCHAR
                          )""".format(variable_table_name=self.time_stamp + '_' + name))

        self.c.execute("""INSERT INTO {variable_table_name} (
                          images, time) VALUES ('{img}', '{time}'
                          )""".format(variable_table_name=self.time_stamp + '_' + name,
                                      img=sqlite3.Binary(np.array(image).tobytes()), time=datetime.datetime.now()))
        self.conn.commit()
634734
def save(self, delete_zip_import=True, *args, **kwargs):
        
        super(BaseGallery, self).save(*args, **kwargs)
        if self.zip_import:
            zip_file = ZipFile(self.zip_import)
            for name in zip_file.namelist():
                data = zip_file.read(name)
                try:
                    from PIL import Image
                    image = Image.open(BytesIO(data))
                    image.load()
                    image = Image.open(BytesIO(data))
                    image.verify()
                except ImportError:
                    pass
                except:
                    continue
                name = os.path.split(name)[1]

                # In python3, name is a string. Convert it to bytes.
                if not isinstance(name, bytes):
                    try:
                        name = name.encode('cp437')
                    except UnicodeEncodeError:
                        # File name includes characters that aren't in cp437,
                        # which isn't supported by most zip tooling. They will
                        # not appear correctly.
                        tempname = name

                # Decode byte-name.
                if isinstance(name, bytes):
                    encoding = charsetdetect(name)['encoding']
                    tempname = name.decode(encoding)

                # A gallery with a slug of "/" tries to extract files
                # to / on disk; see os.path.join docs.
                slug = self.slug if self.slug != "/" else ""
                path = os.path.join(GALLERIES_UPLOAD_DIR, slug, tempname)
                try:
                    saved_path = default_storage.save(path, ContentFile(data))
                except UnicodeEncodeError:
                    from warnings import warn
                    warn("A file was saved that contains unicode "
                         "characters in its path, but somehow the current "
                         "locale does not support utf-8. You may need to set "
                         "'LC_ALL' to a correct value, eg: 'en_US.UTF-8'.")
                    # The native() call is needed here around str because
                    # os.path.join() in Python 2.x (in posixpath.py)
                    # mixes byte-strings with unicode strings without
                    # explicit conversion, which raises a TypeError as it
                    # would on Python 3.
                    path = os.path.join(GALLERIES_UPLOAD_DIR, slug,
                                        native(str(name, errors="ignore")))
                    saved_path = default_storage.save(path, ContentFile(data))
                self.images.create(file=saved_path)
            if delete_zip_import:
                zip_file.close()
                self.zip_import.delete(save=True)
399039
def _set_timestamps_on_attach(self, record, exists=False):
        
        fresh = self._parent.fresh_timestamp()

        if not exists and self._has_pivot_column(self.created_at()):
            record[self.created_at()] = fresh

        if self._has_pivot_column(self.updated_at()):
            record[self.updated_at()] = fresh

        return record
50005
def image(name,locator)

        # generates method for checking the existence of the image.
        # this will return true or false based on if image is available or not
        # @example check if 'logo' image is displayed on the page
        # text(:logo,"xpath~//UITextField")
        # DSL for clicking the logo image.
        # def click_logo
        #  logo # This will click on the logo text on the screen.
        # end
        define_method("#{name}?") do
          ScreenObject::AppElements::Image.new(locator).exists?
        end

        #generates method for clicking image
        # this will not return any value.
        # @example clicking on logo image.
        # text(:logo,"xpath~//UITextField")
        # DSL for clicking the logo image.
        # def click_logo
        #  logo # This will click on the logo text on the screen.
        # end
        define_method("#{name}") do
          ScreenObject::AppElements::Image.new(locator).click
        end
      end
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)
625517
def setRecord( self, record ):
        
        super(XBasicCardWidget, self).setRecord(record)
        
        browser = self.browserWidget()
        if ( not browser ):
            return
        
        factory = browser.factory()
        if ( not factory ):
            return
        
        self._thumbnailButton.setIcon(factory.thumbnail(record))
        self._titleLabel.setText(factory.thumbnailText(record))
449866
def _attacher(self, key, value, attributes, timed):
        
        id, extra = self._get_attach_id(key, value, attributes)

        record = self._create_attach_record(id, timed)

        if extra:
            record.update(extra)

        return record
1319360
def locate(self, image):
        
        from .entity import Image
        if not isinstance(image, Image):
            raise TypeError('image must be a sqlalchemy_imageattach.entity.'
                            'Image instance, not ' + repr(image))
        url = self.get_url(image.object_type, image.object_id,
                           image.width, image.height, image.mimetype)
        if '?' in url:
            fmt = '{0}&_ts={1}'
        else:
            fmt = '{0}?_ts={1}'
        return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f'))
852363
function(callback) {
      if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback();

      var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png');
      gm(width, height, '#00000000').write(transparentImagePath, function(error) {

        // Add as many as needed transparent images to the list of images
        var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length;

        for (var i = 0; i < totalMissingImages; i++)
          imagesPaths.push(transparentImagePath);

        callback(error);
      });
    }
447152
def image_exists(self, image_name, tag='latest'):
        
        code, image = self.image_tags(image_name)
        if code != httplib.OK:
            return False
        tag = tag.lower()
        return any(x.lower() == tag for x in image.tags)
196661
def edit(self, image_id, name=None, note=None, tag=None):
        
        obj = {}
        if name:
            obj['name'] = name
        if note:
            obj['note'] = note
        if obj:
            self.vgbdtg.editObject(obj, id=image_id)
        if tag:
            self.vgbdtg.setTags(str(tag), id=image_id)

        return bool(name or note or tag)
1100799
def importdb(indir):
    """"""
    ecode = 0
    try:
        imgdir = os.path.join(indir, "images")
        feeddir = os.path.join(indir, "feeds")
        storedir = os.path.join(indir, "storedfiles")

        for d in [indir, imgdir, feeddir, storedir]:
            if not os.path.exists(d):
                raise Exception ("specified directory "+str(indir)+" does not appear to be complete (missing "+str(d)+")")

                
        anchore_print("importing images...")
        #imagelist = []
        for ifile in os.listdir(imgdir):
            patt = re.match("(.*)\.json", ifile)
            if patt:
                imageId = patt.group(1)

                if contexts['anchore_db'].is_image_present(imageId):
                    anchore_print("\timage ("+str(imageId)+") already exists in DB, skipping import.")
                else:
                    #imagelist.append(patt.group(1))
                    thefile = os.path.join(imgdir, ifile)
                    with open(thefile, 'r') as FH:
                        imagedata = json.loads(FH.read())
                    try:
                        rc = contexts['anchore_db'].save_image_new(imageId, report=imagedata)
                        if not rc:
                            contexts['anchore_db'].delete_image(imageId)
                            raise Exception("save to anchore DB failed")
                    except Exception as err:
                        contexts['anchore_db'].delete_image(imageId)
                        raise err

                    thedir = os.path.join(storedir, imageId)
                    if os.path.exists(thedir):
                        for namespace in os.listdir(thedir):
                            thefile = os.path.join(thedir, namespace, "stored_files.tar.gz")
                            if os.path.exists(thefile):
                                contexts['anchore_db'].save_files_tarfile(imageId, namespace, thefile)

                    anchore_print("\timage ("+str(imageId)+") imported.")

        anchore_print("importing feeds...")
        thefile = os.path.join(feeddir, "feedmeta.json")
        with open(thefile, 'r') as FH:
            feedmeta = json.loads(FH.read())

        if feedmeta:
            contexts['anchore_db'].save_feedmeta(feedmeta)

        for feed in feedmeta:
            feedobj = feedmeta[feed]
            for group in feedobj['groups']:
                groupobj = feedobj['groups'][group]
                datafiles = groupobj.pop('datafiles', [])
                for datafile in datafiles:
                    thedir = os.path.join(feeddir, feed, group)
                    thefile = os.path.join(thedir, datafile)
                    if not os.path.exists(thefile):
                        pass
                    else:
                        with open(thefile, 'r') as FH:
                            contexts['anchore_db'].save_feed_group_data(feed, group, datafile, json.loads(FH.read()))
                    anchore_print("\tfeed ("+feed+" " + group + " " + datafile + ") imported")

        #TODO import stored files

    except Exception as err:
        anchore_print_err("operation failed: " + str(err))
        ecode = 1

    sys.exit(ecode)
1066626
def upload_photos(request):
    '''
    
    '''
    upurl = ''
    if request.FILES.get("upload"):
        f = request.FILES.get("upload")
        obj = Image_File.objects.create(upload=f, is_image=True)
        obj.save()
        thumbnail_name = 'thumb' + f.name
        if getattr(settings, 'AWS_ENABLED', False):
            image_file = requests.get(obj.upload.url, stream=True)
            with open(thumbnail_name, 'wb') as destination:
                for chunk in image_file.iter_content():
                    destination.write(chunk)
        else:
            image_file = f
            with open(thumbnail_name, 'wb') as destination:
                for chunk in image_file.chunks():
                    destination.write(chunk)
        im = Image.open(destination.name)
        size = (128, 128)
        im.thumbnail(size)
        im.save(thumbnail_name)
        with open(thumbnail_name, 'rb') as imdata:
            obj.thumbnail.save(thumbnail_name, File(imdata))
        obj.save()
        os.remove(os.path.join(settings.BASE_DIR, thumbnail_name))
        upurl = "/" + obj.upload.url
    return HttpResponse(
        """<script type='text/javascript'>
        window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
        </script>""".format(request.GET['CKEditorFuncNum'], upurl)
    )
930449
def _attach_new(self, records, current, touch=True):
        
        changes = {
            'attached': [],
            'updated': []
        }

        for id, attributes in records.items():
            if id not in current:
                self.attach(id, attributes, touch)

                changes['attached'].append(id)
            elif len(attributes) > 0 and self.update_existing_pivot(id, attributes, touch):
                changes['updated'].append(id)

        return changes
23612
def attached_to_model(self):
        """"""
        try:
            if not bool(self.model):
                return False
        except AttributeError:
            return False
        else:
            try:
                return not bool(self.instance)
            except AttributeError:
                return True
484324
def require_backup_exists(func):
    
    def new_func(*args, **kwargs):
        backup_file = kwargs['backup_file']
        if not os.path.exists(backup_file):
            raise RestoreError("Could not find file '{0}'".format(backup_file))
        return func(*args, **kwargs)
    return new_func