Given an image file href and a set of directories, modify the image file
        name so it's correct with respect to the output and cache directories.
774255
def post_process_symbolizer_image_file(file_href, dirs):
    
    # support latest mapnik features of auto-detection
    # of image sizes and jpeg reading support...
    # http://trac.mapnik.org/ticket/508

    mapnik_auto_image_support = (MAPNIK_VERSION >= 701)
    mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601)
    file_href = urljoin(dirs.source.rstrip('/')+'/', file_href)
    scheme, n, path, p, q, f = urlparse(file_href)
    if scheme in ('http','https'):
        scheme, path = '', locally_cache_remote_file(file_href, dirs.cache)
    
    if scheme not in ('file', '') or not systempath.exists(un_posix(path)):
        raise Exception("Image file needs to be a working, fetchable resource, not %s" % file_href)
        
    if not mapnik_auto_image_support and not Image:
        raise SystemExit('PIL (Python Imaging Library) is required for handling image data unless you are using PNG inputs and running Mapnik >=0.7.0')

    img = Image.open(un_posix(path))
    
    if mapnik_requires_absolute_paths:
        path = posixpath.realpath(path)
    
    else:
        path = dirs.output_path(path)

    msg('reading symbol: %s' % path)

    image_name, ext = posixpath.splitext(path)
    
    if ext in ('.png', '.tif', '.tiff'):
        output_ext = ext
    else:
        output_ext = '.png'
    
    # new local file name
    dest_file = un_posix('%s%s' % (image_name, output_ext))
    
    if not posixpath.exists(dest_file):
        img.save(dest_file,'PNG')

    msg('Destination file: %s' % dest_file)

    return dest_file, output_ext[1:], img.size[0], img.size[1]
163809
private URI getImageFile(final URI href) {
        final URI fileName;
        final FileInfo fi = job.getFileInfo(currentFile.resolve(href));
        if (fi != null) {
            fileName = job.getInputDir().relativize(fi.src);
        } else {
            fileName = href;
        }

        final URI outputURI = outputDir.toURI().resolve(fileName);
        if (exists(outputURI)) {
            logger.debug("Found " + outputURI);
            return outputURI;
        }

        final URI tempURI = job.tempDirURI.resolve(fileName);
        if (exists(tempURI)) {
            logger.debug("Found " + tempURI);
            return tempURI;
        }

        if (fi != null) {
            final URI srcTempURI = job.tempDirURI.resolve(fi.uri);
            if (exists(srcTempURI)) {
                logger.debug("Found " + srcTempURI);
                return srcTempURI;
            }
        }

        final URI srcURI = job.getInputDir().resolve(fileName);
        if (exists(srcURI)) {
            logger.debug("Found " + srcURI);
            return srcURI;
        }

        return null;
    }
1343940
def image_dir(image)
      relative = File.join "docker", env, image
      File.expand_path relative, Dir.pwd
    end
646384
def make_file_readable (filename):
    """"""
    if not os.path.islink(filename):
        util.set_mode(filename, stat.S_IRUSR)
28255
def cache_file(filename, reload_on_change=False, opts=default_opts):
    """"""
    filename = pyc2py(filename)
    if filename in file_cache:
        if reload_on_change: checkcache(filename)
        pass
    else:
        opts['use_linecache_lines'] = True
        update_cache(filename, opts)
        pass
    if filename in file_cache:
        return file_cache[filename].path
    else: return None
    return
938371
function resolveImages(currentFile, $) {
    var currentDirectory = path.dirname(currentFile);

    return editHTMLElement($, 'img', function($img) {
        var src = $img.attr('src');

        if (LocationUtils.isExternal(src) || LocationUtils.isDataURI(src)) {
            return;
        }

        // Calcul absolute path for this
        src = LocationUtils.toAbsolute(src, currentDirectory, '.');

        // Convert back to relative
        src = LocationUtils.relative(currentDirectory, src);

        $img.attr('src', src);
    });
}
405259
def updateKeyword(filename, key, value,show=yes):
    """"""

    _fname, _extn = parseFilename(filename)

    # Open image whether it is FITS or GEIS
    _fimg = openImage(_fname, mode='update')

    # Address the correct header
    _hdr = getExtn(_fimg, _extn).header

    # Assign a new value or add new keyword here.
    try:
        _hdr[key] = value
    except KeyError:
        if show:
            print('Adding new keyword ', key, '=', value)
        _hdr[key] = value

    # Close image
    _fimg.close()
    del _fimg
490389
def url_to_filename(url):
    
    # remove leading/trailing slash
    if url.startswith('/'):
        url = url[1:]
    if url.endswith('/'):
        url = url[:-1]
    # remove pardir symbols to prevent unwilling filesystem access
    url = remove_pardir_symbols(url)
    # replace dots to underscore in filename part
    url = replace_dots_to_underscores_at_last(url)
    return url
465907
def _append_filename_extension(self, response: BaseResponse):
        ''''''
        if not self._filename:
            return

        if response.request.url_info.scheme not in ('http', 'https'):
            return

        if not re.search(r'\.[hH][tT][mM][lL]?$', self._filename) and \
                HTMLReader.is_response(response):
            self._filename += '.html'
        elif not re.search(r'\.[cC][sS][sS]$', self._filename) and \
                CSSReader.is_response(response):
            self._filename += '.css'
505945
def ensure_dirs(filename):
    """"""
    dirname, _ = os.path.split(filename)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)
655976
def image_tag(src, options={})
      src = "/images/#{src}" unless src.include? "://" # Add images directory to path if not a full URL
      options[:src] = url_for(src)
      tag(:img, options)
    end
1157656
function rename(file, css, opts) {
    return opts.name({
        dir: path.dirname(file),
        name: path.basename(file, path.extname(file)),
        ext: path.extname(file),
        hash: hash(css, opts.algorithm, opts.trim)
    });
}
314136
def pretty_filename(filename):
    ''''''
    try:
        a = os.path.abspath(filename)
        r = os.path.relpath(filename)
    except ValueError:
        # Catch relpath exception. Happens, because it can not produce relative path
        # if wroking directory is on different drive.
        a = r = filename
    return a if '..' in r else r
930362
function image_local(&$content, $dir='')
	{
	    if(empty($dir)) $dir = UPLOAD_DIR.'/extend/'.date('Ym')."/".date("d");
		if(!file_exists($dir))
		{
			mkdir(WEBPATH.$dir,0777,true);
		}
		$chunklist = array ();
		$chunklist = explode("\n",$content);
		$links = array ();
		$regs = array ();
		$source = array();
		$i = 0;
		while(list ($id, $chunk) = each($chunklist))
		{
			if (strstr(strtolower($chunk),"img") && strstr(strtolower($chunk), "src"))
			{
				while (eregi("(img[^>]*src[[:blank:]]*)=[[:blank:]]*[\'\"]?(([[a-z]{3,5}://(([.a-zA-Z0-9-])+(:[0-9]+)*))*([+:%/?=&;\\\(\),._a-zA-Z0-9-]*))(#[.a-zA-Z0-9-]*)?[\'\" ]?", $chunk, $regs))
				{
					if($regs[2])
					{
						$i++;
						$source[$i] = $regs[2];
					}
					$chunk = str_replace($regs[0], "", $chunk);
				}
			}
		}
		$newImg = array();
		foreach($source as $uri)
		{
			if(!strstr(WEBROOT,$uri) and $uri{0}!='/')
			{
				$filename=substr(time(),6,-1).rand(100000,999999).".jpg";
				copy($uri,WEBPATH.$dir.'/'.$filename);
				$content = str_replace($uri,WEBROOT.$dir."/".$filename,$content);
			}
		}
	}
298725
def modify(file, content = nil)
      Pathname.new(file).tap do |file|
        file.open('w') { |f| f.write(content) } if content
        future = Time.now + 60
        file.utime future, future
      end
    end
234481
def fix_examples_dir(lib_dir):
    """"""
    for x in lib_dir.dirs():
        if x.name.lower() == EXAMPLES:
            return
    for x in lib_dir.dirs():
        if x.name.lower() == EXAMPLES:
            _fix_dir(x)
            return
    for x in lib_dir.dirs():
        if 'example' in x.name.lower():
            _fix_dir(x)
            return
    for x in lib_dir.dirs():
        if len(files_multi_pattern(x, INO_PATTERNS)):
            _fix_dir(x)
            return
181273
def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs):
    
    use_cache = True
    if "use_cache" in kwargs:
        use_cache = kwargs["use_cache"]
        del kwargs["use_cache"]

    json_path = None
    if cache_dir:
        json_path = os.path.join(cache_dir, "cached-img-%s.json" % cache_key)
        if use_cache and os.path.exists(json_path):
            LOG.info("Fetching %r from cache..." % (args,))
            try:
                with closing(open(json_path, "r")) as handle:
                    img_data = json.load(handle)

                return parts.Bunch([(key, parts.Bunch(val))
                    for key, val in img_data.items() # BOGUS pylint: disable=E1103
                ])
            except (EnvironmentError, TypeError, ValueError) as exc:
                LOG.warn("Problem reading cached data from '%s', ignoring cache... (%s)" % (json_path, exc))

    LOG.info("Copying %r..." % (args,))
    img_data = uploader(*args, **kwargs)

    if json_path:
        with closing(open(json_path, "w")) as handle:
            json.dump(img_data, handle)

    return img_data