working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,535 snippets matching: cache

    public by anibal copitan  131797  0  3  0

    zf2 configurarar cache modules

    zf2 configurarar cache modules: zf2-cache.module.php
    // more advanced
    http://akrabat.com/caching-your-zf2-merged-configuration/
    
    
    // basic element
    https://samsonasik.wordpress.com/2013/03/13/zend-framework-2-cache-module-config-module-classmap-caching/
    
    

    public by sTiLL-iLL @ SniPitz-KND  2799  2  7  17

    kacher.js A basic static resource cache module for node.js

    kacher.js A basic static resource cache module for node.js: kacher.js
    
    // kacher.js ... this uses my Signals.js event module as a dependency
    
    var signalCaster = require("./signals").Signals,
    	fs = require('fs'),
    	url = require("url"),
    	path = require("path"),
    	config = {
    		cache: [], 
    		cachedFilesMaximum: function (maxFiles) {
    			var f = maxFiles || 500;
    			return f;
    		},
    		cacheInterval: function (interval) {
    			var v = interval || 1550; // 1/2 hour
    			return v;
    		}, 
    		mimeTypes: {
    			".txt": "text/plain",
    			".css": "text/css",
    			".js": "text/javascript",
    			".htm": "text/html",
    			".html": "text/html",
    			".jpeg": "image/jpeg",
    			".jpg": "image/jpeg",
    			".png": "image/png",
    			".gif": "image/gif",
    			".ico": "image/x-icon",
    			".xml": "text/xml",
    			".rss": "application/rss+xml",
    			".json": "application/json",
    			".zip": "application/zip, application/octet-stream",
    			".rar": "application/x-rar-compressed, application/octet-stream",
    			".exe": "application/octet-stream"
    	  	}
    };
     
    function strt(interval, fileMax) {
    	config.cacheInterval(interval);
    	config.cachedFilesMaximum(fileMax);
    	setInterval(function(){
    		for (var pth in config.cache) {
    			performCacheAssessment(pth);
    		}
    	}, config.cacheInterval());
    }
     
    function addToCache(fPth, dta){
        if(config.cache.length < config.cachedFilesMaximum()) {
            config.cache[fPth] = {data:dta, mtime:0};
        }
    	return;
    }
     
    function performCacheAssessment(pth) {
        fs.stat(pth, function(err, sts){   
            if(!err){
                if(config.cache[pth].mtime != sts.mtime.getTime()){
                    fs.readFile(pth, function(err, dta){
                        if(!err){
                            config.cache[pth].data = dta;
                            config.cache[pth].mtime = sts.mtime.getTime();
                        }
                    });
                }    
            }
        });
        return;
    }
     
    // the srv method is passed to the caller when "startCache" is called. That way, serving the file can still -
    // be explicitly invoked by the caller to issue the response, but all the cache mechanics are abstracted away.
     
    function serve(pnm, request, response) {
    	var fn =  path.basename(pnm),
    	    xt = path.extname(request.url),
    	    dn = path.dirname(request.url),
    	    fPth = path.join(__dirname+dn, fn);
    	
    	if(config.cache[fPth] !== undefined) {
    	    response.writeHead(200, { "Content-Type": config.mimeTypes[xt] });
    		response.end(config.cache[fPth].data);
    		signalCaster.signal("FileServed_Cache", fPth + ": served from the cache...");
    		return;
    	} 
    	else {
    		fs.readFile(fPth, function(err, dta){
    			if(!err){
    				addToCache(fPth, dta, config.mimeTypes[xt]);
    				signalCaster.signal("FileServed_Disk", fPth + ": served from the disk...");
    				response.writeHead(200, {"Content-Type":config.mimeTypes[xt]});
    				response.end(dta);
    				signalCaster.signal("FileCached", fPth + ": placed in cache...");
    			}
    			else{
    				response.writeHead(404, {"Content-Type": "text/html"});
    				response.end("file aint here... Sorry you suck.")
    				console.log(err);
    			}
    		});
    		return;
    	}
    }
     
    exports.startCache = function(i, m) {
    	strt(i,m);
    	return serve;
    }
    
    
    

    public by sTiLL-iLL  2769  0  7  17

    a piecemealed, slapped together, least recent cache js module

    
    //  KnDKaChe
    
    var utils = require('../utils')
      , Cache = require('../cache')
      , fresh = require('fresh');
    
    module.exports = function staticCache(options){
      var options = options || {}
        , cache = new Cache(options.maxObjects || 128)
        , maxlen = options.maxLength || 1024 * 256;
    
      if (process.env.NODE_ENV !== 'test') {
        console.warn('connect.staticCache() is deprecated and will be removed in 3.0');
        console.warn('use varnish or similar reverse proxy caches.');
      }
    
      return function staticCache(req, res, next){
        var key = cacheKey(req)
          , ranges = req.headers.range
          , hasCookies = req.headers.cookie
          , hit = cache.get(key);
    
        req.on('static', function(stream){
          var headers = res._headers
            , cc = utils.parseCacheControl(headers['cache-control'] || '')
            , contentLength = headers['content-length']
            , hit;
    
          // no set-cookie!
          if (headers['set-cookie']) return hasCookies = true;
    
          // dont cache when cookies are present
          if (hasCookies) return;
    
          // ignore giants
          if (!contentLength || contentLength > maxlen) return;
    
          if (headers['content-range']) return;
    
          if ( cc['no-cache']
            || cc['no-store']
            || cc['private']
            || cc['must-revalidate']) return;
    
          if (hit = cache.get(key)){
            if (headers.etag == hit[0].etag) {
              hit[0].date = new Date;
              return;
            }
            else {
              cache.remove(key);
            }
          }
          
          if (null == stream) return;
    
          var arr = [];
          stream.on('data', function(chunk){
            arr.push(chunk);
          });
    
          stream.on('end', function(){
            var cacheEntry = cache.add(key);
            delete headers['x-cache']; // Clean up (TODO: others)
            cacheEntry.push(200);
            cacheEntry.push(headers);
            cacheEntry.push.apply(cacheEntry, arr);
          });
        });
    
        if (req.method == 'GET' || req.method == 'HEAD') {
          if (ranges) {
            next();
          }
          else if (!hasCookies && hit && !mustRevalidate(req, hit)) {
            res.setHeader('X-Cache', 'HIT');
            respondFromCache(req, res, hit);
          }
          else {
            res.setHeader('X-Cache', 'MISS');
            next();
          }
        }
        else {
          next();
        }
      }
    };
    
    function respondFromCache(req, res, cacheEntry) {
      var status = cacheEntry[0]
        , headers = utils.merge({}, cacheEntry[1])
        , content = cacheEntry.slice(2);
    
      headers.age = (new Date - new Date(headers.date)) / 1000 || 0;
    
      switch (req.method) {
        case 'HEAD':
          res.writeHead(status, headers);
          res.end();
          break;
        case 'GET':
          if (utils.conditionalGET(req) && fresh(req.headers, headers)) {
            headers['content-length'] = 0;
            res.writeHead(304, headers);
            res.end();
          } else {
            res.writeHead(status, headers);
    
            function write() {
              while (content.length) {
                if (false === res.write(content.shift())) {
                  res.once('drain', write);
                  return;
                }
              }
              res.end();
            }
    
            write();
          }
          break;
        default:
          // This should never happen.
          res.writeHead(500, '');
          res.end();
      }
    }
    
    function mustRevalidate(req, cacheEntry) {
      var cacheHeaders = cacheEntry[1]
        , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '')
        , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '')
        , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0;
    
      if ( cacheCC['no-cache']
        || cacheCC['must-revalidate']
        || cacheCC['proxy-revalidate']) return true;
    
      if (reqCC['no-cache']) return true;
    
      if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge;
    
      if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge;
    
      return false;
    }
    
    function cacheKey(req) {
      return utils.parseUrl(req).path;
    }
    

    public by sTiLL-iLL @ SniPitz-KND  3517  0  7  19

    KachingFetch.js get it boy! woof! good dog....

    I modeled it after jquery's "getScript" only better.... cause it caches!!!
    
    // caching script fetcher  //
     
    var futrs = {};
     
     var ajaxFetch = function( url, cBak ) {
         if ( !futrs[ url ] ) {
             futrs[ url ] = $.Deferred(function( defer ) {
                 $.getScript( url )
                     .then( defer.resolve, defer.reject );
                 }).promise();
           }
         return futrs[ url ].done( cBak );
     };
     
    /*-----------------------------------------------------------------------*/
     
        // <<  use it! >>
      ajaxFetch('//totalPorn247.com/freeVideos/Tits+Ass?=199BOOBzInVIEW.js', cBak);
     
      function cBak(resp) {
          if(resp.length > 0) {
              var dd = document.querySelector('#resultDiv');
              dd.innerHTML = renderDirtyWords(a, z, 125);                        
          }  
      }
            
                

    public by JKCPR  3338  1  6  2

    Measure memory usage in PHP (utility script):

    You can use this code snippet to measure memory usage in PHP
    <?php 
    $time = microtime(TRUE);
    $mem = memory_get_usage();
    
    /*[the code you want to measure here]*/
    
    print_r(array(
    
      'memory' => (memory_get_usage() - $mem) / (1024 * 1024),
    
      'seconds' => microtime(TRUE) - $time
    
    ));
    ?>

    public by shebin512  3043  1  5  0

    Bash Script to clean magento 1.x Cache

    Magento 1.x cache clean Bash script. 1. Save the code in "/path/of/the/file/.sh" 2. Give executable permission for the file "chmod a+x /path/of/the/file/.sh" 3. Run the script from your magento document root like $ /path/of/the/file/.sh
    #!/bin/bash 
    # author Shebin Sheikh
    
    # function to remove the magento cache.
    function mageCacheClear {
    
    	local current_dir=$(pwd);
    	#echo $current_dir
    	#exit
    
    	if [[ -f "$current_dir/app/Mage.php" ]]; then
    		#echo "Inside Mage Doc root"
    		rm -vrf var/{cache,full_page_cache}/ media/{js,css}/
    	else
    		echo -e "Not inside A magento 1.X's document root!"
    		exit $?
    	fi
    
    }
    
    mageCacheClear # call the function

    public by HeathDernovich  3274  0  4  2

    kacher.js A basic static resource cache module for node.js

    kacher.js A basic static resource cache module for node.js: kacher.js
    
    // kacher.js ... this uses my Signals.js event module as a dependency
    
    var signalCaster = require("./signals").Signals,
    	fs = require('fs'),
    	url = require("url"),
    	path = require("path"),
    	config = {
    		cache: [], 
    		cachedFilesMaximum: function (maxFiles) {
    			var f = maxFiles || 500;
    			return f;
    		},
    		cacheInterval: function (interval) {
    			var v = interval || 1550; // 1/2 hour
    			return v;
    		}, 
    		mimeTypes: {
    			".txt": "text/plain",
    			".css": "text/css",
    			".js": "text/javascript",
    			".htm": "text/html",
    			".html": "text/html",
    			".jpeg": "image/jpeg",
    			".jpg": "image/jpeg",
    			".png": "image/png",
    			".gif": "image/gif",
    			".ico": "image/x-icon",
    			".xml": "text/xml",
    			".rss": "application/rss+xml",
    			".json": "application/json",
    			".zip": "application/zip, application/octet-stream",
    			".rar": "application/x-rar-compressed, application/octet-stream",
    			".exe": "application/octet-stream"
    	  	}
    };
     
    function strt(interval, fileMax) {
    	config.cacheInterval(interval);
    	config.cachedFilesMaximum(fileMax);
    	setInterval(function(){
    		for (var pth in config.cache) {
    			performCacheAssessment(pth);
    		}
    	}, config.cacheInterval());
    }
     
    function addToCache(fPth, dta){
        if(config.cache.length < config.cachedFilesMaximum()) {
            config.cache[fPth] = {data:dta, mtime:0};
        }
    	return;
    }
     
    function performCacheAssessment(pth) {
        fs.stat(pth, function(err, sts){   
            if(!err){
                if(config.cache[pth].mtime != sts.mtime.getTime()){
                    fs.readFile(pth, function(err, dta){
                        if(!err){
                            config.cache[pth].data = dta;
                            config.cache[pth].mtime = sts.mtime.getTime();
                        }
                    });
                }    
            }
        });
        return;
    }
     
    // the srv method is passed to the caller when "startCache" is called. That way, serving the file can still -
    // be explicitly invoked by the caller to issue the response, but all the cache mechanics are abstracted away.
     
    function serve(pnm, request, response) {
    	var fn =  path.basename(pnm),
    	    xt = path.extname(request.url),
    	    dn = path.dirname(request.url),
    	    fPth = path.join(__dirname+dn, fn);
    	
    	if(config.cache[fPth] !== undefined) {
    	    response.writeHead(200, { "Content-Type": config.mimeTypes[xt] });
    		response.end(config.cache[fPth].data);
    		signalCaster.signal("FileServed_Cache", fPth + ": served from the cache...");
    		return;
    	} 
    	else {
    		fs.readFile(fPth, function(err, dta){
    			if(!err){
    				addToCache(fPth, dta, config.mimeTypes[xt]);
    				signalCaster.signal("FileServed_Disk", fPth + ": served from the disk...");
    				response.writeHead(200, {"Content-Type":config.mimeTypes[xt]});
    				response.end(dta);
    				signalCaster.signal("FileCached", fPth + ": placed in cache...");
    			}
    			else{
    				response.writeHead(404, {"Content-Type": "text/html"});
    				response.end("file aint here... Sorry you suck.")
    				console.log(err);
    			}
    		});
    		return;
    	}
    }
     
    exports.startCache = function(i, m) {
    	strt(i,m);
    	return serve;
    }
    
    
    

    public by JKCPR  2136  0  6  2

    Memcache - Basic Example

    Caching slowAndHeavyOperation() with Memcache
    $memcache = new Memcache;
    
    $memcache->connect('localhost', 11211);
    
     
    
    function slowAndHeavyOperation() {
    
        sleep(1);
    
        return date('d/m/Y H:i:s');
    
    }
    
     
    
    $item1 = $memcache->get('item');
    
     
    
    if ($item1 === false) {
    
        $item1 = slowAndHeavyOperation();
    
        $memcache->set('item', $item1);
    
    }
    
    echo $item1;

    public by tirei_01  2753  0  5  0

    #bitrix Cache CPHPCache

    Пример создания кеша в bitrix
    $obCACHE = new CPHPCache;
    $iCACHE_TIME=3600;
    $strCACHE_ID="AreaMaxPlot";
    $strCACHE_PATH = "/object.area";
    if (isset($_REQUEST['clear_cache']) && $_REQUEST['clear_cache']=="Y"){ $obCACHE->Clean($strCACHE_ID,$strCACHE_PATH); }
    if($iCACHE_TIME > 0 && $obCACHE->InitCache($iCACHE_TIME,$strCACHE_ID,$strCACHE_PATH)) 
    {    
    	$arrRESULT = $obCACHE->GetVars();
    	$arrAreaMaxDat  = $arrRESULT['AreaMaxDat'];
    }
    if(!is_array($arrAreaMaxDat) || !count($arrAreaMaxDat)){
    	$arrAreaMaxDat[] = 'test';
    	$obCACHE->StartDataCache($iCACHE_TIME, $strCACHE_ID, $strCACHE_PATH);
    	$obCACHE->EndDataCache(array("AreaMaxDat"=>$arrAreaMaxDat));
    } 

    public by orlandos  2258  1  4  0

    CSS Cache Buster from Genesis

    php
    /** CSS Cache Buster from Genesis added to function.php*/
    //* define( 'CHILD_THEME_VERSION', filemtime( get_stylesheet_directory() . '/style.css' ) );
    //* define above throws wordpress exception since defines CHILD_THEME_VERSION twice
    add_filter( 'stylesheet_uri', 'child_stylesheet_uri' );
    /**
     * Cache bust the style.css reference.
     *
     */
    function child_stylesheet_uri( $stylesheet_uri ) {
        return add_query_arg( 'v', filemtime( get_stylesheet_directory() . '/style.css' ), $stylesheet_uri );
    }
    
    • Public Snippets
    • Channels Snippets