Prompt stringlengths 14 160 | Instruction stringlengths 18 2k | Response stringlengths 8 2k |
|---|---|---|
Difference between "php artisan config:cache" and "php artisan cache:clear" in Laravel |
In Laravel have noticed there is two way to clear the cache
php artisan cache:clear
and
php artisan config:cache
However i realized only the second one working properly when changing the localization, adding laravel/passport package and etc..
What is their difference ?
|
php artisan cache:clear - Flush the application cache
php artisan config:cache - Create a cache file for faster configuration loading.
This is for configuration cache. This command will clear the configuration cache before it creates. More details
php artisan config:clear - Remove the configuration cache file
|
Internet Explorer Caching asp.netmvc ajax results |
I'm having an issue with a page in internet explorer.
I have an ajax call that calls a form, in other browser, when I click the link it passes in the controller and load correctly data. but in IE, when its loaded once, it aways brings me the same old results without passing in the controller.
|
Try:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
This attribute, placed in controller class, disables caching. Since I don't need caching in my application, I placed it in my BaseController class:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public abstract class BaseController : ... |
Python pandas persistent cache |
Is there an implementation for python pandas that cache the data on disk so I can avoid to reproduce it every time?
In particular is there a caching method for get_yahoo_data for financial?
A very plus would be:
very few lines of code to write
possibility to integrate the persisted series when new data is downloaded ... |
22
There are many ways to achieve this, however probably the easiest way is to use the build in methods for writing and reading Python pickles. You can use pandas.DataFrame.to_pickle to store the DataFrame to disk and pandas.read_pickle to read the stored DataFrame from dis... |
Async/Await and Caching |
My service layer is caching alot of Db requests to memcached, does this make it impossible to use Async/Await?? For example how could I await this?
public virtual Store GetStoreByUsername(string username)
{
return _cacheManager.Get(string.Format("Cache_Key_{0}", username), () =>
{
retur... |
It looks like the cache-manager does all the "check it exists, if not run the lambda then store". If so, the only way to make that async is to have a GetAsync method that returns a Task<Store> rather than a Store, i.e.
public virtual Task<Store> GetStoreByUsernameAsync(string username)
{
return _cacheManager.GetAs... |
Managing Cache Invalidation |
Just wondering how you guys manage your cache invalidations. Given that there might objects (hundreds and thousands) in the cache that might be triggered by different algorithms or rules. How do you keep track of it all?
Is there anyway you can reference the relationships from a table in the database and enforce it s... |
The purpose of your cache layer should be pretty much that : reflecting the corresponding data in your database, but providing it faster than the database would, or at least providing it without keeping the database busy.
To achieve this, you have two solutions :
know the exact lifespan of everything you store in cac... |
Html5 cache manifest in a UIWebView? |
I'd like to be able to use the html5 cache manifest to store images locally on an iPhone that is visiting the page via a UIWebView within an app.
I've set up a sample that I think conforms to the specs, and appears to work in safari 4 and mobile safari, but not in my app's UIWebView.
The sample html is set up at http:... |
I got this to work using a .manifest file in a UIWebView. I discovered the trick on the Apple developer forums.
you must deliver the proper mime-type for the manifest file: it must be of type "text/cache-manifest" - if it is anything else, then you won't get your files cached.
you can use web-sniffer at http://web-sni... |
Does iOS clean cache directory automatically? |
I'm saving media files at this path and i wonder does iOS auto clean the cache or i have to do it manually?
let documentsUrl = self.fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
Searched and there is no particular answer for it.
|
The operating system can clear this folder if needed.
Documentation
Put data cache files in the Library/Caches/ directory. Cache data can be used for any data that needs to persist longer than temporary data, but not as long as a support file. Generally speaking, the application does not require cache data to operat... |
How to use multiple caches in rails? (for real) |
I'd like to use 2 caches -- the in memory default one and a memcache one, though abstractly it shouldn't matter (I think) which two.
The in memory default one is where I want to load small and rarely changing data. I've been using the memory one to date. I keep a bunch of 'domain data' type stuff from the database i... |
ActiveSupport::Cache::MemoryStore is what you want to use. Rails.cache uses either MemoryStore, FileStore or in my case DalliStore :-)
You can have global instance of ActiveSupport::Cache::MemoryStore and use it or create a class with a singleton pattern that holds this object (cleaner). Set Rails.cache to the other c... |
How to cache images in Glide |
When I use glide, some images doesn't loads. How can I store it in the cache, or anywhere, to when I'll use the app all my images loads.
Example picture of my problem:
My code:
.java
home_ib7_monster_truck =
(ImageButton)findViewById(R.id.home_ib7_monster_truck);
Glide.with(Home... |
24
Please Read the Description below as per official documentation : https://futurestud.io/tutorials/glide-caching-basics
Share
Improve this answer
Follow
answered Jan 8, 2018 at 14:13
... |
How can I cache image files locally with PhoneGap / Cordova? |
Here's my problem :
I making a Web/Mobile app, using AngularJS and Cordova. For offline purpose, I use localStorage to store all the data of the app (JSON, parameters, and so on).
The thing is : I need to store / cache images locally (again, offline purpose). As localStorage size limit is around 5mo, I can't use it, ... |
After long hours searching on SO and Github, I found imgCache.js, a JS library that handle file cache for Chrome, Android and iOs (through Cordova).
https://github.com/chrisben/imgcache.js/
Then, basically :
var target = $('.cached-img');
ImgCache.isCached(target.attr('src'), function(path, success){
if(su... |
why does knitr caching fail for data.table `:=`? |
This is related in spirit to this question, but must be different in mechanism.
If you try to cache a knitr chunk that contains a data.table := assignement then it acts as though that chunk has not been run, and later chunks do not see the affect of the :=.
Any idea why this is? How does knitr detect objects have upda... |
Speculation:
Here is what appears to be going on.
knitr quite sensibly caches objects as as soon as they are created. It then updates their cached value whenever it detects that they have been altered.
data.table, though, bypasses R's normal copy-by-value assignment and replacement mechanisms, and uses a := operator... |
Most Efficient Way Of Clearing Cache Using ASP.NET |
I am building an ASP.NET/Umbraco powered website which is very custom data driven via entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.
But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the... |
11
The method you use is actually the correct way to clear your cache, there is just one minor 'error' in your code. The enumerator only is valid as long as the original collection remains unchanged. So while the code might work most of the time, there might be small errors... |
Why my Mobile Safari cache won't clear? |
I'm trying to debug a site on my iPhone4 (iOS4) iPad1 (iOS3.3) and desktop.
My problem is I cannot clear the iPhone cache at all.
If I add alerts/consoles to the js files I'm debugging, they show up on iPad and desktop, but the iPhone just keeps reloading from the cache.
If I clear the cache through settings>safari>d... |
Even though this is a bit hacky, maybe have a go at this workaround (I'm assuming this is for development)
As per the notes in disabling ajax cacheing here How to disable Ajax caching in Safari browser? you could set no-cache headers while developing or in plain HTML like this
<META HTTP-EQUIV="Pragma" CONTENT="no-c... |
Magento - get current product |
I have a sidebar block in my layout that is being displayed on different pages.
In this block I have a list of products, and I want to select the current product when I'm on a product page.
I'm using :
$current_product = Mage::registry('current_product');
to get the current product, but this works only for the first... |
If you're not willing to use your own block class inheriting from Mage_Catalog_Block_Navigation, in which you could set your own cache informations (to make it eg depending on the current product), you can get rid of the cache for your block by using this in its layout definition :
<block type="catalog/navigation" nam... |
How to use redis for number of micro-services? |
I am very much new to redis. I have been investigating on redis for past few days.I read the documentation on cache management(lru cache), commands ,etc. I want to know how to implement caching for multiple microservice(s) data .
I have few questions:
Can all microservices data(cached) be kept under a single instance... |
It's possible to use the same Redis for multiple microservices, just make sure to prefix your redis cache keys to avoid conflict between all microservices.
You can use multi db in the same redis instance (i.e one for each microservice) but it's discouraged because Redis is single threaded.
The best way is to use one R... |
Any way to force reset of all cached static files on AppEngine? |
I am running into a known AppEngine issue where the wrong static content is cached if I go to a particular URL for my app, but the right static content shows up if I append a ?foo parameter to bust the cache, and VERSION.myapp.appspot.com works too.
Is there any way to get the correct content showing up at the unmodif... |
It the depends on what cache-control is used. Check in firebug och chrome inspector and see what expiration date are set.
If you've set the cache-control to public you can't affect the control since the files are cache on various proxies and server along the way.
If you use cache-control private you should be able to ... |
How do I prevent IIS 7.5 from caching symlink content? |
I have set up IIS 7.5 to statically serve some files, and some of these files are actually symbolic links (created by mklink).
Even if I disabled both kernel and user caching, these files seems to be cached somehow by IIS. And IIS is still serving old versions after the files are modified.
To be sure that it is not c... |
This problem drove me nuts for like a month a while back. You have to disable IIS caching in the registry, as far as I know this isn't documented anywhere for IIS 7 but instead is an old IIS 5 trick that still works. You can either turn the below into a .reg file and import it or you can just navigate to the section a... |
Partial Page Caching and VaryByParam in ASP.NET MVC 3 |
I'm attempting to use the new partial page caching available in ASP.NET MVC 3. In my view, I'm using:
<% Html.RenderAction("RenderContent", Model); %>
Which calls the controller method:
[Authorize]
[OutputCache(Duration = 6000, VaryByParam = "*", VaryByCustom = "browser")]
public ActionResult RenderContent(Content c... |
I think I figured it out. It looks like the issue is that VaryByParam, when the input parameter is an object, uses ToString() on that object to determine it's uniqueness. So this leaves two options:
Overriding ToString() to provide a unique identifier.
Passing a unique identifier as an additional parameter:
<% Html... |
"Warm Up Cache" on deployment |
I am wondering if anyone has any plugins or capistrano recipes that will "pre-heat" the page cache for a rails app by building all of the page cached html at the time the deployment is made, or locally before deployment happens.
I have some mostly static sites that do not change much, and would run faster if the html ... |
I have set integration tests that confirm all of the main areas of the site are available (a few hundred pages in total). They don't do anything that changes data - just pull back the pages and forms.
I don't currently run them when I deploy my production instance, but now you mention it - it may actually be a good id... |
How to Per-Request caching in ASP.net core |
My old code looks like this:
public static class DbHelper {
// One conection per request
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["Cu... |
There are at least 3 options to store an object per-request in ASP.NET Core:
1. Dependency Injection
You could totally re-design that old code: use the built-in DI and register a Database instance as scoped (per web-request) with the following factory method:
public void ConfigureServices(IServiceCollection services)
... |
How to enable browser caching of static content(images, css, js) with Tomcat? |
How to enable browser caching of static content(images, css, js) with Tomcat?
Preferable solution will be editingspring MVC config files or web.xml
|
try (with changing the values)
<mvc:resources mapping="/static/**" location="/public-resources/"
cache-period="31556926"/>
<mvc:annotation-driven/>
You can also use an interceptor:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/static/*"/>
<bean id="webContentInterceptor"
class=... |
Memory-aware LRU caching in Python? |
I'm using Python 3's builtin functools.lru_cache decorator to memoize some expensive functions. I would like to memoize as many calls as possible without using too much memory, since caching too many values causes thrashing.
Is there a preferred technique or library for accomplishing this in Python?
For example, this ... |
22
I ended up modifying the built-in lru_cache to use psutil.
The modified decorator takes an additional optional argument use_memory_up_to. If set, the cache will be considered full if there are fewer than use_memory_up_to bytes of memory available (according to psutil.vir... |
Force browsers to forget cached redirects? |
I inherited a domain that previously had a 301 redirect from the root ("/") to "/index.shtml"
I've removed the redirect and a different site on the domain, but people who visited the site in the past will have the redirect behavior cached in their browsers... for a terribly long time, unless they manually clear their ... |
16
The short answer: There is no way to tell the browsers of the users to "forget" the R 301 redirect. 301 means permanent, it can be only undone on action of the user or when the cache expires.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2
Similar Q and ... |
How To Cache Images in React? |
Suppose I have a list of url's like so :
[ '/images/1', '/images/2', ... ]
And I want to prefetch n of those so that transitioning between images is faster. What I am doing now in componentWillMount is the following:
componentWillMount() {
const { props } = this;
const { prefetchLimit = 1, document = dummy... |
You don't need to do it in all of your components. As soon as an image is downloaded it gets cached by the browser and will be accessible in all components, so you can do this only once somewhere in a high-level component.
I don't know what exactly UX you are trying to create by caching images, however, your code only... |
How do I prevent Rails 3.1 from caching static assets to Rails.cache? |
I'm using CloudFlare CDN on my Rails 3.1 application. Cloudflare is a CDN that works at the DNS level. On the first hit to a static asset, CloudFlare loads it from your app then caches it in their CDN. Future requests for that asset load from the CDN instead of your app.
The problem I'm having is that if you set contr... |
The original poster wanted to prevent static assets from getting into the general Rails cache, which led them to want to disable the Rack::Cache. Rather than doing this, the better solution is to configure Rack::Cache to use a separate cache than the general Rails cache.
Rack::Cache should be configured differently f... |
How to make Varnish ignore, not delete cookies [closed] |
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
... |
Only sessions are unique to every client, not necessarily cookies.
What you want makes sense and is possible with Varnish, it is just a matter of carefully crafting your own vcl. Please pay attention to the following parts of the default.vcl:
sub vcl_recv {
...
if (req.http.Authorization || req.http.Cookie) {
... |
How to disable model caching in Entity Framework 6 (Code First approach) |
Following MSDN documentation we can read:
The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but note that this can seriously degrade performance.
The problem is the ... |
9
I have the same kind of issue: one db context, 2 or more different db models (different by table names, only)
My solution for EF6: One can still use the internal Entity Framework caching of db model but make a differentiation between DbModel(s) on the same DbContext by im... |
How to disable oracle cache for performance tests |
I'm trying to test the utility of a new summary table for my data.
So I've created two procedures to fetch the data of a certain interval, each one using a different table source. So on my C# console application I just call one or another. The problem start when I want to repeat this several times to have a good patte... |
EDIT: See this thread on asktom, which describes how and why not to do this.
If you are in a test environment, you can put your tablespace offline and online again:
ALTER TABLESPACE <tablespace_name> OFFLINE;
ALTER TABLESPACE <tablespace_name> ONLINE;
Or you can try
ALTER SYSTEM FLUSH BUFFER_CACHE;
but again only on... |
What's the difference between the HttpRuntime Cache and the HttpContext Cache? |
I know there is a very similar question here but I was hoping to get a better explination. Why would I ever use HttpContext.Cache instead of HttpRuntime.Cache if the HttpContext really uses the HttpRuntime.Cache behind the scenes?
In the article Simulate a Windows Service using ASP.NET to run scheduled jobs Omar uses ... |
It really is the same cache at the end, only HttpContext.Current can sometimes be null (when not in a web context, or in a web context but not yet constructed). You'd be safe to always use HttpRuntime.Cache.
|
Rails 3 development environment keeps caching, even without caching on? |
i have a rails 3 app in dev mode that won't load any changes i make when its running webrick. i triple checked the settings for my development.rb and made sure i am running in development mode.
config.cache_classes = false
config.action_controller.perform_caching = false
i also checked my tmp directory to make sure ... |
5
I've had a similar experience, but I don't believe it was with an actual helper class, it was with anything I wrote under the lib/ directory. If you've had to use a require 'some_class' statement, then you should switch it to:
require_dependency 'some_class'
Worked like ... |
Is caching in browser automatic? |
I have a JavaScript app that sends requests to REST API, the responses from server have cache headers (like ETag, cache-control, expires). Is caching of responses in browser automatic, or the app must implement some sort of mechanism to save the data?
|
An AJAX request is no different from a normal request - it's a GET/POST/HEAD/whatever request being sent by the browser, and it is handled as such. This is confirmed here:
The HTTP and Cache sub-systems of modern browsers are at a much lower level than Ajax’s XMLHttpRequest object. At this level, the browser doesn’t... |
How do I stop IIS from caching any files, ever, under any circumstances? |
I do some web development for work and the biggest hit to my productivity comes from IIS. It caches files that will not update even when they are changed, unless I restart IIS. Specifically, I am referring to html, js, and css files. This problem forces me to stop and start my web application constantly. Since I have ... |
10
I suspect that you have enabled output caching, this would exhibit the behaviour that you are describing where recycling the app pool or restarting IIS clears them and allows you to see the new content.
This page gives more information, http://www.iis.net/learn/manage/ma... |
How to display the age of an nginx cached file in headers |
I've set up a caching server for a site through nginx 1.6.3 on CentOS 7, and it's configured to add http headers to served files to show if said files came from the caching server (HIT, MISS, or BYPASS) like so:
add_header X-Cached $upstream_cache_status;
However, i'd like to see if there's a way to add a header to d... |
8
The nginx documentation is quite exhaustive — there's no variable with the direct relative age of the cached file.
The best way would be to use the $upstream_http_ variable class to get the absolute age of the resource by picking up its Date header through $upsteam_http_... |
Regex Syntax changes between POSIX and PCRE |
We are currently in the process of upgrading our Varnish Cache servers.
As part of the process, we upgraded only one of them to see how it behaves compared to the older versions.
Some of the major changes made in this new version is changing the regex engine from POSIX to PCRE. That means that some of our purges (rege... |
See Regular Expression Engine Comparison Chart maintained by Roger Qui which a copy of the information available in the original answer. (Credit to Uberhumus for the new link.)
[Original Answer]
See Flavor Comparison at Regular-Expressions.info.
|
Firebase does not sync offline cache if the app is killed |
I am setting offline persistence
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
as described in an earlier post, but the following use case fails:
Turn internet connectivity OFF on handset
Attempt writing to the DB
Kill app from the memory using the users' multitasking menu in the OS
Turn internet conne... |
According to firebase documentation
Transactions are not persisted across app restarts
Even with persistence enabled, transactions are not persisted across
app restarts. So you cannot rely on transactions done offline being
committed to your Firebase Realtime Database. To provide the best user
experience, your... |
HTTP Caching with Authorization |
Given a response from a web server that contains an Authorization header as per the OAuth spec does HTTP caching fail to be useful?
Request1 Authorization : AUTHTOKEN
Request2 Authorization : ANOTHERAUTOTOKEN
In this case given HTTP caching the second request would return the cached response for the first user. This ... |
7
See http://greenbytes.de/tech/webdav/rfc7234.html#response.cacheability:
"A cache MUST NOT store a response to any request, unless:
The request method is understood by the cache and defined as being cacheable, and
... the Authorization header field (see Section 4.2 of [R... |
require.cache equivalent in ES modules |
ES Modules docs states:
require.cache is not used by import. It has a separate cache.
So where's this separate cache? Is it accessible after all?
I'm looking for invalidating module caching as it can be done in CommonJS modules (node.js require() cache - possible to invalidate?)
|
I saw your thread on the nodeJS github and your answer is there: the cache is designed to be immutable. There's also a good suggestion to use Workers, with each instance having its own fresh imports. Short of that, if you need this behaviour (which doesn't exist for a reason), is there perhaps a better way to design y... |
Cache busting of JSON files in webpack |
I have the following code (written in typescript, but could be any JS variant):
this.http.get('configs/config.json').subscribe(...);
Basically, I'm loading a configuration from a local json file. I would like to have cache busting implemented on the file.
Although I can set up my webpack to modify json files by addin... |
2
You can use query-params in the URL to avoid caching.
No need to change the filename.
this.http.get(`configs/config.json?t=${new Date().getTime()}`).subscribe(...);
new Date().getTime() will create a unique number for every millisecond.
In case of ngx-translate, you can ... |
How do I expire a view cached fragment from console? |
Something like
Rails.cache.delete('site_search_form')
doesn't seem to work. Is this possible? Thanks.
|
Cache fragment entries are created with a slightly different key than what you access with Rails.cache.
Use expire_fragment instead (you can send it to a controller): http://api.rubyonrails.org/classes/ActionController/Caching/Fragments.html#M000438
|
Why does after_save not trigger when using touch? |
Recent days , I was trying to cache rails app use Redis store.
I have two models:
class Category < ActiveRecord::Base
has_many :products
after_save :clear_redis_cache
private
def clear_redis_cache
puts "heelllooooo"
$redis.del 'products'
end
end
and
class Product < ActiveRecord::Base
be... |
39
Have you read documentation for touch method?
Saves the record with the updated_at/on attributes set to the current
time. Please note that no validation is performed and only the
after_touch, after_commit and after_rollback callbacks are executed.
If an attribut... |
Enable / disable session state per controller / action method |
We are building an ASP.NET MVC application which will be deployed behind a hardware load balancer that supports, among other things, caching.
Our proposal is to manually define which URL patterns should be cached by the load balancer. This will be quite an easy process for us as we have 'catalogue' pages which are rel... |
This is included in MVC 2 Futures. See http://blogs.msdn.com/rickandy/archive/2009/12/17/session-less-mvc-controller.aspx for more info.
|
RxjS shareReplay : how to reset its value? |
I use shareReplay to call only once (like a cache) a webservice to retrieve some informations :
In my service :
getProfile(): Observable<Customer> {
return this.callWS().pipe(shareReplay(1));
}
In multiple components :
this.myService.getProfile().subscribe(customer => {
console.log('customer informations has ... |
I know this thread is old, but I think I know what the other answer meant about prepend a "reset" subject to push new values. Check this example:
private _refreshProfile$ = new BehaviorSubject<void>(undefined);
public profile$: Observable<Customer> = _refreshProfile$
.pipe(
switchMapTo(this.callWS()),
share... |
CakePHP 2.0 - Cake was unable to write to File cache |
I'm using CakePHP 2.0 RC-1. After checking out the project from SVN, the application is starting to complain that it can't write cache files to the tmp/cache directory. Since this is local, I know the directory is writeable and I can CLEARLY see that the directories are even filled with files, so the error is a bit st... |
25
Well, in my case, when I checked my app, it hadn't the /tmp folder. Then I created the structure (/tmp/cache/models, /tmp/cache/persistent) and all worked well. This happened to me maybe git ignore empty folders, so they weren't created.
Share
Improve this answ... |
WP7 HttpWebRequest without caching |
It seems that HttpWebRequest caching in WP7 is enabled by default, how do I turn it off?
Adding a random
param url + "?param=" + RND.Next(10000) works, but it's quite tricky and I'm not sure if it will work
with all servers.
|
19
For future reference , this worked for me ( I could not use additional query parameter due to project requirements) :
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
if (request.Headers == null)
{
request.Headers = new WebHead... |
Guava cache 'expireAfterWrite' does not seem to always work |
private Cache<Long, Response> responseCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
I am expecting that response objects that are not send to client within 10 minutes are expired and removed from cache automatically but I n... |
This is specified in the docs:
If expireAfterWrite or expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache.cleanUp(). Expired entries may be counted by Cache.size(), but will never be visible to read or write operations.
And there's more... |
Preventing Caching of CSS Files |
I am developing a simple website using PHP.
Development Configuration : WAMP
Production Configuration : LAMP
While testing, I changed my CSS file, but when I reload the page my browser(not sure) still uses the old cached css.
I did some googling and found different solutions that I have already tried
Appending a que... |
I've ran across this problem a few times and usually over come the problem on production sites by calling my css like this
<link rel="stylesheet" type="text/css" href="style.css?v=1" />
When you roll out an update just change the v=1 to v=2 and it will force all of your users browsers to grab the new style sheets. Th... |
Rails3 - Caching in development mode with Rails.cache.fetch |
In development, the following (simplified) statement always logs a cache miss, in production it works as expected:
@categories = Rails.cache.fetch("categories", :expires_in => 5.minutes) do
Rails.logger.info "+++ Cache missed +++"
Category.all
end
If I change config.cache_classes from false to true in config/deve... |
Try placing the following in /config/environments/development.rb:
# Temporarily enable caching in development (COMMENT OUT WHEN DONE!)
config.action_controller.perform_caching = true
Additionally, if your cache store configuration is in /config/environments/production.rb, then you will need to copy the appropriate li... |
Caching ChildActions using cache profiles won't work? |
I'm trying to use cache profiles for caching child actions in my mvc application, but I get an exception: Duration must be a positive number.
My web.config looks like this:
<caching>
<outputCache enableOutputCache="true" />
<outputCacheSettings>
<outputCacheProfiles>
<add name="TopCategor... |
I did some digging on a related question and looking at mvc 3 source, they definitely don't support any attribute other than Duration and VaryByParam. The main bug with their current implementation is that if you don't supply either one of these you will get an exception telling you to supply that, instead of an exce... |
Configuring redis to consistently evict older data first |
I'm storing a bunch of realtime data in redis. I'm setting a TTL of 14400 seconds (4 hours) on all of the keys. I've set maxmemory to 10G, which currently is not enough space to fit 4 hours of data in memory, and I'm not using virtual memory, so redis is evicting data before it expires.
I'm okay with redis evicting th... |
AFAIK, it is not possible to configure Redis to consistently evict the older data first.
When the *-ttl or *-lru options are chosen in maxmemory-policy, Redis does not use an exact algorithm to pick the keys to be removed. An exact algorithm would require an extra list (for *-lru) or an extra heap (for *-ttl) in memor... |
Can Firebase Hosting Serve Cached Data from Cloud Functions? |
Let's say I have a database of 100,000 pieces of content inside of firestore. Each piece of content is unlikely to change more than once per month. My single page app, using firebase hosting, uses a function to retrieve the content from firestore, render it to HTML, and return it to the browser.
It's a waste of my fi... |
When you use Firebase Hosting on top of Cloud Functions for Firebase, Hosting can act as an edge-cached layer on top of the responses from your HTTPS functions. You can read about that integration in the documentation. In particular, read the section managing cache behavior:
The main tool you'll use to manage cache... |
IIS/ASP.NET responds with cache-control: private for all requests |
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?
For dynamic content (that is, all MVC results) I would not like it to be cached by the br... |
Adding my bit to the great answers, given by community;
1. http caching header attrubute Cache-Control: private is added by default by IIS/ASP.NET ?
Cache request directives
Standard Cache-Control directives that can be used by the client in an HTTP request.
Cache-Control: max-age=<seconds>
Cache-Control: max-... |
Nginx proxy_no_cache and proxy_cache_bypass |
Here's the documentation:
proxy_cache_bypass
Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be taken from the cache:
proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
... |
Yes.
If you just have proxy_cache_bypass set true on pages you don't want cached (eg. logged in users) then they will still be saved into the cache and served to people who should get cached pages (eg. non logged in users).
But setting both proxy_cache_bypass and proxy_no_cache to true means that those users neither r... |
Alamofire loading from cache even when cache policy set to ReloadIgnoringLocalAndRemoteCacheData |
I set cache policy to request in Alamofire to ignore local cache.
Then I load a viewcontroller with network connection, then I disconnect network connection, kill the app and run it again.
Now no network available error is not shown(ie alamofire doesnt create nserror object) created, instead app runs as if the reques... |
I'm using this way in a project and it's working:
let mutableURLRequest = NSMutableURLRequest(URL: SERVICEURL)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.HTTPBody = self.createJson()
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.cachePolicy = NSURLRe... |
Ruby on Rails form page caching including authenticity_token |
I have a simple Ruby on Rails form which includes an authenticity_token. Unfortunatly, I missed that when you page cache this page then the Authenticity Token becomes invalid. I'm glad I figured it out however.
How do you solve caching in such a case?
|
As Matchu posted, you could implement point two from this post (same link he posted, but found via my Googling as well). This adds a dependency on JavaScript, which may or may not be something you want.
Alternatively, you could look into Fragment Caching. This allows you to cache certain portions of a page, but stil... |
Caching with Guava |
What Guava classes are suitable for thread-safe caching? I use a composed key, which gets constructed on the fly, so softKeys() makes no sense, right? I saw somewhere ConcurentLinkedHashMap, is it the way to go? Is it already in the recent release? Sorry for the chaotic way of asking...
Update
This question is pretty ... |
Sounds like you want MapMaker.makeComputingMap, but you mention softKeys so I assume you are already familiar with that class.
You are right about softKeys - it will not work if you compose keys on-the-fly, because softKeys causes the map to use == instead of equals for key comparison. But you should be fine with sof... |
Details on Google App Engine's caching proxy? |
Google App Engine must have some sort of reverse caching proxy because when I set the response header Cache-Control public, max-age=300 from one of my servlets, subsequent requests to the app engine show up in the logs like this: /testcaching 204 1ms 0cpu_ms 49kb, whereas non-cached requests show up in the logs as: /... |
Some of the details it would be nice to have answers for:
http://code.google.com/p/googleappengine/issues/detail?id=2258#c3
|
what is the path to Chrome cache on Ubuntu? |
I want to be able to clear cache (both browser's own cache and possible offline cache manifests) through the command line.
|
16
Chrome Cache located into Path:
$HOME/.cache/google-chrome/Default/
To delete Web browsing Cache:
rm -rf $HOME/.cache/google-chrome/Default/Cache/
To delete video and Music (Media) cache:
rm -rf $HOME/.cache/google-chrome/Default/Media\ Cache/
Also there another cache... |
Turn off Caching in MAMP |
Trying to turn off caching in MAMP for development, waiting for cache to expire after making small changes is killing my productivity.
(Problem started when I changed to PHP 5.5.3, changing back doesn't fix it)
After researching I've taken the following steps to (unsuccessfully) disable cache:
Commented out OPcache li... |
@Philippe, Ensure you commented out OPcache in
/Applications/MAMP/bin/php/php5.5.3/conf/php.ini
not the one in
/Applications/MAMP/conf/php5.5.3/php.ini
|
Is ArrayList.size() method cached? |
I was wondering, is the size() method that you can call on a existing ArrayList<T> cached?
Or is it preferable in performance critical code that I just store the size() in a local int?
I would expect that it is indeed cached, when you don't add/remove items between calls to size().
Am I right?
update
I am not talkin... |
I don't think I'd say it's "cached" as such - but it's just stored in a field, so it's fast enough to call frequently.
The Sun JDK implementation of size() is just:
public int size() {
return size;
}
|
.NET 4 ObjectCache - Can We Hook Into a "Cache Expired" Event? |
I've got a simple object being cached like this:
_myCache.Add(someKey, someObj, policy);
Where _myCache is declared as ObjectCache (but injected via DI as MemoryCache.Default), someObj is the object i'm adding, and policy is a CacheItemPolicy.
If i have a CacheItemPolicy like this:
var policy = new CacheItemPolicy
{... |
There's a property on the CacheItemPolicy called RemovedCallback which is of type: CacheEntryRemovedCallback. Not sure why they didn't go the standard event route, but that should do what you need.
http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.removedcallback.aspx
|
How to efficiently serve massive sitemaps in django |
I have a site with about 150K pages in its sitemap. I'm using the sitemap index generator to make the sitemaps, but really, I need a way of caching it, because building the 150 sitemaps of 1,000 links each is brutal on my server.[1]
I COULD cache each of these sitemap pages with memcached, which is what I'm using else... |
I had a similar issue and decided to use django to write the sitemap files to disk in the static media and have the webserver serve them. I made the call to regenerate the sitemap every couple of hours since my content wasn't changing more often than that. But it will depend on your content how often you need to wri... |
How to implement caching in android app for REST API results? |
My android app gets its data using REST API. I want to have client side caching implemented. Do we have any inbuilt classes for this?
if not, is these any code that i can reuse? I remember coming across such code sometime back. However I cant find it.
If nothing else works, i will write my own. following is basic st... |
10
Now awesome library Volley released on Google I/O 2013 which helps for improve over all problems of calling REST API:
Volley is a library,it is library called Volley from the Android dev team. that makes networking for Android apps easier and most importantly, faster.... |
Using nginx to serve content directly out of a redis cache |
I am using nginx to pass requests to a Node app. The app basically acts as a remote cache for html (checks to see if what the user is requesting is in the redis db, if it is just show that, if not grab it and store it in the redis cache and serve it up.)
I was curious if there was anyway to bypass hitting the Node ap... |
13
Maybe something more difficult to setup than Webdis but you can do that directly in the nginx daemon with some extra modules like redis2-nginx-module. You will have to recompile nginx.
There is some good examples of configuration on the home page.
For instance :
# GET /... |
Best Practice when Caching files in Android |
I currently have my app caching image files in the cache sub-directory for the application. The images are used in a ListView and stored in a HashMap of SoftReferences to Bitmaps.
So my question is this, what is the best way to cache these image files without inflating the space my application uses AND remains respons... |
I can't offer you a comprehensive set of best practices, but I can offer what I've learned so far:
Managing your cache is a good idea. My app's cache is such that I know that I'll never need more than a certain number of cached files, so whenever I insert a new file into the cache, I delete the oldest files until I'm ... |
Cache bandwidth per tick for modern CPUs |
What is a speed of cache accessing for modern CPUs? How many bytes can be read or written from memory every processor clock tick by Intel P4, Core2, Corei7, AMD?
Please, answer with both theoretical (width of ld/sd unit with its throughput in uOPs/tick) and practical numbers (even memcpy speed tests, or STREAM benchma... |
For nehalem: rolfed.com/nehalem/nehalemPaper.pdf
Each core in the architecture has a 128-bit write port and a
128-bit read port to the L1 cache.
128 bit = 16 bytes / clock read
AND
128 bit = 16 bytes / clock write
(can I combine read and write in single cycle?)
The L2 and L3 caches each have a 256-bit port for readi... |
Is there any reason *not* to cache an object's hash? |
I've written a class whose .__hash__() implementation takes a long time to execute. I've been thinking to cache its hash, and store it in a variable like ._hash so the .__hash__() method would simply return ._hash. (Which will be computed either at the end of the .__init__() or the first time .__hash__() is called.)
M... |
Sure, it's fine to cache the hash value. In fact, Python does so for strings itself. The trade-off is between the speed of the hash calculation and the space it takes to save the hash value. That trade-off is for example why tuples don't cache their hash value, but strings do (see request for enhancement #1462796).
|
Cache CSS and JS files |
When I refresh my website in less than 2-3 minutes, Firebug shows these nice requests:
1. /core.css 304 Not modified
2. /core.js 304 Not modified
3. /background.jpg 304 Not modified
BUT when I refresh after >3 minutes, I get:
1. /core.css 200 OK
2. /core.js 200 OK
3. /backgrou... |
Hopefully this will help: http://www.iis.net/ConfigReference/system.webServer/staticContent/clientCache
The <clientCache> element of the <staticContent> element specifies cache-related HTTP headers that IIS 7 and later sends to Web clients, which control how Web clients and proxy servers will cache the content that I... |
What is "false sharing"? How to reproduce / avoid it? |
Today I got a different understand with my professor on the Parallel Programming class, about what is "false sharing". What my professor said makes little sense so I pointed it out immediately. She thought "false sharing" will cause a mistake in the program's result.
I said, "false sharing" happens when different memo... |
I'll share my point of view on your questions.
Two addresses that are separated by more bytes than block's size, won't reside on the exact same cache line. Thus, if a core has the first address in its cache, and another core requests the second address, the first won't be removed from cache because of that request. S... |
dotnet System.Web.Caching.Cache vs System.Runtime.Caching.MemoryCache |
I've got a class that needs to store data in a cache.
Originally I used it in an asp.net application so I used System.Web.Caching.Cache.
Now I need to use it in a Windows Service.
Now, as I understand it, I should not use the asp.net cache in a not asp.net application, so I was looking into MemoryCache.
The problem is... |
8
I would go with your second option and refactor things a little bit. I would create an Interface and two Providers (which are your adapters):
public interface ICachingProvider
{
void AddItem(string key, object value);
object GetItem(string key);
}
public AspNetCa... |
HTML5 Offline app on Android devices |
This is regarding HTML5 offline apps on Android devices.
We are running into an issue where bookmarking an offline capable HTML5 app (with a complete cache manifest file) fails to load on the Android browser under the following conditions:
Bookmark the app on the browser
Switch off all wireless connectivity
Close th... |
5
+50
I'd check and see that:
MIME type really is text/cache-manifest.
Your cache-manifest starts with CACHE MANIFEST, your urls thereafter are either relative to the manifest or absolute URLs.
You don't have any broken links in your man... |
How can caches be defeated? |
I have this question on my assignment this week, and I don't understand how the caches can be defeated, or how I can show it with an assembly program.. Can someone point me in the right direction?
Show, with assembly program examples, how the two different caches (Associative and Direct Mapping) can be defeated. Expl... |
A cache is there to increase performance. So defeating a cache means finding a pattern of memory accesses that decreases performance (in the presence of the cache) rather than increases it.
Bear in mind that the cache is limited in size (smaller than main memory, for instance) so typically defeating the cache involves... |
Chrome back button: only giving cached version of initial page, without any Ajaxed content |
I have two pages, A and B. The flow is as follows:
Go to A
javascript Ajaxes a bunch of content to add to A, forming A'
go to B
pressing [Back] goes back to A, not A', without all the Ajaxed content
Has anyone else noticed this, and if so, how do you fix it?
If Chrome was caching the A' state just before going to B... |
7
This topic is old but thought I would share my solution. To get Firefox, Chrome and Safari to behave consistently, you have to set an unload handler on the page that needs to be reloaded when going back, and also use cache busting headers.
Example
In HTTP Headers
Cache-Co... |
How to measure file read speed without caching? |
My java program spends most time by reading some files and I want to optimize it, e.g., by using concurrency, prefetching, memory mapped files, or whatever.
Optimizing without benchmarking is a non-sense, so I benchmark. However, during the benchmark the whole file content gets cached in RAM, unlike in the real run. T... |
Clear the Linux file cache
sync && echo 1 > /proc/sys/vm/drop_caches
Create a large file that uses all your RAM
dd if=/dev/zero of=dummyfile bs=1024 count=LARGE_NUMBER
(don't forget to remove dummyfile when done).
|
iOS standalone web app cant load new content after upgrade to iOS7 |
I have a JavaScript application that I run in standalone mode (added to home screen) on an iPad.
I have upgraded from iOS 6 to iOS 7 and now my app is always loading the same content, it keeps caching.
Even if I load my JS and CSS files dynamically on every app load with unique timestamp as parameter. I needed that to... |
2
It seems that making a change to your manifest file (like adding a version number ), should make the app reload content: Mobile Web App not clearing cache properly
You should add a version number to your CSS and JS urls to solve caching issues.
e.g. file.css?v=2
Cheer... |
How can I use my "gha" Docker cache to speed up Docker pull, as well as Docker build on Github Actions? |
On Github Actions, I'd like to avoid having to pull my newly built Docker image from the registry when I have it in a cache (and this is the slowest part of my jobs)
My workflow is something like
Build an image (with all my dependencies baked in)
Run a command within the above image
As per the Docker Build Push Acti... |
4
+75
We faced similar situation some time back but we recently found a github-actions which actually helps in caching the docker-layers & images b/w subsequent runs.
I am sure that your problem can also be solved with it. Here is the lin... |
Setting optimum http caching headers and server params in ASP.Net MVC and IIS 7.5 |
I have an ASP.Net site (happens to be MVC, but that's not relevant here) with a few pages I'd like cached really well.
Specifically I'd like to achieve:
output cached on the server for 2 hours.
if the file content on the server changes, that output cache should be flushed for that page
cached in the browser for 10 m... |
1
I'm not sure if you've solved this problem yet (several months later...), but this should be possible.
SetMaxAge should set the amount of "guarranteed" fresh time. If you additionally send an ETag, you'll have satisfied 3 & 4. Requirements 1 & 2 can be solved orthogonal... |
AFNetworking - do not cache response |
I'm using this code to pull a simple JSON feed from a server:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:kDataUrl parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) ... |
Make long story short, just define your AFNetworking manager:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
Enjoy!
|
Which provides better Image Loading/Caching - Volley or Picasso? |
I'm looking for an open source image loading/caching solution.
I am looking in to:
Google's Volley,
Square's Picasso
Universal Image Loader
I want to be able to handle async image loads from disk as well as network, however I'm not sure if Google's volley handle's loading from disk.
Does Volley allow resource loading ... |
volley' Request class deal with all network requests. I have not yet found any class loading resource from disk..
|
Disable caching for a view or url in django |
In django, I wrote a view that simply returns a file, and now I am having problems because memcache is trying to cache that view, and in it's words, "TypeError: can't pickle file objects".
Since I actually do need to return files with this view (I've essentially made a file-based cache for this view), what I need to d... |
Returning a real, actual file object from a view sounds like something is wrong. I can see returning the contents of a file, feeding those contents into an HttpResponse object. If I understand you correctly, you're caching the results of this view into a file. Something like this:
def myview(request):
file = op... |
Caching JSON output in PHP |
Got a slight bit of an issue. Been playing with the facebook and twitter API's and getting the JSON output of status search queries no problem, however I've read up further and realised that I could end up being "rate limited" as quoted from the documentation.
I was wondering is it easy to cache the JSON output each h... |
Here a simple function that adds caching to getting some URL contents:
function getJson($url) {
// cache files are created like cache/abcdef123456...
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$size = filesize($cache... |
How to test django caching? |
Is there a way to be sure that a page is coming from cache on a production server and on the development server as well?
The solution shouldn't involve caching middleware because not every project uses them. Though the solution itself might be a middleware.
Just checking if the data is stale is not a very safe testing... |
We do a lot of component caching and not all of them are updated at the same time. So we set host and timestamp values in a universally included context processor. At the top of each template fragment we stick in:
<!-- component_name {{host}} {{timestamp}} -->
The component_name just makes it easy to do a View Source... |
Using System.Web.Caching.Cache |
I am trying to use the Cache, but get the error below. How can I properly use the Cache?
protected void Page_Load(object sender, EventArgs e) {
x = System.DateTime.Now.ToString();
if (Cache["ModifiedOn"] == null) { // first time so no key/value in Cache
Cache.Insert("ModifiedOn", x); // inserts the key/value pair... |
45
System.Web.Caching.Cache: this is the implementation of .NET caching.
System.Web.HttpContext.Current.Cache: this is the instance of that implementation, that lives in the application domain.
I think you want to use the second one if you are not in the code behind of an a... |
Does using $this instead of $(this) provide a performance enhancement? |
Assume I have the following example:
Example One
$('.my_Selector_Selected_More_Than_One_Element').each(function() {
$(this).stuff();
$(this).moreStuff();
$(this).otherStuff();
$(this).herStuff();
$(this).myStuff();
$(this).theirStuff();
$(this).children().each(function(){
howMuchStu... |
Yes, definitely use $this.
A new jQuery object must be constructed each time you use $(this), while $this keeps the same object for reuse.
A performance test shows that $(this) is significantly slower than $this. However, as both are performing millions of operations a second, it is unlikely either will have any real... |
magento client denied by server configuration |
Magento isn't displaying anything but a white homepage, in the error_log the error given is:
client denied by server configuration: /var/www/httpdocs/app/etc/local.xml
I can access the admin area fine, does anyone know why this might happen?
|
APC caching apparently doesn't play nicely with Magento, disabling it threw a PHP error that an outdated theme was producing
|
How to clear cache Android |
I need to find a way how to clear the data which my application stores in cache.Basically I am using Fedor's ( Lazy load of images in ListView ) lazy list implementation and I want to clear the cache automatically when I have for example 100 images loaded.Any ideas how to do that?
EDIT:
Code :
public void onCreate(Bun... |
this will delete cache
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDi... |
Accessing the ASP.NET Cache from a Separate Thread? |
Normally i have a static class that reads and writes to HttpContext.Current.Cache
However since adding threading to my project, the threads all get null reference exceptions when trying to retrieve this object.
Is there any other way i can access it, workarounds or another cache i can use?
|
37
The System.Web.Cache object itself is thread safe.
The issue is how to obtain a reference to it in a way that works throughout your application. HttpContext.Current returns null unless it is called on a thread that is handling an ASP.NET request. An alternative way to ge... |
JPA: caching queries |
I'm using JPA to load and persist entities in my Java EE-based web application. Hibernate is used as an implementation of JPA, but I don't use Hibernate-specific features and only work with pure JPA.
Here is some DAO class, notice getOrders method:
class OrderDao {
EntityManager em;
List getOrders(Long customerId... |
There is a query plan cache in Hibernate. So the HQL is not parsed every time the DAO is called (so #1 really occurs only once in your application life-time). It's QueryPlanCache. It's not heavily documented, as it "just works". But you can find more info here.
|
Disable OutputCache on Development System |
I use OutputCache in an ASP.net MVC application. As developing with an active OutputCache is not very pleasant I want to disable the OutputCache on the Development Systems (local machines and development server).
What is the best way to do this?
|
19
It's an old one but...
set this in your web.config under system.web
<caching>
<outputCache enableOutputCache="false" />
</caching>
Share
Improve this answer
Follow
edited Feb 17, 2012 at 1:09
... |
Is caching the only advantage of spark over map-reduce? |
I have started to learn about Apache Spark and am very impressed by the framework. Although one thing which keeps bothering me is that in all Spark presentations they talk about how Spark caches the RDDs and therefore multiple operations which need the same data are faster than other approaches like Map Reduce.
So the... |
Caching + in memory computation is definitely a big thing for spark, However there are other things.
RDD(Resilient Distributed Data set): an RDD is the main abstraction of spark. It allows recovery of failed nodes by re-computation of the DAG while also supporting a more similar recovery style to Hadoop by way of che... |
Caching Patterns in ASP.NET |
So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myObject.someValue != cache.Get("myObjectKey").so... |
Dirty tracking is the normal way to handle this, I think. Something like:
class MyObject {
public string SomeValue {
get { return _someValue; }
set {
if (value != SomeValue) {
IsDirty = true;
_someValue = value;
}
}
public bool IsDirty {
get;
private set;
... |
Apollo writeFragment not updating data |
In react-apollo 2.0.1 I have a graphql type that looks like this:
type PagedThing {
data: [Thing]
total: Int
}
When doing the following writeFragment
client.writeFragment({
id,
fragment: gql`
fragment my_thing on Thing {
status
}
`,
data: {
status
}
})
The cache ... |
Turns out I needed to not only add the __typename as the ID needed to be the one resolved by default (Explained here)
So I needed to do the following in order to make it work:
client.writeFragment({
id: `Thing:${id}`,
fragment: gql`
fragment my_thing on Thing {
status
}
`,
data: {
__typename:... |
Get expiration time of Rails cached item |
Somewhere in my app I use
Rails.cache.write 'some_key', 'some_value', expires_in: 1.week
In another part of my app I want to figure out how much time it is left for that cache item.
How do I do that?
|
15
This is not a legal way, but it works:
expires_at = Rails.cache.send(:read_entry, 'my_key', {})&.expires_at
expires_at - Time.now.to_f if expires_at
read_entry is protected method that is used by fetch, read, exists? and other methods under the hood, that's why we use s... |
What's the purpose of the Symfony2 bootstrap.php.cache file? |
I'm using SF2 in one of our legacy project, not the entire framework but by pulling in bundles and components I need. And I have always wondered about these lines of code:
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCac... |
To ensure optimal flexibility and code reuse, Symfony2 applications leverage a variety of classes and 3rd party components. But loading all of these classes from separate files on each request can result in some overhead. To reduce this overhead, the Symfony2 Standard Edition provides a script to generate a so-called... |
How do I cache a web page in PHP? |
how do I cache a web page in php so that if a page has not been updated viewers should get a cached copy?
Thanks for your help.
PS: I am beginner in php.
|
You can actually save the output of the page before you end the script, then load the cache at the start of the script.
example code:
<?php
$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds
if (file_exists($cachefile) && time()... |
Is using PHP accelerators such as MMCache or Zend Accelerator making PHP faster? |
Does anybody have experience working with PHP accelerators such as MMCache or Zend Accelerator? I'd like to know if using either of these makes PHP comparable to faster web-technologies. Also, are there trade offs for using these?
|
Note that Zend Optimizer and MMCache (or similar applications) are totally different things. While Zend Optimizer tries to optimize the program opcode MMCache will cache the scripts in memory and reuse the precompiled code.
I did some benchmarks some time ago and you can find the results in my blog (in German though).... |
Why is output caching not working for my ASP.NET MVC 4 app? |
I am having an issue where output caching doesn't appear to be working for my ASP.NET MVC 4 (EPiServer 7) website.
I have the following output cache profile in my web.config:
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="PageOutput" enabled="true" duration="300" varyByParam="*" location... |
So, it turns out that OutputCaching was working, it was just that my method of testing it was flawed. The result of an action will only be cached if the response doesn't include a cookie. Of course the first response always includes a cookie if you have ASP.NET Session enabled which we do. Therefore the first response... |
Why are uncompiled, repeatedly used regexes so much slower in Python 3? |
When answering this question (and having read this answer to a similar question), I thought that I knew how Python caches regexes.
But then I thought I'd test it, comparing two scenarios:
a single compilation of a simple regex, then 10 applications of that compiled regex.
10 applications of an uncompiled regex (where... |
The code has changed.
In Python 2.7, the cache is a simple dictionary; if more than _MAXCACHE items are stored in it, the whole the cache is cleared before storing a new item. A cache lookup only takes building a simple key and testing the dictionary, see the 2.7 implementation of _compile()
In Python 3.x, the cache h... |
Race-condition creating folder in Python |
I have a urllib2 caching module, which sporadically crashes because of the following code:
if not os.path.exists(self.cache_location):
os.mkdir(self.cache_location)
The problem is, by the time the second line is being executed, the folder may exist, and will error:
File ".../cache.py", line 103, in __init__
... |
In Python 3.x, you can use os.makedirs(path, exist_ok=True), which will not raise any exception if such directory exists. It will raise FileExistsError: [Errno 17] if a file exists with the same name as the requested directory (path).
Verify it with:
import os
parent = os.path.dirname(__file__)
target = os.path.join... |
How would Redis get to know if it has to return cached data or fresh data from DB |
Say, I'm Fechting thousands or record using some long runing task from DB and caching it using Redis. Next day somebody have changed few records in DB.
Next time how redis would know that it has to return cached data or again have to revisit that all thousands of records in DB?
How this synchronisation achived?
|
Redis has no idea whether the data in DB has been updated.
Normally, we use Redis to cache data as follows:
Client checks if the data, e.g. key-value pair, exists in Redis.
If the key exists, client gets the corresponding value from Redis.
Otherwise, it gets data from DB, and sets it to Redis. Also client sets an exp... |
Maximum length of cache keys in HttpRuntime.Cache object? |
We are using HttpRuntime.Cache API in an ASP.NET to cache data retrieved from a database.
For this particular application, our database queries feature a LOT of parameters, so our cache keys look something like this:
table=table1;param1=somevalue1;param2=somevalue2;param3=somevalue3;param4=somevalue4;param5=somevalue... |
Internally, Dictionary uses the hash code of the key you give it. Effectively every key is stored as an integer.
You have nothing to worry about.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.