"Should we download this tile?", either because it's not cached yet or because it's expired

@since 5.6.5
8717
public boolean isTileToBeDownloaded(final ITileSource pTileSource, final long pMapTileIndex) {
        final Long expiration = mTileWriter.getExpirationTimestamp(pTileSource, pMapTileIndex);
        if (expiration == null) {
            return true;
        }
        final long now = System.currentTimeMillis();
        return now > expiration;
    }
492046
function() {
        var context;
        if (this.cacheImageRecord) {
            context = this.cacheImageRecord.getRenderedContext();
        } else if (this.context2D) {
            context = this.context2D;
        } else {
            $.console.warn(
                '[Tile.drawCanvas] attempting to get tile scale %s when tile\'s not cached',
                this.toString());
            return 1;
        }
        return context.canvas.width / (this.size.x * $.pixelDensityRatio);
    }
347571
function _after_version_update( $plugin_prev_version, $plugin_version ) {
            if ( $this->is_theme() ) {
                // Expire the cache of the previous tabs since the theme may
                // have setting updates.
                $this->_cache->expire( 'tabs' );
                $this->_cache->expire( 'tabs_stylesheets' );
            }
        }
250442
public Drawable downloadTile(final long pMapTileIndex, final int redirectCount, final String targetUrl,
                                 final IFilesystemCache pFilesystemCache, final OnlineTileSourceBase pTileSource) throws CantContinueException {

        //prevent infinite looping of redirects, rare but very possible for misconfigured servers
        if (redirectCount>3) {
            return null;
        }

        String userAgent = null;
        if (pTileSource.getTileSourcePolicy().normalizesUserAgent()) {
            userAgent = Configuration.getInstance().getNormalizedUserAgent();
        }
        if (userAgent == null) {
            userAgent = Configuration.getInstance().getUserAgentValue();
        }
        if (!pTileSource.getTileSourcePolicy().acceptsUserAgent(userAgent)) {
            Log.e(IMapView.LOGTAG,"Please configure a relevant user agent; current value is: " + userAgent);
            return null;
        }
        InputStream in = null;
        OutputStream out = null;
        HttpURLConnection c=null;
        ByteArrayInputStream byteStream = null;
        ByteArrayOutputStream dataStream = null;
        try {
            final String tileURLString = targetUrl;

            if (Configuration.getInstance().isDebugMode()) {
                Log.d(IMapView.LOGTAG,"Downloading Maptile from url: " + tileURLString);
            }

            if (TextUtils.isEmpty(tileURLString)) {
                return null;
            }

            //TODO in the future, it may be necessary to allow app's using this library to override the SSL socket factory. It would here somewhere
            if (Configuration.getInstance().getHttpProxy() != null) {
                c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy());
            } else {
                c = (HttpURLConnection) new URL(tileURLString).openConnection();
            }
            c.setUseCaches(true);
            c.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), userAgent);
            for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
                c.setRequestProperty(entry.getKey(), entry.getValue());
            }
            c.connect();


            // Check to see if we got success

            if (c.getResponseCode() != 200) {


                switch (c.getResponseCode()) {
                    case 301:
                    case 302:
                    case 307:
                    case 308:
                        if (Configuration.getInstance().isMapTileDownloaderFollowRedirects()) {
                            //this is a redirect, check the header for a 'Location' header
                            String redirectUrl = c.getHeaderField("Location");
                            if (redirectUrl != null) {
                                if (redirectUrl.startsWith("/")) {
                                    //in this case we need to stitch together a full url
                                    URL old = new URL(targetUrl);
                                    int port = old.getPort();
                                    boolean secure = targetUrl.toLowerCase().startsWith("https://");
                                    if (port == -1)
                                        if (targetUrl.toLowerCase().startsWith("http://")) {
                                            port = 80;
                                        } else {
                                            port = 443;
                                        }

                                    redirectUrl = (secure ? "https://" : "http") + old.getHost() + ":" + port + redirectUrl;
                                }
                                Log.i(IMapView.LOGTAG, "Http redirect for MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage() + " to url " + redirectUrl);
                                return downloadTile(pMapTileIndex, redirectCount + 1, redirectUrl, pFilesystemCache, pTileSource);
                            }
                            break;
                        }	//else follow through the normal path of aborting the download
                    default: {
                        Log.w(IMapView.LOGTAG, "Problem downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage());
                        if (Configuration.getInstance().isDebugMapTileDownloader()) {
                            Log.d(IMapView.LOGTAG, tileURLString);
                        }
                        Counters.tileDownloadErrors++;
                        in = c.getErrorStream(); // in order to have the error stream purged by the finally block
                        return null;
                    }
                }



            }
            String mime = c.getHeaderField("Content-Type");
            if (Configuration.getInstance().isDebugMapTileDownloader()) {
                Log.d(IMapView.LOGTAG, tileURLString + " success, mime is " + mime );
            }
            if (mime!=null && !mime.toLowerCase().contains("image")) {
                Log.w(IMapView.LOGTAG, tileURLString + " success, however the mime type does not appear to be an image " + mime );
            }

            in = c.getInputStream();

            dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
            final long expirationTime = computeExpirationTime(
                    c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_EXPIRES_HEADER),
                    c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_CACHECONTROL_HEADER),
                    System.currentTimeMillis());
            StreamUtils.copy(in, out);
            out.flush();
            final byte[] data = dataStream.toByteArray();
            byteStream = new ByteArrayInputStream(data);

            // Save the data to the cache
            //this is the only point in which we insert tiles to the db or local file system.

            if (pFilesystemCache != null) {
                pFilesystemCache.saveFile(pTileSource, pMapTileIndex, byteStream, expirationTime);
                byteStream.reset();
            }
            return pTileSource.getDrawable(byteStream);
        } catch (final UnknownHostException e) {
            Log.w(IMapView.LOGTAG,"UnknownHostException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
            Counters.tileDownloadErrors++;
        } catch (final BitmapTileSourceBase.LowMemoryException e) {
            // low memory so empty the queue
            Counters.countOOM++;
            Log.w(IMapView.LOGTAG,"LowMemoryException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
            throw new CantContinueException(e);
        } catch (final FileNotFoundException e) {
            Counters.tileDownloadErrors++;
            Log.w(IMapView.LOGTAG,"Tile not found: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
        } catch (final IOException e) {
            Counters.tileDownloadErrors++;
            Log.w(IMapView.LOGTAG,"IOException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
        } catch (final Throwable e) {
            Counters.tileDownloadErrors++;
            Log.e(IMapView.LOGTAG,"Error downloading MapTile: " + MapTileIndex.toString(pMapTileIndex), e);
        } finally {
            StreamUtils.closeStream(in);
            StreamUtils.closeStream(out);
            StreamUtils.closeStream(byteStream);
            StreamUtils.closeStream(dataStream);
            try{
                c.disconnect();
            } catch (Exception ex){}
        }

        return null;
    }
1032509
def get_tile(url):
    
    log = ""
    connection = None

    try:
        if six.PY3:
            connection = urlopen(url=url, timeout=2)  # NOQA
        else:
            connection = urlopen(url=url)
    except Exception as e:
        log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e, url])

    content = ""

    # Read and return requested content
    if connection:
        try:
            content = connection.read()
        except (socket.timeout, socket.error) as e:
            log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e])

        connection.close()
    else:
        log += "MTST: ERROR Got no connection."

    return content, log
240147
def update(state, host, cache_time=None, touch_periodic=False):
    '''
    
    '''

    # If cache_time check when apt was last updated, prevent updates if within time
    if cache_time:
        # Ubuntu provides this handy file
        cache_info = host.fact.file(APT_UPDATE_FILENAME)

        # Time on files is not tz-aware, and will be the same tz as the server's time,
        # so we can safely remove the tzinfo from host.fact.date before comparison.
        host_cache_time = host.fact.date.replace(tzinfo=None) - timedelta(seconds=cache_time)
        if cache_info and cache_info['mtime'] and cache_info['mtime'] > host_cache_time:
            return

    yield 'apt-get update'

    # Some apt systems (Debian) have the /var/lib/apt/periodic directory, but
    # don't bother touching anything in there - so pyinfra does it, enabling
    # cache_time to work.
    if cache_time:
        yield 'touch {0}'.format(APT_UPDATE_FILENAME)
1185547
def outdated(self):
        
        if hydpy.pub.options.forcecompiling:
            return True
        if os.path.split(hydpy.__path__[0])[-2].endswith('-packages'):
            return False
        if not os.path.exists(self.dllfilepath):
            return True
        cydate = os.stat(self.dllfilepath).st_mtime
        for pysourcefile in self.pysourcefiles:
            pydate = os.stat(pysourcefile).st_mtime
            if pydate > cydate:
                return True
        return False
849471
def tile_status(self):
        """"""
        stat = self.status()

        flags = stat['status']

        # FIXME: This needs to stay in sync with lib_common: cdb_status.h
        status = {}
        status['debug_mode'] = bool(flags & (1 << 3))
        status['configured'] = bool(flags & (1 << 1))
        status['app_running'] = bool(flags & (1 << 0))
        status['trapped'] = bool(flags & (1 << 2))

        return status
127200
private function isCacheExpired()
    {
        if (empty($this->cacheInterval)) {
            return true;
        }

        $cache_file = $this->cacheDirectory.'/translations/cache_timestamp';
        $cache_dir  =$this->cacheDirectory.'/translations';
        if ('\\' === DIRECTORY_SEPARATOR) {
            $cache_file = strtr($cache_file, '/', '\\');
            $cache_dir = strtr($cache_dir, '/', '\\');
        }
        if (!\is_dir($cache_dir)) {
            \mkdir($cache_dir);
        }        
        if (!\file_exists($cache_file)) {
            \touch($cache_file);
            return true;
        }
        $expired = false;
        if ((\time() - \filemtime($cache_file)) > $this->cacheInterval) {
            \file_put_contents($cache_file, \time());
            $expired = true;
        }

        return $expired;
    }
242252
def tile_to_path(self, tile):
		''''''
		return os.path.join(self.cache_path, self.service, tile.path())
35879
private void updateEstimate(boolean startJob) {
        try {
            if (cache_east != null &&
                    cache_west != null &&
                    cache_north != null &&
                    cache_south != null &&
                    zoom_max != null &&
                    zoom_min != null) {
                double n = Double.parseDouble(cache_north.getText().toString());
                double s = Double.parseDouble(cache_south.getText().toString());
                double e = Double.parseDouble(cache_east.getText().toString());
                double w = Double.parseDouble(cache_west.getText().toString());

                int zoommin = zoom_min.getProgress();
                int zoommax = zoom_max.getProgress();
                //nesw
                BoundingBox bb= new BoundingBox(n, e, s, w);
                int tilecount = mgr.possibleTilesInArea(bb, zoommin, zoommax);
                cache_estimate.setText(tilecount + " tiles");
                if (startJob)
                {
                    if ( downloadPrompt!=null) {
                        downloadPrompt.dismiss();
                        downloadPrompt=null;
                    }

                    //this triggers the download
                    mgr.downloadAreaAsync(getActivity(), bb, zoommin, zoommax, new CacheManager.CacheManagerCallback() {
                        @Override
                        public void onTaskComplete() {
                            Toast.makeText(getActivity(), "Download complete!", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onTaskFailed(int errors) {
                            Toast.makeText(getActivity(), "Download complete with " + errors + " errors", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax) {
                            //NOOP since we are using the build in UI
                        }

                        @Override
                        public void downloadStarted() {
                            //NOOP since we are using the build in UI
                        }

                        @Override
                        public void setPossibleTilesInArea(int total) {
                            //NOOP since we are using the build in UI
                        }
                    });
                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
919836
private void warnRooCaCertExpired() {
		X509Certificate cert = getRootCaCertificate();
		if (cert == null) {
			return;
		}
		String warnMsg = Constant.messages.getString("dynssl.warn.cert.expired", cert.getNotAfter().toString(),
				new Date().toString());
		if (View.isInitialised()) {
			getView().showWarningDialog(warnMsg);
		}
		logger.warn(warnMsg);
	}
1040662
def getTile(self, lat, lon):
        """"""
        global childFileListDownload
        if childFileListDownload is not None and childFileListDownload.is_alive():
            '''print "Getting file list"'''
            return 0
        elif not self.filelist:
            '''print "Filelist download complete, loading data"'''
            data = open(self.filelist_file, 'rb')
            self.filelist = pickle.load(data)
            data.close()

        try:
            continent, filename = self.filelist[(int(lat), int(lon))]
        except KeyError:
            '''print "here??"'''
            if len(self.filelist) > self.min_filelist_len:
                # we appear to have a full filelist - this must be ocean
                return SRTMOceanTile(int(lat), int(lon))
            return 0

        global childTileDownload
        if not os.path.exists(os.path.join(self.cachedir, filename)):
            if childTileDownload is None or not childTileDownload.is_alive():
                try:
                    childTileDownload = multiprocessing.Process(target=self.downloadTile, args=(str(continent), str(filename)))
                    childTileDownload.start()
                except Exception as ex:
                    childTileDownload = None
                    return 0
                '''print "Getting Tile"'''
            return 0
        elif childTileDownload is not None and childTileDownload.is_alive():
            '''print "Still Getting Tile"'''
            return 0
        # TODO: Currently we create a new tile object each time.
        # Caching is required for improved performance.
        try:
            return SRTMTile(os.path.join(self.cachedir, filename), int(lat), int(lon))
        except InvalidTileError:
            return 0
1218236
function flushExpired () {
  return storage.keys().then(keys => {
    const cacheKeys = keys.filter(key => key.indexOf(expire) === 0)
    return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length))))
  })
}
841451
def check_stale(package_info, *args):
    
    reason = 'Package not updated in {} days'.format(DAYS_STALE)
    result = False

    now = datetime.utcnow()

    release_urls = args[0]
    if len(release_urls) > 0:
        package_uploaded_time = release_urls[0]['upload_time']
        if now - timedelta(days=DAYS_STALE) <= package_uploaded_time:
            result = True

    return result, reason, NOT_STALE
668310
def get_tile_url(self, force_http=False):
        
        base_url = self.base_http_url if force_http else self.base_url
        url = '{}tiles/{}/{}/{}/'.format(base_url, self.tile_name[0:2].lstrip('0'), self.tile_name[2],
                                         self.tile_name[3:5])
        date_params = self.date.split('-')
        for param in date_params:
            url += param.lstrip('0') + '/'
        return url + str(self.aws_index)
345854
def _get_last_cachefile_modification(self):
        

        try:
            mtime = os.path.getmtime(self._tld_list_path)
        except OSError:
            return None

        return datetime.fromtimestamp(mtime)