Get the 'nailing' images associated with expnum
777883
def get_nailing(expnum,ccd):
    """"""
    sql="""
    SELECT e.expnum, (e.mjdate - f.mjdate) dt
    FROM bucket.exposure e
    JOIN bucket.exposure f
    JOIN bucket.association b ON b.expnum=f.expnum
    JOIN bucket.association a ON a.pointing=b.pointing AND a.expnum=e.expnum
    WHERE f.expnum=%d
    AND abs(e.mjdate - f.mjdate) > 0.5
    AND abs(e.mjdate - f.mjdate) < 15.0
    ORDER BY abs(e.mjdate-f.mjdate)
    """ % ( expnum )
    try:
        import MOPdbaccess
        mysql=MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL')
        bucket=mysql.cursor()
        bucket.execute(sql)
        nailings = bucket.fetchall()
        mysql.close()
        if int(ccd) < 18:
            cutout="[-*,-*]"
        else:
            cutout=None
        import MOPfits
        for nailing in nailings:
            filename=MOPfits.adGet(str(nailing[0])+opt.raw,extno=int(ccd),cutout=cutout)
    except:
        raise TaskError, "get nailing failed"
992953
def searchTriples(expnums,ccd):
    """"""
    import MOPfits,os 
    import MOPdbaccess
    
    if len(expnums)!=3:
        return(-1)


    ### Some program Constants

    proc_file = open("proc-these-files","w")
    proc_file.write("# Files to be planted and searched\n")
    proc_file.write("#            image fwhm plant\n")
    
    import string
    import os.path
    filenames=[]
    import pyfits
    for expnum in expnums:
    	try: 
            mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL')
            bucket=mysql.cursor()
	except:
            raise TaskError, "mysql failed"
        bucket.execute("SELECT obs_iq_refccd FROM exposure WHERE expnum=%s" , (expnum, ) )
        row=bucket.fetchone()
	mysql.close()
        fwhm=row[0]
        if not fwhm > 0:
            fwhm=1.0

        if int(ccd)<18:
            cutout="[-*,-*]"
        else:
            cutout=None
        filename=MOPfits.adGet(str(expnum)+"p",extno=int(ccd),cutout=cutout)

        if not os.access(filename,os.R_OK):
            raise TaskError, 'adGet Failed'
	    
        filename=os.path.splitext(filename)
        filenames.append(filename[0])
        proc_file.write("%s %f %s \n" % ( filename[0], fwhm/0.183, "no"))

    proc_file.flush()
    proc_file.close()
    
    command="find.pl -p '' -d ./ "

    try:
        os.system(command)
    except:
        raise TaskErorr, "execute find"
    

    file_extens=[
        "cands.comb",
        "measure3.cands.astrom",
        "measure3.WARNING",
        "measure3.astrom.scatter"]
    
    if not os.access("find.OK",os.R_OK):
        raise TaskError, "find failed"
    
        
    astrom=filenames[0]+".measure3.cands.astrom"
    
    if os.access(astrom,os.R_OK):
        return(1)
    else:
        return(0)
553877
def get_darker_image(self):
        """"""
        icon_pressed = self.icon.copy()

        for x in range(self.w):
            for y in range(self.h):
                r, g, b, *_ = tuple(self.icon.get_at((x, y)))
                const = 0.8
                r = int(const * r)
                g = int(const * g)
                b = int(const * b)
                icon_pressed.set_at((x, y), (r, g, b))

        return icon_pressed
950755
def get_expstart(header,primary_hdr):
    """"""

    if 'expstart' in primary_hdr:
        exphdr = primary_hdr
    else:
        exphdr = header

    if 'EXPSTART' in exphdr:
        expstart = float(exphdr['EXPSTART'])
        expend = float(exphdr['EXPEND'])
    else:
        expstart = 0.
        expend = 0.0

    return (expstart,expend)
1010755
def next_image_partname(self, ext):
        
        def first_available_image_idx():
            image_idxs = sorted([
                part.partname.idx for part in self.iter_parts()
                if part.partname.startswith('/ppt/media/image')
                and part.partname.idx is not None
            ])
            for i, image_idx in enumerate(image_idxs):
                idx = i + 1
                if idx < image_idx:
                    return idx
            return len(image_idxs)+1

        idx = first_available_image_idx()
        return PackURI('/ppt/media/image%d.%s' % (idx, ext))
717506
def generate_filename(self, mark, **kwargs):
        """"""

        kwargs = kwargs.copy()

        kwargs['opacity'] = int(kwargs['opacity'] * 100)
        kwargs['st_mtime'] = kwargs['fstat'].st_mtime
        kwargs['st_size'] = kwargs['fstat'].st_size

        params = [
            '%(original_basename)s',
            'wm',
            'w%(watermark)i',
            'o%(opacity)i',
            'gs%(greyscale)i',
            'r%(rotation)i',
            'fm%(st_mtime)i',
            'fz%(st_size)i',
            'p%(position)s',
        ]

        scale = kwargs.get('scale', None)
        if scale and scale != mark.size:
            params.append('_s%i' % (float(kwargs['scale'][0]) / mark.size[0] * 100))

        if kwargs.get('tile', None):
            params.append('_tiled')

        # make thumbnail filename
        filename = '%s%s' % ('_'.join(params), kwargs['ext'])

        return filename % kwargs
702877
def get_thumbnail_name(self, thumbnail_options, transparent=False,
                           high_resolution=False):
        
        path, source_filename = os.path.split(self.name)
        source_extension = os.path.splitext(source_filename)[1][1:]
        if self.thumbnail_preserve_extensions is True or \
            (self.thumbnail_preserve_extensions and source_extension.lower()
             in self.thumbnail_preserve_extensions):
            extension = source_extension
        elif transparent:
            extension = self.thumbnail_transparency_extension
        else:
            extension = self.thumbnail_extension
        extension = extension or 'jpg'

        thumbnail_options = thumbnail_options.copy()
        size = tuple(thumbnail_options.pop('size'))
        quality = thumbnail_options.pop('quality', self.thumbnail_quality)
        initial_opts = ['%sx%s' % size, 'q%s' % quality]

        opts = list(thumbnail_options.items())
        opts.sort()   # Sort the options so the file name is consistent.
        opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
                for k, v in opts if v]

        all_opts = '_'.join(initial_opts + opts)

        basedir = self.thumbnail_basedir
        subdir = self.thumbnail_subdir

        # make sure our magic delimiter is not used in all_opts
        all_opts = all_opts.replace('__', '_')
        if high_resolution:
            try:
                all_opts += self.thumbnail_highres_infix
            except AttributeError:
                all_opts += '@2x'
        filename = '%s__%s.%s' % (source_filename, all_opts, extension)

        return os.path.join(basedir, path, subdir, filename)
216954
def count_extensions(img, extname='SCI'):
    
    if isinstance(img, str):
        img = fits.open(img, memmap=False)
        img.close()
    elif not isinstance(img, fits.HDUList):
        raise TypeError("Argument 'img' must be either a file name (string) " \
                        "or a `astropy.io.fits.HDUList` object.")

    if extname is None:
        return len(img)

    if not isinstance(extname, str):
        raise TypeError("Argument 'extname' must be either a string " \
        "indicating the value of the 'EXTNAME' keyword of the extensions " \
        "to be counted or None to return the count of all HDUs in the " \
        "'img' FITS file.")

    extname = extname.upper()

    n = 0
    for e in img:
        #if isinstance(e, fits.ImageHDU): continue
        if 'EXTNAME' in list(map(str.upper, list(e.header.keys()))) \
            and e.header['extname'].upper() == extname:
            n += 1

    return n
182872
def find_base_images(self):
        """"""

        for mountpoint, _ in self.mountpoints.items():
            if re.match(self.orig_re_pattern, mountpoint):
                yield mountpoint
121477
def get_built_image_info(self):
        
        logger.info("getting information about built image '%s'", self.image)
        image_info = self.tasker.get_image_info_by_image_name(self.image)
        items_count = len(image_info)
        if items_count == 1:
            return image_info[0]
        elif items_count <= 0:
            logger.error("image '%s' not found", self.image)
            raise RuntimeError("image '%s' not found" % self.image)
        else:
            logger.error("multiple (%d) images found for image '%s'", items_count, self.image)
            raise RuntimeError("multiple (%d) images found for image '%s'" % (items_count,
                                                                              self.image))
1101763
def names_from_exp(exp):
  ""
  def match(exp):
    return isinstance(exp, (sqparse2.NameX, sqparse2.AttrX))
  paths = treepath.sub_slots(exp, match, match=True, recurse_into_matches=False)
  return [exp[path] for path in paths]
952444
def get_exif_by_number(*tag)
      hash = {}
      if tag.length.zero?
        exif_data = self['EXIF:!']
        if exif_data
          exif_data.split("\n").each do |exif|
            tag, value = exif.split('=')
            tag = tag[1, 4].hex
            hash[tag] = value
          end
        end
      else
        get_exif_by_number # ensure properties is populated with exif data
        tag.each do |num|
          rval = self[format('#%04X', num.to_i)]
          hash[num] = rval == 'unknown' ? nil : rval
        end
      end
      hash
    end
708494
def searchTriples(expnums,ccd):
    """"""
    import MOPfits,os 
    import MOPdbaccess
    
    if len(expnums)!=3:
        return(-1)


    


    mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL')
    bucket=mysql.cursor()
    ### Some program Constants

    proc_file = open("proc-these-files","w")
    proc_file.write("# Files to be planted and searched\n")
    proc_file.write("#            image fwhm plant\n")
    
    import string
    import os.path
    filenames=[]
    import pyfits
    for expnum in expnums:
        bucket.execute("SELECT obs_iq_refccd FROM exposure WHERE expnum=%s" , (expnum, ) )
        row=bucket.fetchone()
        fwhm=row[0]
        if not fwhm > 0:
            fwhm=1.0

        if int(ccd)<18:
            cutout="[-*,-*]"
        else:
            cutout=None
        filename=MOPfits.adGet(str(expnum)+"p",extno=int(ccd),cutout=cutout)
        print filename
        if not os.access(filename,os.R_OK):
            return(-3)
        filename=os.path.splitext(filename)
        filenames.append(filename[0])
        proc_file.write("%s %f %s \n" % ( filename[0], fwhm/0.183, "no"))

    proc_file.flush()
    proc_file.close()
    
    command="find.pl -p '' -d ./ "
    sys.stderr.write(command)
    try:
        os.system(command)
    except:
        sys.stderr.write("Failed while running find")
    

    file_extens=[
        "cands.comb",
        "measure3.cands.astrom",
        "measure3.WARNING",
        "measure3.astrom.scatter"]
    
    if os.access("find.OK",os.R_OK):
        os.system("touch /home/cadc/kavelaar/results/05AQ06B/"+filenames[0]+".OK")
    else:
        os.system("touch /home/cadc/kavelaar/results/05AQ06B/"+filenames[0]+".FAILED")
        
        ### look for the cand.comb file and store in the DB
    import shutil
    for ext in file_extens:
        if os.access(filenames[0]+"."+ext,os.R_OK):
            shutil.copy(filenames[0]+"."+ext,"/home/cadc/kavelaar/results/05AQ06B")
    astrom=filenames[0]+".measure3.cands.astrom"
    print astrom
    cmd = "mpc_gen.pl -c "+astrom
    print os.access(astrom,os.R_OK)
    if os.access(astrom,os.R_OK):
        print cmd
        os.system(cmd)
        os.system("mpcIngest.pl *.MPC")
	os.system("cp *.MPC /home/cadc/kavelaar/results/05AQ06B")
	return(1)
    return(0)
58327
def get_next_image(img_dir):
    """"""
    images, current_wall = get_image_dir(img_dir)
    images.sort(key=lambda img: [int(x) if x.isdigit() else x
                                 for x in re.split('([0-9]+)', img)])

    try:
        next_index = images.index(current_wall) + 1

    except ValueError:
        next_index = 0

    try:
        image = images[next_index]

    except IndexError:
        image = images[0]

    return os.path.join(img_dir, image)
1278740
def _get_thumbnail_url(image):
    
    lhs, rhs = splitext(image.url)
    lhs += THUMB_EXT
    thumb_url = f'{lhs}{rhs}'
    return thumb_url
799333
def images_at(cell_name)
      coordinate = calc_coordinate(cell_name)
      pathnames_at_coordinate = @images_pathnames[coordinate]
      return if pathnames_at_coordinate.empty?

      pathnames_at_coordinate.map do |image_pathname|
        if image_pathname.exist?
          image_pathname
        else
          excel_image_path = "xl/media#{image_pathname.to_path.split(tmpdir).last}"
          IO.copy_stream(@book.files.file.open(excel_image_path), image_pathname.to_path)
          image_pathname
         end
      end
    end
669247
def _getphotosets_forphoto(self,pid):
        """"""

        resp=self.flickr.photos_getAllContexts(photo_id=pid)
        if resp.attrib['stat']!='ok':
            logger.error("%s - flickr: photos_getAllContext failed with status: %s",\
                    resp.attrib['stat']);
            return None

        lphotosets=[]
        for element in resp.findall('set'):
            lphotosets.append(element.attrib['title'])

        logger.debug('%s - belongs to these photosets %s',pid,lphotosets)

        return lphotosets